Skip to content

Under the Postgres authority each knowledge document's head is committed in Postgres over the version its writer read - #405

Merged
zlareb1 merged 2 commits into
mainfrom
feat/knowledge-pg-heads
Nov 9, 2026
Merged

zlareb1 merged 2 commits into
mainfrom
feat/knowledge-pg-heads

Conversation

@zlareb1

@zlareb1 zlareb1 commented Nov 8, 2026 •

Copy link
Copy Markdown
Member

Related: #157

Changelog category (leave one):

  • Backward Incompatible Change

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 in GET /v1/health?include=postgres (postgres.parked_knowledge_deliveries). Under that authority a namespace's retention_days no longer expires knowledge documents or their chunks, and the server refuses to start with LOOM_RETENTION_DOCUMENTS_DAYS set. Under either authority, knowledge.update_metadata with reindex=true now re-indexes also when the metadata is already current, so each such call re-embeds the document, and knowledge.bulk_add refuses a batch that names a source_uri twice (422 VALIDATION_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.documents is a ClickHouse ReplacingMergeTree(version) and nothing orders its writers. A knowledge.upsert and a knowledge.add of 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 after 001_memory_authority.sql):

  • loom.knowledge_heads (org, namespace, source_uri): the complete loom.documents row a read serves, plus version, revision, deleted and user_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 and last_error. It is the same outbox shape as loom.memory_deliveries.

One funnel. documents.insert_one / insert_many now take over, the version the writer read (0 for none), and retire_older. Under the Postgres authority (pg_documents.commit):

  1. The writer refuses a row whose source URI or writer's id holds text a Postgres key column cannot store (a NUL character, a lone surrogate) with 422 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.ingest refuses such a key (422) before the job is queued; a job an older build queued fails as unstorable_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, and knowledge.upsert and knowledge.bulk_add now do too. For upsert, its row's delivery retires the chunks it replaces. For bulk add, a commit that answers PUBLICATION_PENDING is published by the worker, which publishes document rows alone. knowledge.add does too: it used to insert both at once, and a commit answering PUBLICATION_PENDING beside a failed chunk insert told its caller not to repeat a write whose chunks never landed.
  2. One transaction locks the heads in key order. It refuses (HeadMoved, a PreconditionFailedError, 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 of LOOM_PG_REQUEST_LEASE_SECONDS.
  3. Under that lease the writer publishes the loom.documents row and, when asked, retires the older chunk versions. Then it deletes the delivery under its token. A writer that cannot finish answers 503 PUBLICATION_PENDING (committed). If the retirement fails after the row is in, the commit stands. Under the Postgres authority that answers PUBLICATION_PENDING, and the worker runs the retirement again. Under the ClickHouse authority it is OlderNotRetired (503), which ingest takes as published (_AfterRow). A Postgres failure clearing the delivery after the publish answers PUBLICATION_PENDING too (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_superseded after their insert. knowledge.dedup_resolve still 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), and knowledge.restore answers 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:

  • When their document does not land, knowledge.upsert, knowledge.add and knowledge.bulk_add retire the chunk versions they just inserted, in one statement (chunks.retire_versions). Its supersession rows are written from the (source, version) pairs, not selected from loom.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 (lightweight DELETE FROM loom.chunks, chunks.delete_versions), so the erased text and author do not remain as retired rows.
  • A metadata edit whose row did not land (any failure _published_anyway does 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.
  • Ingest fails the job with 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_uris read the head and the latest ClickHouse row, and serve the newer version:

  • The head serves a commit that ClickHouse does not have yet.
  • ClickHouse serves a row written by a build that commits no heads. This covers a source written before its namespace had heads, and N-1 during a rolling upgrade or after a rollback.
  • At one version ClickHouse's copy answers. It differs from the head only by a stamp made in place, such as N-1's erasure tombstone or an erased original.

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 NOTHING back 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_PENDING as done, since the write committed: the source sync (a written file, a retired document), a learning's promotion to knowledge or through memory.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. A knowledge.update_metadata with reindex=true whose row answers PUBLICATION_PENDING still 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 and loom rechunk rewrite 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 (409 PRECONDITION_FAILED, its chunks cleaned up) instead of the older content replacing the newer write. Under the ClickHouse authority over is 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 from loom.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, is server/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_delete tombstones every listed live document, chunks or none, as knowledge.delete does; 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_delivery takes deliveries whose lease ran out with FOR UPDATE SKIP LOCKED under 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 the pg_delivery_* settings, its claims leased for LOOM_PG_DELIVERY_LEASE_SECONDS as the memory worker's are. The lease ending before a publish starts (leased refuses 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, an INSERT … 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's superseded_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's INSERT … SELECT), at most LOOM_PG_DELIVERY_BATCH_ROWS deliveries a pass within one LOOM_PG_DELIVERY_LEASE_SECONDS lease (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.

  • Only a refusal counts an attempt, judged by the retirement's own error when the row went in and the retirement failed. An unavailable ClickHouse (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.
  • At LOOM_PG_DELIVERY_MAX_ATTEMPTS the delivery is parked and counted in postgres.parked_knowledge_deliveries.
  • The pass also sweeps deletion evidence older than LOOM_PG_ERASURE_EVIDENCE_HOURS.

Erasure. A new saga step pg_knowledge.delete runs after pg_memory.delete, only under the Postgres authority, built like pg_memory.delete. It runs on a dedicated connection, retries on a deadlock, and works in one transaction:

  1. It takes each namespace's document lock alone (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 waits LOOM_PG_COMMIT_LOCK_TIMEOUT_MS and answers 503, so a scope with a long ClickHouse history holds them for its whole evidence read.
  2. It locks the heads in key order, then deletes the deliveries and heads.
  3. It keeps, in loom.erased_documents (no content) for LOOM_PG_ERASURE_EVIDENCE_HOURS, the doc_id of 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 plain source_uri >= bound the key analysis uses to skip earlier granules (checked with EXPLAIN indexes = 1: the tuple comparison alone does not narrow the key range), with sequential consistency, each page inserted as it arrives.
  4. It waits out the removed leases, and an earlier run's (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: a SET LOCAL of 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 its fenced_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 kept settled, 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 own user_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 the doc_id of 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 with DocumentErased (404). The check is read after the heads' locks the erasure holds. Heads and deliveries are in PG_CENSUS and the residue census, and in PG_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 in PG_NO_MEMORY_CONTENT and 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 pass over, and its unit test pins the write-back's over. 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 answers PUBLICATION_PENDING is 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 the doc_id evidence (the restored row keeps it), and one committing before is removed by that step.

PublicationPending moved from server/memory/store/pg_memory.py to server/core/pg_lease.py, with lease_deadline, check_lease and leased. 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:

  • Keep ClickHouse as the commit point with a KeeperMap claim on every text write. This was rejected because a claim has no fencing token, so a writer whose claim lapsed can still publish over a newer one.
  • Store only (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.
  • Gate head writes on the whole fleet running this build (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

  • Under the ClickHouse authority the funnel inserts the row, then retires older chunks. What changes there:
    • knowledge.upsert, knowledge.add and knowledge.bulk_add insert their chunks before the document rows. Upsert and bulk add used to insert them after; add used to insert both at once.
    • knowledge.delete and knowledge.bulk_delete retire 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.
    • The retirement is stamped by the row (a tombstone's superseded_at, or ClickHouse's now()) instead of the request's clock. Each write's retirement is one statement (mark_docs_superseded now 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's chunks_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 answers deleted=False), and one INSERT … SELECT; a claim not held answers a retryable 503 with nothing written, and a source restored meanwhile answers as not deleted. knowledge.delete and knowledge.bulk_delete run every read sequentially consistent, as knowledge.restore does, so a delete right after a restore sees it on any replica. A bulk_delete batch 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 than LOOM_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's time_ns stamp, and answers how many it retired (main retired every chunk); knowledge.upsert, knowledge.add and knowledge.bulk_add now 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.
    • A delete of a source whose latest row is already a tombstone retires only the chunk versions up to that tombstone. Previously it retired every chunk, including those of a write that had inserted chunks and not yet committed.
    • A retirement that fails after the row is in answers 503 BACKEND_UNAVAILABLE (OlderNotRetired), and a repeat of the write runs it again.
  • Concurrency: a knowledge write now takes a Postgres row lock per source for the length of one small transaction, with the authority's pg_commit_lock_timeout_ms.
  • A source URI or writer's id Postgres cannot store has no head: such a document is read from ClickHouse and never sent to Postgres, and any write of it (a delete, a metadata edit, a restore included) is refused (422), so only an erasure removes it. A knowledge.bulk_add checks every entry's key columns before it embeds any.
  • knowledge.bulk_add refuses a batch that names a source URI twice (422 VALIDATION_FAILED, nothing written). On main both entries were written with one revision number, and a commit holds one row per source (pg_documents.commit refuses a repeat), so the handler refuses the batch before it writes anything. A caller sends the last entry for each source.
  • Under the Postgres authority the retention TTL on loom.documents (LOOM_RETENTION_DOCUMENTS_DAYS, a namespace's retention_days) is not applied, as for loom.memory: it would delete ClickHouse's copy and leave the text in the head. The boot refuses LOOM_RETENTION_DOCUMENTS_DAYS beside the two memory retention settings. A namespace's retention_days leaves loom.chunks too, so a live document keeps the chunks search finds it by; LOOM_RETENTION_CHUNKS_DAYS, set alone, expires chunks alone under either authority.
  • Reads under the Postgres authority add one Postgres primary-key read beside the ClickHouse read they already made. The read that drops a head ClickHouse no longer holds rests on a sequentially consistent read: exact on ClickHouse Cloud and a single server, and on a self-hosted replicated cluster only with every Loom process sent to one replica. So does a knowledge delete's re-read after a restore, under either authority. loom doctor's replica_consistency line now also watches loom.documents, under either authority, and clickhouse.md lists both guarantees.
  • Left for the next PRs of Search documents and query tables across office, code and data files #157: knowledge.search / outline validation against heads (live_versions still reads ClickHouse), ingest jobs and cancels in Postgres, and datasets in the head transaction. Other readers that still decide from loom.documents alone, 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.
  • The originals sweep and a user erasure's shared-originals check do read the owed commits: both keep an original a live document of an unpublished commit names.
  • Erasure:
    • An erasure run by N-1 during a rollout leaves heads, which the first read deletes instead of serving. It also leaves deliveries still owed or parked, which N's worker would publish again. Rule 38 and the parked-delivery runbook say to run those erasures again with N once N-1 stops serving, before retrying a parked delivery.
    • A source written before its namespace had heads has no head to lock. A write of it racing an erasure is the race it is under the ClickHouse authority.

Compatibility, rollout and rollback

  • Wire: additive, with one break under either authority: knowledge.bulk_add refuses a batch that repeats a source_uri with 422 VALIDATION_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_delete and knowledge.update_metadata can answer the following under the Postgres authority:
      • 409 PRECONDITION_FAILED: another write of the source committed first.
      • 404 RESOURCE_NOT_FOUND: the document the write read was erased since.
      • 503 PUBLICATION_PENDING: the write is committed and the worker publishes it.
      • knowledge.restore can answer 409 PRECONDITION_FAILED when another write took the source during its write-back, and 503 BACKEND_UNAVAILABLE when a committed write-back was taken back. An erasure that refused its write-back answers not_restorable, as any erasure does.
      • 422 VALIDATION_FAILED for a source URI or a writer's id holding a NUL character or a lone surrogate, which a Postgres key column cannot store. knowledge.ingest answers it 422 before queueing the job; only a job an older build queued fails unstorable_text. Any other text, a document's content or title included, is accepted and kept exactly.
    • GET /v1/health?include=postgres gains postgres.parked_knowledge_deliveries.
    • A new setting, 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.
    • A new setting, LOOM_PG_ERASURE_EVIDENCE_PAGE_ROWS (default 10,000): the document ids an erasure reads and keeps per page.
  • Break: under the Postgres authority the server refuses to start with LOOM_RETENTION_DOCUMENTS_DAYS set, and a namespace's retention_days puts no TTL on loom.documents or loom.chunks (a TTL left on them is removed). Unset the setting before the rollout (upgrade step 2).
  • Operator steps: after a rollout from a build without knowledge heads, and after a roll forward that follows a rollback, run again every erasure that completed while an older replica served. An older build's erasure removes no head or delivery, so an erased document's text stays in loom.knowledge_heads until then. This is step 11 of the upgrade procedure (docs/operations/upgrades.md) and rule 38. Before the rollout, unset LOOM_RETENTION_DOCUMENTS_DAYS (step 2). Otherwise none: the Postgres migration applies at boot under the advisory lock, and docs/operations/postgres.md gives the statement that retries a parked document delivery.
  • Rolling upgrade: N-1 writes loom.documents alone, and N serves the newer of the two and adopts the newer row on the next commit. See rule 38 in docs/architecture/rolling-upgrades.md.
  • Rollback: the three Postgres tables stay.
  • The delivery insert has no 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

  • New 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:
    • Each upsert is the head and its ClickHouse row, with revision 2.
    • The old text is gone from search.
    • No delivery is left.
    • A delete is a deleted head that knowledge.get does not find.
    • A commit over a version its writer did not read is refused, and the head is unchanged.
    • A source with no head is read from ClickHouse and adopted by its next write.
    • A delivery its request left is published by the worker.
    • A newer row written by a build without heads is served and then adopted with revision 3.
    • A source erased by such a build is not served from its head, and can be written again.
    • A namespace erasure leaves no heads or deliveries, and pg_knowledge.delete counts at least 3 rows.
    • Of two concurrent first commits of a source, exactly one lands.
    • An erasure over a parked delivery completes on Postgres 16 (the step used to fail there, subtracting now() from 'infinity').
    • An erasure's wait covers the send that just parked a delivery (fenced_until).
    • An erasure waits for the request a worker's takeover replaced, and not for a delivery its own request finished.
    • A user erasure waits for that user's taken-over publication after another user's write took the head.
    • A tombstone built from a version a later write replaced before an erasure is refused, and a write after the erasure commits (the replaced version sits in an earlier month's partition, so no merge folds it away first).
    • A write after an erasure whose head was never published commits.
    • A settled delivery does not keep a head whose row an older build purged.
    • A taken-over, settled delete counts as a publication that may still land until the insert bound has passed.
    • A NUL in a document's title and content is served as written, and the document deletes.
    • test_knowledge_restore.py passes under the Postgres authority, and the CI job now runs it.
    • A write built from a read made before the erasure is refused with 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.
    • An upsert carrying the author of a document an erasure recorded answers 404 and deletes the chunk rows it inserted; only the first write's chunk version stays in loom.chunks.
    • A tombstone an older build stamped in place (ALTER … UPDATE superseded_at) hides the head that is still live.
    • A user-scope erasure removes that user's heads and deliveries in every namespace and keeps the other user's.
    • A settled delivery holds no original, and a live row with an artifact and no original keeps the artifact.
    • An unpublished commit's original survives a sweep and is kept from another user's erasure until its delivery is published; a pending delete of it then holds nothing, and the sweep removes it.
    • An older build's user purge that deletes the head's version and stamps another writer's older row deleted: the head is dropped and the document reads as deleted.
  • CI: the integration-postgres job now also runs test_knowledge_pg_heads.py, test_knowledge.py, _upsert, _delete, _restore, _bulk, _bulk_delete, _get, _ingest_queue and _sharing.
  • Unit:
    • tests/unit/test_knowledge_pg_delivery.py (new):
      • Publish and complete under the token, including the retire bit.
      • One refusal holds back only itself, and the third refusal parks it.
      • ClickHouse unavailable, during the row or during the retirement, counts no attempt and releases the rest.
      • A refused retirement counts.
      • Claims whose lease is ending are released unpublished.
      • A send the lease's end cut off (a late send while ClickHouse answers) counts an attempt and parks at the limit.
      • The worker is idle under the ClickHouse authority, and its registry row is checked.
    • tests/unit/test_documents_repo.py:
      • A cancel during the publication after a commit carries the may-have-committed mark under both authorities.
      • The newer of head and ClickHouse answers (5 cases), and a newer deleted row hides a live head.
      • A head ClickHouse lost serves only while owed.
      • A lagging replica never drops a head: the sequentially consistent read finds the row.
      • A job's commit not yet published counts as published.
      • A published head over an older ClickHouse row that the confirming read also shows is dropped.
      • A Postgres failure clearing the delivery after the publish answers 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's DateTime does.
    • tests/unit/test_knowledge_dedup.py:
      • When another write moved the head, knowledge.upsert and knowledge.add retire their own chunk version and raise. Both name a live prior's doc_id as built_from, and name none for a deleted prior.
      • knowledge.bulk_add inserts its chunks before its commit, keeps them when the commit answers PUBLICATION_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.
      • A failed cleanup keeps the write's own 409. An add whose chunks fail commits no document. A bulk add is refused before it embeds anything. An erased write's chunks are deleted even when their retirement fails. A bulk add naming a source twice is refused before any write. A bulk add over a prior stamped ahead of this host's clock stamps past it. An upsert always retires older chunks, even when its count saw none: a count taken before the prior read could miss a write committed since. A chunk insert that timed out or was cancelled is retired (upsert, add, bulk add). A cancelled upsert retires its chunks unless its commit was sent.
      • A rewrite commits over the version its caller read, else over the upsert's own read.
    • tests/unit/test_document_row_builder.py:
      • A delete's first reads are sequentially consistent; a bulk delete counts a source restored meanwhile as 0, retires nothing of it and keeps its datasets.
      • A repeated delete of a deleted source stamps its leftovers at that delete, as the tombstone's own (possibly owed) retirement would, so restore still finds it, under the source's claim; a source restored meanwhile keeps its chunks. A delete of a source with no document row retires only its chunks older than the orphan age, so a first write still to commit keeps its own.
      • The bulk ops commit over what they read: a bulk add names the live priors it carries columns from, and a bulk delete's tombstones retire their sources.
      • A delete left to the delivery worker forgets its datasets. A live document's delete always retires older chunks, even when its count saw none.
      • A bulk delete tombstones a live document that holds no chunks.
      • A claim another write holds answers a retryable 503 naming the op, for both deletes, with nothing retired. An orphan age set below an ingest pass is raised to it plus the skew margin.
      • A delete and a bulk delete of a deleted source retire only up to its tombstone; a source with no document row loses, and counts, only chunks older than the orphan age, so a first write's young chunks stay live and a source with only those answers not deleted.
      • A metadata edit whose row answers PUBLICATION_PENDING still 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.commit against a fake connection, covering:
      • a head replaced over the version read, or adopted when it is behind;
      • a row not above the head and the version read refused;
      • the locks bound to the commit's org, namespace and sorted sources;
      • a head refused when it moved past the version read;
      • the second of two first commits refused;
      • a write built from an erased document refused, by its own id and its 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:
      • A full Postgres outage leaves a due job pending with no attempt counted. A key Postgres cannot store is refused at submit.
      • A NUL in a job's source URI fails it unstorable_text with no chunk written.
      • A Postgres error whose outcome is unknown leaves the job processing and is settled by the next run, as a timed-out insert is. One that committed nothing retries the job. A job whose prior was written by a host whose clock runs ahead publishes above it. This replaces 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 answered PUBLICATION_PENDING is undone and answers a retryable 503. A restore waits while the delete is still being published. A write-back an erasure refused answers not_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_deadlocks and _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 in needed.
    • 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_superseded binds each source's bound in one statement.
    • The World fake in test_knowledge_ingest.py now 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 counts PUBLICATION_PENDING as rechunked.
    • tests/unit/test_knowledge_source_sync.py, tests/unit/test_learnings_dual_destination.py, tests/unit/test_import_recall.py: PUBLICATION_PENDING counts as done (a written file, a retired document, a promotion through memory.set or 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's retention_days leaves chunks, and a TTL left on loom.documents is removed; tests/unit/test_pg_authority.py: the boot refuses the three retention settings.
    • tests/unit/test_doctor_replica_consistency.py: documents is watched under either authority.
  • pytest tests/analyzer passes against a migrated ClickHouse after python -m tests.analyzer.corpus --write. The regenerated shapes.txt has this PR's changes: the two document reads it removes, the reworked bulk retirement, the two erasure evidence reads, the bounded count_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 typecheck and the full unit suite pass on this head, rebased onto main (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 of parked_knowledge_deliveries in GET /v1/health?include=postgres), test_knowledge_bulk_delete.py, test_erasure.py and test_erasure_user_originals_shared.py pass. test_erasure_summary_derived_live_ch.py passes under the ClickHouse authority; one of its tests fails under the Postgres authority on main too (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 typecheck and make test-unit pass; the integration suite passes if server behaviour changed.
  • Generated files are regenerated in this PR, not by hand: the SDK op tables, docs/reference/configuration.md and the docs/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).
  • A new migration is additive and numbered after the latest on main; no merged migration is edited.
  • A behaviour change to any file a plugin ships (hooks/, lib/, bin/, skills/, .mcp.json, the Codex plugin-defaults.json) bumps both plugin manifests' version, and no other open PR uses that version.
  • The frontend builds (npm --prefix frontend run build) and its tests pass, if frontend/ changed.
  • 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; the history goes in this description (tests/unit/test_public_copy.py).
  • Commits are signed off (git commit -s), as CONTRIBUTING.md asks.

🤖 Generated with Claude Code

@zlareb1
zlareb1 force-pushed the feat/knowledge-pg-heads branch 3 times, most recently from 1a92cb5 to 09d1c8d Compare November 9, 2026 04:14
…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
zlareb1 force-pushed the feat/knowledge-pg-heads branch from b038c8c to b3d49d6 Compare November 9, 2026 05:34
… among the maintenance indexes

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: zlareb1 <[email protected]>
@zlareb1
zlareb1 merged commit 241057d into main Nov 9, 2026
35 of 37 checks passed
@zlareb1
zlareb1 deleted the feat/knowledge-pg-heads branch November 9, 2026 05:58
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