Skip to content

knowledge.restore brings a deleted document and its chunks back, and never what an erasure reached - #309

Merged
zlareb1 merged 1 commit into
mainfrom
feat/knowledge-restore
Nov 8, 2026
Merged

zlareb1 merged 1 commit into
mainfrom
feat/knowledge-restore

Conversation

@zlareb1

@zlareb1 zlareb1 commented Nov 6, 2026 •

Copy link
Copy Markdown
Member

Changelog category (leave one):

  • New Feature

Changelog entry (one or two sentences a user of Loom can read without the diff; the release pull request collects these into the release notes):

knowledge.restore undoes a knowledge.delete or knowledge.bulk_delete: the document's last version and its chunks are searchable again. It never brings back what an erasure retired, and it says whether the stored original could be kept and, when it restores nothing, why.

Why

A document delete is already a soft delete: the document row and its chunks stay, marked superseded. Memory has memory.restore for the same mistake, but a deleted document had no way back short of adding it again, which loses its id and revision and needs the content at hand. An agent that deletes the wrong document, or a source sync that retired one by mistake, needs one call to undo it.

Design

The op is Revise-shaped, on the knowledge plane, with the preconditions of memory.restore:

  • Input: org, namespace, source_uri, and if_revision, which restores only when the deleted document is at that revision.
  • Output: restored with chunks_restored and original (kept, gone, none), or a reason: not_found, live (with doc_id and revision naming the live version, which may be a later write), revision_mismatch, not_restorable, or expired.

