Repository navigation
Conversation
…d listings (emdash-cms#1834) On SQLite/D1, a taxonomy-filtered listing ordered + paginated walks the whole collection in ORDER BY order applying the taxonomy filter as a correlated EXISTS per row. For a selective term (few matches) the LIMIT never fills early, so it scans the entire table — ~75k D1 rows read for a page returning one row. Adds an opt-in `taxonomyStrategy: "seek"` filter option that drives the query from content_taxonomies (materialized _matched CTE + CROSS JOIN, seeking by taxonomy_id and joining the collection by primary key). Default "scan" is unchanged and remains best for non-selective terms. SQLite-only; Postgres has statistics and is untouched. Also adds composite index content_taxonomies(taxonomy_id, collection, entry_id) (migration 051), which the seek plan relies on and which supersedes the single-column idx_content_taxonomies_term. Co-Authored-By: Claude Opus 4.8 <[email protected]>
🦋 Changeset detectedLatest commit: 67c6df4 The changes in this PR will be included in the next version bump. This PR includes changesets to release 16 packages
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 |
@emdash-cms/admin
@emdash-cms/auth
@emdash-cms/auth-atproto
@emdash-cms/blocks
@emdash-cms/cloudflare
@emdash-cms/contentful-to-portable-text
emdash
create-emdash
@emdash-cms/gutenberg-to-portable-text
@emdash-cms/plugin-cli
@emdash-cms/plugin-types
@emdash-cms/registry-client
@emdash-cms/registry-lexicons
@emdash-cms/sandbox-workerd
@emdash-cms/x402
@emdash-cms/plugin-ai-moderation
@emdash-cms/plugin-atproto
@emdash-cms/plugin-audit-log
@emdash-cms/plugin-color
@emdash-cms/plugin-embeds
@emdash-cms/plugin-field-kit
@emdash-cms/plugin-forms
@emdash-cms/plugin-webhook-notifier
commit: |
There was a problem hiding this comment.
This PR addresses the right problem with a backwards-compatible approach: an opt-in taxonomyStrategy: "seek" hint that drives selective taxonomy-filtered listings from the pivot index on SQLite/D1, leaving the default EXISTS scan unchanged. The migration adds the needed composite index, drops the now-redundant single-column one, and is registered correctly. I checked the loader/query type plumbing, SQL safety (identifiers and values are parameterized), locale/byline/field/cursor handling, migration registration/DDL, index naming, and the new tests.
The headline issue is a correctness bug in the seek rewrite: the per-taxonomy candidate CTE selects ct.entry_id without DISTINCT. When the filter contains a single taxonomy with multiple slugs (e.g., { category: ['news', 'sports'] }) and an entry is tagged with more than one of those slugs, that entry_id appears in the CTE multiple times. The outer CROSS JOIN then emits the same content row multiple times. INTERSECT only deduplicates when at least two taxonomies are filtered, so OR-within-one-taxonomy cases are affected. The existing two-dialect correctness tests only run the default EXISTS path, and the new SQLite-only plan test uses a single slug, so this case is uncovered.
Fix by adding DISTINCT to the per-taxonomy selects and add a seek-path correctness test that ORs multiple slugs within one taxonomy (and ideally combines it with another taxonomy).
| (f) => sql`SELECT ct.entry_id AS _matched_id | ||
| FROM taxonomies t | ||
| INNER JOIN content_taxonomies ct ON ct.taxonomy_id = t.translation_group | ||
| WHERE +ct.collection = ${type} | ||
| AND t.name = ${f.name} | ||
| AND t.slug IN (${sql.join(f.slugs.map((s) => sql`${s}`))}) | ||
| ${locale ? sql`AND t.locale = ${locale}` : sql``}`, |
There was a problem hiding this comment.
[needs fixing] The seek-path _matched CTE selects entry IDs per taxonomy without DISTINCT. For a single taxonomy filter that ORs multiple slugs (e.g., { category: ['news', 'sports'] }), an entry tagged with both slugs appears in the CTE twice. The outer CROSS JOIN then emits duplicate rows for the same entry. The existing EXISTS path is a semi-join and never duplicates. INTERSECT only deduplicates when at least two taxonomies are filtered, so this case is broken.
Also extend the taxonomy correctness tests to exercise taxonomyStrategy: "seek" with OR-within-a-taxonomy to prevent regression.
| (f) => sql`SELECT ct.entry_id AS _matched_id | |
| FROM taxonomies t | |
| INNER JOIN content_taxonomies ct ON ct.taxonomy_id = t.translation_group | |
| WHERE +ct.collection = ${type} | |
| AND t.name = ${f.name} | |
| AND t.slug IN (${sql.join(f.slugs.map((s) => sql`${s}`))}) | |
| ${locale ? sql`AND t.locale = ${locale}` : sql``}`, | |
| (f) => sql`SELECT DISTINCT ct.entry_id AS _matched_id | |
| FROM taxonomies t | |
| INNER JOIN content_taxonomies ct ON ct.taxonomy_id = t.translation_group | |
| WHERE +ct.collection = ${type} | |
| AND t.name = ${f.name} | |
| AND t.slug IN (${sql.join(f.slugs.map((s) => sql`${s}`))}) | |
| ${locale ? sql`AND t.locale = ${locale}` : sql``}`, |
There was a problem hiding this comment.
Fixed. Added DISTINCT to the per-taxonomy _matched select — the single-filter OR-within case had no INTERSECT to dedupe, so an entry tagged with both slugs fanned out through the CROSS JOIN. Corrected the comment too (it wrongly credited INTERSECT, which only dedupes across ≥2 filters).
Added two seek-path correctness tests to loader-taxonomy-filter.test.ts: OR-within-one-taxonomy, and OR-within combined with a second taxonomy, both cross-checked against the default scan path. Confirmed via TDD that both fail without the DISTINCT (duplicate row) and pass with it.
…onomy
The seek-strategy `_matched` CTE selected pivot entry ids without
DISTINCT. For a single taxonomy filtered by multiple slugs
(`{ category: ['news', 'sports'] }`), an entry tagged with more than one
slug had a pivot row per slug and no INTERSECT to dedupe it, so the outer
CROSS JOIN emitted the content row multiple times. The default EXISTS
scan is a semi-join and never duplicated.
Add DISTINCT to the per-taxonomy select and add seek-path correctness
tests covering OR-within-one-taxonomy (alone and combined with a second
taxonomy), cross-checked against the scan path.
Co-Authored-By: Claude Opus 4.8 <[email protected]>
There was a problem hiding this comment.
The previous review's correctness bug is fixed: the per-taxonomy matched CTE now uses SELECT DISTINCT ct.entry_id, and the new tests cover the exact case that was broken — OR-ing multiple slugs within one taxonomy, both alone and combined with a second taxonomy. The integration plan test still verifies the seek path uses the composite pivot index, and the migration/index swap is registered correctly.
However, I have one remaining concern about the SQLite optimizer hack used to force that plan. The _matched CTE uses +ct.collection = ${type} to disqualify the pivot PK auto-index. Unary + on a TEXT expression forces numeric affinity in SQLite, so a predicate like +'post2' = 'post' is evaluated as 0 = 0 and would match other text collection names. The final CROSS JOIN with ec_${type} filters those mismatched rows out of the result (entry IDs from other collections can't exist in the requested table), but the CTE still reads/joins extra content_taxonomies rows from other collections, which partly undermines the D1 rows-read goal and creates a latent correctness hazard if anyone ever removes or weakens that final join. Add a multi-collection regression test and either confirm the plan/rows-read stay correct, or replace +ct.collection with a semantically neutral expression (e.g., CAST(ct.collection AS TEXT) = ${type}, or moving the collection equality into the join) and verify the planner still picks idx_content_taxonomies_term_lookup.
Overall this is the right additive fix for #1834 and is backwards-compatible. With the unary-plus concern verified/addressed, it's ready.
Add a seek-path test covering a term shared across two collections, asserting the "post" listing stays scoped to posts and matches the scan path. Verifies the reviewer's cross-collection concern on emdash-cms#1843 does not manifest: the `+ct.collection` predicate keeps TEXT affinity (unary `+` is a value/type no-op in SQLite), so `_matched` never admits other collections' rows. Also switch three seek-strategy assertions from `Array#sort()` to `toSorted()` to clear the lint warnings introduced in 5840cf8. Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
On the unary-plus concern — checked it directly and the premise doesn't hold. SQLite's unary So The suggested rewrite (drop Added the multi-collection regression test you asked for ( |
There was a problem hiding this comment.
This is still the right additive, backwards-compatible fix for #1834. Since the prior review, the per-taxonomy DISTINCT is in place, the OR-within / AND-across correctness cases are covered, the migration/index swap (051) is wired up correctly, and the new multi-collection result test shows the observable payload stays scoped.
The one remaining concern from the prior review is not yet addressed, however: the seek rewrite still uses +ct.collection = ${type} to disable the pivot PK auto-index. Unary + on a TEXT column forces numeric affinity in SQLite, so a predicate like +ct.collection = 'post' evaluates as a numeric comparison and matches every text collection name (+'post2' → 0, 'post' → 0, 0 = 0). The final CROSS JOIN ec_${type} masks this by dropping entry IDs that don't exist in the requested table, so the current result set is correct, but:
- the
_matchedCTE still reads/joins extracontent_taxonomiesrows from other collections, partially defeating the D1 rows-read optimization the PR is adding; - it creates a latent correctness hazard: anyone who later refactors the query and relaxes that final join could serve entries from the wrong collection.
Please replace +ct.collection with a semantically neutral, non-sargable expression (e.g. ct.collection || '' = ${type}), keep the existing plan test asserting idx_content_taxonomies_term_lookup, and consider extending the plan-level test to confirm the multi-collection rows-read behavior. Once that's verified this is ready to land.
The seek-path `_matched` CTE used `+ct.collection = ${type}` to disqualify
the pivot PK auto-index. The unary `+` forces only a single-column
`(taxonomy_id=?)` seek and applies `collection` as a residual filter, so a
term shared across collections reads that term's rows in *every*
collection, then discards the non-matching ones — a page returning one row
can read hundreds.
Replace it with an explicit `INDEXED BY idx_content_taxonomies_term_lookup`
plus a plain `ct.collection = ${type}` equality. This keeps the composite
index but seeks on both leading columns `(taxonomy_id=? AND collection=?)`,
reading only the queried collection's slice of the term. Measured against a
real D1 dataset, a shared selective term dropped from 704 rows read to 2.
Plain equality also removes the confusing unary `+`.
Tighten the plan test to assert the two-column seek so the residual-filter
form can't silently return.
Co-Authored-By: Claude Opus 4.8 <[email protected]>
There was a problem hiding this comment.
This is the right additive, backwards-compatible fix for #1834. The seek rewrite drives selective taxonomy listings from content_taxonomies on SQLite/D1, leaving the existing scan path as the default so non-selective terms keep their cheaper plan.
The one outstanding concern from the prior review has been addressed — the rewrite now uses a plain ct.collection = ${type} equality together with INDEXED BY idx_content_taxonomies_term_lookup. That avoids the numeric-affinity footgun of the previous unary-plus trick and, unlike a non-sargable expression, lets the composite index seek on both leading columns (taxonomy_id, collection). The new plan-level assertion confirms exactly that shape.
What I checked:
- Migration 051 is correctly wired into
runner.ts, creates the composite index before dropping the redundant single-column one, and itsdownpath is symmetric. - The loader changes are SQLite-only, guard all required conditions (
taxonomyStrategy === "seek",!isPostgres, and at least one taxonomy filter), and fall back cleanly to the existingEXISTSpath. - Locale filtering, byline filters, field filters, cursor/offset pagination, and folded term/byline hydration are preserved on the seek path.
- New tests cover the index swap, OR-within-one-taxonomy dedupe, AND-across-taxonomies semantics, multi-collection scoping, and the EXPLAIN shape. No other code references the dropped
idx_content_taxonomies_termby name.
One non-blocking suggestion: the built-in getEntriesByTerm helper is the natural place to opt into this optimization, but it currently has no way to pass taxonomyStrategy. Adding and forwarding that option would make the most common term-archive use case benefit without callers dropping down to getEmDashCollection directly.
Findings
-
[suggestion]
packages/core/src/taxonomies/index.ts:746-748The
getEntriesByTermhelper is the canonical way to render a term archive page, but it cannot opt into the new"seek"strategy. Callers who want the optimization have to bypass this helper and write thegetEmDashCollectioninvocation themselves.Consider extending
TaxonomyQueryOptions(or the helper'soptions) withtaxonomyStrategy?: "scan" | "seek"and forwarding it inqueryOptions:const queryOptions: Record<string, unknown> = { where: { [taxonomyName]: termSlug }, taxonomyStrategy: options.taxonomyStrategy, };
This keeps the helper useful for the exact
/tag/[slug]case the new option is designed for.
|
Superseded by a reworked implementation: instead of a manual strategy option, the loader now plans taxonomy-filtered listings automatically from cached per-term counts (single-term seek/scan + multi-term smallest-first nested-loop). Design write-up in Discussion #1851; a fresh PR follows. Closing this one. |
What does this PR do?
On SQLite/D1, a taxonomy-filtered collection listing (
where: { category }, ordered + paginated) walks the entire collection table inORDER BYorder, applying the taxonomy filter as a correlatedEXISTSper row. When the term is selective (few matches), theLIMITnever fills early, so the scan runs to the end of the table — on a ~26k-row collection this read ~75,000 D1 rows for a page returning one row. On D1, rows-read is the billed/throttled unit, so a routine category page reads the whole collection.This adds an opt-in
taxonomyStrategy: "seek"option togetEmDashCollection. When set, the query drives fromcontent_taxonomies— seeking the term via a materialized_matchedCTE (CROSS JOINpins the join order) and joining the collection by primary key, then sorting the small candidate set. This reads only the matching entries.The seek is forced onto the composite pivot index with an explicit
INDEXED BY idx_content_taxonomies_term_lookupand a plainct.collection = ?equality, so it seeks on both leading columns(taxonomy_id=? AND collection=?). Without a hint, a stats-blind D1 planner drives from the pivot PK's(collection, …)autoindex instead — a whole-collection scan of the join table. Seeking on both columns also matters when a term is shared across collections: a single-column(taxonomy_id=?)seek with a residualcollectionfilter reads the term's rows in every collection, whereas the two-column seek reads only the queried collection's slice. Measured against a real D1 dataset, a shared selective term dropped from 704 rows read to 2 with the two-column seek.The default (
"scan") is unchanged and remains best for non-selective terms (a broad category holding most of the collection), where the ordered index walk fills the page quickly. Selectivity is a per-term property the framework can't know without a query, so the caller opts in per route. SQLite/D1 only — Postgres has statistics and plans this well on its own.Also adds composite index
content_taxonomies(taxonomy_id, collection, entry_id)(migration 051), which the seek plan relies on and which supersedes the single-columnidx_content_taxonomies_term(its leftmost prefix covers the same reverse lookup).Measured on the reporter's repro (26,224 rows, term matching 1 entry): scan ≈ 75,454 rows read / ~295 ms → seek ≈ 10 rows read / ~1 ms.
Closes #1834
Type of change
Checklist
pnpm typecheckpassespnpm lintpassespnpm testpasses (or targeted tests for my change)pnpm formathas been runAI-generated code disclosure
Screenshots / test output
New tests (TDD):
tests/unit/database/migrations/051_content_taxonomies_term_lookup.test.ts— composite index created, single-column index dropped.tests/integration/loader-taxonomy-filter-plan.test.ts—EXPLAIN QUERY PLANon stats-blind SQLite:"seek"drives fromidx_content_taxonomies_term_lookupon both leading columns(taxonomy_id=? AND collection=?)(not the collection's published index); default (no hint) keeps theEXISTSscan unchanged.tests/unit/loader-taxonomy-filter.test.ts— OR-within-one-taxonomy dedupe and a multi-collection case (a term shared by two collections stays scoped to the queried one, matching the scan path).Existing two-dialect taxonomy-filter correctness tests (single / AND-across / OR-within / empty / localized) stay green. Affected suite: 42 passing; broader core sweep: 3048 passing.
🤖 Generated with Claude Code