Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
LPH (h3): page purge deletes unreferenced texts holding the page's claims, both forms
garrytan6a3584f954b2
diff --git a/docs/architecture/key-files/memory-purge.md b/docs/architecture/key-files/memory-purge.mdindex b554ee78a2..2d630fbecd 100644--- a/docs/architecture/key-files/memory-purge.md+++ b/docs/architecture/key-files/memory-purge.md@@ -15,7 +15,7 @@ User-facing contract: [expire versus purge](../../guides/memory-boundaries.md#pu- `src/core/deletion-inventory.ts` — the deletion-target registry: every table with a text, JSON, bytes, array, lexeme or vector column, classed `swept`, `retained_inactive` or `out_of_scope` (`probed_reported` with probe columns, `text_free_ledger`, `secret_material`, `no_memory_text`), plus on-disk stores and out-of-reach residuals. `test/deletion-inventory.test.ts` fails on any unlisted text-bearing column of a fresh schema and pins the AGENTS.md "never promise physical erasure" line.- `src/core/persistence/intent-redaction.ts` — accounting-aware intent redaction: `findRequestsCarrying` (intent, outcome, error detail or message, compacted rows included; the fact purge's planning read) / `findRequestsForSlugs` (index-served by `persistence_requests_slug_intent`), the page purge's preparation-time journal census `sweepRequestsCarrying` (#6511: a keyset walk of the source's journal in `JOURNAL_SWEEP_CHUNK_ROWS` chunks, every needle in raw and JSON-escaped form against intent, outcome, error detail and message, compacted rows included, the purge's own row excluded, stopped by the claim clock between chunks and at `JOURNAL_SWEEP_MATCH_CAP`; returns the carrying ids, the ids pending at the scan, the `sequence` ceiling as text and `complete`; #6884: `sweepRequestsForGroups` runs it once for several needle groups, each row read and lowered once and every hit attributed to the groups carrying that needle, the match cap per group, and `after` starts past an earlier ceiling) with `recheckRequestsCarrying` for the publication's bounded re-check of the tail past the ceiling and of the rows that were pending, `redactRequestIntents` locks counters then request rows, refuses on a non-terminal or recovering request (unless `skipPending`), nulls `intent`/`error_message` and replaces every outcome or error-detail string carrying a needle with `"[purged]"` (`redactJson`), with compaction's terminal-byte accounting, so replay keeps returning the (redacted) stored outcome. `findRequestsHoldingStagings` / `cancelRequestsHoldingStagings`: the queued requests whose `intent.body_ref.staging_id` names a staging a fact purge aborts are completed `cancelled` with `purged_content`.- `src/core/persistence/purged-intent.ts` — `intentCarriesPurgedContent`: `completeWrite` (journal.ts) nulls the intent of any terminal request whose content (`fact`, `claim`, page fence rows, or the page's content hash) matches a subject-scoped purge tombstone, and of any refusal coded `purged_content`; a write refused for another reason, or committed as a no-op after the overlay dropped purged rows, keeps no copy. Only content-bearing intents are checked, and whether the source holds any tombstone is selected by completeWrite's terminal statement itself (`PURGE_PRESENCE_COLUMNS`), so the hook adds no statement to a write on a source without tombstones (#6007 budget). `purged_content` is a write error code, so receipts and the frozen verb path (wire `invalid_params`, canonical `purged_content`) keep it typed.-- `src/core/persistence/page-purge.ts` — #6884: `preparePagePurge` takes its census from `sweepForPurge`: a purge an earlier batch sweep covered for all of its current claims scans only the tail past that sweep's ceiling (`journal_sweep.watermark`); otherwise it sweeps once for its own claims and those of the next queued purges of the source (up to `PURGE_SWEEP_BATCH_MEMBERS`, `PURGE_SWEEP_BATCH_NEEDLES` claim forms) and caches each member's result in process memory (never in the journal; `journal_sweep.batch` counts the purges one sweep covered). Rows a member's cached census saw as pending, the leader's own row included, are re-tested at publication. Tests: `test/page-purge-batch-sweep-6884.test.ts`. `purgePageInTransaction`, called by the `delete_page purge:true` apply in `page-prepare.ts`: records in `page_purges` the content hash of the page and of every retained version (up to 1000), each as imported and as purge-overlaid, so an older version is refused too; drops the decide rows, trust proposals, gate holds (by slug) and gate receipts naming the page or its rows and clears legacy `query_cache`; tombstones and deletes facts filed on the page, tombstones its takes, deletes take proposals, open loops, core notices and `files` rows, the page's `page_aliases` and the `slug_aliases` redirects whose `canonical_slug` is the page (#6619; a redirect from this slug to another page stays; counted in `removed` and checked by slug in the receipt), redacts finished intents for the slug and the carrying ids the preparation sweep found plus the publication's tail and pending re-check (#6511: `preparePagePurge` runs `readPurgeClaims` and `sweepRequestsCarrying` under the preparation budget at steps `purge_claims` / `purge_journal_sweep`, so the O(journal) substring scan is a charged `preparation_deadline` release and `preparation_stalled` at the attempt limit, never a transaction timeout; the lookups that stay inside the transaction go through `lookup`, which maps a 57014 to the terminal, non-retryable `purge_lookup_timeout` naming `gbrain repair request-indexes` only when `persistence_requests_slug_intent` is missing or INVALID; the receipt's `journal_sweep` reports `ceiling`, `scanned`, `tail`, `pending_rechecked` and `complete`), then deletes the page (FK cascades). `PURGE_RESIDUALS` names what stays out of reach. `finishPagePurge` deletes stored blobs after commit, lists any left by storage path, and attaches `receipt`, the store-by-store receipt from `verifyPagePurge` (same shape as the fact receipt: residuals first, every swept inventory store, other pages' prose naming a purged claim as `source_prose`); the page's claims used as needles live only in process memory, and a same-id replay returns the result built when the purge ran. `residuals` stays the prose string. `readPagePurgeTombstones` feeds `screenImportContent({ purgedPages })` from managed sync's freeze-time screen (`sync-screen.ts`, one read per run) and publication (`sync-prepare.ts`), which hold a matching file as `purged_content`; direct imports and `put_page` hit the pages guard instead; `listPagePurges` / `unpurgePage` (also clears the fact and take tombstones of the same request) back the owner-only ops. Pinned by `test/page-purge.test.ts` and `test/page-purge-journal-timeout-6511.test.ts` (both engines; seams `purge:*` in `fault-points.ts`). #6368: a purge of a tombstone whose file matches `sync.exclude` (discovery's globs via `syncExcludePatterns` in `sync-discovery.ts`, matched relative to the source root) owns no file: `prepareFileTarget`'s `excludeTombstone` option returns no target, the purge is database-only and the receipt says `write_through.skipped: 'sync_excluded'`; the file is neither compared nor removed (an unchanged excluded file used to be deleted, an edited one refused forever). The apply re-reads the exclusion inside the publication transaction and refuses `source_changed` if it was removed meanwhile. Live-page purges and soft deletes are unchanged. A segmented page or version is never loaded whole: its stored `content_hash` and the purge-overlaid hash streamed by `rewrittenContentHash` are tombstoned; its stagings (by slug or page id) and the segment texts its manifests referenced or its stagings recorded in `page_body_staging_texts` (LPH (h), N14-5: a text an earlier write's sweep dropped from the manifest stays unreferenced for the GC grace window, and only the page's staging still names it) that no manifest row references are deleted in the purge transaction with the page (`deletePageWithSegments`, shared with the restore-time page-scope replay; `removed.page_body_manifest` / `page_body_stagings` / `page_segment_texts`), except a text another page's live staging recorded in `page_body_staging_texts` (an unpublished create or replace still needs it; `stagingNeedsTextSql`, also applied by the 72-hour hard delete and the receipt's text probe).+- `src/core/persistence/page-purge.ts` — #6884: `preparePagePurge` takes its census from `sweepForPurge`: a purge an earlier batch sweep covered for all of its current claims scans only the tail past that sweep's ceiling (`journal_sweep.watermark`); otherwise it sweeps once for its own claims and those of the next queued purges of the source (up to `PURGE_SWEEP_BATCH_MEMBERS`, `PURGE_SWEEP_BATCH_NEEDLES` claim forms) and caches each member's result in process memory (never in the journal; `journal_sweep.batch` counts the purges one sweep covered). Rows a member's cached census saw as pending, the leader's own row included, are re-tested at publication. Tests: `test/page-purge-batch-sweep-6884.test.ts`. `purgePageInTransaction`, called by the `delete_page purge:true` apply in `page-prepare.ts`: records in `page_purges` the content hash of the page and of every retained version (up to 1000), each as imported and as purge-overlaid, so an older version is refused too; drops the decide rows, trust proposals, gate holds (by slug) and gate receipts naming the page or its rows and clears legacy `query_cache`; tombstones and deletes facts filed on the page, tombstones its takes, deletes take proposals, open loops, core notices and `files` rows, the page's `page_aliases` and the `slug_aliases` redirects whose `canonical_slug` is the page (#6619; a redirect from this slug to another page stays; counted in `removed` and checked by slug in the receipt), redacts finished intents for the slug and the carrying ids the preparation sweep found plus the publication's tail and pending re-check (#6511: `preparePagePurge` runs `readPurgeClaims` and `sweepRequestsCarrying` under the preparation budget at steps `purge_claims` / `purge_journal_sweep`, so the O(journal) substring scan is a charged `preparation_deadline` release and `preparation_stalled` at the attempt limit, never a transaction timeout; the lookups that stay inside the transaction go through `lookup`, which maps a 57014 to the terminal, non-retryable `purge_lookup_timeout` naming `gbrain repair request-indexes` only when `persistence_requests_slug_intent` is missing or INVALID; the receipt's `journal_sweep` reports `ceiling`, `scanned`, `tail`, `pending_rechecked` and `complete`), then deletes the page (FK cascades). `PURGE_RESIDUALS` names what stays out of reach. `finishPagePurge` deletes stored blobs after commit, lists any left by storage path, and attaches `receipt`, the store-by-store receipt from `verifyPagePurge` (same shape as the fact receipt: residuals first, every swept inventory store, other pages' prose naming a purged claim as `source_prose`); the page's claims used as needles live only in process memory, and a same-id replay returns the result built when the purge ran. `residuals` stays the prose string. `readPagePurgeTombstones` feeds `screenImportContent({ purgedPages })` from managed sync's freeze-time screen (`sync-screen.ts`, one read per run) and publication (`sync-prepare.ts`), which hold a matching file as `purged_content`; direct imports and `put_page` hit the pages guard instead; `listPagePurges` / `unpurgePage` (also clears the fact and take tombstones of the same request) back the owner-only ops. Pinned by `test/page-purge.test.ts` and `test/page-purge-journal-timeout-6511.test.ts` (both engines; seams `purge:*` in `fault-points.ts`). #6368: a purge of a tombstone whose file matches `sync.exclude` (discovery's globs via `syncExcludePatterns` in `sync-discovery.ts`, matched relative to the source root) owns no file: `prepareFileTarget`'s `excludeTombstone` option returns no target, the purge is database-only and the receipt says `write_through.skipped: 'sync_excluded'`; the file is neither compared nor removed (an unchanged excluded file used to be deleted, an edited one refused forever). The apply re-reads the exclusion inside the publication transaction and refuses `source_changed` if it was removed meanwhile. Live-page purges and soft deletes are unchanged. A segmented page or version is never loaded whole: its stored `content_hash` and the purge-overlaid hash streamed by `rewrittenContentHash` are tombstoned; its stagings (by slug or page id) and the segment texts its manifests referenced or its stagings recorded in `page_body_staging_texts` (LPH (h), N14-5: a text an earlier write's sweep dropped from the manifest stays unreferenced for the GC grace window, and only the page's staging still names it) that no manifest row references, plus the source's unreferenced texts holding one of the page's claims (facts, withdrawn ones included, and takes; plain or as a fence cell stores it, `claimTextForms` in fence-shared.ts: a text another page's write reused outlives this page's 24-hour staging record), are deleted in the purge transaction with the page (`deletePageWithSegments`, shared with the restore-time page-scope replay; `removed.page_body_manifest` / `page_body_stagings` / `page_segment_texts`), except a text another page's live staging recorded in `page_body_staging_texts` (an unpublished create or replace still needs it; `stagingNeedsTextSql`, also applied by the 72-hour hard delete and the receipt's text probe).- `src/core/ops/purge.ts` — `purge_fact`, `list_page_purges`, `unpurge_page`: admin scope, `cliOnly` (every MCP route gets `trusted_local_only`). The resident owner runs them only for its verified local CLI registration (`LOCAL_CLI_OWNER_OPERATIONS` in `persistence/ipc.ts`, checked in `persistence/provider.ts`).- `src/commands/forget-purge.ts` + `src/commands/pages-purges.ts` — the CLI fronts. `runForgetPurge` always runs the dry run, then a typed token on a terminal or `--yes` plus `--request-id` without one; `--match` lists ids, `--status` polls completion; `PURGE_FAMILY_HELP` is the purge-family table shown by `gbrain forget --help`. `gbrain pages purges list` and `gbrain pages unpurge <slug>` run the page-tombstone ops as the trusted CLI.diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 13ee3a728c..aa58797e83 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -907,7 +907,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;{ since: 'TBD', text: 'A publication or withdrawal-mirror recovery record of a version this gbrain does not know (one a newer gbrain wrote) is now refused with `recovery_version_unsupported` before anything reads it: the record, its staged files and the canonical file are left exactly as they are, the effect keeps retrying instead of parking, and `gbrain sources writer status` and a stalled sync name it as a blocker whose fix is `gbrain upgrade` on the owner host. Before, recovery could read a newer record as an older one: a withdrawal-mirror recovery published the bytes the record embedded, removed its staging file and cleared the record, and a request recovery tried to rewrite the record\'s staging (the database refused it with an untyped `unsupported_mutation_protocol`). v0.60.290.0 and older still read a version 2 withdrawal-mirror record as version 1 and fail every attempt with an untyped `effect_unavailable` while the record holds every write and effect on the worktree; they never delete the record or its staging file, and an upgraded owner finishes it.' },{ since: 'TBD', text: 'While a gbrain older than the segmented writer floor (v0.60.290.0 included) that doctor `segmented_storage` still warns about wrote to the brain in the last 7 days (another host, an older `serve` or worker still running on this host, or an older write this build has not matched; doctor names the host), a withdrawal (`forget`, `forget_fact`, `purge_fact`) on a page stored in segments still commits, but its withdrawal mirror no longer writes a version 2 recovery record, which that older gbrain cannot read and would wedge the worktree on. The mirror refuses `segmented_mirror_writer_gate` (its fix names the hosts to upgrade), retries, and parks after five attempts like any failed mirror, so writes on the worktree are not held; the page\'s canonical file keeps the withdrawn row and the withdrawal\'s Git effect waits meanwhile. Once the older writer is upgraded and out of the 7-day window, the parked mirror runs again by itself (checked at most once a minute), rewrites the file and the Git effect commits it. `gbrain sources writer retry-effects` retries it at any time. A hold left only by this host\'s own writes from before it upgraded, which the upgraded gbrain has since superseded with the same kind of write (doctor reports it as information), still keeps new pages inline but does not hold the mirror: an upgraded single-host brain mirrors withdrawals at once.' },{ since: 'TBD', text: 'A withdrawal (`forget`, `forget_fact`, `purge_fact`) of a claim in a facts fence that crosses a forced segment cut, when that one fence holds more than 16,384 rows (or more than 8 MiB of rows to check), is still refused `withdrawal_capacity` (the bound is unchanged), but the refusal now says why: it carries reason `split_fence_rows`, names the page, the fence\'s row count and the limit, and its fix asks you to split that fence into fences of at most 16,384 rows and write the page again. It used to say discovery "could not prove a bounded complete target set" and told you not to split the source.' },- { since: 'TBD', text: '`delete_page purge: true` (`gbrain delete --purge`) of a page stored in segments now also deletes, in the purge, the segment texts the page stopped referencing within the last hour, which used to stay in `page_segment_texts` until the hourly segment sweep removed them. A withdrawal (`forget`, `forget_fact`) followed by another write to the page (a delete and `restore_page` included) left the text that held the withdrawn row, with the page text around it, in that state, and the purge reported success. `removed.page_segment_texts` in the purge receipt counts these texts too. A text that an unpublished write of another page staged is still kept, as before for the texts the page referenced.' },+ { since: 'TBD', text: '`delete_page purge: true` (`gbrain delete --purge`) of a page stored in segments now also deletes, in the purge, the segment texts the page stopped referencing within the last hour, which used to stay in `page_segment_texts` until the hourly segment sweep removed them. A withdrawal (`forget`, `forget_fact`) followed by another write to the page (a delete and `restore_page` included) left the text that held the withdrawn row, with the page text around it, in that state, and the purge reported success. The purge also deletes every unreferenced segment text of the source that holds one of the page\'s claims (its facts, withdrawn ones included, and its takes), plain or as a facts-fence cell stores it, which covers a text another page\'s write reused after the page\'s own write record of it expired. `removed.page_segment_texts` in the purge receipt counts these texts too, and the receipt\'s `page_segment_texts` store checks for them. A text that an unpublished write of another page staged is still kept, as before for the texts the page referenced.' },{ since: 'TBD', text: '`purge_fact` (`gbrain forget <id> --purge`) of a claim containing `|` now also deletes the unreferenced segment texts that hold the claim as its facts-fence cell stores it (`|` escaped as `\\|`, a line break as `<br>`), in the purge. It matched only the claim\'s exact bytes, so after a withdrawal and another write to a page stored in segments (a delete and `restore_page` included) the text holding the old fence row stayed until the hourly segment sweep, and the receipt\'s `page_segment_texts` store did not report it. The receipt now probes both forms.' },{ since: 'TBD', text: 'A managed write the database interrupts under load is now retried with backoff instead of failing at the second interruption. A statement the database ends with a statement timeout or cancel (SQLSTATE 57014) and, new, a publication the owner cancels past `persistence.publication_ceiling_ms` (until now released and published again without limit, or on Postgres sometimes failed `storage_error` at once) count against their own budget, `persistence.max_transient_retries` (default 5, 0 to 20), instead of `persistence.max_preparation_attempts`: each one schedules the request\'s next claim after 1 s, 2 s, 4 s, 8 s, then 15 s (stored on the request, so nothing is held while it waits; `gbrain sources writer status` names the waiting head `transient_backoff`), and the interruption after the last retry ends it `failed` with `write_interrupted` as before. Its receipt names the interruptions (`attempts`), the retry limit (`limit`, `limit_key`), the cause (`statement_cancel` or `publication_ceiling`) and the SQLSTATE. Preparations cut off at their deadline still count against `persistence.max_preparation_attempts` alone, and lock timeouts, serialization failures, deadlocks and lost connections are still never counted. `persistence.preparation_deadlines false` turns this counting and the backoff off with the deadlines. Upgrading adds two columns to `persistence_requests` (migration v261, no rewrite of existing rows).' },];diff --git a/src/core/facts/purge-verify.ts b/src/core/facts/purge-verify.tsindex 2b8b217968..9514fb79f1 100644--- a/src/core/facts/purge-verify.ts+++ b/src/core/facts/purge-verify.ts@@ -20,7 +20,7 @@ import { existsSync, readFileSync, unlinkSync } from 'node:fs';import { join } from 'node:path';import type { BrainEngine } from '../engine.ts';import { getCode } from '../retry-matcher.ts';-import { escapeFenceCell } from '../fence-shared.ts';+import { claimTextForms, escapeFenceCell } from '../fence-shared.ts';import { gbrainPath } from '../config.ts';import type { WriteRequest } from '../persistence/model.ts';import { DELETION_INVENTORY, OUT_OF_REACH_RESIDUALS, type InventoryEntry } from '../deletion-inventory.ts';@@ -521,12 +521,14 @@ export async function verifyPagePurge(engine: BrainEngine, input: { sourceId: stawait keyed('write_gate_holds', 'SELECT 1 FROM write_gate_holds WHERE source_id=$1 AND slug=$2', [src, slug]);if (!await relationExists(engine, 'query_cache')) stores.push(missingCache('query_cache'));else await keyed('query_cache', 'SELECT 1 FROM query_cache WHERE $1::text IS NOT NULL', [src]);- // The page's own segment texts only: a text of another page holding the same words is that page's body, never a- // residue of this purge (an inline page referenced none, so the inventory sweep below must not probe the table).- if (context && !context.segmentShas.length) stores.push({ store: 'page_segment_texts', status: 'not_present', removed: removed.page_segment_texts ?? 0 });- if (context?.segmentShas.length) await keyed('page_segment_texts', `SELECT 1 FROM page_segment_texts t WHERE t.source_id=$1- AND t.sha256=ANY(SELECT decode(h,'hex') FROM unnest($2::text[]) AS h)- AND NOT EXISTS (SELECT 1 FROM page_body_manifest m WHERE m.source_id=t.source_id AND m.sha256=t.sha256) AND NOT ${stagingNeedsTextSql('t')}`, [src, context.segmentShas]);+ // The page's own segment texts, and unreferenced texts holding one of its claims (plain or as a fence cell stores it),+ // only: a text of another page holding the same words is that page's body, never a residue of this purge (an inline+ // page with no claims referenced none, so the inventory sweep below must not probe the table).+ const claimForms = context ? claimTextForms(context.needles) : [];+ if (context && !context.segmentShas.length && !claimForms.length) stores.push({ store: 'page_segment_texts', status: 'not_present', removed: removed.page_segment_texts ?? 0 });+ if (context && (context.segmentShas.length || claimForms.length)) await keyed('page_segment_texts', `SELECT 1 FROM page_segment_texts t WHERE t.source_id=$1+ AND (t.sha256=ANY(SELECT decode(h,'hex') FROM unnest($2::text[]) AS h) OR EXISTS (SELECT 1 FROM unnest($3::text[]) AS n WHERE strpos(lower(convert_from(t.body,'UTF8')),n)>0))+ AND NOT EXISTS (SELECT 1 FROM page_body_manifest m WHERE m.source_id=t.source_id AND m.sha256=t.sha256) AND NOT ${stagingNeedsTextSql('t')}`, [src, context.segmentShas, claimForms]);if (context) {const refs = context.factIds.map(String);for (const table of ['decide_review_queue', 'decide_review_proposals']) await keyed(table, `SELECT 1 FROM ${table} WHERE source_id=$1 AND (a_ref=ANY($2::text[]) OR b_ref=ANY($2::text[]))`, [src, refs]);diff --git a/src/core/fence-shared.ts b/src/core/fence-shared.tsindex d5821cc1e5..f65c1cea84 100644--- a/src/core/fence-shared.ts+++ b/src/core/fence-shared.ts@@ -141,6 +141,11 @@ export function escapeFenceCell(s: string): string {return encodeFenceMarkers(s.replace(/\|/g, '\\|').replace(/\r\n?|\n/g, '<br>'));}+/** Each claim lowered, plain and as a facts-fence cell stores it (escapeFenceCell), deduplicated: the forms stored text holds it in. */+export function claimTextForms(claims: readonly string[]): string[] {+ return [...new Set(claims.flatMap(claim => [claim.toLowerCase(), escapeFenceCell(claim).toLowerCase()]).filter(Boolean))];+}+/*** A fence rewrite refused because the fence it starts from does not parse* cleanly. Every rewriter re-renders the rows the parser returned, sodiff --git a/src/core/persistence/page-purge.ts b/src/core/persistence/page-purge.tsindex e2b1d61cce..8215007b6d 100644--- a/src/core/persistence/page-purge.ts+++ b/src/core/persistence/page-purge.ts@@ -51,6 +51,7 @@ import { contentHash } from '../utils.ts';import { isSegmentedPage } from '../page-body/page-shape.ts';import { rewrittenContentHash } from '../page-body/segment-rewrite.ts';import { stagingNeedsTextSql } from '../page-body/schema.ts';+import { claimTextForms } from '../fence-shared.ts';import type { PagePurgeContext } from '../facts/purge-verify.ts';import { assertHeldPageKeys } from '../page-state/guards.ts';import { noteBelief } from '../belief/ledger.ts';@@ -333,7 +334,7 @@ export async function purgePageInTransaction(tx: BrainEngine, row: WriteRequest,derived_hidden: await appendDerivedHidden(tx, { sourceId, request: row.id, publicationId: row.id, op: 'delete_page', targets: heldTargets, truncated: walk === 'truncated' }),derived_walk: walk })) : null;if (ledger) removed.belief_events = ledger.purged_events + ledger.redacted_fields.length;- const { shas, ...segmentRows } = await deletePageWithSegments(tx, sourceId, slug, page.id);+ const { shas, ...segmentRows } = await deletePageWithSegments(tx, sourceId, slug, page.id, needles);Object.assign(removed, segmentRows);if (!retention) appendPurgeIntent({ request: row.id, request_id: row.request_id, source_id: sourceId, source_incarnation: row.source_incarnation,scope: 'page', slug, purge_epoch: epoch, content_hashes: [...hashes], facts: mirrorFacts, takes: mirrorTakes, lifetimes });@@ -421,8 +422,13 @@ export async function unpurgePage(ctx: OperationContext, p: Record<string, unkno* page still references stays, and so does one an unpublished write of another page staged or deduped onto (a create* holds its manifest rows in memory until it publishes): that write's copy, not this page's. The restore-time purge* replay deletes a page this way too.+ *+ * A text can outlive the staging that recorded it: another page's write that dedupes onto it refreshes its created_at+ * (stageSegmentTexts), so it stays younger than the grace window after this page's stagings expired. So, with+ * `claims` (the page's own claims, withdrawn ones included), every unreferenced text of the source holding one of them,+ * plain or as a facts-fence cell stores it (escapeFenceCell; the match purgeSegmentStorage uses), goes too.*/-export async function deletePageWithSegments(tx: BrainEngine, sourceId: string, slug: string, pageId: number):+export async function deletePageWithSegments(tx: BrainEngine, sourceId: string, slug: string, pageId: number, claims: readonly string[] = []):Promise<{ shas: string[]; page_body_manifest: number; page_body_stagings: number; page_segment_texts: number }> {const shas = (await tx.executeRaw<{ sha: string }>(`SELECT encode(sha256,'hex') AS sha FROM page_body_manifest WHERE page_id=$1UNION SELECT encode(r.sha256,'hex') FROM page_body_stagings s JOIN page_body_staging_texts r ON r.staging_id=s.id@@ -432,5 +438,10 @@ export async function deletePageWithSegments(tx: BrainEngine, sourceId: string,await tx.deletePage(slug, { sourceId });const texts = shas.length ? (await tx.executeRaw(`DELETE FROM page_segment_texts t WHERE t.source_id=$1 AND t.sha256=ANY(SELECT decode(h,'hex') FROM unnest($2::text[]) AS h)AND NOT EXISTS (SELECT 1 FROM page_body_manifest m WHERE m.source_id=t.source_id AND m.sha256=t.sha256) AND NOT ${stagingNeedsTextSql('t')} RETURNING 1`, [sourceId, shas])).length : 0;- return { shas, page_body_manifest: manifest, page_body_stagings: stagings, page_segment_texts: texts };+ const forms = claimTextForms(claims);+ const carrying = forms.length ? (await tx.executeRaw<{ sha: string }>(`DELETE FROM page_segment_texts d WHERE (d.source_id,d.sha256) IN (SELECT t.source_id,t.sha256+ FROM page_segment_texts t WHERE t.source_id=$1 AND NOT EXISTS (SELECT 1 FROM page_body_manifest m WHERE m.source_id=t.source_id AND m.sha256=t.sha256) OFFSET 0)+ AND EXISTS (SELECT 1 FROM unnest($2::text[]) AS n WHERE strpos(lower(convert_from(d.body,'UTF8')),n)>0) AND NOT ${stagingNeedsTextSql('d')}+ RETURNING encode(d.sha256,'hex') AS sha`, [sourceId, forms])).map(r => r.sha) : [];+ return { shas: [...shas, ...carrying], page_body_manifest: manifest, page_body_stagings: stagings, page_segment_texts: texts + carrying.length };}diff --git a/test/pathological/lp-h-purge-orphan-segment-text.test.ts b/test/pathological/lp-h-purge-orphan-segment-text.test.tsindex 2872494a46..43b760c74e 100644--- a/test/pathological/lp-h-purge-orphan-segment-text.test.ts+++ b/test/pathological/lp-h-purge-orphan-segment-text.test.ts@@ -10,7 +10,10 @@* references, in the same transaction. A text a live staging of another write recorded stays (that unpublished* write's copy, the rule for referenced texts); purge_fact aborts a live staging holding the claim, so its texts go.* purge_fact's text delete also matches the claim as a fence cell stores it (escapeFenceCell: `|` as `\|`), the- * forms stagingsHoldingClaim matches, so an orphan holding a claim with `|` goes too.+ * forms stagingsHoldingClaim matches, so an orphan holding a claim with `|` goes too. A text can outlive the staging+ * that recorded it (another page's write that dedupes onto it refreshes its created_at, and terminal stagings go+ * after 24 h), so the page purge also deletes the source's unreferenced texts holding one of the page's claims,+ * withdrawn ones included, in both forms; a text a live staging holds still stays.* 2. Fails when: right after the purge, before any GC, a row of page_segment_texts still holds the planted claim, plain* or escaped.* 3. A 2 MB conversation page with a facts fence: put_page, forget_fact, delete_page, restore_page, then delete_page@@ -187,4 +190,63 @@ for (const { backend, databaseUrl } of pathologicalArms()) describe(`a purge aftexpect(body.compiled_truth).not.toContain(PIPE_MARKER);for (const needle of NEEDLES) expect(body.compiled_truth).toContain(needle);}), 600_000);++ /**+ * Page A's fence text, deduped onto by a write of page B (stageSegmentTexts refreshes its created_at, page-body.ts),+ * after A's stagings expired (terminal stagings go after BODY_STAGING_HARD_MS). forget_fact, delete_page and+ * restore_page then leave the text unreferenced, younger than the GC grace window, and named by no staging of A.+ */+ async function expiredStagingOrphan(slug: string, other: string, seed: number, marker: string, keepOpen: boolean) {+ const claim = `The vault marker is quill|${marker}`, cell = escapeFenceCell(claim);+ await op('put_page', { slug, content: page(seed, cell), request_id: randomUUID(), wait_ms: 30000 });+ const { id: pageId } = await segmentedPageRow(engine, slug);+ const [text] = await engine.executeRaw<{ sha: string; body: Uint8Array; line_count: number }>(`SELECT DISTINCT encode(t.sha256,'hex') AS sha, t.body, t.line_count+ FROM page_body_manifest m JOIN page_segment_texts t ON t.source_id=m.source_id AND t.sha256=m.sha256+ WHERE m.page_id=$1 AND position(convert_to($2::text,'UTF8') in t.body)>0`, [pageId, cell]);+ const sha = text!.sha;+ const [source] = await engine.executeRaw<{ incarnation: string }>(`SELECT incarnation FROM sources WHERE id='default'`);+ const staging = randomUUID();+ await engine.transaction(tx => withCoordinatedWrite(tx, ['default'], async () => {+ await tx.openBodyStaging({ id: staging, kind: 'put', principalKind: 'application', principalId: 'test:fixture', clientRequestId: randomUUID(),+ sourceId: 'default', sourceIncarnation: source!.incarnation, slug: other, pageId: null, mode: 'create', baseRevision: null, baseGeneration: null,+ declaredBytes: 16, declaredSha256: null, reservedBytes: 0, idleExpiresAt: new Date(Date.now() + 3_600_000), hardExpiresAt: new Date(Date.now() + 7_200_000) });+ await tx.stageSegmentTexts('default', [{ sha256: Buffer.from(sha, 'hex'), body: new Uint8Array(text!.body), lineCount: Number(text!.line_count) }], { stagingId: staging });+ if (!keepOpen) await tx.setBodyStagingState(staging, 'aborted');+ }, TEST_WRITE_ATTRIBUTION));+ await engine.executeRaw(`UPDATE page_body_stagings SET updated_at=now() - interval '25 hours' WHERE source_id='default' AND slug=$1`, [slug]);+ await engine.sweepSegments({ sourceId: 'default', expireStagings: true });+ expect(await engine.executeRaw(`SELECT 1 FROM page_body_stagings WHERE source_id='default' AND (slug=$1 OR page_id=$2)`, [slug, pageId])).toHaveLength(0);+ const [fact] = await engine.executeRaw<{ id: number }>('SELECT id FROM facts WHERE source_id=$1 AND strpos(fact,$2)>0', ['default', marker]);+ expect((await op('forget_fact', { id: Number(fact!.id), reason: 'lp-h lifecycle' })).expired).toBe(true);+ expect((await op('delete_page', { slug, request_id: randomUUID(), expected_revision: await revision(slug) })).status).toBe('soft_deleted');+ expect((await op('restore_page', { slug, request_id: randomUUID(), expected_revision: await revision(slug, true) })).status).toBe('restored');+ expect(await textExists(sha)).toBe(true);+ expect(await engine.executeRaw(`SELECT 1 FROM page_body_manifest WHERE source_id='default' AND sha256=decode($1,'hex')`, [sha])).toHaveLength(0);+ expect(await orphansOf(slug)).not.toContain(sha);+ return { claim, cell, sha, staging };+ }++ test('delete_page purge:true deletes an unreferenced text holding the page\'s withdrawn claim after its staging expired', async () => withEnv(env(), async () => {+ const slug = 'notes/lp-h-expired-staging';+ const { claim, cell, sha, staging } = await expiredStagingOrphan(slug, 'notes/lp-h-expired-dedupe', 23, 'vault5501', false);+ const purge = await op('delete_page', { slug, purge: true, request_id: randomUUID(), expected_revision: await revision(slug) });+ expect(purge.status).toBe('purged');+ const left = { escaped: await textsHolding(cell), plain: await textsHolding(claim), text: await textExists(sha) };+ console.log(`[lp-h] ${backend} expired-staging page purge: after: ${JSON.stringify(left)}`);+ expect(left).toEqual({ escaped: 0, plain: 0, text: false });+ expect((purge.receipt.stores as Array<{ store: string; status: string }>).find(s => s.store === 'page_segment_texts')?.status).toBe('deleted');+ await engine.executeRaw('DELETE FROM page_body_stagings WHERE id=$1::uuid', [staging]);+ }), 600_000);++ test('that text survives the page purge while an unpublished write of another page still holds it', async () => withEnv(env(), async () => {+ const slug = 'notes/lp-h-expired-held';+ const { sha, staging } = await expiredStagingOrphan(slug, 'notes/lp-h-expired-held-create', 29, 'vault5502', true);+ const purge = await op('delete_page', { slug, purge: true, request_id: randomUUID(), expected_revision: await revision(slug) });+ expect(purge.status).toBe('purged');+ expect(await stagingState(staging)).toBe('open');+ expect(await textExists(sha)).toBe(true);+ expect((purge.receipt.stores as Array<{ store: string; status: string }>).find(s => s.store === 'page_segment_texts')?.status).not.toBe('incomplete');+ await engine.executeRaw('DELETE FROM page_body_stagings WHERE id=$1::uuid', [staging]);+ await engine.executeRaw(`DELETE FROM page_segment_texts WHERE source_id='default' AND sha256=decode($1,'hex')`, [sha]);+ }), 600_000);});