Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Lane H (PR2 fix): retained generations through the block cutter, sweep deferral in SQL, streamed timeline compare, facts view skips line-boundary forced cuts
garrytan9b11b9e31f15
diff --git a/scripts/page-body-readers-baseline.tsv b/scripts/page-body-readers-baseline.tsvindex e402d25c9f..107c8da3ea 100644--- a/scripts/page-body-readers-baseline.tsv+++ b/scripts/page-body-readers-baseline.tsv@@ -507,12 +507,11 @@ src/core/think/index.ts composeExtractiveFallback field LEADsrc/core/think/index.ts persistSynthesis call:putPage SEGWsrc/core/timeline-dedup-repair.ts repairLegacyTimelineSourceRows field STREAMsrc/core/timeline-dedup-repair.ts repairLegacyTimelineSourceRows sql STREAM-src/core/timeline-extract.ts pruneTimelineOrphans field STREAMsrc/core/timeline-extract.ts pruneTimelineOrphans sql STREAM-src/core/timeline-extract.ts retractCoordinated field STREAMsrc/core/timeline-extract.ts retractCoordinated sql STREAMsrc/core/timeline-extract.ts retractRemovedTimelineEntries field STREAMsrc/core/timeline-extract.ts retractRemovedTimelineEntries sql STREAM+src/core/timeline-extract.ts retractStoredPage field STREAMsrc/core/timeline-write-through.ts writeTimelineEntryThrough field SEGW assertInlineBody before the file or row is touchedsrc/core/timeline-write-through.ts writeTimelineEntryThrough sql SEGW assertInlineBody before the file or row is touchedsrc/core/transcripts/recover.ts userlessCodexSessions sql STREAMdiff --git a/src/commands/extract-timeline-db.ts b/src/commands/extract-timeline-db.tsindex 0beda0ba78..e58ad26c6e 100644--- a/src/commands/extract-timeline-db.ts+++ b/src/commands/extract-timeline-db.ts@@ -19,10 +19,11 @@import type { BrainEngine, TimelineBatchInput } from '../core/engine.ts';import type { Page, PageType } from '../core/types.ts';import { parseTimelineEntries, deriveTimelineAnchor } from '../core/link-extraction.ts';-import { retractRemovedTimelineEntries, segmentedTimelineText } from '../core/timeline-extract.ts';+import { eachStoredTimelineRow, retractRemovedTimelineEntries, segmentedTimelineText, storedTimelineKey, TimelineKeySet, unkeptTimelineRows } from '../core/timeline-extract.ts';+import { timelineKey } from '../core/timeline-marker.ts';import { managedPersistenceEnabled } from '../core/persistence/ownership.ts';import { maintenanceTransaction } from '../core/persistence/attribution.ts';-import { storedCanonicalTimeline, unrecordedCanonicalTimeline } from '../core/persistence/canonical-projections.ts';+import { segmentedCanonicalCollector, unrecordedCanonicalTimeline } from '../core/persistence/canonical-projections.ts';import { isSegmentedPage } from '../core/page-body/page-shape.ts';import { maintenancePreflight, submitDatabaseMaintenanceIntent, type MaintenanceAuthority } from '../core/persistence/prepared-maintenance.ts';import { authorizeWrite } from '../core/persistence/authority.ts';@@ -162,7 +163,7 @@ export async function extractTimelineFromDB(engine: BrainEngine, opts: TimelineDif (managed) {try {const outcome = await publishPageTimeline(engine, await authorityFor(source_id), slug, source_id, opts,- { snapshot, stored: snapshot ? readBatch.stored.get(Number(snapshot.page.id)) ?? [] : [] });+ { snapshot, stored: !snapshot ? [] : isSegmentedPage(snapshot.page) ? undefined : readBatch.stored.get(Number(snapshot.page.id)) ?? [] });if (outcome === 'skipped') result.skipped++;else if (outcome === 'pending') result.pending++;else if (outcome !== null) { result.created += outcome; result.pages++; opts.completed?.add(extractCompletionKey(source_id, slug, snapshot!.revision)); }@@ -242,56 +243,87 @@ interface TimelineReadBatch {start: number;covered: number;snapshots: Map<string, PageSnapshot>;- /** Managed walks only: stored rows by page id. */+ /** Managed walks only: stored rows by page id (inline pages). */stored: Map<number, StoredTimelineRows[]>;}+/** The stored non-event timeline rows of each page, by page id. */+async function storedTimelineRows(engine: BrainEngine, pageIds: readonly number[]): Promise<Map<number, StoredTimelineRows[]>> {+ const stored = new Map<number, StoredTimelineRows[]>();+ const rows = await engine.executeRaw<StoredTimelineRows & { page_id: number }>(+ `SELECT page_id, id, to_char(date, 'YYYY-MM-DD') AS date, date::text AS date_text, source, summary, detail FROM timeline_entries+ WHERE page_id = ANY($1::int[]) AND event_page_id IS NULL ORDER BY date, id`, [pageIds]);+ for (const { page_id, ...row } of rows) {+ const list = stored.get(Number(page_id)) ?? [];+ list.push(row);+ stored.set(Number(page_id), list);+ }+ return stored;+}+async function readTimelineBatch(engine: BrainEngine, refs: ReadonlyArray<{ slug: string; source_id: string }>, start: number,withStoredRows: boolean): Promise<TimelineReadBatch> {const { snapshots, covered } = await engine.readPageSnapshotsBatch(refs.slice(start, start + BATCH_SIZE).map(ref => ({ slug: ref.slug, sourceId: ref.source_id })));- const stored = new Map<number, StoredTimelineRows[]>();- const pageIds = [...snapshots.values()].map(snapshot => Number(snapshot.page.id));- if (withStoredRows && pageIds.length) {- const rows = await engine.executeRaw<StoredTimelineRows & { page_id: number }>(- `SELECT page_id, id, to_char(date, 'YYYY-MM-DD') AS date, date::text AS date_text, source, summary, detail FROM timeline_entries- WHERE page_id = ANY($1::int[]) AND event_page_id IS NULL ORDER BY date, id`, [pageIds]);- for (const { page_id, ...row } of rows) {- const list = stored.get(Number(page_id)) ?? [];- list.push(row);- stored.set(Number(page_id), list);- }- }+ // A segmented page's rows are streamed by its plan (plannedTimeline), not held for the batch.+ const pageIds = [...snapshots.values()].filter(snapshot => !isSegmentedPage(snapshot.page)).map(snapshot => Number(snapshot.page.id));+ const stored = withStoredRows && pageIds.length ? await storedTimelineRows(engine, pageIds) : new Map<number, StoredTimelineRows[]>();return { start, covered, snapshots, stored };}/*** The timeline change one page needs: removed rows to retract and canonical* tuples (or an inferred anchor) to insert. `stored` is the caller's read of- * the page's rows; without it the checks read them.+ * the page's rows; without it they are read once here. A segmented body is+ * read once, block by block, keeping only what differs from the stored rows+ * (the keys of the rows it produces, the entries no row records). `retract`+ * deletes the removed rows; `stop` is asked before each segment read.*/-async function plannedTimeline(engine: BrainEngine, page: Page, slug: string, sourceId: string, inferDates: boolean, stored?: StoredTimelineRows[]) {- // A segmented body is read block by block, through the engine given (inside the coordinator's transaction too).- const segmented = isSegmentedPage(page) ? await segmentedTimelineText(engine, page) : null;- const fullContent = segmented ?? page.compiled_truth + '\n' + page.timeline;- const removed = await retractRemovedTimelineEntries(engine, slug, sourceId, fullContent, { dryRun: true,- ...(stored ? { storedRows: stored.map(({ date_text: _text, ...row }) => row) } : {}) });- let entries: Array<{ date: string; source?: string; summary: string; detail?: string }> = await unrecordedCanonicalTimeline(engine, page.id,- segmented ? await storedCanonicalTimeline(engine, page, slug) : page, slug, stored?.map(row => ({ date: row.date_text, source: row.source, summary: row.summary })));- const parsed = segmented ? segmented.entries.length : parseTimelineEntries(page.compiled_truth + '\n' + page.timeline).length;- if (entries.length === 0 && inferDates && parsed === 0) {+async function plannedTimeline(engine: BrainEngine, page: Page, slug: string, sourceId: string, inferDates: boolean, stored?: StoredTimelineRows[],+ opts: { retract?: boolean; stop?: () => boolean } = {}) {+ const retraction = { dryRun: opts.retract !== true, ...(opts.stop ? { stop: opts.stop } : {}) };+ const strip = (rows: StoredTimelineRows[]) => rows.map(({ date_text: _text, ...row }) => row);+ let entries: Array<{ date: string; source?: string; summary: string; detail?: string }>;+ let removed: unknown[];+ let parsed: number;+ let rowCount: number;+ if (!isSegmentedPage(page)) {+ const rows = stored ?? (await storedTimelineRows(engine, [Number(page.id)])).get(Number(page.id)) ?? [];+ const text = page.compiled_truth + '\n' + page.timeline;+ removed = await retractRemovedTimelineEntries(engine, slug, sourceId, text, { ...retraction, storedRows: strip(rows) });+ entries = await unrecordedCanonicalTimeline(engine, page.id, page, slug, rows.map(row => ({ date: row.date_text, source: row.source, summary: row.summary })));+ parsed = parseTimelineEntries(text).length;+ rowCount = rows.length;+ } else {+ // A segmented body is read once, through the engine given (inside the coordinator's transaction too), and its+ // rows are held as key digests (TimelineKeySet), never as one array unless the caller read them.+ const within = new TimelineKeySet();+ const recorded = new TimelineKeySet();+ rowCount = 0;+ const take = (row: StoredTimelineRows) => {+ within.add(storedTimelineKey(row));+ recorded.add(timelineKey({ date: row.date_text, source: row.source, summary: row.summary }));+ rowCount++;+ };+ if (stored) stored.forEach(take);+ else await eachStoredTimelineRow(engine, Number(page.id), take);+ const collector = segmentedCanonicalCollector(slug, recorded);+ const keys = await segmentedTimelineText(engine, page, { within, entries: false, ...(opts.stop ? { stop: opts.stop } : {}), onBlock: text => collector.add(text) });+ removed = await retractRemovedTimelineEntries(engine, slug, sourceId, keys, { ...retraction,+ storedRows: stored ? strip(stored) : await unkeptTimelineRows(engine, Number(page.id), keys) });+ entries = [...collector.result().values()];+ parsed = keys.parsed;+ }+ if (entries.length === 0 && inferDates && parsed === 0 && rowCount === 0) {const anchor = anchorFor(page, slug);- const [count] = !anchor ? [{ n: 1 }] : stored ? [{ n: stored.length }] : await engine.executeRaw<{ n: number }>(- 'SELECT count(*)::int AS n FROM timeline_entries WHERE page_id=$1 AND event_page_id IS NULL', [page.id]);- if (anchor && !count?.n) entries = [anchor];+ if (anchor) entries = [anchor];}- return { fullContent, removed: removed.length, entries };+ return { removed: removed.length, entries };}/** Under the coordinator's page lock: retract removed rows, insert the planned tuples. */async function writePageTimeline(tx: BrainEngine, page: Page, slug: string, sourceId: string, inferDates: boolean): Promise<number> {- const plan = await plannedTimeline(tx, page, slug, sourceId, inferDates);- if (plan.removed) await retractRemovedTimelineEntries(tx, slug, sourceId, plan.fullContent);+ const plan = await plannedTimeline(tx, page, slug, sourceId, inferDates, undefined, { retract: true });if (!plan.entries.length) return 0;return tx.addTimelineEntriesBatch(plan.entries.map(entry => ({ slug, date: entry.date, source: entry.source,summary: entry.summary, detail: entry.detail || '', source_id: sourceId })), { auditSite: 'extract.timeline_db' });@@ -305,10 +337,10 @@ async function writePageTimeline(tx: BrainEngine, page: Page, slug: string, sour* the caller's batched read of the page and its stored rows.*/async function publishPageTimeline(engine: BrainEngine, authority: MaintenanceAuthority, slug: string, sourceId: string,- opts: TimelineDbOptions, read?: { snapshot: PageSnapshot | null; stored: StoredTimelineRows[] }): Promise<number | null | 'skipped' | 'pending'> {+ opts: TimelineDbOptions, read?: { snapshot: PageSnapshot | null; stored: StoredTimelineRows[] | undefined }, stop?: () => boolean): Promise<number | null | 'skipped' | 'pending'> {const snapshot = read ? read.snapshot : await engine.readPageSnapshot(slug, { sourceId });if (!snapshot || isQuarantined(snapshot.page.frontmatter) || (opts.typeFilter && snapshot.page.type !== opts.typeFilter)) return null;- const plan = await plannedTimeline(engine, snapshot.page, slug, sourceId, opts.inferDates === true, read?.stored);+ const plan = await plannedTimeline(engine, snapshot.page, slug, sourceId, opts.inferDates === true, read?.stored, stop ? { stop } : {});if (!plan.removed && !plan.entries.length) return 0;for (let attempt = 0; ; attempt++) {const h = digest(['extract-timeline-db-v1', sourceId, slug, snapshot.revision, attempt]);@@ -331,12 +363,14 @@ async function publishPageTimeline(engine: BrainEngine, authority: MaintenanceAu* One page's timeline on a managed brain, through the coordinator (the serve* sweep's path): rows added, 0 when nothing changes, or 'unsettled' when the* page changed mid-run or its request is still pending (retry next time).+ * `stop` is the caller's budget, asked before each segment the planning read+ * takes (BodyReadStopped ends it before any request is admitted).*/-export async function publishManagedPageTimeline(engine: BrainEngine, slug: string, sourceId: string): Promise<number | 'unsettled'> {+export async function publishManagedPageTimeline(engine: BrainEngine, slug: string, sourceId: string, stop?: () => boolean): Promise<number | 'unsettled'> {const authority = await maintenancePreflight(engine, sourceId);if (!authority) throw opError('writer_coordinator_required', 'This brain is not managed; write the timeline batch directly.',`Source ${sourceId} has no managed writer, so there is no coordinator to publish through.`);- const outcome = await publishPageTimeline(engine, authority, slug, sourceId, { dryRun: false, jsonMode: false });+ const outcome = await publishPageTimeline(engine, authority, slug, sourceId, { dryRun: false, jsonMode: false }, undefined, stop);return outcome === 'skipped' || outcome === 'pending' ? 'unsettled' : outcome ?? 0;}diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 77b39ff41b..ba6a29641c 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -660,7 +660,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }{ since: 'TBD', text: '`delete_page` (soft and `purge: true`), `restore_page`, `gbrain delete` and `gbrain restore` now work on a page over 24 MiB on a source backed by files: the file is compared with the page by digest, streamed, and a file edited on disk still refuses as before. Restoring such a page clears its deletion without re-importing it and writes its file back from the database; the 25 MiB pre-push scan cap on written files still applies, and a core page or an external_untrusted writer still refuses.' },{ since: 'TBD', text: 'A write that stores a page in segments says in its receipt whether search sees it: `searchable: true` when it commits (every new page up to 4 MiB and every rewrite), or `searchable: "pending"` for a larger new page while its chunks are built after commit, with `searchable_retry_after_ms` and a `searchable_fix` that reads the receipt again (`get_write_request`) until it says `searchable: true`. A new page up to 4 MiB was previously searchable only once a post-commit build finished.' },{ since: 'TBD', text: '`gbrain projections drain` now builds pages stored in segments whose post-commit build never ran or died, skipping one another process is still building (claim renewed within 60 s), so a brain with no resident writer can make a large new page searchable. A pending receipt\'s `searchable_fix` names it as the fallback after the re-read wait, and doctor `text_projection_readiness` counts such pages (`segmented_pending`) and points to it.' },- { since: 'TBD', text: 'The maintenance sweep (`gbrain sweep`, the serve idle sweep) links a page stored in segments on its own after the inline pages, smallest first, and stops reading one at its time budget; a page that does not fit is skipped with reason `budget_deferred:segmented_page`, left for `gbrain extract --stale`, and later sweeps in the same process skip it (`segmented_page_deferred`) until it changes. Derived passes over a page stored in segments no longer refuse a page of short lines or dated bullets over 8 MiB with `page_body_segmented`.' },+ { since: 'TBD', text: 'The maintenance sweep (`gbrain sweep`, the serve idle sweep) links a page stored in segments on its own after the inline pages, smallest first, and stops reading one at its time budget; a page that does not fit, though it started with at least half of the sweep\'s budget, is skipped with reason `budget_deferred:segmented_page`, left for `gbrain extract --stale`, and later sweeps in the same process leave it out (`segmented_page_deferred`) until it changes, so the pages behind it are still reached; one that started with less is left for the next sweep (`budget_exhausted:links_timeline`). Derived passes over a page stored in segments, timeline retraction over its earlier versions (`gbrain extract timeline --prune-orphans`, `gbrain extract timeline --source db`, doctor `timeline_orphans`) included, no longer refuse a page of short lines or dated bullets over 8 MiB with `page_body_segmented`.' },{ since: 'TBD', text: 'Deleting and restoring a page over 24 MiB on a source backed by files is now lossless up to the page ceiling (`pages.max_bytes`). `restore_page` and `gbrain restore` write the file back byte for byte by streaming it from the stored segments into its staging file, including a file over the 25 MiB pre-push scan cap (the restore used to refuse with `request_too_large`, so the file a soft delete had removed could not be put back on disk). A delete or restore that replaces or removes a file over 24 MiB keeps the prior file as a staged copy beside it (a hidden `.<sha256>.tmp.before-<uuid>` file) until the write commits, named in its recovery record by path and SHA-256 instead of embedded in it: the record stays a few hundred bytes, the recovery reservation counts the file once (a 90 MiB delete used to need 283 MB against the 256 MiB `persistence.limits.worktree_recovery_bytes` budget and was refused), and a crash between removing the file and committing renames the copy back. A page whose file plus its staging does not fit that budget (a Postgres page near the 256 MiB ceiling) is still refused with `request_too_large` before anything is touched. `gbrain repair stuck-recovery` refuses such a recovery with `recovery_large_file_unsupported` (resolve it by hand; the resident writer finishes it).' },{ since: 'TBD', text: 'A page purge (`delete_page` with `purge: true`, `gbrain delete --purge` and the 72-hour hard delete of soft-deleted pages) of a page stored in segments no longer breaks another page\'s write that is still being prepared with some of the same text: the purge keeps exactly the segment texts such a write staged, and still deletes every other text only the purged page used. `restore_page` of a page over 24 MiB whose old chunks were still waiting to be removed returns `projection: "pending"` and makes the page searchable once they are gone, instead of showing the old text in search.' },{ since: 'TBD', text: 'Chunks of a page stored in segments keep a Markdown heading with the text after it, so a section appended after a full last chunk re-embeds only its own chunk (was two). Inline pages chunk as before.' },diff --git a/src/core/page-body/limits.ts b/src/core/page-body/limits.tsindex 4f4930c115..b48f75ac6d 100644--- a/src/core/page-body/limits.ts+++ b/src/core/page-body/limits.ts@@ -3,8 +3,9 @@* number and config key in one place. The product numbers (ceilings, version* retention) are open product calls; change them here and nowhere else.*- * `pages.segmented_storage` defaults to `on`, and is effectively on only while- * no recent writer predates segmented pages (`segmentedWriterBlockers`). While+ * `pages.segmented_storage` defaults to `off` (SEGMENTED_STORAGE_DEFAULT); set+ * `on`, it is effectively on only while no recent writer predates segmented+ * pages (`segmentedWriterBlockers`). While* it is off no page is newly segmented, every page stays inline up to* `PAGE_MAX_BYTES` (Wave A) and no code path below the inline threshold changes.*/diff --git a/src/core/page-body/segment-blocks.ts b/src/core/page-body/segment-blocks.tsindex 9c2e922bf9..a46e46727d 100644--- a/src/core/page-body/segment-blocks.ts+++ b/src/core/page-body/segment-blocks.ts@@ -22,8 +22,9 @@import type { BrainEngine } from '../engine.ts';import { opError } from '../ops/contract.ts';import { SEGMENT_MAX_BYTES } from './limits.ts';-import { bodyRowWork, openSegmentedBody, readBodyRange, trustedSegments, type TrustedSegment } from './read-range.ts';-import { cutBlocked } from './segmenter.ts';+import { bodyRowWork, openSegmentedBody, readBodyRange, trustedSegments } from './read-range.ts';+import { ledgerApplies } from './segment-ledger.ts';+import { cutBlocked, SEGMENTER_VERSION } from './segmenter.ts';import { readEntryState } from './entry-state.ts';import type { BodyRegion } from './types.ts';@@ -79,6 +80,11 @@ export interface BodyBlockOptions {want?: (run: { seqs: readonly number[]; first: boolean }) => boolean;/** Asked before each segment is read: true ends the read with BodyReadStopped (a caller's time budget ran out). */stop?: () => boolean;+ /**+ * Collects the key (runKey) of each run read whole, when no withdrawal applies to the page (each block's text is its+ * stored text), so a retained generation's run with the same key need not be read (retainedGenerationBlocks).+ */+ runKeys?: Set<string>;}/** bodyBlocks ended before a segment read because `stop` said so; nothing after the blocks already yielded was read. */@@ -101,7 +107,7 @@ export function blockTooLargeError(slug: string, sourceId: string, bytes: number* segment, not after a bare `\r`) and a structural cut before the segment's first line would have been allowed* (`cutBlocked` on its stored entry state, the parser state at the cut). Pages of another segmenter version never do.*/-function freshAfterForcedCut(previous: Uint8Array, seg: TrustedSegment, stale: boolean): boolean {+function freshAfterForcedCut(previous: Uint8Array, seg: Pick<CutSegment, 'raw' | 'entryState'>, stale: boolean): boolean {if (stale || previous[previous.length - 1] !== 0x0a) return false;const entry = readEntryState(seg.entryState);if (!entry) return false;@@ -111,12 +117,62 @@ function freshAfterForcedCut(previous: Uint8Array, seg: TrustedSegment, stale: breturn !cutBlocked(entry, utf8.decode(seg.raw.subarray(0, end)));}+/** One stored segment as the block cutter reads it: where it sits, its stored bytes and entry state, and its text in pieces. */+interface CutSegment {+ byteStart: number;+ byteLen: number;+ raw: Uint8Array;+ entryState: unknown;+ texts: readonly string[];+}++/**+ * The texts of one run of segments joined by forced cuts (`segments` in order, the first at stored byte `start`): a+ * block ends at each forced cut freshAfterForcedCut allows, and one longer than BLOCK_MAX_BYTES refuses with+ * `page_body_segmented`. Counts each block's bytes and units in segmentedPassWork.+ */+async function* runBlocks(segments: AsyncIterable<CutSegment>, start: number, page: { slug: string; sourceId: string }, stale: boolean,+ collect: (bytes: number) => void): AsyncIterable<string> {+ let parts: Buffer[] = [];+ let previous: Uint8Array | null = null;+ let end = start;+ const flush = (to: number): string => {+ const text = Buffer.concat(parts).toString('utf8');+ collect(to - start);+ segmentedPassWork.bytes += to - start;+ segmentedPassWork.blocks += text.length;+ parts = [];+ start = to;+ return text;+ };+ for await (const seg of segments) {+ bodyRowWork.visits++;+ if (previous && freshAfterForcedCut(previous, seg, stale)) yield flush(seg.byteStart);+ end = seg.byteStart + seg.byteLen;+ if (end - start > BLOCK_MAX_BYTES) throw blockTooLargeError(page.slug, page.sourceId, end - start);+ for (const text of seg.texts) parts.push(Buffer.from(text, 'utf8'));+ previous = seg.raw;+ }+ yield flush(end);+}++const toJson = (v: unknown) => typeof v === 'string' ? JSON.parse(v) as unknown : v;++/**+ * The identity of a run's stored text and of every cut the block cutter can make in it: its region, whether its page is+ * of another segmenter version, and each segment's SHA-256 and entry state. Two runs with one key yield the same blocks.+ */+function runKey(region: BodyRegion, stale: boolean, segments: ReadonlyArray<{ sha256: Uint8Array; entryState: unknown }>): string {+ return JSON.stringify([region, stale, segments.map(seg => [Buffer.from(seg.sha256).toString('hex'), toJson(seg.entryState)])]);+}+export async function* bodyBlocks(engine: BrainEngine, page: { id: number; slug: string; source_id?: string },opts: BodyBlockOptions = {}): AsyncIterable<BodyBlock> {const body = await openSegmentedBody(engine, { pageId: Number(page.id) });const forced = new Set((await engine.executeRaw<{ seq: number }>(`SELECT seq FROM page_body_manifest WHERE page_id=$1 AND staging_id IS NULLAND gen_from<=$2 AND (gen_to IS NULL OR gen_to>$2) AND cut_kind='forced'`, [body.pageId, body.generation])).map(row => Number(row.seq)));const collect = readGarbageCollector();+ const runKeys = opts.runKeys && !ledgerApplies(body.ledger) ? opts.runKeys : undefined;let at = 0;for (const [n, region] of (opts.regions ?? ['truth', 'timeline'] as const).entries()) {if (n > 0) {@@ -130,36 +186,77 @@ export async function* bodyBlocks(engine: BrainEngine, page: { id: number; slug:let j = i;while (j + 1 < rows.length && forced.has(rows[j]!.seq)) j++;bodyRowWork.visits += j - i + 1;- if (opts.want && !opts.want({ seqs: rows.slice(i, j + 1).map(row => row.seq), first: i === 0 })) {+ const run = rows.slice(i, j + 1);+ i = j + 1;+ if (opts.want && !opts.want({ seqs: run.map(row => row.seq), first: run[0] === rows[0] })) {at = NaN;- i = j + 1;continue;}- let parts: Buffer[] = [];- let start = rows[i]!.byteStart;- let previous: Uint8Array | null = null;- const flush = (end: number): BodyBlock => {- const text = Buffer.concat(parts).toString('utf8');- collect(end - start);- segmentedPassWork.bytes += end - start;- segmentedPassWork.blocks += text.length;+ const stop = opts.stop;+ const read: Array<{ sha256: Uint8Array; entryState: unknown }> = [];+ const segments = async function* (): AsyncIterable<CutSegment> {+ for await (const seg of trustedSegments(engine, body, run, stop && (() => { if (stop()) throw new BodyReadStopped(page.slug); }))) {+ bodyRowWork.visits++;+ read.push({ sha256: seg.row.sha256, entryState: seg.entryState });+ yield { byteStart: seg.row.byteStart, byteLen: seg.row.byteLen, raw: seg.raw, entryState: seg.entryState, texts: seg.pieces.map(piece => piece.text) };+ }+ };+ for await (const text of runBlocks(segments(), run[0]!.byteStart, { slug: page.slug, sourceId: body.sourceId }, body.stale, collect)) {const block = { region, text, at };at += text.length;- parts = [];- start = end;- return block;- };- const stop = opts.stop;- for await (const seg of trustedSegments(engine, body, rows.slice(i, j + 1), stop && (() => { if (stop()) throw new BodyReadStopped(page.slug); }))) {- bodyRowWork.visits++;- if (previous && freshAfterForcedCut(previous, seg, body.stale)) yield flush(seg.row.byteStart);- const end = seg.row.byteStart + seg.row.byteLen;- if (end - start > BLOCK_MAX_BYTES) throw blockTooLargeError(page.slug, body.sourceId, end - start);- for (const piece of seg.pieces) parts.push(Buffer.from(piece.text, 'utf8'));- previous = seg.raw;+ yield block;}- yield flush(rows[j]!.byteStart + rows[j]!.byteLen);+ runKeys?.add(runKey(region, body.stale, read));+ }+ }+}++/**+ * @internal Retained-generation reads, for the bounded-work test: bytes of the runs a retained generation read+ * (`bytes`) and of the runs it skipped because a run with the same key was already read (`skipped`). Counts, not time.+ */+export const retainedGenerationWork = { bytes: 0, skipped: 0 };++/**+ * The stored text of a retained segmented generation (a segmented page_versions row references a generation; its body+ * columns are NULL) as `${compiled_truth}\n${timeline}`, cut into blocks as bodyBlocks cuts the live body (runBlocks),+ * from the generation's manifest rows, so a page demoted inline since still yields its segmented versions. A run whose+ * key is in `seen` (a run of the live body read without an overlay, or of a generation read before) is skipped, and+ * each run read is added to it. `stop` is asked before each segment read, as in bodyBlocks.+ */+export async function* retainedGenerationBlocks(engine: Pick<BrainEngine, 'executeRaw' | 'readManifest' | 'readSegmentTexts'>,+ page: { id: number; slug: string; sourceId: string }, generation: number,+ opts: { seen?: Set<string>; stop?: () => boolean } = {}): AsyncIterable<string> {+ const rows = await engine.readManifest(page.id, { generation });+ const [state] = await engine.executeRaw<{ segmenter_version: number | null }>('SELECT segmenter_version FROM pages WHERE id=$1', [page.id]);+ const stale = Number(state?.segmenter_version) !== SEGMENTER_VERSION;+ const collect = readGarbageCollector();+ for (const [n, region] of (['truth', 'timeline'] as const).entries()) {+ if (n > 0) yield '\n';+ const own = rows.filter(row => row.region === region);+ for (let i = 0; i < own.length;) {+ let j = i;+ while (j + 1 < own.length && own[j]!.cutKind === 'forced') j++;+ const run = own.slice(i, j + 1);i = j + 1;+ const bytes = run.reduce((sum, row) => sum + row.byteLen, 0);+ const key = runKey(region, stale, run);+ if (opts.seen?.has(key)) {+ retainedGenerationWork.skipped += bytes;+ continue;+ }+ opts.seen?.add(key);+ retainedGenerationWork.bytes += bytes;+ const segments = async function* (): AsyncIterable<CutSegment> {+ for (const row of run) {+ if (opts.stop?.()) throw new BodyReadStopped(page.slug);+ const hex = Buffer.from(row.sha256).toString('hex');+ const raw = (await engine.readSegmentTexts(page.sourceId, [row.sha256])).get(hex);+ if (raw === undefined) throw new Error(`Segment text of page ${page.id} generation ${generation} is missing.`);+ yield { byteStart: row.byteStart, byteLen: row.byteLen, raw, entryState: toJson(row.entryState), texts: [utf8.decode(raw)] };+ }+ };+ yield* runBlocks(segments(), run[0]!.byteStart, page, stale, collect);}}}diff --git a/src/core/page-body/segment-facts.ts b/src/core/page-body/segment-facts.tsindex b24bad23a7..fc76971377 100644--- a/src/core/page-body/segment-facts.ts+++ b/src/core/page-body/segment-facts.ts@@ -8,9 +8,10 @@* timeline line outside fenced code is the begin marker. Only runs holding a* fence marker can change any of those, so only they are read: the live* manifest rows that carry facts slots or whose segment text holds a marker- * (found in SQL, nothing transferred), plus every run with a forced cut (a- * marker may straddle one), and every run after an open fence until it- * closes. A block starts outside code (segment-blocks.ts), so each marker is+ * (found in SQL, nothing transferred), plus every run with a forced cut+ * inside a line (a marker may straddle one; no marker holds a newline, so a+ * forced cut after one cannot split it), and every run after an open fence+ * until it closes. A block starts outside code (segment-blocks.ts), so each marker is* located in its block exactly as in the joined section. The segmenter never* cuts inside a fence, so a fence lies in one block: a fence longer than a* segment is a run of forced cuts, which bodyBlocks joins up to@@ -42,7 +43,8 @@ async function markerSeqs(engine: BrainEngine, pageId: number): Promise<Set<numbconst rows = await engine.executeRaw<{ seq: number }>(`SELECT m.seq FROM page_body_manifest mJOIN page_segment_texts t ON t.source_id=m.source_id AND t.sha256=m.sha256WHERE m.page_id=$1 AND m.gen_to IS NULL AND m.staging_id IS NULL- AND (m.facts_slots<>'[]'::jsonb OR m.cut_kind='forced' OR position($2::bytea in t.body)>0 OR position($3::bytea in t.body)>0)`,+ AND (m.facts_slots<>'[]'::jsonb OR (m.cut_kind='forced' AND get_byte(t.body, length(t.body)-1)<>10)+ OR position($2::bytea in t.body)>0 OR position($3::bytea in t.body)>0)`,[pageId, Buffer.from(FACTS_FENCE_BEGIN, 'utf8'), Buffer.from(FACTS_FENCE_END, 'utf8')]);return new Set(rows.map(row => Number(row.seq)));}diff --git a/src/core/persistence/canonical-projections.ts b/src/core/persistence/canonical-projections.tsindex cff488043c..18923a0413 100644--- a/src/core/persistence/canonical-projections.ts+++ b/src/core/persistence/canonical-projections.ts@@ -218,19 +218,38 @@ async function priorView(engine: BrainEngine, page: PageSnapshot['page'], slug:}/**- * The canonical timeline of a stored segmented page whose body is unread, block by block, extractTimeline's two passes- * merged in its order (every bullet and heading entry, then parseTimelineEntries' readings over them).+ * The canonical timeline of a segmented body fed one block at a time (`add`), extractTimeline's two passes merged in its+ * order (every bullet and heading entry, then parseTimelineEntries' readings over them). An entry whose timelineKey is in+ * `recorded` (the page's stored rows) is not kept: unrecordedCanonicalTimeline drops it, and once a page is extracted+ * its recorded entries are nearly all of it.*/-async function segmentedCanonicalTimeline(engine: BrainEngine, page: { id: number; slug: string; source_id: string }, slug: string): Promise<Map<string, ExtractedTimelineEntry>> {+export function segmentedCanonicalCollector(slug: string, recorded?: { has(key: string): boolean }): { add(text: string): void; result(): Map<string, ExtractedTimelineEntry> } {const extracted = new Map<string, ExtractedTimelineEntry>();const parsed = new Map<string, ExtractedTimelineEntry>();- for await (const block of bodyBlocks(engine, page)) {- const safe = sanitizeRemoteBody(block.text, { keepMaterializedMarkers: true });- for (const t of extractTimelineFromContent(safe, slug)) extracted.set(timelineKey(t), detachedValue(t));- for (const t of parseTimelineEntries(safe)) parsed.set(timelineKey({ ...t, source: t.source ?? 'markdown' }), detachedValue({ ...t, source: t.source ?? 'markdown', slug }));- }- for (const [key, entry] of parsed) extracted.set(key, entry);- return extracted;+ return {+ add(text) {+ const safe = sanitizeRemoteBody(text, { keepMaterializedMarkers: true });+ for (const t of extractTimelineFromContent(safe, slug)) {+ const key = timelineKey(t);+ if (!recorded?.has(key)) extracted.set(key, detachedValue(t));+ }+ for (const t of parseTimelineEntries(safe)) {+ const key = timelineKey({ ...t, source: t.source ?? 'markdown' });+ if (!recorded?.has(key)) parsed.set(key, detachedValue({ ...t, source: t.source ?? 'markdown', slug }));+ }+ },+ result() {+ for (const [key, entry] of parsed) extracted.set(key, entry);+ return extracted;+ },+ };+}++/** The canonical timeline of a stored segmented page whose body is unread, block by block (segmentedCanonicalCollector). */+async function segmentedCanonicalTimeline(engine: BrainEngine, page: { id: number; slug: string; source_id: string }, slug: string): Promise<Map<string, ExtractedTimelineEntry>> {+ const collector = segmentedCanonicalCollector(slug);+ for await (const block of bodyBlocks(engine, page)) collector.add(block.text);+ return collector.result();}/**diff --git a/src/core/sweep.ts b/src/core/sweep.tsindex 311354106c..8078158092 100644--- a/src/core/sweep.ts+++ b/src/core/sweep.ts@@ -180,6 +180,7 @@ export async function runMaintenanceSweep(else report.skipped.push({ reason, count });};const overBudget = () => now() >= deadline;+ const budgetLeft = () => budgetMs > 0 ? Math.max(0, deadline - now()) / budgetMs : 0;// Budget abort signal: threads into the fence pass's per-page loop so a// long item can be interrupted at its own checkpoints. unref'd — the sweep must never hold the@@ -248,6 +249,7 @@ export async function runMaintenanceSweep(batchLimit,cutoffIso,overBudget,+ budgetLeft,report,skip,log,@@ -304,10 +306,14 @@ interface PassCtx {skip: (reason: string, count?: number) => void;}+/** The share of the sweep's budget still left (1 at its start, 0 once it is spent). */+type FreshBudget = { budgetLeft: () => number };+/**- * Segmented pages whose links/timeline pass did not fit a sweep's budget, `source\0slug` to the page's updated_at then:- * later sweeps in this process skip them until the page changes, so one page too large for any budget cannot take- * every sweep's budget. `gbrain extract --stale` extracts them.+ * Segmented pages whose links/timeline pass did not fit a whole sweep budget, `source\0slug` to the page's updated_at+ * then: later sweeps in this process leave them out of the pass's page query until the page changes, so one page too+ * large for any budget cannot take every sweep's budget, nor the batch slots of the pages behind it.+ * `gbrain extract --stale` extracts them.*/const deferredSegmentedPages = new Map<string, string>();@@ -326,7 +332,7 @@ export function _resetDeferredSegmentedPagesForTests(): void {*/async function runLinksTimelinePass(engine: BrainEngine,- ctx: PassCtx & { cutoffIso: string; log: (msg: string) => void },+ ctx: PassCtx & FreshBudget & { cutoffIso: string; log: (msg: string) => void },): Promise<void> {const { sourceId, batchLimit, cutoffIso, overBudget, report, skip, log } = ctx;@@ -356,7 +362,9 @@ async function runLinksTimelinePass(// (no versionTs branch — extractor-version catch-up is `extract --stale`'s// job; the sweep is a recency back-stop). The µs to_char projection is the// #1768 stamp discipline: stamp the row's READ updated_at, not now(), so an- // edit between SELECT and stamp stays stale and re-sweeps.+ // edit between SELECT and stamp stays stale and re-sweeps. Deferred pages are left out in SQL, before the LIMIT.+ const deferred = await liveDeferredPages(engine, sourceId, cutoffIso);+ skip('segmented_page_deferred', deferred.length);const recent = await engine.executeRaw<{ slug: string; updated_at_iso: string; body_storage: string | null; body_bytes: number | null }>(`SELECT slug,to_char(updated_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"') AS updated_at_iso,@@ -366,9 +374,10 @@ async function runLinksTimelinePass(AND deleted_at IS NULLAND updated_at >= $2::timestamptzAND (links_extracted_at IS NULL OR updated_at > links_extracted_at)+ AND NOT (slug = ANY($4::text[]))ORDER BY updated_at DESCLIMIT $3`,- [sourceId, cutoffIso, batchLimit],+ [sourceId, cutoffIso, batchLimit, deferred],);if (recent.length === 0) return;@@ -388,7 +397,7 @@ async function runLinksTimelinePass(type Extracted = Awaited<ReturnType<typeof extractPageLinks>>;type Snapshot = NonNullable<Awaited<ReturnType<BrainEngine['readPageSnapshot']>>>;const { extractSegmentedPageLinks, segmentedRoleText } = await import('./page-body/segment-links.ts');- const { bodyBlocks, detachedValue } = await import('./page-body/segment-blocks.ts');+ const { BodyReadStopped, bodyBlocks, detachedValue } = await import('./page-body/segment-blocks.ts');/*** One batch through every phase. A segmented page's reads ask `stop` before each segment, so one that does not fit@@ -550,12 +559,14 @@ async function runLinksTimelinePass(if (tlBatch.length > 0 && await managedPersistenceEnabled(engine)) {const { publishManagedPageTimeline } = await import('../commands/extract-timeline-db.ts');for (const slug of new Set(tlBatch.map(row => row.slug))) {+ if (overBudget() && stop) throw new BodyReadStopped(slug); // a segmented page's batch is that page aloneif (overBudget()) { skip('budget_exhausted:timeline'); timelineUnsettled.add(slug); continue; }try {- const added = await publishManagedPageTimeline(engine, slug, sourceId);+ const added = await publishManagedPageTimeline(engine, slug, sourceId, stop);if (added === 'unsettled') timelineUnsettled.add(slug);else report.timelineExtracted += added;- } catch {+ } catch (e) {+ if (e instanceof BodyReadStopped) throw e;skip('timeline_publish_failed');timelineUnsettled.add(slug);}@@ -620,26 +631,48 @@ async function runLinksTimelinePass(await runLinksTimelineBatches(recent, ctx, runBatch);}+/**+ * The slugs of this source's deferred segmented pages that are still stale and unchanged since they were deferred;+ * an entry whose page changed, was stamped or left the recency window is forgotten.+ */+async function liveDeferredPages(engine: BrainEngine, sourceId: string, cutoffIso: string): Promise<string[]> {+ const prefix = `${sourceId}\0`;+ const entries = [...deferredSegmentedPages].filter(([key]) => key.startsWith(prefix));+ if (entries.length === 0) return [];+ const rows = await engine.executeRaw<{ slug: string; updated_at_iso: string }>(+ `SELECT slug, to_char(updated_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"') AS updated_at_iso+ FROM pages+ WHERE source_id = $1+ AND deleted_at IS NULL+ AND updated_at >= $2::timestamptz+ AND (links_extracted_at IS NULL OR updated_at > links_extracted_at)+ AND slug = ANY($3::text[])`,+ [sourceId, cutoffIso, entries.map(([key]) => key.slice(prefix.length))],+ );+ const live = new Set(rows.filter(row => deferredSegmentedPages.get(prefix + row.slug) === row.updated_at_iso).map(row => row.slug));+ for (const [key] of entries) if (!live.has(key.slice(prefix.length))) deferredSegmentedPages.delete(key);+ return [...live];+}++/** A segmented page that does not fit is deferred only when it started with at least this share of the sweep's budget. */+const FRESH_BUDGET_SHARE = 0.5;+/*** #C5: a segmented page is read several times per pass and can outlast any budget, so it never shares a batch: the* inline pages run first as one batch, then each segmented page alone, smallest first, while budget remains. One- * that does not fit stops at a segment bound (BodyReadStopped) and is deferred (left unstamped) until its page- * changes, so it cannot take the budget of the rest of this sweep, or of later sweeps in this process.+ * that does not fit stops at a segment bound (BodyReadStopped) and is left unstamped. It is deferred until its page+ * changes only when it started with at least FRESH_BUDGET_SHARE of the sweep's budget, so it cannot take the budget of+ * later sweeps in this process; one that started after other work spent more is left for the next sweep.*/async function runLinksTimelineBatches(recent: Array<{ slug: string; updated_at_iso: string; body_storage: string | null; body_bytes: number | null }>,- ctx: Pick<PassCtx, 'sourceId' | 'overBudget' | 'skip'> & { log: (msg: string) => void },+ ctx: Pick<PassCtx, 'sourceId' | 'overBudget' | 'skip'> & FreshBudget & { log: (msg: string) => void },runBatch: (recent: Array<{ slug: string; updated_at_iso: string }>, stop?: () => boolean) => Promise<void>,): Promise<void> {const { sourceId, overBudget, skip, log } = ctx;const { BodyReadStopped } = await import('./page-body/segment-blocks.ts');- const pending = recent.filter(row => {- if (deferredSegmentedPages.get(`${sourceId}\0${row.slug}`) !== row.updated_at_iso) return true;- skip('segmented_page_deferred');- return false;- });- const inline = pending.filter(row => row.body_storage !== 'segmented');- const segmented = pending.filter(row => row.body_storage === 'segmented').sort((a, b) => Number(a.body_bytes ?? 0) - Number(b.body_bytes ?? 0));+ const inline = recent.filter(row => row.body_storage !== 'segmented');+ const segmented = recent.filter(row => row.body_storage === 'segmented').sort((a, b) => Number(a.body_bytes ?? 0) - Number(b.body_bytes ?? 0));if (inline.length > 0) await runBatch(inline);for (let i = 0; i < segmented.length; i++) {if (overBudget()) {@@ -647,10 +680,15 @@ async function runLinksTimelineBatches(break;}const row = segmented[i]!;+ const whole = ctx.budgetLeft() >= FRESH_BUDGET_SHARE;try {await runBatch([row], overBudget);} catch (e) {if (!(e instanceof BodyReadStopped)) throw e;+ if (!whole) {+ skip('budget_exhausted:links_timeline');+ continue;+ }deferredSegmentedPages.set(`${sourceId}\0${row.slug}`, row.updated_at_iso);skip('budget_deferred:segmented_page');log(`[sweep] links/timeline: ${row.slug} (${row.body_bytes ?? '?'} bytes, segmented) does not fit the sweep budget; deferred until it changes. \`gbrain extract --stale --source-id ${sourceId}\` extracts it.`);diff --git a/src/core/timeline-extract.ts b/src/core/timeline-extract.tsindex e4413db084..598aa617b7 100644--- a/src/core/timeline-extract.ts+++ b/src/core/timeline-extract.ts@@ -13,9 +13,10 @@import { parseInlineCitationTimelineEntries, findTimelineSourceDelimiter, parseTimelineEntries } from './link-extraction.ts';import { isDatedTimelineLine, supersededInlineCitationEntries } from './timeline-citations.ts';+import { createHash } from 'node:crypto';import type { BrainEngine } from './engine.ts';import { firstMaterializedMarkerIndex } from './timeline-marker.ts';-import { BLOCK_MAX_BYTES, blockTooLargeError, bodyBlocks, detachedValue, segmentedPassWork } from './page-body/segment-blocks.ts';+import { bodyBlocks, detachedValue, retainedGenerationBlocks } from './page-body/segment-blocks.ts';export interface ExtractedTimelineEntry {slug: string;@@ -139,61 +140,149 @@ function markdownTimelineKeys(text: string, slug: string): Set<string> {return keys;}-/** What a page text says about its timeline rows: the tuples either parser yields, and the older citation readings it supersedes. */-export interface TimelineTextKeys { kept: Set<string>; superseded: Set<string> }+/** Membership of timeline keys: a Set of them, or a TimelineKeySet. */+export interface TimelineKeyLookup { has(key: string): boolean }++const LOW = 2 ** 32;+const AMBIGUOUS = 1;+const MARKED = 2;++/**+ * A set of keys held as two hashes of each (53 and 32 bits of its SHA-256), not the key strings: a few dozen bytes a+ * key instead of a few hundred, for sets with one key per stored timeline row of a large page. A key never added+ * answers true only when both of its hashes collide with an added key's (about 2^-85 a pair); two added keys whose+ * first hashes collide share one entry, which then answers for either. `mark` flags an added key (a stored row the+ * body produces), so one entry per row answers both questions.+ */+export class TimelineKeySet implements TimelineKeyLookup {+ private readonly digests = new Map<number, number>();+ add(key: string): void {+ const [a, b] = keyDigest(key);+ const at = this.digests.get(a);+ if (at === undefined) this.digests.set(a, b);+ else if (at % LOW !== b) this.digests.set(a, at - (at % LOW) + b + (Math.floor(at / LOW) & AMBIGUOUS ? 0 : AMBIGUOUS * LOW));+ }+ has(key: string): boolean {+ return this.entry(key) !== undefined;+ }+ /** Flag an added key; false when it was not added. */+ mark(key: string): boolean {+ const [a] = keyDigest(key);+ const at = this.entry(key);+ if (at === undefined) return false;+ if (!(Math.floor(at / LOW) & MARKED)) this.digests.set(a, at + MARKED * LOW);+ return true;+ }+ marked(key: string): boolean {+ const at = this.entry(key);+ return at !== undefined && (Math.floor(at / LOW) & MARKED) !== 0;+ }+ get size(): number { return this.digests.size; }+ private entry(key: string): number | undefined {+ const [a, b] = keyDigest(key);+ const at = this.digests.get(a);+ return at !== undefined && ((Math.floor(at / LOW) & AMBIGUOUS) !== 0 || at % LOW === b) ? at : undefined;+ }+}++function keyDigest(key: string): [number, number] {+ const hash = createHash('sha256').update(key).digest();+ return [hash.readUIntBE(0, 6) * 32 + (hash[6]! >> 3), hash.readUInt32BE(8)];+}++/**+ * What a page text says about its timeline rows: the tuples either parser yields, and the older citation readings it+ * supersedes. Read from a segmented body (segmentedTimelineText) with `within`, both hold only those keys, and a+ * stored row whose key is not in `within` (one written after the read) is never retracted against them. `runs` holds+ * the keys of the body's runs whose blocks were their stored text, which a retained generation need not read again.+ */+export interface TimelineTextKeys { kept: TimelineKeyLookup; superseded: TimelineKeyLookup; within?: TimelineKeyLookup; runs?: ReadonlySet<string> }++/** The key retraction compares a stored row by (`within` of segmentedTimelineText). */+export const storedTimelineKey = (row: TimelineTuple): string => tupleKey(row);++export interface SegmentedTimelineOptions {+ /**+ * The keys (storedTimelineKey) of the page's stored rows: kept is then the keys of `within` the body produces (marked+ * there, so the result holds no set of its own) and superseded only keys of `within`.+ */+ within?: TimelineKeySet;+ /** Collect the entries parseTimelineEntries reads (default true); `parsed` counts them either way. */+ entries?: boolean;+ /** Asked before each segment read (bodyBlocks): true ends the read with BodyReadStopped. */+ stop?: () => boolean;+ /** Each block's text, for a caller deriving more from the same walk. */+ onBlock?: (text: string) => void;+}/*** TimelineTextKeys of a segmented page's `${compiled_truth}\n${timeline}`, block by block (page-body/segment-blocks.ts),- * with the entries parseTimelineEntries reads there, in body order. Blocks start outside timeline detail runs, so- * each entry is read whole.+ * with the entries parseTimelineEntries reads there, in body order, and their count. Blocks start outside timeline+ * detail runs, so each entry is read whole. With `within` and `entries: false` the result holds at most one key per+ * stored row, not one per entry.*/-export async function segmentedTimelineText(engine: Pick<BrainEngine, 'executeRaw' | 'readSegmentTexts'>, page: { id: number; slug: string; source_id?: string }):- Promise<TimelineTextKeys & { entries: ReturnType<typeof parseTimelineEntries> }> {+export async function segmentedTimelineText(engine: Pick<BrainEngine, 'executeRaw' | 'readSegmentTexts'>, page: { id: number; slug: string; source_id?: string },+ opts: SegmentedTimelineOptions = {}): Promise<TimelineTextKeys & { entries: ReturnType<typeof parseTimelineEntries>; parsed: number; runs: Set<string> }> {const kept = new Set<string>();const superseded = new Set<string>();+ const runs = new Set<string>();const entries: ReturnType<typeof parseTimelineEntries> = [];- for await (const block of bodyBlocks(engine as BrainEngine, page)) {- for (const key of markdownTimelineKeys(block.text, page.slug)) kept.add(key);- for (const entry of supersededCitationTimeline(block.text)) superseded.add(tupleKey(entry));- entries.push(...detachedValue(parseTimelineEntries(block.text)));+ const { within } = opts;+ let parsed = 0;+ for await (const block of bodyBlocks(engine as BrainEngine, page, { runKeys: runs, ...(opts.stop ? { stop: opts.stop } : {}) })) {+ for (const key of markdownTimelineKeys(block.text, page.slug)) if (!within) kept.add(key); else within.mark(key);+ for (const entry of supersededCitationTimeline(block.text)) {+ const key = tupleKey(entry);+ if (!within || within.has(key)) superseded.add(key);+ }+ const read = parseTimelineEntries(block.text);+ parsed += read.length;+ if (opts.entries !== false) entries.push(...detachedValue(read));+ opts.onBlock?.(block.text);}- return { kept, superseded, entries };+ return { kept: within ? { has: key => within.marked(key) } : kept, superseded, ...(within ? { within } : {}), runs, entries, parsed };}+/** A page's stored non-event timeline row as reconciliation reads it (`date` is `YYYY-MM-DD`). */+export type StoredTimelineTuple = TimelineTuple & { id: number; detail: string | null };++function storedTimelineRows(engine: Pick<BrainEngine, 'executeRaw'>, sourceId: string, slug: string): Promise<StoredTimelineTuple[]> {+ return engine.executeRaw<StoredTimelineTuple>(+ `SELECT t.id, to_char(t.date, 'YYYY-MM-DD') AS date, t.source, t.summary, t.detail FROM timeline_entries t+ JOIN pages p ON p.id = t.page_id+ WHERE p.source_id = $1 AND p.slug = $2 AND t.event_page_id IS NULL`, [sourceId, slug]);+}++const STORED_ROWS_PAGE = 5_000;+/**- * The stored text of a retained segmented generation (a segmented page_versions row: its body columns are NULL) as- * `${compiled_truth}\n${timeline}` in blocks cut as bodyBlocks cuts the live body (a run of forced cuts is one block),- * read from the generation's manifest rows, so a page demoted inline since still yields its segmented versions.- * Counts its bytes and units in segmentedPassWork.+ * Each stored non-event timeline row of a page (`date_text` is `date::text`, unrecordedCanonicalTimeline's form),+ * STORED_ROWS_PAGE rows at a time by id, so a page with many rows is never held as one array.*/-async function* retainedGenerationBlocks(engine: Pick<BrainEngine, 'readManifest' | 'readSegmentTexts'>,- page: { id: number; slug: string; sourceId: string }, generation: number): AsyncIterable<string> {- const rows = await engine.readManifest(page.id, { generation });- for (const [n, region] of (['truth', 'timeline'] as const).entries()) {- if (n > 0) yield '\n';- const own = rows.filter(row => row.region === region);- for (let i = 0; i < own.length;) {- let j = i;- while (j + 1 < own.length && own[j]!.cutKind === 'forced') j++;- const run = own.slice(i, j + 1);- i = j + 1;- const bytes = run.reduce((sum, row) => sum + row.byteLen, 0);- if (bytes > BLOCK_MAX_BYTES) throw blockTooLargeError(page.slug, page.sourceId, bytes);- const texts = await engine.readSegmentTexts(page.sourceId, run.map(row => row.sha256));- const text = Buffer.concat(run.map(row => {- const bytes = texts.get(Buffer.from(row.sha256).toString('hex'));- if (bytes === undefined) throw new Error(`Segment text of page ${page.id} generation ${generation} is missing.`);- return bytes;- })).toString('utf8');- segmentedPassWork.bytes += bytes;- segmentedPassWork.blocks += text.length;- yield text;- }+export async function eachStoredTimelineRow(engine: Pick<BrainEngine, 'executeRaw'>, pageId: number,+ fn: (row: StoredTimelineTuple & { date_text: string }) => void): Promise<void> {+ for (let after = 0; ;) {+ const rows = await engine.executeRaw<StoredTimelineTuple & { date_text: string }>(+ `SELECT id, to_char(date, 'YYYY-MM-DD') AS date, date::text AS date_text, source, summary, detail FROM timeline_entries+ WHERE page_id = $1 AND event_page_id IS NULL AND id > $2 ORDER BY id LIMIT $3`, [pageId, after, STORED_ROWS_PAGE]);+ for (const row of rows) fn(row);+ if (rows.length < STORED_ROWS_PAGE) return;+ after = Number(rows[rows.length - 1]!.id);}}-/** A page's stored non-event timeline row as reconciliation reads it (`date` is `YYYY-MM-DD`). */-export type StoredTimelineTuple = TimelineTuple & { id: number; detail: string | null };+/**+ * The stored rows of a page a segmented read of it can retract: those whose key `keys` (segmentedTimelineText with+ * `within`) neither keeps nor leaves out of `within`, streamed (eachStoredTimelineRow).+ */+export async function unkeptTimelineRows(engine: Pick<BrainEngine, 'executeRaw'>, pageId: number, keys: TimelineTextKeys): Promise<StoredTimelineTuple[]> {+ const out: StoredTimelineTuple[] = [];+ await eachStoredTimelineRow(engine, pageId, ({ date_text: _text, ...row }) => {+ const key = tupleKey(row);+ if (!keys.kept.has(key) && (!keys.within || keys.within.has(key))) out.push(row);+ });+ return out;+}/*** Reconcile a page's timeline rows with its current text: retract every row@@ -201,7 +290,10 @@ export type StoredTimelineTuple = TimelineTuple & { id: number; detail: string |* does (a corrected or deleted dated bullet, however many edits ago). Rows no* version of the page ever produced (enrichment, meeting fan-out, inferred* anchors) and event-page projections are never touched. The page_versions- * scan only runs when the page holds a row the current text does not produce.+ * scan only runs when the page holds a row the current text does not produce,+ * and keeps only the keys of those rows. A retained segmented generation is read+ * run by run (retainedGenerationBlocks), skipping each run whose key the live body+ * or an earlier generation already read; `stop` is asked before each of its segment reads.* Returns the orphaned rows; they are deleted unless `dryRun`. `storedRows`* is the caller's own read of those rows (a batched walk), used instead of reading them here.* `current` is the page text, or its keys when the caller read a segmented body (segmentedTimelineText).@@ -211,28 +303,30 @@ export async function retractRemovedTimelineEntries(slug: string,sourceId: string,current: string | TimelineTextKeys,- opts: { dryRun?: boolean; storedRows?: ReadonlyArray<StoredTimelineTuple> } = {},+ opts: { dryRun?: boolean; storedRows?: ReadonlyArray<StoredTimelineTuple>; stop?: () => boolean } = {},): Promise<Array<TimelineTuple & { id: number }>> {const kept = typeof current === 'string' ? markdownTimelineKeys(current, slug) : current.kept;- const rows = opts.storedRows ?? await engine.executeRaw<StoredTimelineTuple>(- `SELECT t.id, to_char(t.date, 'YYYY-MM-DD') AS date, t.source, t.summary, t.detail FROM timeline_entries t- JOIN pages p ON p.id = t.page_id- WHERE p.source_id = $1 AND p.slug = $2 AND t.event_page_id IS NULL`, [sourceId, slug]);- const extra = rows.filter(row => !kept.has(tupleKey(row)));+ const within = typeof current === 'string' ? undefined : current.within;+ const rows = opts.storedRows ?? await storedTimelineRows(engine, sourceId, slug);+ const extra = rows.filter(row => !kept.has(tupleKey(row)) && (!within || within.has(tupleKey(row))));if (!extra.length) return [];const versions = await engine.executeRaw<{ compiled_truth: string | null; timeline: string | null; body_storage: string; page_id: number; generation: number | null }>(`SELECT DISTINCT v.compiled_truth, v.timeline, v.body_storage, v.page_id, v.body_generation AS generation FROM page_versions v JOIN pages p ON p.id = v.page_idWHERE p.source_id = $1 AND p.slug = $2`, [sourceId, slug]);+ const wanted = new Set(extra.map(tupleKey));const produced = new Set<string>();// #6226: rows the older citation reading filed for this text or a stored version.- const superseded = new Set(typeof current === 'string' ? supersededCitationTimeline(current).map(tupleKey) : current.superseded);+ const superseded = new Set(typeof current === 'string' ? supersededCitationTimeline(current).map(tupleKey)+ : [...wanted].filter(key => current.superseded.has(key)));const addText = (text: string) => {- for (const key of markdownTimelineKeys(text, slug)) produced.add(key);- for (const entry of supersededCitationTimeline(text)) superseded.add(tupleKey(entry));+ for (const key of markdownTimelineKeys(text, slug)) if (wanted.has(key)) produced.add(key);+ for (const entry of supersededCitationTimeline(text)) if (wanted.has(tupleKey(entry))) superseded.add(tupleKey(entry));};+ const seen = new Set(typeof current === 'string' ? [] : current.runs ?? []);for (const version of versions) {if (version.body_storage !== 'segmented') { addText(`${version.compiled_truth}\n${version.timeline ?? ''}`); continue; }- for await (const block of retainedGenerationBlocks(engine, { id: Number(version.page_id), slug, sourceId }, Number(version.generation))) addText(block);+ for await (const block of retainedGenerationBlocks(engine, { id: Number(version.page_id), slug, sourceId }, Number(version.generation),+ { seen, ...(opts.stop ? { stop: opts.stop } : {}) })) addText(block);}const orphans = extra.filter(row => produced.has(tupleKey(row)) || (superseded.has(tupleKey(row)) && hasExtractorDetail(row))).map(({ detail: _detail, ...row }) => row);@@ -243,6 +337,20 @@ export async function retractRemovedTimelineEntries(return orphans;}+/**+ * Retract a page's removed rows against its stored text: a segmented body is read block by block, keeping only the+ * keys of its stored rows (segmentedTimelineText `within`, a TimelineKeySet), and the rows are streamed, not held.+ */+async function retractStoredPage(engine: BrainEngine, page: { id: number; slug: string; source_id: string; compiled_truth: string; timeline: string | null; body_storage: string },+ opts: { dryRun?: boolean }) {+ if (page.body_storage !== 'segmented') return retractRemovedTimelineEntries(engine, page.slug, page.source_id, `${page.compiled_truth}\n${page.timeline ?? ''}`, opts);+ const within = new TimelineKeySet();+ await eachStoredTimelineRow(engine, page.id, row => within.add(tupleKey(row)));+ if (!within.size) return [];+ const keys = await segmentedTimelineText(engine, page, { within, entries: false });+ return retractRemovedTimelineEntries(engine, page.slug, page.source_id, keys, { ...opts, storedRows: await unkeptTimelineRows(engine, page.id, keys) });+}+export interface TimelineOrphanPruneResult {pagesScanned: number;orphans: number;@@ -263,8 +371,7 @@ async function retractCoordinated(engine: BrainEngine, pageId: number, slug: strconst [page] = await tx.executeRaw<{ compiled_truth: string; timeline: string | null; body_storage: string }>('SELECT compiled_truth, timeline, body_storage FROM pages WHERE id = $1 AND deleted_at IS NULL', [pageId]);if (!page) return [];- return retractRemovedTimelineEntries(tx, slug, sourceId, page.body_storage === 'segmented'- ? await segmentedTimelineText(tx, { id: pageId, slug, source_id: sourceId }) : `${page.compiled_truth}\n${page.timeline ?? ''}`);+ return retractStoredPage(tx, { ...page, id: pageId, slug, source_id: sourceId }, {});}, attribution));}@@ -294,8 +401,7 @@ export async function pruneTimelineOrphans(for (const page of pages) {const orphans = opts.coordinated && !opts.dryRun? await retractCoordinated(engine, page.id, page.slug, page.source_id)- : await retractRemovedTimelineEntries(engine, page.slug, page.source_id, page.body_storage === 'segmented'- ? await segmentedTimelineText(engine, page) : `${page.compiled_truth}\n${page.timeline ?? ''}`, { dryRun: opts.dryRun });+ : await retractStoredPage(engine, page, { dryRun: opts.dryRun });result.orphans += orphans.length;if (!opts.dryRun) result.removed += orphans.length;for (const row of orphans.slice(0, Math.max(0, 5 - result.examples.length))) {diff --git a/test/large-pages/segmented-facts-forced-lines.test.ts b/test/large-pages/segmented-facts-forced-lines.test.tsnew file mode 100644index 0000000000..c202cead44--- /dev/null+++ b/test/large-pages/segmented-facts-forced-lines.test.ts@@ -0,0 +1,98 @@+/**+ * Wave B PR 2 fix lane H (finding H4): the facts fence view skips forced cuts that fall at a line boundary.+ *+ * 1. Protects: a segmented page cut only by force at line boundaries (short lines, no blank line or heading) and+ * holding no facts marker reads no segment for its facts fence view: no marker holds a newline, so a forced cut+ * after one cannot split a marker. A page of the same lines with a facts fence still gives factsFenceView of its+ * strings (its fence sits in the page's one forced run, which is read whole).+ * 2. Fails when: markerSeqs selects every cut_kind='forced' row, so the view reads every segment of the forced run+ * of a page that has no fence at all.+ * Runs on PGLite, and on Postgres when DATABASE_URL is set. Seams: none; the readSegmentTexts spy wraps the engine+ * method and counts segment texts read (a work count, not time).+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import type { BrainEngine } from '../../src/core/engine.ts';+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';+import { importFromContent } from '../../src/core/import-file.ts';+import { factsFenceView, FACTS_FENCE_BEGIN, FACTS_FENCE_END } from '../../src/core/facts-fence.ts';+import { segmentedFactsFenceView } from '../../src/core/page-body/segment-facts.ts';+import { materializedPage } from '../../src/core/persistence/segmented-apply.ts';+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';+import { testBackends } from '../helpers/test-backends.ts';++const MB = 1024 * 1024;++/** About `bytes` of lines of at most 49 bytes: no blank line, no heading, so every cut is forced at a line boundary. */+function shortLines(bytes: number, from = 0): string {+ const lines: string[] = [];+ let size = 0;+ for (let i = from; size < bytes; i++) {+ const line = 'line ' + String(i).padStart(8, '0') + ' acme-example noted the plan\n';+ lines.push(line);+ size += line.length;+ }+ return lines.join('');+}++const HEADER = '| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |\n'+ + '|---|-------|------|------------|------------|------------|------------|-------------|--------|---------|\n';+const FENCE = FACTS_FENCE_BEGIN + '\n' + HEADER + '| 1 | Works at Beta Example | fact | 0.9 | world | high | 2022-01-01 | | notes | |\n' + FACTS_FENCE_END + '\n';++for (const kind of testBackends()) {+ describe('facts fence view over forced cuts at line boundaries (' + kind + ')', () => {+ let engine: BrainEngine;+ let close: () => Promise<void>;++ beforeAll(async () => {+ if (kind === 'postgres') {+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!);+ engine = pg.engine;+ close = pg.close;+ } else {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ close = () => engine.disconnect();+ }+ await engine.setConfig('pages.segmented_storage', 'on');+ }, 120_000);++ afterAll(async () => { await close(); });++ const view = async (slug: string) => {+ const p = await engine.getPage(slug, { sourceId: 'default' });+ expect((p as { body_storage?: string } | null)?.body_storage).toBe('segmented');+ const [cuts] = await engine.executeRaw<{ forced: number; rows: number }>(+ "SELECT count(*) FILTER (WHERE cut_kind='forced')::int AS forced, count(*)::int AS rows FROM page_body_manifest WHERE page_id=$1 AND gen_to IS NULL AND staging_id IS NULL", [p!.id]);+ const original = engine.readSegmentTexts.bind(engine);+ let reads = 0;+ engine.readSegmentTexts = (async (sourceId: string, shas: Uint8Array[]) => { reads += shas.length; return original(sourceId, shas); }) as BrainEngine['readSegmentTexts'];+ try {+ return { result: await segmentedFactsFenceView(engine, { id: p!.id, slug, source_id: 'default' }), reads, forced: cuts!.forced, rows: cuts!.rows, page: p! };+ } finally {+ delete (engine as { readSegmentTexts?: unknown }).readSegmentTexts;+ }+ };++ test('a page with no facts marker, cut only by force at line boundaries, reads no segment', async () => {+ const content = '---\ntitle: Short lines\ntype: note\n---\n' + shortLines(3 * MB);+ expect((await importFromContent(engine, 'notes/forced-no-fence', content, { sourceId: 'default', noEmbed: true })).status).toBe('imported');+ const { result, reads, forced, rows, page } = await view('notes/forced-no-fence');+ console.log('[facts-forced-lines] ' + kind + ' no fence: ' + reads + ' segment reads of ' + rows + ' rows (' + forced + ' forced)');+ expect(forced).toBeGreaterThanOrEqual(2);+ expect(result).toEqual(factsFenceView(await materializedPage(engine, page)));+ expect(reads).toBe(0);+ }, 300_000);++ test('the same lines with a facts fence still give the strings view', async () => {+ const content = '---\ntitle: Short lines with a fence\ntype: note\n---\n' + shortLines(2 * MB) + FENCE + shortLines(2 * MB, 1_000_000);+ expect((await importFromContent(engine, 'notes/forced-fence', content, { sourceId: 'default', noEmbed: true })).status).toBe('imported');+ const { result, reads, rows, page } = await view('notes/forced-fence');+ console.log('[facts-forced-lines] ' + kind + ' fence: ' + reads + ' segment reads of ' + rows + ' rows');+ expect(result).toEqual(factsFenceView(await materializedPage(engine, page)));+ expect(result.body.facts).toHaveLength(1);+ expect(reads).toBeGreaterThan(0);+ expect(reads).toBeLessThanOrEqual(rows);+ }, 300_000);+ });+}diff --git a/test/large-pages/segmented-retained-blocks.test.ts b/test/large-pages/segmented-retained-blocks.test.tsnew file mode 100644index 0000000000..c15d71ed32--- /dev/null+++ b/test/large-pages/segmented-retained-blocks.test.ts@@ -0,0 +1,106 @@+/**+ * Wave B PR 2 fix lane H (finding H1): timeline retraction reads retained segmented generations with the live body's+ * block cutter, and reads each stored run once.+ *+ * 1. Protects: a retained generation is cut into blocks as bodyBlocks cuts the live body (a forced cut at a line+ * boundary ends a block), so a page of dated bullets over BLOCK_MAX_BYTES with a segmented version is pruned, not+ * refused; and a run of a retained generation whose key the live body (or an earlier generation) already read is+ * skipped, so pruning a page with several versions that share their compiled truth reads that truth once.+ * 2. Fails when: retainedGenerationBlocks joins every run of forced cuts into one block (page_body_segmented on the+ * 9 MiB timeline), or reads every retained generation in full (the bytes read grow with the version count).+ * Runs on PGLite, and on Postgres when DATABASE_URL is set. Seams: segmentedPassWork.bytes (a work count, not time).+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import type { BrainEngine } from '../../src/core/engine.ts';+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';+import { importFromContent } from '../../src/core/import-file.ts';+import { extractTimelineFromDB } from '../../src/commands/extract-timeline-db.ts';+import { pruneTimelineOrphans } from '../../src/core/timeline-extract.ts';+import { BLOCK_MAX_BYTES, segmentedPassWork } from '../../src/core/page-body/segment-blocks.ts';+import { conversationBody } from '../helpers/conversation-page.ts';+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';+import { testBackends } from '../helpers/test-backends.ts';++const MB = 1024 * 1024;++/** A short truth, then about `bytes` of dated bullets with no blank line (every cut forced), the first one `first`. */+function bulletPage(bytes: number, first: string): string {+ const bullets = [first + '\n'];+ let size = first.length + 1;+ for (let i = 0; size < bytes; i++) {+ const line = '- **20' + String(10 + (i % 15)) + '-0' + (1 + (i % 9)) + '-1' + (i % 10) + '** | Met acme-example about item ' + i + '\n';+ bullets.push(line);+ size += line.length;+ }+ return '---\ntitle: Bullet timeline\ntype: note\n---\nA short truth.\n\n<!-- timeline -->\n\n' + bullets.join('');+}++/** About 2.4 MiB of conversation in the truth, then the dated bullets. */+const versionedPage = (bullets: string[]) => '---\ntype: note\ntitle: Versions\n---\n\n' + conversationBody(1_200_000, { seed: 51 }) + '\n\n'+ + conversationBody(1_200_000, { seed: 52 }) + '\n\n## Timeline\n\n' + bullets.join('\n') + '\n';++const summaries = async (engine: BrainEngine, slug: string) => (await engine.executeRaw<{ summary: string }>(+ 'SELECT t.summary FROM timeline_entries t JOIN pages p ON p.id=t.page_id WHERE p.slug=$1 AND t.event_page_id IS NULL ORDER BY t.summary', [slug])).map(row => row.summary);++for (const kind of testBackends()) {+ describe('timeline retraction over retained generations (' + kind + ')', () => {+ let engine: BrainEngine;+ let close: () => Promise<void>;++ beforeAll(async () => {+ if (kind === 'postgres') {+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!);+ engine = pg.engine;+ close = pg.close;+ } else {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ close = () => engine.disconnect();+ }+ await engine.setConfig('pages.segmented_storage', 'on');+ }, 120_000);++ afterAll(async () => { await close(); });++ test('a 9 MiB timeline of dated bullets with a segmented version is pruned, not refused', async () => {+ const slug = 'notes/bullets-versioned';+ const removed = '- **2009-01-01** | A bullet the next version drops';+ const older = bulletPage(9 * MB, removed);+ expect(Buffer.byteLength(older)).toBeGreaterThan(BLOCK_MAX_BYTES);+ expect((await importFromContent(engine, slug, older, { sourceId: 'default', noEmbed: true })).status).toBe('imported');+ await extractTimelineFromDB(engine, { dryRun: false, jsonMode: false, quiet: true, sourceIdFilter: 'default', slugs: [slug] });+ expect(await summaries(engine, slug)).toContain('A bullet the next version drops');+ expect((await importFromContent(engine, slug, older.replace(removed + '\n', '- **2009-01-02** | Its replacement\n'), { sourceId: 'default', noEmbed: true })).status).toBe('imported');+ const [versions] = await engine.executeRaw<{ n: number }>(+ "SELECT count(*)::int AS n FROM page_versions v JOIN pages p ON p.id=v.page_id WHERE p.slug=$1 AND v.body_storage='segmented'", [slug]);+ expect(versions!.n).toBeGreaterThanOrEqual(1);+ const pruned = await pruneTimelineOrphans(engine, { sourceId: 'default', dryRun: false }).then(r => r, (e: unknown) => ({ error: (e as { code?: string }).code ?? String(e) }));+ console.log('[retained-blocks] ' + kind + ' 9 MiB bullets: ' + JSON.stringify(pruned));+ expect(pruned).toMatchObject({ removed: 1 });+ expect(await summaries(engine, slug)).not.toContain('A bullet the next version drops');+ }, 900_000);++ test('versions that share their compiled truth: the prune reads that truth once, not once per version', async () => {+ const slug = 'notes/shared-truth';+ await engine.executeRaw('UPDATE pages SET deleted_at = now() WHERE deleted_at IS NULL');+ const steps = [['- **2026-03-04** | Kickoff', '- **2026-04-05** | Pricing review'], ['- **2026-03-04** | Kickoff'],+ ['- **2026-03-04** | Kickoff', '- **2026-05-06** | Launch'], ['- **2026-03-04** | Kickoff', '- **2026-05-06** | Launch', '- **2026-06-07** | Retro']];+ for (const [n, bullets] of steps.entries()) {+ expect((await importFromContent(engine, slug, versionedPage(bullets), { sourceId: 'default', noEmbed: true })).status).toBe('imported');+ if (n === 0) await extractTimelineFromDB(engine, { dryRun: false, jsonMode: false, quiet: true, sourceIdFilter: 'default', slugs: [slug] });+ }+ const [live] = await engine.executeRaw<{ id: number; body_bytes: number; body_storage: string }>('SELECT id, body_bytes, body_storage FROM pages WHERE slug=$1', [slug]);+ expect(live!.body_storage).toBe('segmented');+ const versions = await engine.executeRaw<{ body_bytes: number }>("SELECT DISTINCT body_generation, body_bytes FROM page_versions WHERE page_id=$1 AND body_storage='segmented'", [live!.id]);+ expect(versions.length).toBeGreaterThanOrEqual(3);+ const before = segmentedPassWork.bytes;+ const pruned = await pruneTimelineOrphans(engine, { sourceId: 'default', dryRun: false });+ const read = segmentedPassWork.bytes - before;+ console.log('[retained-blocks] ' + kind + ' shared truth: ' + read + ' bytes read for a ' + live!.body_bytes + '-byte page with ' + versions.length + ' retained generations');+ expect(pruned.removed).toBe(1);+ expect(await summaries(engine, slug)).toEqual(['Kickoff']);+ expect(read).toBeLessThan(2 * Number(live!.body_bytes));+ }, 900_000);+ });+}diff --git a/test/large-pages/segmented-sweep-deferral.test.ts b/test/large-pages/segmented-sweep-deferral.test.tsnew file mode 100644index 0000000000..76cce250ea--- /dev/null+++ b/test/large-pages/segmented-sweep-deferral.test.ts@@ -0,0 +1,183 @@+/**+ * Wave B PR 2 fix lane H (finding H2): the sweep's links/timeline pass over deferred and budgeted segmented pages.+ *+ * 1. Protects: (a) a deferred segmented page is left out of the pass's page query, so the pages behind it (older,+ * inline ones included) are still reached when the newest batchLimit stale pages are deferred; (b) a segmented+ * page that stops after other work of the sweep spent the budget is left for the next sweep, not deferred until+ * it changes, and the next sweep extracts it; (c) on a managed brain the timeline publication's planning read+ * asks the sweep budget before each segment, so a page whose publication does not fit stops there and is deferred;+ * one that fits is read twice by the publication (its plan, the coordinator's apply), each read once.+ * 2. Fails when: (a) deferred pages are filtered after LIMIT batchLimit (sweep 2 gives linksExtracted 0 and only+ * segmented_page_deferred); (b) any stopped page is deferred (the small page stays unextracted after a sweep with+ * budget to spare); (c) publishManagedPageTimeline reads the page about four times with no budget, so the pass+ * reads far past it, and seven times the page with budget to spare instead of five.+ * Seams: the sweep's clock (opts.now) advances with segmentedPassWork.bytes, plus a fixed charge per inline page+ * read through a getPage wrapper, so the budget is a work budget and no machine load moves it.+ * Runs on PGLite, and on Postgres when DATABASE_URL is set.+ */+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import { mkdirSync, mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import type { BrainEngine } from '../../src/core/engine.ts';+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';+import { importFromContent } from '../../src/core/import-file.ts';+import { runMaintenanceSweep, _resetDeferredSegmentedPagesForTests } from '../../src/core/sweep.ts';+import { segmentedPassWork } from '../../src/core/page-body/segment-blocks.ts';+import { SEGMENT_MAX_BYTES } from '../../src/core/page-body/limits.ts';+import { claimWorktree } from '../../src/core/persistence/ownership.ts';+import { disposePersistenceConsumer } from '../../src/core/persistence/service.ts';+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';+import { testBackends } from '../helpers/test-backends.ts';+import { withEnv } from '../helpers/with-env.ts';++const MB = 1024 * 1024;+/** Clock ms per segmented byte read. */+const BYTES_PER_MS = 1024;++/** About `bytes` of paragraphs (the first names the person page), then `bullets` dated bullets in the timeline. */+function segmentedPage(title: string, bytes: number, bullets: number): string {+ const paras: string[] = [];+ let size = 0;+ for (let i = 0; size < bytes; i++) {+ const p = 'Paragraph ' + i + ' notes that the widget plan moved again; the team met ' + (i === 0 ? '[[people/alice-example]]' : 'the vendor') + ' to review the ' + 'rollout '.repeat(40) + '\n\n';+ paras.push(p);+ size += p.length;+ }+ const timeline = Array.from({ length: bullets }, (_, i) => '- **2025-0' + (1 + (i % 9)) + '-1' + (i % 10) + '** | Review ' + i + ' of the widget plan').join('\n');+ return '---\ntype: note\ntitle: ' + title + '\n---\n' + paras.join('') + '<!-- timeline -->\n\n' + timeline + '\n';+}++const inlinePage = (i: number) => '---\ntype: note\ntitle: Inline ' + i + '\n---\nMet [[people/alice-example]] about item ' + i + '.\n';++for (const kind of testBackends()) {+ describe('sweep deferral of segmented pages (' + kind + ')', () => {+ let engine: BrainEngine;+ let close: () => Promise<void>;+ let start = 0;+ let charged = 0;+ const now = () => start + segmentedPassWork.bytes / BYTES_PER_MS + charged;+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-sweep-deferral-'));++ beforeAll(async () => {+ if (kind === 'postgres') {+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!);+ engine = pg.engine;+ close = pg.close;+ } else {+ engine = new PGLiteEngine();+ await engine.connect({ database_path: join(dir, 'db') });+ await engine.initSchema();+ close = () => engine.disconnect();+ }+ await engine.setConfig('pages.segmented_storage', 'on');+ await engine.putPage('people/alice-example', { type: 'person', title: 'Alice Example', compiled_truth: 'Fixture.', timeline: '', frontmatter: {} }, { sourceId: 'default' });+ }, 120_000);++ afterAll(async () => {+ await disposePersistenceConsumer(engine);+ await close();+ rmSync(dir, { recursive: true, force: true });+ });++ beforeEach(async () => {+ _resetDeferredSegmentedPagesForTests();+ segmentedPassWork.bytes = 0;+ charged = 0;+ start = 1_000_000;+ // Every page written so far counts as extracted (links_extracted_at a day ahead), so each test sweeps its own pages.+ await engine.executeRaw("UPDATE pages SET links_extracted_at = now() + interval '1 day'");+ });++ /** The sweep's stamp: a links_extracted_at the sweep wrote (not the day-ahead one beforeEach set), or null. */+ const stamped = async (slug: string, sourceId = 'default') => (await engine.executeRaw<{ at: unknown }>(+ "SELECT links_extracted_at AS at FROM pages WHERE slug=$1 AND source_id=$2 AND links_extracted_at < now() + interval '1 hour'", [slug, sourceId]))[0]?.at ?? null;+ const reasons = (r: { skipped: Array<{ reason: string }> }) => r.skipped.map(s => s.reason);++ test('(a) a deferred page does not take the batch slots of the older pages behind it', async () => {+ expect((await importFromContent(engine, 'notes/older-inline', inlinePage(0), { sourceId: 'default', noEmbed: true })).status).toBe('imported');+ await Bun.sleep(5);+ expect((await importFromContent(engine, 'notes/deferred-large', segmentedPage('Deferred large', 6 * MB, 50), { sourceId: 'default', noEmbed: true })).status).toBe('imported');+ const budgetMs = (2 * MB) / BYTES_PER_MS;+ const first = await runMaintenanceSweep(engine, { sourceId: 'default', budgetMs, batchLimit: 1, now });+ expect(reasons(first)).toContain('budget_deferred:segmented_page');+ expect(await stamped('notes/deferred-large')).toBeNull();++ segmentedPassWork.bytes = 0;+ const second = await runMaintenanceSweep(engine, { sourceId: 'default', budgetMs, batchLimit: 1, now });+ console.log('[sweep-deferral] ' + kind + ' (a) second sweep: ' + JSON.stringify({ links: second.linksExtracted, skipped: second.skipped }));+ expect(reasons(second)).toContain('segmented_page_deferred');+ expect(segmentedPassWork.bytes).toBe(0);+ expect(second.linksExtracted).toBeGreaterThanOrEqual(1);+ expect(await stamped('notes/older-inline')).not.toBeNull();+ }, 300_000);++ test('(b) a page stopped after inline work spent the budget is left for the next sweep, which extracts it', async () => {+ for (let i = 1; i <= 3; i++) expect((await importFromContent(engine, 'notes/busy-inline-' + i, inlinePage(i), { sourceId: 'default', noEmbed: true })).status).toBe('imported');+ expect((await importFromContent(engine, 'notes/small-segmented', segmentedPage('Small segmented', 2 * MB, 20), { sourceId: 'default', noEmbed: true })).status).toBe('imported');+ const budgetMs = (10 * MB) / BYTES_PER_MS;+ const perInline = (budgetMs - (MB / 2) / BYTES_PER_MS) / 3;+ const getPage = engine.getPage.bind(engine);+ engine.getPage = (async (slug: string, opts?: Parameters<BrainEngine['getPage']>[1]) => {+ if (slug.startsWith('notes/busy-inline-')) charged += perInline;+ return getPage(slug, opts);+ }) as BrainEngine['getPage'];+ try {+ const first = await runMaintenanceSweep(engine, { sourceId: 'default', budgetMs, batchLimit: 20, now });+ console.log('[sweep-deferral] ' + kind + ' (b) first sweep: ' + segmentedPassWork.bytes + ' bytes, ' + JSON.stringify({ links: first.linksExtracted, skipped: first.skipped }));+ for (let i = 1; i <= 3; i++) expect(await stamped('notes/busy-inline-' + i)).not.toBeNull();+ expect(await stamped('notes/small-segmented')).toBeNull();+ expect(reasons(first)).not.toContain('budget_deferred:segmented_page');++ segmentedPassWork.bytes = 0;+ charged = 0;+ const second = await runMaintenanceSweep(engine, { sourceId: 'default', budgetMs, batchLimit: 20, now });+ console.log('[sweep-deferral] ' + kind + ' (b) second sweep: ' + segmentedPassWork.bytes + ' bytes, ' + JSON.stringify({ links: second.linksExtracted, skipped: second.skipped }));+ expect(reasons(second)).not.toContain('segmented_page_deferred');+ expect(await stamped('notes/small-segmented')).not.toBeNull();+ } finally {+ delete (engine as { getPage?: unknown }).getPage;+ }+ }, 300_000);++ test('(c) managed: the timeline publication reads under the sweep budget and a page that does not fit is deferred', async () => {+ const root = join(dir, 'brain-' + kind);+ mkdirSync(root, { recursive: true });+ const sourceId = 'deferral-' + kind;+ await withEnv({ GBRAIN_HOME: join(dir, 'home-' + kind), GBRAIN_AUDIT_DIR: join(dir, 'audit-' + kind) }, async () => {+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', [sourceId, root]);+ await engine.putPage('people/alice-example', { type: 'person', title: 'Alice Example', compiled_truth: 'Fixture.', timeline: '', frontmatter: {} }, { sourceId });+ expect((await importFromContent(engine, 'notes/managed-large', segmentedPage('Managed large', 3 * MB, 40), { sourceId, noEmbed: true })).status).toBe('imported');+ const [page] = await engine.executeRaw<{ body_bytes: number; body_storage: string }>('SELECT body_bytes, body_storage FROM pages WHERE slug=$1 AND source_id=$2', ['notes/managed-large', sourceId]);+ expect(page!.body_storage).toBe('segmented');+ const bytes = Number(page!.body_bytes);+ await engine.executeRaw("UPDATE pages SET links_extracted_at = now() + interval '1 day' WHERE source_id=$1 AND slug='people/alice-example'", [sourceId]);+ await claimWorktree(engine, sourceId, root);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ try {+ // Room for the extraction's three reads and half of the publication's planning read.+ const budgetMs = (3.5 * bytes) / BYTES_PER_MS;+ const r = await runMaintenanceSweep(engine, { sourceId, budgetMs, batchLimit: 20, now });+ console.log('[sweep-deferral] ' + kind + ' (c) managed, over budget: ' + segmentedPassWork.bytes + ' bytes for a ' + bytes + '-byte page, ' + JSON.stringify({ timeline: r.timelineExtracted, skipped: r.skipped }));+ expect(reasons(r)).not.toContain('links_timeline_error');+ expect(reasons(r)).not.toContain('timeline_publish_failed');+ expect(segmentedPassWork.bytes).toBeLessThanOrEqual(3.5 * bytes + SEGMENT_MAX_BYTES);+ expect(reasons(r)).toContain('budget_deferred:segmented_page');+ expect(await stamped('notes/managed-large', sourceId)).toBeNull();++ // With budget to spare the publication reads the page twice (its plan, then the coordinator's apply).+ _resetDeferredSegmentedPagesForTests();+ segmentedPassWork.bytes = 0;+ const fits = await runMaintenanceSweep(engine, { sourceId, budgetMs: (100 * bytes) / BYTES_PER_MS, batchLimit: 20, now });+ console.log('[sweep-deferral] ' + kind + ' (c) managed, fits: ' + segmentedPassWork.bytes + ' bytes (' + (segmentedPassWork.bytes / bytes).toFixed(2) + ' reads), ' + JSON.stringify({ timeline: fits.timelineExtracted, skipped: fits.skipped }));+ expect(fits.timelineExtracted).toBe(40);+ expect(await stamped('notes/managed-large', sourceId)).not.toBeNull();+ expect(segmentedPassWork.bytes).toBeLessThanOrEqual(5 * bytes);+ } finally {+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ }+ });+ }, 300_000);+ });+}diff --git a/test/large-pages/segmented-timeline-heap.test.ts b/test/large-pages/segmented-timeline-heap.test.tsnew file mode 100644index 0000000000..a3f7b66b02--- /dev/null+++ b/test/large-pages/segmented-timeline-heap.test.ts@@ -0,0 +1,135 @@+/**+ * Wave B PR 2 fix lane H (finding H3): the maintenance timeline passes over a segmented page compare its blocks+ * against the page's stored timeline rows as they stream, instead of keeping every entry the body yields.+ *+ * 1. Protects: on an 18 MiB page of dated bullets whose rows are all stored, the prune pass (timeline retraction) and+ * the managed publication's plan (gbrain extract timeline --source db on a managed brain, the sweep's publication)+ * keep, while they read the body, only what differs from the stored rows: the heap after a full collection, sampled+ * before each segment read, stays under the page's bytes: one key digest per stored row (TimelineKeySet), not every+ * parsed entry, key and canonical entry (2.4-7.9 MiB held at 18 MiB, against 22-51 MiB before).+ * 2. Fails when: segmentedTimelineText keeps every parsed entry and every key, and storedCanonicalTimeline every+ * canonical entry, until the plan ends (the heap held grows to several times the page).+ * Runs on PGLite, and on Postgres when DATABASE_URL is set. Seams: the readSegmentTexts spy samples the heap after+ * Bun.gc(true) (a heap sample, not time).+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { mkdirSync, mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import type { BrainEngine } from '../../src/core/engine.ts';+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';+import { importFromContent } from '../../src/core/import-file.ts';+import { extractTimelineFromDB } from '../../src/commands/extract-timeline-db.ts';+import { pruneTimelineOrphans } from '../../src/core/timeline-extract.ts';+import { claimWorktree } from '../../src/core/persistence/ownership.ts';+import { disposePersistenceConsumer } from '../../src/core/persistence/service.ts';+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';+import { testBackends } from '../helpers/test-backends.ts';+import { withEnv } from '../helpers/with-env.ts';++const MB = 1024 * 1024;++const jsHeap = () => {+ const usage = process.memoryUsage();+ return usage.heapUsed - usage.arrayBuffers;+};++/** A short truth, then about `bytes` of dated bullets with distinct summaries, no blank line. */+function bulletPage(bytes: number): { content: string; bullets: number } {+ const bullets: string[] = [];+ let size = 0;+ for (let i = 0; size < bytes; i++) {+ const line = '- **20' + String(10 + (i % 15)) + '-0' + (1 + (i % 9)) + '-1' + (i % 10) + '** | Met acme-example about item ' + i + ' of the rollout plan ' + 'and its review '.repeat(8) + '\n';+ bullets.push(line);+ size += line.length;+ }+ return { content: '---\ntitle: Heap timeline\ntype: note\n---\nA short truth.\n\n<!-- timeline -->\n\n' + bullets.join(''), bullets: bullets.length };+}++for (const kind of testBackends()) {+ describe('maintenance timeline heap over a segmented page (' + kind + ')', () => {+ let engine: BrainEngine;+ let close: () => Promise<void>;+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-timeline-heap-'));++ beforeAll(async () => {+ if (kind === 'postgres') {+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!);+ engine = pg.engine;+ close = pg.close;+ } else {+ engine = new PGLiteEngine();+ await engine.connect({ database_path: join(dir, 'db') });+ await engine.initSchema();+ close = () => engine.disconnect();+ }+ await engine.setConfig('pages.segmented_storage', 'on');+ }, 120_000);++ afterAll(async () => {+ await disposePersistenceConsumer(engine);+ await close();+ rmSync(dir, { recursive: true, force: true });+ });++ /**+ * The most JS heap held above the heap before `fn`, sampled after a full collection before each segment read: heap+ * used less ArrayBuffer backing stores, which the drivers' read buffers (grown to the largest segment response) and+ * PGLite's memory dominate; entries, keys and rows are JS objects and strings. `fn` runs once first unmeasured, so+ * the code it loads and compiles is not counted as held.+ */+ async function heldWhile(fn: () => Promise<unknown>): Promise<{ held: number; samples: number }> {+ await fn();+ const original = engine.readSegmentTexts.bind(engine);+ let peak = 0;+ let samples = 0;+ engine.readSegmentTexts = (async (sourceId: string, shas: Uint8Array[]) => {+ Bun.gc(true);+ peak = Math.max(peak, jsHeap());+ samples++;+ return original(sourceId, shas);+ }) as BrainEngine['readSegmentTexts'];+ Bun.gc(true);+ const base = jsHeap();+ try {+ await fn();+ } finally {+ delete (engine as { readSegmentTexts?: unknown }).readSegmentTexts;+ }+ return { held: peak - base, samples };+ }++ test('an 18 MiB page of stored bullets: prune and the managed plan hold less than the page while they read it', async () => {+ const root = join(dir, 'brain');+ mkdirSync(root, { recursive: true });+ const sourceId = 'heap-' + kind;+ await withEnv({ GBRAIN_HOME: join(dir, 'home'), GBRAIN_AUDIT_DIR: join(dir, 'audit') }, async () => {+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', [sourceId, root]);+ const { content, bullets } = bulletPage(18 * MB);+ expect((await importFromContent(engine, 'notes/heap-timeline', content, { sourceId, noEmbed: true })).status).toBe('imported');+ await extractTimelineFromDB(engine, { dryRun: false, jsonMode: false, quiet: true, sourceIdFilter: sourceId, slugs: ['notes/heap-timeline'] });+ const [page] = await engine.executeRaw<{ body_bytes: number; rows: number }>(+ "SELECT p.body_bytes, (SELECT count(*)::int FROM timeline_entries t WHERE t.page_id=p.id) AS rows FROM pages p WHERE p.slug='notes/heap-timeline' AND p.source_id=$1", [sourceId]);+ expect(page!.rows).toBe(bullets);+ const bytes = Number(page!.body_bytes);++ const prune = await heldWhile(() => pruneTimelineOrphans(engine, { sourceId, dryRun: true }));+ console.log('[timeline-heap] ' + kind + ' prune: ' + (prune.held / MB).toFixed(1) + ' MiB held over ' + prune.samples + ' segment reads of a ' + (bytes / MB).toFixed(1) + ' MiB page with ' + bullets + ' rows');++ await claimWorktree(engine, sourceId, root);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ try {+ const plan = await heldWhile(() => extractTimelineFromDB(engine, { dryRun: false, jsonMode: false, quiet: true, sourceIdFilter: sourceId, slugs: ['notes/heap-timeline'] }));+ console.log('[timeline-heap] ' + kind + ' managed plan: ' + (plan.held / MB).toFixed(1) + ' MiB held over ' + plan.samples + ' segment reads');+ expect(plan.samples).toBeGreaterThan(0);+ expect(plan.held).toBeLessThan(bytes);+ } finally {+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ }+ expect(prune.samples).toBeGreaterThan(0);+ expect(prune.held).toBeLessThan(bytes);+ });+ }, 1_200_000);+ });+}diff --git a/test/large-pages/segmented-timeline-retract-versions.test.ts b/test/large-pages/segmented-timeline-retract-versions.test.tsindex 44e2f53d42..2a444c2f53 100644--- a/test/large-pages/segmented-timeline-retract-versions.test.ts+++ b/test/large-pages/segmented-timeline-retract-versions.test.ts@@ -6,8 +6,10 @@* current body no longer holds is retracted (its row was produced by a* version of the page). A segmented page_versions row has NULL body* columns and references a body generation, so the reconciliation streams- * that generation's stored text block by block (each block once: the work- * counter equals the live body's bytes plus the retained generation's).+ * that generation's stored text block by block (each run once, and a run+ * the live body read with the same key not at all: the work counter equals+ * the live body's bytes plus the retained runs read, fewer than the+ * retained generation's bytes).* 2. Fails when: the retraction reads the segmented version's NULL columns* (the text `null\n`), finds no version producing the row, and keeps the* removed bullet's row forever.@@ -21,7 +23,7 @@ import type { BrainEngine } from '../../src/core/engine.ts';import { importFromContent } from '../../src/core/import-file.ts';import { extractTimelineFromDB } from '../../src/commands/extract-timeline-db.ts';import { pruneTimelineOrphans } from '../../src/core/timeline-extract.ts';-import { segmentedPassWork } from '../../src/core/page-body/segment-blocks.ts';+import { retainedGenerationWork, segmentedPassWork } from '../../src/core/page-body/segment-blocks.ts';import { conversationBody } from '../helpers/conversation-page.ts';import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';@@ -65,9 +67,14 @@ describe('timeline retraction over segmented versions', () => {expect(versions.every(v => v.body_storage === 'segmented' && v.compiled_truth === null)).toBe(true);expect([...retained.keys()].every(g => g < Number(live!.body_generation))).toBe(true);const before = segmentedPassWork.bytes;+ retainedGenerationWork.bytes = 0;+ retainedGenerationWork.skipped = 0;const pruned = await pruneTimelineOrphans(engine, { sourceId: 'default', dryRun: false });- expect({ removed: pruned.removed, rows: await rows(), bytes: segmentedPassWork.bytes - before })- .toEqual({ removed: 1, rows: ['Kickoff with the design team'], bytes: Number(live!.body_bytes) + [...retained.values()].reduce((a, b) => a + b, 0) });+ const retainedBytes = [...retained.values()].reduce((a, b) => a + b, 0);+ // Each run of the retained generation is read once, or skipped when the live body read a run with its key.+ expect({ removed: pruned.removed, rows: await rows(), bytes: segmentedPassWork.bytes - before, retained: retainedGenerationWork.bytes + retainedGenerationWork.skipped })+ .toEqual({ removed: 1, rows: ['Kickoff with the design team'], bytes: Number(live!.body_bytes) + retainedGenerationWork.bytes, retained: retainedBytes });+ expect(retainedGenerationWork.bytes).toBeLessThan(retainedBytes);}}, 600_000);});diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txtindex c988f9609f..21fc7b4cbf 100644--- a/test/postgres-unit-arms.txt+++ b/test/postgres-unit-arms.txt@@ -101,6 +101,7 @@ test/large-pages/segmented-embedding-paths.test.tstest/large-pages/segmented-embedding.test.tstest/large-pages/segmented-evidence-read-cost.test.tstest/large-pages/segmented-evidence.test.ts+test/large-pages/segmented-facts-forced-lines.test.tstest/large-pages/segmented-facts-reconcile.test.tstest/large-pages/segmented-file-drift-ledger.test.tstest/large-pages/segmented-file-drift.test.ts@@ -114,12 +115,15 @@ test/large-pages/segmented-prior-view.test.tstest/large-pages/segmented-read-refusals.test.tstest/large-pages/segmented-remember-refusal.test.tstest/large-pages/segmented-repair-scans.test.ts+test/large-pages/segmented-retained-blocks.test.tstest/large-pages/segmented-search-dedup.test.tstest/large-pages/segmented-shrink-below-ceiling.test.tstest/large-pages/segmented-storage-visibility.test.tstest/large-pages/segmented-sweep-budget.test.ts+test/large-pages/segmented-sweep-deferral.test.tstest/large-pages/segmented-switch.test.tstest/large-pages/segmented-think-compile-leads.serial.test.ts+test/large-pages/segmented-timeline-heap.test.tstest/large-pages/segmented-timeline-retract-versions.test.tstest/large-pages/segmented-versions.test.tstest/large-pages/v249-master-reader-compat.test.ts