Repository navigation
fix(platform): purge corpus, blobs, and retrievability consistently - #3140
Merged
Merged
Conversation
The knowledge corpus is keyed by blob ref, so every lane that rotates or destroys a ref must de-index dead corpus rows and delete unreferenced bytes through ONE implementation. releaseRefs answers both liveness questions (corpus-live: some document's CURRENT file_ref or a live unbound file row; blob-live: any file_ref, history_files entry, or live file row), reports failures instead of swallowing them, and ships with the durable knowledge.release_refs job for rotation points plus the daily knowledge.reconcile_corpus sweep that heals historically stranded rows on existing deployments. Migration 0063 adds the GIN index the history containment probe needs.
purgeDocument used to warn-swallow corpus and blob delete failures and delete the app rows anyway — every hard-delete lane (user delete, folder cascade, REST, retention sweep, erasure cascade, sync prune) funnels here, so a GDPR erasure receipt could read done while the content kept answering RAG queries. It now releases every ref (current + history) through the shared refcounted seam FIRST and throws PurgeIncompleteError on failure, keeping the row so the daily sweep re-selects it, an erasure lands partial and can be re-armed, and a user sees the failure. The temp-file sweep gets the same contract (release before row delete, keep the row on failure — a swallowed blob failure used to leak the bytes forever), and the grace=0 documents pass now hard-deletes trashed and expired rows, which it previously never selected — a project-cascade's expired documents sat unpurged for good on no-grace orgs.
Controlled-record replacement never de-indexed the ref it rotated away, so the superseded approved content kept answering RAG queries as if current; the WebDAV PUT-overwrite deleted the old blob inside the transaction but stranded its corpus rows retrievable forever; the cloud sync update de-indexed best-effort and swallowed failures. All three now enqueue the durable knowledge.release_refs job transactionally with the rotation: the shared seam de-indexes the dead corpus rows and applies the refcount before touching bytes (a trashed COPY twin's blob now survives an overwrite of the live copy).
The knowledge_entries module comment claimed the corpus key survives a version rotation, but indexing keys the corpus by the blob ref the file row carries — every edit therefore stranded one unpurgeable corpus document and orphaned the previous blob. The rotate branch now captures the outgoing ref and enqueues the shared release job in the same transaction (de-index + delete bytes; nothing else references entry blobs), and the comment states the real contract. Entry mutations also gained the write-matrix gate the documents lanes got in the parallel write-matrix fix: entries materialize app.documents rows and feed the org RAG corpus, yet any org member (role member is read-only platform-wide) could create, edit, or delete them through the app and REST lanes. The service seam now requires the new knowledge write grant (editor and up), enforced for every caller.
filterRetrievableRagFileIds admitted whatever a file row remembered: a replaced version's history row kept the superseded ref retrievable, a trashed unbound row (the WebDAV overwrite strand) fell through the legacy fallback org-wide, and an expired document (a project-cascade mark) stayed retrievable because only 'trashed' was checked. The decision is now the pure decideRetrievable: a ref passes only through a document whose CURRENT file_ref it is with an ACTIVE lifecycle (scope per candidate document, so a WebDAV COPY twin admits through its own scope), or through a LIVE unbound file row (thread files in their thread's scope; document-less lanes like video-link transcripts keep the same-org posture — the one legitimate unbound producer). Trashed file rows and refs nothing holds are dark immediately, whatever the physical purge is still doing.
Seven scenarios against the real worker, corpus database, and object store: replacement de-indexes the superseded version (bytes retained as the snapshot); a knowledge-entry edit releases the rotated-away ref (corpus + blob); a purge that cannot reach the corpus keeps the document and answers failure, and a retry after recovery heals row + corpus + blob; a project cascade goes dark immediately and the grace=0 sweep hard-deletes it; a shared blob ref (the WebDAV COPY shape) survives its sibling's purge and keeps answering through its own scope until the last holder dies; the reconcile sweep de-indexes a seeded pre-fix strand; and knowledge-entry mutations refuse the member role on the app lane while reads keep working.
larryro
marked this pull request as ready for review
September 3, 2026 03:56
This was referenced Sep 3, 2026
Israeltheminer
added a commit
that referenced
this pull request
Sep 3, 2026
0.4 ran 19 eraseSubject arms; the 0.5 cascade runs 10 passes. Seven categories of subject data survived a request that reported done: - app.notifications, the ORG-level bells about the subject — a different table from the per-user inbox the notifications pass clears. subject_user_id was added for this and never read, and the lockout alert stamps it on the row carrying the subject's email and IP. - app.automation_runs they started, whose input, output, trace and effects hold every node's resolved values. - app.approvals and app.tasks.reviewer_user_id. The decision is KEPT and de-identified — it is the audit record of a governance gate — while the reviewer pointer is live routing and is cleared. - app.login_attempts and app.login_block_counters, keyed by email. - app.two_factor_attempts and app.two_factor_grace, keyed by user id. - app.user_cloud_authorizations and app.cloud_import_oauth_states, the subject's sealed OAuth grant for Documents import. - app.onedrive_sync_configs and app.google_drive_sync_configs, which name the member whose grant the sync runs under. - app.video_link_jobs, which can own a blob even when the linked file_metadata row never landed. The auth tables are global rather than org-scoped, so they are refused while the subject is still an active member elsewhere: those counters protect those organizations too, and wiping them on one org's request hands a multi-org user a lockout bypass. 0.4 paged Better Auth at a 256-membership cap and failed closed on truncation; SQL answers exactly. Video-link blobs delete strictly, following the uploads pass #3140 landed rather than the retention sweeps' best-effort idiom: a receipt that says done is a claim about the bytes. Refs #3120.
This was referenced Sep 3, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
fix(platform): corpus purge consistency — deleted means gone
The invariant
The knowledge corpus is keyed by blob ref, so content lives in up to three places — corpus rows,
bytes, app rows — and this PR makes one rule hold everywhere: every ref a document ever exposed
to the corpus is de-indexed the moment it stops being current (or the document dies), bytes are
deleted exactly when the last reference goes, the retrievable set follows lifecycle truth
immediately, and no purge lane reports success it did not achieve. One shared implementation per
concept:
releaseRefs(refcounted corpus de-index + blob delete, failures reported, indomains/knowledge/release.ts), the durableknowledge.release_refsjob for rotation points, thepure
decideRetrievablepredicate for the RAG filter, and the dailyknowledge.reconcile_corpussweep as backstop-and-backfill.
Per-finding outcome
bindReplacementenqueuesknowledge.release_refsfor the rotated-away ref in the bind transaction; the retrievable filter also refuses non-current refs immediately (a history file row no longer admits its ref)purgeDocumentnow releases current +historyFilesrefs through the shared seam; all rotation points (replacement, knowledge entries, WebDAV PUT-overwrite, cloud-sync update) funnel into the same jobstorage_ref, so it does notpurgeDocumentreleases refs FIRST and throwsPurgeIncompleteErroron failure — the row is kept so retention re-selects it daily, erasure landspartial(operator can re-arm), a user sees the failure.deleteBlobBestEffortassessed: no sweep reconciled it — a swallowed failure after row deletion was an unrecoverable leak; it is removed, and the temp-file sweep now also releases-before-delete and keeps the row on failureexpiredrows (claim held there), but (a) the retrievable filter admittedexpireddocs, and (b) the grace=0 pass never selectedtrashed/expiredrows at all — on no-grace orgs the promised hard-delete never rantrashed/expiredrows (mirroring the contacts sweep); cascade comment updated to the true storyfile_ref/history_files/live file row holds the ref; corpus rows live while any document's CURRENT ref (any lifecycle — trash is restorable) or live unbound file row holds it. WebDAV's ownpurgeOldBlobnow delegates to the job (no more network I/O inside its transaction; a trashed twin's bytes survive an overwrite of the live copy)expireddocs. The unbound-fallback audit found ONE legitimate producer — video-link transcripts index withdocument_id NULL— so live unbound rows keep the 0.4 same-org posture; trashed rows and row-less refs are darkdecideRetrievable(pure, unit-tested): current-ref + active-lifecycle + per-candidate scope for documents; thread scope for thread files; live unbound retainedretrievable.test.ts(12 cases incl. twins/lifecycle matrix) + every itest scenario above exercises the filterauthorizeRls(role, 'knowledge', 'write')at the service seam (create/update/delete), enforced for app routes and REST; newknowledgesubject in the access matrix (editor+ write, member read, disabled none) — mirrors unmerged #3136's idiom for documents, implemented against main's own rls helpersaccess.test.tsRefuted: none — all eight findings verified in code; #5 and #7 landed narrower than filed (detailed above).
The lane sweep (every purge/rotation lane, one seam)
sweepDocuments)purgeDocument; per-doc catch keeps the sweep alive; grace=0 selects trashed/expireddeleteDocumentHard,deleteFolderCascade)DELETE /v1/documents/:idpartial, operator re-arm retries (mirrors #3135's uploads-pass honesty contract)knowledge.release_refsjobbindReplacement)attachEntryDocument)purgeOldBlob)sweepTempFiles)deleteWebdavBlob)knowledge.reconcile_corpus)Migration
0063_documents_history_files_gin.sql— GIN index overdocuments.history_filesfor thehistory-containment probe (
@>) both liveness predicates use. Forward-only, rolling-safe(IF NOT EXISTS, plain CREATE INDEX). The stranded-row backfill is deliberately NOT a migration:
the reconcile sweep drains it incrementally.
Gates (observed)
retrievable.test.ts+access.test.ts— 2 files / 12 tests passed; full platform suite 374 files / 72287 tests passed, exit 0access.test.ts3/3 assertions red (noknowledgegrant),retrievable.test.tsfails to load (module absent)backend:integrationon a throwaway tale-db + MinIO:oldCorpusGone=false, oldFetchDark=false; entry editv1Released=false; honestybrokenDelete → 200, rowKept=false, corpusKept=true(success reported, corpus content left behind unrecoverably); cascadesweepDocs=0, rowGone=false; twinscorpusKept=false, blobKept=false, twinAnswers=false; reconcilereconcileRan=false; role gatecreate → 201, update → 200, delete → 200Cross-class notes
uploadspass still deletes file rows without blob release — sibling PR fix(platform): enforce the GDPR erasure governance gates #3135'sterritory (unmerged), untouched here to avoid collision;
purgeDocument's honesty covers thedocuments pass either way.
deleteKnowledgeDocumentsBatchcompletes a pre-existing type-only vestige incore/legacy/knowledge_delete.ts(the batch types existed with no implementation).