From a23a9862ccae90a77d7d6985683c7ec88e785a5a Mon Sep 17 00:00:00 2001 From: Matt Date: Mon, 11 May 2026 11:10:47 +0200 Subject: [PATCH] docs(documents): clarify ensureSystemRoots safety invariants MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Adds inline comments explaining (a) why no-target onConflictDoNothing is safe for root inserts (the only unique index that can fire on a root row is uniq_document_folders_sibling_name; the partial entity index excludes entity_id=NULL rows) and (b) why createPort doesn't wrap the root bootstrap in a transaction (ensureSystemRoots is re- runnable; the backfill script heals orphaned ports). Surfaces the assumption that Task 3 (ensureEntityFolder) must not blindly copy this pattern — it inserts with entity_id NOT NULL and needs an explicit conflict target. Co-Authored-By: Claude Opus 4.7 (1M context) --- src/lib/services/document-folders.service.ts | 6 ++++++ src/lib/services/ports.service.ts | 2 ++ 2 files changed, 8 insertions(+) diff --git a/src/lib/services/document-folders.service.ts b/src/lib/services/document-folders.service.ts index 46ca9541..abee0846 100644 --- a/src/lib/services/document-folders.service.ts +++ b/src/lib/services/document-folders.service.ts @@ -324,6 +324,12 @@ export async function ensureSystemRoots(portId: string, userId: string): Promise createdBy: userId, })); + // ON CONFLICT DO NOTHING with no target is safe here because root + // inserts can only collide on `uniq_document_folders_sibling_name` + // (entityId is null on roots, so the partial index + // `uniq_document_folders_entity` is excluded). Do not copy this + // pattern into helpers that insert per-entity subfolders — they + // need an explicit target to avoid masking real conflicts. await db.insert(documentFolders).values(values).onConflictDoNothing(); const rows = await db diff --git a/src/lib/services/ports.service.ts b/src/lib/services/ports.service.ts index 9dc837ea..0bab8542 100644 --- a/src/lib/services/ports.service.ts +++ b/src/lib/services/ports.service.ts @@ -41,6 +41,8 @@ export async function createPort(data: CreatePortInput, meta: AuditMeta) { }) .returning(); + // Non-fatal if this throws: ensureSystemRoots is re-runnable, and + // scripts/backfill-document-folders.ts heals orphaned ports. await ensureSystemRoots(port!.id, meta.userId); void createAuditLog({