Skip to content

fix(platform): purge corpus, blobs, and retrievability consistently - #3140

Merged
larryro merged 6 commits into
mainfrom
fix/corpus-purge-consistency
Sep 3, 2026
Merged

larryro merged 6 commits into
mainfrom
fix/corpus-purge-consistency

Conversation

@larryro

@larryro larryro commented Sep 2, 2026

Copy link
Copy Markdown
Contributor

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, in
domains/knowledge/release.ts), the durable knowledge.release_refs job for rotation points, the
pure decideRetrievable predicate for the RAG filter, and the daily knowledge.reconcile_corpus
sweep as backstop-and-backfill.

Per-finding outcome

# Finding Verdict Fix Proof
1 Replaced document versions stay retrievable in RAG forever confirmed bindReplacement enqueues knowledge.release_refs for 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) itest "corpus purge: replacement de-indexes the superseded version" — old ref de-indexed, fetch dark, snapshot bytes retained
2 Replaced and deleted versions stay searchable (history refs escape purge) confirmed the invariant above; purgeDocument now releases current + historyFiles refs through the shared seam; all rotation points (replacement, knowledge entries, WebDAV PUT-overwrite, cloud-sync update) funnel into the same job same itest + "reconcile sweep de-indexes stranded refs" (heals pre-fix strands)
3 Every knowledge-entry edit strands a stale, unpurgeable corpus document confirmed — the module comment claimed the corpus key survives rotation; indexing keys by storage_ref, so it does not rotate branch captures the outgoing ref and enqueues the release job in the same tx (corpus row + blob released — nothing else references entry blobs); comment now states the real contract itest "knowledge-entry edit releases the old ref (corpus + blob)"
4 Document purge swallows corpus/blob failures — erasure receipts lie confirmed (high×2) purgeDocument releases refs FIRST and throws PurgeIncompleteError on failure — the row is kept so retention re-selects it daily, erasure lands partial (operator can re-arm), a user sees the failure. deleteBlobBestEffort assessed: 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 failure itest "failed purge keeps the row (honest), retry heals" — corpus endpoint dead → delete 500s, row+corpus+blob intact; recover → retry releases everything
5 Project cascade delete never destroys documents; they stay RAG-retrievable confirmed in two halves: the grace>0 sweep DID select expired rows (claim held there), but (a) the retrievable filter admitted expired docs, and (b) the grace=0 pass never selected trashed/expired rows at all — on no-grace orgs the promised hard-delete never ran filter refuses every non-active lifecycle (dark immediately); the grace=0 documents pass now includes trashed/expired rows (mirroring the contacts sweep); cascade comment updated to the true story itest "project cascade darkens now, grace=0 sweep hard-deletes" — corpus row still present yet fetch dark, then sweep removes row+corpus+blob
6 WebDAV COPY shares blob refs that purge paths delete without refcount confirmed the shared seam refcounts BOTH surfaces: bytes live while any file_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 own purgeOldBlob now delegates to the job (no more network I/O inside its transaction; a trashed twin's bytes survive an overwrite of the live copy) itest "shared blob ref survives the sibling, dies with the last holder" — twin keeps corpus + bytes + answers through its own scope; last delete releases both
7 Retrievable filter ignores file lifecycle and admits unbound refs confirmed, with one refinement: refs with NO file row were already denied; the live leaks were history rows admitting non-current refs, trashed unbound rows (WebDAV strands), and expired docs. The unbound-fallback audit found ONE legitimate producer — video-link transcripts index with document_id NULL — so live unbound rows keep the 0.4 same-org posture; trashed rows and row-less refs are dark decideRetrievable (pure, unit-tested): current-ref + active-lifecycle + per-candidate scope for documents; thread scope for thread files; live unbound retained unit retrievable.test.ts (12 cases incl. twins/lifecycle matrix) + every itest scenario above exercises the filter
8 knowledge_entries mutations lack the write-matrix role gate (#3136's class) confirmed authorizeRls(role, 'knowledge', 'write') at the service seam (create/update/delete), enforced for app routes and REST; new knowledge subject in the access matrix (editor+ write, member read, disabled none) — mirrors unmerged #3136's idiom for documents, implemented against main's own rls helpers itest "member role is read-only (app + REST seam gate)" — member 403 on all three mutations, list still 200, owner delete works; unit access.test.ts

Refuted: 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)

Lane Before Now
retention documents sweep (sweepDocuments) corpus swallow + best-effort blob, rows deleted anyway; grace=0 never purged trashed/expired honest purgeDocument; per-doc catch keeps the sweep alive; grace=0 selects trashed/expired
user hard delete / folder cascade (deleteDocumentHard, deleteFolderCascade) same funnel, same swallow honest funnel — failure surfaces to the caller, row kept
REST DELETE /v1/documents/:id same same honest funnel
erasure documents pass pass counted "done" over swallowed failures purge throws → pass fails → request partial, operator re-arm retries (mirrors #3135's uploads-pass honesty contract)
cloud-sync prune (onedrive/gdrive shared pipeline) same funnel honest funnel; sync loop retries next scan
cloud-sync update (ref rotation) direct best-effort corpus delete, failures swallowed durable knowledge.release_refs job
controlled-record replacement (bindReplacement) never de-indexed the old ref release job enqueued in the bind tx
knowledge-entry re-materialize (attachEntryDocument) old ref fully stranded (corpus + blob) release job enqueued in the rotation tx
WebDAV PUT-overwrite (purgeOldBlob) blob-only refcount (active docs), corpus stranded, network I/O in tx file rows trashed in tx + release job (corpus + refcounted blob)
temp-file sweep (sweepTempFiles) best-effort blob delete then row delete (failure = permanent leak; indexed thread files left corpus strands) release first (corpus + refcounted blob), row deleted only on success
WebDAV upload-abort (deleteWebdavBlob) direct best-effort delete of a never-registered staging blob unchanged — pre-registration janitor, outside this class
daily reconcile (knowledge.reconcile_corpus) did not exist walks each org's corpus, releases every ref both liveness predicates declare dead — the lazy backfill for existing deployments (chosen over a synchronous migration backfill; volumes can be large and the sweep is idempotent and bounded per run)

Migration

0063_documents_history_files_gin.sql — GIN index over documents.history_files for the
history-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)

  • unit (branch): retrievable.test.ts + access.test.ts — 2 files / 12 tests passed; full platform suite 374 files / 72287 tests passed, exit 0
  • unit (base src + these tests): 2 files FAIL — access.test.ts 3/3 assertions red (no knowledge grant), retrievable.test.ts fails to load (module absent)
  • platform typecheck: exit 0 · platform lint (oxlint type-aware): exit 0
  • backend:integration on a throwaway tale-db + MinIO:
    • branch (fresh stack): 286/286 checks passed, exit 0 — includes the 7 new corpus-purge scenarios
    • base (main src + this PR's tests, fresh stack): 279/286 — exactly the 7 corpus-purge scenarios FAIL, every other check green (279 matches the main baseline), with the bug signatures verbatim: replacement oldCorpusGone=false, oldFetchDark=false; entry edit v1Released=false; honesty brokenDelete → 200, rowKept=false, corpusKept=true (success reported, corpus content left behind unrecoverably); cascade sweepDocs=0, rowGone=false; twins corpusKept=false, blobKept=false, twinAnswers=false; reconcile reconcileRan=false; role gate create → 201, update → 200, delete → 200

Cross-class notes

  • The erasure uploads pass still deletes file rows without blob release — sibling PR fix(platform): enforce the GDPR erasure governance gates #3135's
    territory (unmerged), untouched here to avoid collision; purgeDocument's honesty covers the
    documents pass either way.
  • deleteKnowledgeDocumentsBatch completes a pre-existing type-only vestige in
    core/legacy/knowledge_delete.ts (the batch types existed with no implementation).

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
larryro marked this pull request as ready for review September 3, 2026 03:56
@larryro
larryro merged commit 52871fb into main Sep 3, 2026
23 checks passed
@larryro
larryro deleted the fix/corpus-purge-consistency branch September 3, 2026 03:56
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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant