Skip to content

Under Postgres, a key's first memory.set answers at the commit and ClickHouse gets one insert per table per flush - #433

Merged
zlareb1 merged 3 commits into
mainfrom
feat/pg-batched-delivery
Nov 9, 2026
Merged

zlareb1 merged 3 commits into
mainfrom
feat/pg-batched-delivery

Conversation

@zlareb1

@zlareb1 zlareb1 commented Nov 8, 2026 •

Copy link
Copy Markdown
Member

Changelog category (leave one):

  • Performance 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 LOOM_STORAGE_AUTHORITY=postgres, a memory.set of a key with no live head answers once Postgres commits, and each process publishes its commits to ClickHouse in shared flushes, one insert per table and month, on average one flush every LOOM_PG_PUBLISH_INTERVAL_MS (250 ms) with bursts of up to a second's worth, so loom.memory and loom.memory_embeddings get parts at that rate instead of one per write.

Why

Postgres became the memory authority for two reasons: fast memory ops, and no small ClickHouse inserts that each make a part. Neither was true yet. After its Postgres commit a writer published its own rows before it answered, with committed inserts (the fenced INSERT … SELECT FROM input() of a version row cannot be async-buffered). So memory.set still waited on a ClickHouse insert, and loom.memory, loom.memory_versions and loom.memory_embeddings each got one part per write. Measured on main (below): 357 new loom.memory parts for 363 memory.set calls in 30 s, and memory.set p99 no better than the ClickHouse authority's.

