Repository navigation
Live memory can be held in Postgres, with search and history in ClickHouse - #158
Merged
Merged
Conversation
zlareb1
force-pushed
the
feat/pg-live-memory
branch
26 times, most recently
from
November 3, 2026 15:10
9328c3d to
ce9cb41
Compare
4 of 7 tasks
zlareb1
force-pushed
the
feat/pg-live-memory
branch
28 times, most recently
from
November 6, 2026 04:47
4fa44bc to
4801eb4
Compare
…vectors and search Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: zlareb1 <[email protected]>
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: #142
The whole of #142 in one pull request: Postgres holds live memory (current content, provenance, atomic audit, admission generations, the revision journal, delivery jobs and idempotency), and ClickHouse keeps every vector, the search projection and history. The ClickHouse authority stays the default and behaves as on
mainwhenLOOM_STORAGE_AUTHORITYis unset.What this pull request carries
stale_droppedmemory.keys,memory.statuses,memory.list's counts,memory.related,memory.aggregate,memory.inspect's counts, tags and categories, the revisionsnamespace.auditandnamespace.validatefindings cite, whose hash is the authority head's, asmemory.getserves it) checked against the authorityA part marked in progress is not in this head.
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):
A deployment can keep live memory in Postgres (
LOOM_STORAGE_AUTHORITY=postgres,LOOM_PG_DSN): point reads, compare-and-set and the conflict check's view of concurrent writes come from a Postgres transaction, while vectors, search and history stay in ClickHouse. ClickHouse alone stays the default.Why
A memory write needs ordered versions, compare-and-set, locks and pin checks; ClickHouse makes each committed write a part to merge, and two concurrent writers cannot see each other before they reach their verdicts. Measured on this branch's ClickHouse authority: six concurrent
memory.setof one fact under six keys land as sixclearfacts. Under the Postgres authority one lands and five merge into it.Design
Full page:
docs/architecture/storage-authority.md. In short:loom.memoryrow (loom.memory_current), replaced only by a version that is not older, which is whatloom.memory FINALserves. Every writer already builds full rows and inserts them throughinsert_memory_versions; under Postgres that funnel commits (head, revision, delivery, audit row, idempotency state) and publishes from the commit. The ~120 write sites need no change. ClickHouse'sloom.memory,memory_embeddings,memory_versionsandaudit_logbecome projections of committed revisions.memory.setliveness and scope) are ruled out without I/O; otherwisememory.setadds the gap's rows to its peer rows and re-reaches its verdict,bulk_setmeasures the gap on ClickHouse's vectors of the embedder's model and restarts if one is within reach, or if a row of an entry's type has no such vector to measure. A seq missing from the gap was erased and cannot be a peer, so an erasure behind a stuck delivery does not hold the namespace's admissions back; a verdict that links the written row to an erased memory (its canonical, a conflict) is refused at commit (PeerErased) and reached again on peers read anew, and an erased memory is dropped from the peers a verdict reads, since ClickHouse still holds it until the erasure's ClickHouse steps run. Excess contention answers 503ADMISSION_CONTENDEDafterLOOM_PG_ADMISSION_DEADLINE_MS. The vectors this process's commits wrote (pg_admission._recent, at mostLOOM_PG_ADMISSION_RECENT_VECTORS) only rule a gap row out of reach and are never served, so a redaction leaves them.memory.set,memory.bulk_set,memory.update_by_idandmemory.clear, the commit locks each written key's head and compares it with the row the write read:if_match_sha256requires that very version (true compare-and-set); an unconditional write may land over a newer value (last version wins, as in ClickHouse) but never over a delete, pin, lock or status change it did not see. The other write paths commit as they write on the ClickHouse authority, the newer version winning. A redaction since the read counts as a moved head:memory.set,memory.bulk_setandmemory.clearstart over from the scrubbed head, andmemory.update_by_idanswers 503ADMISSION_CONTENDEDso its retry reads it; a copy writer that read a version before its redaction answers 503 and its retry reads the scrubbed head (below). An unconditional write never waits on a concurrent one: 15 concurrent writes of one key all answer 200 (test_ratelimit.py).memory.revision, naming as actor the token's principal, else the pipeline stage's actor, else-inside a request andprocess:loomfor Loom's own jobs, never the earlier writer a copy carries; a process that never wired its writer refuses the commit, beside the row a write op such asmemory.setormemory.update_by_idleaves itself) and (searchable writes) search document, tracked apart from the payload with a lease and a fencing token. The writer publishes at once under its 5 s lease; a writer that stops is finished by the next admission in the namespace or thepg_deliveryworker, which re-embeds from the revision (vectors never pass through Postgres).loom.idempotencybeside the revisions and fail closed. The commit marks the keycommittedunder its lease token; a retry after a lost answer replays the committed revision's identity; a retry that takes over an expired claim fences the request it replaces.pg_memory.deleteruns first in every saga: deletes heads and revisions holding the scope's generation locks, keeps the erased ids as deletion evidence (a write built from an older head is refused with 404), moves the audit rows ClickHouse does not have yet toloom.audit_outboxin the statement that deletes their revisions (the delivery pass publishes them per namespace, deduplicated, once no earlier publisher can land them, and parks a row ClickHouse keeps refusing; an erasure never waits on ClickHouse, and a parked delivery costs it only the lease its park kept, until that and the insert bound have passed), then waits out every publisher lease it removed plus the ClickHouse write bound before the ClickHouse steps. Erasure evidence is kept by namespace: a namespace restored from another's snapshot keeps its memory ids. The idempotency step fences the org's claims in flight, recording when inloom.idempotency_fenceswhile holding the org's claim lock for those two statements only (a keyed request that meets it answersIDEMPOTENT_IN_PROGRESS); it then deletes the answers claimed before that time, which the residue census counts until they are gone. Census rows cover the Postgres tables; a failed saga's census tail counts Postgres and the document bucket each on its own, so a store that cannot be read costs only its own counts. A failed saga's census tail that could not read a store keeps the counts it made and leavesverified_atunset, and the recovery worker carries those counts onto an abandoned saga's terminal row (a ClickHouse-only install with a bucket sees this too).loom erasure-re-verifynow exits 1 when Postgres or the document bucket cannot be read, where it exited 0 with no residue found (a change on a ClickHouse-only install with a bucket too).LOOM_PG_DELIVERY_MAX_ATTEMPTS. ClickHouse refused nothing, and the pass stops uncounted, when it answers with a state that clears on its own (a merge backlog, a read-only table, Keeper lost, too many queries, an insert of unknown status, the server out of memory as a whole), every pooled connection is busy, or a publish fails at the connection and ClickHouse then does not answer a probe. A connection failure while ClickHouse answers, a timeout, and an insert block spanning too many partitions count, so the batch is tried row by row and a row that keeps failing is parked. A publish that ends the worker process counts too: a claim is markedheldjust before its own publish and cleared with its outcome, so the next pass counts one still marked, publishes it alone and parks it at the limit (a delivery owing only its search document gets its stub). A pass cut short clears the marks of claims whose publish had not started and counts nothing; the publish running when it was cancelled keeps its mark and counts, so one that always outlasts the pass is parked. A Postgres outage during a publish ends the pass with nothing counted; a refused Postgres statement counts on its claim, which parks at the limit. The worker probes ClickHouse after a connection failure; an admission helping with a namespace's backlog does not, and counts nothing on one.memory.redactscrubs the heads and the journal in one transaction and fences the scrubbed revisions' deliveries (a new token, the lease ended; a parked one stays parked), so no holder renews or completes one after; the ClickHouse scrub runs once the holders are waited out.loom.storage_authority, migration 085) and Postgres; a replica configured for the other refuses to start.53100,53200,53300,58000,58030) and a cached statement a migration changed answer 503POSTGRES_UNAVAILABLE; a configuration limit or a missing file does not. A data or constraint error (SQLSTATE class 22 or 23, or the driver's own argument error) answers 500POSTGRES_REFUSEDnaming the SQLSTATE, constraint, table and column, never the row or argument the driver's text quotes; it fails the same way on a retry.default_transaction_isolation = read committed, which the commits' re-checks of rows they waited on rely on, whatever the server's default. A single statement outside a transaction commits under the statement timeout, so it writes only what a failover may lose (a lease, a claim, a counter); the idempotency answer is stored in a transaction, whose commit waits for the standby.synchronous_commit = on;LOOM_PG_DURABILITY=synchronous(default) refuses a primary whosesynchronous_standby_namesis empty, and boot warns when no synchronous standby is attached orpg_stat_replicationis not visible;localaccepts the primary's disk alone, with a warning.Rejected: a typed Postgres table of every column (two schemas drift; every new column twice); Postgres heads with content in ClickHouse (a second lookup per point read, ClickHouse still on the write path); a namespace lock held across the check (a connection or transaction held across inference and a ClickHouse query); re-running the whole check whenever a generation moves (measured: 30% of
memory.setat concurrency 5 answeredADMISSION_CONTENDED, since every commit in a busy namespace moves it).Decisions and evidence
asyncpg(Apache-2.0, async-native, with its own pool).postgres:16with one synchronous standby (dev/ci_start_postgres.sh).schemas/pg_migrations/, applied at boot under an advisory lock, each file in one transaction with its checksum; drift refuses. Every file runs in one transaction: no file builds an index concurrently, so the runner carries no path for one (a session waiting on the advisory lock holds a snapshot that a concurrent build would wait out, a deadlock reproduced on Postgres 16 with two sessions; the path that needs it comes with its first file).org(the delivery queue bylease_until, settled deliveries bylease_until, the audit outbox bydue_at, idempotency retention byexpires_at, erasure evidence byerased_at): all are maintenance queues local to one database; every tenant read uses anorg-led key.LOOM_RETENTION_MEMORY_DAYSand a namespace'sretention_daysare ClickHouse TTLs that would delete ClickHouse's copy alone: under Postgres the TTL is not put onloom.memoryand the boot refuses the setting. A retention sweep on the authority comes with retained history in this PR.loom.memorypublication feedsmemory_versions); change capture is qualified for mirrors in this PR.Alternatives: a database per tenant, copy-on-write branching
docs/architecture/storage-authority.md("A database per tenant", "Postgres branching") has the evidence.max_replication_slotsandmax_wal_sendersdefault to 10); the cluster's 3 autovacuum workers rotate over every database, each with its own wraparound horizon; migrations fan out to every database and a partial run leaves tenants on different schemas. It isolates nothing: the WAL, buffers, IO and vacuum workers are the cluster's. Its one advantage, moving a tenant as one dump, is covered by the placement route.DROP DATABASEerasure cannot run in a transaction and leaves backups and archived WAL holding the data, so quarantine restores are needed either way. Schema per tenant has the same costs and conflicts with transaction pooling. Kept: a dedicated placement unit (cluster) for a large or regulated tenant.postgres:16container with a synchronous standby: it needs no account or network and tests the standby a branch lacks. Restore-in-quarantine and cutover or migration rehearsal on production-size data work as procedures on a point-in-time fork or a recovery cluster under the HA manager; a branch, where the platform offers one, is a faster copy for the same procedure. Per-PR previews must not branch production data, since erasures do not reach the copies.LOOM_PG_DSNnames the direct endpoint (docs/operations/postgres.md).Research summary
LOOM_PG_LEASE_MARGIN_SECONDS, refused at boot under Postgres unless shorter than both leases), and every ClickHouse insert made under a lease starts on the server within a transit allowance of the lease's end (later ones are refused) and runs for at most the write limit (60 s whenLOOM_CH_TIMEOUT_WRITE_Sis 0), so an erasure can bound when the last copy can arrive (pg.insert_bound_s, the same bound a carried insert's boot wait uses). An insert into a table that is not carried (the audit rows) is sent under a lease with the start guard alone and unbuffered, so under Postgres a publisher's audit row is a committed insert of its own rather than part of a shared flush; an outbox claim's audit insert starts within its claim, and a delivery taken over within the insert bound of the lease it replaced sends its audit row through the outbox, due once that holder can no longer land it, so the claim's duplicate read cannot miss it. Each id an erasure removes keeps, with its evidence, when no publisher of what it removed can still land a row (quiet_at), and a run that finds the rows already gone waits until then;erasure.requestandmemory.redactanswer after their wait (about 80 s past the latest lease with the default settings). A committedmemory.bulk_setreplay names the rows the batch committed, in commit order, not one result per entry. Under Postgres a commit whose row is not embedded over a head that was (as the commit finds it under the head lock, on every write path, whatever the write read) owes the retirement of the old vectors as a delivery target of its own (bit 16,OLD_VECTORS): the publish retires them and clears it, and when that fails the answer isPublicationPendingand the delivery worker retires them under its lease. A redaction of the key may be purging those rows while the retirement is in flight, so under Postgres its tombstones keep only each row's sort key and partition, with no text or vector (the trade: amemory.restoreof such a key's deleted row mirrors a row with no text or vector, and anas_ofreplay from before the retirement does not find the key's vector); on the ClickHouse authority a retirement copies the rows, as onmain. The worker builds no search document for a redacted head, nor for a revision a newer head replaced unless that head is a live, embedded copy of the same content, whose row the document is then built from. Under Postgres a reject re-emits only the vector rows of the head's own content hash (none of a redacted, unhashed, 'high' or unsearchable head) and retires the rest with no text, from one sequential read per key, under its commit's lease and before its publish clears the delivery a redaction waits out; a copy that fails leaves the committed reject standing, and the key's entity vectors stay as they are, as on the ClickHouse authority. The copies sit at the reject's version, so a later 'high' write's fence wins over them, and they skip the head re-check other copy writers run (it reads ClickHouse's head, not the authority's).loom reconcile-statusunder Postgres holds back a key whose authority head is newer than itsloom.memoryrow or erased, and counts it, so it does not revert a reject or a delete whose publish is pending or copy the vectors of an erased key. The wait covers what the authority publishes (memory rows, search documents, audit rows, decision records). A write's own ClickHouse copies of search rows after its publish (a vector retirement, a fence, a lift, a status or expiry mirror) and what is derived from it (the graph projection, conflict judging, the background workers) race an erasure of their scope as any concurrent write does under the ClickHouse authority; the erasure's ClickHouse steps and residue census cover what lands before the census.Scope and risk
Touches the memory write funnel, point reads,
memory.set/bulk_setadmission,memory.clear,memory.reject, redaction, the usage fold, the idempotency gate, erasure and boot. Each Postgres branch is taken only whenLOOM_STORAGE_AUTHORITY=postgres; underclickhousethe paths aremain's (the idempotency gate callscheckexactly as before;check_on_commitgetscandidate_rows=None) except for the fixes listed below, which reach a ClickHouse-only install too. New on every deployment: the authority row inloom.storage_authorityat first boot (not by a process withLOOM_BOOT_MIGRATE=0, which only checks it),storage_authorityin/v1/health, an idlepg_deliveryworker.namespace.snapshotreads the authority's heads, so a delete ClickHouse has not published (or never will, parked) is not snapshotted;namespace.inventory's memory counts wait once at the search barrier and then read sequentially; a copy of a head its writer read (lifecycle.insert_versions_over_heads: a tombstone, a status, a pin, a touch, the supersessions and cascades of any write),memory.rejectandmemory.clearare done once committed, even when their publication is pending: the delivery worker publishes them, a search serves a hit only while the authority's head shows its content and a point read answers from the authority, so the write goes on as on the ClickHouse authority, where a row once inserted stands (status mirror; derived retirement, a decision's record through its delivery; webhook, whichmemory.clearsends before it retires a page's vectors), and a ClickHouse follow-up that then fails answers its own error; every other write answers 503PUBLICATION_PENDING. A by-id write is confirmed by its commit, which keeps the newer version, so a row older than the head it read is overtaken, as the ClickHouse re-read found it.memory.inspectlists its newest rows (its located read selectsorg,namespaceandredacted_aton every install; a sample can be short ofsample_limitwhile older rows are live), and the entity extractor takes a candidate and sends its value to the model, only while the authority still serves that version (lifecycle.served_rows), so a delete, a rewrite or a redaction ClickHouse has not published is neither shown nor sent.memory_repo.get_many_by_keysreads the authority's heads, somemory.bulk_get(and the export, which reads values through it), a search'sbodies="unit"read,procedure.match/procedure.listbodies, the extraction prompt andmemory.proposalsanswer asmemory.getdoes, a newer head not yet in ClickHouse included and ahighhead past its retention window left out as ClickHouse's read does (one Postgres read per call in place of two ClickHouse statements).memory.list, in either order, serves a ClickHouse row only while it is the authority's live head at that version, redacted or not alike (lifecycle.served_rows; the list reads selectredacted_at), so a delete, rewrite or redaction ClickHouse has not published is not read back; a recovery listing (include_tombstoned) checks its deleted rows too (lifecycle.recovered_rows) and lists a row the authority has since only deleted (the same id, type, text, tags, times, sensitivity, pin and run, a status the listing serves, the trace when it filters on it, and never underas_of) as that deleted head, with ClickHouse's preview of the text; a row restored, rewritten, relabelled or redacted only in the authority waits until ClickHouse holds it, so the listing's filters hold. The other reads of ClickHouse alone (memory.keys,memory.statuses,memory.list's counts,memory.related,memory.aggregate,memory.inspect's counts, tags and categories, the revisionsnamespace.auditandnamespace.validatefindings cite, whose hash is the authority head's, asmemory.getserves it) are in progress, above. The blacklist sweep waits until ClickHouse holds the memory rows committed in the pattern's scope (one barrier for a namespace or an org, whose cost follows the backlog; 503PROJECTION_BEHINDpast its wait), matches with a sequential read, then pages through the live heads whose memory row is parked (pg_memory.parked_heads, in the deliveries' key order, judged from the value text the page reads before any is tombstoned, so a sweep takes longer with the parked backlog/v1/health?include=postgresreports), and judges every head the authority holds with ClickHouse's RE2 match (.matching a newline), so a head rewritten or redacted since the match is left and a decision so left keeps its record;matchedcounts what ClickHouse matched and the parked heads it tombstoned, andtruncatedonly ClickHouse's matches past the limit. A search tier whose check fails is left out and named indegraded, without marking/v1/healthdegraded.memory.search_tracewaits at the search barrier too, serves a hit only while the authority's head shows it (a replay underas_ofas it read, asmemory.searchserves one), and its vector read selects the row's agent, user and session on every install;memory.importdecides what to skip from the authority's heads. Search admits at a barrier (every revision through each searched namespace's generation is published first, or 503PROJECTION_BEHIND) and serves a fact hit only when its document shows a live head's content; dropped hits are counted instale_dropped. Do not run the Postgres authority in production before the release gates of #142 pass.The decision extractor's writer check (
records.live_writer_record, used bydecision.outcomeand the revision check too) counts a writer live by the decision heads the authority holds, so a decision deleted but not yet published is not taken for a live writer, and one committed but not yet published is.Changes that reach a ClickHouse-only install, all fixes, in brief:
maina failed source read wrote the period without its lineage or entities, which no later pass repaired, and a failed writer lookup, embedding or row write ended the identity's remaining periods. The lineage follows the row once the row is in ClickHouse, so a user erasure reaches it through the row's key; a failed lineage write, or a row whose publication is pending, is recorded and goes without its lineage until a rewrite. A failed embedding insert after the row is logged and the lineage still written (onmainit skipped the lineage). Under Postgres the period row's commit owes its search document, written within the commit's lease (lifecycle.insert_documented_versions), so the delivery worker builds one a failure left and an erasure waits it out. A period row its writer deleted, rejected or redacted counts as written, so no pass writes it back, a rewrite included, which redoes only live periods (onmainthe next pass, and any rewrite, wrote a new live version of it; the--rewritehelp says so, and the command's help names the rows' type,semantic, where it said episodic). On ClickHouse the keys are read in the period rows' own session, so the read stays on a sort-key prefix; under Postgres the authority's heads decide which periods are written, so a period whose publication is pending is not planned and paid for again, and a period restored in the authority but still deleted in ClickHouse is rewritten. The per-identity cap applies after that, so a period skipped takes no place in it, and the count of skipped periods, renamedperiods_skipped(the CLI prints it as skipped as written or taken out), counts every one of the identity (onmain,periods_existingstopped at the cap). Its failure lines carry the error's type and code, not its message.short(it reads asstaleand is rebuilt) or, with no profile served, writes nothing; it wrote the short or all-null profile under the full digest, which read as current.memory.delete_version, a dedup flag clear,memory.apply's label and demote, a move's redirect, the expiry sweep, a rollback's tombstone, a proposal decision, the observation tags,write_versions_by_ids' default version and a cascade's tombstones) writes above the head it read (rows.version_over), and a restore and the entity pass, which draw before their read, lift above it, as a rollback's reinstated version (above the key's head when it applies, a delete included, and announced as a revival or a revision by that head) andmemory.rejectlift above the head they read; a restore's search row takes its version: onmaina version drawn on a replica whose clock was behind the head's writer sat below the head and never became it, while the op answered that it had (a lock answeringlockedover an unlocked head). The row, its vector retirement and the op's answer share that version.served_rows), as the entity extractor's candidates do, so under Postgres a delete, a rewrite, a status, ahighlabel or a redaction ClickHouse has not published is not sent: the conflict resolver's peers (a flagged peer so left out holds its row back, with no model call and no attempt, forLOOM_PG_DELIVERY_LEASE_SECONDSat a time, counted in the pass's newskipped_behind; that setting's description says so), the profile builders' facts (a structured profile built short of the facts it counted carries the sources digestshort, which no digest takes, so it reads as behind (profile.structuredanswersstale) and is built again after the cooldown, a model call each time while a fact stays behind, and a build that gets none of the facts it counted writes the all-null profile over a served one without a model call, never keeping it (it may carry a source that has left since), while a user with no profile yet gets none;postgres.parked_deliveriescounts the deliveries that hold one back) and a period row's entities (a newer head that is only a copy, active with the same id and text, still lends the entities ClickHouse read; a period row is not rewritten unless asked, so a source otherwise behind its delivery lends none to it); a distill pass's session context also keeps a newer head that is still the same observation, with the same memory id and text, such as an earlier pass's DONE mark (served_rows(..., still=...)). The session context also leaves out redacted rows on every install (they read as an empty observation).memory.askjudges its finished pool after the tag belt as search judges its page (pg_validation.stale_flags), dropping what fails with no refill; its completion and identifier-injection lookups now select the row's identity and version, so an injected fact hit carries its storedversionon every install (it was 0). Under Postgres the precedent fast path, which answers before retrieval from ClickHouse's write marks, is off (LOOM_MEMORY_ASK_PRECEDENTS_FAST_MAX_AGE_HOURSsays so): a precedent is reused only against the checked pool.parked_deliveriesreports), and the pass's outcome counts it underleft. Ahighcandidate's vectors are retired only while the scanned head stands; under Postgres its fence follows the commit, as every other writer's does, so a commit refused for a moved head leaves no fence hiding that head's vectors. A relabel whose commit may have landed unanswered (its answer lost, or the pass cancelled from its COMMIT on) is fenced as any write's is. The graph is judged from ClickHouse's rows and no later scan reads a labelled row, so the sweep owes a high relabel's mined facts right before it commits, as a new projection-repair kind,sensitivity_facts_owed: it closes them and resolves the debt once the relabel is in and ClickHouse holds it, and otherwise (its publication pending, its answer lost, its pass cancelled, a ClickHouse outage, its close failed) the repair closes them once ClickHouse's head of the key reaches the relabel's version, a delete since included, and owes nothing for a relabel that settled below it, judged by the authority's head read withFOR SHARE(settled_head_versions) so a COMMIT still waiting on the synchronous standby is waited for; a debt younger than ten minutes is left alone, as a follow intent is. The close calls the raising edge drop and triple close, each run whatever the other does, so a failure keeps the debt rather than resolving it with facts open; a fallback restate whose interval repair fails is owed on its own as atriples_reconcile, as the reconcile owed it onmain. Onmaina failure after the relabel left them open, and a debt the sweep cannot record fails the candidate unlabelled. A relabel that is in and then fails or is cancelled is still announced; amediumone cancelled after its commit leaves its vectors untagged. The sweep's vector tombstones hold no text or vector (bare), so one that lands after a redaction's purge leaves nothing to scrub; onmainthey carried the row's text and vector. A candidate keeps its key as stored: a user or session sent empty is stored as given, and the sweep reads, labels, retires and announces the row under that key (onmainits vectors were retired under-and stayed). Onmainthe relabel overwrote a head written between the scan and its draw, so a writer'shighcould be relabelledmediumand reindexed, and it read and wrote the candidate by id, so after a namespace was restored into itself under another agent the label went to whichever key held the id at the newer version.memory.redactalso scrubs the later versions of the key that copy the redacted text (each announced asmemory.redacted), and a search row is judged by its real content hash, by its excerpt when it has none or a placeholder; a newer write's row and a fence row stay.memory.restoreof a key so redacted answersredacted: trueand writes nothing.namespace.rollbackto a version held redacted writes it back with no search stub and retires the key's vectors, as for a row that is not embedded (onmainits stub carried the redacted placeholder to search).memory.redactfinds its target by(memory_id, version)in the namespace that holds it (onmainthe newest row of the id across the org, so a restored copy could make it answerredacted=False).memory.get_by_id,memory.update_by_idandmemory.verifyby id act in the one namespace holding a live head of the id that the caller reaches, with one more statement per op.memory.update_by_idwith a new value over a redacted version clearsredacted_at.memory.update_by_id,memory.setandmemory.bulk_setwrite above the head they read when that head's writer's clock ran ahead (onmainthey took the next version, which such a head kept outranking, so the write answered success and was never served).mainit judged ClickHouse's copy and wrote one version drawn before its read, which a head written since or on a replica whose clock ran ahead outranked, while counting it as tombstoned). The tombstone or downgrade goes above a head that still cites the sources judged; a summary rebuilt from other sources is left, anddependents_tombstonedcounts the rows written. Each summary is judged and written by its key, so one memory id held under two keys (a namespace restored into itself under another agent) is written under each, with its own vectors (onmainthe write went by id, to the newest of them); the vectors take the row's version, under Postgres within the commit's lease (a redacted head gets none: its purge is their only writer): a tombstone retires them with no text and a downgrade copies only those of its head's own hash (none for a head written before hashes, whose placeholder cannot tell its own rows from an older version's: under Postgres its document stays owed for the delivery worker, on ClickHouse its rows keep their status untilloom reconcile-status), so neither carries text a redaction of another version may be purging (onmainthe cascade copied every live row, text included). Under Postgres an embedded downgrade owes its search document, settled once ClickHouse holds it at the row's version (held_documents;insert_versions_over_heads(settle_held=True)), so one the copy did not land is built by the delivery worker. Both stores' reads of the summaries take their keys and tags alone. The usage fold matches each memory's totals to its identity, and itsloom.memoryUPDATE picks and filters each row's counters, by org, namespace and memory id, and its cold-start watermark groups the same way (onmainall three went by memory id alone, so in a batch holding one id in two namespaces, as a namespace restored from another's snapshot does, both rows took one namespace's counters and a copy with no usage could take another namespace's; under Postgres they would also reach the authority's head). Two keys holding one id in a namespace both take its totals; the identity read and the UPDATE take each memory's key once, in statements cut by the keys' rendered size (onmainthe identity read bound the batch's orgs, namespaces and ids whole, and long namespace names could push one past ClickHouse's field limit and stop the fold), and under Postgres a row whose org or namespace Postgres cannot store (a NUL character) holds no head, so the fold leaves it out of the heads' update rather than failing the batch each pass, and its filter keeps the sort-key andmemory_idskip-index prunes (checked on clickhouse-local, lightweight UPDATE and ALTER UPDATE alike). The search documents the delivery worker builds now carry the row'sinvalid_at, as the status mirror's copies do, so an invalidated head is not served as valid underas_of. A consolidation's merge tombstones go above the heads they retire, as a delete's does, and leave a row rewritten, pinned or locked since the merge read it; when the canonical key is a merged one, its row goes over that head on the same terms, or the cluster counts as failed.memory.consolidate, on either authority: a redacted row is never a candidate; the summary is written at the model's key in session-over its head only when that head is a merged row still as the merge read it, above it; a key holding a live row the merge never read is left alone (onmainan unprotected one was written over), as is a key another cluster of the same pass took (onmainthe later summary replaced the earlier one on ClickHouse), and the summary takes a key of the cluster's own (the model's key and a hash of the merged ids), or the cluster is recorded as failed with drop reasonkey_taken, as it is withembed_failedwhen the summary cannot be embedded (onmainan embedder failure failed the whole op); a summary written over a merged row's key tombstones that row's verbatim chunks (onmainthey stayed searchable beside it); ahighsummary never takes a merged row's key, so that row is tombstoned with its vectors rather than left for a fence to hide, and a high summary whose fence fails is recorded as afence_faileddrop naming its key (onmainthe op failed after the summary was written); a merged row changed, pinned or locked since the read is left live beside the summary instead of tombstoned, recorded as amerged_row_left_livedrop and a failure reason on the written run (a merged row deleted since is gone, not held); thederived_fromlineage is written once the row is in, whatever the vector does, and no longer links the summary to itself; a failed merge's recorded reason names what was lost by kind and count, and a model reply that is not JSON is recorded without quoting it (onmainboth carried source text into the log andloom.consolidation_runs). Under Postgres it clusters only the rows the authority still serves, and the summary commits with the merged rows as its sources, each still its key's live head at the version read: a merged row deleted, written again, pinned, locked, redacted or erased since the read leaves the cluster for the next pass, recorded as failed. The summary's vector is written under the commit's lease and owed to the delivery worker until it lands. Merged rows that keep moving throughLOOM_PG_ADMISSION_ROUNDSreads are left live beside the summary and recorded: aretire_contendeddrop and a failure reason on the written run. A redaction of a merged source after the merge does not reach the summary, as onmain: redact it too. A copy lifted above a head goes two above it, past a vector-only copy of that head at one above, so its vector retire reaches every vector row.highrow's fence runs after a failed write-fence lift or vector retire too (memory.set,memory.bulk_set,namespace.rollback; onmaineither failure skipped it), and a rollback batch retires and fences its rows before inserting its stubs (onmainevery row went in first, then every stub, then one retire and one fence).memory.dedup_resolve'skeep_duplicatechecks the canonical's lock first and clears the flag before it deletes the canonical; every decision answers 404DEDUP_PAIR_NOT_FOUNDfor a duplicate gone, resolved or flagged against another canonical since the read, and leaves both rows (each tombstone rechecks the head it writes over, read current, its lock included;keep_duplicatereportscanonical_tombstoned: falsefor a canonical deleted since, and a canonical locked after its check answers 423 with the flag already cleared, both rows live). A rollback leaves a key erased since its plan, as the plan leaves a key with no head, and its answer and audit row count what it applied (the key so left inskipped_no_head).memory.outcomereportsquarantined: trueonly when its reject wrote a version (onmainalso when the key had no live head to reject); under Postgres a quarantine whose heads keep moving answersquarantined: falsewith the outcome recorded, and the next negative outcome over the threshold quarantines the key (a 503 would ask for a retry that counts the outcome twice).LOOM_STORAGE_AUTHORITYwith the authority ClickHouse records before it runs and refuses with exit 2 on a mismatch, or when it is configured for Postgres and ClickHouse records none (onmainthere is no record); under Postgres its first connection, pooled or the dedicated one an erasure step opens, also checks before any statement that the databaseLOOM_PG_DSNnames records this deployment. An erasure or an import run from a shell configured for another store would leave or write that store's rows. A command that never touches memory opens no connection, so it runs while Postgres is down, and an offlineloom mint-tokenrefused this way no longer falls back to signing with the root secret. An emptyLOOM_PG_DSNis refused the same way. An erasure refused this way registers no saga, so no recovery worker runs it later, and a refusedrevoke-tokenormint-tokensays so on its one line.src:tag with its namespace (bound as(namespace, tag)pairs read first, as every user-scope step on a replicated table binds its values), and its code-link delete binds(namespace, memory_id).namespace.restoreanswerscounts.erased_skipped(0), a replay answers the counts of the restore it repeats and matches itssnapshot_idin either case (it is stored canonical; an earlier build's restore whose payload id was spelled in upper case is found too, one spelled another way is not) (onmainany audit subject containing the id matched, so an empty id matched every restore), its audit row is written strictly (a restore fails when it cannot be written, so a retry is not taken for done), and the rows a payload builds are checked against the column types before anything is written (snapshot_rows.checked_rows; a snapshot still reads back every stored row): asnapshot_idor memory id that is not a UUID (memory_id,conflict_with,cross_promoted_from_memory_id), an unknownstatus, a count outside aUInt32(evidence_count,recall_count,reinforcement_count,char_limit), a content hash that is not 64 lowercase hex,value_jsonthat is not a JSON object, or a time outside 1970-2106 (in UTC) is refused with 422, and under Postgres also aduplicate_ofthat is not an id, a confidence that is not a finite Float32, or text holding a NUL character or a lone surrogate (onmainmost failed the insert with a 500; under Postgres they committed rows ClickHouse refused); an id in another UUID spelling is stored canonical. Under Postgres any write of a confidence that is not a finite Float32 is a 422 (ClickHouse stores it)./v1/healthreports Postgres detail only under?include=postgres.high; the head's search documents that show its content follow under the commit's lease, so a redaction waits them out, and a newer write's document keeps its own (heal_divergent_entitieslater copies the head's entities onto every document of the key, as onmain). It reads the heads with sequential consistency, and a commit refused by a key written or erased since is read again without it. Onmaina value revised or redacted during the model call took the old value's entities. A write that drew its version before the pass's and lands after its read (a value, a delete, a relabel tohigh) is still overtaken under the ClickHouse authority, as onmainand as by every copy writer there; the storage-authority page states it, and Postgres refuses it. A redacted head is no longer a candidate (its placeholder went to the model onmain). The whole-table candidate scan's addedargMax(redacted_at IS NULL, version)reads one more nullable column: measured fromsystem.query_logover five runs each on a localloom.memoryof 15,813 rows, 851.9 KiB read against 836.5 KiB before, memory 12.2 MiB against 12.1 MiB.memory_dropsrow counts the rows it tombstoned rather than the rows it matched; its tombstone version is drawn once every row is read (one read per row instead of two); each cascade tombstone is written above the head it reads, so a head from a replica whose clock is ahead is tombstoned too. A sweep failure after a row may have landed answers what landed (a commit whose answer was lost counts as possibly landed and is answered with its error: its tombstones are in the authority with their audit rows, which the delivery worker publishes, and theirmemory.tombstonedevents andmemory_dropscount are not sent; a deleted decision's record is retired as a delivery target of its own (DECISION_RECORD), by the request's publish or the delivery worker (pg_publish.retire_decision_records), keeping a record whose writer the authority holds live and copying only records below a version drawn on the retiring host before that read (within the hosts' clock skew, as every version is), under a server-checked start deadline like a carried insert's (the server clock measured on demand, and again once the measure is a minute old) and the write limit an erasure's wait counts; a retirement that fails stays owed and parks on its own, never holding back the memory row) witherrorset to<code>: <message>(a Loom error's own code, orSWEEP_FAILEDwith the detail left to the server log), and one while tombstoning before that is the call's error; a failed match query answers its message without the driver's prefix and URL (ch_errors.error_line), wheremainanswered the raw text.write_versions_by_idsdraws a version only for a row itsupdategives none.blacklist.add, whose pattern is stored by then, answers its pattern id with any sweep failure insweep_error(onmaina sweep failure answered 5xx after the pattern was stored, and a retry stored it again).In detail:
memory.redactalso scrubs the later versions of the key that copy the redacted one's text until the key holds other text (a restatement of the same value is a copy too), the live head left alone (a touch, a lock, the entity pass, a delete's tombstone and a restore each copy the head; onmaindelete, redact, restore brought the text back), andmemory.restoreof such a key answersredacted: trueand writes nothing;memory.dedup_resolve'skeep_duplicatechecks the canonical's lock before it clears the duplicate's flag, and clears the flag before it deletes the canonical, the by-id namespace rule and theupdate_by_idredaction fix (this paragraph), the redact target lookup, the user-erasure consolidated match and its code-link delete,/v1/healthreporting Postgres detail only under?include=postgres(below), and these in the redaction's search-row scrub and the by-id read: an embedding row with a real content hash is judged by the hash rather than the excerpt (a row with the placeholder'0'or none by its excerpt, also against the redaction's version bound), a hashed row stamped after the redaction began stays unless it carries the redacted hash (onmainevery row whose excerpt was not live went, a racing write's included), a fence row stays (onmainthe purge deleted it), and the namespaces holding a live head of an id are judged by each key's newest row, so deleting one of two keys holding the id no longer hides the other, and a key a restore wrote another id over no longer counts as holding the old one. In this paragraph:memory.update_by_idwith a new value over a redacted version clearsredacted_at, so the new value is not marked redacted; and every lookup of a memory by id names a namespace. A namespace restored from another's snapshot keeps the memory ids under newer versions, and an id-only lookup could reach the other copy (under ClickHouse either one, under Postgres the newest).reads.get_by_id,write_versions_by_ids,tombstone_cascade_by_ids,supersede_duplicatesandmark_peers_conflictednow take the namespace as a required argument, and every caller passes the one it acts in: the ops that address a namespace (memory.update,memory.outcome,memory.cross_promote,memory.dedup_resolve,memory.resolve_orphan_duplicates,memory.link,conflicts.resolve,conflicts.propose_revision), the conflict marks and supersessions ofmemory.set,memory.bulk_setandmemory.update_by_id, the conflict resolver, proposals, consolidation, run retention, value updates, projection repair, and the blacklist sweep (each row in its own namespace).memory.get_by_id,memory.update_by_idandmemory.verifyby id act in the one namespace holding a live head of the id that the caller can reach (a miss is read again with sequential consistency, so an id handed out moments ago is found, and a write's lookup,memory.update_by_idandmemory.verifyby id, reads with it at once;memory.verifyby key reads its row with it at once too, one more metadata round trip on every verify by key), and answer not found when it can reach several, or when any holder's grant could not be read (then the request is the server's failure: choosing another holder past it could pick the wrong one);memory.verifyby id ignores anamespacethe call also carries, since MCP fills in the caller's default. Restore keeps the ids on purpose: a snapshot round trip leaves every id an agent recorded addressable. The cost is that a caller who reaches both the source and a live copy addresses either by key, not by id alone. A conflict is surfaced within one namespace, soconflicts.resolvewrites only the body's namespace: a peer id another namespace holds is left alone, where it used to be resolved for an admin of both.memory.redactfinds the namespace that holds(memory_id, version)and reads its target there (under the Postgres authority from the revision journal, so a version not yet delivered to ClickHouse is redacted too); onmainit took the newest version of the id across the org, so a restored copy of a memory could make the redaction of the source's version answerredacted=False. A restore writes fresh versions, so the pair lives in one namespace. The separate check that the version exists is gone: the lookup reads the version fromloom.memory_versions.conflicts.resolvereads its target from the authority before writing:lookup_targetreads ClickHouse, which may not yet hold the Postgres authority's delete of it.A user erasure retires a consolidated row only where the user wrote its
src:key, in the row's own namespace, in both stores. Onmainthe ClickHouse stepconsolidated.tombstonematched the key name across the org, so it also tombstoned another namespace's summary built from a key of the same name; the Postgres step matches the same rows, by (namespace, memory_id), so the two stores never disagree. This trades completeness for precision on one point: asrc:tag names a key of the summary's own namespace, as the writer that tags a summary with its sources writes it, so a summary a client wrote elsewhere with such a tag, or a consolidated row copied to another namespace (memory.copy_to,memory.cross_promote, which keep tags), is no longer retired by the user's erasure, as a plain copy already is not. The memory architecture page states the contract.In the default install every search leg reads the columns
mainreads.One helper reads a row's identity key (
rows.identity_key, typedIdentityKey), from aMemoryRow, a dict or a Postgres record; the per-module copies it replaces are deleted./v1/health/readydoes not wait for Postgres to answer, and/v1/healthanswers 200 withpg_ok: false: a replica that cannot reach it keeps serving every plane that does not use it (code, tracker, knowledge, the dashboard) and answers memory ops with 503POSTGRES_UNAVAILABLE, which the SDKs retry. Taking the replica out of rotation would take those planes down with it while every replica shares the same Postgres. The default/v1/healthruns one Postgres ping;?include=postgresadds apostgresblock with the standby check and the parked counts, read concurrently.memory.rejectand an outcome's quarantine read the key's heads from the authority and commit over them, reading them again when one moved (up toLOOM_PG_ADMISSION_ROUNDS); their vectors retire under the commit's lease, and a failure there is answered once the revision is published. A supersession draws its version before its read and is not lifted, so any head above that version keeps the key: its row is overtaken, neither heard as written nor as unconfirmed. Copy writers (touch, lock, unpin, verify, move, expiry, a delete's tombstone, a status mark, supersession, a cascade tombstone,memory.apply's label and demote,memory.dedup_resolve's status flip,memory.proposalsdecisions, the entity pass, the crystallize tag, the observation worker's DONE mark,memory.restoreandnamespace.rollback, which commits a batch at a time over the heads read just before it, a head moved since answering 503 with the earlier batches written, whose batch is announced once its rows are in, its search stubs, vector retirements and fences landing under the commit's lease and a reinstated row's search document owed until its stub lands, whose audit row counts the batches that landed before a 503, and which under Postgres reinstates each version as the authority's revision holds it, its commit refusing one a redaction scrubbed since it read it, so a redaction is never undone) are built under the Postgres authority from the head Postgres holds and commit only over that very version: a value, delete, pin, lock, status or redaction committed since (a redaction scrubs in place, a deleted head included) answers 503ADMISSION_CONTENDEDfor the call, whose retry reads the newer head. A bulk read that feeds a write,get_many_by_keys(strong=True), reads Postgres with ClickHouse's wildcard rules. Expiry,memory.apply's filter target and the observation worker read ClickHouse first and look each head up again: each acts on a newer head that still qualifies (still expired, still matching the filter, still a pending observation) (so a key whose delivery is parked is not passed over on every run) and leave the rest, which expiry counts asmoved_skippedinmemory.sweep_expired; the observation worker's DONE mark is built from the heads read just before it commits, and only over a head that still holds the text distilled. A writer that rechecks no head (the period digest (loom period-digest),observe.record,namespace.restore, the lesson import,memory.delete_version's write-back and the write fence's lift) commits what it read, as onmain: one racing a redaction can write the text back as a new version, which is then deleted and redacted in turn.memory.redactreads, inside its transaction, the locks on the key and on every profile key with a revision built from the memory (the keys the handler checks), and the key's live head: one written or restored since its check answers 503; it re-reads the head (and each profile key's head) before it scrubs their search rows. A redacted head counts as no live head. An embedding row with a real content hash is judged by it against the live head's, read from the authority, so under Postgres an older row ClickHouse still serves as live goes; one without a hash cannot be matched to a write and is judged by its excerpt; a fence row (no excerpt, terms or vector) holds no text and stays, so an older vector in flight stays hidden under ahighhead. A redaction's fence ends a delivery's lease, so the scrubbed revision publishes at once, and keeps the ended lease inmemory_deliveries.fenced_until(a column of001_memory_authority.sql): its holder may still be sending the old text until then, so a retry of a call stopped while it waited, which reads the deliveries of the copies the first call scrubbed too, and an erasure of the scope wait it out, a delivery parked since included, and the sweep keeps a delivery the next claim settles until that fence and the insert bound have passed, however often it is fenced again. A hashed row stamped after the redaction began is a newer write's and stays, unless it carries the redacted version's content hash (a restore's mirror of the old excerpt); a profile head the redaction dropped bounds nothing. Under Postgres the chunks of a longmemory.setvalue are judged by the chunks the key's live heads write, in any session, read from the authority, so an older value's chunks ClickHouse still holds as live go, on a retry as well; any other chunk, and every chunk on the ClickHouse authority, is judged by the chunks ClickHouse holds as live, as onmain(a build with another chunker would plan other hashes, and ClickHouse is the authority there). An embedding writer that holds no delivery lease (the embedding worker, a re-embed, a long value's chunks) and read the text before the redaction can land its row after the scrub; a later write hides that row from search, but only a retry of the redaction removes its text (a chunk's tombstone keeps the content it retires). The kept chunks are planned as far as the key's stored chunks reach, and a search's chunk check as far as the page's furthest chunk of the key, so a key written under a higher cap than today's keeps and serves all of them; any other plan stops at today's cap, as onmain. A restore racing a redaction ends by authority: under Postgres the redaction answers 503 and its retry leaves the restored head live; on the ClickHouse authority a restore landing before the copies are read is scrubbed with them.memory.restoreroutes from the head the authority holds, so under Postgres a delete not yet delivered to ClickHouse is restored. Under Postgres, ahighrow (memory.set,memory.bulk_set,memory.update,memory.update_by_id,memory.restore,namespace.rollback, a consolidation's summary) is fenced once whenever its commit may have landed (its answer received, lost, or the write cancelled from its COMMIT on, the connection's release included; a cancel before it rolls back and fences nothing), a lost one where its key's head, read withFOR SHAREin the commit's key order and rolled back so a COMMIT still waiting on the synchronous standby is waited for without the read waiting on the standby itself, is that row or absent (every row, recorded as afenced_outcome_unknowndrop, when the read fails; a restore whose answer was lost reads its head back the same way and answers a plain retryable 503 only when that head is below it, since heads only move up), and the fence runs to its end when the request is cancelled again (server/auth/shielded.pymoves toserver/core/shielded.pyso the memory plane can use it); a fence that fails then answers as the commit does, the failure recorded as afence_faileddrop under the op naming the key (fence_failed_outcome_unknownwhen the commit's own answer was lost), so a retry never writes it twice; its old vectors still retire with its publication or through the delivery worker, and a copy in flight goes unfenced until a later write to the key. Under Postgres an Undo of a retirement brings back the status the authority's revisions of the key held before it (memory_repo.status_before), not ClickHouse's history, which may still lack a revision whose publication is owed; on either authority that read matches the key as well as the memory id (onmainit matched the id alone, so after a namespace restored into itself under another agent an Undo could take the status of the other key holding the id). A restore's search document (for an Undo, its search rows served again) is written under its commit's lease; under Postgres an embedded row owes it until it lands, so the delivery worker builds one a failed write left, and the restore answers as written without reading the key again. On the ClickHouse authority a restore that landed with its answer lost still announces and writes its search document, as onmain. Under Postgres the repairs that copy a key's search rows outside a commit (a retry finishing an Undo that landed late, a restore of a live key whose undelete left its search row deleted) are left to the delivery worker, which builds the document the commit owes; the repair never brings back a row for a redacted head. The redaction acts on the key of the version it names: onmainit took the newest row of the id, which another key holds after a namespace is restored into itself under another agent. Amemory.restorewhose memory an erasure removed since its read answers 404, not a 503 that asks for a retry; deletion evidence lastsLOOM_PG_ERASURE_EVIDENCE_HOURSjudged by its age where it is read (the delivery worker's sweep only reclaims expired rows, and an erasure of an id whose evidence expired starts it again); anamespace.restoreinto a namespace leaves out the snapshot's memories an erasure removed from it while their evidence is kept, since their rows cannot be told from a stale writer's, restores the rest and counts the ones left out incounts.erased_skipped(0 under the ClickHouse authority, where a restore writes every memory, as onmain); a restore under Postgres commits in batches of the newLOOM_PG_RESTORE_BATCH_ROWS(default 500; one transaction for the whole payload outlived a commit's lease from about 20,000 memories: measured with 20,000 and 50,000 synthetic memories posted tonamespace.restoreon a local server against Postgres 16, before 503, after 200 in 12.8 s and 37.9 s on the publishing path, by posting a generated payload to/v1/namespace.restore); once a batch's publication is pending the rest are only committed, for the delivery worker to publish, claimable by the delivery worker at once, and the restore completes with the newpublication_pending: true(until the worker has published them, a search or semantic write in the namespace answersPROJECTION_BEHINDpast its wait); its replay lookup reads with sequential consistency, so a retry on another replica finds it; an erasure that lands between the check and a batch refuses that batch with 409PRECONDITION_FAILED: the batches before it stay, and the retry writes every memory again without those; a payload memory withoutupdated_atorlast_reinforced_atlands itscreated_at(the restore time when it has none; onmainit failed the insert). The restore is done for thatsnapshot_id: a replay writes nothing, so the memories it left out never come back from it; a snapshot first restored after their evidence expires writes them, as every restore does under the ClickHouse authority. A replay answers thecountsits restore recorded,erased_skippedincluded (0 for a restore by an earlier build). A ClickHouse-only boot withLOOM_BOOT_MIGRATE=0serves without theloom.storage_authoritytable and writes no record; a Postgres one lists the Postgres files it skips in/v1/healthpending_migrationswith apg:prefix (pg:<ledger unreadable>when it cannot read the ledger) and stays not ready on/v1/health/ready: a skipped file until the process restarts after it is applied, as for a skipped ClickHouse file, and an unreadable ledger until a readiness probe reads it; a ledger that disagrees with the build refuses the boot. In the default install a by-id op reads one more statement than onmain, the holders' namespaces: an org-widememory_idskip-index read of the keys that ever held the id, then each such key's versions by its sort-key prefix, so the cost grows with how many keys held the id (one, unless a namespace was restored). Measured fromsystem.query_logover fivememory.get_by_idcalls against a localloom.memoryof 5,262 rows: the holders statement read 258 rows in 4 marks (11 ms on average), the narrowed first phase 1 row in 1 mark (4 ms) and the second phase 258 rows in 3 marks (12 ms); the holders statement selects the same skip-index granules as the first phase does across the org. These are a floor on a small table, not a production figure: the holders statement's cost follows the org's granules thememory_idskip index selects, as the first phase's does onmain. Folding the first phase into it would save that repeated read, at the cost ofnamespace_for_idreturning a key hint andget_by_idtaking one for its three by-id callers; it is left for a measurement on a large org to justify. The point read's first phase is narrowed to the namespace found, and its second reads the newest of the id's live rows there, within the caller's read scope as its first does (onmainthe second applied no scope).Compatibility, rollout and rollback
stale_droppedonmemory.searchand onmemory.search_traceandmoved_skippedonmemory.sweep_expired(0 under the ClickHouse authority), andredactedonmemory.restore; no op or field removed;namespace.restore's input is narrowed (below), a break for a payload that held a value its column cannot.namespace.restoreaddscounts.erased_skippedandpublication_pending, and under Postgres can answerPRECONDITION_FAILED(409, above). New error codes:POSTGRES_UNAVAILABLE(503),ADMISSION_CONTENDED(503),PROJECTION_BEHIND(503),PUBLICATION_PENDING(503);IDEMPOTENT_TAKEN_OVER(503) when a retry took over a request's idempotency key./v1/healthaddsstorage_authority, and under Postgrespg_ok;?include=postgresadds apostgresblock (standby:synchronouswhile the standbyssynchronous_standby_nameswaits for (FIRST n,ANY n,n (...), else one) are attached,primary_onlywhen none is named,waitingwhen fewer are attached, null when Postgres did not answer or the role cannot see the standbys;parked_deliveries,parked_audits); the boot check warns on fewer attached than required too.VALIDATION_FAILED(422) under Postgres for a string with a NUL character or a lone surrogate, or a confidence that is not a finite Float32.docs/operations/postgres.md.schemas/pg_migrations/001_memory_authority.sqlchanged during review; a database that applied an earlier head of this branch drops itsloomschema before booting this one (no release carries 001 yet).loom.storage_authority(one row) and, on a Postgres deployment, theloomschema in Postgres. A Postgres deployment cannot roll back to a build without this change (rolling-upgrade rule 29).process:loom; naming each worker would take a pipeline actor set per pass by the worker supervisor, which cannot read the memory plane's actor names today.memory.setchunk of its key, as onmain, because a chunk row carries no version; a newer head written between a commit and its fence, or between the sensitivity sweep's check of the head it scanned and its fence (the sweep then leaves that head unlabelled, and the embedding worker's orphan pass embeds it again), loses its chunks until the key is written again. Keeping them needs a version onloom.memory_chunks.get_by_id), as onmain; after a namespace is restored into itself under another agent the id is held under two keys.loom.entity_triple_rows, as onmain; a value whose triples are linked only by key (loom.entity_triple_memories, written before that table) keeps them until it is written again.high(amemory.setor update over an embedded head on ClickHouse,memory.bulk_set, a rollback, and the copy retire in a high fence) still carry the row's text, as onmain; the sweep's and the publish's are bare.pg_xact_status) instead of fencing every row.Tests
make format lint typecheckpass; unit:tests/unit/test_pg_authority.py(durability verdicts, migration plan and drift, the row codec, gap checks, recorded authority in every case, pool settings, transaction error mapping, NUL refusal, vector reuse, delivery isolation and parking, the idempotency unbind),tests/unit/test_retention_overrides.py(no memory or vector TTL under Postgres).LOOM_STORAGE_AUTHORITY=postgresand Postgres 16 and 18 with a synchronous standby (CI jobintegration-postgres, which also runs the memory, isolation, idempotency, erasure and restored-id suites, its isolation gates with the test end-user issuer and the code scope set, whatever the memory suites did, over the isolation files that write or read memory (the isolation part's run-claim, extraction-queue and projection-failure files hold no Postgres row)):tests/integration/test_pg_authority.py, among them: an org blacklist sweep tombstoning a head whose delivery is parked, an audit outbox row ClickHouse keeps refusing parked, counted in/v1/healthand published after the documented reset, an id op on a restored source reading the source, an org blacklist sweep tombstoning a source and its restored copy, an erasure of a parked owed audit row (namespace and user sagas) publishing it to ClickHouse once from the outbox, a redaction leaving a restored copy's head alone, a redaction refused by a lock on a profile key rebuilt without the memory, the head and its ClickHouse rows compared field by field, compare-and-set, concurrent restatements, pinned peers, an unpublished commit published by the next admission (memory row and search document), a replayed lost commit, cross-org and narrowed-scope reads answeringfound=False, NUL refusal, redact of the journal and history, clear, namespace and user erasure, the usage fold, a retry's takeover of an idempotency key, three concurrent migrations of one database, and key collation.scripts/ops/benchmark.py --op memory.set --concurrency 5 --duration 30: p50/p95/p99 372/646/717 ms against the ClickHouse authority's 338/605/702. At concurrency 50 into one namespace: 10.4 commits/s with 5%ADMISSION_CONTENDEDagainst the ClickHouse authority's 13.2 writes/s, the host's limit for both.memory.setof one fact under six keys: ClickHouse authority 6clear; Postgres authority 1clearand 5merge.timeout-minutesgoes from 45 to 60. Its pytest step takes 37 to 44 minutes onmainand this change adds about 576 unit tests, so the job reached the limit with every step but the last passed; no test is skipped or changed.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. Every path was run against a private ClickHouse and Postgres 16 with a synchronous standby.
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.main; no merged migration is edited.docs/describe the system as it now is, and this description names any operator steps and wire changes.git commit -s).🤖 Generated with Claude Code