Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
LPH (h): page purge deletes segment texts the page's stagings recorded that no manifest references (N14-5)
garrytan3bf97940832d
diff --git a/docs/architecture/key-files/memory-purge.md b/docs/architecture/key-files/memory-purge.mdindex 91dc583440..b554ee78a2 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 only its manifests referenced 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 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 2abbfd439d..86829b5f91 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -909,6 +909,8 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;{ 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.' },// Large-pages hardening (f).{ 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.' },+ // Large-pages hardening (h): N14-5.+ { 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.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/persistence/page-purge.ts b/src/core/persistence/page-purge.tsindex 5ed9c91c85..e2b1d61cce 100644--- a/src/core/persistence/page-purge.ts+++ b/src/core/persistence/page-purge.ts@@ -412,15 +412,21 @@ export async function unpurgePage(ctx: OperationContext, p: Record<string, unkno}/**- * Delete a purged page with its segment storage (Wave B, spec 11), in the caller's transaction: the segment texts only- * its manifests referenced go with it, and so do its stagings (one of a create has no page row to cascade from). A text- * another 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.+ * Delete a purged page with its segment storage (Wave B, spec 11), in the caller's transaction: the segment texts its+ * manifests referenced go with it, and so do its stagings (one of a create has no page row to cascade from). So do the+ * texts its stagings recorded (page_body_staging_texts) that no manifest row references any more: a sweep that drops+ * a closed generation's rows keeps a text younger than the GC grace window, so the text a forget rewrite replaced is+ * no longer in the manifest after a later write's sweep (N14-5), and only the staging that wrote it still names it.+ * Stagings outlive that window (BODY_STAGING_HARD_MS), so the page's stagings name every such text. A text another+ * 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.*/export async function deletePageWithSegments(tx: BrainEngine, sourceId: string, slug: string, pageId: number):Promise<{ shas: string[]; page_body_manifest: number; page_body_stagings: number; page_segment_texts: number }> {- const shas = (await tx.executeRaw<{ sha: string }>(`SELECT DISTINCT encode(sha256,'hex') AS sha FROM page_body_manifest WHERE page_id=$1`, [pageId])).map(r => r.sha);+ const shas = (await tx.executeRaw<{ sha: string }>(`SELECT encode(sha256,'hex') AS sha FROM page_body_manifest WHERE page_id=$1+ UNION SELECT encode(r.sha256,'hex') FROM page_body_stagings s JOIN page_body_staging_texts r ON r.staging_id=s.id+ WHERE s.source_id=$2 AND (s.slug=$3 OR s.page_id=$1) AND r.source_id=$2`, [pageId, sourceId, slug])).map(r => r.sha);const manifest = (await tx.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM page_body_manifest WHERE page_id=$1', [pageId]))[0]?.n ?? 0;const stagings = (await tx.executeRaw('DELETE FROM page_body_stagings WHERE source_id=$1 AND (slug=$2 OR page_id=$3) RETURNING 1', [sourceId, slug, pageId])).length;await tx.deletePage(slug, { sourceId });diff --git a/test/pathological/lp-h-purge-orphan-segment-text.test.ts b/test/pathological/lp-h-purge-orphan-segment-text.test.tsnew file mode 100644index 0000000000..5a09356d9d--- /dev/null+++ b/test/pathological/lp-h-purge-orphan-segment-text.test.ts@@ -0,0 +1,162 @@+/**+ * Large-pages hardening (h), N14-5: a purge removes the segment text an earlier withdrawal and restore left unreferenced.+ *+ * 1. Protects: on a page stored in segments, forget_fact rewrites the fence segment into a new generation without a+ * version, so the old fence text is held only by a closed manifest row no GC root needs. The post-write sweep of a+ * later write (restore_page) deletes that row and, because the text is younger than the GC grace window+ * (SEGMENT_TEXT_GC_GRACE_MS, 1 h), keeps the text unreferenced. `delete_page purge: true` found the page's texts+ * only through its manifest, so it left that text, holding the withdrawn claim, until the GC. The purge now also+ * takes every text the page's own stagings recorded (page_body_staging_texts) and deletes those no manifest row+ * 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.+ * 2. Fails when: right after the purge, before any GC, a row of page_segment_texts still holds the planted claim.+ * 3. A 2 MB conversation page with a facts fence: put_page, forget_fact, delete_page, restore_page, then delete_page+ * purge:true (the N14 lifecycle) or purge_fact of the claim. Runs on PGLite, and on Postgres when DATABASE_URL is+ * set. N14 reproduced it at 2 MB, 20 MB and 24 MiB; the orphan is one fence segment at any size, so the 2 MB page+ * exercises the same path.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import type { BrainEngine } from '../../src/core/engine.ts';+import type { OperationContext } from '../../src/core/ops/contract.ts';+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';+import { operations } from '../../src/core/operations.ts';+import { registerLocalWriter } from '../../src/core/persistence/identity.ts';+import { withCoordinatedWrite } from '../../src/core/persistence/context.ts';+import { disposePersistenceConsumer } from '../../src/core/persistence/service.ts';+import { conversationBody } from '../helpers/conversation-page.ts';+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';+import { reconstructedPage, segmentedPageRow } from '../helpers/segmented-page-checks.ts';+import { TEST_WRITE_ATTRIBUTION } from '../helpers/write-attribution.ts';+import { withEnv } from '../helpers/with-env.ts';+import { pathologicalArms } from './harness.ts';++const TOKEN = 'quillfeather7731';+const CLAIM = `The lifecycle marker is ${TOKEN}`;+const NEEDLES = ['lphneedleone', 'lphneedletwo', 'lphneedlethree'];+const FENCE = ['', '', '## Facts', '', '<!--- gbrain:facts:begin -->',+ '| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |',+ '|---|-------|------|------------|------------|------------|------------|-------------|--------|---------|',+ `| 1 | ${CLAIM} | fact | 1.0 | world | low | 2026-10-01 | | chat | |`,+ '<!--- gbrain:facts:end -->', ''].join('\n');+const page = (seed: number) => `---\ntitle: Lifecycle chat\ntype: note\n---\n\n${conversationBody(2_000_000, { seed,+ needles: NEEDLES.map((word, i) => ({ at: 0.2 + i * 0.3, word })) })}${FENCE}`;++const homes: string[] = [];+afterAll(() => { for (const home of homes) rmSync(home, { recursive: true, force: true }); });++for (const { backend, databaseUrl } of pathologicalArms()) describe(`a purge after forget, delete and restore leaves no segment text (${backend})`, () => {+ const home = mkdtempSync(join(tmpdir(), 'gbrain-lp-h-'));+ homes.push(home);+ const env = () => ({ GBRAIN_HOME: home, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined, OPENAI_API_KEY: undefined, VOYAGE_API_KEY: undefined, ANTHROPIC_API_KEY: undefined });+ let engine: BrainEngine;+ let close: () => Promise<void>;+ beforeAll(async () => withEnv(env(), async () => {+ if (databaseUrl) ({ engine, close } = await isolatedPersistencePostgres(databaseUrl));+ else { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); close = () => engine.disconnect(); }+ await registerLocalWriter(engine, 'cli');+ await engine.setConfig('pages.segmented_storage', 'on');+ }), 120_000);+ afterAll(async () => withEnv(env(), async () => { await disposePersistenceConsumer(engine); await close?.(); }), 120_000);++ const ctx = (): OperationContext => ({ engine, sourceId: 'default', remote: false, dryRun: false,+ config: { engine: engine.kind, embedding_disabled: true, storage: { backend: 'local', bucket: 'b', localPath: join(home, 'storage') } },+ logger: { info() {}, warn() {}, error() {} } } as OperationContext);+ const op = (name: string, params: Record<string, unknown>) => operations.find(o => o.name === name)!.handler(ctx(), params) as Promise<Record<string, any>>;+ const revision = async (slug: string, includeDeleted = false) =>+ (await op('get_page', { slug, body: 'none', ...(includeDeleted ? { include_deleted: true } : {}) })).revision as string;+ /** Texts of the source holding `needle`'s bytes, referenced or not. */+ const textsHolding = async (needle: string) => Number((await engine.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM page_segment_texts+ WHERE source_id='default' AND position(convert_to($1::text,'UTF8') in body)>0`, [needle]))[0]!.n);+ /** Unreferenced texts the page's stagings recorded: what the purge must not leave. */+ const orphansOf = async (slug: string) => (await engine.executeRaw<{ sha: string }>(`SELECT DISTINCT encode(t.sha256,'hex') AS sha+ FROM page_body_stagings s JOIN page_body_staging_texts r ON r.staging_id=s.id JOIN page_segment_texts t ON t.source_id=r.source_id AND t.sha256=r.sha256+ WHERE s.source_id='default' AND s.slug=$1 AND NOT EXISTS (SELECT 1 FROM page_body_manifest m WHERE m.source_id=t.source_id AND m.sha256=t.sha256)+ ORDER BY 1`, [slug])).map(row => row.sha);++ /** put_page, forget_fact, delete_page, restore_page: leaves the pre-forget fence text unreferenced (N14-5). */+ async function lifecycle(slug: string, seed: number): Promise<{ factId: number; orphans: string[] }> {+ await op('put_page', { slug, content: page(seed), request_id: randomUUID(), wait_ms: 30000 });+ expect((await segmentedPageRow(engine, slug)).body_storage).toBe('segmented');+ const [fact] = await engine.executeRaw<{ id: number }>('SELECT id FROM facts WHERE source_id=$1 AND strpos(fact,$2)>0', ['default', TOKEN]);+ const factId = Number(fact!.id);+ expect((await op('forget_fact', { id: factId, 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');+ const orphans = await orphansOf(slug);+ expect(orphans.length).toBeGreaterThan(0);+ expect(await textsHolding(TOKEN)).toBeGreaterThan(0);+ return { factId, orphans };+ }+ /** An unpublished create of another page that deduped onto `sha` (its staging recorded the text). */+ async function holdText(slug: string, sha: string): Promise<string> {+ const [source] = await engine.executeRaw<{ incarnation: string }>(`SELECT incarnation FROM sources WHERE id='default'`);+ const id = randomUUID();+ await engine.transaction(tx => withCoordinatedWrite(tx, ['default'], async () => {+ await tx.openBodyStaging({ id, kind: 'put', principalKind: 'application', principalId: 'test:fixture', clientRequestId: randomUUID(),+ sourceId: 'default', sourceIncarnation: source!.incarnation, slug, 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.executeRaw(`INSERT INTO page_body_staging_texts (staging_id, source_id, sha256) VALUES ($1::uuid, 'default', decode($2,'hex'))`, [id, sha]);+ }, TEST_WRITE_ATTRIBUTION));+ return id;+ }+ const stagingState = async (id: string) => (await engine.executeRaw<{ state: string }>('SELECT state FROM page_body_stagings WHERE id=$1::uuid', [id]))[0]?.state;+ const allTexts = async () => (await engine.executeRaw<{ sha: string }>(`SELECT encode(sha256,'hex') AS sha FROM page_segment_texts WHERE source_id='default' ORDER BY 1`)).map(r => r.sha);+ const textExists = async (sha: string) => (await engine.executeRaw(`SELECT 1 FROM page_segment_texts WHERE source_id='default' AND sha256=decode($1,'hex')`, [sha])).length === 1;++ test('delete_page purge:true deletes the text the restore left unreferenced, in the purge', async () => withEnv(env(), async () => {+ const slug = 'notes/lp-h-page-purge';+ const before = new Set(await allTexts());+ const { orphans } = await lifecycle(slug, 11);+ const purge = await op('delete_page', { slug, purge: true, request_id: randomUUID(), expected_revision: await revision(slug) });+ expect(purge.status).toBe('purged');+ const left = { token: await textsHolding(TOKEN), needles: await Promise.all(NEEDLES.map(textsHolding)), orphans: (await Promise.all(orphans.map(textExists))).filter(Boolean).length };+ console.log(`[lp-h] ${backend} page purge: ${orphans.length} orphan(s) before; after: ${JSON.stringify(left)}`);+ expect(left).toEqual({ token: 0, needles: NEEDLES.map(() => 0), orphans: 0 });+ expect((await allTexts()).filter(sha => !before.has(sha))).toEqual([]);+ expect((purge.receipt.stores as Array<{ store: string; status: string }>).find(s => s.store === 'page_segment_texts')?.status).toBe('deleted');+ }), 600_000);++ test('a text an unpublished write of another page holds survives the page purge; the rest of the page goes', async () => withEnv(env(), async () => {+ const slug = 'notes/lp-h-held', other = 'notes/lp-h-held-create';+ const before = new Set(await allTexts());+ const { orphans } = await lifecycle(slug, 13);+ const held = orphans[0]!;+ const staging = await holdText(other, held);+ 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(held)).toBe(true);+ expect((await Promise.all(orphans.slice(1).map(textExists))).filter(Boolean)).toHaveLength(0);+ for (const needle of NEEDLES) expect(await textsHolding(needle)).toBe(0);+ expect((await allTexts()).filter(sha => !before.has(sha))).toEqual([held]);+ 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')`, [held]);+ }), 600_000);++ test('purge_fact of the claim deletes the unreferenced text, aborts a live staging holding it, and the page still reads', async () => withEnv(env(), async () => {+ const slug = 'notes/lp-h-fact-purge', other = 'notes/lp-h-fact-create';+ const { factId, orphans } = await lifecycle(slug, 17);+ const holding = (await engine.executeRaw<{ sha: string }>(`SELECT encode(sha256,'hex') AS sha FROM page_segment_texts WHERE source_id='default'+ AND sha256=ANY(SELECT decode(h,'hex') FROM unnest($1::text[]) AS h) AND position(convert_to($2::text,'UTF8') in body)>0`, [orphans, TOKEN])).map(r => r.sha);+ expect(holding.length).toBeGreaterThan(0);+ const staging = await holdText(other, holding[0]!);+ const dry = await op('purge_fact', { id: factId, dry_run: true });+ const done = await op('purge_fact', { id: factId, confirm: dry.confirm_token, expected_revision: dry.expected_revision, request_id: randomUUID() });+ expect(done.state).toBe('committed');+ expect(await stagingState(staging)).toBe('aborted');+ expect(await textsHolding(TOKEN)).toBe(0);+ for (const sha of holding) expect(await textExists(sha)).toBe(false);+ const { page: row, body, hash } = await reconstructedPage(engine, slug);+ expect(row.body_storage).toBe('segmented');+ expect(hash).toBe(row.content_hash);+ expect(body.compiled_truth).not.toContain(TOKEN);+ for (const needle of NEEDLES) expect(body.compiled_truth).toContain(needle);+ const read = await op('get_page', { slug, body: 'auto' });+ expect(read.revision).toBe(row.knowledge_revision);+ await engine.executeRaw('DELETE FROM page_body_stagings WHERE id=$1::uuid', [staging]);+ }), 600_000);+});diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txtindex 1eb7ebe3a9..22c4e2d630 100644--- a/test/postgres-unit-arms.txt+++ b/test/postgres-unit-arms.txt@@ -276,6 +276,7 @@ test/pathological/lp-d-recovery-version.test.tstest/pathological/lp-d-segmented-mirror-gate.test.tstest/pathological/lp-f-split-fence-withdrawal-capacity.test.tstest/pathological/lp-g-file-digest-fence-bound.test.ts+test/pathological/lp-h-purge-orphan-segment-text.test.tstest/persistence-background-pause.test.tstest/persistence-bounded-read-session.test.tstest/persistence-capacity-forecast.test.ts