Repository navigation
Under Postgres, a key's first memory.set answers at the commit and ClickHouse gets one insert per table per flush - #433
Merged
Merged
Conversation
…ickHouse gets one insert per table per flush Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: zlareb1 <[email protected]>
zlareb1
force-pushed
the
feat/pg-batched-delivery
branch
from
November 9, 2026 11:37
04adda9 to
212ccff
Compare
…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]>
This was referenced Nov 9, 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.
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
LOOM_STORAGE_AUTHORITY=postgres, amemory.setof 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 everyLOOM_PG_PUBLISH_INTERVAL_MS(250 ms) with bursts of up to a second's worth, soloom.memoryandloom.memory_embeddingsget 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). Somemory.setstill waited on a ClickHouse insert, andloom.memory,loom.memory_versionsandloom.memory_embeddingseach got one part per write. Measured onmain(below): 357 newloom.memoryparts for 363memory.setcalls in 30 s, andmemory.setp99 no better than the ClickHouse authority's.Design
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 ofloom.memory,loom.audit_logandloom.memory_embeddings, then one Postgres transaction that clears what landed (pg_memory.complete_each).LOOM_PG_PUBLISH_INTERVAL_MSat 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.memory.setof a key with no live head (a new key, or one deleted since) that states no relations and is nothighanswers 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 readsloom.memoryfor it waits for the request's own publication (below). A revision, a write with relations, a write with ahighrow,memory.bulk_setand 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 answersPUBLICATION_PENDING(set_commit.settled/finished,bulk_set'sunpublished), so code that checks "is it in ClickHouse" after a write is unchanged. They all share the batched parts.boot.drain_writes) sends what is queued first.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_overends 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.contextvars.Context(), query tagpg_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 answersPUBLICATION_PENDINGat its lease at the latest, however long an earlier flush takes.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.loom.memoryandloom.memory_embeddingsarePARTITION BY toYYYYMM(created_at), andcreated_atis 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 toserver/core/ch_writes.partition_blocks.loom.audit_logis bytoYYYYMM(ts)of rows written now.write_fence.lift_above_deletes,lift_after_insert). It read ClickHouse'smemory_versionsto 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 everymemory.setandmemory.bulk_set.memory.list(memory rows owed; anas_ofreplay too),memory.historyand amemory.getormemory.get_by_idas_ofreplay (which read ClickHouse's history) andnamespace.rollback's plan (in its handler) start at the search barrier (pg_validation.admit), asnamespace.inventoryand the blacklist sweep already did, so a key written just before is listed and planned; pastLOOM_PG_PROJECTION_WAIT_MSeach answers 503PROJECTION_BEHIND, and with Postgres down each answers 503POSTGRES_UNAVAILABLErather than reading what ClickHouse holds (they fail closed, as point reads do;memory.historyand theas_ofreplays were ClickHouse-only reads onmain). Onmaina 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.newest_winssupersession (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) andmemory.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 ofloom.memory FINAL. One indexed query instead of a ClickHouse read.loom.memoryshows 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 onmainfor 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.memory.setanswered by N can be missing from them on an N-1 replica for up to one flush (onmainboth 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:
INSERT … SELECT FROM input()cannot be buffered (batched inserts).memory.set. This bounds parts but keeps ClickHouse on the write path, plus up to one interval. Rejected for a key's firstmemory.set, the common write; kept for revisions,memory.bulk_setand the other writers, whose graph fences or callers read ClickHouse after them.Scope and risk
memory.get,bulk_get,get_by_idread 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 othersstorage-authority.mdlists) shows amemory.setonce its flush lands, usually within 250 ms.memory.setwhose flush fails answers 200 instead of 503PUBLICATION_PENDING. Its delivery is published by the delivery worker (or a waiting admission) once the lease runs out. The idempotency key is alreadycommittedin the same transaction as before.memory.setstill leaves its op audit row (audit.emit, a batched async insert). At concurrency 5 those rows did not share a flush:loom.audit_loggot about one part per write (see Tests). That is the existingch_batched_insert_wait_*window, not this path, and is left as is.Compatibility, rollout and rollback
memory.setno longer answersPUBLICATION_PENDINGfor a failed publication.LOOM_PG_PUBLISH_INTERVAL_MS(default 250, 0–2000; the flush caps it at halfLOOM_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 amemory.setormemory.bulk_sethas its own trace span,pg.publish.Tests
tests/unit/test_pg_batch.py(new; fails onmain, 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=Falsereturns 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): amemory.deleteordelete_versioncommitted 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_answersandtest_a_read_of_clickhouses_history_right_after_a_write_sees_it(integration):memory.listlists,namespace.rollbackplans, andmemory.historyand thememory.get/memory.get_by_idas_ofreplays 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 onmain, which has no flush): 20 concurrentmemory.setinto 20 namespaces are published by fewer than 20 inserts intoloom.memorytaggedpg_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.listand 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_publishedfailed 1 run in 4 before the graph fences waited (a first write's triples were skipped); 6 of 6 after.test_list_and_bulk_get_serve_what_the_authority_holdsparks the rewrite it leaves unpublished, sincememory.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 totest_pg_batch.py(test_a_bulk_set_cancelled_while_it_waits_for_its_flush_is_announced_and_sent), against the batch's wait.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'sloom.memoryinsert.postgres:16with 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 onmainhere (no code repository indexed locally).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:16with a synchronous standby (dev/ci_start_postgres.sh), the fake embedder, one server process per build,scripts/ops/benchmark.py --concurrency 5 --duration 30per op.mainand this branch ran against the same ClickHouse and Postgres, interleaved, two rounds;memory.searchagainst one 300-row namespace. Parts aresystem.part_logNewPartrows of the 30 s window. The host is shared, so treat single numbers as ±30%.memory.setmemory.bulk_set(20 entries)memory.getmemory.searchmemory.setloom.memoryloom.memory_embeddingsSo
loom.memorygets 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.setp99 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 formemory.setis 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_setp99 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_setwaited for its flush (the table above predates that), same setup, one round each of branch, control andmain, interleaved. The host's load average was 35–50 throughout (other jobs), so these tails are mostly the host's; a second round in whichmain's server stalled (p99 over 10 s) is left out:memory.setmemory.bulk_set(20 entries)loom.memoryparts per 30 smemory.setAt 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.setp50 is less than half the control's.memory.bulk_setp99 sits between the control's two rounds and belowmain's on Postgres. The release gates instorage-authority.mdare 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 ofmemory.set(first write, entity-bearing text),memory.setof the same key in another session (a same-key supersession) andmemory.update,mainand the branch back to back on the same stores (p50 / p99 ms):memory.set, firstmemory.set, another session's keymemory.updateThe 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-setupanddev/ci_start_postgres.shdo, run a server withLOOM_STORAGE_AUTHORITY=postgres, thenscripts/ops/benchmark.py --op memory.set --concurrency 5 --duration 30and countSELECT 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 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