Skip to content

fix(core): keep the pivot join pinned for taxonomy listings with a temp sort - #3409

Merged
ascorbic merged 2 commits into
emdash-cms:mainfrom
eisenbruch:fix/pivot-temp-sort-keeps-pin
Sep 27, 2026
Merged

ascorbic merged 2 commits into
emdash-cms:mainfrom
eisenbruch:fix/pivot-temp-sort-keeps-pin

Conversation

@eisenbruch

Copy link
Copy Markdown
Contributor

What does this PR do?

Keeps buildTaxonomyPivotQuery's CROSS JOIN pin in the temp-sort branch and leaves #3300's plain JOIN in the indexed-sort branch:

const pivotContentJoin = isPostgres(db) || isIndexedSort ? sql`JOIN` : sql`CROSS JOIN`;

The temp-sort picked collects every tagged entry and has no LIMIT, so starting from ec_* can never stop early. On D1, with the pin released, a collection whose trash holds many distinct deleted_at values starts there anyway and walks every published row: a listings collection on one production site's data went from 4,209 to 13,453 rows read for the same 49 rows. Indexed sorts are equal or better with JOIN, as #3299 measured, and are unchanged by this PR. The measurements and plans are in #3408.

Closes #3408

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). Do not include messages.po changes except in translation PRs — a workflow extracts catalogs on merge to main.
  • I have added and reviewed the user-facing changeset (if this PR changes a published package)
  • New features link to an approved Discussion: https://github.com/emdash-cms/emdash/discussions/...
  • I have included screenshots below if this PR changes the UI

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).

About the test: I tried to assert the plan, the way loader-taxonomy-pivot-plan.test.ts does. That doesn't work here. With the site's sqlite_stat1 rows loaded into the test database, local SQLite 3.51.0 keeps the pivot outer under a plain JOIN, where D1 does not, so a plan assertion passes on main and proves nothing. The new test pins the join the builder emits for each branch instead: CROSS JOIN for updated_at and a field sort, JOIN for published_at. It fails on main and passes here.

loader-taxonomy-pivot-plan.test.ts, loader-taxonomy-pivot.test.ts (unit + integration): 26 passed
tsc --noEmit; oxfmt --ignore-path .gitignore --check; oxlint --type-aware --deny-warnings: clean

🤖 Generated with Claude Code

@changeset-bot

changeset-bot Bot commented Sep 24, 2026 •

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 9bc0364

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

@pkg-pr-new

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

Copy link
Copy Markdown

Open in StackBlitz

@emdash-cms/admin

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

@emdash-cms/auth

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

@emdash-cms/auth-atproto

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

@emdash-cms/blocks

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

@emdash-cms/cloudflare

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

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

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

emdash

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

create-emdash

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

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

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

@emdash-cms/plugin-cli

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

@emdash-cms/plugin-test

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

@emdash-cms/plugin-types

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

@emdash-cms/registry-client

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

@emdash-cms/registry-lexicons

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

@emdash-cms/registry-loader

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

@emdash-cms/registry-moderation

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

@emdash-cms/registry-verification

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

@emdash-cms/sandbox-workerd

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

@emdash-cms/x402

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

@emdash-cms/plugin-ai-moderation

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

@emdash-cms/plugin-atproto

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

@emdash-cms/plugin-audit-log

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

@emdash-cms/plugin-color

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

@emdash-cms/plugin-embeds

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

@emdash-cms/plugin-field-kit

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

@emdash-cms/plugin-forms

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

@emdash-cms/plugin-webhook-notifier

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

commit: 9bc0364

@eisenbruch
eisenbruch force-pushed the fix/pivot-temp-sort-keeps-pin branch from 213edfe to 225dd4d Compare September 24, 2026 18:04
@eisenbruch
eisenbruch marked this pull request as ready for review September 25, 2026 22:16
@eisenbruch

Copy link
Copy Markdown
Contributor Author

Marking ready: 0.40.0 released #3300, so the temp-sort case this fixes is now in a release. CI is green on 225dd4d and it merges cleanly with current main. On our site I'm carrying this exact change as a local patch on 0.40.1.

@github-actions github-actions Bot added the review/needs-review No maintainer or bot review yet label Sep 25, 2026

@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.

The approach is correct and targeted. buildTaxonomyPivotQuery should only let the planner reorder the picked CTE when the sort key has an index that supports stopping early at LIMIT (published_at/created_at). For updated_at and field sorts the temp-sort branch collects every tagged entry, so releasing the pin allows D1 to walk the collection index; restoring CROSS JOIN forces content_taxonomies as the outer table. The conditional isPostgres(db) || isIndexedSort mirrors the join-order pinning pattern already used elsewhere in this file (e.g., the byline fold), and the dialect-agnostic unit tests cover both the indexed and temp-sort paths.

I read the diff, the surrounding loader code, the integration plan test, the unit pivot test, the changeset, and the relevant AGENTS.md conventions. The implementation is sound and the SQL is safe. The remaining items are documentation/comment polish: the changeset references issue #3300 and speaks in implementation terms, and the new test comment repeats PR narrative that will be stale to a future reader.

Comment thread .changeset/pivot-temp-sort-pin.md Outdated
"emdash": patch
---

Fixes taxonomy-filtered listings sorted by `updated_at` or a field reading the whole collection on D1. The plain join from #3300 now applies only to `published_at` and `created_at` sorts, where the query can stop at its limit; other sorts start from the term's assignments again.

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.

[suggestion] The issue reference #3300 and the "plain join" wording are implementation history, not guidance for someone reading the CHANGELOG. The first sentence already names the user-facing problem. Keep that and restate the affected sorts in terms of what readers can observe.

Suggested change
Fixes taxonomy-filtered listings sorted by `updated_at` or a field reading the whole collection on D1. The plain join from #3300 now applies only to `published_at` and `created_at` sorts, where the query can stop at its limit; other sorts start from the term's assignments again.
Fixes taxonomy-filtered listings sorted by `updated_at` or a custom field reading the whole collection on D1. `published_at` and `created_at` sorts still use the indexed path that stops at `LIMIT`; `updated_at` and field sorts now seek from the term's assignments again.

Comment on lines +164 to +167
// The plan itself is not asserted here: which side SQLite drives from with
// a plain JOIN depends on planner statistics, and D1 chose the collection
// (10,471 rows, 3x the rows read) where local SQLite with the same
// `sqlite_stat1` chose the pivot. So this pins the join the builder emits.

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.

[suggestion] This comment is addressed to the PR reader, not a future maintainer: it explains why the plan-assertion approach was rejected and repeats production row counts from the incident. The invariant the test enforces is important, but the surrounding narrative will be stale once the PR is merged. Trim it to the stable reason.

Suggested change
// The plan itself is not asserted here: which side SQLite drives from with
// a plain JOIN depends on planner statistics, and D1 chose the collection
// (10,471 rows, 3x the rows read) where local SQLite with the same
// `sqlite_stat1` chose the pivot. So this pins the join the builder emits.
// `EXPLAIN QUERY PLAN` differs between D1 and local SQLite for the same plain
// JOIN, so this test pins the join the builder emits as the stable contract.

@emdashbot emdashbot Bot added review/awaiting-author Reviewed; waiting on the author to respond and removed review/needs-review No maintainer or bot review yet labels Sep 25, 2026
@github-actions github-actions Bot added review/needs-rereview New commits since the last review and removed review/awaiting-author Reviewed; waiting on the author to respond labels Sep 26, 2026
@eisenbruch

Copy link
Copy Markdown
Contributor Author

Both suggestions applied in 9bc0364: the changeset now describes what readers observe, and the test comment states the stable reason only. oxfmt clean, pivot tests pass (26).

@ascorbic ascorbic added the bot:review Trigger an emdashbot code review on this PR label Sep 27, 2026

@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.

The approach remains correct and targeted. The previous review's two documentation/comment findings have been addressed: the test comment is now a concise, stable explanation of why the test asserts the emitted join rather than the query plan, and the changeset no longer references implementation-history issue numbers or speaks in diff terms. The implementation safely restores the CROSS JOIN pin for the temp-sort branch on SQLite/D1 while keeping the indexed-sort branch on JOIN; tests cover updated_at, field, and published_at sorts; locale filtering and status/deleted re-checks are unchanged; and the changeset is user-facing and helpful.

The one remaining item is a comment gap in packages/core/src/loader.ts: the explanatory block above pivotContentJoin explains the SQLite planner rationale (indexed sorts want JOIN, temp sorts want CROSS JOIN) but never says why isPostgres(db) is part of the condition. A maintainer reading only the comment could think Postgres is grouped with indexed sorts for performance reasons and might be tempted to remove the check. The byline fold earlier in the same file already documents the same Postgres constraint (CROSS JOIN … ON is rejected), so adding it here is a straightforward consistency fix. I checked AGENTS.md conventions (SQL safety, API envelope, auth, locale filtering on content tables, index discipline, changeset quality, logged-out query counts, and comment discipline) and found no other issues.


Findings

  • [suggestion] packages/core/src/loader.ts:951-964

    The pivotContentJoin condition mixes two unrelated reasons into one expression: isPostgres(db) is there because Postgres rejects CROSS JOIN … ON syntax, while isIndexedSort is there because SQLite/D1 can stop early at LIMIT for indexed sorts. The surrounding comment only explains the SQLite indexed-sort rationale and the temp-sort pin, so the Postgres exception is unexplained. A future reader could easily assume isPostgres(db) is a performance grouping and remove it.

    The byline fold earlier in this file already documents the same Postgres constraint (line 136). Add the same note here.

    	// A plain JOIN lets SQLite reorder the `picked` CTE. For indexed sorts
    	// (`published_at`/`created_at`) the planner can then drive from the
    	// `(deleted_at, <sort> DESC, id DESC)` index on `ec_*`, probe the pivot
    	// by primary key, and short-circuit at `LIMIT`. A `CROSS JOIN` pin would
    	// force `content_taxonomies` as the outer table and require a temp sort,
    	// producing a full nested loop over the collection on D1. Postgres
    	// rejects `CROSS JOIN ... ON`, so it also falls back to a plain JOIN.
    	//
    	// The temp-sort branch keeps the pin. Its `picked` collects every tagged
    	// entry with no `LIMIT`, so starting from `ec_*` can never stop early, and
    	// D1 does start there when `ANALYZE` has underestimated
    	// `deleted_at IS NULL` (a trash with many distinct deletion times): it
    	// walks the collection's `(deleted_at, status)` index and probes the pivot
    	// once per published row.
    	const pivotContentJoin = isPostgres(db) || isIndexedSort ? sql`JOIN` : sql`CROSS JOIN`;
    

@emdashbot emdashbot Bot added review/awaiting-author Reviewed; waiting on the author to respond and removed bot:review Trigger an emdashbot code review on this PR review/needs-rereview New commits since the last review labels Sep 27, 2026

@ascorbic ascorbic left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Thanks!

@emdashbot emdashbot Bot added review/approved Approved; no new commits since and removed review/awaiting-author Reviewed; waiting on the author to respond labels Sep 27, 2026
@ascorbic
ascorbic merged commit 1ee3c4f into emdash-cms:main Sep 27, 2026
47 checks passed
danielmlr added a commit to danielmlr/emdash that referenced this pull request Sep 27, 2026
emdash-cms#3409 pinned the pivot join for temp sorts and freed it for every indexed
sort. This branch frees it only for a single large term under an indexed
sort with a LIMIT, which already keeps temp sorts pinned, so its join
condition stays. The comment keeps emdash-cms#3409's reason for the temp-sort pin
and drops the claim that D1 keeps no planner statistics, which emdash-cms#3409's
production statistics contradict. emdash-cms#3409's join test moves into the
large-term block, the only shape whose indexed sort still frees the join.

emdash-cms#3510 replaced better-sqlite3, so the plan test uses the node:sqlite
helper.
danielmlr added a commit to danielmlr/emdash that referenced this pull request Sep 27, 2026
emdash-cms#3409 pinned the pivot join for updated_at and field sorts on main, so
those listings no longer walk the collection and this change no longer
fixes them. The entry now names only the indexed sorts it changes, and
created_at as the default, so it does not repeat emdash-cms#3409's entry in the
same release.
khoinguyenpham04 pushed a commit that referenced this pull request Sep 30, 2026
…rms (#3402)

* fix(core): stop taxonomy listings walking the collection for small terms

The plain JOIN in the pivot listing lets SQLite drive every taxonomy
listing from the ec_* sort index. That fills a page quickly for a term
with many entries, but for a small term it reads up to the whole
collection, and the same happens for updated_at sorts and for listings
that combine several terms or taxonomies.

The term lookup now carries a capped count of the term's pivot rows.
Only a single term with at least 200 of them, under a published_at or
created_at sort with a LIMIT, walks ec_*. Every other listing seeks the
pivot again, as it did before the plain JOIN. The count rides in the
existing lookup query, so the query count is unchanged.

Measured on local D1 with 20,000 posts, listing plus term lookup: a
2-post term reads 40 rows instead of 20,030, a 19,000-post term 486
instead of 285.

* ci: update query-count snapshots

* docs(core): narrow the changeset to published_at and created_at sorts

#3409 pinned the pivot join for updated_at and field sorts on main, so
those listings no longer walk the collection and this change no longer
fixes them. The entry now names only the indexed sorts it changes, and
created_at as the default, so it does not repeat #3409's entry in the
same release.

* test(core): cover the size probe's collection scope

The size probe counts a term's pivot rows in the listed collection only.
Without that condition, a term with 200 or more assignments in another
collection would count as large and walk the whole collection for a
listing where it tags a single entry. No plan test failed when the
condition was removed; this one does, and it fails on main as well.

* docs(core): say why Postgres gets the plain pivot join, drop the D1 statistics claim

The join comment explained the SQLite choice only, leaving `isPostgres(db)`
in the condition unexplained; Postgres rejects `CROSS JOIN ... ON`, as the
byline fold in the same file already notes.

The plan tests claimed D1 never keeps sqlite_stat1 and that their plans
match D1 exactly. A D1 database has statistics once its operator runs
ANALYZE or PRAGMA optimize (#3408 measured one). EmDash never runs either,
which is why the tests run without them.

---------

Co-authored-by: emdashbot[bot] <emdashbot[bot]@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Taxonomy pivot: #3300's plain JOIN in the temp-sort branch lets D1 walk the collection (3x rows read)

2 participants