Repository navigation
Under the Postgres authority each knowledge document's head is committed in Postgres over the version its writer read - #405
Merged
Conversation
zlareb1
force-pushed
the
feat/knowledge-pg-heads
branch
3 times, most recently
from
November 9, 2026 04:14
1a92cb5 to
09d1c8d
Compare
…ted in Postgres over the version its writer read Knowledge document heads, their owed ClickHouse deliveries and an erasure's deletion evidence live in Postgres (pg migration 002). A commit takes the namespace lock shared and the heads in key order, and refuses a head that moved (409) or a removed document's write (404). The knowledge_pg_delivery worker publishes a delivery whose writer stopped. Under that authority documents and chunks carry no namespace TTL. knowledge.bulk_add refuses a batch that repeats a source_uri (422) under either authority. Related: #157 Signed-off-by: zlareb1 <[email protected]> Co-Authored-By: Claude Opus 5.5 <[email protected]>
zlareb1
force-pushed
the
feat/knowledge-pg-heads
branch
from
November 9, 2026 05:34
b038c8c to
b3d49d6
Compare
… among the maintenance indexes Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: zlareb1 <[email protected]>
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.
Related: #157
Changelog category (leave one):
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):
Under the Postgres storage authority, knowledge documents now have their current version in Postgres. Two concurrent writes of one document can no longer both publish or both take the same revision: the later one answers 409
PRECONDITION_FAILED, and a parked document delivery is counted inGET /v1/health?include=postgres(postgres.parked_knowledge_deliveries). Under that authority a namespace'sretention_daysno longer expires knowledge documents or their chunks, and the server refuses to start withLOOM_RETENTION_DOCUMENTS_DAYSset. Under either authority,knowledge.update_metadatawithreindex=truenow re-indexes also when the metadata is already current, so each such call re-embeds the document, andknowledge.bulk_addrefuses a batch that names asource_uritwice (422VALIDATION_FAILED, nothing written): send one entry per source.Why
Issue #157 asks for knowledge documents with real concurrency control under the Postgres authority, as memory has had since that authority landed. Today
loom.documentsis a ClickHouseReplacingMergeTree(version)and nothing orders its writers. Aknowledge.upsertand aknowledge.addof one source, or an upsert racing an ingest publish, both read revision N and both write N+1. Both rows then publish, and the one with the higher nanosecond version wins without either caller learning about the other. Ingest publishes and metadata edits take a KeeperMap claim, but text writes take none, and the claim has no fencing token. This PR is the first of four (heads; search validation against heads; ingest jobs; datasets). It gives every document write one commit point in Postgres.Design
Tables (
schemas/pg_migrations/002_knowledge_documents.sql, the next Postgres migration after001_memory_authority.sql):loom.knowledge_heads (org, namespace, source_uri): the completeloom.documentsrow a read serves, plusversion,revision,deletedanduser_id(for user erasure).loom.knowledge_deliveries (org, namespace, source_uri, version): what a commit still owes ClickHouse. Bit 1 is the document row and bit 2 the retirement of the source's older chunk versions. Each delivery keeps its own copy of the row, a lease, a fencing token, attempts andlast_error. It is the same outbox shape asloom.memory_deliveries.One funnel.
documents.insert_one/insert_manynow takeover, the version the writer read (0 for none), andretire_older. Under the Postgres authority (pg_documents.commit):VALIDATION_FAILED, before writing anything, the original's bytes included, then inserts its chunks. Any other text is kept exactly: the stored row holds it in base64 (encode_row), so every document ClickHouse holds can be deleted, edited and restored.knowledge.ingestrefuses such a key (422) before the job is queued; a job an older build queued fails asunstorable_text. Search finds them as soon as they land, beside the version they replace, as it always did for an ingest. Checking search hits against heads is the next PR of Search documents and query tables across office, code and data files #157. Ingest already inserted them first, andknowledge.upsertandknowledge.bulk_addnow do too. For upsert, its row's delivery retires the chunks it replaces. For bulk add, a commit that answersPUBLICATION_PENDINGis published by the worker, which publishes document rows alone.knowledge.adddoes too: it used to insert both at once, and a commit answeringPUBLICATION_PENDINGbeside a failed chunk insert told its caller not to repeat a write whose chunks never landed.HeadMoved, aPreconditionFailedError, 409) when a head is newer than what the writer read, or when the new row is not above both the head and the version read. A row not above them would move the head back. Every writer stamps its version past the one it read (documents.version_past, shared by the text writes, ingest and restore). A host whose clock runs behind therefore still writes above the head. Otherwise it writes the head and a delivery under token 1, with a lease ofLOOM_PG_REQUEST_LEASE_SECONDS.loom.documentsrow and, when asked, retires the older chunk versions. Then it deletes the delivery under its token. A writer that cannot finish answers 503PUBLICATION_PENDING(committed). If the retirement fails after the row is in, the commit stands. Under the Postgres authority that answersPUBLICATION_PENDING, and the worker runs the retirement again. Under the ClickHouse authority it isOlderNotRetired(503), which ingest takes as published (_AfterRow). A Postgres failure clearing the delivery after the publish answersPUBLICATION_PENDINGtoo (the worker clears it), as memory does.The funnel now owns the older-chunk retirement of the document writers under both authorities, so they no longer call
mark_doc_supersededafter their insert.knowledge.dedup_resolvestill retires a source's chunks itself, outside the funnel, as on main. A delete is a tombstone head whose delivery retires every older chunk version. Its retirement runs before its row is published (a new version's runs after its row), andknowledge.restoreanswers a retryable 503 while a publication of the source may still land: one owed, or one the worker took over and settled whose replaced request is still within the insert bound. A delete's retirement therefore never lands after a restore brought the chunks back. A delete that loses the head to another write therefore leaves that write's chunks alone.On a refused commit:
knowledge.upsert,knowledge.addandknowledge.bulk_addretire the chunk versions they just inserted, in one statement (chunks.retire_versions). Its supersession rows are written from the (source, version) pairs, not selected fromloom.chunks, so they also retire chunks of an insert that timed out and lands afterwards. That covers a 409, a Postgres error before the commit, and a ClickHouse refusal or timeout under its own authority. They keep them only when the row may still serve: committed (PUBLICATION_PENDING), the row in with only the retirement failed, or a commit whose answer was lost. A chunk insert that failed, timed out or was cancelled is cleaned up the same way, since its rows may still land; so is a request cancelled before its commit was sent, the cleanup shielded from the cancel. One cancelled from its commit on keeps them: the funnel marks a cancel raised once the row is committed (or, under the ClickHouse authority, once its publication began) as one that may have committed. A timed-out ClickHouse insert that lands later therefore serves a document whose new chunks are retired until the caller's retry writes it again. Before, the same timeout left a document with no chunks. On a refusal for an erased document (DocumentErased, below) they delete those chunk rows instead (lightweightDELETE FROM loom.chunks,chunks.delete_versions), so the erased text and author do not remain as retired rows._published_anywaydoes not cover, a cancel included) forgets the datasets it carried to its new version. A row Postgres cannot store is refused before any dataset is carried.revision_conflict.I chose 409 over an automatic retry in the handler. The caller already has the error, and the plane already uses the same error for the metadata edit's moved-source check.
Reads.
get_one/get_many_by_urisread the head and the latest ClickHouse row, and serve the newer version:The next commit of such a source adopts that row. A commit is refused only by a head newer than what its writer read, and of two concurrent first commits the second gets
INSERT … ON CONFLICT DO NOTHINGback and is refused.If a head owes nothing and ClickHouse holds no row at its version, the source was erased by N-1's saga, which has no Postgres step. A user purge can leave older rows by other writers, so the check is the head's version, not the source. The read first confirms the absence with a sequentially consistent read, so a replica behind the write never counts. It then deletes that head (
drop_unbacked, only at that version and only while the source has no delivery) instead of serving erased content.Callers that kept going on an error now count
PUBLICATION_PENDINGas done, since the write committed: the source sync (a written file, a retired document), a learning's promotion to knowledge or throughmemory.set(the review records its decision),loom rechunk(its chunk count leaves that document out), and the importers' shared writer (loom import-brain,loom import-recall), in process and over HTTP. Aknowledge.update_metadatawithreindex=truewhose row answersPUBLICATION_PENDINGstill runs its reindex before answering, and a reindex now runs also when the metadata is already current, so repeating an edit whose reindex did not finish completes it. A reindex andloom rechunkrewrite the content they read, so each commits its row over the version it read (handle_knowledge_upsert(read_version=...)), not over the one the upsert's own read found. Under the Postgres authority a source written since, up to the commit, refuses the rewrite (409PRECONDITION_FAILED, its chunks cleaned up) instead of the older content replacing the newer write. Under the ClickHouse authorityoveris not checked, so nothing changes there. A metadata edit's reindex rewrites over the edit's own version, or the version it read when nothing changed; a reindex refused after the edit committed its row, published or still owed, answers a 409 that says the metadata was committed and to ask for the reindex again; a repeat that wrote nothing answers the plain 409.The originals sweep (
document_blob_gc), the originals move and a user erasure's shared-originals check decide what is needed fromloom.documents. Under the Postgres authority they also read the originals and extraction artifacts that unsettled deliveries name, before ClickHouse: the sweep drops them from each page of candidates and its cursor moves past them (blobs.owed_originals, filtered in Python, since their number is not bounded; the Postgres fragment, shared with the erasure, isserver/knowledge/domain/owed_originals.py), the move counts them needed, and a user erasure keeps one another user's unpublished commit names (steps_memory._others_owed_originals, read per batch with the batch's pairs bound, so it returns one batch at most; for an erased user id Postgres cannot store, every owed delivery is another's). Only a live document's original counts: a pending delete's tombstone or an erased original needs none. A committed write whose row is still owed, or parked for an operator, keeps its new original however long the row takes.knowledge.bulk_deletetombstones every listed live document, chunks or none, asknowledge.deletedoes; before, a live document with no active chunks was left live with zero counts.Ingest's check for whether an earlier run published (
revision_by_ingestion) also reads the head and any delivery still owed. Otherwise a run whose commit landed but whose publish did not would look unpublished, and its chunks would be retired before the worker published its row. A Postgres error at the commit is transient for ingest. One whose commit's answer was lost stops the run as any uncertain insert does, and the next run settles it; one that committed nothing (a lock timeout while an erasure holds the namespace) retries the job with its backoff.Delivery worker.
knowledge_pg_deliverytakes deliveries whose lease ran out withFOR UPDATE SKIP LOCKEDunder the next token and publishes them from the stored row, under the claim's lease (pg_lease.leased), so an erasure that waited the lease out finds everything it could land. It reuses thepg_delivery_*settings, its claims leased forLOOM_PG_DELIVERY_LEASE_SECONDSas the memory worker's are. The lease ending before a publish starts (leasedrefuses on entry, before any send) releases the rest uncounted. A send the lease's end cut off is refused by its start guard as a late send while ClickHouse answers, and counts, so a delivery that always outlasts the lease parks. The chunk retirement a publication sends under its lease (chunks._record_supersessions, anINSERT … SELECT) carries the same start guard and write limit as the lease's inserts, so no retirement lands after the lease an erasure or a restore waited out; its deadline is drawn once, so the client's reconnect retry keeps it. It publishes one delivery at a time: a delivery's retirement is its own (stamped at its tombstone'ssuperseded_at, which restore matches, and bounded by its own version), which one insert for several deliveries of a namespace cannot keep. A backlog costs up to two inserts per delivery (its row, and its retirement'sINSERT … SELECT), at mostLOOM_PG_DELIVERY_BATCH_ROWSdeliveries a pass within oneLOOM_PG_DELIVERY_LEASE_SECONDSlease (which on a backlog usually ends the pass first); a pass the lease's end cuts short releases the rest uncounted, and the next pass takes them.ch_errors.refused_nothing, moved here from the memory worker so both workers use one classification), or the lease about to end, stops the pass and releases the remaining claims.LOOM_PG_DELIVERY_MAX_ATTEMPTSthe delivery is parked and counted inpostgres.parked_knowledge_deliveries.LOOM_PG_ERASURE_EVIDENCE_HOURS.Erasure. A new saga step
pg_knowledge.deleteruns afterpg_memory.delete, only under the Postgres authority, built likepg_memory.delete. It runs on a dedicated connection, retries on a deadlock, and works in one transaction:pg.KNOWLEDGE_LOCK_KEY, an advisory lock every commit holds shared). A user's scope locks every namespace holding the user's heads or deliveries, reading again until none more does. The user's namespaces that hold only ClickHouse rows are read for evidence without a lock: a commit there during the step makes a head carrying the user's id, which the residue census finds, so the saga fails and runs again. Until the transaction ends, any user's knowledge write in those namespaces waitsLOOM_PG_COMMIT_LOCK_TIMEOUT_MSand answers 503, so a scope with a long ClickHouse history holds them for its whole evidence read.loom.erased_documents(no content) forLOOM_PG_ERASURE_EVIDENCE_HOURS, thedoc_idof every version of the scope's documents: those of the heads and deliveries it removed, and those ClickHouse holds, read page by page along the table's key, each namespace by source URI (LOOM_PG_ERASURE_EVIDENCE_PAGE_ROWS, 10,000), with a plainsource_uri >=bound the key analysis uses to skip earlier granules (checked withEXPLAIN indexes = 1: the tuple comparison alone does not narrow the key range), with sequential consistency, each page inserted as it arrives.quiet_at). The transaction's idle limit covers every attempt the client makes of one ClickHouse evidence read plus its reconnects, never below the pool's own limit, and none when reads are unbounded, since the session idles while each page is read (checked on Postgres 16: aSET LOCALof it governs later idle periods in the same transaction). A parked delivery's lease is endless, so the wait covers the send that parked it from itsfenced_until(pg.LEASE_LEFT_S, as for memory). A timed-out insert that parked it may still land. A delivery the worker took over and finished is keptsettled, its lease ending then, until the insert bound has passed, as memory keeps one. The request it replaced may still have an insert in flight, so the wait covers that delivery too, and a user's scope finds it by its ownuser_id. The pass sweeps settled deliveries afterwards.A row built from a read keeps the document's
doc_id(a delete's tombstone, a metadata edit). The erasure records thedoc_idof every version of the scope's documents, the ones ClickHouse holds included, read under its locks where the scope has heads. A write built from a version a later write replaced before the erasure therefore keeps a recorded id and is refused. A write that reads after the erasure carries none: a new version takes a fresh id, and a deleted document lends none. A version a merge folded away before the erasure leaves no id, which is the race the ClickHouse authority has. A write that carries a live document's original or author (knowledge.upsert,knowledge.add,knowledge.bulk_add) names that document (built_from). Either way, a commit built from a removed document is refused withDocumentErased(404). The check is read after the heads' locks the erasure holds. Heads and deliveries are inPG_CENSUSand the residue census, and inPG_IN_USE_TABLES, so a namespace holding a committed document is in use for the name checks (test_in_use_coverage.py). The evidence table is inPG_NO_MEMORY_CONTENTand exempt from that check.knowledge.restore(#309, rebased over) writes through the funnel over the version it read under the source's claim. Its write-back and its undo passover, and its unit test pins the write-back'sover. A write-back that committed and then could not publish (PUBLICATION_PENDING) is undone, and the restore then answers a retryable 503 (BACKEND_UNAVAILABLE, "call knowledge.restore again"), never "committed". An undo whose own retired row answersPUBLICATION_PENDINGis committed, and the worker publishes it. A purge undo also takes back the restored head and its delivery (documents.drop_committed), then waits out that delivery's lease before deleting the ClickHouse row, since a holder of it may still land the row. An undo refused because a later write took the source, or an erasure removed it, still retires the restored chunks. Under the Postgres authority, a restore committing after an erasure's Postgres step is refused by thedoc_idevidence (the restored row keeps it), and one committing before is removed by that step.PublicationPendingmoved fromserver/memory/store/pg_memory.pytoserver/core/pg_lease.py, withlease_deadline,check_leaseandleased. Both planes raise it now, and a knowledge store may not import a memory store (test_package_contracts.py). The old location is removed and every caller is updated.Alternatives considered:
(version, revision)in Postgres and read rows from ClickHouse. This was rejected because a head that cannot serve the row cannot answer a read before ClickHouse has it, and a later delivery could not republish it.machines.fleet_at). This was rejected because the gate keys on a ClickHouse migration number, which this change does not add, and it would not survive a rollback. Reading both and serving the newer handles both cases.Scope and risk
knowledge.upsert,knowledge.addandknowledge.bulk_addinsert their chunks before the document rows. Upsert and bulk add used to insert them after; add used to insert both at once.knowledge.deleteandknowledge.bulk_deleteretire the chunks older than their tombstone, instead of every chunk, still before the tombstone's row as on main. A delete therefore never retires the chunks of a write that took the source after it.superseded_at, or ClickHouse'snow()) instead of the request's clock. Each write's retirement is one statement (mark_docs_supersedednow takes each source's version bound). A deleted document's leftover chunks are retired by source, under the source's claim, which restore holds: read again under it, a source restored meanwhile keeps its chunks, and a deleted one's go stamped at its own delete, so restore still finds it while that delete's own retirement is owed. Each source holding leftovers costs, in turn, a claim (waiting up to 10 s for one another write holds), a read of the document under it with sequential consistency, a count of its chunks up to the tombstone (the answer'schunks_tombstoned, so a newer write's chunks still to commit are neither retired nor counted, and a delete that finds none up to the tombstone answersdeleted=False), and oneINSERT … SELECT; a claim not held answers a retryable 503 with nothing written, and a source restored meanwhile answers as not deleted.knowledge.deleteandknowledge.bulk_deleterun every read sequentially consistent, asknowledge.restoredoes, so a delete right after a restore sees it on any replica. Abulk_deletebatch runs that per such source, then the tombstones' retirement before their rows. Leftovers are the rare case (chunks left after a delete), so a batch of live documents pays none of it. A delete of a source with no document row retires only its chunks older thanLOOM_KNOWLEDGE_ORPHAN_CHUNK_MIN_AGE_SECONDS(default 3600, a new setting, never less than an ingest pass plus 5 minutes of clock skew), by their version'stime_nsstamp, and answers how many it retired (main retired every chunk);knowledge.upsert,knowledge.addandknowledge.bulk_addnow stamp their versions after embedding, so a version is the time its chunks are written: every writer now inserts a new source's chunks before its row, so a younger version may be a first write's still to commit, which keeps its chunks. Orphans left by a failed cleanup, a crash or a TTL that took the row go once old enough.BACKEND_UNAVAILABLE(OlderNotRetired), and a repeat of the write runs it again.pg_commit_lock_timeout_ms.knowledge.bulk_addchecks every entry's key columns before it embeds any.knowledge.bulk_addrefuses a batch that names a source URI twice (422VALIDATION_FAILED, nothing written). On main both entries were written with one revision number, and a commit holds one row per source (pg_documents.commitrefuses a repeat), so the handler refuses the batch before it writes anything. A caller sends the last entry for each source.loom.documents(LOOM_RETENTION_DOCUMENTS_DAYS, a namespace'sretention_days) is not applied, as forloom.memory: it would delete ClickHouse's copy and leave the text in the head. The boot refusesLOOM_RETENTION_DOCUMENTS_DAYSbeside the two memory retention settings. A namespace'sretention_daysleavesloom.chunkstoo, so a live document keeps the chunks search finds it by;LOOM_RETENTION_CHUNKS_DAYS, set alone, expires chunks alone under either authority.loom doctor'sreplica_consistencyline now also watchesloom.documents, under either authority, andclickhouse.mdlists both guarantees.knowledge.search/outlinevalidation against heads (live_versionsstill reads ClickHouse), ingest jobs and cancels in Postgres, and datasets in the head transaction. Other readers that still decide fromloom.documentsalone, and so miss a commit whose row is owed or parked until it lands: the source sync's view of its documents (sources.source_revisions,source_documents), which writes such a file again on its next turn, and a learning's promotion check (learnings.rule_promoted). Neither loses data; the next PR moves them to heads with search.Compatibility, rollout and rollback
knowledge.bulk_addrefuses a batch that repeats asource_uriwith 422VALIDATION_FAILED, where main wrote every entry. A caller sends one entry per source (the last one it means).knowledge.upsert,knowledge.add,knowledge.bulk_add,knowledge.delete,knowledge.bulk_deleteandknowledge.update_metadatacan answer the following under the Postgres authority:PRECONDITION_FAILED: another write of the source committed first.RESOURCE_NOT_FOUND: the document the write read was erased since.PUBLICATION_PENDING: the write is committed and the worker publishes it.knowledge.restorecan answer 409PRECONDITION_FAILEDwhen another write took the source during its write-back, and 503BACKEND_UNAVAILABLEwhen a committed write-back was taken back. An erasure that refused its write-back answersnot_restorable, as any erasure does.VALIDATION_FAILEDfor a source URI or a writer's id holding a NUL character or a lone surrogate, which a Postgres key column cannot store.knowledge.ingestanswers it 422 before queueing the job; only a job an older build queued failsunstorable_text. Any other text, a document's content or title included, is accepted and kept exactly.GET /v1/health?include=postgresgainspostgres.parked_knowledge_deliveries.LOOM_KNOWLEDGE_ORPHAN_CHUNK_MIN_AGE_SECONDS(default 3600): how old a source's chunks with no document row must be before a delete retires them.LOOM_PG_ERASURE_EVIDENCE_PAGE_ROWS(default 10,000): the document ids an erasure reads and keeps per page.LOOM_RETENTION_DOCUMENTS_DAYSset, and a namespace'sretention_daysputs no TTL onloom.documentsorloom.chunks(a TTL left on them is removed). Unset the setting before the rollout (upgrade step 2).loom.knowledge_headsuntil then. This is step 11 of the upgrade procedure (docs/operations/upgrades.md) and rule 38. Before the rollout, unsetLOOM_RETENTION_DOCUMENTS_DAYS(step 2). Otherwise none: the Postgres migration applies at boot under the advisory lock, anddocs/operations/postgres.mdgives the statement that retries a parked document delivery.loom.documentsalone, and N serves the newer of the two and adopts the newer row on the next commit. See rule 38 indocs/architecture/rolling-upgrades.md.ON CONFLICT: a delivery's version always comes from a head that only grows, so a duplicate would be a defect, refused loudly. A rolled-back build ignores them, and the next roll forward serves ClickHouse's newer rows over the stale heads.Tests
tests/integration/test_knowledge_pg_heads.py(26 tests). It ran against a server from this branch on its own Postgres 16 and ClickHouse, with workers on and the reference extractor. Cases:knowledge.getdoes not find.pg_knowledge.deletecounts at least 3 rows.now()from'infinity').fenced_until).test_knowledge_restore.pypasses under the Postgres authority, and the CI job now runs it.DocumentErased, leaving evidence, and no version of it commits or publishes. The same holds for a new row of its own id that names the live document it carried columns from.loom.chunks.ALTER … UPDATE superseded_at) hides the head that is still live.integration-postgresjob now also runstest_knowledge_pg_heads.py,test_knowledge.py,_upsert,_delete,_restore,_bulk,_bulk_delete,_get,_ingest_queueand_sharing.tests/unit/test_knowledge_pg_delivery.py(new):tests/unit/test_documents_repo.py:PUBLICATION_PENDING. A head keeps text Postgres cannot store exactly, and a key column holding one is refused. A tombstone retires its chunks before its row, and a new version after. A source URI Postgres cannot store is read from ClickHouse and never sent to Postgres. A commit taken back waits out its delivery's lease. A head keeps its datetimes to the second, as ClickHouse'sDateTimedoes.tests/unit/test_knowledge_dedup.py:knowledge.upsertandknowledge.addretire their own chunk version and raise. Both name a live prior'sdoc_idasbuilt_from, and name none for a deleted prior.knowledge.bulk_addinserts its chunks before its commit, keeps them when the commit answersPUBLICATION_PENDING, and retires them when the commit is refused. Upsert and add retire theirs on 409 and delete them on 404. A new version is above the one its writer read. A refused metadata edit forgets the datasets it carried. An upsert keeps its chunks only when its row may serve (4 cases). A NUL in an upsert, add or bulk add source URI, or in the writer's id from the token, answers 422 having written nothing.tests/unit/test_document_row_builder.py:PUBLICATION_PENDINGstill runs its reindex, over the exact version it wrote; an edit with nothing changed still reindexes, over the version it read; a reindex refused after a committed edit (published or owed) answers the 409 that says so, and an unchanged repeat the plain one.tests/unit/test_knowledge_pg_commit.py(new):pg_documents.commitagainst a fake connection, covering:built_from, after the namespace lock and the heads' locks.tests/unit/test_pg_authority.py: the knowledge erasure's lock order is pinned to the commit's.tests/unit/test_knowledge_ingest.py:unstorable_textwith no chunk written.test_an_ingest_a_later_text_write_overtook_fails_and_retires_its_chunks, which pinned the opposite: a prior stamped ahead of the job's clock failed the job. That prior was read before the publish, so publishing above it is the right order._check_unchanged's check of the latest row against the job's version is removed, because it can no longer fire. A write landing after the read is still refused (test_a_write_between_the_revision_and_the_claim_fails_the_publish).tests/unit/test_knowledge_restore.py: a document whose source URI or user id Postgres cannot store is refused (422) before any chunk is brought back. A write-back that answeredPUBLICATION_PENDINGis undone and answers a retryable 503. A restore waits while the delete is still being published. A write-back an erasure refused answersnot_restorable. An undo refused by a later write or an erasure still retires the chunks. An undo whose retirement is pending still answers not restored. A purge undo takes back the Postgres commit.tests/unit/test_knowledge_erasure_pg.py(new), with the memory and knowledge steps now sharing_after_deadlocksand_earlier_run. Besides the evidence read, paged per namespace along the table's key under sequential reads (a user's scope reading its namespaces first), it covers: the deadlock retry, the user scope's lock loop reaching a namespace added meanwhile, and the earlier run's wait.tests/unit/test_blob_store.py: under the Postgres authority the sweep spares an unpublished commit's original and deletes the rest of the page, and the original counts as needed; the owed read comes before each ClickHouse read, in the sweep and inneeded.tests/unit/test_document_object_store.py: a user erasure keeps an original another user's unpublished live document names, reading Postgres before the batch's ClickHouse re-read, and an erased user id Postgres cannot store reads every owed delivery as another's; both owed reads use the shared fragment.tests/unit/test_knowledge_repo.py: a retirement sent under a lease carries the lease's start guard and the write limit, and its refusal answers as a late send;mark_docs_supersededbinds each source's bound in one statement.Worldfake intest_knowledge_ingest.pynow retires inside the funnel. Fakes in the dedup, row builder, shared-blob and sharing tests were updated to the funnel's signature and to the chunk-first order.tests/unit/test_knowledge_maintenance_cli.py: rechunk passes the version it read and countsPUBLICATION_PENDINGas rechunked.tests/unit/test_knowledge_source_sync.py,tests/unit/test_learnings_dual_destination.py,tests/unit/test_import_recall.py:PUBLICATION_PENDINGcounts as done (a written file, a retired document, a promotion throughmemory.setor to knowledge, an importer's write in process and over HTTP, where any other 503 still fails).tests/unit/test_retention_overrides.py: under the Postgres authority no TTL reaches memory or documents, a namespace'sretention_daysleaves chunks, and a TTL left onloom.documentsis removed;tests/unit/test_pg_authority.py: the boot refuses the three retention settings.tests/unit/test_doctor_replica_consistency.py:documentsis watched under either authority.pytest tests/analyzerpasses against a migrated ClickHouse afterpython -m tests.analyzer.corpus --write. The regeneratedshapes.txthas this PR's changes: the two document reads it removes, the reworked bulk retirement, the two erasure evidence reads, the boundedcount_active_by_uri, and the deletion of a refused write's chunks (delete_versions). Their retirement by (source, version) pair (retire_versions) is not there: it is a row insert, which has no statement shape.make format,make lint,make typecheckand the full unit suite pass on this head, rebased ontomain(1995092): 32081 passed, 25 skipped, 1 xfailed under-n 3 -p randomly; the one commit after it changes a doc page. Against a Postgres-authority server running this head,test_knowledge_pg_heads.py(26, among them the full-row comparison of a head with its published row and the check ofparked_knowledge_deliveriesinGET /v1/health?include=postgres),test_knowledge_bulk_delete.py,test_erasure.pyandtest_erasure_user_originals_shared.pypass.test_erasure_summary_derived_live_ch.pypasses under the ClickHouse authority; one of its tests fails under the Postgres authority onmaintoo (it seeds memory in ClickHouse and promotes in process, which reads Postgres), and CI's Postgres job does not run that file. On an earlier head of this PR the bulk, restore, delete and write files passed as well (59 with the heads file). With the reference extractor configured on that server, the get, ingest, ingest-queue and ingest-fault files pass too (25).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. I checked the lock order, the CAS rule, the lease and erasure ordering and the rolling-upgrade read, and ran the tests above.
I can explain every line of this diff and how it interacts with the rest of Loom.
Checklist
make format-check,make lint,make typecheckandmake test-unitpass; the integration suite passes if server behaviour changed.docs/reference/configuration.mdand thedocs/reference/tables (python scripts/codegen/docs_reference.py), the reach manifest,schemas/schema.sql(make schema-dump) and the Codex plugin copies (python3 scripts/codegen/agent_plugin_sync.py).main; no merged migration is edited.hooks/,lib/,bin/,skills/,.mcp.json, the Codexplugin-defaults.json) bumps both plugin manifests' version, and no other open PR uses that version.npm --prefix frontend run build) and its tests pass, iffrontend/changed.docs/describe the system as it now is, and this description names any operator steps and wire changes.tests/unit/test_public_copy.py).git commit -s), as CONTRIBUTING.md asks.🤖 Generated with Claude Code