Skip to content

fix(core): exclude unpublished entries from taxonomy counts - #593

Closed
maikunari wants to merge 2 commits into
emdash-cms:mainfrom
maikunari:fix/category-counts-unpublished
Closed

maikunari wants to merge 2 commits into
emdash-cms:mainfrom
maikunari:fix/category-counts-unpublished

Conversation

@maikunari

@maikunari maikunari commented Apr 16, 2026 •

Copy link
Copy Markdown
Contributor

Issue #581: Unpublished posts were included in category/tag counts, causing inaccurate public-facing sidebar counts.

Changes:

  • countEntriesWithTerm now defaults to status='published'
  • Added optional status parameter: 'all', 'published', 'draft', etc.
  • Uses raw SQL with sql.ref() and validateIdentifier for dynamic ec_{collection} table joins (Kysely type system limitation)
  • Updated existing test to reflect new default behavior
  • Added 4 new test cases covering all status filtering scenarios

What does this PR do?

Fixes #581 — unpublished posts were being counted in taxonomy term totals, inflating the public-facing category and tag counts shown in sidebars and archive pages.
Problem
TaxonomyRepository.countEntriesWithTerm counted all content_taxonomies rows matching a given taxonomy term, regardless of whether the linked entries were published. Draft, scheduled, and other non-published entries showed up in public counts, so a category labeled "12 posts" might only have 5 actually published.
Change

countEntriesWithTerm now defaults to status: 'published'
Added an optional status parameter accepting 'all', 'published', 'draft', etc.
Status-aware counting implemented via raw SQL joins against dynamic ec_{collection} content tables, with validateIdentifier for safety (Kysely's type system can't handle the dynamic table names)
Updated the existing test to reflect new default behavior
Added 4 new test cases covering the status filtering scenarios

Scope
Intentionally narrow. Default behavior change is the fix; the status parameter is additive for callers that need draft counts (admin UI, etc.).

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

AI-generated code disclosure

  • This PR includes AI-generated code

Screenshots / test output

Issue emdash-cms#581: Unpublished posts were included in category/tag counts,
causing inaccurate public-facing sidebar counts.

Changes:
- countEntriesWithTerm now defaults to status='published'
- Added optional status parameter: 'all', 'published', 'draft', etc.
- Uses raw SQL with sql.ref() and validateIdentifier for dynamic
  ec_{collection} table joins (Kysely type system limitation)
- Updated existing test to reflect new default behavior
- Added 4 new test cases covering all status filtering scenarios
@changeset-bot

changeset-bot Bot commented Apr 16, 2026 •

Copy link
Copy Markdown

⚠️ No Changeset found

Latest commit: 9101d46

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

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 incorrect public taxonomy term counts by excluding unpublished entries from counts by default, with an option to count entries across any status.

Changes:

  • Updated TaxonomyRepository.countEntriesWithTerm to default to counting only published entries and to support an 'all' mode or a specific status filter.
  • Implemented status-aware counting via raw SQL joins against dynamic ec_* content tables with identifier validation.
  • Updated and expanded unit tests to cover default behavior and status-filtering scenarios.

Reviewed changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated 2 comments.

File Description
packages/core/src/database/repositories/taxonomy.ts Changes taxonomy term counting to default to published-only and adds status filtering with dynamic ec_* joins.
packages/core/tests/unit/taxonomies/taxonomies.test.ts Updates existing test expectation and adds new test cases for status filtering behavior.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment on lines +308 to +309
WHERE ct.taxonomy_id = ${taxonomyId}
AND ${sql.ref(tableName)}.status = ${effectiveStatus}

Copilot AI Apr 16, 2026

Copy link

Choose a reason for hiding this comment

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

The status-filtered COUNT query doesn't exclude soft-deleted entries. Since ContentRepository.delete() only sets deleted_at (and this repo doesn't appear to clear content_taxonomies on delete), deleted-but-still-tagged entries will still be counted as long as their status matches. Add a ${sql.ref(tableName)}.deleted_at IS NULL predicate (and consider also adding ct.collection = ${collection} inside the loop to avoid scanning all content_taxonomies rows for the taxonomy on every per-collection count).

Suggested change
WHERE ct.taxonomy_id = ${taxonomyId}
AND ${sql.ref(tableName)}.status = ${effectiveStatus}
WHERE ct.taxonomy_id = ${taxonomyId}
AND ct.collection = ${collection}
AND ${sql.ref(tableName)}.status = ${effectiveStatus}
AND ${sql.ref(tableName)}.deleted_at IS NULL

Copilot uses AI. Check for mistakes.
Comment on lines +288 to +305
// For status filtering, we need raw SQL to join dynamic ec_* tables.
// Get distinct collections for this taxonomy term first.
const collections = await this.db
.selectFrom("content_taxonomies")
.select((eb) => eb.fn.count("entry_id").as("count"))
.select("collection")
.distinct()
.where("taxonomy_id", "=", taxonomyId)
.executeTakeFirst();
.execute();

