Skip to content

fix(core): remove taxonomy assignments when content is permanently deleted - #3091

Merged
ascorbic merged 2 commits into
emdash-cms:mainfrom
danielmlr:fix/permanent-delete-taxonomy-assignments
Sep 13, 2026
Merged

fix(core): remove taxonomy assignments when content is permanently deleted#3091
ascorbic merged 2 commits into
emdash-cms:mainfrom
danielmlr:fix/permanent-delete-taxonomy-assignments

Conversation

@danielmlr

@danielmlr danielmlr commented Sep 13, 2026

Copy link
Copy Markdown
Contributor

What does this PR do?

Removes an entry's taxonomy assignments when its last translation is permanently deleted.

Assignments belong to the translation group rather than to a row, with no foreign key, and permanent delete never removed them, so they stayed in the database after the entry was gone. The handler now reads the row's group before the delete and removes the group's assignments once no row of it is left. A translation in the trash keeps them, since restoring it brings its terms back.

The check is the same row lookup and hasTranslationsIncludingTrashed helper that #1928 and #2799 add to this handler for reference edges. On D1 it runs after the delete without a transaction, like the SEO, comment and revision cleanup. On PostgreSQL, two overlapping permanent deletes of a group's last two translations each still see the other's row, so both keep the assignments, and a single DELETE … WHERE NOT EXISTS keeps them the same way. SQLite and D1 run one write at a time, so there the check after the second delete finds no row left. Assignments that earlier deletes left behind stay.

Part of #1683, the third gap in the audit.

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) (the full emdash suite)
  • 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). Do not include messages.po changes except in translation PRs — a workflow extracts catalogs on merge to main. (n/a: no admin UI change)
  • I have added and reviewed the user-facing changeset (if this PR changes a published package)
  • New features link to an approved Discussion: https://github.com/emdash-cms/emdash/discussions/... (n/a: bug fix)
  • I have included screenshots below if this PR changes the UI (n/a: no UI change)

AI-generated code disclosure

  • This PR includes AI-generated code — model/tool: Claude Opus 5

Screenshots / test output

Not applicable for screenshots. Against the unmodified handler, the two cases in permanent-delete-terms.test.ts that delete a group's last row fail, and the trash case passes:

 × handleContentPermanentDelete: term assignments [sqlite] > removes the assignments when the last translation is deleted
 × handleContentPermanentDelete: term assignments [sqlite] > keeps the assignments while another translation exists
 ✓ handleContentPermanentDelete: term assignments [sqlite] > keeps the assignments while another translation is in the trash
AssertionError: expected [ Array(1) ] to deeply equal []

With the change, all three pass on SQLite and PostgreSQL, and the full emdash suite passes on SQLite:

 Test Files  550 passed | 2 skipped (552)
      Tests  6716 passed | 10 skipped (6726)

Term assignments are keyed by the entry's translation group. Permanently
deleting an entry removes its row, SEO data, comments and revisions, but not
the assignments, so once the group's last row is gone nothing owns them.

Against the current handler, permanently deleting a post that has no
translations leaves its assignment behind, and so does deleting both
translations of a translated post. A third case pins that a translation in
the trash keeps the assignments, since restoring it brings its terms back.
…leted

Term assignments belong to the translation group rather than to a single
locale row, so the permanent-delete handler now removes them only when no
row of the group is left. A translation in the trash counts as left: it can
be restored, and its terms with it.

The removal takes the group directly instead of an entry id, because the
entry-id variant resolves the group through a row that no longer exists at
that point.
@changeset-bot

changeset-bot Bot commented Sep 13, 2026

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: f435c31

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

This PR includes changesets to release 18 packages
Name Type
emdash Patch
@emdash-cms/cloudflare Patch
@emdash-cms/plugin-test 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
create-emdash Patch
@emdash-cms/gutenberg-to-portable-text Patch
@emdash-cms/x402 Patch
@emdash-cms/auth-atproto Patch
@emdash-cms/release-service 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

@pkg-pr-new

pkg-pr-new Bot commented Sep 13, 2026

Copy link
Copy Markdown

Open in StackBlitz

@emdash-cms/admin

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

@emdash-cms/auth

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

@emdash-cms/auth-atproto

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

@emdash-cms/blocks

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

@emdash-cms/cloudflare

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

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

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

emdash

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

create-emdash

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

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

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

@emdash-cms/plugin-cli

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

@emdash-cms/plugin-test

npm i https://pkg.pr.new/emdash-cms/emdash/@emdash-cms/plugin-test@3091

@emdash-cms/plugin-types

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

@emdash-cms/registry-client

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

@emdash-cms/registry-lexicons

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

@emdash-cms/registry-moderation

npm i https://pkg.pr.new/emdash-cms/emdash/@emdash-cms/registry-moderation@3091

@emdash-cms/registry-verification

npm i https://pkg.pr.new/emdash-cms/emdash/@emdash-cms/registry-verification@3091

@emdash-cms/sandbox-workerd

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

@emdash-cms/x402

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

@emdash-cms/plugin-ai-moderation

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

@emdash-cms/plugin-atproto

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

@emdash-cms/plugin-audit-log

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

@emdash-cms/plugin-color

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

@emdash-cms/plugin-embeds

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

