Skip to content

Under Postgres, a publisher reads another session's commit durably before sending what it built from it to ClickHouse - #456

Merged
zlareb1 merged 34 commits into
mainfrom
fix/pg-publish-durable-only
Nov 10, 2026
Merged

zlareb1 merged 34 commits into
mainfrom
fix/pg-publish-durable-only

Conversation

@zlareb1

@zlareb1 zlareb1 commented Nov 9, 2026 •

Copy link
Copy Markdown
Member

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in a release)

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 authority, the delivery worker decides a claimed search document from a durable read whenever the key's head is not the claimed revision, a deleted decision's record retirement reads its writers durably, and a knowledge job whose projection lags is sent again only from a durable read, so a failover never leaves ClickHouse with a row, or without one, because of a commit the new primary does not have.

Why

A commit whose synchronous-standby wait is cancelled (a client timeout, a cancel) is committed on the primary alone and visible to every session there. After a failover the new primary never had that revision and reuses its seq. ClickHouse must not keep rows of it.

The delivery claims were already safe: a claim is an UPDATE of the rows it claims, its commit waits for the standbys, the server's statement timeout does not cover that wait (checked on Postgres 16), and a client timeout raises, so nothing claimed is sent. docs/operations/postgres.md said otherwise ("the delivery worker publishes it"), and the integration file now pins the claims' behaviour. Four paths were not safe:

  • a search document built onto a newer copy of the key's head (a pin, a touch, a status), in the delivery worker's _still_heads and the writer flush's _served_documents, sends that head's row, another session's commit, read without a commit of its own;
  • in the delivery worker, a head that is not the claimed revision and not a copy (a newer delete or other content, a redaction in place, an erasure) settles the claimed document unsent; the settling commit runs on another connection, so after a failover it can mark the document done on a primary where the claimed revision is the head again, leaving it unsearchable (the writer flush sends such a document to its stale list instead, which the worker decides again);
  • a deleted decision's record retirement keeps the records of the live decision writers it reads, and retires the others: a writer on the primary alone, deleted again after a failover, or one whose delete is lost, leaves the record wrong;
  • a knowledge job version ClickHouse lacks, projected again by ingest_run._take from a plain read, can be one a cut-off save left on the primary alone; after a failover pg_jobs.adopt brings it back from ClickHouse.

The fix rests on one Postgres fact: a row becomes visible only after its own commit's standby wait has ended, so a later commit that writes WAL and returns from its own wait covers every row its transaction read.

  • The three publisher claims stay single statements: the memory delivery worker's claim_due, the audit outbox's claim_outbox and the knowledge delivery worker's claim_due. Each is an UPDATE of the rows it claims, so its commit waits for the standbys. The server's statement timeout does not cover a commit's standby wait (checked on Postgres 16: an INSERT under a one-second timeout waited for an absent standby until the client gave up), and the client's command timeout raises, so nothing claimed is sent.

  • Some reads after a claim send another session's commit:

    • a newer copy of a head that a search document is built onto, in the worker's _still_heads and the writer flush's _served_documents;
    • the live decision writers a record retirement keeps;
    • and, outside a claim, the knowledge job version ingest_run._take projects again, which it sends only when a durable read (pg_jobs.get(..., durable=True)) returns the same version.

    These are read again in pg.durable_transaction(), and the decision is made from that read. Its last statement writes a transactional logical message (pg_logical_emit_message(true, 'loom.durable', '')), so its COMMIT waits for the standbys although the transaction wrote nothing else (a transaction that only reads, or only takes an xid, writes no WAL and does not wait). The read and the commit share one connection, so a failover in between fails the commit instead of passing on another primary. A writer's flush otherwise sends only its own commits, which already returned from their wait, so the usual flush gains no round trip.

  • A lease already spent before the durable read counts as the send's own, as before (pg_lease.check_lease); one the standby wait itself ended stops the pass as a Postgres outage, releasing the claims uncounted (pg_lease.check_lease_after_durable_read).

  • The window on main is narrow: a publish's own commits before the head read (its claim, its renewal, its rows' completion) each wait for the standbys, so only a copy cut off between the last of them and the head read was sent.

  • Boot refuses a role that may not write the message, checked in a rolled-back transaction so a missing standby does not stall boot, and names the GRANT that fixes it.

  • A durable read on a demoted primary (its logical message cannot take an xid in recovery, SQLSTATE XX000) counts as the read-only outage a write's 25006 is: the pool is expired and the caller gets a 503.

  • pg.transaction() no longer runs SET LOCAL statement_timeout = 0 before its COMMIT: Postgres stops the statement timeout before it commits, so the statement changed nothing and cost a round trip on every write. The integration case for a cut-off commit (outcome_unknown under a one-second timeout) passes without it.

  • Not refused: an empty synchronous_standby_names. A non-strict HA manager empties it when its standby drops, and every commit is then the primary's alone, writes included; refusing only the publishers cost availability without restoring the guarantee. The docs state that the guarantee needs a strict manager, as LOOM_PG_DURABILITY=local already says for its own case.

