Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

persistence: a charged member publishes alone; page purge sweeps texts for every claim; laneFallback charge test (LPH review round 2)

garrytan8c787f6929de
diff --git a/docs/architecture/key-files/memory-purge.md b/docs/architecture/key-files/memory-purge.md
index e87893bf28..a1bb99e49c 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, 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/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 (every fact filed on it, withdrawn ones included, and every take, not the journal sweep's first 32, tested in batches of `CLAIM_FORMS_BATCH` forms; 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.ts
index e2a0e03eb9..e54dd5c54f 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -919,7 +919,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;
{ 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. 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).' },
+ { 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. An interruption of a grouped publication (a `put_pages` batch, a managed import batch or a sync lane group) counts against every member of the group, and a member already charged an interruption is claimed and published on its own from then on, so a batch that overruns only as a whole still commits page by page. 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).' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/facts/purge-verify.ts b/src/core/facts/purge-verify.ts
index 9514fb79f1..6e9cd17b5f 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 { claimTextForms, escapeFenceCell } from '../fence-shared.ts';
+import { CLAIM_FORMS_BATCH, 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';
@@ -487,7 +487,7 @@ export async function verifyFactPurge(engine: BrainEngine, input: { target: Purg
}
/** In-process context a page purge keeps for its receipt (never journaled): the page's claims as probe needles, and row ids. */
-export interface PagePurgeContext { needles: string[]; factIds: number[]; pageId: number; paths: string[]; segmentShas: string[]; ledgerClaims?: string[]; ledger?: LedgerPurgeReport | null }
+export interface PagePurgeContext { needles: string[]; factIds: number[]; pageId: number; paths: string[]; segmentShas: string[]; segmentClaims?: string[]; ledgerClaims?: string[]; ledger?: LedgerPurgeReport | null }
const outOfReach = (engine: BrainEngine): StoreReport[] => OUT_OF_REACH_RESIDUALS.map(r => ({ store: r.store, status: 'out_of_reach' as const,
detail: r.store === 'database_physical' ? `${r.detail}${engine.kind === 'pglite' ? ' PGLite has no autovacuum.' : ' On Postgres the operator runs VACUUM; WAL archives, replicas and PITR windows are outside gbrain.'}` : r.detail }));
@@ -524,11 +524,23 @@ export async function verifyPagePurge(engine: BrainEngine, input: { sourceId: st
// 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) : [];
+ const claimForms = context ? claimTextForms(context.segmentClaims ?? 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 && (context.segmentShas.length || claimForms.length)) {
+ const n = removed.page_segment_texts ?? 0;
+ let remaining = 0, unverified: string | undefined;
+ for (let at = 0; at === 0 || at < claimForms.length; at += CLAIM_FORMS_BATCH) {
+ const result = await boundedCount(engine, `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, at === 0 ? context.segmentShas : [], claimForms.slice(at, at + CLAIM_FORMS_BATCH)], deadline);
+ if ('unverified' in result) { unverified = result.unverified; break; }
+ remaining += result.count;
+ }
+ if (unverified) stores.push({ store: 'page_segment_texts', status: 'unverified', reason: unverified, removed: n });
+ else if (remaining) stores.push({ store: 'page_segment_texts', status: 'incomplete', remaining, removed: n });
+ else stores.push({ store: 'page_segment_texts', status: n ? 'deleted' : 'not_present', removed: n });
+ }
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.ts
index f65c1cea84..b124c51262 100644
--- a/src/core/fence-shared.ts
+++ b/src/core/fence-shared.ts
@@ -141,6 +141,9 @@ export function escapeFenceCell(s: string): string {
return encodeFenceMarkers(s.replace(/\|/g, '\\|').replace(/\r\n?|\n/g, '<br>'));
}
+/** The most claim forms one segment-text statement tests per row; a longer list runs in batches of this size. */
+export const CLAIM_FORMS_BATCH = 512;
+
/** 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))];
diff --git a/src/core/persistence/consumer.ts b/src/core/persistence/consumer.ts
index 62c18d58cd..c97871cb99 100644
--- a/src/core/persistence/consumer.ts
+++ b/src/core/persistence/consumer.ts
@@ -1070,7 +1070,7 @@ export class PersistenceConsumer implements PersistenceConsumerLike {
// A managed import batch also groups on PGLite: its members share one transaction's guards there too.
if (!group || this.engine.kind !== 'postgres' && !group.startsWith('import:')) return this.execute(row, root);
// #6007: a put_pages or import batch publishes in groups of at most PAGE_BATCH_GROUP_MAX pages.
- const followers = await claimGroupFollowers(this.engine, row, group, syncGroup(group) ? 63 : PAGE_BATCH_GROUP_MAX - 1);
+ const followers = (row.transient_interruptions ?? 0) > 0 ? [] : await claimGroupFollowers(this.engine, row, group, syncGroup(group) ? 63 : PAGE_BATCH_GROUP_MAX - 1);
if (!followers.length && !lane) return this.execute(row, root);
claimed.push(...followers);
const rows = [row, ...followers];
diff --git a/src/core/persistence/journal.ts b/src/core/persistence/journal.ts
index ea19e3869e..ffbfab4a30 100644
--- a/src/core/persistence/journal.ts
+++ b/src/core/persistence/journal.ts
@@ -451,10 +451,11 @@ export async function claimGroupFollowers(engine: BrainEngine, head: WriteReques
// #5984 G6: only the group's candidate prefix is locked. Locking every next row also held a foreground write's row
// (the first non-member) for the claim's round trips, so its recovery record and reads waited on the lane.
const next = await tx.executeRaw<{ id: string; state: string; grp: string | null; recovering: boolean; claim_phase: unknown }>(`WITH next AS (
- SELECT id,sequence,state,${GROUP_KEY_SQL} AS grp,recovery IS NOT NULL AS recovering,NOT ${BACKOFF_ELAPSED('persistence_requests')} AS backoff FROM persistence_requests
+ SELECT id,sequence,state,${GROUP_KEY_SQL} AS grp,recovery IS NOT NULL AS recovering,NOT ${BACKOFF_ELAPSED('persistence_requests')} AS backoff,transient_interruptions>0 AS charged FROM persistence_requests
WHERE worktree_id=$1::uuid AND sequence>$2 AND (state IN ('queued','running','recovering') OR recovery IS NOT NULL) ORDER BY sequence LIMIT $3),
- -- v261: a member still in its transient backoff ends the group's prefix like a non-member.
- bound AS (SELECT min(sequence) AS sequence FROM next WHERE grp IS DISTINCT FROM $4 OR state<>'queued' OR recovering OR backoff)
+ -- v261: a member still in its transient backoff ends the group's prefix like a non-member, and so does one already
+ -- charged a transient interruption: it publishes alone, so a batch that overruns only as a whole is not retried as one.
+ bound AS (SELECT min(sequence) AS sequence FROM next WHERE grp IS DISTINCT FROM $4 OR state<>'queued' OR recovering OR backoff OR charged)
SELECT r.id,r.state,${GROUP_KEY_SQL} AS grp,r.recovery IS NOT NULL AS recovering,r.claim_phase
FROM persistence_requests r WHERE r.id IN (SELECT id FROM next WHERE sequence<COALESCE((SELECT sequence FROM bound),9223372036854775807))
ORDER BY r.sequence FOR UPDATE OF r`, [head.worktree_id, head.sequence, max, group]);
diff --git a/src/core/persistence/page-purge.ts b/src/core/persistence/page-purge.ts
index 8215007b6d..f0f38811a6 100644
--- a/src/core/persistence/page-purge.ts
+++ b/src/core/persistence/page-purge.ts
@@ -51,7 +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 { CLAIM_FORMS_BATCH, 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';
@@ -86,6 +86,13 @@ async function readPurgeClaims(engine: Pick<BrainEngine, 'executeRaw'>, sourceId
return { factRows, takeRows, needles };
}
+/** Every claim of the page (its facts, withdrawn ones included, and its takes), trimmed and deduplicated, unbounded: the segment-text sweep's needles. */
+async function readSegmentClaims(engine: Pick<BrainEngine, 'executeRaw'>, sourceId: string, slug: string, pageId: number): Promise<string[]> {
+ const rows = await engine.executeRaw<{ c: string }>('SELECT fact AS c FROM facts WHERE source_id=$1 AND source_markdown_slug=$2 UNION SELECT claim FROM takes WHERE page_id=$3',
+ [sourceId, slug, pageId]);
+ return [...new Set(rows.map(r => r.c.trim()).filter(t => t.length >= 8))];
+}
+
/** #6884: how many queued purges of the source one preparation's journal sweep covers at most, this one included. */
export const PURGE_SWEEP_BATCH_MEMBERS = 32;
/** #6884: the most claim forms one batch sweep tests per journal row; members past it sweep on their own. */
@@ -275,6 +282,7 @@ export async function purgePageInTransaction(tx: BrainEngine, row: WriteRequest,
const hashes = new Set<string>();
if (!retention) await tombstonePage(tx, sourceId, slug, page.id, snapshot, row.id, actor, { hash: storedHash, generation: Number(stored?.body_generation) }, hashes);
const { factRows, takeRows, needles } = await readPurgeClaims(tx, sourceId, slug, page.id);
+ const segmentClaims = await readSegmentClaims(tx, sourceId, slug, page.id);
const factIds = factRows.map(f => Number(f.id)), takeIds = takeRows.map(t => Number(t.id));
const derivedFrom = await derivedRowsFrom(tx, [{ table: 'pages', id: page.id }, ...factIds.map(id => ({ table: 'facts', id })), ...takeIds.map(id => ({ table: 'takes', id }))]);
const purgedHere = new Set([...factIds.map(id => `facts:${id}`), ...takeIds.map(id => `takes:${id}`)]);
@@ -334,13 +342,13 @@ 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, needles);
+ const { shas, ...segmentRows } = await deletePageWithSegments(tx, sourceId, slug, page.id, segmentClaims);
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 });
const key = `${sourceId}:${row.request_id}`;
purgeContext.delete(key);
- purgeContext.set(key, { needles, factIds, pageId: page.id, paths, segmentShas: shas.slice(0, 4096), ledgerClaims: inventory.claims, ledger });
+ purgeContext.set(key, { needles, factIds, pageId: page.id, paths, segmentShas: shas.slice(0, 4096), segmentClaims, ledgerClaims: inventory.claims, ledger });
while (purgeContext.size > PURGE_CONTEXT_LIMIT) purgeContext.delete(purgeContext.keys().next().value!);
return { status: 'purged', slug, source_id: sourceId, residuals: PURGE_RESIDUALS, journal_sweep: journalSweep, ...(retention ? { retention: true } : {}),
purge: { content_hash8: storedHash?.slice(0, 8) ?? null, tombstoned: hashes.size > 0, content_hashes_tombstoned: hashes.size, removed,
@@ -438,10 +446,12 @@ 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;
- 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
+ const forms = claimTextForms(claims), carrying: string[] = [];
+ for (let at = 0; at < forms.length; at += CLAIM_FORMS_BATCH) {
+ carrying.push(...(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) : [];
+ RETURNING encode(d.sha256,'hex') AS sha`, [sourceId, forms.slice(at, at + CLAIM_FORMS_BATCH)])).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-c-publication-ceiling-retry.test.ts b/test/pathological/lp-c-publication-ceiling-retry.test.ts
index 823bd9501e..1c65301152 100644
--- a/test/pathological/lp-c-publication-ceiling-retry.test.ts
+++ b/test/pathological/lp-c-publication-ceiling-retry.test.ts
@@ -8,7 +8,9 @@
* publication overruns the ceiling every time ends `failed`/`write_interrupted` (cause `publication_ceiling`) after
* the cap instead of being prepared and published again without limit. A single overrun re-prepares and commits. Both
* publication arms: a database-only page (finishUnpublishedFailure) and a worktree-backed page (the recovery route,
- * which restores the canonical file first; on Postgres the retried publish there surfaces as a bare AbortError).
+ * which restores the canonical file first; on Postgres the retried publish there surfaces as a bare AbortError). A
+ * member a group's overrun charged publishes alone from then on, and a sync lane group cancelled while its predecessor
+ * still publishes charges each member on release (laneFallback).
* 2. Fails when: the cancelled publication is released as `database_contention` uncounted (v0.60.299.0: the error is a
* discarded connection, which is never counted), so the claim count grows past the cap; or when the recovery route
* fails it `storage_error` at once.
@@ -38,6 +40,9 @@ import { resetWriteSwitches } from '../../src/core/persistence/switches.ts';
import { _resetWriteThroughCacheForTest } from '../../src/core/write-through.ts';
import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';
import { withEnv } from '../helpers/with-env.ts';
+import { waitFor } from '../helpers/wait-for.ts';
+import { performSync } from '../../src/commands/sync/perform.ts';
+import { execFileSync } from 'node:child_process';
import { pathologicalArms } from './harness.ts';
const op = (name: string) => operations.find(o => o.name === name)!;
@@ -212,6 +217,47 @@ for (const { backend, databaseUrl } of pathologicalArms()) describe(`[${backend}
for (const { sourcePath } of files) expect(await engine.readPageSnapshot(sourcePath.replace(/\.md$/, ''), { sourceId })).toBeNull();
}, 180_000);
+ test('a grouped import whose group publication overruns only as a whole publishes each member alone after one charged interruption, and both commit', async () => {
+ await engine.setConfig('persistence.max_transient_retries', '2');
+ resetWriteSwitches();
+ const dir = `grp-whole-${++n}`;
+ mkdirSync(join(brainDir, dir), { recursive: true });
+ const files = ['a', 'b'].map(name => {
+ const sourcePath = `${dir}/${name}.md`;
+ writeFileSync(join(brainDir, sourcePath), page(`Whole ${name} ${n}`));
+ return { filePath: join(brainDir, sourcePath), sourcePath };
+ });
+ // A publication overruns only while another member prepared in the same pass is still unpublished (a group of two):
+ // the members prepare together and then reach before_commit one after the other inside the one transaction.
+ const unpublished = new Set<string>(), claims = new Map<string, number>(), grouped: string[][] = [];
+ installFaultHook(async (point, detail) => {
+ if (detail.sourceId !== sourceId) return;
+ if (point === 'consumer:preparing') { unpublished.add(detail.requestId!); claims.set(detail.requestId!, (claims.get(detail.requestId!) ?? 0) + 1); return; }
+ if (point !== 'publication:before_commit') return;
+ const together = unpublished.size;
+ unpublished.delete(detail.requestId!);
+ if (together < 2 || grouped.length >= GUARD) return;
+ grouped.push([...unpublished, detail.requestId!]);
+ unpublished.clear();
+ await new Promise(resolve => setTimeout(resolve, PARK_MS));
+ throw discarded();
+ });
+ const results = await withEnv({ GBRAIN_HOME: home }, () => importManagedFiles(engine, files, { sourceId, noEmbed: true }));
+ installFaultHook(undefined);
+ expect(results.map(result => result.status === 'rejected' ? (result.reason as { code?: string }).code : result.status)).toEqual(['fulfilled', 'fulfilled']);
+ // One group publication, cancelled at the ceiling; after it each member is claimed and published on its own.
+ expect(grouped.length).toBe(1);
+ const rows = await engine.executeRaw<{ request_id: string; state: string; transient_interruptions: number }>(
+ "SELECT request_id::text AS request_id,state,transient_interruptions FROM persistence_requests WHERE source_id=$1 AND intent->>'import_batch' IS NOT NULL AND slug LIKE $2 ORDER BY sequence",
+ [sourceId, `${dir}/%`]);
+ expect(rows.length).toBe(2);
+ for (const member of rows) {
+ expect(member).toMatchObject({ state: 'committed', transient_interruptions: 1 });
+ expect(claims.get(member.request_id)).toBe(2);
+ }
+ for (const { sourcePath } of files) expect(await engine.readPageSnapshot(sourcePath.replace(/\.md$/, ''), { sourceId })).not.toBeNull();
+ }, 180_000);
+
test('a single overrun is retried, never a terminal storage_error (on Postgres the retried publish surfaces as a bare AbortError), and commits', async () => {
const slug = `wt/overrun-once-${++n}`;
expect(await call({ slug, content: page(`Prior ${n}`), request_id: randomUUID() }, sourceId)).toMatchObject({ state: 'committed' });
@@ -224,4 +270,74 @@ for (const { backend, databaseUrl } of pathologicalArms()) describe(`[${backend}
expect(readFileSync(join(brainDir, `${slug}.md`), 'utf8')).toContain(`Next ${n}`);
}, 180_000);
});
+
+ /**
+ * #5984 lanes (Postgres only): a lane group the ceiling cancels while its predecessor group still publishes releases
+ * its claims (laneFallback) instead of taking the single path, and charges each member there. Eight pages in bulk
+ * groups on two lanes: the first group parks at `lane:applied` until the second's release is seen; the second overruns once at
+ * `lane:applied` (inside its transaction, before its turn) and rejects as the discarded connection does. Without the
+ * charge on release, a lane group the ceiling cancels every time would be released and claimed again without bound.
+ */
+ (backend === 'postgres' ? describe : describe.skip)('lane group (laneFallback)', () => {
+ let lanes: BrainEngine;
+ let closeLanes: (() => Promise<void>) | undefined;
+ const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] });
+ beforeAll(async () => { const pg = await isolatedPersistencePostgres(databaseUrl!, 'instance', 12); lanes = pg.engine; closeLanes = pg.close; }, 120_000);
+ afterAll(async () => { await withEnv({ GBRAIN_HOME: home }, () => disposePersistenceConsumer(lanes)); await closeLanes?.(); }, 60_000);
+
+ test('a lane group cancelled at the ceiling while its predecessor still publishes charges each member on release, and every page commits', async () => withEnv({ GBRAIN_HOME: home, GBRAIN_SYNC_BULK_SIZE: '4' }, async () => {
+ const id = `lpc-lanes-${randomUUID().slice(0, 8)}`, root = join(home, id);
+ mkdirSync(join(root, 'notes'), { recursive: true }); git(root, 'init', '-q');
+ for (let i = 0; i < 8; i++) writeFileSync(join(root, 'notes', `n${i}.md`), page(`Lane note ${i}`));
+ git(root, 'add', '.'); git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', 'notes');
+ await lanes.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ await lanes.executeRaw("INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,'{}')", [id, root]);
+ await claimWorktree(lanes, id, root);
+ await lanes.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ /** The request's group and the source's first two groups in admission order. */
+ const groupOf = async (requestId: string) => {
+ const [row] = await lanes.executeRaw<{ grp: string | null }>("SELECT intent->>'group' AS grp FROM persistence_requests WHERE request_id=$1::uuid", [requestId]);
+ const order = (await lanes.executeRaw<{ grp: string }>(`SELECT intent->>'group' AS grp FROM persistence_requests WHERE source_id=$1 AND intent ? 'group'
+ GROUP BY 1 ORDER BY min(sequence) LIMIT 2`, [id])).map(r => r.grp);
+ return { grp: row?.grp ?? null, first: order[0], second: order[1] };
+ };
+ let releaseFirst!: () => void;
+ const firstReleased = new Promise<void>(resolve => { releaseFirst = resolve; });
+ setTimeout(() => releaseFirst(), 10_000);
+ const overrun = new Set<string>(), charges: Array<{ grp: string | null; blocked: string | null }> = [];
+ let second: string | null = null;
+ installFaultHook(async (point, detail) => {
+ if (detail.sourceId !== id) return;
+ if (point === 'persistence:interruption_charged') {
+ const [charged] = await lanes.executeRaw<{ grp: string | null; blocked: string | null }>(
+ "SELECT intent->>'group' AS grp,blocked_reason AS blocked FROM persistence_requests WHERE request_id=$1::uuid", [detail.requestId]);
+ charges.push(charged!);
+ if (charged!.grp === second) releaseFirst();
+ return;
+ }
+ if (point !== 'lane:applied') return;
+ const group = await groupOf(detail.requestId!);
+ if (!group?.grp) return;
+ if (group.grp === group.first) { await firstReleased; return; }
+ if (group.grp !== group.second || overrun.has(group.grp)) return;
+ overrun.add(group.grp); second = group.grp;
+ await new Promise(resolve => setTimeout(resolve, PARK_MS));
+ throw discarded();
+ });
+ try {
+ await performSync(lanes, { sourceId: id, noPull: true, noEmbed: true, noExtract: true, drain: true, lanes: 2 });
+ await waitFor(async () => (await lanes.executeRaw<{ n: number }>(
+ "SELECT count(*)::int AS n FROM persistence_requests WHERE source_id=$1 AND intent->>'kind'='managed_sync_import' AND state<>'committed'", [id]))[0]!.n === 0,
+ { timeoutMs: 120_000, label: 'every lane page commits' });
+ } finally { installFaultHook(undefined); }
+ expect(overrun.size).toBe(1);
+ const members = await lanes.executeRaw<{ slug: string; transient_interruptions: number }>(
+ "SELECT slug,transient_interruptions FROM persistence_requests WHERE source_id=$1 AND intent->>'group'=$2 ORDER BY sequence", [id, second]);
+ expect(members.length).toBeGreaterThan(1);
+ // Each member of the cancelled group was charged once, by the lane release (its claim went back as group_member_waiting).
+ expect(members.map(member => member.transient_interruptions)).toEqual(members.map(() => 1));
+ expect(charges.filter(charge => charge.grp === second)).toEqual(members.map(() => ({ grp: second, blocked: 'group_member_waiting' })));
+ for (let i = 0; i < 8; i++) expect(await lanes.readPageSnapshot(`notes/n${i}`, { sourceId: id })).not.toBeNull();
+ }), 300_000);
+ });
});
diff --git a/test/pathological/lp-h-purge-orphan-segment-text.test.ts b/test/pathological/lp-h-purge-orphan-segment-text.test.ts
index 43b760c74e..71359a7a63 100644
--- a/test/pathological/lp-h-purge-orphan-segment-text.test.ts
+++ b/test/pathological/lp-h-purge-orphan-segment-text.test.ts
@@ -13,7 +13,8 @@
* 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.
+ * withdrawn ones included (all of them, not only the first 32 the journal sweep reads), 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
@@ -124,7 +125,6 @@ for (const { backend, databaseUrl } of pathologicalArms()) describe(`a purge aft
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(MARKER), 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');
@@ -183,7 +183,6 @@ for (const { backend, databaseUrl } of pathologicalArms()) describe(`a purge aft
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');
const left = { escaped: await textsHolding(cell), plain: await textsHolding(PIPE_CLAIM), orphans: (await Promise.all(orphans.map(textExists))).filter(Boolean).length };
- console.log(`[lp-h] ${backend} pipe purge_fact: ${escaped} orphan(s) holding the escaped cell before; after: ${JSON.stringify(left)}`);
expect(left).toEqual({ escaped: 0, plain: 0, orphans: 0 });
const { page: row, body, hash } = await reconstructedPage(engine, slug);
expect(hash).toBe(row.content_hash);
@@ -232,12 +231,27 @@ for (const { backend, databaseUrl } of pathologicalArms()) describe(`a purge aft
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('the purge deletes that text when the withdrawn claim is the 41st claim of the page (past the journal sweep\'s first 32)', async () => withEnv(env(), async () => {
+ const slug = 'notes/lp-h-expired-many';
+ const { claim, cell, sha, staging } = await expiredStagingOrphan(slug, 'notes/lp-h-expired-many-dedupe', 31, 'vault5503', false);
+ // 40 more claims filed on the page, ordered before it (negative ids), held by no segment text: the purge's journal
+ // sweep reads the first 32 claims by id, so the withdrawn claim is past it.
+ const [marked] = await engine.executeRaw<{ id: number }>("SELECT id FROM facts WHERE source_id='default' AND source_markdown_slug=$1", [slug]);
+ await engine.executeRaw(`INSERT INTO facts SELECT (jsonb_populate_record(NULL::facts, to_jsonb(f) || jsonb_build_object('id', -g, 'row_num', null, 'fact', 'Filler claim number ' || g || ' of the page'))).*
+ FROM facts f, generate_series(1, 40) AS g WHERE f.id=$1`, [marked!.id]);
+ expect(Number((await engine.executeRaw<{ n: number }>("SELECT count(*)::int AS n FROM facts WHERE source_id='default' AND source_markdown_slug=$1", [slug]))[0]!.n)).toBe(41);
+ const purge = await op('delete_page', { slug, purge: true, request_id: randomUUID(), expected_revision: await revision(slug) });
+ expect(purge.status).toBe('purged');
+ expect({ escaped: await textsHolding(cell), plain: await textsHolding(claim), text: await textExists(sha) }).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);