Skip to content

Under Postgres, a revision every usable ClickHouse backup holds can lose its payload, past a horizon no shorter than the backup interval plus 60 minutes - #457

Merged
zlareb1 merged 1 commit into
mainfrom
feat/pg-revision-payload-clear
Nov 12, 2026
Merged

zlareb1 merged 1 commit into
mainfrom
feat/pg-revision-payload-clear

Conversation

@zlareb1

@zlareb1 zlareb1 commented Nov 9, 2026 •

Copy link
Copy Markdown
Member

Migration 010_revision_delivered_at.sql builds its index inside the migration's transaction. That is safe only while loom.memory_revisions is small. No released build writes the Postgres journal, and every known deployment runs the ClickHouse authority, so it is small wherever 010 runs. This PR therefore has to ship in the release that first carries the Postgres authority (Postgres migrations 001 onward). If a release carrying them is cut first, the index moves to CREATE INDEX CONCURRENTLY before this PR merges.

Changelog category (leave one):

  • Improvement

Changelog entry (one or two sentences a user of Loom can read without the diff; the release pull request collects these into the release notes):

Under LOOM_STORAGE_AUTHORITY=postgres with LOOM_PG_PAYLOAD_CLEAR_ENABLED, a memory revision keeps only its metadata in Postgres once every usable ClickHouse backup holds it. That happens past a horizon that is never shorter than LOOM_CH_BACKUP_INTERVAL_MINUTES plus 60. Before restoring a ClickHouse backup, turn the switch off; the steps are in backup and recovery.

Why

loom.memory_revisions.row keeps every version's full row, and ClickHouse's memory_versions holds the same. The journal keeps a revision's metadata in typed columns (003_revision_metadata.sql), and every reader tolerates a cleared payload: the readers outside pg_memory (the idempotency replay and erasure's consolidated-row lookup) read coalesce(memory_key, row->>'memory_key'), and the typed memory_key survives a clear. The payload is still needed to write a version back into ClickHouse after a backup restore. So it may go only once every backup a restore may use holds the version.

Design

  • Delivery time. A completion that empties a delivery more than 15 minutes after its revision's commit sets delivered_at on the revision (pg_memory._STAMP_LATE). The stamp is a data-modifying CTE fed from the RETURNING of the existing DELETE and settle UPDATE. A completion sends no more statements than before, and an on-time write never touches the journal. So a revision's delivery time is at most coalesce(delivered_at, committed_at) plus 15 minutes.

  • The pass. It is a worker of its own, pg_payload_clear, off by default (LOOM_PG_PAYLOAD_CLEAR_ENABLED, not LIVE, so a restore of loom.runtime_overrides cannot turn it on). Each batch works in three steps:

    • It reads up to LOOM_PG_DELIVERY_BATCH_ROWS candidates through the new partial index memory_revisions_payload (its predicate is pg_memory.CLEARABLE, word for word). A candidate is past the horizon, owes no delivery, and is not a profile revision.
    • It checks the candidates against loom.memory_versions with sequential consistency: same key and version, same memory_id, same content hash. A redaction keeps the hash.
    • It clears the matches with FOR NO KEY UPDATE SKIP LOCKED, so a row held by a redaction or an erasure is skipped.

    A version ClickHouse lacks is kept and counted (missing_in_clickhouse). A pass works through batches until one comes back short or half its deadline has gone, so clearing keeps up with a write rate above one batch per interval. A ClickHouse read that got no answer (ch_errors.is_connection_failure) or met a state that clears by itself (is_passing_state) is retried within the same budget. Past the budget, the first batch fails the pass. A later batch is noted as the pass's failure and ends it with what it cleared, its cursor before that batch. The pass checks for a stop before each batch's read and again before its clear. The next pass, in any process or colour, resumes from where this one stopped (its cursor in loom.worker_status), and a pass that reaches the end starts over. It clears nothing until the process has adopted the deployment's overrides (settings_overrides.adopted()): before that it would clear under the horizon and backup interval it started with, not an operator's override of them.

  • Horizon. The horizon is LOOM_PG_PAYLOAD_RESTORE_HORIZON_MINUTES (LIVE; 0, the default, means twice the backup interval plus 60). It is never under LOOM_CH_BACKUP_INTERVAL_MINUTES (LIVE, default 1440) plus 60, nor under the insert bound plus 60. The 60 minutes cover replica lag and clock skew, which a backup's start time does not show; a late backup shows in its start time, which the runbook's backup choice checks. The arithmetic and the restore runbook are in docs/operations/backup-and-recovery.md.

  • Nothing records what was cleared. The only new state is delivered_at and the pass's resume cursor in loom.worker_status; there is no new table: row IS NULL already means cleared by this pass, because a redaction scrubs the payload rather than nulling it.

