Skip to content

Under the Postgres authority knowledge search serves only the chunks each document's head serves - #441

Merged
zlareb1 merged 1 commit into
mainfrom
feat/knowledge-pg-search
Nov 9, 2026
Merged

zlareb1 merged 1 commit into
mainfrom
feat/knowledge-pg-search

Conversation

@zlareb1

@zlareb1 zlareb1 commented Nov 9, 2026 •

Copy link
Copy Markdown
Member

Related: #157
Related: #405

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.search, knowledge.outline, knowledge.synthesize and memory.stack serve only the chunks of each document's current version (a document written before its namespace had heads keeps serving every version ClickHouse holds): an older version still being retired, a deleted document whose delete is not yet published, and a write that has not committed are left out, and knowledge.search counts them in a new stale_dropped field. Under that authority knowledge.add and knowledge.bulk_add retire a source's earlier chunk versions, as knowledge.upsert does.

Why

#405 made Postgres the authority for each knowledge document's current version (its head), but search still read loom.chunks alone. ClickHouse reads a chunk as live until something retires it, so under the Postgres authority it also serves:

  • the older version's chunks while the new version's retirement of them is still owed (a request stopped after its commit, or a delivery the worker has not published yet);
  • a deleted document's chunks while its tombstone is owed;
  • the chunks a write inserted before its commit: one still to commit, one refused (409), or one whose cleanup failed, which then served forever.

This PR has search ask the head which chunks it serves, as memory.search already asks the memory heads. It is the second PR of #157's Postgres work (P11b in the issue's plan).

Design. A head records which chunks it serves. Postgres migration 004_knowledge_chunk_heads.sql adds two nullable columns to loom.knowledge_heads: chunks_revision and chunks_version.

  • A commit whose write inserted chunks sets them to its own row's revision and version. These are the add, upsert, bulk add and ingest publish commits, and the commit path's new chunked argument marks them.
  • Any other commit leaves them as they are (COALESCE in the update): a delete, a metadata edit without reindex, or a restore.
  • A first head written by such a commit leaves them NULL.

A chunk of revision r at version v is served when:

  • its source has no head (a document written before its namespace had heads), or
  • the head is not deleted, r is the head's revision, and, while chunks_revision is that revision, v is chunks_version (server/knowledge/domain/serving.py).

The version tells apart two writes that numbered the same revision, where the second was refused. A chunk that recorded no revision (r = 0) is judged by its version alone while chunks_revision is the head's revision, and served otherwise.

Alternatives considered:

  • Infer the chunk version from the commit that changed the revision. Wrong for documents written before heads existed. Their first head can come from a delete or a metadata edit, whose row version is not their chunks' version, so every hit of the document would be dropped.
  • Judge by revision alone. Serves a refused writer's chunks, which carry the winner's revision number, until their cleanup lands, and forever when the cleanup fails.
  • Add a chunk-version column to loom.documents. A ClickHouse migration, a value N-1 would have to write, and still no answer for the chunks of a write that has not committed.

Reads.

  • pg_documents.serving reads the heads of a page's (namespace, source_uri) pairs in one unnest join.
  • knowledge.search checks each search pass (one statement over every namespace it reads, judged in one Postgres read) before it reranks, collapses sections or cuts the page. A full page that left a candidate out (a stale one, or a second served version of one chunk) is fetched once more, twice as deep (pg_serving.served_search), and stale_dropped counts the stale ones.
  • Every search leg now selects doc_version; under the Postgres authority fusion keys a chunk by it (below).
  • knowledge.outline and document_reads.document_chunks (read by knowledge.synthesize and loom decisions extract) take the same check, and so does memory.stack's knowledge section (server/memory/app/stack.py), whose search callable refills the same way. context.pack and memory.ask read through knowledge.search.
  • knowledge.get already serves the head (Under the Postgres authority each knowledge document's head is committed in Postgres over the version its writer read #405).
  • Without the Postgres authority, none of these reads Postgres or drops anything.

Scope and risk

  • Under the Postgres authority only. Under the ClickHouse authority every path is unchanged: pg_serving.stale returns all-False without a read, keep_served returns every row of the outline and document_chunks without a read, and fusion merges as before.
  • Behaviour change. Under the Postgres authority, knowledge.add and knowledge.bulk_add retire the source's older chunk versions (retire_older), as knowledge.upsert does, a first write's included (a failed write may have left chunks behind): search serves the head's version alone, so keeping them would leave chunks nothing serves, and they would crowd every page as stale candidates (the refill fetches once, twice as deep). This matches what knowledge.get already serves. Under the ClickHouse authority an add again keeps them, both served, as before.
  • Fusion under the Postgres authority keys a chunk by its version too (fuse_rrf(by_version=...)), so the check sees the stale and the served version of one chunk as two candidates; a merged one would show one version's text under the other's identity. The page then keeps one hit per chunk, the best ranked, when two versions of one chunk are both served (a source with no head, or a head whose recorded chunks belong to an earlier revision) (served_search), and a version left out that way counts toward the refill. The reranker shows each hit its own chunk's context (carried on the hit). Under the ClickHouse authority fusion merges as before.
  • Dashboard. The inspect finding mixed_live_versions is labelled "Two live versions" (it was "Two versions served"), and a document's chunk line says "N live versions" (it said "N versions served"): under the Postgres authority search serves one of them. The documents section is headed "Live chunks" (it was "What search serves"), and the Assistant page's subtitle says "live chunks". knowledge.inspect's MCP description, field comments and docstrings say the same.
  • Availability. Under the Postgres authority, a knowledge search, outline or synthesis read that cannot read the heads fails closed with 503 POSTGRES_UNAVAILABLE, as a memory search does; memory.stack leaves its knowledge section out instead, as it does for any knowledge failure.
  • Cost. One Postgres primary-key read per search pass (two when it refills), batched over the page's sources.
  • Not changed:
    • What counts chunks without serving their text still reads every chunk ClickHouse reads as live: knowledge.inspect (the view that shows a retirement still owed), knowledge.list's chunk_count, knowledge.dedup_list and an upsert's duplicate_chunk_count.
    • knowledge.get was already head-backed.
    • Ingest jobs and datasets move to Postgres in the next PRs of Search documents and query tables across office, code and data files #157.

Compatibility, rollout and rollback

  • Wire: additive. knowledge.search gains stale_dropped (int, 0 under the ClickHouse authority). The behaviour change above is named in the changelog entry.
  • Rolling upgrade: rule 39 in docs/architecture/rolling-upgrades.md.
    • N-1 serves every live chunk, as it does today: nothing on main writes chunks_revision or chunks_version.
    • N-1's commits leave the two columns as they were, so once N-1 numbers a new revision, N judges that source by revision alone until the source's next N write that inserts chunks (a delete, a metadata edit or a restore keeps the columns as they are). During that window N also serves a refused writer's chunks of that revision.
    • A head N-1 creates holds no recorded chunks.
  • Operator steps: none. The Postgres migration runs at boot, adding two nullable columns, which is a catalog change only.
  • Rollback: the two columns stay, unread by the older build.

Tests

  • New tests/unit/test_knowledge_serving.py:
    • the serving rule's matrix (no head, deleted, older revision, uncommitted next revision, a refused racer's version, no recorded revision, a head whose recorded chunks belong to an earlier revision);
    • no Postgres read without its authority;
    • one read for a page across namespaces;
    • the refill fetch only after a full page left hits out (stale ones, or a second served version of one chunk, which also counts toward the refill);
    • a search that leaves out the stale version and counts it, in semantic and in hybrid mode (where fusion runs first, so the test fails without the version key);
    • fusion keeping two versions of a chunk apart under the Postgres authority and merging them under the ClickHouse one;
    • a source with no head serving one hit per chunk;
    • the outline and document_chunks showing the head's version only.
    • memory.stack's knowledge section serving the head's version only and fetching again, deeper (it fails when the stack calls the search without the check).
    • a search, an outline and document_chunks (which synthesize reads) whose heads read fails answering POSTGRES_UNAVAILABLE (503), not unchecked chunks.
  • tests/unit/test_knowledge_pg_commit.py: a chunked commit sends its revision and version for a new and an existing head, and another commit sends NULLs (the integration test pins that they keep the recorded chunks).
  • tests/unit/test_knowledge_dedup.py: upsert, add and bulk add pass chunked=True; under the Postgres authority an add and a bulk add pass retire_older, a first write's included, and under the ClickHouse one they do not. tests/unit/test_knowledge_ingest.py: the ingest publish passes chunked=True. tests/unit/test_knowledge_search_service.py: every leg selects doc_version and the hit carries it.
  • tests/integration/test_knowledge_pg_heads.py gains new tests against a Postgres-authority server and its ClickHouse (five functions, two of them run two ways):
    • an older version's retirement owed (its supersession rows removed): search, the outline and document_chunks show the head's version alone, and stale_dropped counts the other;
    • the chunks of a write not committed, both a next revision and a refused racer's version at the head's revision, are not served;
    • a deleted document's chunks while its tombstone is owed are not served;
    • a metadata edit, a delete and a restore keep the head's recorded chunks, and the document is still found;
    • an add or a bulk add again retires the earlier text, and search shows the latest with nothing dropped.
  • tests/integration/test_knowledge_inspect.py builds its two live versions with an add again; under the Postgres authority that now retires the earlier one, so the test removes that version's supersession rows there, the state an older build's add again leaves. CI runs it under the ClickHouse authority, where it is unchanged.
  • At this head, one commit on main d1ec764. Under Postgres, each revision's key, status and redaction live in typed columns that every journal reader but the profile reach matches on #445 merged first with Postgres migration 003_revision_metadata.sql, so this PR's migration is renumbered 004_knowledge_chunk_heads.sql, and the two docs that name it follow; nothing else changed in the rebase (Under Postgres, each revision's key, status and redaction live in typed columns that every journal reader but the profile reach matches on #445's own edits are to memory statements and other sections of storage-authority.md).
  • Before the rebase, at 3102472 (the same change with the migration numbered 003):
    • against a Postgres-authority server (workers off, a test end-user issuer configured), these knowledge integration files passed: heads, knowledge, inspect, upsert, delete, restore, bulk, bulk delete, get, ingest queue, sharing, and the outline, synthesize and stack files (115 tests; one inspect case skipped, it needs a server that enforces auth); then test_knowledge_pg_heads.py (34);
    • the full unit suite: 32214 passed, 23 skipped, 1 xfailed under -n 3 -p randomly;
    • the generators reproduced every generated file with no diff; make format, make lint, make typecheck, the frontend's tests (2268), build and budget passed.
  • The paths that rewrite chunk rows after a model change keep them served: the provider rebuild (Settings → Models & keys) copies every column of loom.chunks (server/insights/app/provider_rebuild_batch.py), so a chunk keeps its doc_version and revision, and loom rechunk writes through knowledge.upsert, which passes chunked=True. Nothing else changes a stored chunk's doc_version or recorded revision: the erasure saga's chunk steps only retire or delete chunks, and a chunk's noise label is written with the chunk and never backfilled.
  • Every caller of the document commit path (documents_repo.insert_one / insert_many) is in writes.py, restore.py and ingest_run.py; each one that inserts chunks passes chunked=True.
  • pytest tests/analyzer passes against a migrated ClickHouse after python -m tests.analyzer.corpus --write. The corpus is unchanged: the search statements only select one more column.

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 serving rule was checked against every writer through the commit path (which ones insert chunks, which keep the revision) and the tests were run against a Postgres-authority server.

  • 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-search branch 4 times, most recently from 7632fdb to d0de4a6 Compare November 9, 2026 12:00
@zlareb1
zlareb1 force-pushed the feat/knowledge-pg-search branch 2 times, most recently from ae24b3f to a815d4b Compare November 9, 2026 21:14
…each document's head serves

Each knowledge head records the revision and version of the last commit that inserted its chunks (pg migration 004). knowledge.search, knowledge.outline, document_chunks and memory.stack keep only the chunks their head serves, refill a short page once, and knowledge.search reports stale_dropped. Under that authority knowledge.add and bulk_add retire older chunk versions, as upsert does.

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-search branch from a815d4b to 7339783 Compare November 9, 2026 23:31
@zlareb1
zlareb1 merged commit dc0d742 into main Nov 9, 2026
21 checks passed
@zlareb1
zlareb1 deleted the feat/knowledge-pg-search branch November 9, 2026 23:31
@zlareb1 zlareb1 mentioned this pull request Nov 12, 2026
3 tasks done
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