Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/purge-entry-term-assignments.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"emdash": patch
---

Fixes permanently deleting an entry leaving its taxonomy term assignments in the database. The assignments are removed with the last translation of the entry and kept while another translation exists, including one in the trash.
16 changes: 16 additions & 0 deletions packages/core/src/api/handlers/content.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1389,6 +1389,7 @@ export async function handleContentPermanentDelete(
// Wrap content delete + SEO/comment cleanup in a transaction
const deleted = await withTransaction(db, async (trx) => {
const trxRepo = new ContentRepository(trx);
const item = await trxRepo.findByIdIncludingTrashed(collection, resolvedId);
const wasDeleted = await trxRepo.permanentDelete(collection, resolvedId);

if (wasDeleted) {
Expand All @@ -1402,6 +1403,21 @@ export async function handleContentPermanentDelete(
const revisionRepo = new RevisionRepository(trx);
await revisionRepo.deleteByEntry(collection, resolvedId);
await new EntryLockRepository(trx).releaseEntry(collection, resolvedId);
// 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(
Comment on lines +1406 to +1415

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.

collection,
item.translationGroup,
);
}
}
}

return wasDeleted;
Expand Down
13 changes: 13 additions & 0 deletions packages/core/src/database/repositories/content.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1665,6 +1665,19 @@ export class ContentRepository {
return result.rows.map((row) => this.mapRow(type, row));
}

/** Whether any row of `translationGroup` exists, trashed rows included. */
async hasTranslationsIncludingTrashed(type: string, translationGroup: string): Promise<boolean> {
const tableName = getTableName(type);

const result = await sql<Record<string, unknown>>`
SELECT id FROM ${sql.ref(tableName)}
WHERE translation_group = ${translationGroup}
LIMIT 1
`.execute(this.db);

return result.rows.length > 0;
}

/**
* Batch variant of {@link findTranslations}: every (non-deleted) locale
* variant for any of `translationGroups`, in one `WHERE translation_group IN
Expand Down
8 changes: 8 additions & 0 deletions packages/core/src/database/repositories/taxonomy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -749,7 +749,15 @@ export class TaxonomyRepository {
async clearEntryTerms(collection: string, entryId: string): Promise<number> {
const entryGroup = await this.resolveEntryTranslationGroup(collection, entryId);
if (!entryGroup) return 0;
return this.clearEntryGroupTerms(collection, entryGroup);
}

/**
* Remove every term assignment held by an entry translation group. Takes the
* group rather than an entry id, so it still works after the group's last
* row has been deleted.
*/
async clearEntryGroupTerms(collection: string, entryGroup: string): Promise<number> {
const result = await this.db
.deleteFrom("content_taxonomies")
.where("collection", "=", collection)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
/**
* Term assignments belong to the translation group, so permanent delete
* removes them only with the group's last row, trashed rows included.
*/

import { afterEach, beforeEach, expect, it } from "vitest";

import { handleContentPermanentDelete } from "../../../src/api/handlers/content.js";
import { ContentRepository } from "../../../src/database/repositories/content.js";
import { TaxonomyRepository } from "../../../src/database/repositories/taxonomy.js";
import {
describeEachDialect,
setupForDialectWithCollections,
teardownForDialect,
type DialectTestContext,
} from "../../utils/test-db.js";

describeEachDialect("handleContentPermanentDelete: term assignments", (dialect) => {
let ctx: DialectTestContext;
let content: ContentRepository;
let taxonomies: TaxonomyRepository;
let termId: string;

beforeEach(async () => {
ctx = await setupForDialectWithCollections(dialect);
content = new ContentRepository(ctx.db);
taxonomies = new TaxonomyRepository(ctx.db);
const term = await taxonomies.create({ name: "tag", slug: "news", label: "News" });
termId = term.id;
});

afterEach(async () => {
await teardownForDialect(ctx);
});

async function assignmentsFor(group: string) {
return ctx.db
.selectFrom("content_taxonomies")
.select("taxonomy_id")
.where("collection", "=", "post")
.where("entry_id", "=", group)
.execute();
}

async function trashAndPurge(id: string) {
expect(await content.delete("post", id)).toBe(true);
const result = await handleContentPermanentDelete(ctx.db, "post", id);
expect(result.success).toBe(true);
}

async function createTranslatedPost() {
const en = await content.create({ type: "post", locale: "en", data: { title: "Hello" } });
const de = await content.create({
type: "post",
locale: "de",
translationOf: en.id,
data: { title: "Hallo" },
});
await taxonomies.attachToEntry("post", en.id, termId);
return { en, de, group: en.translationGroup! };
}

it("removes the assignments when the last translation is deleted", async () => {
const post = await content.create({ type: "post", data: { title: "Only" } });
await taxonomies.attachToEntry("post", post.id, termId);
expect(await assignmentsFor(post.translationGroup!)).toHaveLength(1);

await trashAndPurge(post.id);

expect(await assignmentsFor(post.translationGroup!)).toEqual([]);
});

it("keeps the assignments while another translation exists", async () => {
const { en, de, group } = await createTranslatedPost();

await trashAndPurge(en.id);
expect(await assignmentsFor(group)).toHaveLength(1);

await trashAndPurge(de.id);
expect(await assignmentsFor(group)).toEqual([]);
});

it("keeps the assignments while another translation is in the trash", async () => {
const { en, de, group } = await createTranslatedPost();
expect(await content.delete("post", de.id)).toBe(true);

await trashAndPurge(en.id);

expect(await assignmentsFor(group)).toHaveLength(1);
});
});
Loading