Repository navigation
Under Postgres, knowledge ingestion jobs live in loom.knowledge_jobs, each save fenced by its run's token - #447
Merged
Merged
Conversation
zlareb1
force-pushed
the
feat/knowledge-pg-jobs
branch
9 times, most recently
from
November 10, 2026 02:34
d2be9d6 to
07ce7ed
Compare
… each save fenced by its run's token knowledge.ingest commits its job to the Postgres table, and knowledge.ingest_status, ingest_cancel and the ingest worker's queue read it. A run takes its job by raising the job's lease_token, and its reads and saves name that token. Every write commits in a transaction. A best-effort ClickHouse projection into loom.knowledge_ingestions follows each commit, and a run re-projects a job ClickHouse is behind on. The originals sweep and a user erasure's shared-originals check read open jobs from Postgres. The erasure step deletes the scope's jobs, and the knowledge delivery pass expires jobs no run has saved for 30 days. During a rolling upgrade a job only ClickHouse holds runs there, and the two stores' queues interleave. Related: #157 Signed-off-by: zlareb1 <[email protected]> Co-Authored-By: Claude Opus 5.5 <[email protected]>
zlareb1
force-pushed
the
feat/knowledge-pg-jobs
branch
from
November 10, 2026 03:22
07ce7ed to
589c184
Compare
This was referenced Nov 10, 2026
Merged
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 ingestion jobs are kept in Postgres. A job's status and cancel read what was last saved, and a run that lost its job to another worker saves nothing more.
Why
Under the Postgres authority, document heads and their deliveries are already in Postgres. The ingestion jobs that publish documents were still
ReplacingMergeTreerows inloom.knowledge_ingestions, and that left three problems:sequential_reads,own_write_reads).This PR moves the job into Postgres as the authority:
loom.knowledge_jobs(Postgres migration005_knowledge_jobs.sql) holds one row per job. The row is the completeloom.knowledge_ingestionsrow, revised in place, with the queue's columns beside it.Commit and reads.
knowledge.ingestcommits the job.knowledge.ingest_statusandknowledge.ingest_cancelread it, and the worker's queue reads the table with the same rules asingestions.due: one source at a time, oldest first, and namespaces take turns. During a rollout, Postgres's due jobs and ClickHouse's due jobs that Postgres does not offer are interleaved, and the two lists lead in turn from one pass to the next, so neither store's due jobs wait out the other's backlog.Fencing. The deployment-wide lease on the job's id still keeps two runs apart. A take also raises the job's
lease_token. Every read of the job during the run (pg_jobs.read) and every save (UPDATE … WHERE lease_token = $token) names that token:LeaseLost;JobGone.The token is held in a context variable set by
take_and_run, so the stage helpers keep their signatures. Because the reads are fenced too, a stale run's retry or failure path (_retire_unpublishedbefore its_save) stops before it retires the chunk version of the run that took the job. The fence works against a later taker of this build only: a build that predates the table takes the job under the lease alone. Between those reads, a run's chunk and document inserts are guarded bylease.held, as under ClickHouse.Projection. Once a version commits, it is also inserted into
loom.knowledge_ingestions, which reports,knowledge.inspectand an older build read. The insert is best effort, with a warning when it fails: every version carries the whole row, so the next save repairs a version that did not land. An ended job has no next save, so a run that finds ClickHouse behind a held job's version (the queue offers it again from ClickHouse) projects it again and does not run it. A job is therefore never visible in ClickHouse before Postgres holds it. The originals sweep (pg_documents.owed_originals) and a user erasure's shared-originals check (_others_owed_originals) also read the open jobs' originals from Postgres (OPEN_JOB), so a job whose projection has not landed keeps its original.Cancel. A cancel sets
cancel_requested_aton the job. It is also written toloom.knowledge_ingest_cancelswith who asked, as before, because a build that predates the table reads only that.Erasure.
pg_knowledge.deletedeletes the scope's jobs together with its heads and deliveries, last in its transaction, so their row locks are held only to the commit. A take skips a job whose row another transaction holds (EXISTS (… FOR UPDATE SKIP LOCKED)on the key), so an erasure never stalls the queue.loom.knowledge_jobsgets aPG_CENSUSrow and joinsPG_IN_USE_TABLES. ClickHouse keeps the erased job untildocuments.tombstone, about 30 steps later. Until then a run finds it there and runs it in ClickHouse alone, as it did before this PR. Postgres never inserts a job it does not hold (pg_jobs.adoptonly updates), so neither an erasure nor the expiry can be undone and the residue census stays at zero.Durability. Every write to the table (insert, save, take, adopt, cancel) commits in
pg.transaction(), acknowledged as durably as the standby allows. A take's token that a failover lost would hand two runs the same token.Expiry. The knowledge delivery pass deletes jobs no run has saved for 30 days,
pg_delivery_batch_rowsat a time, to matchloom.knowledge_ingestions' TTL. It runs whether or not the ingest worker runs, sinceknowledge.ingestcommits jobs either way. Until the pass reaches it, an expired job is offered by no read: the queue and the earlier-job check skip jobs past the window, and a take leaves one alone rather than projecting it back into ClickHouse, whose TTL has dropped its rows.Millisecond times.
ingestion_rownow builds its three times to the millisecond, asDateTime64(3)keeps them, so a job read from Postgres compares equal to its projection. Without this,take_and_run's "due time moved past the queued row" check read every Postgres job as moved by its sub-millisecond part. That left a retrying job open intest_knowledge_inspect_ingest.py.Alternatives considered:
lease_until, replacing the deployment-wide lease. Rejected: a build that predates the table takes only the deployment-wide lease, so it would still be needed to keep the two builds apart. Given that, the token is all the fencing needs.version. Rejected: several error paths save with a copy of the job taken before the last save (_publishreassigns its localjob), so they would be refused as if another run held the job.LOOM_PG_STATEMENT_TIMEOUT_MS, 10 s by default) is shorter than a ClickHouse insert may take (60 s), so a slow ClickHouse failed every commit;knowledge.ingestanswered 503;Scope and risk
This PR changes the ingest job's store, the three ingest ops, the ingest worker's queue, the Postgres knowledge erasure step and its census. It leaves alone the stages of a run (parse, embed, publish), the source claim,
claim_sourceand dataset approvals.The ClickHouse authority's path changes in three small ways:
ingestion_rowbuilds its times to the millisecond, which is whatDateTime64(3)stores anyway;ingestions.dueandolder_openskip rows older than the table's 30-day TTL, which ClickHouse drops only at a later merge, so neither store's queue offers an expired job.ingestions.duebreaks a tie between two jobs of one source created in the same millisecond by the id's text instead of the UUID.knowledge.inspect's per-source next job (inspect._JOB_KEY) andingestions.older_openuse the same order, andknowledge.inspectleaves out rows past the 30-day TTL (ingestions.UNEXPIRED, in the one job read every count comes from), so every reader agrees on which job runs next.Risks:
loom.knowledge_ingestionsone version behind until the next save. Status reads the newer of the two stores, so Postgres answers. Reports and an older build read the lagging version meanwhile. An older build may also run again a job the newer one ended whose last projection did not land, once that row reads as stale. A published job it finds published; a failed one runs again in full. The newer build repairs the projection when its worker takes the job first. An older build's originals sweep and user erasure read open jobs from ClickHouse alone. So while they run, they may delete the original of a newer-build job whose projection has not landed and whose upload has expired, and that job then failsoriginal_gone.documents.tombstone(an insert that timed out and landed late) is found by the residue census, and the saga runs again.POSTGRES_UNAVAILABLEwhen Postgres cannot be reached. Before this PR,knowledge.ingestaccepted the job anyway.docs/operations/postgres.mdsays so.Compatibility, rollout and rollback
Wire: no op or field changes.
Rolling upgrade (rule 40 in
docs/architecture/rolling-upgrades.md, upgrade step 12): N-1 keeps its jobs in ClickHouse alone. While it serves beside N:ingest_jobs.earlier_open), so a source's jobs still run one at a time, oldest first. Postgres decides for every job it holds (pg_jobs.earlier_open), so a projection that did not land changes nothing; ClickHouse is read only for earlier jobs Postgres does not hold (ingestions.older_open,pg_jobs.held_ids). Ties within one millisecond go by the id's text in both stores' queues;lease_token, so the token fences an N run only against a later N taker;The ClickHouse reads that serve N-1 are removed in a later release, once no N-1 is left.
Same-millisecond ties: under either authority, N-1 and N can pick a different head for two jobs of one source created in the same millisecond, because N-1 orders the tie by UUID and N by text. In that case both builds' workers can run the two jobs at once. It needs two ingests of one source within one millisecond during the rollout.
Operator steps: the Postgres migration runs with the others. Once the newer build serves alone, run again every erasure an older build completed during the rollout (
docs/operations/upgrades.md, step 12). An older build's erasure leaves the scope's jobs in Postgres, and the newer build's worker would project and run an open one. One run per erasure covers step 11 as well.Rollback: jobs N saved are in
loom.knowledge_ingestionstoo, so N-1 serves and runs them. Theloom.knowledge_jobstable stays and is unused.Migration number: Under Postgres, each revision's key, status and redaction live in typed columns that every journal reader but the profile reach matches on #445 and Under the Postgres authority knowledge search serves only the chunks each document's head serves #441 merged first with Postgres migrations
003and004, so this PR's file is005_knowledge_jobs.sql. Its rolling-upgrade rule is 40, after Under the Postgres authority knowledge search serves only the chunks each document's head serves #441's 39. The branch is one commit onmain574bc91.Tests
Unit (
tests/unit/test_knowledge_ingest.py): the test world now fakespg_jobs(with a projection that can be made to fail), and nineteen new tests cover:insertreturns andsaveanswerssaved, with a warning.130 passed.
tests/unit/test_knowledge_erasure_pg.py's connection fake answers a count with 0, as Postgres does.tests/unit/test_knowledge_pg_delivery.pyadds one: the delivery pass expires old jobs, bounded by its batch, and reports how many.tests/unit/test_document_object_store.pychecks that both owed-originals reads includeOPEN_JOB.Integration, against a server and pytest process with
LOOM_STORAGE_AUTHORITY=postgreson their own ClickHouse and Postgres:tests/integration/test_knowledge_pg_jobs.py(new, 15 tests) covers:saveanswersgone), for a namespace and for a user (the user's jobs alone, with the user-scope residue at 0);documents.tombstonereading the job from ClickHouse with Postgres still empty;older_openon real rows;owed_originalsand an ended job's not;pg_jobs.earlier_openandheld_idson real rows;_others_owed_originalson real rows: another writer's open job is kept, and the erased user's own job and an ended job are not.Every test ends the jobs it leaves open in both stores, so the server's worker never runs them later.
test_knowledge*.py,test_erasure*.py,test_ingest*.pyandtest_document*.py: 174 passed and 88 skipped (no extractor declares sql/toml/pdf here). Three memory-plane failures do not touch this PR's files: two*_replicated_cherasure checks and a summary promote, all expecting the ClickHouse authority. On some runs a retrieval-floor test is also refused with 429 by the rate limit.At this head (one commit on
main574bc91):make format,make lintandmake typecheckpass. The full unit suite, run in 16 parts on a loaded host (-n 4 -p randomly, the one part whose tests hang only under parallel workers run serially), passes onmained15038 plus this commit; one code-plane linear-time test (test_code_proto_gotemplate_lanes.py::test_a_file_of_many_messages_parses_in_linear_time) failed under load and passes alone. After the rebase onto Code-index lane walks read a file in linear time #448 (no shared file), Code-index lane walks read a file in linear time #448's 11 unit files with this PR's nearest tests give 1168 passed. Against a Postgres-authority server migrated through005,test_knowledge*.py,test_erasure*.py,test_ingest*.pyandtest_document*.pygive 183 passed, 88 skipped;test_knowledge_restore.py::test_a_purge_landing_between_the_ledger_reads_leaves_no_copy[True]failed in the parallel run and passes alone, and the three memory-plane tests that expect the ClickHouse authority fail as onmain. The analyzer shapes check passes.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,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