Skip to content

Live memory can be held in Postgres, with search and history in ClickHouse - #158

Merged
zlareb1 merged 1 commit into
mainfrom
feat/pg-live-memory
Nov 7, 2026
Merged

zlareb1 merged 1 commit into
mainfrom
feat/pg-live-memory

Conversation

@zlareb1

@zlareb1 zlareb1 commented Oct 30, 2026 •

Copy link
Copy Markdown
Member

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 main when LOOM_STORAGE_AUTHORITY is unset.

What this pull request carries

Part State
Current content, provenance, atomic audit, admission generations, revision / job / idempotency contracts, erasure, recorded authority in this head
Search projection published from revisions, bounded batching, idempotent recovery, poison isolation, explicit 503 outcomes in this head: publication, isolation, parking, a finite barrier per search, candidates validated against the heads with bounded refill and stale_dropped
Retained history, reconciliation, retention sweep on the authority, failover and restore procedures, qualification of change capture for mirrors; the reads of ClickHouse alone (memory.keys, memory.statuses, memory.list's counts, memory.related, memory.aggregate, memory.inspect's counts, tags and categories, the revisions namespace.audit and namespace.validate findings cite, whose hash is the authority head's, as memory.get serves it) checked against the authority in progress
Search-quality validation, model generations, SDK error mapping, fenced authority cutover in progress (SDK error codes in this head)
Placement units, fair scheduling, capacity qualification in progress (per-namespace admission limit measured in this head)

A part marked in progress is not in this head.

Changelog category (leave one):

  • New Feature

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.set of one fact under six keys land as six clear facts. Under the Postgres authority one lands and five merge into it.

Design

Full page: docs/architecture/storage-authority.md. In short:

  • One choke point. Postgres holds the head of every key as the complete loom.memory row (loom.memory_current), replaced only by a version that is not older, which is what loom.memory FINAL serves. Every writer already builds full rows and inserts them through insert_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's loom.memory, memory_embeddings, memory_versions and audit_log become projections of committed revisions.
  • Admission. Every commit in a namespace advances its generation; an admission captures the namespace's published watermark and the policy generations, reaches its verdict in ClickHouse outside any transaction, and its commit checks the gap inside the transaction, holding the generation lock: rows that cannot be peers (type, key, a vector clearly out of reach on this process's copy, and for memory.set liveness and scope) are ruled out without I/O; otherwise memory.set adds the gap's rows to its peer rows and re-reaches its verdict, bulk_set measures 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 503 ADMISSION_CONTENDED after LOOM_PG_ADMISSION_DEADLINE_MS. The vectors this process's commits wrote (pg_admission._recent, at most LOOM_PG_ADMISSION_RECENT_VECTORS) only rule a gap row out of reach and are never served, so a redaction leaves them.
  • Head recheck. For memory.set, memory.bulk_set, memory.update_by_id and memory.clear, the commit locks each written key's head and compares it with the row the write read: if_match_sha256 requires 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_set and memory.clear start over from the scrubbed head, and memory.update_by_id answers 503 ADMISSION_CONTENDED so 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).
  • Delivery. Each revision owes ClickHouse its memory row, audit row (memory.revision, naming as actor the token's principal, else the pipeline stage's actor, else - inside a request and process:loom for 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 as memory.set or memory.update_by_id leaves 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 the pg_delivery worker, which re-embeds from the revision (vectors never pass through Postgres).
  • Idempotency. Keys move to loom.idempotency beside the revisions and fail closed. The commit marks the key committed under 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.
  • Erasure. pg_memory.delete runs 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 to loom.audit_outbox in 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 in loom.idempotency_fences while holding the org's claim lock for those two statements only (a keyed request that meets it answers IDEMPOTENT_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 leaves verified_at unset, 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-verify now 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).
  • Retries. A delivery or outbox publish that fails counts an attempt, re-tried when its lease ends and parked after 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 marked held just 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.
  • Redaction. memory.redact scrubs 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.
  • Recorded authority. Recorded once per deployment in ClickHouse (loom.storage_authority, migration 085) and Postgres; a replica configured for the other refuses to start.
  • Postgres errors. A lost connection, a cancelled statement, a deadlock or serialization failure, a read-only node, a server short of a resource (53100, 53200, 53300, 58000, 58030) and a cached statement a migration changed answer 503 POSTGRES_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 500 POSTGRES_REFUSED naming the SQLSTATE, constraint, table and column, never the row or argument the driver's text quotes; it fails the same way on a retry.
  • Sessions pin 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.
  • Durability check at boot: Loom's sessions commit with synchronous_commit = on; LOOM_PG_DURABILITY=synchronous (default) refuses a primary whose synchronous_standby_names is empty, and boot warns when no synchronous standby is attached or pg_stat_replication is not visible; local accepts 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.set at concurrency 5 answered ADMISSION_CONTENDED, since every commit in a busy namespace moves it).

Decisions and evidence

  • Driver: asyncpg (Apache-2.0, async-native, with its own pool).
  • Postgres 16+, core features only; CI on stock postgres:16 with one synchronous standby (dev/ci_start_postgres.sh).
  • Migrations: numbered SQL in 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).
  • Five indexes do not lead with org (the delivery queue by lease_until, settled deliveries by lease_until, the audit outbox by due_at, idempotency retention by expires_at, erasure evidence by erased_at): all are maintenance queues local to one database; every tenant read uses an org-led key.
  • Identity, grants, revocation, namespace configuration and tasks stay in ClickHouse (about 250 statements over 60 modules, most on security paths); their changes advance admission generations through the existing change hooks. Moving them is its own design.
  • LOOM_RETENTION_MEMORY_DAYS and a namespace's retention_days are ClickHouse TTLs that would delete ClickHouse's copy alone: under Postgres the TTL is not put on loom.memory and the boot refuses the setting. A retention sweep on the authority comes with retained history in this PR.
  • Change capture: the evaluated tool's documented limits include no support for unplanned primary promotion, so the revision archive is delivered by Loom's own job from the journal (the loom.memory publication feeds memory_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.

  • A database per tenant: rejected. A connection reaches one database, so every process needs a pool per tenant (tenants × processes × a pooler's usual default of 20); a logical slot decodes one database, so change capture needs a slot and a walsender per tenant, each reading the whole WAL (max_replication_slots and max_wal_senders default 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 DATABASE erasure 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.
  • Copy-on-write branching: not a dependency. A branch is a copy-on-write snapshot with a new Postgres on it, created in seconds, with one primary and no standby. CI keeps the postgres:16 container 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.
  • The pooler: Managed Postgres's pooler runs in transaction mode, and Loom's migrations hold a session advisory lock while its driver prepares statements, so LOOM_PG_DSN names the direct endpoint (docs/operations/postgres.md).

Research summary

  • Outbox versus CDC: an outbox written in the same transaction gives exactly the rows a commit made, numbered by the writer; CDC gives the same rows later and in its own order, with tables of one transaction visible at different times (the change-capture tool's documented ordering limits). Enrichment needs the former; mirrors can use the latter.
  • Validating candidates against the authority is how search stays correct while its index lags: the index proposes, the authority disposes.
  • Fencing: every lease carries a token checked by the store on every update; a publisher also stops sending before its lease ends (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 when LOOM_CH_TIMEOUT_WRITE_S is 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.request and memory.redact answer after their wait (about 80 s past the latest lease with the default settings). A committed memory.bulk_set replay 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 is PublicationPending and 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: a memory.restore of such a key's deleted row mirrors a row with no text or vector, and an as_of replay from before the retirement does not find the key's vector); on the ClickHouse authority a retirement copies the rows, as on main. 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-status under Postgres holds back a key whose authority head is newer than its loom.memory row 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.
  • Managed Postgres: one HA standby replicates asynchronously, two synchronously. A self-hosted HA manager must run in its strict synchronous mode.

Scope and risk

Touches the memory write funnel, point reads, memory.set/bulk_set admission, memory.clear, memory.reject, redaction, the usage fold, the idempotency gate, erasure and boot. Each Postgres branch is taken only when LOOM_STORAGE_AUTHORITY=postgres; under clickhouse the paths are main's (the idempotency gate calls check exactly as before; check_on_commit gets candidate_rows=None) except for the fixes listed below, which reach a ClickHouse-only install too. New on every deployment: the authority row in loom.storage_authority at first boot (not by a process with LOOM_BOOT_MIGRATE=0, which only checks it), storage_authority in /v1/health, an idle pg_delivery worker.

namespace.snapshot reads 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.reject and memory.clear are 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, which memory.clear sends before it retires a page's vectors), and a ClickHouse follow-up that then fails answers its own error; every other write answers 503 PUBLICATION_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.inspect lists its newest rows (its located read selects org, namespace and redacted_at on every install; a sample can be short of sample_limit while 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_keys reads the authority's heads, so memory.bulk_get (and the export, which reads values through it), a search's bodies="unit" read, procedure.match / procedure.list bodies, the extraction prompt and memory.proposals answer as memory.get does, a newer head not yet in ClickHouse included and a high head 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 select redacted_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 under as_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 revisions namespace.audit and namespace.validate findings cite, whose hash is the authority head's, as memory.get serves 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; 503 PROJECTION_BEHIND past 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=postgres reports), 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; matched counts what ClickHouse matched and the parked heads it tombstoned, and truncated only ClickHouse's matches past the limit. A search tier whose check fails is left out and named in degraded, without marking /v1/health degraded. memory.search_trace waits at the search barrier too, serves a hit only while the authority's head shows it (a replay under as_of as it read, as memory.search serves one), and its vector read selects the row's agent, user and session on every install; memory.import decides 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 503 PROJECTION_BEHIND) and serves a fact hit only when its document shows a live head's content; dropped hits are counted in stale_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 by decision.outcome and 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:

  • A period digest fails a period alone when its source read, writer lookup, model call, embedding or row write fails: nothing more is written for it, the failure is recorded against the period, and a later pass writes it with its lineage and entities. On main a 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 (on main it 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 (on main the next pass, and any rewrite, wrote a new live version of it; the --rewrite help 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, renamed periods_skipped (the CLI prints it as skipped as written or taken out), counts every one of the identity (on main, periods_existing stopped at the cap). Its failure lines carry the error's type and code, not its message.
  • A structured profile build that reads fewer facts than its digest counted, which on ClickHouse alone needs the two reads to reach replicas at different points of replication while the second digest still matches, now tags the profile short (it reads as stale and 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.
  • Every copy writer that draws its version after its read (lock, unlock, unpin, touch, verify, delete, 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) and memory.reject lift above the head they read; a restore's search row takes its version: on main a 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 answering locked over an unlocked head). The row, its vector retirement and the op's answer share that version.
  • The background reads whose rows go to a model, or onto a plain derived row, serve a ClickHouse row only while it is the authority's live head at that version (served_rows), as the entity extractor's candidates do, so under Postgres a delete, a rewrite, a status, a high label 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, for LOOM_PG_DELIVERY_LEASE_SECONDS at a time, counted in the pass's new skipped_behind; that setting's description says so), the profile builders' facts (a structured profile built short of the facts it counted carries the sources digest short, which no digest takes, so it reads as behind (profile.structured answers stale) 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_deliveries counts 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.ask judges 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 stored version on 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_HOURS says so): a precedent is reused only against the checked pool.
  • The sensitivity sweep reads each candidate's head by its key, strong, and relabels only the head it scanned, above that head: a head written since the scan holds text its detector did not read, or its writer's own label, and is left: the pass keeps its cursor at that agent, so the next pass reads the newer head (under Postgres, a head whose delivery is parked waits for the delivery's retry, which parked_deliveries reports), and the pass's outcome counts it under left. A high candidate'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 with FOR 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 a triples_reconcile, as the reconcile owed it on main. On main a 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; a medium one 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; on main they 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 (on main its vectors were retired under - and stayed). On main the relabel overwrote a head written between the scan and its draw, so a writer's high could be relabelled medium and 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.redact also scrubs the later versions of the key that copy the redacted text (each announced as memory.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.restore of a key so redacted answers redacted: true and writes nothing.
  • namespace.rollback to 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 (on main its stub carried the redacted placeholder to search).
  • memory.redact finds its target by (memory_id, version) in the namespace that holds it (on main the newest row of the id across the org, so a restored copy could make it answer redacted=False).
  • Every lookup of a memory by id names a namespace; memory.get_by_id, memory.update_by_id and memory.verify by 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_id with a new value over a redacted version clears redacted_at.
  • memory.update_by_id, memory.set and memory.bulk_set write above the head they read when that head's writer's clock ran ahead (on main they took the next version, which such a head kept outranking, so the write answered success and was never served).
  • A source's delete finds each consolidated summary built from it on the authority and judges it on its own head there, counting its live sources in one read (on main it 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, and dependents_tombstoned counts 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 (on main the 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 until loom reconcile-status), so neither carries text a redaction of another version may be purging (on main the 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 its loom.memory UPDATE picks and filters each row's counters, by org, namespace and memory id, and its cold-start watermark groups the same way (on main all 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 (on main the 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 and memory_id skip-index prunes (checked on clickhouse-local, lightweight UPDATE and ALTER UPDATE alike). The search documents the delivery worker builds now carry the row's invalid_at, as the status mirror's copies do, so an invalidated head is not served as valid under as_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 (on main an unprotected one was written over), as is a key another cluster of the same pass took (on main the 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 reason key_taken, as it is with embed_failed when the summary cannot be embedded (on main an embedder failure failed the whole op); a summary written over a merged row's key tombstones that row's verbatim chunks (on main they stayed searchable beside it); a high summary 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 a fence_failed drop naming its key (on main the 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 a merged_row_left_live drop and a failure reason on the written run (a merged row deleted since is gone, not held); the derived_from lineage 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 (on main both carried source text into the log and loom.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 through LOOM_PG_ADMISSION_ROUNDS reads are left live beside the summary and recorded: a retire_contended drop and a failure reason on the written run. A redaction of a merged source after the merge does not reach the summary, as on main: 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.
  • A high row's fence runs after a failed write-fence lift or vector retire too (memory.set, memory.bulk_set, namespace.rollback; on main either failure skipped it), and a rollback batch retires and fences its rows before inserting its stubs (on main every row went in first, then every stub, then one retire and one fence).
  • memory.dedup_resolve's keep_duplicate checks the canonical's lock first and clears the flag before it deletes the canonical; every decision answers 404 DEDUP_PAIR_NOT_FOUND for 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_duplicate reports canonical_tombstoned: false for 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 in skipped_no_head).
  • memory.outcome reports quarantined: true only when its reject wrote a version (on main also when the key had no live head to reject); under Postgres a quarantine whose heads keep moving answers quarantined: false with 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).
  • A CLI command, the in-process importers included, compares its LOOM_STORAGE_AUTHORITY with 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 (on main there is no record); under Postgres its first connection, pooled or the dedicated one an erasure step opens, also checks before any statement that the database LOOM_PG_DSN names 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 offline loom mint-token refused this way no longer falls back to signing with the root secret. An empty LOOM_PG_DSN is refused the same way. An erasure refused this way registers no saga, so no recovery worker runs it later, and a refused revoke-token or mint-token says so on its one line.
  • The user-erasure match of consolidated rows pairs a 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.restore answers counts.erased_skipped (0), a replay answers the counts of the restore it repeats and matches its snapshot_id in 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) (on main any 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): a snapshot_id or memory id that is not a UUID (memory_id, conflict_with, cross_promoted_from_memory_id), an unknown status, a count outside a UInt32 (evidence_count, recall_count, reinforcement_count, char_limit), a content hash that is not 64 lowercase hex, value_json that is not a JSON object, or a time outside 1970-2106 (in UTC) is refused with 422, and under Postgres also a duplicate_of that is not an id, a confidence that is not a finite Float32, or text holding a NUL character or a lone surrogate (on main most 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/health reports Postgres detail only under ?include=postgres.
  • The entity extractor writes a row's entities only onto a head that still holds the text it extracted them from (the version it read, or a later copy of the same content), with no entities of its own, unredacted and not 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_entities later copies the head's entities onto every document of the key, as on main). It reads the heads with sequential consistency, and a commit refused by a key written or erased since is read again without it. On main a 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 to high) is still overtaken under the ClickHouse authority, as on main and 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 on main). The whole-table candidate scan's added argMax(redacted_at IS NULL, version) reads one more nullable column: measured from system.query_log over five runs each on a local loom.memory of 15,813 rows, 851.9 KiB read against 836.5 KiB before, memory 12.2 MiB against 12.1 MiB.
  • Two overlapping blacklist cache refreshes install the later read: one that read earlier no longer replaces it, and one that read before an invalidation installs what it read but leaves the cache to be read again.
  • The blacklist sweep's memory_drops row 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 their memory.tombstoned events and memory_drops count 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) with error set to <code>: <message> (a Loom error's own code, or SWEEP_FAILED with 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), where main answered the raw text. write_versions_by_ids draws a version only for a row its update gives none. blacklist.add, whose pattern is stored by then, answers its pattern id with any sweep failure in sweep_error (on main a sweep failure answered 5xx after the pattern was stored, and a retry stored it again).

In detail: memory.redact also 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; on main delete, redact, restore brought the text back), and memory.restore of such a key answers redacted: true and writes nothing; memory.dedup_resolve's keep_duplicate checks 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 the update_by_id redaction fix (this paragraph), the redact target lookup, the user-erasure consolidated match and its code-link delete, /v1/health reporting 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 (on main every row whose excerpt was not live went, a racing write's included), a fence row stays (on main the 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_id with a new value over a redacted version clears redacted_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_duplicates and mark_peers_conflicted now 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 of memory.set, memory.bulk_set and memory.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_id and memory.verify by 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_id and memory.verify by id, reads with it at once; memory.verify by 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.verify by id ignores a namespace the 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, so conflicts.resolve writes 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.redact finds 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); on main it 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 answer redacted=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 from loom.memory_versions.

conflicts.resolve reads its target from the authority before writing: lookup_target reads 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. On main the ClickHouse step consolidated.tombstone matched 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: a src: 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 main reads.

One helper reads a row's identity key (rows.identity_key, typed IdentityKey), from a MemoryRow, a dict or a Postgres record; the per-module copies it replaces are deleted.

/v1/health/ready does not wait for Postgres to answer, and /v1/health answers 200 with pg_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 503 POSTGRES_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/health runs one Postgres ping; ?include=postgres adds a postgres block with the standby check and the parked counts, read concurrently.

memory.reject and an outcome's quarantine read the key's heads from the authority and commit over them, reading them again when one moved (up to LOOM_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.proposals decisions, the entity pass, the crystallize tag, the observation worker's DONE mark, memory.restore and namespace.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 503 ADMISSION_CONTENDED for 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 as moved_skipped in memory.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 on main: one racing a redaction can write the text back as a new version, which is then deleted and redacted in turn. memory.redact reads, 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 a high head. A redaction's fence ends a delivery's lease, so the scrubbed revision publishes at once, and keeps the ended lease in memory_deliveries.fenced_until (a column of 001_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 long memory.set value 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 on main (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 on main. 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.restore routes from the head the authority holds, so under Postgres a delete not yet delivered to ClickHouse is restored. Under Postgres, a high row (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 with FOR SHARE in 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 a fenced_outcome_unknown drop, 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.py moves to server/core/shielded.py so the memory plane can use it); a fence that fails then answers as the commit does, the failure recorded as a fence_failed drop under the op naming the key (fence_failed_outcome_unknown when 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 (on main it 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 on main. 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: on main it took the newest row of the id, which another key holds after a namespace is restored into itself under another agent. A memory.restore whose memory an erasure removed since its read answers 404, not a 503 that asks for a retry; deletion evidence lasts LOOM_PG_ERASURE_EVIDENCE_HOURS judged 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); a namespace.restore into 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 in counts.erased_skipped (0 under the ClickHouse authority, where a restore writes every memory, as on main); a restore under Postgres commits in batches of the new LOOM_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 to namespace.restore on 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 new publication_pending: true (until the worker has published them, a search or semantic write in the namespace answers PROJECTION_BEHIND past 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 409 PRECONDITION_FAILED: the batches before it stay, and the retry writes every memory again without those; a payload memory without updated_at or last_reinforced_at lands its created_at (the restore time when it has none; on main it failed the insert). The restore is done for that snapshot_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 the counts its restore recorded, erased_skipped included (0 for a restore by an earlier build). A ClickHouse-only boot with LOOM_BOOT_MIGRATE=0 serves without the loom.storage_authority table and writes no record; a Postgres one lists the Postgres files it skips in /v1/health pending_migrations with a pg: 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 on main, the holders' namespaces: an org-wide memory_id skip-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 from system.query_log over five memory.get_by_id calls against a local loom.memory of 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 the memory_id skip index selects, as the first phase's does on main. Folding the first phase into it would save that repeated read, at the cost of namespace_for_id returning a key hint and get_by_id taking 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 (on main the second applied no scope).

Compatibility, rollout and rollback

  • Wire: four response fields added, stale_dropped on memory.search and on memory.search_trace and moved_skipped on memory.sweep_expired (0 under the ClickHouse authority), and redacted on memory.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.restore adds counts.erased_skipped and publication_pending, and under Postgres can answer PRECONDITION_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/health adds storage_authority, and under Postgres pg_ok; ?include=postgres adds a postgres block (standby: synchronous while the standbys synchronous_standby_names waits for (FIRST n, ANY n, n (...), else one) are attached, primary_only when none is named, waiting when 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.
  • Operator steps: none for the ClickHouse authority (migration 085 applies at boot). For Postgres: docs/operations/postgres.md. schemas/pg_migrations/001_memory_authority.sql changed during review; a database that applied an earlier head of this branch drops its loom schema before booting this one (no release carries 001 yet).
  • Rollback: reverting leaves loom.storage_authority (one row) and, on a Postgres deployment, the loom schema in Postgres. A Postgres deployment cannot roll back to a build without this change (rolling-upgrade rule 29).
  • Follow-up, not in this change: a background worker's revisions are audited as 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.
  • Follow-up, not in this change: a 'high' row's fence tombstones every live memory.set chunk of its key, as on main, 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 on loom.memory_chunks.
  • Follow-up, not in this change: under Postgres, a restore of an episodic or profile row (not embedded, so its commit owes no search document) whose commit answer is lost leaves its dim-0 search stub deleted until the key is written again.
  • Follow-up, not in this change: an Undo's check of a conflicted peer or a duplicate's original looks the id up within the namespace (get_by_id), as on main; after a namespace is restored into itself under another agent the id is held under two keys.
  • Follow-up, not in this change: the sweep's close of a high row's triples finds them through loom.entity_triple_rows, as on main; a value whose triples are linked only by key (loom.entity_triple_memories, written before that table) keeps them until it is written again.
  • Follow-up, not in this change: the vector tombstones of other writes that make a key high (a memory.set or 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 on main; the sweep's and the publish's are bare.
  • Follow-up, not in this change: a lost answer whose heads cannot be read could be settled by the transaction's status (pg_xact_status) instead of fencing every row.

Tests

  • make format lint typecheck pass; 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).
  • Integration, against a server with LOOM_STORAGE_AUTHORITY=postgres and Postgres 16 and 18 with a synchronous standby (CI job integration-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/health and 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 answering found=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.
  • Measured on one host, fake embedder, 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_CONTENDED against the ClickHouse authority's 13.2 writes/s, the host's limit for both.
  • Race check: six concurrent memory.set of one fact under six keys: ClickHouse authority 6 clear; Postgres authority 1 clear and 5 merge.
  • CI: the unit job's timeout-minutes goes from 45 to 60. Its pytest step takes 37 to 44 minutes on main and 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 typecheck and make test-unit pass; the integration suite passes if server behaviour changed.
  • Generated files are regenerated in this PR, not by hand.
  • A new migration is additive and numbered after the latest on main; no merged migration is edited.
  • Docs under docs/ describe the system as it now is, and this description names any operator steps and wire changes.
  • Repository text has no dates, people, host names, internal namespaces, ticket or decision numbers.
  • Commits are signed off (git commit -s).

🤖 Generated with Claude Code

@zlareb1
zlareb1 force-pushed the feat/pg-live-memory branch 28 times, most recently from 4fa44bc to 4801eb4 Compare November 6, 2026 04:47
…vectors and search

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: zlareb1 <[email protected]>
@zlareb1 zlareb1 mentioned this pull request Nov 12, 2026
3 tasks done
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