Repository navigation
fix(taxonomies): count only publicly visible entries in term counts - #1892
Conversation
…581) Term usage counts aggregated the content_taxonomies pivot directly, so drafts, scheduled-future, and trashed entries inflated the counts shown in the Categories/Tags widgets, on term pages, and in the admin term list. All three paths now share a single UNION ALL count query that joins the content tables, filters with buildStatusCondition (published or scheduled-and-due) and deleted_at IS NULL, and scopes to the taxonomy's declared collections. Consolidates the fixes proposed in #1839, #822, and #593.
🦋 Changeset detectedLatest commit: 234bb9f 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 |
Deploying with
|
| Status | Name | Latest Commit | Updated (UTC) |
|---|---|---|---|
| ✅ Deployment successful! View logs |
emdash-playground | 234bb9f | Jul 09 2026, 02:05 PM |
Deploying with
|
| Status | Name | Latest Commit | Updated (UTC) |
|---|---|---|---|
| ✅ Deployment successful! View logs |
emdash-demo-cache | 234bb9f | Jul 09 2026, 02:06 PM |
Deploying with
|
| Status | Name | Latest Commit | Updated (UTC) |
|---|---|---|---|
| ✅ Deployment successful! View logs |
emdash-demo-do | 234bb9f | Jul 09 2026, 02:06 PM |
There was a problem hiding this comment.
This is a well-scoped bug fix for #581. The approach is sound: centralize visible-term counting in one helper, compute visibility using the same buildStatusCondition logic that drives public content queries, scope counts to the taxonomy's declared collections, and cache/invalidate correctly via content namespaces. The change fits EmDash's architecture (handler layer, repository layer, request cache, object-cache epochs) and is well documented.
I read the new helper, the wiring in taxonomies/index.ts and api/handlers/taxonomies.ts, the moved buildStatusCondition, the repository docstrings, the updated tests, and the query-count snapshot diff. The SQL is safe: dynamic table identifiers are validated and passed through sql.ref; taxonomyName is parameterized; there is no raw interpolation. Cache keys and namespaces are coherent: term/widget/term-detail results now live under [content:<collection>, ..., "taxonomies"] so publishing, unpublishing, trashing, and taxonomy assignment writes all invalidate visible counts. The new describeEachDialect test suite covers the visibility matrix, multi-collection aggregation, cross-taxonomy isolation, translation groups, missing tables, and empty declared collections. The SQLite query-count snapshots were updated and the trade-off (+1 query per rendered taxonomy) is intentional and bounded.
No blocking issues. One inherited edge case worth noting: buildStatusCondition's SQLite branch compares scheduled_at against strftime('%Y-%m-%dT%H:%M:%fZ', 'now') (millisecond precision). If scheduled_at was stored without fractional seconds (e.g. a UI picker producing 2026-07-09T08:00:00Z), lexicographic comparison treats it as greater than ...:00.000Z and the entry stays non-visible for up to a second past its scheduled time. This bug predates this PR, and this PR does not make it worse, but because term counts now share the same visibility logic it affects them too.
Overall: clean fix, good tests, correct cache invalidation. LGTM.
There was a problem hiding this comment.
Pull request overview
Fixes taxonomy term usage counts so they reflect only publicly visible content (published or scheduled-and-due, excluding soft-deleted), instead of counting raw content_taxonomies pivot rows that include drafts/scheduled-future/trashed content.
Changes:
- Introduces a shared
fetchVisibleTermCountshelper (UNION ALL per declared collection) and switches public + admin count paths to use it. - Moves
buildStatusConditionintodatabase/dialect-helpers.tsfor reuse and applies it to term counting logic. - Adds a new cross-dialect unit test suite for term-count semantics and updates query-count snapshots/expectations.
Reviewed changes
Copilot reviewed 11 out of 11 changed files in this pull request and generated 1 comment.
Show a summary per file
| File | Description |
|---|---|
| scripts/query-counts.snapshot.sqlite.json | Updates expected query counts for affected routes after count logic changes. |
| scripts/query-counts.queries.sqlite.json | Records the new SQL shape for visible term counting and the added taxonomy-def lookup. |
| packages/core/tests/unit/taxonomies/term-counts.test.ts | New describeEachDialect coverage for visible-term-count behavior across all count consumers. |
| packages/core/tests/unit/taxonomies/get-term.test.ts | Updates test setup and query-count expectation to account for taxonomy-def lookup and visible counting. |
| packages/core/src/taxonomies/term-counts.ts | Adds the shared visible-term-count query helper (status-aware + deleted-aware, per declared collections). |
| packages/core/src/taxonomies/index.ts | Switches runtime taxonomy term list/get to visible counts and adjusts caching namespaces. |
| packages/core/src/loader.ts | Removes the local buildStatusCondition implementation in favor of the shared helper. |
| packages/core/src/database/repositories/taxonomy.ts | Documents that repository “raw” counters include all statuses, and points callers to the visible-count helper. |
| packages/core/src/database/dialect-helpers.ts | Exports buildStatusCondition for reuse across status-aware queries. |
| packages/core/src/api/handlers/taxonomies.ts | Updates admin term list/get to use the shared visible-count helper and def collection scope. |
| .changeset/taxonomy-term-counts-visible-only.md | Adds a patch changeset describing the user-visible fix. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| collections: string[], | ||
| ): Promise<Map<string, number>> { | ||
| return requestCached(`taxonomy-term-counts:${taxonomyName}`, async () => { | ||
| const db = await getDb(); | ||
| const countsResult = await db | ||
| .selectFrom("content_taxonomies") | ||
| .select(["taxonomy_id"]) | ||
| .select((eb) => eb.fn.count<number>("entry_id").as("count")) | ||
| .groupBy("taxonomy_id") | ||
| .execute(); | ||
| const counts = new Map<string, number>(); | ||
| for (const row of countsResult) counts.set(row.taxonomy_id, row.count); | ||
| return counts; | ||
| return fetchVisibleTermCounts(db, taxonomyName, collections); |
There was a problem hiding this comment.
Confirmed and fixed in 234bb9f — the request-cache key now includes the sorted, deduped collection scope. Regression test added (per-locale defs drifting in declared collections, both rendered in one request).
Query-count snapshot changes12 routes changed, total Δ +12 queries. SQLite
D1
Comparing snapshot files between base and head. Updated automatically on each push. |
Overlapping PRsThis PR modifies files that are also changed by other open PRs:
This may cause merge conflicts or duplicated work. A maintainer will coordinate. |
@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: |
|
/review |
There was a problem hiding this comment.
Focused on the count semantics, the shared helper, cache invalidation, and the request-cache wiring. One nit on a subtly-scoped cache key that is fine in practice today but easy to trip on later.
SQL is safe (identifiers validated, values parameterized). The UNION ALL shape is right, the translation_group IN (SELECT translation_group ...) scoping correctly handles a deleted anchor row, the missing-table fallback yields partial counts rather than throwing, and the object-cache namespaces now include each counted collection so publish/unpublish/trash invalidates the embedded count. The new describeEachDialect suite covers the visibility matrix, cross-taxonomy isolation, translation-group keying, and drift. The scheduled-and-due lexicographic comparison edge case in buildStatusCondition is pre-existing and out of scope here.
| taxonomyName: string, | ||
| collections: string[], | ||
| ): Promise<Map<string, number>> { | ||
| return requestCached(`taxonomy-term-counts:${taxonomyName}`, async () => { |
There was a problem hiding this comment.
Nit / latent correctness. The requestCached key is taxonomy-term-counts:${taxonomyName}, but the result is scoped by collections. Today's two call sites (loadTaxonomyTerms, loadTerm) both derive collections from getTaxonomyDef(taxonomyName, options), and getTaxonomyDef is itself request-cached per resolved locale — so within a normal single-locale render the collections list is stable and the shared cache entry is correct.
What makes this fragile:
_emdash_taxonomy_defs.collectionsis a per-row column. Nothing in the schema or the create/update path forces translations of the same taxonomy to declare identicalcollections. If they drift (deliberately or by admin mistake), a page that resolves the def for two different locales in one request will get two differentcollectionslists — whichever call runs first poisons the shared cache entry for the other.- Any future caller that passes a narrower
collectionslist explicitly (e.g. scoping a widget to one collection) will hit the same footgun without any warning.
Cheapest fix: fold the (deduped, sorted) collections into the key, e.g. `taxonomy-term-counts:${taxonomyName}:${[...new Set(collections)].sort().join(',')}`. That preserves the sharing between the widget and the term page on the hot path (identical inputs → same key) and stops the two call sites from silently disagreeing when they don't.
Not a merge blocker — it just quietly relies on a coincidence that isn't enforced by the data model.
There was a problem hiding this comment.
Legit — and it violated the repo's own request-cache rule (key must include every argument that changes the result). Fixed in 234bb9f: the key now folds in the sorted, deduped collection scope, so identical inputs (the widget + term-page hot path) still share one entry while drifted per-locale defs or a narrower explicit scope get their own. Added a failing-first regression test covering the two-locale drift case.
|
Review posted successfully at #1892 (review). Posted a single line-anchored comment as a nit:
The overall verdict in the review body: clean, well-tested fix; SQL is parameterized/validated; cache namespaces correctly invalidate on publish/unpublish/trash; the pre-existing |
… key Per-locale rows of the same taxonomy def can drift in their declared collections, and a future caller may pass a narrower scope; keying the request cache by taxonomy name alone let the first scope poison the entry for the rest of the request. Raised by review on #1892.
What does this PR do?
Term usage counts aggregated the
content_taxonomiespivot directly, with no join to the content tables. Pivot rows are written for every entry regardless of status and are never pruned on unpublish/trash, so drafts, scheduled-future, and soft-deleted entries inflated the counts users see — in the public Categories/Tags widgets, on single-term pages, and in the admin term list.All three count paths now share one helper (
fetchVisibleTermCountsintaxonomies/term-counts.ts) that counts only entries currently visible on the public site:buildStatusCondition(moved todatabase/dialect-helpers.tsand reused) treatspublishedOR (scheduledAND due) as visible, plus an explicitdeleted_at IS NULL. Scheduled-and-due entries are counted; scheduled-future ones are not.UNION ALLacross the taxonomy's declared collections — one query per taxonomy, not per collection. The map is request-cached, so a page rendering both the widget and a term detail shares one computation (the term page is a Map lookup).translation_group(locale-independent, one count per entry row across locales), scoped to the taxonomy viatranslation_group IN (...)(robust to a deleted anchor row), and limited to the def's declared collections. Missingec_*tables (pre-migration drift) fall back to a per-collection loop, yielding a partial-but-correct count instead of a throw.handleTermList/handleTermGetuse the same helper (public semantics). The raw repository counters remain, documented as counting all statuses.Consolidates the competing partial fixes: query shape inspired by #822, scheduled-aware status logic from #1839, admin path from #593.
Query-count snapshots (sqlite) updated:
/category,/tag, and/posts/[slug]each gain one query (the def lookup for collection scope / one count per taxonomy instead of a shared pivot-wide aggregate). The d1 snapshot needs the CI auto-update — the local d1 harness fails on cleanmain.Closes #581
Type of change
Checklist
pnpm typecheckpassespnpm lintpassespnpm testpasses (or targeted tests for my change) — full core suite on SQLite and Postgrespnpm formathas been runAI-generated code disclosure
Screenshots / test output
New
describeEachDialectsuite (tests/unit/taxonomies/term-counts.test.ts) covers: draft/scheduled-future/soft-deleted excluded and scheduled-and-due included on all three paths; multi-collection aggregation; cross-taxonomy isolation; cross-locale translation groups; missing-table partial counts; empty declared collections.Full suite: 339 files / 4822 tests green with
EMDASH_TEST_PGset (SQLite + Postgres).Verified end-to-end on the perf fixture: the Categories widget count went 4 → 3 after drafting a post, → 2 after soft-deleting another, dropped when a post was scheduled in the future, and recovered when the schedule passed.
Try this PR
Open a fresh playground →
A full working EmDash site, deployed from this branch. Each visit gets its own session-scoped sandbox: no login needed and no shared state. Try the admin, edit content, hit the public site.
Tracks
fix/taxonomy-term-counts-581. Updated automatically when the playground redeploys.