Rejected alternatives:

  • Comparing pg_current_wal_lsn() with pg_stat_replication.flush_lsn. Read at a pass's start, it misses commits that become visible before the claim. It also reimplements FIRST n / ANY n counting, reads NULL for roles that cannot see pg_stat_replication, and has to poll.
  • A separate barrier transaction after the reads. After a failover it would commit on the new primary and prove nothing about the old one's reads.

Scope and risk

Touches the two head re-reads, the decision-record retirement, the knowledge job re-projection in ingest_run._take, the boot check and the docs. Reads served to callers are unchanged: a read of Postgres can still see a commit whose standby wait was cancelled. That is Postgres's own visibility, and this change only keeps such commits out of ClickHouse. bulk_set's dedup against another session's unpublished keeper belongs to that class and is not changed here, including the usage event it records for the keeper's id.

tests/unit/test_pg_durable_reads.py pins every module that calls a read of pg_memory, pg_documents or pg_jobs, with why its use is safe. A new caller fails until it is classified there.

With the standby detached:

  • A claim waits up to LOOM_PG_STATEMENT_TIMEOUT_MS plus one second, then the pass ends as it does during a Postgres outage.
  • A claim whose wait was cut off keeps its rows leased until LOOM_PG_DELIVERY_LEASE_SECONDS ends after the standby is back, so searches in those namespaces wait for it at the barrier.
  • A redaction or erasure that locks a claimed delivery waits up to LOOM_PG_COMMIT_LOCK_TIMEOUT_MS, then answers its retryable 503, as its own commit would.

The guarantee holds when a failover promotes a standby of the synchronous set that holds the highest flush position, which a strict HA manager does. The docs state this condition.

Change-data-capture consumers of the Postgres database receive one transactional logical message with the prefix loom.durable per durable re-read. decision.record checks its writers durably after its record lands, and a delete of a decision retires its record durably in its flush, so each waits for one more standby round trip.

Compatibility, rollout and rollback

  • Wire: none.
  • Settings: none added.
  • Operator steps: the Loom role must be able to run pg_logical_emit_message (its text overload; Postgres 17 added a fourth argument with a default). It is executable by PUBLIC on Postgres 16, 17 and 18 unless revoked, and boot refuses a role that may not, naming the grant.
  • Rolling upgrade: builds N-1 and N claim the same rows under the same locks. N-1 keeps publishing as it does today until it is replaced.
  • Rollback: reverting leaves nothing behind (no migration, no rows).

Tests

  • tests/unit/test_pg_durable_reads.py:
    • the message is the last statement before COMMIT;
    • a newer head copy is read again durably and a writer's own row is not;
    • the flush decides again from the durable read, and a copy that vanished goes to stale;
    • the lease cases at a real lease length and at an expired one;
    • a request's decision read does not wait for the standby, and a retirement's does;
    • boot refuses a role without the message;
    • a knowledge job's lagging version is projected only when a durable read returns it (test_a_job_is_projected_again_only_from_a_durable_read);
    • the caller inventory.
  • tests/integration/test_pg_durable_publish.py, in the Postgres authority job on 16 and 18 (primary plus synchronous standby, workers off). It points synchronous_standby_names at an absent standby and checks:
    • a durable transaction waits and raises with outcome_unknown;
    • an ordinary role (not a superuser) may run the statement the boot checks;
    • the boot check does not wait;
    • a connection lost inside a transaction answers 503 POSTGRES_UNAVAILABLE, not the driver's error;
    • a memory.set cut off at its commit wait raises at its claim while the standby lacks it, so no pass sends it and it is not in ClickHouse, then is published once the standby is back.
    • a revision owing its search document under a newer copy (a pin) cut off at its commit after the claim: the head read reads the copy again durably and fails while the standby is away, where main's plain read serves the copy (checked: the test fails there with DID NOT RAISE, its call adapted to main's one-argument _still_heads).
  • Local runs: the affected unit files pass (test_pg_durable_reads, test_pg_authority, test_pg_batch, test_pg_memory_reads, test_knowledge_pg_delivery and the others that use server.core.pg: 2262 tests). tests/integration/test_pg_durable_publish.py passes 6 of 6 against a local server on Postgres 16 with a synchronous standby. The rest of the Postgres authority integration files run in this PR's CI.
  • The integration file found an existing bug, fixed here: a connection lost inside pg.transaction() raised the driver's InterfaceError (a 500). asyncpg detaches the pooled connection's proxy when the connection is lost, so the terminate() and is_closed() calls on it raised, replacing the outage. They now treat a detached proxy as closed, and the caller gets 503 POSTGRES_UNAVAILABLE. CI then showed the same loss surfacing as asyncpg's InternalClientError (its protocol caught mid-switch when the server ended the connection between two statements). Now an InternalClientError of any kind is a 503 outage for every Postgres call, and inside transaction() and rolled_back() any error on a connection that reads closed is 503 too, the commit's marked outcome_unknown. is_outage has no retry loop of its own; a delivery worker releases a claim uncounted on a 503, so only a driver error that repeated on the same row could keep it from parking, and a stale schema cache clears on the next try.
  • Latency: the writer's usual flush gains no statement. The claims are unchanged. No timing was taken.