Scope and risk

  • Postgres authority only, and only with the switch on. A profile revision keeps its payload. Knowledge documents are not covered: their old versions already live only in ClickHouse.
  • If a ClickHouse restore skips the runbook, the content of superseded versions committed between the backup and the restore can be lost; their metadata stays. A cleared revision that is still its key's head is sent again from its memory_current row (the same version), so loom reconcile restores every live head ClickHouse lacks. A superseded cleared revision is left out of the holds (counting only what was held), and a delivery that reaches one anyway (held as a pass cleared it) parks at its claim with last_error "payload cleared, nothing to send", so the delivery pipeline keeps running.
  • A restore must use a backup that started less than the horizon minus 60 minutes before the clearing stopped (runbook step 4), the 60 minutes being the backup replica's lag and clock skew. That backup holds every cleared version, so the versions a restore lacks all keep their payloads, which is what a republish of the journal after a restore reads.
  • Erasure: unchanged. The saga deletes revisions by scope, and delivered_at holds no content.

Compatibility, rollout and rollback

  • Migration 010 adds a nullable column and a partial index. A build without 010 ignores both. While such a build still serves, it completes late deliveries without stamping them, and those stay unstamped, so the switch goes on no sooner than one clearing horizon after the new build serves alone (rolling-upgrade rule 43).
  • Write cost: every non-profile commit adds one entry to memory_revisions_payload, a fifth index on loom.memory_revisions beside four (its key is a timestamp and the primary key's three columns). A late stamp or a clear changes an indexed column, so neither is a HOT update; the stamp never updates an on-time commit; only a clear does, once. With the switch off the index holds every non-profile revision and never shrinks; with it on, a cleared revision leaves it. What the entry costs a commit is not measured here: that takes a load run, which this PR does not include.
  • New settings: LOOM_PG_PAYLOAD_CLEAR_ENABLED, LOOM_PG_PAYLOAD_CLEAR_INTERVAL_SECONDS, LOOM_CH_BACKUP_INTERVAL_MINUTES and LOOM_PG_PAYLOAD_RESTORE_HORIZON_MINUTES. Wire: none. Operator steps: none until the switch is turned on.
  • Rollback: the previous build's reads (history, gap reads, idempotency, erasure) tolerate a cleared payload; its delivery and loom reconcile do not. A cleared payload stays cleared. The previous build completes late deliveries unstamped, so turn the switch off before rolling back, and on again no sooner than one horizon after the new build serves alone again (rolling-upgrade rule 43). The previous build's delivery cannot send a cleared revision, so once a clearing pass has run, loom reconcile runs only with a build that carries 010 and the deployment starts on that build after it (with Helm, the release's image is set to it for the reconcile Job and the restart), a rollback waits until the new build owes no claimable delivery for a cleared revision (a query in upgrades.md returns 0), and while the previous build serves a retry of parked deliveries leaves the cleared revisions out (postgres.md gives the clause; rule 43).
  • docs/operations/backup-and-recovery.md's "Restoring one store" steps open with this PR's clearing stop and backup choice.
  • docs/operations/upgrades.md names the switch's wait in the upgrade procedure (step 8) and in the rollback.

Tests

  • tests/unit/test_pg_payload_clear.py:

    • the index predicate equals CLEARABLE;
    • the stored cursor reads back what a pass left, and starts over at the end, with none, or with one it cannot read; one too long to store (a long non-ASCII namespace) keeps only its delivery time;
    • the horizon is clamped to the backup interval and the insert bound, each plus 60;
    • no clearing before the overrides are adopted, and adopting them opens that gate;
    • only revisions ClickHouse holds are cleared;
    • a pass works through full batches until a short one, and the next starts over; one ending on a full batch reads one more and is not idle; one that finds nothing is idle; one out of time stops after its batch and the next resumes past it;
    • a later batch ClickHouse cannot read within the budget ends the pass with what it cleared and notes the failure, and a first batch fails the pass;
    • an unreachable ClickHouse (BackendUnavailableError) and a busy pool (OverloadedError) are retried within the pass; a read past its deadline (BackendTimeoutError) and a refusal are not;
    • a stopped pass clears nothing;
    • a version matches only with its id and hash;
    • a batch too large for one parameter field is checked a slice at a time;
    • the operator DELETE in postgres.md names the last_error text the code writes;
    • the worker row is switched by pg_payload_clear_enabled and paced by pg_payload_clear_interval_seconds.
  • tests/unit/test_restore_reconcile.py: test_heads_that_hold_leaves_out_are_not_counted_and_are_warned_of: pg_memory.hold returns how many it held, and hold_heads_behind counts only those and warns of the heads it could not hold.

  • test_pg_authority.py (integration):

    • test_a_revision_delivered_late_is_stamped_and_one_delivered_at_once_is_not: a delivery taken over from a writer that stopped an hour ago is stamped through the settle arm, replacing an older stamp (the arm a redelivery after a restore takes); on-time ones are not.
    • test_a_writer_finishing_its_own_delivery_late_stamps_it: the same through the DELETE arm, also replacing an older stamp.
    • test_the_clearing_read_walks_its_index_in_order: with sequential scans, bitmap scans and sorts priced out, clearable_revisions' plan is an index scan of memory_revisions_payload with no Sort node.
    • test_a_cleared_head_is_sent_from_its_head_row_and_a_cleared_older_version_parks: hold holds a cleared head and leaves out a cleared superseded version; the head's claim carries its memory_current row, field for field and at its version, and a delivery owed for the superseded one parks at its claim with its reason; the head's claim then publishes into a ClickHouse whose loom.memory lacks the key, settles, and the head reads back at its version.
    • test_an_unstamped_revision_waits_out_the_late_delivery_allowance: an unstamped revision whose commit is the horizon plus 5 minutes old is not offered; at the horizon plus 20 minutes it is.
    • test_a_revision_past_the_horizon_that_clickhouse_holds_loses_its_payload:
      • past the horizon, every version of a key is cleared, a redacted one included; each keeps its typed metadata field for field (the redaction's time and reason, delivered_at, request_id and the audit row among them), and memory.history answers as before;
      • a resumed read starts past its cursor;
      • a later redaction of a cleared version marks its columns, and memory.history serves that version scrubbed (value, reason, time and hash) with every other field and version as before;
      • a revision ClickHouse lacks, a profile revision and one owing a parked delivery all keep their payloads;
      • a revision committed long ago but stamped as delivered just now is not offered until its stamp is past the horizon too.
  • The candidate read uses the index. EXPLAIN (ANALYZE, BUFFERS) of clearable_revisions' statement, on a local journal with 100,000 synthetic revisions past the horizon (one org, 50 namespaces; deleted after), shows an ordered Index Scan using memory_revisions_payload, its Index Cond holding the horizon cut and the cursor's row comparison, and a Nested Loop Anti Join on memory_deliveries_pkey. A batch of 500 took 0.8 ms and 1,180 shared buffers, so a batch's cost does not grow with the backlog. The rows and the read, with the default horizon (2,940 minutes) and an empty cursor:

    INSERT INTO loom.memory_revisions (org, namespace, seq, user_id, memory_id, version, content_sha256,
        actor, source_class, committed_at, row, audit)
    SELECT 'it-explain-100k', 'ns' || (g % 50), g, '-', gen_random_uuid(), g, repeat('a', 64), 't',
        'asserted', now() - interval '30 days' + (g || ' seconds')::interval,
        jsonb_build_object('agent', 'a', 'session_id', '-', 'memory_key', 'k' || g,
                           'memory_type', 'semantic', 'value', 'v' || g), '{}'::jsonb
    FROM generate_series(1, 100000) g;
    ANALYZE loom.memory_revisions;
    -- clearable_revisions' statement, $1 = 176400 (the horizon in seconds), the cursor at
    -- ('0001-01-01 00:00:00+00', '', '', -1) as it binds an empty one, LIMIT 500, under
    -- EXPLAIN (ANALYZE, BUFFERS)
  • Local:

    • All runs on Postgres 16 with a synchronous standby, every Postgres migration applied in order through this PR's, against a server on the named head: on main cbfa649 with this PR's file as 008 up to 47eae4a, then squashed and rebased onto main fa12d75 (which took 008 for 008_cells.sql) with the file renumbered 009, from baa5825 on main 32bd5f7, at c550f34 squashed onto main 28de00a (which took 009 for 009_cell_probe.sql) with the file renumbered 010, and from aa80427 on main c19346c. test_deeply_nested_hidden_html_parses_in_bounded_time fails on this host on main too, in code this PR does not touch; it is the one failure in every full unit run below.
    • 385b907: full unit suite 33,504 passed; the three integration files (test_pg_authority.py, test_pg_durable_publish.py, test_pg_pipeline_metrics.py) 150 passed.
    • 59b718c: full unit suite 33,503 passed (one statement-count unit test removed); the three integration files 151 passed.
    • d6ac11c: test_pg_authority.py 142 passed.
    • c27dc52: full unit suite 33,506 passed; the three integration files 151 passed.
    • 44cebbb: the three integration files 151 passed; test_readiness.py, test_pg_payload_clear.py, test_pg_durable_reads.py, test_doc_links.py and test_public_copy.py 299 passed.
    • f2ccbd7: removes the unit test that read clearable_revisions' source text and adds test_the_clearing_read_walks_its_index_in_order in its place; both changed integration tests passed.
    • 2b2ce81 (a test and a doc paragraph after f2ccbd7): the cleared-head integration test passed, publishing into a ClickHouse with the head deleted and reading it back.
    • 47eae4a (a cursor too long to store keeps only its delivery time): test_pg_payload_clear.py 24 passed.
    • af2e7ab (47eae4a squashed and rebased onto fa12d75, migration renumbered 009, a sentence in storage-layout.md): on a fresh Postgres and ClickHouse, the three integration files 152 passed; the settings, worker, census, ratchet, snapshot, inventory, storage layout, cell, doc, copy, test_pg_* and clearing and reconcile unit files 1,772 passed.
    • 3186847, 99630bc and 6819d6f (doc text, one code comment and one setting comment with its generated reference, schema and example): test_doc_links.py, test_public_copy.py, test_storage_layout_rows.py, test_pg_payload_clear.py and the test_settings* files passed. The full unit suite at af2e7ab ran under host memory pressure: 33,776 passed and 32 failed, almost all clickhouse-local MEMORY_LIMIT_EXCEEDED. Run again alone, the six files with failures (test_aliases_verified_email_sql.py, test_delete_version_sql.py, test_profile_redaction.py, test_projection_repair_cursor.py, test_sdk_set_coalescer.py, test_signup_name_in_use.py) 263 passed; the remaining one is the host's test_deeply_nested_hidden_html_parses_in_bounded_time.
    • baa5825 (6819d6f rebased onto main 32bd5f7, which added A first cell in recording records a new org only while the directory answers that it is attaching #519 and The router answers a placed org's lookup from its cache while the directory is down #520; this PR's own diff is unchanged, and the settings generators report current): the three integration files 152 passed; the settings, worker, census, ratchet, snapshot, inventory, storage layout, cell, router, readiness, errors, doc, copy, test_pg_* and clearing and reconcile unit files 1,975 passed.
    • 2e97bf3 (two tests): test_pg_payload_clear.py 25 passed, and test_a_revision_past_the_horizon_that_clickhouse_holds_loses_its_payload passed against a server on that head.
    • e16ee8b (a test, and the end-of-index cursor read explicitly): test_pg_payload_clear.py 25 passed, and test_an_unstamped_revision_waits_out_the_late_delivery_allowance passed against a server on that head.
    • 0cdae2c (a re-wrapped migration comment and docs line): test_pg_payload_clear.py and test_doc_links.py 241 passed.
    • 7783788 (the parked-deliveries definition in postgres.md and parked_count): test_doc_links.py and test_public_copy.py 221 passed, and make format lint passed.
    • 449bb29 (two docstrings): make format lint passed; the full unit suite 33,844 passed and the host's one known failure (test_deeply_nested_hidden_html_parses_in_bounded_time). The commits after it change docs, one docstring, one log message and two unit test files.
    • 9874aa0 (the parked-deliveries definition and the parked_count docstring): make format lint typecheck passed, and the prose check on postgres.md is clean.
    • 3e57a51 (one postgres.md paragraph): test_doc_links.py and test_public_copy.py 221 passed, and the prose check is clean.
    • 017650a (rule 43 and the rollback steps): test_doc_links.py, test_public_copy.py and test_agent_instructions.py 425 passed, the prose check is clean, and the rollback query runs on Postgres 16.
    • 6feeac7 (the rollback query counts every unsettled delivery of a cleared revision but a nothing-to-send park): test_doc_links.py and test_public_copy.py 221 passed, the prose check is clean, and the query runs on Postgres 16.
    • 35253ed (the rollback query skips only a parked nothing-to-send delivery, the operator DELETE only a parked one, and reconcile holds are released by finishing loom reconcile): test_doc_links.py and test_public_copy.py 221 passed, the prose check is clean, and the query and the DELETE (rolled back) run on Postgres 16.
    • e997eeb (the rollback steps send a leftover reconcile hold to the restore runbook, and a unit test ties PAYLOAD_CLEARED to the rollback check and the operator DELETE): test_pg_payload_clear.py, test_doc_links.py and test_public_copy.py 247 passed; make format lint and the prose check pass.
    • 5210d08 (the rollback check counts claimable deliveries of cleared revisions, and parked ones stay untouched while the previous build serves): test_pg_payload_clear.py, test_doc_links.py and test_public_copy.py 247 passed; make format lint and the prose check pass; the query runs on Postgres 16.
    • ccbbffe (one rule for builds without 009 in rule 43, the rollback steps and the restore runbook; the retry clause and the reordered park paragraph in postgres.md): test_pg_payload_clear.py, test_doc_links.py and test_public_copy.py 247 passed; make format lint and the prose check pass; the retry with its clause runs on Postgres 16 (rolled back).
    • 90439ac (the retry clause as a NOT EXISTS anti-join, and the rollback and restore steps name which build runs reconcile and starts after it): test_pg_payload_clear.py, test_doc_links.py and test_public_copy.py 247 passed; the prose check passes; the retry with the clause runs on Postgres 16 (rolled back) and plans as a nested-loop anti join.
    • 8b73909 and c299a8e (reconcile runs with a 009 build rather than while one serves, and the Helm restore sets that image, by tag or digest, for the Job and the restart): test_doc_links.py and test_public_copy.py 221 passed, and the prose check passes.
    • db7842f (the Helm image change opens restore step 3, step 5 waits a horizon after a roll forward, upgrade step 8's list): test_doc_links.py and test_public_copy.py 221 passed, and the prose check passes.
    • 841ee1b (the Helm image change carries step 2's new host, and step 5 names the restore runbook's step 4): test_doc_links.py and test_public_copy.py 221 passed, and the prose check passes.
    • 0ad348c (Helm restore step 4 keeps step 3's image, and the reconcile warning puts its count last): test_restore_reconcile.py, test_doc_links.py and test_public_copy.py 263 passed; make format lint and the prose check pass.
    • c550f34 ( 0ad348c squashed and rebased onto main 28de00a, migration renumbered 010; the settings generators report current): make format lint typecheck passed, and the settings, worker, census, ratchet, snapshot, inventory, storage layout, cell, router, readiness, doc, copy, test_pg_* and clearing and reconcile unit files 1,853 passed. On a fresh Postgres and ClickHouse, the three integration files 153 passed, and the full unit suite 34,065 passed with the host's one known failure (test_deeply_nested_hidden_html_parses_in_bounded_time).
    • aa80427 (this head: c550f34 rebased onto main c19346c, which added The router registers a cell once its probe listener answers the cell's deployment id and prepare's nonces #535 and loom install gives Cursor the coding toolset, as the dashboard does #548; this PR's own diff is unchanged, and the settings generators report current): make format lint typecheck passed, and the settings, worker, census, ratchet, snapshot, inventory, storage layout, cell, router, readiness, doc, copy, test_pg_* and clearing and reconcile unit files 2,213 passed.
    • The integration tests call the store functions; the pass's batch loop (run_pass) is covered by the unit tests.

AI assistance in the code (leave one; writing this description with AI is fine):

  • AI-generated (an agent wrote most of the diff): Claude Code. Checked: the delivery-time bound on every completion path, the lock order against redaction and erasure, and the restore runbook against the compose deployment.

  • 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.
  • A behaviour change to any file a plugin ships bumps both plugin manifests' version.
  • The frontend builds and its tests pass, if frontend/ changed.
  • Docs under docs/ describe the system as it now is, and this description names any operator steps and wire changes.
  • Repository text has no dates, people, host names, internal namespaces, ticket or decision numbers.
  • Commits are signed off (git commit -s), as CONTRIBUTING.md asks.

🤖 Generated with Claude Code

@zlareb1
zlareb1 force-pushed the feat/pg-revision-payload-clear branch 14 times, most recently from 0ad348c to c550f34 Compare November 12, 2026 03:33
…ose its payload, past a horizon no shorter than the backup interval plus 60 minutes

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: zlareb1 <[email protected]>
@zlareb1
zlareb1 force-pushed the feat/pg-revision-payload-clear branch from c550f34 to aa80427 Compare November 12, 2026 04:15
@zlareb1
zlareb1 marked this pull request as ready for review November 12, 2026 04:17
@zlareb1
zlareb1 merged commit 0350223 into main Nov 12, 2026
36 of 37 checks passed
@zlareb1
zlareb1 deleted the feat/pg-revision-payload-clear branch November 12, 2026 04:18
@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