Design

  • A publication batch per process (server/memory/store/pg_batch.py). A commit hands its rows, its audit rows and the search documents its writer built to the batch. A flush sends every commit queued since the last one, across namespaces and orgs: one insert into each of loom.memory, loom.audit_log and loom.memory_embeddings, then one Postgres transaction that clears what landed (pg_memory.complete_each).
  • Cadence. With LOOM_PG_PUBLISH_INTERVAL_MS at 0 a flush starts as soon as the last ends. Otherwise flushes start at most 1000 / LOOM_PG_PUBLISH_INTERVAL_MS (new, live, 250 ms, so 4) a second on average, by a token bucket that holds up to a second's worth (at least one): a process that writes now and then sends each write at once (a fixed spacing between flushes made a lone writer's waiting tail, a supersession or a graph fence, wait out the interval), and a busy one sends at most 4 inserts a second per table. This is the per-write wakeup the delivery worker's 2 s pass could not give.
  • Who answers at the commit. Only a memory.set of a key with no live head (a new key, or one deleted since) that states no relations and is not high answers at its commit (set_commit._answers_at_commit, wait=False). Such a write owes no graph fence a read of its own row: it has no earlier edges to close and no stated relations to project, and the background entity projection that reads loom.memory for it waits for the request's own publication (below). A revision, a write with relations, a write with a high row, memory.bulk_set and every other publisher (copy writers, memory.update, restore, rollback, digests) wait for their flush and keep their contract: past the lease a committed write still runs its follow-ups (conflict marks, supersession, stated relations, audit), then answers PUBLICATION_PENDING (set_commit.settled / finished, bulk_set's unpublished), so code that checks "is it in ClickHouse" after a write is unchanged. They all share the batched parts.
  • The vector. It is computed before the commit, as before, and held in the writer's process until its flush. Postgres stores no vector. A process that stops before its flush loses only the document: the delivery worker takes the delivery when its lease runs out and embeds the revision's text again, as it does today for any writer cut off after its commit. The shutdown drain (boot.drain_writes) sends what is queued first.
  • A document is sent only under its head. Before the insert, the flush reads the heads of the keys whose documents it carries (one Postgres query) and sends a document only while its key's head still serves it: the revision it was built from, or a newer same-content copy (a pin, a touch, a conflict mark) that owes no document, whose own delivery owes no document (pg_memory.heads_owing), onto which it carries the writer's vectors (pg_batch._onto), so the text is not embedded again; the delivery worker, building from the head itself, re-embeds instead. One deleted, rewritten or redacted since has its own retirement or columns, which the document would land live above. Its delivery is handed over at the end of the flush (pg_memory.hand_over ends the commit's lease), and so is every delivery of a commit ClickHouse refused, so the delivery worker, or a search waiting at its barrier, builds it from the head or settles it (pg_delivery._still_heads) instead of every search waiting out the lease. A flush that got no answer (or a lease that ended) ends no lease: an insert of it may still be running, and an erasure must keep waiting for it.
  • The flush runs in a context of its own (contextvars.Context(), query tag pg_batch.flush): it sends every org's commits, so no request's quota key, query tag or budget is charged for them. A writer that waits for its flush answers PUBLICATION_PENDING at its lease at the latest, however long an earlier flush takes.
  • Fencing, leases, erasure, redaction. Every commit in a flush is still sent under its own lease (COMMIT_TOKEN, Committed.deadline): the flush runs under the earliest lease among its commits (pg_memory.leased), skips a commit whose lease ran out in the queue, and clears a target only under that commit's token. An erasure's wait for leases and a redaction's token fence therefore cover a batched send exactly as they covered the writer's own send. A flush ClickHouse refuses is sent again commit by commit, and only the table that refused (memory rows that landed are not sent again), so one bad row holds back only its own commit: each commit answers as soon as its own resend lands, and the resends stop at the first one ClickHouse does not answer, leaving the rest to the delivery worker. A refused retirement of old vectors is tried commit by commit too, and its tombstones are split by partition like the rows. A flush that got no answer (a state that clears on its own, a lost connection, a class-deadline timeout, Postgres down) is left whole to the delivery worker, not retried once per commit; when one table timed out and another refused, the timeout decides. Leases are checked again after the heads read, so a commit whose lease ended during it does not turn the flush into one send per commit. The flush retires the old vectors its commits owe (OLD_VECTORS) in one call; a failed retirement leaves only the commits that owe it pending.
  • Partitions. loom.memory and loom.memory_embeddings are PARTITION BY toYYYYMM(created_at), and created_at is a key's first write, so a shared flush can span many months, a part per month. It is split into blocks of at most 100 months (max_partitions_per_insert_block, which ClickHouse Cloud pins at 100), with the helper the code index already used for namespaces, moved to server/core/ch_writes.partition_blocks. loom.audit_log is by toYYYYMM(ts) of rows written now.
  • The write fence is not called under Postgres (write_fence.lift_above_deletes, lift_after_insert). It read ClickHouse's memory_versions to lift a write over a delete that landed during its embed. Under Postgres the commit already orders the two: a delete since the write read the key's head refuses the commit (heads_unchanged), and the write starts over with a version drawn after it. With publication batched, ClickHouse may not hold the delete yet anyway, so the read could not fence. This removes two ClickHouse reads from every memory.set and memory.bulk_set.
  • Reads that act on ClickHouse wait for it. memory.list (memory rows owed; an as_of replay too), memory.history and a memory.get or memory.get_by_id as_of replay (which read ClickHouse's history) and namespace.rollback's plan (in its handler) start at the search barrier (pg_validation.admit), as namespace.inventory and the blacklist sweep already did, so a key written just before is listed and planned; past LOOM_PG_PROJECTION_WAIT_MS each answers 503 PROJECTION_BEHIND, and with Postgres down each answers 503 POSTGRES_UNAVAILABLE rather than reading what ClickHouse holds (they fail closed, as point reads do; memory.history and the as_of replays were ClickHouse-only reads on main). On main a commit whose publication was pending (a writer cut off) was already missed by both; now every write would be for a moment, so they wait.
  • Same-key reads take the authority's heads. A later write of the key in another session must see a first write that answered at its commit: under Postgres, newest_wins supersession (key_supersession._live_same_key_rows), the resolver's owed mark for a key held elsewhere (keys_held_elsewhere), the guard that refuses a proposal over an accepted fact (reads.key_holds_established_fact) and memory.delete_version's check of the chunks other identities serve (reads.served_key_rows) read the live heads from Postgres (pg_memory.live_key_heads: in the writer's read scope for the supersession and the resolver's mark, namespace-wide for the proposal guard and the chunk check, as on ClickHouse; the chunk check counts the deleter's own head too, since it is the tombstone unless a write landed above it) instead of loom.memory FINAL. One indexed query instead of a ClickHouse read.
  • The graph's fences wait for the request's own write. A write's edges and facts are projected only while loom.memory shows the row holds its value (graph_holders). A write that answers at its commit records its publication for its request (pg_batch._own_write), and a fence in that request, or a task it schedules, waits for it (own_write_published), up to the write's lease. Past the lease it reads what ClickHouse holds, as on main for a write whose publication is pending; the extractor's pass backstops that projection. A later write of the request that waits for its own flush leaves the record, so a fence after it still waits for the first one, whatever order the flush sends them in. There is no namespace-wide wait and no Postgres query per fence.
  • Rolling upgrade. Build N-1 publishes each write itself; N batches. Both send the same rows under the same leases into the same tables, and the delivery worker is unchanged, so they serve side by side. No schema change. One window: N-1's reads of ClickHouse that wait at the barrier in N (above) do not wait, so until the rollout ends a key's first memory.set answered by N can be missing from them on an N-1 replica for up to one flush (on main both builds published before answering).

What this leaves alone: the delivery worker still publishes a namespace at a time. It only handles deliveries whose writer's lease lapsed (a crash, a ClickHouse outage), and its per-namespace batches are what keep a refused row from holding back other namespaces' retries.

Alternatives weighed:

  • Store the vector in Postgres and let the delivery worker publish everything. About 8 KB of WAL per write for two 1024-dim vectors, written and deleted again within a second. It also moves every send off the writer's lease onto a worker claim, which changes what an erasure waits for. Rejected.
  • Async-insert the version rows. The fenced INSERT … SELECT FROM input() cannot be buffered (batched inserts).
  • Wait for the shared flush in memory.set. This bounds parts but keeps ClickHouse on the write path, plus up to one interval. Rejected for a key's first memory.set, the common write; kept for revisions, memory.bulk_set and the other writers, whose graph fences or callers read ClickHouse after them.

Scope and risk

  • Read-your-writes: memory.get, bulk_get, get_by_id read Postgres (current at the commit). A search waits at its barrier for the flush, at most one interval plus an insert. A read of ClickHouse alone (memory.keys, memory.aggregate, the others storage-authority.md lists) shows a memory.set once its flush lands, usually within 250 ms.
  • Such a memory.set whose flush fails answers 200 instead of 503 PUBLICATION_PENDING. Its delivery is published by the delivery worker (or a waiting admission) once the lease runs out. The idempotency key is already committed in the same transaction as before.
  • memory.set still leaves its op audit row (audit.emit, a batched async insert). At concurrency 5 those rows did not share a flush: loom.audit_log got about one part per write (see Tests). That is the existing ch_batched_insert_wait_* window, not this path, and is left as is.

Compatibility, rollout and rollback

  • Wire: no op or field changes. Under Postgres, such a memory.set no longer answers PUBLICATION_PENDING for a failed publication.
  • Operator steps: none. New live setting LOOM_PG_PUBLISH_INTERVAL_MS (default 250, 0–2000; the flush caps it at half LOOM_PG_PROJECTION_WAIT_MS, a live change included, so a read right after a write has time to wait for its flush). The publish wait of a memory.set or memory.bulk_set has its own trace span, pg.publish.
  • Rollback: revert; no stored data or schema to undo.

Tests

  • tests/unit/test_pg_batch.py (new; fails on main, where the module does not exist; a manual clock): commits queued while a flush runs share the next one's inserts and each delivery clears only what landed for it; an idle commit is sent at once and the next flush waits out the interval; a refused row is sent again commit by commit; a refused document resends only the documents; a timeout or lost connection is not retried per commit; a document whose key moved on is not sent and its delivery is handed over; a waiting writer answers by its lease behind a hung flush; the flush runs with its own query tag, not the caller's; only a first write with no relations answers before its flush (_answers_at_commit); a failed retirement leaves only its commits pending; a commit whose lease ran out in the queue is not sent; wait=False returns before the flush, and a cancelled waiting writer's commit is sent all the same; a drain that runs out leaves the queue; partition blocks; a pending set or bulk_set runs its follow-ups and answers last; a document carried onto a same-content copy that owes none, not onto one that owes its own; a commit that lands alone answers before the other resends, and an unanswered resend or retirement stops the rest; a later waited write keeps the request's earlier unwaited one for its fences.
  • test_pg_authority.py::test_a_delete_committed_during_a_write_refuses_its_commit (unit): a memory.delete or delete_version committed after the write read the head refuses its commit, which is what lets the Postgres path go without the ClickHouse fence.
  • test_pg_authority.py::test_a_write_is_listed_and_rolled_back_right_after_it_answers and test_a_read_of_clickhouses_history_right_after_a_write_sees_it (integration): memory.list lists, namespace.rollback plans, and memory.history and the memory.get / memory.get_by_id as_of replays serve, a key written just before. test_list_locates_then_reads.py: each of those reads waits at the barrier (test_a_get_replay_waits_for_the_namespaces_memory_rows, test_history_and_a_get_by_id_replay_wait_for_the_namespaces_memory_rows), and history reads sequentially once it waited.
  • tests/integration/test_pg_authority.py::test_writes_made_together_share_their_clickhouse_inserts (new; fails on main, which has no flush): 20 concurrent memory.set into 20 namespaces are published by fewer than 20 inserts into loom.memory tagged pg_batch.flush (system.query_log).
  • test_graph_holders_published.py (a fence waits for its own request's write, and for nothing else), test_list_locates_then_reads.py::test_the_list_waits_for_the_namespaces_memory_rows, test_rollback_plan.py::test_the_plan_is_read_after_the_namespace_is_published: memory.list and the rollback plan wait at the barrier for memory rows before they read. test_pg_authority.py::test_a_relabel_whose_publication_is_pending_owes_its_facts_until_published failed 1 run in 4 before the graph fences waited (a first write's triples were skipped); 6 of 6 after.
  • Changed tests: test_list_and_bulk_get_serve_what_the_authority_holds parks the rewrite it leaves unpublished, since memory.list's barrier now publishes a lapsed one; the publish test patches the batch's inserts and expects the decision records retired beside a failed vector retirement; the revision test checks the document rides in the publish; the bulk tests follow _insert_batch; the cancelled-while-publishing bulk test moves to test_pg_batch.py (test_a_bulk_set_cancelled_while_it_waits_for_its_flush_is_announced_and_sent), against the batch's wait.
  • Integration tests that set up deliveries by hand after a memory.set, or read ClickHouse right after one, now wait for the org's deliveries first (_published), since the write answers before its flush; the restore test injects its failure into the batch's loom.memory insert.
  • Integration, Postgres authority (postgres:16 with a synchronous standby, workers off, 3 web workers): every file of CI's Postgres job, 286 passed, 15 skipped. The one failure, test_cross_principal_leakage.py::test_positive_control_a_reader_of_the_repository_reads_its_decision, fails the same way on main here (no code repository indexed locally).
  • Integration, ClickHouse authority: test_memory_bulk*, test_memory_set*, test_memory_search*, test_memory_delete_list, test_memory_get*, test_memory_conflicts, test_memory_history_redact, test_memory_precondition, the rollback and delete-version files: 50 passed.
  • make format-check lint typecheck, tests/unit (-n 12 -p randomly) on the rebased head: all pass (31,923 unit tests).

Measured locally: one host, ClickHouse in Docker, postgres:16 with a synchronous standby (dev/ci_start_postgres.sh), the fake embedder, one server process per build, scripts/ops/benchmark.py --concurrency 5 --duration 30 per op. main and this branch ran against the same ClickHouse and Postgres, interleaved, two rounds; memory.search against one 300-row namespace. Parts are system.part_log NewPart rows of the 30 s window. The host is shared, so treat single numbers as ±30%.

op (p50 / p99 ms) main, postgres branch, postgres main, clickhouse branch, clickhouse
memory.set 389 / 896, 570 / 1230 135 / 350, 264 / 745 411 / 845, 399 / 1009 546 / 1152, 466 / 901
memory.bulk_set (20 entries) 894 / 1841, 1065 / 1657 703 / 1028, 898 / 1797 746 / 1780, 728 / 1883 808 / 1272, 922 / 1751
memory.get 33 / 410, 67 / 255 30 / 194, 32 / 236 66 / 161, 41 / 139 75 / 221, 38 / 596
memory.search 177 / 440, 281 / 656 177 / 377, 183 / 511 352 / 1258, 166 / 784 281 / 892, 219 / 571
new parts in 30 s of memory.set main, postgres branch, postgres main, clickhouse
loom.memory 357 for 363 writes 115 for 1002 writes 355 for 356 writes
loom.memory_embeddings 357 115 355

So loom.memory gets 3.8 parts a second at 33 writes a second, bounded by 1000 / 250 per process, where it got one per write. In these rounds, where every write answered at its commit, memory.set p99 was below the control's in both. The benchmark writes a new key each time, so it still measures the write that answers at its commit; the release gate for memory.set is now "below the control's", a target the release soak measures on a quiet host, which the re-measured rounds below, on a loaded host, could not settle. memory.bulk_set p99 is within the noise of the control's (one round below, one 3% above): its time is the verdicts and the Postgres commit (50–140 ms on this host's disk with a synchronous standby), not the insert, so its gate stays at 1.10 × the control's.

Re-measured once memory.bulk_set waited for its flush (the table above predates that), same setup, one round each of branch, control and main, interleaved. The host's load average was 35–50 throughout (other jobs), so these tails are mostly the host's; a second round in which main's server stalled (p99 over 10 s) is left out:

op (p50 / p99 ms) branch, postgres main, clickhouse (control) main, postgres
memory.set 188 / 2756, 308 / 2826 430 / 1715, 489 / 863 604 / 2533
memory.bulk_set (20 entries) 633 / 2966, 648 / 2727 688 / 2554, 1263 / 4263 858 / 3526
new loom.memory parts per 30 s branch, postgres main, clickhouse main, postgres
during memory.set 217 for 302 writes 317 for 321 190 for 191

At about ten writes a second, three processes and 250 ms, a flush carries two or three writes, so parts are about three-quarters of writes; the bound is 4 a second per process, whatever the write rate (115 parts for 1002 writes above, at 33 a second). Under this load the Postgres commit (a synchronous standby on the same disk) sets both Postgres builds' tails; the control's tail does not include it. memory.set p50 is less than half the control's. memory.bulk_set p99 sits between the control's two rounds and below main's on Postgres. The release gates in storage-authority.md are measured on a quiet host; these numbers neither meet nor contradict them.

A write's tail that waits for a flush (the copies a verdict writes, a supersession, memory.update, the graph fences of an entity-bearing write) was measured sequentially, one client, 25 rounds of memory.set (first write, entity-bearing text), memory.set of the same key in another session (a same-key supersession) and memory.update, main and the branch back to back on the same stores (p50 / p99 ms):

round memory.set, first memory.set, another session's key memory.update
main 1 804 / 2023 325 / 1246 820 / 1655
branch 1 773 / 1251 190 / 434 790 / 1271
main 2 1055 / 1833 507 / 1188 1048 / 3664
branch 2 939 / 1406 296 / 607 1234 / 1504

The host was shared and loaded (load average 25–31), so these say "no worse", not a speed-up.

Reproduce: start ClickHouse and Postgres as loom-dev-setup and dev/ci_start_postgres.sh do, run a server with LOOM_STORAGE_AUTHORITY=postgres, then scripts/ops/benchmark.py --op memory.set --concurrency 5 --duration 30 and count SELECT table, count() FROM system.part_log WHERE event_type = 'NewPart' AND database = 'loom' AND event_time >= <start> GROUP BY table.

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. Checked: the lease and token handling against storage-authority.md, the benchmark and part counts above, the unit and integration suites.

  • 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 changed the title Under Postgres, memory.set and memory.bulk_set answer at the commit and ClickHouse gets one insert per table per flush Under Postgres, a key's first memory.set answers at the commit and ClickHouse gets one insert per table per flush Nov 9, 2026
…ickHouse gets one insert per table per flush

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: zlareb1 <[email protected]>
@zlareb1
zlareb1 force-pushed the feat/pg-batched-delivery branch from 04adda9 to 212ccff Compare November 9, 2026 11:37
zlareb1 and others added 2 commits November 9, 2026 11:46
…answer at their commit

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]>
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