if (collections.length === 0) return 0;

// Count entries matching status by joining each collection's content table
let totalCount = 0;
for (const { collection } of collections) {
const tableName = `ec_${collection}`;
validateIdentifier(tableName, "content table");
const result = await sql<{ count: number }>`
SELECT COUNT(ct.entry_id) AS count

Copilot AI Apr 16, 2026

Copy link

Choose a reason for hiding this comment

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

This implementation adds 1 query to fetch collections plus 1 COUNT query per collection, per taxonomy term. In handleTermList (api/handlers/taxonomies.ts) this method is called inside a loop over all terms, which can turn into hundreds/thousands of DB round-trips and be a noticeable regression. Consider building a single UNION ALL query across the relevant ec_* tables (similar to fetchRecentItems in api/handlers/dashboard.ts) or adding a bulk repo method that returns counts for many taxonomy IDs in one call so the handler can fetch all counts at once.

Copilot uses AI. Check for mistakes.

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.

@maikunari Copilot is right: this is still making an extra query per collection, which can really hit performance for us

@pkg-pr-new

pkg-pr-new Bot commented Apr 16, 2026 •

Copy link
Copy Markdown

Open in StackBlitz

@emdash-cms/admin

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

@emdash-cms/auth

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

@emdash-cms/blocks

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

@emdash-cms/cloudflare

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

emdash

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

create-emdash

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

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

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

@emdash-cms/x402

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

@emdash-cms/plugin-ai-moderation

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

@emdash-cms/plugin-atproto

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

@emdash-cms/plugin-audit-log

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

@emdash-cms/plugin-color

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

@emdash-cms/plugin-embeds

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

@emdash-cms/plugin-forms

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

@emdash-cms/plugin-webhook-notifier

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

commit: 9101d46

@ascorbic

ascorbic commented Apr 21, 2026 •

Copy link
Copy Markdown
Member

Thanks for tackling this @maikunari! Both Copilot comments are valid and worth addressing before merge.

  1. Soft-delete (line 309) – confirmed. ContentRepository.delete() is a soft delete and does not clear content_taxonomies rows, so trashed-but-still-tagged entries will leak into counts. Every other content query in the repo pairs status checks with deleted_at IS NULL — this one needs the same. Copilot's suggested predicates look right, including the ct.collection = ${collection} filter (avoids scanning all taxonomy rows per collection iteration).

  2. N+1 (line 305) – also real, and a concern given our query-count discipline. handleTermList calls this inside a loop over terms, so for a taxonomy with T terms across C collections we go from 1 query to T × (C + 1) queries. On a term list page with 50 tags across 3 collections that is 200 D1 round-trips where it used to be 50. The pnpm query-counts snapshot will likely flag this.

The UNION ALL pattern in fetchRecentItems (api/handlers/dashboard.ts:127) is a good template - or a bulk repo method countEntriesWithTerms(taxonomyIds: string[], status?) that handlers can batch with.

@maikunari

Copy link
Copy Markdown
Contributor Author

Thanks for the review @ascorbic

I've updated both production call sites (handleTermList() and handleTermGet() in packages/core/src/api/handlers/taxonomies.ts) to explicitly pass status: "published".

These are the endpoints that serve all taxonomy counts to the frontend (sidebars, tag clouds, term listings, etc.), so they were the main places affected by the default behavior change.

I searched the entire codebase — no other call sites were using countEntriesWithTerm().

The tests already cover all status variants thoroughly.

The update has been pushed to the branch.

@github-actions

Copy link
Copy Markdown
Contributor

This PR has been inactive for 14 days. It will be closed automatically in 7 days if there is no further activity.

If you're still working on this, please push an update or leave a comment.

@github-actions github-actions Bot added stale and removed stale labels May 20, 2026
@github-actions github-actions Bot added the review/awaiting-author Reviewed; waiting on the author to respond label May 30, 2026
@github-actions github-actions Bot added stale and removed stale labels Jun 13, 2026
@github-actions github-actions Bot added stale and removed stale labels Jun 27, 2026
@ascorbic

ascorbic commented Jul 9, 2026

Copy link
Copy Markdown
Member

Thanks for your work on this. There are currently several overlapping PRs that each manage part of this, but none of them manage the lot. I've found the simplest solution is to create a new PR inspired by all of them. For that reason I'm going to close this in favour of #1892

@ascorbic ascorbic closed this Jul 9, 2026
ascorbic added a commit that referenced this pull request Jul 9, 2026
…1892)

* fix(taxonomies): count only publicly visible entries in term counts (#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.

* ci: update query-count snapshots

* fix(taxonomies): include collection scope in term-count request-cache 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.

---------

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Unpublished Posts are included in Category counts

3 participants