How it works:

  • A delete stamps one time on both the document row (superseded_at) and the supersession rows it writes for the document's live ingestion (loom.chunk_supersessions). Restore takes the ingestions of the row's revision (chunks record it in chunk_metadata) listed as retired at exactly that time, removes those rows (a lightweight DELETE, every embedding model, nothing another retirement wrote), and writes the document row back live with a new version. The chunks read as live again through the shared LIVE_CHUNK_SQL, on N-1 and N alike.
  • It restores only what carries that signature, and never what an erasure reached:
    • A non-purge erasure supersedes a live document in place and stamps doc_superseded_at on its chunks without writing supersession rows, so its documents have no signature and are not_restorable.
    • An erasure that stamped the ingestions' chunks, or erased the original (blob_erased_at), refuses the restore.
    • An erasure that ran after the delete could stamp nothing: its chunk step counted live chunks and skipped the update when the scope had none. This PR makes that step count and stamp every unstamped chunk of its scope, a retired one too (server/erasure/store/steps_memory.py, supersede_chunks_by_namespace / _by_user; the mutation itself is unchanged, only the count that gates it), so the stamp outlives the ledger row. Restore also reads the ledger (ledger_reads.unfinished_reaching, a read of loom.erasure_requests narrowed in SQL to the erasures that may reach the namespace, with the clock margin the originals fence uses) and refuses when an erasure that may reach the document had not finished when it was written: its namespace's, a namespace list naming it (one it cannot read covers), or the user who wrote the restored revision. A user's purge also supersedes in place another writer's version that the user's replaced, but that version has no delete signature, so it is refused already; for a cut-off restore's live leftovers, which no signature ties to a writer, any user's erasure covers. The ledger rows carry purge (server/erasure/store/ledger.py). The scope rule lives in server/erasure/domain/scopes.py (may_cover) and the clock margin in server/erasure/app/ledger_reads.py (LEDGER_CLOCK_MARGIN_S), both shared with the originals move. The ledger keeps a request 90 days, so a restore reaches deletes of the last 89 (expired after); a unit test pins that window inside the TTL in schema.sql.
    • Once the row is written, restore reads the ledger again. When an erasure registered meanwhile covers the document, restore takes back what it wrote: under a purge a lightweight DELETE of its own row (by its version, so the purge finds no copy of the content left), otherwise the row written back retired (a merge may already have folded the delete's row into the restored one, so deleting it could leave no row); then its ingestions listed as retired again at the delete's own time, so the delete's signature is what it was. Any other failure once the writes begin takes it back the same way: it reads the ledger again, as the restore read it (a user's purge counts only for the writer of a signed revision), and deletes its row under a purge. Otherwise, and when the ledger cannot be read, it writes the row back retired (a delete could leave the source with no row, since a merge may fold the delete's row into the restored one at any moment); when a later write's row won meanwhile, the undo leaves it as it is and retires only the restore's own ingestions. Text writes take no claim, so one that started before the restore stores its row under a lower version and the restored row hides it, as a delete's row hides one that started before the delete; the docs say so and say to write it again. The row the undo writes back is built from the newest row, so a blob_erased_at or superseded_at an erasure stamped on the restored row in place stays; when no row is left (a purge took them all), it writes nothing. Leftover live chunks of a cut-off restore that an erasure covers are retired.
    • A purge leaves no rows (not_found). A document with no chunks has nothing a delete listed and is not_restorable; adding it again restores it.
  • Choosing by revision, not by the newest doc_version, keeps an ingest's unpublished chunks (written before it takes the claim, and listed by a delete that raced it) out of the restore.
  • It runs under the source's claim (claim_source), as an ingest's publish and a metadata edit do, and re-reads the row there; a row that changed in between is PRECONDITION_FAILED, and a second call is safe. Text writes and deletes take no claim: a text write landing on the same source during a restore can leave both versions' chunks searchable until the next write of that source, as it can during a delete today, and a delete landing during one can leave the document live with no searchable chunks until a second delete. The docs say both.
  • Reads are sequential from the first one, so a restore right after the caller's delete sees it.
  • The bucket reads go first, then the writes. A restore cut off between the chunks and the row leaves the revision's chunks searchable under a retired row; the next call finds them live, checks the erasure conditions again, and writes the row or retires them.
  • Row versions are later than the row they replace (max(now_ns, version + 1)), so a replica with a clock behind the deleting one still wins under ReplacingMergeTree.
  • The original: when the document_blob_gc sweep had removed it, the restored row names no original and the answer says gone; an extraction artifact the sweep removed is cleared from the row the same way. The sweep reads unreferenced originals in batches, so one it read just before the restore may still go; the download then fails as it does for any missing original. Keeping originals for a restore window would hold bucket bytes for every delete; reporting it costs nothing.
  • Datasets published from the document were deleted with it and are not restored; ingesting the file again publishes them.

Alternatives:

  • Writing a "restored" row into loom.chunk_supersessions instead of deleting rows would change LIVE_CHUNK_SQL for every reader, and an N-1 reader would still see the chunks as retired.

  • Re-inserting the chunk rows would copy every vector.

  • Trusting the ledger alone misses an erasure whose row has expired; the stamps cover it. Trusting the stamps alone misses an erasure that has not run yet, or ran on a build that stamped only live chunks; the ledger and the 89-day window cover those.

  • frontend/src/views/Documents.tsx, frontend/src/components/Toast.tsx, frontend/src/api/knowledge.ts: the Library's delete notice carries Undo, which calls knowledge.restore for the namespace the delete ran in and says why when nothing came back. A notice with an action keeps no clock, so a keyboard or screen-reader user can reach it, and is keyed by the document, so a later delete of it replaces the notice and its Undo. Undo hands focus back to the search field. Neither delete confirmation says the delete is irreversible any more: the single one points at Undo, and the bulk one says a bulk delete has no Undo in the dashboard and each document can be restored through the API; both say the uploaded file may not come back. This is the dashboard control a new person-facing op ships with (the op reach census).

Scope and risk

  • The erasure change: a non-purge erasure's chunk step now counts and stamps every unstamped chunk of its scope, retired ones too, so its chunks.supersede count includes them, and its ALTER UPDATE now runs for a scope that holds only retired chunks, where it used to be skipped. It stamps more, never less; the residue census and the purge path are unchanged.
  • Two lightweight DELETEs on a request path: the supersession rows one delete wrote, and the one document row the restore wrote (by its version), only when it takes itself back under a purge that may cover the document.
  • The residual window: an erasure that registers and completes between the restore's two ledger reads (milliseconds of SQL apart), followed by a failure of both the second read and the undo, or the process ending between the row write and the second read, leaves the restored row live. A purge whose ledger read fails during the undo leaves the row retired, which its residue census reports only if it runs after the undo. The docs state both. Closing it fully needs the erasure saga to fence a restore that holds the source's claim, a change to the saga left out of this PR.
  • New op knowledge.restore (writer, audited, experimental, idempotent), reachable over HTTP, the SDKs and loom_op. It is not in the default MCP listing.
  • No schema change.
  • Tenant isolation: the op is namespace-scoped, like knowledge.delete; the leakage walk skips it with the other knowledge writes.
  • A restored document a source sync retired is retired again by the next sync if the source no longer lists it, as the docs say.

Compatibility, rollout and rollback

  • Wire: added op knowledge.restore and Python Agent.knowledge.restore(source_uri, if_revision=None); generated SDK tables regenerated.
  • Operator steps: none.
  • Rollback: reverting removes the op. Documents it restored stay live, as if they had been added again.

Restore's ordering against erasures, other writes and the original sweep, and what it cannot take back, is on docs/architecture/failure-and-recovery.md (Knowledge restore); the feature page keeps the contract and the reasons. One window is named there and not closed: the sweep deletes an unreferenced original by age alone, so a sweep pass that read the namespace while the document was deleted can delete the original after restore found it, and the restored row names an original that is gone. Every write that names an existing original again shares it; closing it means a reference re-check in the sweep's delete, its own change.

The ledger read returns the rows that may reach the document (its namespace's, the writer's, every user's for a cut-off restore's leftovers, and namespace lists to parse), bounded by the ledger's 90 days. An undo deletes its row only when the erasure purges as its saga reads it (a user's from the column, a namespace list's from its scope); a namespace erasure only supersedes in place, so it never does. A failed write is taken back, and so is the restore of a request that is cancelled (nobody hears of it and no audit row would record it). The claimed part of a restore, from the re-read to the write back and its undo, runs as one shielded task (server.core.shielded, which now returns the coroutine's result), so a cancelled request neither cuts the undo short nor gives up the source's claim before it ends (unit-tested with a raised error, a raised cancellation from the claim's own timeout, and a cancelled anyio task group with and without an erasure at the second ledger read: the restore is taken back and the claim released after its last write); the chunk count runs with the writes, before the second ledger read, so a failed count is taken back like any failed write. A caller that goes away after the restore answered, while the transport writes its audit row, can leave it standing with no audit row, as any audited write can (failure-and-recovery.md). The dashboard's Undo restores the document's last deleted revision, whichever delete retired it (docs/features/dashboard.md).

Tests

  • tests/unit/test_knowledge_restore.py: every branch (restored, not found, live, a revision precondition, an erasure by chunks and by request, no delete signature, a swept or erased original, a row that changed under the claim, a held claim).
  • tests/integration/test_knowledge_restore.py, against a private ClickHouse and server (LOOM_CH_* and LOOM_BASE_URL exported from the worktree's .env, then pytest tests/integration/test_knowledge_restore.py), on the server built from the head, rebased on main: 20 passed in three runs in a row, the first straight after the server started (logs kept). Three of them run the ledger statement on real ClickHouse while it returns covering rows: a queued namespace erasure and a queued erasure of the writer each keep the document deleted, and a direct read returns the namespace's, the writer's and a namespace list's rows, leaves out another user's unless every user's is asked for, and keeps a completed erasure only when it finished after the document was written.
    • add, delete, restore: every document column but version and superseded_at matches what it was, the chunk count matches, and search finds it again; a second restore answers live with the same doc_id;
    • a revision precondition is refused, then a later write is named;
    • a missing document is not_found;
    • a real namespace erasure (erasure.request, run to completion) on a document deleted before it and on one live when it ran: both not_restorable, chunks still retired;
    • a user erasure (tombstone mode) of the document's writer, its ledger row then removed: not_restorable on the chunk stamp alone; one of another user: the document restores;
    • a pending namespace_list request in its object form keeps a deleted document retired;
    • restoring one document of a bulk_delete leaves the other retired;
    • a restore left half-done (supersession rows gone, row retired) is finished by the next call;
    • delete, restore and delete in one second retire the chunks again (each insert carries its own deduplication token, so the second delete's identical supersession rows land);
    • the undo's own statements against real ClickHouse (the handler run in the test process, a purge landing between the two ledger reads): no live chunk and the restore's row gone, with the delete's row the newest, or no row when a merge folded the delete's row into the restored one first (forced in one case; a clickhouse-local unit test pins the DELETE to its own version); and the undo under an unreadable ledger, with and without a partition merge folding the delete's row into the restored one first: either way the document reads deleted with no live chunk;
    • a document added twice comes back at the revision its row names;
    • chunks written before chunks recorded their revision come back with the document.
  • Cost, from system.query_log on that run: each restore read finished in 3-9 ms reading at most 14 rows, and the lightweight DELETE in 18 ms, inside the op's 200 ms budget.
  • frontend/src/views/Documents.restore.test.tsx: Undo restores into the namespace the delete ran in, says why a refusal left the document deleted, returns focus to the search, a second delete of the document replaces its notice, axe passes with the notice up, and the notice outlives the toast clock. The frontend suite (2,074 passed), build and bundle budget pass.
  • make lint, make typecheck, and the unit slice covering ops, reach, MCP, knowledge, SDK, audit, erasure, mutations and docs (7,741 passed; the SDK surface snapshot updated for the new method).

AI assistance in the code (leave one; writing this description with AI is fine):

  • AI-generated (an agent wrote most of the diff): Claude Code. The SQL was run against a real ClickHouse through the integration tests, and the erasure paths were read to confirm which rows they keep.

  • I can explain every line of this diff and how it interacts with the rest of Loom.

Checklist

  • make format-check, make lint, make typecheck and make test-unit pass; the integration suite passes if server behaviour changed.
  • Generated files are regenerated in this PR, not by hand.
  • Docs under docs/ describe the system as it now is, and this description names any operator steps and wire changes.
  • Repository text has no dates, people, host names, internal namespaces, ticket or decision numbers.
  • Commits are signed off (git commit -s).

🤖 Generated with Claude Code

@zlareb1
zlareb1 force-pushed the feat/knowledge-restore branch 2 times, most recently from d9d1f67 to a6c8328 Compare November 8, 2026 01:20
…never what an erasure reached

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: zlareb1 <[email protected]>
@zlareb1
zlareb1 force-pushed the feat/knowledge-restore branch from c148a30 to 4b61c8b Compare November 8, 2026 04:27
@zlareb1
zlareb1 merged commit 3188fcf into main Nov 8, 2026
21 checks passed
@zlareb1
zlareb1 deleted the feat/knowledge-restore branch November 8, 2026 04:28
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