Repository navigation
fix(core): drive the taxonomy pivot query from the most selective taxonomy, not the first where key - #3266
Conversation
🦋 Changeset detectedLatest commit: ed270ef The changes in this PR will be included in the next version bump. This PR includes changesets to release 12 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-test
@emdash-cms/plugin-types
@emdash-cms/registry-client
@emdash-cms/registry-lexicons
@emdash-cms/registry-loader
@emdash-cms/registry-moderation
@emdash-cms/registry-verification
upgrade-emdash
@emdash-cms/sandbox-workerd
@emdash-cms/x402
@emdash-cms/plugin-ai-moderation
@emdash-cms/plugin-ai-search
@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.
The approach is sound: reordering the taxonomy sets so the most selective one drives the pivot seek fixes the key-order dependency described in #3259 and keeps results identical. The code is otherwise correct — the count query is parameterized through Kysely and the locale-agnostic pivot rows mean omitting a locale filter is appropriate.
The main concern is that the "optimization" introduces one extra round-trip per additional taxonomy filter on the public-collection hot path, which is exactly what EmDash’s performance conventions warn against ("one query beats two" and "the logged-out hot path only ratchets down"). The selectivity probe should be batched into a single GROUP BY taxonomy_id count instead of Promise.all per set. The new regression test also only asserts result equality, which was already true before the fix; it does not protect against the reported rows-read regression. The changeset and the new inline comment are usable but drift toward describing internal query mechanics rather than the user-facing behavior.
I did not run the test suite, builds, or query-count tooling; those claims are unverified.
| if (groupSets.length > 1) { | ||
| const sizes = await Promise.all( | ||
| groupSets.map((groups) => | ||
| db | ||
| .selectFrom("content_taxonomies") | ||
| .select((eb) => eb.fn.countAll<number>().as("n")) | ||
| .where("collection", "=", type) | ||
| .where("taxonomy_id", "in", groups) | ||
| .executeTakeFirst() | ||
| .then((r) => Number(r?.n ?? 0)), | ||
| ), | ||
| ); | ||
| const ordered = groupSets |
There was a problem hiding this comment.
[needs fixing] The new selectivity probe issues one query per taxonomy set in Promise.all. On a logged-out collection route filtered by two or more taxonomies, this adds N extra round-trips to D1 for every request that takes this path, partially undermining a PR whose goal is to reduce query cost. EmDash’s conventions prefer batching over multiple similar queries.
Use a single GROUP BY taxonomy_id count over the union of all sets, then sum per set locally:
| if (groupSets.length > 1) { | |
| const sizes = await Promise.all( | |
| groupSets.map((groups) => | |
| db | |
| .selectFrom("content_taxonomies") | |
| .select((eb) => eb.fn.countAll<number>().as("n")) | |
| .where("collection", "=", type) | |
| .where("taxonomy_id", "in", groups) | |
| .executeTakeFirst() | |
| .then((r) => Number(r?.n ?? 0)), | |
| ), | |
| ); | |
| const ordered = groupSets | |
| if (groupSets.length > 1) { | |
| const allGroups = groupSets.flat(); | |
| const rows = await db | |
| .selectFrom("content_taxonomies") | |
| .select(["taxonomy_id", (eb) => eb.fn.countAll<number>().as("n")]) | |
| .where("collection", "=", type) | |
| .where("taxonomy_id", "in", allGroups) | |
| .groupBy("taxonomy_id") | |
| .execute(); | |
| const countById = new Map(rows.map((r) => [r.taxonomy_id, Number(r.n ?? 0)])); | |
| const sizes = groupSets.map((groups) => | |
| groups.reduce((sum, g) => sum + (countById.get(g) ?? 0), 0), | |
| ); | |
| const ordered = groupSets | |
| .map((groups, i) => ({ groups, n: sizes[i] })) | |
| .toSorted((a, b) => a.n - b.n) | |
| .map((x) => x.groups); | |
| groupSets.splice(0, groupSets.length, ...ordered); | |
| } |
| // The pivot query walks the FIRST set through `content_taxonomies` and checks the rest with a | ||
| // correlated EXISTS per candidate row, so the rows read depend on which set drives. Until now that | ||
| // was the caller's first `where` key: the same query read 3,131 rows one way round and 539 the | ||
| // other. Drive from the set with the fewest pivot rows; the counts are an index-only read. |
There was a problem hiding this comment.
[suggestion] This comment reads like the PR description (specific observed row counts, historical ordering behavior) rather than a concise invariant for future readers. AGENTS.md asks comments to explain why the code must do something, not to summarize the change or PR.
| // The pivot query walks the FIRST set through `content_taxonomies` and checks the rest with a | |
| // correlated EXISTS per candidate row, so the rows read depend on which set drives. Until now that | |
| // was the caller's first `where` key: the same query read 3,131 rows one way round and 539 the | |
| // other. Drive from the set with the fewest pivot rows; the counts are an index-only read. | |
| // The pivot query walks the first set through content_taxonomies and | |
| // correlates the rest with an EXISTS per candidate row, so choose the | |
| // smallest set to minimize rows read. |
| expect(titles).toContain("Sports + Featured"); | ||
| }); | ||
|
|
||
| it("gives the same result whichever taxonomy is written first (#3259)", async () => { |
There was a problem hiding this comment.
[suggestion] This test asserts that both key orders return the same IDs, but #3259 reports a rows-read asymmetry, not a correctness bug — the result set was already identical before the fix. A test that cannot fail on the reported regression gives false confidence. Consider either instrumenting rows_read via the DB (e.g., D1 meta.rows_read, or an EXPLAIN/plan-cost assertion on SQLite) or removing this case if measuring the plan is impractical in unit tests.
| "emdash": patch | ||
| --- | ||
|
|
||
| A collection query filtered by two or more taxonomies now drives the pivot query from the taxonomy with the fewest tagged entries instead of whichever key the caller wrote first. Results are unchanged; on a large collection the rows read no longer depend on key order (3,131 versus 539 for the same query in one measurement). |
There was a problem hiding this comment.
[suggestion] The changeset describes the internal “pivot query” mechanics rather than leading with the user-facing behavior. Per .changeset/README.md, readers should be able to tell whether the release affects them without knowing the loader’s internal query shape.
| A collection query filtered by two or more taxonomies now drives the pivot query from the taxonomy with the fewest tagged entries instead of whichever key the caller wrote first. Results are unchanged; on a large collection the rows read no longer depend on key order (3,131 versus 539 for the same query in one measurement). | |
| A collection query filtered by two or more taxonomies now evaluates those filters in the order that minimizes rows read, instead of the order they were written in `where`. Results are unchanged; on large collections the rows read no longer depend on key order (3,131 versus 539 for the same query in one measurement). |
|
Agreed on "one query beats two", and done in On the test: it asserts result equality across key orders, which is the contract, and I have not added a rows-read assertion because the unit harness has no statement or row counter to assert against (the figures in #3259 are D1's own |
050cbb9 to
d7afc6c
Compare
|
Rebased onto The statement
The |
…onomy, not the first where key
The selectivity probe ran one COUNT per taxonomy set; a GROUP BY over all the sets' ids is one round trip on the public render path.
d7afc6c to
df2f562
Compare
|
Brought up to date with |
ascorbic
left a comment
There was a problem hiding this comment.
This is good, and worth having, but I'd like to remove the extra round trip. As it stands, this adds an extra query for collections filtered by two or more taxonomies. This could be avoided by adding it to the query in resolveTermGroups. Adding it as a subquery means we can get the count without the extra round trip.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01RktNvhjty22ohh1GSHXGMq
|
Done in The new test counts statements. With the per-isolate taxonomy definitions warm, a Locally: |
There was a problem hiding this comment.
The approach is sound. Ordering the taxonomy sets so the smallest drives the pivot seek fixes the key-order dependency from #3259 and leaves results unchanged. The earlier round-trip concern is resolved, because set sizes now come from a correlated COUNT inside the existing term-resolution query. The new test checks query count and driving-set choice, so it can fail on a real regression. The reviewers disagree on one point. openai/gpt-6.1-sol found no remaining issues and approved. anthropic/claude-opus-5-5 raised one needs_fixing finding: the size probe is an uncapped COUNT that could read about as many rows as the plan it is meant to avoid. That finding is kept below. Both reviews were static, and neither ran tests nor measured rows_read.
Reviewed by anthropic/claude-opus-5-5 and openai/gpt-6.1-sol.
| .$if(countCollection !== undefined, (qb) => | ||
| qb.select((eb) => | ||
| eb | ||
| .selectFrom("content_taxonomies") | ||
| .select((inner) => inner.fn.countAll<number>().as("n")) | ||
| .where("content_taxonomies.collection", "=", countCollection!) | ||
| .whereRef("content_taxonomies.taxonomy_id", "=", "taxonomies.translation_group") | ||
| .as("assignments"), |
There was a problem hiding this comment.
[needs fixing] Raised by anthropic/claude-opus-5-5; openai/gpt-6.1-sol found no remaining issues and did not raise this. The size probe is an uncapped COUNT(*) over content_taxonomies for each resolved term. It runs on every logged-out listing that filters on two or more taxonomies. The idx_content_taxonomies_group_lookup (taxonomy_id, collection, entry_id) index keeps it index-only, but it still steps through every index entry for each term, and D1 bills those steps as rows_read.
Take the #3259 shape. If business_type has about 3,000 assignments and places has about 500, the probe reads about 3,500 entries before the 539-row pivot query runs. That totals about 4,000 rows, which is worse than the 3,131 the slow key order read before this change. The cost also grows with the largest term on every request.
The sort only needs to know which set is smaller, not exact sizes. Cap the probe the same way LARGE_TERM_ASSIGNMENTS caps the large probe, for example SELECT COUNT(*) FROM (SELECT 1 … LIMIT cap). Check first that the correlated form works on both SQLite and Postgres. Another option is a few LIMIT 1 OFFSET k existence probes at fixed thresholds. Also measure rows_read with the probe included for both #3259 key orders, to confirm the total actually drops.
There was a problem hiding this comment.
Fair point, and the numbers back it. eaaf11e caps the count at LARGE_TERM_ASSIGNMENTS per term (SELECT COUNT(*) FROM (SELECT 1 … LIMIT 200) AS capped, still correlated and still inside the term lookup).
Measured on D1 (meta.rows_read). These are the statements the loader compiles, captured from the test executor and bound to real values, so the totals are term lookups plus the content query (orderBy: { title: "asc" }, limit: 13):
Listings: one place (95 assignments) and five business types (154 to 1,149 each, 3,285 in all). Returns 13.
| lookups | content | total | |
|---|---|---|---|
| main, types written first | 17 | 29,549 | 29,566 |
| main, place written first | 17 | 1,164 | 1,181 |
| previous commit (uncapped count) | 3,403 | 1,164 | 4,567 |
| this commit (capped at 200) | 1,068 | 1,164 | 2,232 |
Articles: one topic (226) and one place (32). Returns 13.
| lookups | content | total | |
|---|---|---|---|
| main, topic written first | 4 | 1,073 | 1,077 |
| main, place written first | 4 | 489 | 493 |
| this commit | 237 | 489 | 726 |
So the uncapped count did cost more than it saved against a well-ordered where. Capped, the total no longer depends on key order and stays far below the slow order. It is still above a caller who already writes the selective key first, because each term can cost up to 200 index steps. A smaller dedicated cap would narrow that gap (50 gives 1,481 for the listings case), but two sets tie more often, and a tie keeps the written order. I kept the existing constant. Happy to change it if you'd prefer a separate one.
The content statement reads more here than the 3,131 / 539 in #3259 because it's a different statement (title order, full row, different data).
Postgres: the loader taxonomy and field-filter tests pass on a local PostgreSQL 14 as well as SQLite (44 of 44). The derived table carries the alias that PostgreSQL 14 requires. The #3259 test now also checks that both lookups bind the cap, and it fails without it. Core unit suite: 6,426 tests pass. Typecheck, oxlint --type-aware --deny-warnings and repo-wide oxfmt --check are clean.
🤖 Generated with Claude Code
…term The sort only has to tell a few dozen assignments from thousands. An uncapped count read every assignment of a large term on each listing filtered by two or more taxonomies. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01RktNvhjty22ohh1GSHXGMq
There was a problem hiding this comment.
The approach remains sound: bounded selectivity estimates inside the existing term lookups address the reported query-cost problem without adding round trips.
Reviewed the follow-up SQL change, its callers and supporting index, and the added regression assertion. The count is now capped per term, and the derived table has the alias required by PostgreSQL. The author's D1 measurements and SQLite/PostgreSQL verification reasonably address the remaining uncapped-count finding, including the acknowledged overhead versus an already well-ordered query. Earlier round-trip and regression-coverage concerns remain addressed.
No new issues found in the follow-up changes. Review was static; I did not run tests or independently reproduce the reported measurements.
Follow-up review by openai/gpt-6.1-sol, scoped to the changes since the last review.
|
Thanks a lot for sticking with this one, @eisenbruch, and for moving the count into the term lookup and capping it so quickly. I had opened #4643 for the same issue without noticing this PR, sorry about that; I've closed mine in favor of yours. Two small things, neither blocking (they came up in @danielmlr's review of #4643 and apply here as well):
|
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01RktNvhjty22ohh1GSHXGMq
|
Thanks @swissky. Both are done in
The loader workerd tests pass (3 files, 17 tests). Typecheck, @ascorbic, the extra round trip you asked to remove is gone since 🤖 Generated with Claude Code |
There was a problem hiding this comment.
The approach remains sound: bounded selectivity estimates in existing lookups address the query-cost problem without extra round trips. The follow-up adds useful D1 rows-read regression coverage for both key orders and makes the changeset identify the affected public API and query shape.
Reviewed those follow-up changes and their supporting loader, D1 adapter, and test configuration. Earlier performance concerns remain reasonably addressed by the author's response; no new functional defects found. One small comment-convention violation remains below.
Review was static; I did not run tests or independently reproduce the D1 measurements.
Follow-up review by openai/gpt-6.1-sol, scoped to the changes since the last review.
|
|
||
| /** | ||
| * With two taxonomy filters, the listing walks one taxonomy's pivot rows and | ||
| * checks the other per row. It must start from the smaller one whichever key |
There was a problem hiding this comment.
[needs fixing] Remove the issue reference from this new code comment. AGENTS.md explicitly prohibits issue/PR references in comments; the invariant is understandable without historical context, which belongs in the commit message or PR description.
| * checks the other per row. It must start from the smaller one whichever key | |
| * the caller writes first, which is visible only in the rows D1 reads. |
ascorbic
left a comment
There was a problem hiding this comment.
Thanks! I think this is ready to go
What does this PR do?
buildTaxonomyPivotQuerywalksgroupSets[0]throughcontent_taxonomiesand checks every other set with a correlatedEXISTSper candidate row.groupSetsfollowed the caller'swherekey order, so the rows read depended on how the object was written: the same listings query read 3,131 rows as{ business_type, places }and 539 as{ places, business_type }(D1meta.rows_read, #3259).With two or more taxonomy filters, the resolved term groups are now counted in
content_taxonomies (collection, taxonomy_id)(an index-only read per set) and sorted ascending, so the most selective taxonomy drives. One taxonomy is untouched. Results are identical; only the plan changes.The second half of #3259 (any field filter abandons the pivot path) is the documented limitation in the comment above this branch and is not changed here.
Tests: a new key-order test (many posts in the category, one with the tag) asserts both orders return the same ids; the existing two-taxonomy tests still pass.
Refs #3259.
Type of change
Checklist
pnpm typecheckpasses (core)pnpm lintpassespnpm testpasses (loader-taxonomy-filter.test.tsandloader-field-filters.test.ts, 23 of 23)pnpm formathas been runAI-generated code disclosure
Screenshots / test output