Skip to content

Under Postgres, the dataset catalog lives in loom.knowledge_datasets, and an approval commits with the source's head - #465

Merged
zlareb1 merged 6 commits into
mainfrom
feat/knowledge-pg-datasets
Nov 10, 2026
Merged

zlareb1 merged 6 commits into
mainfrom
feat/knowledge-pg-datasets

Conversation

@zlareb1

@zlareb1 zlareb1 commented Nov 10, 2026 •

Copy link
Copy Markdown
Member

Related: #157

Changelog category (leave one):

  • Improvement

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, the knowledge dataset catalog (which snapshot serves each dataset, and its schema approval) is kept in Postgres. knowledge.dataset_approve commits only while the document and snapshot it reviewed still serve.

Why

The issue puts schema approvals and active serving pointers in Postgres. For datasets, both live in one place: the catalog row (loom.datasets, a ReplacingMergeTree(version) row per source, dataset and document version). That row says which snapshot of loom.dataset_rows serves the dataset, and carries its schema and approval.

Under the Postgres authority, document heads, deliveries and ingestion jobs are already in Postgres, but this catalog was still read from ClickHouse. That had two problems:

  • An approval switches a dataset to a new snapshot and deletes the rows of the snapshot it replaced. A read on a replica that had not caught up with that switch could pick the replaced snapshot, whose rows were gone.
  • The approval's recheck before its switch depended on the replica being caught up too.

This PR moves the catalog's authority into Postgres:

  • loom.knowledge_datasets (Postgres migration 007_knowledge_datasets.sql) holds one row per (source, document version, dataset): the complete loom.datasets row, with the snapshot id, version and uploader beside it.
  • Writes. datasets_repo.insert_catalog writes an ingest's publish and a metadata edit's carry; an approval commits through pg_datasets.approve (below) and projects with datasets_repo.project. Under Postgres it commits each row over an older version only, as ReplacingMergeTree(version) decides. Then it inserts the rows that commit wrote into loom.datasets (a row kept out by a newer version is not projected), best effort with a warning when that fails, for a build that predates the table and a rollback to one (the erasure deletes loom.datasets by scope, and counts Postgres's copy through its own census row). A dataset's rows are still written before the catalog row that names them.
  • Reads. Every read of the catalog (datasets_repo.at_version) reads Postgres, and the rows only ClickHouse holds: knowledge.dataset_get, knowledge.query, an approval's read and its recheck under the claim, a publish's and a metadata edit's carry, and a publish's check that no approval landed.
  • Approval. The switch commits in one transaction (pg_datasets.approve) under the namespace's lock that a document commit shares and an erasure holds alone, reading the source's head FOR SHARE. The write lands unless the head has moved past the document version reviewed (a later version, or that version deleted), an erasure removed that document (its doc_id in loom.erased_documents), or a write of the catalog row followed the one the approver read (WHERE version <= <read>); a row Postgres does not hold yet (an older build published it) is inserted. A source with no head (written before its namespace had heads) is approved too. Otherwise the transaction rolls back, so a refusal never waits for the standby, and it answers 409 PRECONDITION_FAILED with nothing written, and the retype's own rows are deleted, as they are when the transaction failed without committing (a lock timeout, a refused connection). A commit whose answer was lost keeps them, since it may have landed (pg.may_have_committed). The source's claim still keeps an approval apart from an ingest's publish, which checks that no approval landed while it ran.
  • Deletes. forget and forget_published remove Postgres's catalog rows first, each in a transaction, so a lost commit answer is outcome_unknown. Then they delete the ClickHouse catalog rows and the snapshots' rows, using the dataset ids Postgres named as well as ClickHouse's, so a lost projection leaves no rows behind. forget_published also keeps the snapshots Postgres's later rows serve.
  • Erasure. pg_knowledge.delete deletes the scope's catalog rows together with its heads, deliveries and jobs, the catalog rows last. A user erasure also locks the namespaces holding the catalog rows Postgres holds of the user's (_lock_user_knowledge), so an approval of a headless source's row there waits for it; an approval adding a first Postgres row elsewhere is caught by the residue census. The table gets a PG_CENSUS row and joins PG_IN_USE_TABLES. A publish's catalog write reads its job's Postgres row in the same transaction (pg_datasets.upsert(job=…)): once an erasure deleted the job it writes nothing (JobErased, which the run takes as JobGone), and an erasure that comes after waits for it and deletes what it wrote. A run whose job another run took (the job still held, under a new token) is stopped by its alive check before each catalog write, as the run's reads and saves are, not by this job read. A metadata edit's carry, a publish of a job only ClickHouse holds and an approval of a dataset only ClickHouse held have no Postgres row to read; one landing during the erasure is found by the residue census and the saga runs again.
  • Restore. A dataset's rows stay in ClickHouse alone, while its catalog row is now in Postgres. After a ClickHouse restore, a dataset whose rows were written after the point (a publish, or an approval that retyped a column) therefore reads with rows missing, where before the restore took its catalog row back too. loom reconcile --restored clickhouse lists, in its dry run too, each source with a catalog row written after its lower bound, to upload and ingest again (pg_datasets.sources_written_since). It filters on the row's version, which is drawn once the snapshot's last rows are inserted; the snapshot id is drawn when the write begins, so a long publish across the point would slip past it. A row an approval or a metadata edit wrote over surviving rows is named too. docs/operations/backup-and-recovery.md adds the step to both restore procedures, and names the ingestion jobs and the dataset catalog among what Postgres holds.
  • Keys Postgres cannot store. A source written before its namespace had heads may hold a source URI or uploader Postgres cannot store: its catalog stays in ClickHouse alone (pg_datasets.storable), read and approved as on main, rather than fail the write.
  • Millisecond times. dataset_row builds its times to the millisecond, as DateTime64(3) keeps them, so a row read from Postgres compares equal to its ClickHouse copy.

Alternatives considered:

  • A serving pointer on the document head (one column of loom.knowledge_heads), with the catalog left in ClickHouse. Rejected: an approval changes a dataset's schema and snapshot without a new document version. The head would then hold a copy of every dataset's catalog row, and knowledge_heads would be rewritten for a schema change.
  • Dropping the source's claim from the approval and checking everything in the Postgres transaction. Rejected for this PR. An ingest's publish checks for an approval before its head commit, and with no claim an approval landing between that check and the commit would be lost. Moving that check into the head commit is a change to the commit funnel itself.

Also corrected: docs/operations/postgres.md said knowledge.search and knowledge.query keep serving during a Postgres outage. Search fails closed under this authority since the heads check was added, and knowledge.query now reads the catalog there.

Scope and risk

This PR touches the dataset catalog's store, the approval's switch, a publish's catalog write (fenced on its Postgres job), the Postgres knowledge erasure step and its census, and the output of loom reconcile --restored clickhouse. It leaves alone:

  • the dataset rows (loom.dataset_rows), which stay in ClickHouse: written once per snapshot and never revised;
  • the ClickHouse authority's path, unchanged apart from dataset_row's millisecond times, which is what DateTime64(3) stores anyway.

Risks:

  • A projection that does not land leaves loom.datasets one version behind until the row's next write. Reads under Postgres go to Postgres. An older build reads the lagging version meanwhile.
  • Every catalog read under Postgres adds one Postgres read beside the ClickHouse read it already made (knowledge.query makes two per dataset). The ClickHouse read stays as it was, not sequentially consistent: a row an older build wrote that a replica has not caught up with is served on its next read; until then Postgres's older row serves, so a dataset the older build retyped can read empty for that window, and an approval over it still outranks it.
  • knowledge.dataset_get, knowledge.dataset_approve and knowledge.query answer 503 POSTGRES_UNAVAILABLE when Postgres cannot be reached under this authority. docs/operations/postgres.md says so.

Compatibility, rollout and rollback

Tests

  • Unit:
    • tests/unit/test_knowledge_datasets.py adds eight cases under Postgres:
      • a commit over the snapshot reviewed, then projected, with the replaced rows deleted;
      • a head or snapshot that moved, which writes and projects nothing and deletes only the retype's own rows;
      • a dataset whose keys Postgres cannot store, approved in ClickHouse alone;
      • a commit whose answer was lost, which keeps its rows;
      • a transaction that failed without committing, which drops the retype's rows;
      • a projection that failed, which keeps the replaced snapshot's rows that loom.datasets still names;
      • a publish passing its job only when Postgres holds it, and a JobErased ending the run as JobGone;
      • both catalog writes of a publish (the base row and the typed one) carrying the job.
    • tests/unit/test_knowledge_erasure_pg.py: the knowledge erasure deletes the scope's catalog rows after the jobs, counted in what it removed.
    • tests/unit/test_restore_reconcile.py: a ClickHouse restore prints the sources to ingest again, read from the reconcile's lower bound, and its dry run prints them too.
    • New tests/unit/test_knowledge_pg_datasets.py (13 tests):
      • a write commits to Postgres, then projects, and a row Postgres kept out is not projected;
      • a refused approval (a later head, the reviewed version deleted, the erasure's evidence, a later write of the row) rolls back, and an accepted one commits;
      • pg_datasets.forget deletes in a transaction;
      • a row whose keys Postgres cannot store is written to ClickHouse alone;
      • a publish's job reaches the Postgres write;
      • a catalog row, with and without an approval time, round-trips through the Postgres JSON at millisecond precision;
      • a failed projection leaves the commit and warns;
      • a read takes Postgres's rows and those only ClickHouse holds, newer version winning (Postgres on a tie), in table order;
      • forget deletes Postgres's rows before ClickHouse's and deletes the rows of every dataset either store names;
      • forget_published keeps the snapshots Postgres's later rows serve and deletes the rows of every dataset either store names.
  • Integration, against a server and pytest process with LOOM_STORAGE_AUTHORITY=postgres on their own ClickHouse and Postgres, migrated from empty through 007 (pg_datasets.upsert writes a batch in one statement and returns only the rows it wrote):
    • new tests/integration/test_knowledge_pg_datasets.py (11 tests):
      • a row lands only over an older version, its text kept;
      • an approval commits only over the version of the row it read, while the head serves the version reviewed; it commits over an older Postgres row when the version read is a newer one from ClickHouse, inserts a row Postgres does not hold, and is refused after a later write of the row, a later write of the source and a delete;
      • a source with no head, or a head an older build left behind ClickHouse's row, is approved;
      • the deletes return the datasets they named and the snapshots later rows serve;
      • a user erasure deletes the scope's catalog rows, with the residue at 0;
      • an approval that read before a namespace erasure is refused by the erasure's evidence and writes nothing back;
      • a publish's catalog write after an erasure deleted its job raises and writes nothing;
      • a user erasure's lock covers the namespace of the user's headless catalog row, so an approval there waits for it (the test fails without that);
      • after a ClickHouse restore, the reconcile's read names the source whose catalog row was written after the point though its snapshot id is older, and not one written before it.
    • with the reference extractor configured, test_knowledge_query_live.py and test_knowledge_ingest_live.py give 18 passed. They publish CSV, Parquet and XLSX datasets, approve them over the server and query them. Postgres's statistics for loom.knowledge_datasets showed 47 inserts and 28 updates across that run.
    • test_knowledge*.py, test_*dataset*.py, test_erasure*.py and test_document*.py: 189 passed, 85 skipped. Three memory-plane tests that expect the ClickHouse authority fail, as on main.
  • After the rebase onto Under Postgres, a publisher reads another session's commit durably before sending what it built from it to ClickHouse #456 (a publisher reads another session's commit durably before sending to ClickHouse), pg_datasets is registered in tests/unit/test_pg_durable_reads.py: its writes are each its own transaction; of its two reads, at_version reaches ClickHouse only as part of a write the caller commits, and sources_written_since (the restore reconcile's) only prints the sources to ingest again and sends nothing. Under Postgres, a publisher reads another session's commit durably before sending what it built from it to ClickHouse #456's and this PR's nearest unit files give 805 passed; the catalog, live, jobs and heads integration files give 77 passed.
  • On the current head (rebased onto Under Postgres, loom reconcile runs again in a restored store the erasures and redactions the other records past the restore point #460, Under Postgres, knowledge.inspect counts the ingestion jobs ClickHouse holds at an older version #466, Code-index extractors and PR text read a file in linear time #463, Memory search's key-match arm splits a key at whitespace before stemming it #475 and A tracker source that lacks a feature column reads it as a default, so its PR-file reads no longer fail #477, migration renumbered to 007): make format, make lint and make typecheck pass, and the analyzer shapes check passes, since the ClickHouse statements are unchanged. The overlap's unit files (this PR's, Under Postgres, loom reconcile runs again in a restored store the erasures and redactions the other records past the restore point #460's reconcile and ledger files, Under Postgres, knowledge.inspect counts the ingestion jobs ClickHouse holds at an older version #466's inspect file, the durable-reads inventory, doc links and public copy) pass. Against a server on a ClickHouse and Postgres migrated from empty (Postgres 001–007), test_knowledge_pg_datasets.py, test_knowledge_pg_jobs.py, test_knowledge_pg_heads.py, test_knowledge_ingest_live.py, test_knowledge_query_live.py and test_restore_reconcile.py pass. The full unit suite passes in 16 parts (-n 4 -p randomly, the slow parts split further and test_profile_redaction.py run serially) on the head before Memory search's key-match arm splits a key at whitespace before stemming it #475 and A tracker source that lacks a feature column reads it as a default, so its PR-file reads no longer fail #477, which touch no file of this change or its tests; on the head that merges, the files those two change and this change's nearest files pass.

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 author checks the design against the storage-authority and rolling-upgrade rules and reviews each change.

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

Checklist

  • make format-check, make lint and make typecheck pass, and make test-unit passes in 16 parts (see Tests for the head); 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-datasets branch 9 times, most recently from 4cffacf to deda7f7 Compare November 10, 2026 07:06
@zlareb1
zlareb1 force-pushed the feat/knowledge-pg-datasets branch 2 times, most recently from edefd89 to f2a2236 Compare November 10, 2026 11:10
zlareb1 and others added 6 commits November 10, 2026 13:14
… and an approval commits with the source's head

Every catalog write (an ingest's publish, an approval, a metadata edit's carry) commits
to loom.knowledge_datasets over an older version only, then projects into loom.datasets.
knowledge.dataset_get, knowledge.query and a publish's checks read the catalog there. An
approval commits in the transaction that holds the source's head, only while the head is
the document version reviewed and the catalog still names the snapshot reviewed. Deletes
remove Postgres's catalog rows first; the erasure step and census cover the table. During
a rolling upgrade a read also takes the catalog rows an older build wrote to ClickHouse.

Related: #157

Signed-off-by: zlareb1 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ion, and only rows Postgres wrote are projected

pg_datasets.upsert returns the rows it wrote and insert_catalog projects only
those; approve raises inside its transaction on a refusal so nothing commits and
no standby wait can turn the refusal into a 503; forget deletes inside
pg.transaction so a lost commit answer is outcome_unknown. The durable-reads
inventory and the storage-authority failure table say so.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: zlareb1 <[email protected]>
…ollback is tested

pg_datasets.upsert writes every row through one INSERT ... SELECT FROM unnest
and returns the keys the ON CONFLICT let through, instead of a round trip per
row inside the job's lock. The rollback test covers the erasure-evidence
refusal; the storage-authority failure row and the forget comment read plainly.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: zlareb1 <[email protected]>
…ause

_UPSERT and _APPROVE are built from _INSERT and _ON_CONFLICT, so a column is
named once beside _args; _UPSERT's RETURNING lists the key in _args' order. A
test docstring takes the forget comment's wording.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: zlareb1 <[email protected]>
…taset snapshot the restore lost

A dataset's rows live in ClickHouse alone while its catalog row is in Postgres, so
a snapshot published or approved after the restore point reads with no rows. The
reconcile lists every source whose catalog row names a snapshot written after its
lower bound (a snapshot id is its write time), to upload and ingest again, and the
backup page says so and names the catalog and jobs among what Postgres holds.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: zlareb1 <[email protected]>
… says so in its dry run

A snapshot id is drawn when its rows' write begins, so a long publish across the
restore point slipped past a filter on it; the row's version is drawn after the
last rows land. The dry run prints the sources to ingest again, both restore
procedures carry the step, and the page says rows may be missing, not that none are.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: zlareb1 <[email protected]>
@zlareb1
zlareb1 force-pushed the feat/knowledge-pg-datasets branch from f2a2236 to 7a3b9ad Compare November 10, 2026 13:14
@zlareb1
zlareb1 merged commit 6039dd6 into main Nov 10, 2026
34 of 37 checks passed
@zlareb1
zlareb1 deleted the feat/knowledge-pg-datasets branch November 10, 2026 13:18
@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