Skip to content

fix(redirects): give overlapping pattern rules a stable precedence - #3693

Merged
ascorbic merged 2 commits into
fix/redirect-enable-loopfrom
fix/redirect-pattern-precedence
Oct 1, 2026
Merged

ascorbic merged 2 commits into
fix/redirect-enable-loopfrom
fix/redirect-pattern-precedence

Conversation

@ascorbic

Copy link
Copy Markdown
Member

What does this PR do?

When several enabled pattern redirects match the same path, the winner depended on physical row order.

Enabled rules were loaded without an ORDER BY, and both the middleware cache and matchPath return the first matching pattern. On PostgreSQL every update, hit tracking included, rewrites the row and can change that order. As a result, which of two overlapping rules wins could change after an unrelated hit.

Enabled rules are now loaded oldest first by created_at, with ties broken by id. Cached matching and direct matching use that same order.

This is stacked on #3692 and is the second of three PRs from work on #2288.

Closes # (no issue; found while working on #2288)

Type of change

  • Bug fix
  • Feature (requires maintainer-approved Discussion)
  • Refactor (no behavior change)
  • Translation
  • Documentation
  • Performance improvement
  • Tests
  • Chore (dependencies, CI, tooling)

Checklist

  • I have read CONTRIBUTING.md
  • pnpm typecheck passes
  • pnpm lint passes
  • pnpm test passes (or targeted tests for my change)
  • pnpm format has been run
  • I have added/updated tests for my changes (if applicable)
  • User-visible strings in the admin UI are wrapped for translation (if applicable). n/a: no admin UI changes.
  • I have added and reviewed the user-facing changeset (if this PR changes a published package)
  • New features link to an approved Discussion: n/a, this is a bug fix.
  • I have included screenshots below if this PR changes the UI. n/a: no UI changes.

AI-generated code disclosure

  • This PR includes AI-generated code — model/tool: Claude Opus 5.5 (Claude Code)

Screenshots / test output

Not applicable (no UI change).

redirect-pattern-precedence.test.ts runs on SQLite and PostgreSQL. It inserts overlapping rules in the reverse of their creation order and checks that both cached and direct matching return the earliest-created rule, then that created_at ties are broken by id.

🤖 Generated with Claude Code

@changeset-bot

changeset-bot Bot commented Sep 30, 2026 •

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 7dd2545

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 12 packages
Name Type
emdash Patch
@emdash-cms/cloudflare Patch
@emdash-cms/plugin-test Patch
@emdash-cms/sandbox-workerd Patch
@emdash-cms/admin Patch
@emdash-cms/auth Patch
@emdash-cms/blocks Patch
create-emdash Patch
@emdash-cms/gutenberg-to-portable-text Patch
@emdash-cms/x402 Patch
@emdash-cms/auth-atproto Patch
@emdash-cms/plugin-embeds Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@emdashbot emdashbot Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is the right fix for the reported instability: ordering enabled redirects by created_at and id makes pattern precedence deterministic across PostgreSQL row movement, and the change is applied consistently to both the cached load (findAllEnabled) and the direct matcher (findEnabledPatternRules). The regression test is well targeted — it runs on both SQLite and PostgreSQL, inserts overlapping patterns in reverse creation order, and checks both code paths, including created_at ties.

The main gap is index discipline. The new ORDER BY clauses land on the logged-out redirect middleware path (via loadCachedRedirects(() => repo.findAllEnabled())), but _emdash_redirects has no index on created_at or id — only source, enabled, and group_name. Without a supporting index, every cold isolate start now sorts the full enabled redirect set, and on PostgreSQL (the platform called out in the PR description) that sort executes against a table whose rows are rewritten by hit tracking. Add a forward-only migration covering the sort columns before this merges.

The changeset is accurate, proportional, and follows .changeset/README.md.