@emdash-cms/plugin-field-kit

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

@emdash-cms/plugin-forms

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

@emdash-cms/plugin-webhook-notifier

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

commit: f435c31

@danielmlr
danielmlr marked this pull request as ready for review September 13, 2026 02:06
@github-actions github-actions Bot added the review/needs-review No maintainer or bot review yet label Sep 13, 2026

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

Approach judgment: This is the right change. Permanent delete should remove translation-group–owned taxonomy assignments once the last content row of the group is gone, and keeping them while a trashed row remains matches the restore workflow. The implementation follows existing repository conventions, adds a focused regression test for the three cases (single translation, surviving translation, and trashed translation), and uses safe SQL (sql.ref for the identifier, parameterized value).

What I checked: diff, changed handler and repository files, existing permanent-delete.test.ts and content-taxonomies.test.ts, the transaction utility, AGENTS.md conventions, and the changeset.

Headline conclusion: The code is correct in the success path and the tests cover it. The main concern is that the cleanup is split across multiple statements and is not atomic on D1 (the production runtime), and the read-then-write pattern is also vulnerable to a TOCTOU race under the default READ COMMITTED isolation used by SQLite and PostgreSQL. I would address that before merging, or at least document the limitation, because the bug fix can still leave orphan assignments in concurrent or failure scenarios. I also note that no migration or backfill is provided for assignments already orphaned before this fix.

Changeset: purge-entry-term-assignments.md is a clear, user-facing patch entry that states the fixed behavior and when assignments are preserved. It meets the changeset README standard.

Comment on lines +1406 to +1415
// Term assignments are keyed by translation_group, so they belong to the
// group rather than to this row. They go only once no row of the group is
// left, trashed ones included, since a trashed row can still be restored.
if (item?.translationGroup) {
const groupSurvives = await trxRepo.hasTranslationsIncludingTrashed(
collection,
item.translationGroup,
);
if (!groupSurvives) {
await new TaxonomyRepository(trx).clearEntryGroupTerms(

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.

[suggestion] The cleanup block uses a read-then-write pattern: it deletes the content row, probes whether any group rows remain, and then deletes taxonomy assignments. This is wrapped in withTransaction, but packages/core/src/database/transaction.ts documents that D1 does not support transactions—the wrapper falls back to running the callback directly against the database, so multi-statement atomicity is lost on the production runtime. If the handler fails or the worker is evicted after the content row is deleted but before the assignment cleanup runs, the assignments stay orphaned, which partly undermines the fix.

Under the default READ COMMITTED isolation used by SQLite and PostgreSQL, the same pattern is also vulnerable to a TOCTOU race: two concurrent permanent deletes of the last two rows in a group can each see the other's row during the probe and both skip cleanup.

Consider making the assignment cleanup a single self-checking statement so the delete itself is atomic, e.g. by adding to TaxonomyRepository:

async clearEntryGroupTermsIfNoRowsRemain(
  collection: string,
  entryGroup: string,
): Promise<number> {
  validateIdentifier(collection, "collection type");
  const tableName = `ec_${collection}`;
  const result = await this.db
    .deleteFrom("content_taxonomies")
    .where("collection", "=", collection)
    .where("entry_id", "=", entryGroup)
    .where(({ not, exists }) =>
      not(
        exists(
          this.db
            .selectFrom(tableName as keyof Database)
            .select("id")
            .where("translation_group", "=", entryGroup),
        ),
      ),
    )
    .executeTakeFirst();
  const removed = Number(result.numDeletedRows ?? 0);
  if (removed > 0) invalidateTaxonomyObjectCache();
  return removed;
}

Then replace the probe-and-delete block with a single call to that method after permanentDelete. This does not close the crash-between-statements gap on D1 (only a future deferred cleanup can), but it removes the read-then-write race and makes the cleanup statement atomic. The same limitation also applies to the existing SEO/comment/revision cleanup in this handler, so fixing it comprehensively may belong in a follow-up.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I'm keeping the probe. I ran both cleanups as plain SQL against PostgreSQL with two connections: each deleted one of a group's last two translations, then ran its cleanup before either committed. Neither saw the other's uncommitted delete, so with the probe and DELETE … WHERE NOT EXISTS alike, the assignment stayed. Run in sequence, the second cleanup removes it in either case. SQLite lets one connection write at a time (a second connection's delete got database is locked), and D1 is single-writer, as withTransaction notes, so on both, the check after the second delete finds no row left. The D1 gap between statements is the lost multi-statement atomicity withTransaction calls a known D1 limitation, and the SEO, comment and revision cleanup here share it, so it's a question for the whole handler, not this PR. The description now states both limits, and that assignments orphaned before this change stay.

@github-actions github-actions Bot added review/awaiting-author Reviewed; waiting on the author to respond and removed review/needs-review No maintainer or bot review yet labels Sep 13, 2026

@ascorbic ascorbic left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Thanks!

@ascorbic
ascorbic merged commit ef22a2d into emdash-cms:main Sep 13, 2026
66 checks passed
@danielmlr
danielmlr deleted the fix/permanent-delete-taxonomy-assignments branch September 13, 2026 10:56
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area/core review/awaiting-author Reviewed; waiting on the author to respond size/M

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants