Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(large-pages): purged text no longer survives in page_segment_derivations (Wave B PR 4 lane 4a round 2)

garrytane9f9c1f29f00
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 1068b4fc4e..c3da3e0105 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -1056,7 +1056,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;
// PR 4 (Wave B incremental derivation, transcripts)
// PR 4 4a
{ since: 'TBD', text: 'Links, mentions, timeline entries and facts/takes fences of a large (segmented) page are now kept per segment, so a write reads only the segments it changed, and an append reads its new tail instead of the whole page. A rewrite of the whole page does the same work as before. The results are unchanged.' },
- { since: 'TBD', text: 'Forgetting, purging or withdrawing a fact on a large page now also deletes the stored link, mention, timeline and fence results of the segment that held it, in the same transaction. A purge counts them as `page_segment_derivations`.' },
+ { since: 'TBD', text: 'Forgetting, purging or withdrawing a fact on a large page now also deletes the stored link, mention, timeline and fence results of the segment that held it, and of segments an earlier write replaced, in the same transaction. A fact purge also deletes every stored result anywhere in the source that still holds the claim (including a page since stored inline) and counts them as `page_segment_derivations`; stored fence results keep a digest of the fence, never its text. A derivation that read a page before a purge, forget or edit no longer writes its results after it.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/facts/purge.ts b/src/core/facts/purge.ts
index 2506e6f406..1a4796f6f9 100644
--- a/src/core/facts/purge.ts
+++ b/src/core/facts/purge.ts
@@ -27,6 +27,7 @@ import { readFix } from '../ops/op-fix.ts';
import { faultPoint } from '../persistence/fault-points.ts';
import { contentHash, rowToPage } from '../utils.ts';
import { rewriteLiveSegmentedFences, rewriteSegmentedGeneration, segmentedBodyContains } from '../page-body/segment-rewrite.ts';
+import { sweepDerivationText } from '../page-body/segment-derive.ts';
import { discoverWithdrawalTargets, withdrawalDiscoveryFailure } from './withdrawal-discovery.ts';
import { dropPurgedFenceRows } from './purge-overlay.ts';
import { derivedRowsFrom, hideDerivedRows, type DerivationRef } from './derivation-inputs.ts';
@@ -522,6 +523,7 @@ export async function submitPurgeFactMutation(ctx: OperationContext, params: Rec
const facts = (await tx.executeRaw('DELETE FROM facts WHERE id=ANY($1::bigint[]) AND source_id=$2 RETURNING id', [ids, p.sourceId])).length;
const bodies = await rewritePageBodies(tx, p.sourceId, plan.pages);
({ rewritten, unsealed } = bodies);
+ const derivationRows = bodies.derivations + await sweepDerivationText(tx, p.sourceId, [current.fact, escapeFenceCell(current.fact)]);
const pageIds = plan.pages.map(page => page.page_id);
// A segmented page's flip already retired only the chunks of the occurrences it rewrote.
const inline = pageIds.filter(id => !bodies.segmented.includes(id));
@@ -542,7 +544,7 @@ export async function submitPurgeFactMutation(ctx: OperationContext, params: Rec
targets: pages.map(page => ({ slug: page.slug, page_id: Number(page.id), revision: page.knowledge_revision })) })]);
counts = { facts, takes, chunks, page_versions: versions.redacted, pages: rewritten.length, persistence_requests: intents,
query_cache: cache, decide_review: review, open_loops: loops, take_proposals: proposals, core_edit_notices: notices,
- write_gate_holds: holdIds.length, write_gate_receipts: gateReceipts, page_segment_texts: segments.texts, page_segment_derivations: bodies.derivations,
+ write_gate_holds: holdIds.length, write_gate_receipts: gateReceipts, page_segment_texts: segments.texts, page_segment_derivations: derivationRows,
page_body_stagings: segments.stagings, page_body_staging_parts: segments.parts, persistence_requests_cancelled: segments.cancelled,
derived_hidden: Object.values(derived.hidden).reduce((a, b) => a + b, 0) };
derivedHidden = derived;
diff --git a/src/core/page-body/derivations.ts b/src/core/page-body/derivations.ts
index 13384a79ef..f098366ce8 100644
--- a/src/core/page-body/derivations.ts
+++ b/src/core/page-body/derivations.ts
@@ -22,7 +22,14 @@ export type SegmentDerivationKind = typeof SEGMENT_DERIVATION_KINDS[number];
export type SegmentDerivationState = typeof SEGMENT_DERIVATION_STATES[number];
export const SETTLED_DERIVATION_STATES: readonly SegmentDerivationState[] = ['done', 'skipped'];
-/** What a pipeline records for one occurrence. `output` stays bounded per segment (candidates, keys, anchors, never text). */
+/**
+ * What a pipeline records for one occurrence. `output` stays bounded per segment (candidates, keys, digests, anchors).
+ * It is not text-free: a links row keeps the excerpts and dated lines its candidates carry (what links.context and the
+ * temporal pass store), so the store is swept, not probed: a fact purge deletes every row whose output or receipt holds
+ * the claim (segment-derive.ts sweepDerivationText), fence rewrites delete the rows of the runs they touched and of
+ * occurrences no longer live, and demotion to inline deletes the page's rows. Prefer digests and offsets where the
+ * pipeline can read the segment again (a fences row keeps fence digests, never fence text).
+ */
export interface SegmentDerivationInput {
pageId: number;
kind: SegmentDerivationKind;
diff --git a/src/core/page-body/schema.ts b/src/core/page-body/schema.ts
index b374906f3b..5c44f57873 100644
--- a/src/core/page-body/schema.ts
+++ b/src/core/page-body/schema.ts
@@ -181,7 +181,8 @@ const sqlList = (values: readonly string[]) => values.map(v => `'${v}'`).join(',
* the segment text and the context (`context_hash`: entry state plus the page-level inputs the pipeline reads) it was
* derived from, the pipeline version, the outcome and a bounded per-segment output. A pipeline's work on a page is the
* live occurrences without a settled row whose segment sha, context hash and version match, found from metadata alone.
- * Rows of an occurrence that left the live generation are deleted by their pipeline (retireSegmentDerivations); a page
+ * Rows of an occurrence that left the live generation are deleted by their pipeline (retireSegmentDerivations) or by a
+ * fence rewrite; demotion to inline deletes the page's rows, a fact purge every row holding the claim, and a page
* delete cascades. The output holds link context and window anchors, so the table gets the segment tables' RLS posture.
*/
export const PAGE_SEGMENT_DERIVATIONS_SQL = `CREATE TABLE IF NOT EXISTS page_segment_derivations (
diff --git a/src/core/page-body/segment-derive.ts b/src/core/page-body/segment-derive.ts
index 4f3a22a13f..4d57f73657 100644
--- a/src/core/page-body/segment-derive.ts
+++ b/src/core/page-body/segment-derive.ts
@@ -16,23 +16,31 @@
import { createHash } from 'node:crypto';
import type { BrainEngine } from '../engine.ts';
import { canonicalJson } from '../belief/keys.ts';
-import { planSegmentDerivations, segmentDerivationContextHash, type LiveSegment, type SegmentDerivationInput, type SegmentDerivationKind,
+import { planSegmentDerivations, segmentDerivationContextHash, type LiveSegment, type SegmentDerivationKind,
type SegmentDerivationRow } from './derivations.ts';
import { bodyBlocks, type BodyBlock } from './segment-blocks.ts';
import { ledgerApplies, readBodyLedger } from './segment-ledger.ts';
import { SEGMENTER_VERSION } from './segmenter.ts';
import type { BodyRegion, ManifestRow } from './types.ts';
-/** Bump a kind's version to re-derive every page's rows of that kind once. */
-export const SEGMENT_PIPELINE_VERSIONS = { links: 1, mentions: 1, timeline: 1, fences: 1 } as const satisfies Partial<Record<SegmentDerivationKind, number>>;
+/** Bump a kind's version to re-derive every page's rows of that kind once. fences 2: rows keep fence digests, not fence text. */
+export const SEGMENT_PIPELINE_VERSIONS = { links: 1, mentions: 1, timeline: 1, fences: 2 } as const satisfies Partial<Record<SegmentDerivationKind, number>>;
export type UnpaidDerivationKind = keyof typeof SEGMENT_PIPELINE_VERSIONS;
-/** @internal Runs derived (and their occurrences) and runs reused per kind, for the work-volume tests. Counts, not time. */
-export const segmentDeriveWork: Record<UnpaidDerivationKind, { derived: number; occurrences: number; reused: number }> = {
- links: { derived: 0, occurrences: 0, reused: 0 }, mentions: { derived: 0, occurrences: 0, reused: 0 },
- timeline: { derived: 0, occurrences: 0, reused: 0 }, fences: { derived: 0, occurrences: 0, reused: 0 },
+/**
+ * @internal Per kind, for the work-volume tests (counts, not time): runs derived and their occurrences, runs reused,
+ * writes skipped because the page moved before they could commit (`skipped`), and current runs read again for text
+ * their rows do not keep (`reread`).
+ */
+export const segmentDeriveWork: Record<UnpaidDerivationKind, { derived: number; occurrences: number; reused: number; skipped: number; reread: number }> = {
+ links: { derived: 0, occurrences: 0, reused: 0, skipped: 0, reread: 0 }, mentions: { derived: 0, occurrences: 0, reused: 0, skipped: 0, reread: 0 },
+ timeline: { derived: 0, occurrences: 0, reused: 0, skipped: 0, reread: 0 }, fences: { derived: 0, occurrences: 0, reused: 0, skipped: 0, reread: 0 },
};
+let beforeWrite: ((scope: DerivationScope) => Promise<void>) | null = null;
+/** @internal Test seam: runs before each derivation write (a purge forced into the window between the read and the write). */
+export function __setBeforeDerivationWriteForTests(fn: ((scope: DerivationScope) => Promise<void>) | null): void { beforeWrite = fn; }
+
export interface DeriveRun {
index: number;
region: BodyRegion;
@@ -183,22 +191,49 @@ export async function assertScopeCurrent(engine: BrainEngine, scope: DerivationS
*/
export async function commitRuns(engine: BrainEngine, kind: UnpaidDerivationKind, scope: DerivationScope, outputs: ReadonlyMap<number, unknown>,
inputsOf: (run: DeriveRun) => Record<string, unknown>): Promise<void> {
- await storeRuns(engine, kind, scope, outputs, inputsOf);
- await engine.retireSegmentDerivations(scope.pageId, scope.runs.flatMap(run => run.occurrences), { kind });
+ if (await storeRuns(engine, kind, scope, outputs, inputsOf)) await engine.retireSegmentDerivations(scope.pageId, scope.runs.flatMap(run => run.occurrences), { kind });
}
+/** Rows per guarded insert statement. */
+const STORE_BATCH_ROWS = 64;
+
+/**
+ * Store the outputs of derived runs. Each statement inserts only while the page row, read FOR SHARE, is still
+ * segmented at the scope's generation: a purge, a fence rewrite (forget, withdrawal, edit) or a demotion holds that
+ * row FOR UPDATE until it commits and moves the generation, so a statement racing one waits for it and then writes
+ * nothing, and a statement that committed first is in place for that writer's deletes. A single statement, not a
+ * transaction, so a caller's own transaction or connection is never waited on. Returns false, counted in `skipped`,
+ * when the page moved; the caller's result still stands for the generation it read.
+ */
async function storeRuns(engine: BrainEngine, kind: UnpaidDerivationKind, scope: DerivationScope, outputs: ReadonlyMap<number, unknown>,
- inputsOf: (run: DeriveRun) => Record<string, unknown>): Promise<void> {
- const rows: SegmentDerivationInput[] = [];
+ inputsOf: (run: DeriveRun) => Record<string, unknown>): Promise<boolean> {
+ const rows: Array<Record<string, unknown>> = [];
+ let occurrences = 0;
for (const [index, output] of outputs) {
const run = scope.runs[index]!;
const hashes = runContextHashes(kind, scope, run, inputsOf(run));
- segmentDeriveWork[kind].derived++;
- segmentDeriveWork[kind].occurrences += run.occurrences.length;
- run.occurrences.forEach((occurrenceId, i) => rows.push({ pageId: scope.pageId, kind, occurrenceId, version: SEGMENT_PIPELINE_VERSIONS[kind],
- segmentSha256: run.shas[i]!, contextHash: hashes[i]!, state: 'done', output: i === 0 ? output : { run: run.occurrences[0] }, receipt: null }));
+ occurrences += run.occurrences.length;
+ run.occurrences.forEach((occurrenceId, i) => rows.push({ pipeline: kind, occurrence_id: occurrenceId, pipeline_version: SEGMENT_PIPELINE_VERSIONS[kind],
+ segment_sha256: hex(run.shas[i]!), context_hash: hex(hashes[i]!), output: i === 0 ? output : { run: run.occurrences[0] } }));
}
- if (rows.length) await engine.upsertSegmentDerivations(rows);
+ if (!rows.length) return true;
+ await beforeWrite?.(scope);
+ for (let at = 0; at < rows.length; at += STORE_BATCH_ROWS) {
+ const written = await engine.executeRaw(`WITH live AS (SELECT id FROM pages WHERE id=$1 AND body_storage='segmented' AND body_generation=$2 FOR SHARE)
+ INSERT INTO page_segment_derivations (page_id, pipeline, occurrence_id, pipeline_version, segment_sha256, context_hash, state, output, receipt)
+ SELECT live.id, d.pipeline, d.occurrence_id, d.pipeline_version, decode(d.segment_sha256, 'hex'), decode(d.context_hash, 'hex'), 'done', d.output, NULL
+ FROM live, jsonb_to_recordset($3::text::jsonb) AS d(pipeline text, occurrence_id bigint, pipeline_version int, segment_sha256 text, context_hash text, output jsonb)
+ ON CONFLICT (page_id, pipeline, occurrence_id) DO UPDATE SET pipeline_version = EXCLUDED.pipeline_version, segment_sha256 = EXCLUDED.segment_sha256,
+ context_hash = EXCLUDED.context_hash, state = EXCLUDED.state, output = EXCLUDED.output, receipt = EXCLUDED.receipt, updated_at = now()
+ RETURNING 1`, [scope.pageId, scope.generation, JSON.stringify(rows.slice(at, at + STORE_BATCH_ROWS))]);
+ if (!written.length) {
+ segmentDeriveWork[kind].skipped++;
+ return false;
+ }
+ }
+ segmentDeriveWork[kind].derived += outputs.size;
+ segmentDeriveWork[kind].occurrences += occurrences;
+ return true;
}
/** Runs per batch of streamRuns: rows and texts of at most this many runs are held at once. */
@@ -238,11 +273,12 @@ export async function streamRuns<O>(engine: BrainEngine, kind: UnpaidDerivationK
}
};
let deriving: { run: DeriveRun; output: O } | null = null;
+ let moved = false;
const finish = async () => {
if (!deriving) return;
const { run, output } = deriving;
deriving = null;
- await storeRuns(engine, kind, scope, new Map([[run.index, output]]), inputsOf);
+ if (!await storeRuns(engine, kind, scope, new Map([[run.index, output]]), inputsOf)) moved = true;
visit(run, output);
next = run.index + 1;
};
@@ -260,17 +296,19 @@ export async function streamRuns<O>(engine: BrainEngine, kind: UnpaidDerivationK
});
await finish();
await handOver(scope.runs.length);
- await engine.retireSegmentDerivations(scope.pageId, scope.runs.flatMap(run => run.occurrences), { kind });
+ if (!moved) await engine.retireSegmentDerivations(scope.pageId, scope.runs.flatMap(run => run.occurrences), { kind });
}
/** Bytes of neighbouring runs whose link rows a rewrite also drops: a link excerpt reaches 120 units past its block. */
const LINK_REACH_BYTES = 4096;
/**
- * Delete the derivation rows that may hold text a fence rewrite (forget, purge; spec 11) replaced, in the caller's
- * transaction: every kind's rows of each run holding a rewritten row (a run's output sits on its first occurrence),
- * and the links rows of the runs on either side up to LINK_REACH_BYTES away, whose candidate excerpts can reach into
- * it. `rows` is the generation's manifest in order; `spans` the rewritten index ranges. Returns the rows deleted.
+ * Delete the derivation rows that may hold text a fence rewrite (forget, purge, withdrawal; spec 11) replaced, in the
+ * caller's transaction: every kind's rows of each run holding a rewritten row (a run's output sits on its first
+ * occurrence), the links rows of the runs on either side up to LINK_REACH_BYTES away, whose candidate excerpts can
+ * reach into it, and every unpaid kind's rows of occurrences that had already left the live body (a pipeline retires
+ * them only when it next runs, so they can still hold the text). `rows` is the generation's manifest in order;
+ * `spans` the rewritten index ranges. Returns the rows deleted.
*/
export async function deleteRewrittenDerivations(engine: BrainEngine, pageId: number,
rows: ReadonlyArray<Pick<ManifestRow, 'occurrenceId' | 'region' | 'cutKind' | 'byteLen'>>, spans: ReadonlyArray<{ from: number; to: number }>): Promise<number> {
@@ -301,7 +339,23 @@ export async function deleteRewrittenDerivations(engine: BrainEngine, pageId: nu
}
if (!touched.size) return 0;
return (await engine.executeRaw(`DELETE FROM page_segment_derivations WHERE page_id=$1
- AND (occurrence_id = ANY($2::bigint[]) OR (pipeline = 'links' AND occurrence_id = ANY($3::bigint[]))) RETURNING 1`, [pageId, [...touched], [...reach]])).length;
+ AND (occurrence_id = ANY($2::bigint[]) OR (pipeline = 'links' AND occurrence_id = ANY($3::bigint[]))
+ OR (pipeline = ANY($4::text[]) AND NOT (occurrence_id = ANY($5::bigint[])))) RETURNING 1`,
+ [pageId, [...touched], [...reach], Object.keys(SEGMENT_PIPELINE_VERSIONS), rows.map(row => row.occurrenceId)])).length;
+}
+
+/**
+ * Delete every derivation row of a source's pages (live, soft-deleted or demoted; any occurrence, any kind) whose
+ * output or receipt holds one of `needles`, matched as the purge receipt probes the store: case-insensitive, raw and
+ * JSON-escaped. A fact purge runs it in its transaction after the body rewrites, so a row a rewrite could not place
+ * (an occurrence retired before it, a page demoted to inline) goes too. Returns the rows deleted.
+ */
+export async function sweepDerivationText(engine: Pick<BrainEngine, 'executeRaw'>, sourceId: string, needles: readonly string[]): Promise<number> {
+ const list = [...new Set(needles.filter(Boolean).flatMap(n => [n.toLowerCase(), JSON.stringify(n).slice(1, -1).toLowerCase()]))];
+ if (!list.length) return 0;
+ return (await engine.executeRaw(`DELETE FROM page_segment_derivations d USING pages p WHERE p.id=d.page_id AND p.source_id=$1
+ AND EXISTS (SELECT 1 FROM unnest($2::text[]) n WHERE strpos(lower(COALESCE(d.output::text,'')),n)>0 OR strpos(lower(COALESCE(d.receipt::text,'')),n)>0)
+ RETURNING 1`, [sourceId, list])).length;
}
/** SHA-256 hex (its first 32 digits) of a key, recorded in an output instead of the key's text. */
diff --git a/src/core/page-body/segment-facts.ts b/src/core/page-body/segment-facts.ts
index 26c6506da5..e45f132650 100644
--- a/src/core/page-body/segment-facts.ts
+++ b/src/core/page-body/segment-facts.ts
@@ -38,7 +38,7 @@ import {
FACTS_FENCE_BEGIN, FACTS_FENCE_END, parseFactsFence, timelineHasGenuineFactsFenceMarker, type FactsFenceParseResult, type FactsFenceView,
} from '../facts-fence.ts';
import { TAKES_FENCE_BEGIN } from '../takes-fence.ts';
-import { commitRuns, derivationScope, planRuns, readRuns, SegmentDerivationRaced, type DerivationScope, type DeriveRun } from './segment-derive.ts';
+import { commitRuns, derivationScope, keyDigest, planRuns, readRuns, SegmentDerivationRaced, segmentDeriveWork, type DerivationScope, type DeriveRun } from './segment-derive.ts';
import { TakesFenceScan, type TakesRunSummary } from './segment-takes.ts';
import { BodyScanner } from './body-scan.ts';
import { readBodyRange } from './read-range.ts';
@@ -113,7 +113,8 @@ export class FactsFenceScan {
/** What the blocks pushed so far hold, for a run's fences row. */
summary(): FactsRunSummary {
- return { marker: this.marker, endOnly: this.endOnly, fence: this.fence ? { text: this.fence.join(''), closed: this.parsedText !== null } : null };
+ const text = this.fence?.join('');
+ return { marker: this.marker, endOnly: this.endOnly, fence: text === undefined ? null : { sha: keyDigest(text), closed: this.parsedText !== null, text } };
}
}
@@ -141,12 +142,19 @@ export async function segmentedFactsFenceView(engine: BrainEngine, page: { id?:
return { body: truth.parsed, timeline: timeline.parsed, sections: { body: truth.holds, timeline: timeline.holds }, timelineMarker: timeline.marker };
}
-/** One run's FactsFenceScan state (a scan started fresh at the run): the timeline marker, the end-only scan before any begin, and its first fence. */
-export interface FactsRunSummary { marker: boolean; endOnly: boolean; fence: { text: string; closed: boolean } | null }
+/**
+ * One run's FactsFenceScan state (a scan started fresh at the run): the timeline marker, the end-only scan before any
+ * begin, and its first fence: its digest and whether it closed. Its `text` is held in memory only (a run just scanned,
+ * or read again for it) and never stored on the fences row.
+ */
+export interface FactsRunSummary { marker: boolean; endOnly: boolean; fence: { sha: string; closed: boolean; text?: string } | null }
-/** What a run's fences row holds (spec 8.2 facts / takes fences): the facts and takes scans of its blocks. */
+/** What a run's fences row holds (spec 8.2 facts / takes fences): the facts and takes scans of its blocks, fence texts left out. */
export interface FenceRunOutput { facts: FactsRunSummary; takes: TakesRunSummary }
+const withoutText = <F extends { fence: { sha: string; closed: boolean; text?: string } | null }>(summary: F): F =>
+ ({ ...summary, fence: summary.fence && { sha: summary.fence.sha, closed: summary.fence.closed } });
+
/**
* Each run of a segmented page with its fences row output, in page order (spec 8.2 facts / takes fences): runs whose
* rows match their text are reused, the others are read block by block and stored. Null when the page is not
@@ -160,30 +168,62 @@ export async function segmentedFenceRuns(engine: BrainEngine, page: FencePage):
return fences.finish();
}
+type FenceScans = Map<number, { facts: FactsFenceScan; takes: TakesFenceScan; at: number; seen: boolean }>;
+const fenceScans = (page: FencePage, runs: readonly DeriveRun[]): FenceScans =>
+ new Map(runs.map(run => [run.index, { facts: new FactsFenceScan(page, run.region), takes: new TakesFenceScan(page), at: 0, seen: false }]));
+const scanOf = (scans: FenceScans) => [...scans].map(([index, scan]) => [index, { facts: scan.facts.summary(), takes: scan.takes.summary() }] as const);
+
+/** Feed one block of a run to that run's scans, in order. */
+const feed = (scans: FenceScans) => (run: DeriveRun | null, block: BodyBlock) => {
+ const scan = run && scans.get(run.index);
+ if (!scan) return;
+ scan.seen = true;
+ scan.facts.push(block.text, run.first && scan.at === 0);
+ scan.takes.push({ text: block.text, at: run.first ? scan.at : Number.MAX_SAFE_INTEGER });
+ scan.at += block.text.length;
+};
+
/**
* The fences rows of a scope, for a caller that reads some runs for another kind: `push` the blocks it reads (a due
- * run seen whole is scanned there), then `finish` reads only the due runs still unscanned and stores every scan.
+ * run seen whole is scanned there), then `finish` reads only the due runs still unscanned and stores every scan. A
+ * row keeps a fence's digest, not its text (spec 11): the run holding each region's first closed facts or takes fence
+ * is read again for it when its row is current, and a text whose digest moved throws SegmentDerivationRaced.
*/
export async function openFenceRuns(engine: BrainEngine, page: FencePage, scope: DerivationScope) {
const inputs = () => ({ facts: FACTS_FENCE_BEGIN, takes: TAKES_FENCE_BEGIN });
const plan = await planRuns<FenceRunOutput>(engine, 'fences', scope, inputs);
- const scans = new Map(plan.todo.map(run => [run.index, { facts: new FactsFenceScan(page, run.region), takes: new TakesFenceScan(page), at: 0, seen: false }]));
- const push = (run: DeriveRun | null, block: BodyBlock) => {
- const scan = run && scans.get(run.index);
- if (!scan) return;
- scan.seen = true;
- scan.facts.push(block.text, run.first && scan.at === 0);
- scan.takes.push({ text: block.text, at: run.first ? scan.at : Number.MAX_SAFE_INTEGER });
- scan.at += block.text.length;
- };
+ const scans = fenceScans(page, plan.todo);
+ const push = feed(scans);
return {
/** Feed one block a caller read whole with its run's other blocks, in order. */
push,
async finish(): Promise<Array<{ run: DeriveRun; output: FenceRunOutput }>> {
await readRuns(engine, scope, new Set([...scans].filter(([, scan]) => !scan.seen).map(([index]) => index)), push);
- const outputs = new Map([...scans].map(([index, scan]) => [index, { facts: scan.facts.summary(), takes: scan.takes.summary() }]));
- await commitRuns(engine, 'fences', scope, outputs, inputs);
- return scope.runs.map(run => ({ run, output: outputs.get(run.index) ?? plan.current.get(run.index)! }));
+ const outputs = new Map<number, FenceRunOutput>(scanOf(scans));
+ await commitRuns(engine, 'fences', scope, new Map([...outputs].map(([index, o]) => [index, { facts: withoutText(o.facts), takes: withoutText(o.takes) }])), inputs);
+ const runs = scope.runs.map(run => ({ run, output: outputs.get(run.index) ?? plan.current.get(run.index)! }));
+ const holders = new Set<number>();
+ const unread = (fence: FactsRunSummary['fence']) => !!fence?.closed && fence.text === undefined;
+ for (const region of ['truth', 'timeline'] as const) {
+ const own = runs.filter(({ run }) => run.region === region);
+ const facts = own.find(({ output }) => output.facts.fence), takes = own.find(({ output }) => output.takes.fence);
+ if (facts && unread(facts.output.facts.fence)) holders.add(facts.run.index);
+ if (takes && unread(takes.output.takes.fence)) holders.add(takes.run.index);
+ }
+ if (!holders.size) return runs;
+ const again = fenceScans(page, scope.runs.filter(run => holders.has(run.index)));
+ await readRuns(engine, scope, holders, feed(again));
+ segmentDeriveWork.fences.reread += holders.size;
+ const text = <F extends FactsRunSummary | TakesRunSummary>(stored: F, read: F): F => {
+ if (!stored.fence || stored.fence.text !== undefined) return stored;
+ if (read.fence?.sha !== stored.fence.sha) throw new SegmentDerivationRaced(page.slug);
+ return { ...stored, fence: { ...stored.fence, text: read.fence.text } };
+ };
+ for (const [index, read] of scanOf(again)) {
+ const at = runs[index]!;
+ at.output = { facts: text(at.output.facts, read.facts), takes: text(at.output.takes, read.takes) };
+ }
+ return runs;
},
};
}
@@ -195,7 +235,7 @@ export function factsFromRuns(summaries: readonly FactsRunSummary[]): RegionFenc
marker ||= summary.marker;
if (parsedText !== null) continue;
if (summary.fence) {
- if (!summary.fence.closed) return null;
+ if (!summary.fence.closed || summary.fence.text === undefined) return null;
parsedText = summary.fence.text;
} else endOnly ||= summary.endOnly;
}
diff --git a/src/core/page-body/segment-takes.ts b/src/core/page-body/segment-takes.ts
index 2bc750a711..71d1b2f930 100644
--- a/src/core/page-body/segment-takes.ts
+++ b/src/core/page-body/segment-takes.ts
@@ -12,6 +12,7 @@
import { indexOfOutsideCode } from '../fence-scan.ts';
import { parseTakesFence, TAKES_FENCE_BEGIN, TAKES_FENCE_END, type ParseResult } from '../takes-fence.ts';
import { BLOCK_MAX_BYTES, blockTooLargeError, segmentedPassWork, type BodyBlock } from './segment-blocks.ts';
+import { keyDigest } from './segment-derive.ts';
export interface StreamedTakes {
parsed: ParseResult;
@@ -73,8 +74,9 @@ export class TakesFenceScan {
/** What the blocks pushed so far hold, for a run's fences row (segment-facts.ts segmentedFenceRuns). */
summary(): TakesRunSummary {
+ const text = this.fence?.join('');
return { hasBegin: this.hasBegin, hasMarker: this.hasMarker, endOnly: this.endOnly, nearMiss: this.nearMiss,
- fence: this.fence ? { text: this.fence.join(''), closed: this.done !== null } : null };
+ fence: text === undefined ? null : { sha: keyDigest(text), closed: this.done !== null, text } };
}
}
@@ -85,20 +87,22 @@ function reducedTakes(begun: boolean, endOnly: boolean, nearMiss: boolean): stri
/**
* One run's TakesFenceScan state (a scan started fresh at the run, its blocks pushed with region offsets): the raw marker
- * flags up to the block that closed its first fence, the end-only and near-miss scans before any begin, and that fence.
+ * flags up to the block that closed its first fence, the end-only and near-miss scans before any begin, and that fence:
+ * its digest and whether it closed. Its `text` is held in memory only (a run just scanned, or read again for it) and
+ * never stored on the fences row.
*/
-export interface TakesRunSummary { hasBegin: boolean; hasMarker: boolean; endOnly: boolean; nearMiss: boolean; fence: { text: string; closed: boolean } | null }
+export interface TakesRunSummary { hasBegin: boolean; hasMarker: boolean; endOnly: boolean; nearMiss: boolean; fence: { sha: string; closed: boolean; text?: string } | null }
/**
* parseTakesFenceBlocks of a region from its runs' summaries, in order; null when a fence a run begins does not close
- * in that run (the caller reads the region whole).
+ * in that run, or its text was not read (the caller reads the region whole).
*/
export function takesFromRuns(summaries: readonly TakesRunSummary[]): StreamedTakes | null {
let hasBegin = false, hasMarker = false, endOnly = false, nearMiss = false;
for (const summary of summaries) {
hasBegin ||= summary.hasBegin;
hasMarker ||= summary.hasMarker;
- if (summary.fence) return summary.fence.closed ? { parsed: parseTakesFence(summary.fence.text), hasBegin, hasMarker } : null;
+ if (summary.fence) return summary.fence.closed && summary.fence.text !== undefined ? { parsed: parseTakesFence(summary.fence.text), hasBegin, hasMarker } : null;
endOnly ||= summary.endOnly;
nearMiss ||= summary.nearMiss;
}
diff --git a/src/core/persistence/effect-journal.ts b/src/core/persistence/effect-journal.ts
index 7877f9542c..fcd955bd74 100644
--- a/src/core/persistence/effect-journal.ts
+++ b/src/core/persistence/effect-journal.ts
@@ -54,13 +54,7 @@ export async function queuePublicationEffects(tx: BrainEngine, row: EffectReques
else queue('facts-backstop', { visibility: await resolveDefaultVisibility(tx) });
}
// The links effect is inserted with the others, gated in SQL on auto_link and mcp.remote_auto_links.
- // Wave B (spec 8.5): on a segmented page it carries the occurrences this write added (live rows with no older row).
- if (queuesMentionLinks(row, prepared)) {
- const added = await tx.executeRaw<{ id: string }>(`SELECT m.occurrence_id::text AS id FROM page_body_manifest m JOIN pages p ON p.id=m.page_id
- WHERE m.page_id=$1 AND p.body_storage='segmented' AND m.gen_from=p.body_generation AND m.gen_to IS NULL AND m.staging_id IS NULL
- AND NOT EXISTS (SELECT 1 FROM page_body_manifest o WHERE o.page_id=m.page_id AND o.occurrence_id=m.occurrence_id AND o.gen_from<m.gen_from) ORDER BY m.seq`, [snapshot.page.id]);
- queued.push({ kind: 'links', data: { ...data, ...(prepared?.mentionRange ? { range: prepared.mentionRange } : {}), ...(added.length ? { occurrence_ids: added.map(r => Number(r.id)) } : {}) }, gated: true });
- }
+ if (queuesMentionLinks(row, prepared)) queued.push({ kind: 'links', data: { ...data, ...(prepared?.mentionRange ? { range: prepared.mentionRange } : {}) }, gated: true });
// #5876: the Life Chronicle decision is a ledger row, not an effect; the `chronicle` cycle phase executes it.
await recordChronicleDecision(tx, row, snapshot, outcome);
}
diff --git a/src/core/persistence/segmented-apply.ts b/src/core/persistence/segmented-apply.ts
index c18ba4a4e4..23fe0bdf1e 100644
--- a/src/core/persistence/segmented-apply.ts
+++ b/src/core/persistence/segmented-apply.ts
@@ -201,8 +201,9 @@ export async function applySegmentedBody(tx: BrainEngine, input: SegmentedApplyI
* Demotion: turn a segmented page row into an inline row with an empty body
* (the caller's inline write fills it in the same transaction). The live
* manifest rows close at the next generation, so versions that pin earlier
- * generations keep theirs; the page's segmented chunk rows are deleted here,
- * before the inline write stages its chunks. The write holds the page row FOR
+ * generations keep theirs; the page's segmented chunk rows and every
+ * page_segment_derivations row (outputs of segments no body holds any more)
+ * are deleted here, before the inline write stages its chunks. The write holds the page row FOR
* UPDATE (lockPageKeys), so a chunk batch in flight (FOR KEY SHARE) commits
* before this delete, and a later batch of a racing preparation refuses
* (stageSegmentChunks: an inline page at the generation it targets).
@@ -214,6 +215,7 @@ export async function demoteSegmentedPage(tx: Pick<BrainEngine, 'executeRaw'>, p
body_bytes=NULL, truth_bytes=NULL, body_lines=NULL, segment_count=NULL, segmenter_version=NULL, body_flags=NULL,
body_generation=body_generation+1 WHERE id=$1 AND body_storage='segmented'`, [pageId]);
await tx.executeRaw('DELETE FROM content_chunks WHERE page_id=$1 AND occurrence_id IS NOT NULL', [pageId]);
+ await tx.executeRaw('DELETE FROM page_segment_derivations WHERE page_id=$1', [pageId]);
}
/** Abort a staging whose write will not publish (best effort: expiry collects it anyway). */
diff --git a/test/e2e/derivation-purge-postgres.test.ts b/test/e2e/derivation-purge-postgres.test.ts
new file mode 100644
index 0000000000..71e0f5a2fe
--- /dev/null
+++ b/test/e2e/derivation-purge-postgres.test.ts
@@ -0,0 +1,11 @@
+/**
+ * Wave B PR 4 lane 4a round 2 (spec 11), Postgres arm: a fact purge leaves no page_segment_derivations row holding the
+ * claim, for a row of a retired occurrence, a derivation racing the purge and a page demoted to inline. Cases in
+ * test/helpers/derivation-purge-cases.ts; PGLite arm: test/large-pages/derivation-purge.test.ts.
+ */
+import { describe, test } from 'bun:test';
+import { registerDerivationPurgeCases } from '../helpers/derivation-purge-cases.ts';
+import { hasDatabase } from './helpers.ts';
+
+if (hasDatabase()) registerDerivationPurgeCases('postgres');
+else describe.skip('purge leaves no derivation row holding the claim (postgres)', () => { test('needs DATABASE_URL', () => {}); });
diff --git a/test/helpers/derivation-equivalence-cases.ts b/test/helpers/derivation-equivalence-cases.ts
index ed8f73a564..8e2987bf5f 100644
--- a/test/helpers/derivation-equivalence-cases.ts
+++ b/test/helpers/derivation-equivalence-cases.ts
@@ -11,7 +11,7 @@
import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { randomUUID } from 'node:crypto';
import type { BrainEngine } from '../../src/core/engine.ts';
-import { makeResolver, type ExtractPageLinksOptions } from '../../src/core/link-extraction.ts';
+import { extractPageLinks, makeResolver, type ExtractPageLinksOptions } from '../../src/core/link-extraction.ts';
import { loadActivePackForLocalEngine } from '../../src/core/schema-pack/best-effort.ts';
import { extractSegmentedPageLinks, openSegmentedLinkSession, segmentedRoleText } from '../../src/core/page-body/segment-links.ts';
import { segmentDeriveWork, SEGMENT_PIPELINE_VERSIONS, type UnpaidDerivationKind } from '../../src/core/page-body/segment-derive.ts';
@@ -107,6 +107,13 @@ export async function incrementalLinks(engine: BrainEngine, page: EquivalencePag
return session!.finish({ ...opts, temporal: true, targetType } as never);
}
+/** extractPageLinks over the joined body (`${compiled_truth}\n${timeline}`), as an inline page of the same text is extracted. */
+export async function inlineLinks(engine: BrainEngine, page: EquivalencePage, body: { truth: string; timeline: string }) {
+ const resolver = makeResolver(engine, { mode: 'live', sourceId: SOURCE });
+ const { opts, targetType } = await linkOptions(engine);
+ return extractPageLinks(page.slug, `${body.truth}\n${body.timeline}`, page.frontmatter, page.type, resolver, { ...opts, targetType });
+}
+
export async function fullLinks(engine: BrainEngine, page: EquivalencePage) {
const resolver = makeResolver(engine, { mode: 'live', sourceId: SOURCE });
const { opts, targetType } = await linkOptions(engine);
@@ -198,7 +205,7 @@ export async function liveOccurrences(engine: BrainEngine, pageId: number): Prom
}
export function resetDeriveWork(): void {
- for (const work of Object.values(segmentDeriveWork)) Object.assign(work, { derived: 0, occurrences: 0, reused: 0 });
+ for (const work of Object.values(segmentDeriveWork)) Object.assign(work, { derived: 0, occurrences: 0, reused: 0, skipped: 0, reread: 0 });
}
const revision = async (brain: AppendBrain) => (await brain.engine.executeRaw<{ r: string }>(
@@ -264,6 +271,8 @@ export function registerDerivationEquivalenceCases(kind: 'pglite' | 'postgres'):
const current = await storedPage(brain.engine);
const links = { incremental: await incrementalLinks(brain.engine, current), full: await fullLinks(brain.engine, current) };
expect({ label, links: links.incremental.candidates }).toEqual({ label, links: links.full.candidates });
+ const inline = await inlineLinks(brain.engine, current, await brain.body(EQUIVALENCE_SLUG));
+ expect({ label, inline: links.incremental.candidates }).toEqual({ label, inline: inline.candidates });
expect({ label, temporal: links.incremental.temporalBody }).toEqual({ label, temporal: links.full.temporalBody! });
expect({ label, attendance: links.incremental.attendanceComplete }).toEqual({ label, attendance: links.full.attendanceComplete });
expect({ label, mentions: await incrementalMentions(brain.engine, current) }).toEqual({ label, mentions: await fullMentions(brain.engine, current) });
@@ -340,21 +349,6 @@ export function registerDerivationEquivalenceCases(kind: 'pglite' | 'postgres'):
await derivationRowsMatch(brain.engine, current, KINDS);
}, 600_000);
- test('a remote edit queues a links effect carrying the occurrences the edit added (spec 8.5)', async () => {
- const page = await storedPage(brain.engine);
- const before = await liveOccurrences(brain.engine, page.id);
- const old = /Marker 3(?: \(edit \d+\))?: /.exec((await brain.body(EQUIVALENCE_SLUG)).truth)![0];
- const res = await brain.call('edit_page', { slug: EQUIVALENCE_SLUG, expected_revision: await revision(brain),
- edits: [{ old_text: old, new_text: 'Marker 3 (remote edit): see [[companies/c3-example]] and ' }] }, { remote: true });
- expect(res).toMatchObject({ isError: false });
- const added = [...await liveOccurrences(brain.engine, page.id)].filter(id => !before.has(id)).sort((a, b) => a - b);
- expect(added.length).toBeGreaterThan(0);
- const effects = await brain.engine.executeRaw<{ data: { occurrence_ids?: number[]; slug?: string } }>(
- "SELECT e.data FROM persistence_effects e JOIN persistence_requests r ON r.id=e.request_id WHERE e.kind='links' AND r.operation='edit_page' AND e.data->>'slug'=$1",
- [EQUIVALENCE_SLUG]);
- expect(effects.length).toBe(1);
- expect([...(effects[0]!.data.occurrence_ids ?? [])].sort((a, b) => a - b)).toEqual(added);
- }, 600_000);
});
}
diff --git a/test/helpers/derivation-purge-cases.ts b/test/helpers/derivation-purge-cases.ts
new file mode 100644
index 0000000000..dbd36ec7d6
--- /dev/null
+++ b/test/helpers/derivation-purge-cases.ts
@@ -0,0 +1,156 @@
+/**
+ * Shared cases for purge, forget and demotion against page_segment_derivations (Wave B PR 4 lane 4a, round 2; spec 11):
+ * after a fact purge no derivation row may hold the purged claim and the purge receipt reports the store complete,
+ * whether the row belongs to an occurrence an append retired before the purge, to a derivation that read the page
+ * before the purge and tried to write after it, or to a segmented body the page was demoted from. A fences row keeps
+ * fence digests, never the fence text, and a forget deletes the unpaid rows of occurrences no longer live.
+ *
+ * test/large-pages/derivation-purge.test.ts runs them on PGLite; test/e2e/derivation-purge-postgres.test.ts on PostgreSQL.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import type { BrainEngine } from '../../src/core/engine.ts';
+import { runExtractFacts } from '../../src/core/cycle/extract-facts.ts';
+import { __setBeforeDerivationWriteForTests, segmentDeriveWork } from '../../src/core/page-body/segment-derive.ts';
+import { incrementalFactsFenceView, segmentedFactsFenceView } from '../../src/core/page-body/segment-facts.ts';
+import { forgetFactInFence } from '../../src/core/facts/forget.ts';
+import { deriveAll, KINDS, liveOccurrences, resetDeriveWork, storedPage } from './derivation-equivalence-cases.ts';
+import { conversationBody } from './conversation-page.ts';
+import { openAppendBrain, type AppendBrain } from './append-brain.ts';
+
+const SOURCE = 'default';
+const prose = (bytes: number, seed: number) => conversationBody(bytes, { seed }).replace(/^## Day \\d+$/gm, 'Next day.');
+
+/** A segmented page whose truth ends with a facts fence: `claim` in a row that also links a person, then a short timeline. */
+function purgePage(claim: string): string {
+ return ['---\ntype: person\ntitle: Purge Example\n---\n\nIntro: met [[people/alice-example]].\n\n', prose(1_300_000, 41), '\n\n## Facts\n\n',
+ '<!--- gbrain:facts:begin -->\n',
+ '| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |\n',
+ '|---|---|---|---|---|---|---|---|---|---|\n',
+ `| 1 | ${claim} | fact | 0.9 | world | low | 2026-03-01 | | [[people/alice-example]] | |\n`,
+ '| 2 | prefers email | preference | 0.8 | world | low | 2026-02-01 | | user | |\n',
+ '<!--- gbrain:facts:end -->\n\n<!-- timeline -->\n\n- **2026-04-02** | Met [[people/alice-example]]\n'].join('');
+}
+
+/** Derivation rows of a page whose output or receipt holds `claim` (as the purge receipt probes the store). */
+async function holders(engine: BrainEngine, pageId: number, claim: string): Promise<Array<{ pipeline: string; occurrence_id: number }>> {
+ return (await engine.executeRaw<{ pipeline: string; occurrence_id: string }>(`SELECT pipeline, occurrence_id::text AS occurrence_id FROM page_segment_derivations
+ WHERE page_id=$1 AND (strpos(lower(COALESCE(output::text,'')),$2)>0 OR strpos(lower(COALESCE(receipt::text,'')),$2)>0) ORDER BY pipeline, occurrence_id`,
+ [pageId, claim.toLowerCase()])).map(row => ({ pipeline: row.pipeline, occurrence_id: Number(row.occurrence_id) }));
+}
+
+export function registerDerivationPurgeCases(kind: 'pglite' | 'postgres'): void {
+ describe(`purge leaves no derivation row holding the claim (${kind})`, () => {
+ let brain: AppendBrain;
+ beforeAll(async () => {
+ brain = await openAppendBrain(kind);
+ await brain.engine.putPage('people/alice-example', { type: 'person', title: 'Alice Example', compiled_truth: 'Alice Example fixture.', timeline: '', frontmatter: {} }, { sourceId: SOURCE });
+ }, 600_000);
+ afterAll(() => brain.close(), 120_000);
+
+ const seed = async (slug: string, claim: string) => {
+ await brain.seed(slug, purgePage(claim));
+ await runExtractFacts(brain.engine, { slugs: [slug] });
+ const [fact] = await brain.engine.executeRaw<{ id: number }>(
+ 'SELECT id FROM facts WHERE source_id=$1 AND source_markdown_slug=$2 AND fact=$3 AND expired_at IS NULL', [SOURCE, slug, claim]);
+ expect(fact).toBeDefined();
+ return Number(fact!.id);
+ };
+
+ const purge = async (id: number) => {
+ const dry = await brain.call('purge_fact', { id, dry_run: true });
+ expect(dry.body.confirm_token).toBeString();
+ const done = await brain.call('purge_fact', { id, confirm: dry.body.confirm_token, expected_revision: dry.body.expected_revision });
+ expect(done.body.state).toBe('committed');
+ return done.body as Record<string, any>;
+ };
+
+ /** The receipt's page_segment_derivations report, and that no store is left incomplete. */
+ const complete = (receipt: Record<string, any>) => {
+ const stores = receipt.stores as Array<{ store: string; status: string }>;
+ expect(stores.filter(s => s.status === 'incomplete')).toEqual([]);
+ const store = stores.find(s => s.store === 'page_segment_derivations');
+ expect(store && ['deleted', 'not_present'].includes(store.status)).toBe(true);
+ };
+
+ test('a purge after an append retired the occurrence holding the claim deletes its rows', async () => {
+ const slug = 'notes/purge-retired', claim = 'Purge Example door code is 5528';
+ const id = await seed(slug, claim);
+ const page = await storedPage(brain.engine, slug);
+ await deriveAll(brain.engine, page);
+ const held = await holders(brain.engine, page.id, claim);
+ expect(held.length).toBeGreaterThan(0);
+ const res = await brain.call('append_page', { slug, text: 'Appended note: nothing about the claim.\n', region: 'truth', request_id: randomUUID() });
+ expect(res).toMatchObject({ isError: false });
+ const live = await liveOccurrences(brain.engine, page.id);
+ expect(held.filter(row => !live.has(row.occurrence_id)).length).toBeGreaterThan(0);
+ complete(await purge(id));
+ expect(await holders(brain.engine, page.id, claim)).toEqual([]);
+ }, 600_000);
+
+ test('a derivation that read the page before a purge does not write its rows after it', async () => {
+ const slug = 'notes/purge-race', claim = 'Purge Example badge number is 7731';
+ const id = await seed(slug, claim);
+ const page = await storedPage(brain.engine, slug);
+ let receipt: Record<string, any> | null = null;
+ __setBeforeDerivationWriteForTests(async () => {
+ if (receipt) return;
+ receipt = {};
+ receipt = await purge(id);
+ });
+ resetDeriveWork();
+ try { await deriveAll(brain.engine, page); } finally { __setBeforeDerivationWriteForTests(null); }
+ expect(receipt).not.toBeNull();
+ expect(await holders(brain.engine, page.id, claim)).toEqual([]);
+ complete(receipt!);
+ expect(KINDS.reduce((n, k) => n + segmentDeriveWork[k].skipped, 0)).toBeGreaterThan(0);
+ }, 600_000);
+
+ test('a fences row keeps the fence digest, not its text; a current fence run is read again for it', async () => {
+ const slug = 'notes/fence-digest', claim = 'Purge Example vault code is 9902';
+ await seed(slug, claim);
+ const page = await storedPage(brain.engine, slug);
+ await deriveAll(brain.engine, page);
+ const fences = await brain.engine.readSegmentDerivations(page.id, { kind: 'fences' });
+ expect(fences.length).toBeGreaterThan(0);
+ expect(fences.filter(row => JSON.stringify(row.output).includes('gbrain:facts:begin') || JSON.stringify(row.output).toLowerCase().includes(claim.toLowerCase()))).toEqual([]);
+ resetDeriveWork();
+ const view = await incrementalFactsFenceView(brain.engine, page);
+ expect(view).toEqual(await segmentedFactsFenceView(brain.engine, page));
+ expect(view.body.facts.map(f => f.claim)).toContain(claim);
+ expect({ derived: segmentDeriveWork.fences.derived, reread: segmentDeriveWork.fences.reread }).toEqual({ derived: 0, reread: 1 });
+ }, 600_000);
+
+ test('a forget after an append retired an occurrence deletes the unpaid rows of every occurrence no longer live', async () => {
+ const slug = 'notes/forget-retired', claim = 'Purge Example gate code is 3318';
+ const id = await seed(slug, claim);
+ const page = await storedPage(brain.engine, slug);
+ await deriveAll(brain.engine, page);
+ const res = await brain.call('append_page', { slug, text: 'Appended note: nothing about the claim.\n', region: 'truth', request_id: randomUUID() });
+ expect(res).toMatchObject({ isError: false });
+ const retired = async () => {
+ const live = await liveOccurrences(brain.engine, page.id);
+ return (await brain.engine.readSegmentDerivations(page.id)).filter(row => KINDS.includes(row.kind as never) && !live.has(row.occurrenceId)).length;
+ };
+ expect(await retired()).toBeGreaterThan(0);
+ expect((await forgetFactInFence(brain.engine, id, { sourceId: SOURCE })).ok).toBe(true);
+ expect(await retired()).toBe(0);
+ }, 600_000);
+
+ test('a purge after the page was demoted to inline leaves no row of its segmented body', async () => {
+ const slug = 'notes/purge-demoted', claim = 'Purge Example locker is 4410';
+ const id = await seed(slug, claim);
+ const page = await storedPage(brain.engine, slug);
+ await deriveAll(brain.engine, page);
+ expect((await holders(brain.engine, page.id, claim)).length).toBeGreaterThan(0);
+ const [row] = await brain.engine.executeRaw<{ r: string }>('SELECT knowledge_revision::text AS r FROM pages WHERE id=$1', [page.id]);
+ const small = purgePage(claim).replace(prose(1_300_000, 41), 'Short body now.');
+ const res = await brain.call('put_page', { slug, content: small, expected_revision: row!.r, request_id: randomUUID() });
+ expect(res).toMatchObject({ isError: false });
+ const [after] = await brain.engine.executeRaw<{ body_storage: string }>('SELECT body_storage FROM pages WHERE id=$1', [page.id]);
+ expect(after!.body_storage).toBe('inline');
+ complete(await purge(id));
+ expect(await holders(brain.engine, page.id, claim)).toEqual([]);
+ }, 600_000);
+ });
+}
diff --git a/test/large-pages/derivation-purge.test.ts b/test/large-pages/derivation-purge.test.ts
new file mode 100644
index 0000000000..c97fbad3ee
--- /dev/null
+++ b/test/large-pages/derivation-purge.test.ts
@@ -0,0 +1,8 @@
+/**
+ * Wave B PR 4 lane 4a round 2 (spec 11): a fact purge leaves no page_segment_derivations row holding the claim, for a
+ * row of a retired occurrence, a derivation racing the purge and a page demoted to inline (PGLite arm; the PostgreSQL
+ * arm is test/e2e/derivation-purge-postgres.test.ts). Cases in test/helpers/derivation-purge-cases.ts.
+ */
+import { registerDerivationPurgeCases } from '../helpers/derivation-purge-cases.ts';
+
+registerDerivationPurgeCases('pglite');