Skip to content

fix(taxonomies): count only publicly visible entries in term counts - #1892

Merged
ascorbic merged 3 commits into
mainfrom
fix/taxonomy-term-counts-581
Jul 9, 2026
Merged

ascorbic merged 3 commits into
mainfrom
fix/taxonomy-term-counts-581

Conversation

@ascorbic

@ascorbic ascorbic commented Jul 9, 2026 •

Copy link
Copy Markdown
Member

What does this PR do?

Term usage counts aggregated the content_taxonomies pivot 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 (fetchVisibleTermCounts in taxonomies/term-counts.ts) that counts only entries currently visible on the public site:

  • Visibility is computed, not literal: buildStatusCondition (moved to database/dialect-helpers.ts and reused) treats published OR (scheduled AND due) as visible, plus an explicit deleted_at IS NULL. Scheduled-and-due entries are counted; scheduled-future ones are not.
  • No N+1 on the hot path: per-collection counts are combined into a single round-trip with UNION ALL across 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).
  • Scoped correctly: counts are keyed by translation_group (locale-independent, one count per entry row across locales), scoped to the taxonomy via translation_group IN (...) (robust to a deleted anchor row), and limited to the def's declared collections. Missing ec_* tables (pre-migration drift) fall back to a per-collection loop, yielding a partial-but-correct count instead of a throw.
  • Cache invalidation: object-cache entries that embed counts now also key on each counted collection's content namespace, so publishing/unpublishing/trashing an entry invalidates cached counts promptly.
  • Admin: handleTermList/handleTermGet use 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 clean main.

Closes #581

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) — full core suite on SQLite and Postgres
  • 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 strings changed
  • I have added a changeset (if this PR changes a published package)
  • New features link to an approved Discussion: n/a (bug fix)

AI-generated code disclosure

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

Screenshots / test output

New describeEachDialect suite (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_PG set (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.

…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.
Copilot AI review requested due to automatic review settings July 9, 2026 12:28
@changeset-bot

changeset-bot Bot commented Jul 9, 2026 •

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 234bb9f

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

This PR includes changesets to release 16 packages
Name Type
emdash Patch
@emdash-cms/cloudflare Patch
@emdash-cms/sandbox-workerd Patch
@emdash-cms/fixture-perf-site Patch
@emdash-cms/perf-demo-site Patch
@emdash-cms/cache-demo-site Patch
@emdash-cms/do-demo-site Patch
@emdash-cms/do-solo-demo-site Patch
@emdash-cms/admin Patch
@emdash-cms/auth Patch
@emdash-cms/blocks Patch
@emdash-cms/gutenberg-to-portable-text Patch
@emdash-cms/x402 Patch
create-emdash 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

@cloudflare-workers-and-pages

cloudflare-workers-and-pages Bot commented Jul 9, 2026 •

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
emdash-playground 234bb9f Jul 09 2026, 02:05 PM

@cloudflare-workers-and-pages

cloudflare-workers-and-pages Bot commented Jul 9, 2026 •

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
emdash-demo-cache 234bb9f Jul 09 2026, 02:06 PM

@cloudflare-workers-and-pages

cloudflare-workers-and-pages Bot commented Jul 9, 2026 •

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
emdash-demo-do 234bb9f Jul 09 2026, 02:06 PM

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

Copilot AI 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.

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 fetchVisibleTermCounts helper (UNION ALL per declared collection) and switches public + admin count paths to use it.
  • Moves buildStatusCondition into database/dialect-helpers.ts for 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.

Comment on lines +307 to +311
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);

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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

@github-actions github-actions Bot added the query-count changed PR diff modifies query-count snapshot files label Jul 9, 2026
@github-actions

github-actions Bot commented Jul 9, 2026 •

Copy link
Copy Markdown
Contributor

Query-count snapshot changes

12 routes changed, total Δ +12 queries.

SQLite

Route Before After Δ
GET /category/development (cold) 10 11 +1
GET /category/development (warm) 9 10 +1
GET /posts/building-for-the-long-term (cold) 17 18 +1
GET /posts/building-for-the-long-term (warm) 17 18 +1
GET /tag/webdev (cold) 9 10 +1
GET /tag/webdev (warm) 9 10 +1

D1

Route Before After Δ
GET /category/development (cold) 21 22 +1
GET /category/development (warm) 9 10 +1
GET /posts/building-for-the-long-term (cold) 28 29 +1
GET /posts/building-for-the-long-term (warm) 17 18 +1
GET /tag/webdev (cold) 21 22 +1
GET /tag/webdev (warm) 9 10 +1

Comparing snapshot files between base and head. Updated automatically on each push.

@github-actions

github-actions Bot commented Jul 9, 2026

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.

@github-actions github-actions Bot added review/approved Approved; no new commits since cla: signed labels Jul 9, 2026
@github-actions github-actions Bot added review/needs-rereview New commits since the last review area/core size/XL and removed review/approved Approved; no new commits since labels Jul 9, 2026
@pkg-pr-new

pkg-pr-new Bot commented Jul 9, 2026 •

Copy link
Copy Markdown

Open in StackBlitz

@emdash-cms/admin

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

@emdash-cms/auth

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

@emdash-cms/auth-atproto

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

@emdash-cms/blocks

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

@emdash-cms/cloudflare

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

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

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

emdash

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

create-emdash

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

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

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

@emdash-cms/plugin-cli

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

@emdash-cms/plugin-types

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

@emdash-cms/registry-client

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

@emdash-cms/registry-lexicons

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

@emdash-cms/sandbox-workerd

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

@emdash-cms/x402

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

@emdash-cms/plugin-ai-moderation

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

@emdash-cms/plugin-atproto

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

@emdash-cms/plugin-audit-log

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

@emdash-cms/plugin-color

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

@emdash-cms/plugin-embeds

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

@emdash-cms/plugin-field-kit

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

@emdash-cms/plugin-forms

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

@emdash-cms/plugin-webhook-notifier

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

commit: 234bb9f

@ascorbic

ascorbic commented Jul 9, 2026

Copy link
Copy Markdown
Member Author

/review

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

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.

Comment thread packages/core/src/taxonomies/index.ts Outdated
taxonomyName: string,
collections: string[],
): Promise<Map<string, number>> {
return requestCached(`taxonomy-term-counts:${taxonomyName}`, async () => {

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.

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.collections is a per-row column. Nothing in the schema or the create/update path forces translations of the same taxonomy to declare identical collections. If they drift (deliberately or by admin mistake), a page that resolves the def for two different locales in one request will get two different collections lists — whichever call runs first poisons the shared cache entry for the other.
  • Any future caller that passes a narrower collections list 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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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.

@ask-bonk

ask-bonk Bot commented Jul 9, 2026

Copy link
Copy Markdown
Contributor

Review posted successfully at #1892 (review).

Posted a single line-anchored comment as a nit:

  • packages/core/src/taxonomies/index.ts:309 — The requestCached key omits collections, which the result depends on. Fine today because both call sites derive collections from the same request-cached def lookup for one locale, but nothing in the schema forces translations of a def to share a collections list, so cross-locale renders (or future callers passing an explicit narrower list) can silently get counts scoped to the wrong collections. Cheap fix: fold the sorted, deduped collections into the key.

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 buildStatusCondition sub-second edge case is inherited and out of scope.

github run

… 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.
@github-actions github-actions Bot added review/needs-rereview New commits since the last review and removed review/approved Approved; no new commits since labels Jul 9, 2026
@ascorbic
ascorbic merged commit 9c0733f into main Jul 9, 2026
54 checks passed
@ascorbic
ascorbic deleted the fix/taxonomy-term-counts-581 branch July 9, 2026 15:00
@emdashbot emdashbot Bot mentioned this pull request Jul 9, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area/core cla: signed query-count changed PR diff modifies query-count snapshot files review/needs-rereview New commits since the last review size/XL

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Unpublished Posts are included in Category counts

2 participants