Comment on lines 439 to +465
@@ -458,6 +461,8 @@ export class RedirectRepository {
.selectAll()
.where("enabled", "=", 1)
.where("is_pattern", "=", 1)
.orderBy("created_at", (order) => order.asc().nullsFirst())
.orderBy("id", "asc")

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[needs fixing] Both findAllEnabled and findEnabledPatternRules now order by created_at ASC NULLS FIRST, id ASC, but _emdash_redirects has no index on created_at or id. The migration (029_redirects.ts) only indexes source, enabled, and group_name.

Because findAllEnabled feeds the logged-out redirect middleware cache (packages/core/src/astro/middleware/redirect.ts), this unindexed sort runs on every cold isolate start. On PostgreSQL — the platform explicitly called out in the PR description — that means sorting a table whose rows are rewritten each time hit tracking updates updated_at.

Add a forward-only migration that covers these order columns. For example:

// packages/core/src/database/migrations/091_redirects_precedence_index.ts
import type { Kysely } from "kysely";

export async function up(db: Kysely<unknown>): Promise<void> {
	await db.schema
		.createIndex("idx_redirects_enabled_created_at")
		.on("_emdash_redirects")
		.columns(["enabled", "created_at", "id"])
		.execute();

	await db.schema
		.createIndex("idx_redirects_pattern_enabled_created_at")
		.on("_emdash_redirects")
		.columns(["is_pattern", "enabled", "created_at", "id"])
		.execute();
}

export async function down(_db: Kysely<unknown>): Promise<void> {}

If you prefer a single index, idx_redirects_created_at_id on (created_at, id) is still an improvement, though it will not push the enabled/is_pattern filters into the index.

@github-actions github-actions Bot added the review/awaiting-author Reviewed; waiting on the author to respond label Sep 30, 2026
@pkg-pr-new

pkg-pr-new Bot commented Sep 30, 2026 •

Copy link
Copy Markdown

Open in StackBlitz

@emdash-cms/admin

npm i https://pkg.pr.new/@emdash-cms/admin@3693

@emdash-cms/auth

npm i https://pkg.pr.new/@emdash-cms/auth@3693

@emdash-cms/auth-atproto

npm i https://pkg.pr.new/@emdash-cms/auth-atproto@3693

@emdash-cms/blocks

npm i https://pkg.pr.new/@emdash-cms/blocks@3693

@emdash-cms/cloudflare

npm i https://pkg.pr.new/@emdash-cms/cloudflare@3693

@emdash-cms/contentful-to-portable-text

npm i https://pkg.pr.new/@emdash-cms/contentful-to-portable-text@3693

emdash

npm i https://pkg.pr.new/emdash@3693

create-emdash

npm i https://pkg.pr.new/create-emdash@3693

@emdash-cms/gutenberg-to-portable-text

npm i https://pkg.pr.new/@emdash-cms/gutenberg-to-portable-text@3693

@emdash-cms/plugin-cli

npm i https://pkg.pr.new/@emdash-cms/plugin-cli@3693

@emdash-cms/plugin-test

npm i https://pkg.pr.new/@emdash-cms/plugin-test@3693

@emdash-cms/plugin-types

npm i https://pkg.pr.new/@emdash-cms/plugin-types@3693

@emdash-cms/registry-client

npm i https://pkg.pr.new/@emdash-cms/registry-client@3693

@emdash-cms/registry-lexicons

npm i https://pkg.pr.new/@emdash-cms/registry-lexicons@3693

@emdash-cms/registry-loader

npm i https://pkg.pr.new/@emdash-cms/registry-loader@3693

@emdash-cms/registry-moderation

npm i https://pkg.pr.new/@emdash-cms/registry-moderation@3693

@emdash-cms/registry-verification

npm i https://pkg.pr.new/@emdash-cms/registry-verification@3693

@emdash-cms/sandbox-workerd

npm i https://pkg.pr.new/@emdash-cms/sandbox-workerd@3693

@emdash-cms/x402

npm i https://pkg.pr.new/@emdash-cms/x402@3693

@emdash-cms/plugin-ai-moderation

npm i https://pkg.pr.new/@emdash-cms/plugin-ai-moderation@3693

@emdash-cms/plugin-atproto

npm i https://pkg.pr.new/@emdash-cms/plugin-atproto@3693

@emdash-cms/plugin-audit-log

npm i https://pkg.pr.new/@emdash-cms/plugin-audit-log@3693

@emdash-cms/plugin-color

npm i https://pkg.pr.new/@emdash-cms/plugin-color@3693

@emdash-cms/plugin-embeds

npm i https://pkg.pr.new/@emdash-cms/plugin-embeds@3693

@emdash-cms/plugin-field-kit

npm i https://pkg.pr.new/@emdash-cms/plugin-field-kit@3693

@emdash-cms/plugin-forms

npm i https://pkg.pr.new/@emdash-cms/plugin-forms@3693

@emdash-cms/plugin-webhook-notifier

npm i https://pkg.pr.new/@emdash-cms/plugin-webhook-notifier@3693

commit: 7dd2545

@cloudflare-workers-and-pages

cloudflare-workers-and-pages Bot commented Sep 30, 2026 •

Copy link
Copy Markdown

🚀 Deploying Preview to Cloudflare 🚀

Preview URL: https://fix-redirect-pattern-precedence.try.emdashcms.com, https://fix-redirect-pattern-precedence-emdash-playground.emdash-cms.workers.dev (commit 7dd2545)

This URL reflects your latest Preview deployment

Preview Deployments by commit

Status Deployment URL Commit Updated (UTC) See this deployment's details
  • Build: Success ✅
  • Deployment: Success ✅

View logs ↗
https://4141d9e5.try.emdashcms.com, https://4141d9e5-emdash-playground.emdash-cms.workers.dev 7dd2545 2026-10-01T10:59:10.638Z Visit the dashboard ↗
  • Build: Success ✅
  • Deployment: Success ✅

View logs ↗
https://80e7c7da.try.emdashcms.com, https://80e7c7da-emdash-playground.emdash-cms.workers.dev 38c9cd6 2026-10-01T10:40:26.726Z Visit the dashboard ↗
  • Build: Success ✅
  • Deployment: Success ✅

View logs ↗
https://0f84940b.try.emdashcms.com, https://0f84940b-emdash-playground.emdash-cms.workers.dev 31badd9 2026-09-30T15:32:59.122Z Visit the dashboard ↗
  • Build: Success ✅
  • Deployment: Success ✅

View logs ↗
https://f435d2f5.try.emdashcms.com, https://f435d2f5-emdash-playground.emdash-cms.workers.dev 2095394 2026-09-30T15:21:26.796Z Visit the dashboard ↗
  • Build: Success ✅
  • Deployment: Success ✅

View logs ↗
https://59f5961f.try.emdashcms.com, https://59f5961f-emdash-playground.emdash-cms.workers.dev 21f08a3 2026-09-30T13:59:25.722Z Visit the dashboard ↗

@cloudflare-workers-and-pages

Copy link
Copy Markdown

Deploying with  Cloudflare Workers  Cloudflare Workers

The latest updates on your project. Learn more about integrating Git with Workers.

Status Name Latest Commit Updated (UTC)
✅ Deployment successful!
View logs
docs 21f08a3 Sep 30 2026, 01:59 PM

@github-actions github-actions Bot added the review/needs-rereview New commits since the last review label Sep 30, 2026
@ascorbic
ascorbic force-pushed the fix/redirect-pattern-precedence branch from 2095394 to 31badd9 Compare September 30, 2026 15:07
@github-actions github-actions Bot added overlap and removed review/awaiting-author Reviewed; waiting on the author to respond labels Sep 30, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Overlapping PRs

This PR modifies files that are also changed by other open PRs:

This may cause merge conflicts or duplicated work. A maintainer will coordinate.

Enabled redirects were loaded without an ORDER BY, and both the
middleware cache and matchPath return the first matching pattern, so the
winner followed physical row order. On PostgreSQL every update (including
hit tracking) rewrites the row and can reorder rules. Load enabled rules
oldest first, tie-broken by id.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@ascorbic
ascorbic force-pushed the fix/redirect-pattern-precedence branch from 31badd9 to 38c9cd6 Compare October 1, 2026 10:38
@ascorbic
ascorbic merged commit d1b4402 into main Oct 1, 2026
41 checks passed
@ascorbic
ascorbic deleted the fix/redirect-pattern-precedence branch October 1, 2026 15:24
@emdashbot emdashbot Bot mentioned this pull request Oct 1, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area/core review/needs-rereview New commits since the last review size/M

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant