Skip to content

Under Postgres, knowledge ingestion jobs live in loom.knowledge_jobs, each save fenced by its run's token - #447

Merged
zlareb1 merged 1 commit into
mainfrom
feat/knowledge-pg-jobs
Nov 10, 2026
Merged

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

Conversation

@zlareb1

@zlareb1 zlareb1 commented Nov 9, 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, 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 ReplacingMergeTree rows in loom.knowledge_ingestions, and that left three problems:

  • A status or cancel read and the worker's re-read under the lease depended on the replica being caught up (sequential_reads, own_write_reads).
  • A run whose job lease lapsed while it ran could still write versions over the run that took the job.
  • A cancel reached the worker through a second ClickHouse table, so the "read the job again after the cancel" guarantee also depended on replica freshness.

This PR moves the job into Postgres as the authority:

  • loom.knowledge_jobs (Postgres migration 005_knowledge_jobs.sql) holds one row per job. The row is the complete loom.knowledge_ingestions row, revised in place, with the queue's columns beside it.

  • Commit and reads. knowledge.ingest commits the job. knowledge.ingest_status and knowledge.ingest_cancel read it, and the worker's queue reads the table with the same rules as ingestions.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:

    • another token means another run took the job, so this run stops with LeaseLost;
    • no row means an erasure deleted the job, so it stops with 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_unpublished before 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 by lease.held, as under ClickHouse.

  • Projection. Once a version commits, it is also inserted into loom.knowledge_ingestions, which reports, knowledge.inspect and 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_at on the job. It is also written to loom.knowledge_ingest_cancels with who asked, as before, because a build that predates the table reads only that.

  • Erasure. pg_knowledge.delete deletes 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_jobs gets a PG_CENSUS row and joins PG_IN_USE_TABLES. ClickHouse keeps the erased job until documents.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.adopt only 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_rows at a time, to match loom.knowledge_ingestions' TTL. It runs whether or not the ingest worker runs, since knowledge.ingest commits 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_row now builds its three times to the millisecond, as DateTime64(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 in test_knowledge_inspect_ingest.py.

Alternatives considered:

  • A Postgres lease with its own 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.
  • Fencing by compare-and-set on the job's version. Rejected: several error paths save with a copy of the job taken before the last save (_publish reassigns its local job), so they would be refused as if another run held the job.
  • Projecting inside the save's transaction, before the commit. This was the first version of this PR, and it was dropped for three reasons:
    • Postgres's idle-in-transaction timeout (twice 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;
    • a failed commit left a pending job in ClickHouse that ran although knowledge.ingest answered 503;
    • a worker could read the job from ClickHouse before Postgres committed it.

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_source and dataset approvals.

The ClickHouse authority's path changes in three small ways:

  • ingestion_row builds its times to the millisecond, which is what DateTime64(3) stores anyway;
  • ingestions.due and older_open skip 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.due breaks 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) and ingestions.older_open use the same order, and knowledge.inspect leaves 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:

  • A projection that does not land leaves loom.knowledge_ingestions one 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 fails original_gone.
  • In an erasure, a projection that lands after documents.tombstone (an insert that timed out and landed late) is found by the residue census, and the saga runs again.
  • Under Postgres, the ingest ops answer 503 POSTGRES_UNAVAILABLE when Postgres cannot be reached. Before this PR, knowledge.ingest accepted the job anyway. docs/operations/postgres.md says 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:

    • N's status and cancel read the newer version of the two stores;
    • N's queue interleaves its own due jobs with ClickHouse's, the two leading in turn from one pass to the next;
    • a job N-1 queued (only ClickHouse holds it) runs in ClickHouse alone, as N-1 runs it;
    • a run of a job Postgres holds first takes ClickHouse's version when it is the newer;
    • that run also waits while an earlier open job of its source exists (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;
    • cancels go to both stores, and the deployment-wide lease alone keeps the two builds' runs apart: N-1 does not raise lease_token, so the token fences an N run only against a later N taker;
    • N-1's erasure leaves the scope's Postgres jobs, which N would project back and run, so it is run again with N (upgrade step 12).

    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_ingestions too, so N-1 serves and runs them. The loom.knowledge_jobs table 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 003 and 004, so this PR's file is 005_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 on main 574bc91.

Tests

  • Unit (tests/unit/test_knowledge_ingest.py): the test world now fakes pg_jobs (with a projection that can be made to fail), and nineteen new tests cover:

    • a job under Postgres committed, run and projected;
    • a run whose job another run took saving nothing after its first save;
    • a run that lost its job after the taker recorded a chunk version, whose transient failure retires nothing of it;
    • a job only ClickHouse holds run there, never inserted into Postgres;
    • a job waiting behind an earlier one only ClickHouse holds;
    • a job waiting behind an earlier one whose projection never landed;
    • a full page of earlier ClickHouse jobs, all held in Postgres, waited for, and a page that is not full read through;
    • an ended job whose last projection was lost, which is repaired on its next offer and blocks nothing;
    • an older build's newer ended version read and not run again;
    • an older build's newer open version adopted and run under a new token;
    • an open held job that ClickHouse is behind on, projected again before it runs;
    • a job only ClickHouse holds waiting for an earlier one Postgres holds, whose projection did not land;
    • a cancel marking both stores;
    • a cancel the older build wrote stopping the run;
    • the two queues interleaved, leading in turn;
    • no earlier-job read sent for a source URI Postgres cannot store (an older build's job), which would otherwise fail every pass;
    • an expired job (30 days unsaved, ClickHouse's rows dropped) neither run nor projected back;
    • a JSON round trip with text Postgres cannot store and millisecond times;
    • a projection whose ClickHouse insert fails: insert returns and save answers saved, 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.py adds one: the delivery pass expires old jobs, bounded by its batch, and reports how many. tests/unit/test_document_object_store.py checks that both owed-originals reads include OPEN_JOB.

  • Integration, against a server and pytest process with LOOM_STORAGE_AUTHORITY=postgres on their own ClickHouse and Postgres:

    • tests/integration/test_knowledge_pg_jobs.py (new, 15 tests) covers:

      • the token fence on a real row and its projection compared column by column;
      • a cancel;
      • adoption that updates only a held job at an older version;
      • the queue's one-source-at-a-time and stale-run rules, under the job's lease so the server's worker cannot take it;
      • the erasure step deleting the jobs (then save answers gone), for a namespace and for a user (the user's jobs alone, with the user-scope residue at 0);
      • a run between the erasure's Postgres step and documents.tombstone reading the job from ClickHouse with Postgres still empty;
      • the 30-day expiry (31 days deleted, 29 kept, whichever pass expires it), and an expired job neither offered as its source's head nor waited on by a later one;
      • older_open on real rows;
      • an open job's original in owed_originals and an ended job's not;
      • the queue's namespace fairness (never served first) and a stale run before a pending job;
      • pg_jobs.earlier_open and held_ids on real rows;
      • a take that skips, at once, a job whose row another transaction (an erasure) holds;
      • the user erasure's _others_owed_originals on 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*.py and test_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_ch erasure 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 main 574bc91): make format, make lint and make typecheck pass. 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 on main ed15038 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 through 005, test_knowledge*.py, test_erasure*.py, test_ingest*.py and test_document*.py give 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 on main. 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 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-jobs branch 9 times, most recently from d2be9d6 to 07ce7ed Compare November 10, 2026 02:34
… 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
zlareb1 force-pushed the feat/knowledge-pg-jobs branch from 07ce7ed to 589c184 Compare November 10, 2026 03:22
@zlareb1
zlareb1 merged commit bef518b into main Nov 10, 2026
21 checks passed
@zlareb1
zlareb1 deleted the feat/knowledge-pg-jobs branch November 10, 2026 03:22
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