Two test fixes outside the durable read itself:

  • The analyzer corpus's fake live_decision_writers and the pg_get fake in tests/unit/test_knowledge_ingest.py now take the new durable keyword.
  • tests/integration/test_knowledge_retrieval_floors.py now waits out a 429. Its corpus is ingested back to back. The new integration file moves this test into another CI shard, and there those ingests drain the namespace's ingest bucket.

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. Each Postgres claim was checked against the commit path (a commit becomes visible after its standby wait; a transaction that writes no WAL does not wait).

  • 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. Locally: format and lint on the changed files, the affected unit files and the new integration file; the full suites run in CI.
  • Generated files are regenerated in this PR, not by hand: none affected.
  • A new migration is additive and numbered after the latest on main; no merged migration is edited: no migration.
  • A behaviour change to any file a plugin ships bumps both plugin manifests' version: no plugin file.
  • The frontend builds, if frontend/ changed: not 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.
  • Commits are signed off (git commit -s).

🤖 Generated with Claude Code

@zlareb1 zlareb1 changed the title Under Postgres, a revision reaches ClickHouse only once the synchronous standby holds it Under Postgres, a publisher reads another session's commit durably before sending what it built from it to ClickHouse Nov 9, 2026
@zlareb1
zlareb1 force-pushed the fix/pg-publish-durable-only branch 4 times, most recently from 1bcf99d to 7e6d60d Compare November 10, 2026 03:59
zlareb1 and others added 25 commits November 10, 2026 04:26
…us standby holds it

A commit whose standby wait was cancelled is visible on the primary alone; the delivery workers published it, and a failover then left ClickHouse with rows of a revision the new primary never had. The publishers' claims, and the reads after a claim that send another session's commit, now run in pg.durable_transaction(), whose commit carries a logical message and waits for the standbys on the connection that read the rows.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: zlareb1 <[email protected]>
… carry the logical message

Review: an empty synchronous_standby_names no longer refuses the publishers alone (it cost availability without the guarantee; the docs state a strict manager is needed); a claim that wrote rows needs no message; one predicate for a newer head copy; decision.record's extra standby round trip is named.

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

A commit's standby wait is outside the statement timeout, so an UPDATE claim already waited for the standbys and its client timeout raised; the transaction around it changed nothing. Review nits: newer_copy is not a journal read, the role test checks it runs as that role, a decision delete's extra round trip is named.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: zlareb1 <[email protected]>
…redicates say what they answer, the lost-connection test says what it pins

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: zlareb1 <[email protected]>
…s the GRANT; the head-copy path has an integration regression

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: zlareb1 <[email protected]>
…he statement timeout; the lease check after a durable read says so; timing tests on a fake clock; the head-copy test claims only what it checks

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: zlareb1 <[email protected]>
A commit's standby wait is outside the statement timeout, so SET LOCAL statement_timeout = 0 changed nothing and cost a round trip on every write. The boot's grant names the text overload on every Postgres version; one comment, one helper moved.

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

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: zlareb1 <[email protected]>
…he key's head is newer than its claim, a delete or other content as much as a copy

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

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: zlareb1 <[email protected]>
…ain and durable reads disagree

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: zlareb1 <[email protected]>
…ach claim's own revision: an erasure and a redaction in place too

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

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: zlareb1 <[email protected]>
A redaction keeps the content hash, so the flush's refactored copy check took a redacted head for a copy and would build the writer's document, with the redacted text, onto it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: zlareb1 <[email protected]>
…cases (a copy built onto, a failed durable read), the docs give the reason before the risk

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: zlareb1 <[email protected]>
…ound trip is its own bullet, one contextlib import

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: zlareb1 <[email protected]>
…; the lease tests use the shared clock fake and flush helper

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: zlareb1 <[email protected]>
…py leaves redaction to embedded; tests use real rows

On a server in recovery the logical message cannot take an xid (XX000), checked on the standby; it now expires the pool and answers 503 as a write's 25006 does.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: zlareb1 <[email protected]>
…entory's pg_delivery reason covers every head that is not the claim

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: zlareb1 <[email protected]>
…ion tests check the 503 and its cause; a test pins that the usual flush reads no head durably

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: zlareb1 <[email protected]>
…iting it out once per namespace

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: zlareb1 <[email protected]>
zlareb1 and others added 4 commits November 10, 2026 04:26
…loors test reads Retry-After

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: zlareb1 <[email protected]>
…and pg_jobs is in the durable-read inventory

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

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: zlareb1 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: zlareb1 <[email protected]>
@zlareb1
zlareb1 force-pushed the fix/pg-publish-durable-only branch from 4371665 to 24c9deb Compare November 10, 2026 04:26
zlareb1 and others added 5 commits November 10, 2026 04:31
…_set's reason its dedup read

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

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: zlareb1 <[email protected]>
…ent names the driver states it covers

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: zlareb1 <[email protected]>
@zlareb1
zlareb1 merged commit 1fedf02 into main Nov 10, 2026
41 of 42 checks passed
@zlareb1
zlareb1 deleted the fix/pg-publish-durable-only branch November 10, 2026 06:48
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