Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Read a segmented prior once per write and keep one flag per stored row (fix C4)

garrytan4fe11d07c428
diff --git a/src/core/page-body/segment-takes.ts b/src/core/page-body/segment-takes.ts
index 5605e53fc2..5cc248dd99 100644
--- a/src/core/page-body/segment-takes.ts
+++ b/src/core/page-body/segment-takes.ts
@@ -21,39 +21,63 @@ export interface StreamedTakes {
hasMarker: boolean;
}
-export async function parseTakesFenceBlocks(blocks: AsyncIterable<BodyBlock>, page: { slug: string; source_id: string }): Promise<StreamedTakes> {
- let fence: string[] | null = null;
- let fenceChars = 0;
- let endOnly = false;
- let nearMiss = false;
- let hasBegin = false;
- let hasMarker = false;
- for await (const { text, at } of blocks) {
- hasBegin ||= text.includes(TAKES_FENCE_BEGIN);
- hasMarker ||= text.includes('gbrain:takes:');
- if (!hasMarker) continue;
+/** parseTakesFenceBlocks as a push scan: feed one region's blocks in order (`at` from the region start), then `result`. */
+export class TakesFenceScan {
+ private fence: string[] | null = null;
+ private fenceChars = 0;
+ private endOnly = false;
+ private nearMiss = false;
+ private hasBegin = false;
+ private hasMarker = false;
+ private done: StreamedTakes | null = null;
+
+ constructor(private readonly page: { slug: string; source_id: string }) {}
+
+ push({ text, at }: Pick<BodyBlock, 'text' | 'at'>): void {
+ if (this.done) return;
+ this.hasBegin ||= text.includes(TAKES_FENCE_BEGIN);
+ this.hasMarker ||= text.includes('gbrain:takes:');
+ if (!this.hasMarker) return;
let from = 0;
let search = 0;
- if (!fence) {
+ if (!this.fence) {
const begin = indexOfOutsideCode(text, TAKES_FENCE_BEGIN);
if (begin === -1) {
// parseTakesFence's end search with no begin starts at TAKES_FENCE_BEGIN.length - 1.
- endOnly ||= indexOfOutsideCode(text, TAKES_FENCE_END, Math.max(0, TAKES_FENCE_BEGIN.length - 1 - at)) !== -1;
- nearMiss ||= indexOfOutsideCode(text, 'gbrain:takes:begin') !== -1;
- continue;
+ this.endOnly ||= indexOfOutsideCode(text, TAKES_FENCE_END, Math.max(0, TAKES_FENCE_BEGIN.length - 1 - at)) !== -1;
+ this.nearMiss ||= indexOfOutsideCode(text, 'gbrain:takes:begin') !== -1;
+ return;
}
- fence = [];
+ this.fence = [];
from = begin;
search = begin + TAKES_FENCE_BEGIN.length;
}
const end = indexOfOutsideCode(text, TAKES_FENCE_END, search);
const piece = text.slice(from, end === -1 ? text.length : end + TAKES_FENCE_END.length);
- fenceChars += piece.length;
+ this.fenceChars += piece.length;
segmentedPassWork.carry += piece.length;
- if (fenceChars > BLOCK_MAX_BYTES) throw blockTooLargeError(page.slug, page.source_id, fenceChars);
- fence.push(piece);
- if (end !== -1) return { parsed: parseTakesFence(fence.join('')), hasBegin, hasMarker };
+ if (this.fenceChars > BLOCK_MAX_BYTES) throw blockTooLargeError(this.page.slug, this.page.source_id, this.fenceChars);
+ this.fence.push(piece);
+ if (end !== -1) this.done = { parsed: parseTakesFence(this.fence.join('')), hasBegin: this.hasBegin, hasMarker: this.hasMarker };
+ }
+
+ /** The scan is complete: later blocks cannot change the result. */
+ get finished(): boolean {
+ return this.done !== null;
+ }
+
+ result(): StreamedTakes {
+ if (this.done) return this.done;
+ const reduced = this.fence ? TAKES_FENCE_BEGIN : this.endOnly ? `${'\n'.repeat(TAKES_FENCE_BEGIN.length)}${TAKES_FENCE_END}` : this.nearMiss ? 'gbrain:takes:begin' : '';
+ return { parsed: parseTakesFence(reduced), hasBegin: this.hasBegin, hasMarker: this.hasMarker };
+ }
+}
+
+export async function parseTakesFenceBlocks(blocks: AsyncIterable<BodyBlock>, page: { slug: string; source_id: string }): Promise<StreamedTakes> {
+ const scan = new TakesFenceScan(page);
+ for await (const block of blocks) {
+ scan.push(block);
+ if (scan.finished) break;
}
- const reduced = fence ? TAKES_FENCE_BEGIN : endOnly ? `${'\n'.repeat(TAKES_FENCE_BEGIN.length)}${TAKES_FENCE_END}` : nearMiss ? 'gbrain:takes:begin' : '';
- return { parsed: parseTakesFence(reduced), hasBegin, hasMarker };
+ return scan.result();
}
diff --git a/src/core/persistence/canonical-projections.ts b/src/core/persistence/canonical-projections.ts
index 1153ae5857..1fdf2f7aee 100644
--- a/src/core/persistence/canonical-projections.ts
+++ b/src/core/persistence/canonical-projections.ts
@@ -13,7 +13,9 @@ import { sanitizeRemoteBody } from '../remote-body.ts';
import { sanitizeForJsonb } from '../batch-rows.ts';
import { bodyUnread } from '../page-body/page-shape.ts';
import { bodyBlocks, detachedValue } from '../page-body/segment-blocks.ts';
-import { parseTakesFenceBlocks } from '../page-body/segment-takes.ts';
+import { TakesFenceScan } from '../page-body/segment-takes.ts';
+import type { BodyRegion } from '../page-body/types.ts';
+import { createHash } from 'node:crypto';
import { materializedMarker, materializedMarkerHash, timelineKey, timelineKeyHash } from '../timeline-marker.ts';
import type { OperationError } from '../ops/contract.ts';
import { protectedRegions } from '../fence-scan.ts';
@@ -150,40 +152,85 @@ function timelineView(body: CanonicalBody, slug: string): TimelineView {
return { entries: extractTimeline(safe, slug), marked: markedTimeline(safe, slug), superseded: new Set(supersededCitationTimeline(safe).map(t => timelineKey(t))) };
}
+/**
+ * What a prior body says about the stored rows a write classifies, by the row's index in the rows read and its key:
+ * a bullet (`entry`), a bullet a marker still matches (`marked`), a superseded citation reading (`superseded`).
+ */
+interface PriorRows { entry(i: number, key: string): boolean; marked(i: number, key: string): boolean; superseded(i: number, key: string): boolean }
+
/** The views a prior snapshot contributes, plus its takes rows per field and whether either field's takes fence warns. */
-interface PriorView extends TimelineView { takeRows: Set<number>; takesWarn: boolean }
+interface PriorView { rows: PriorRows; takeRows: Set<number>; takesWarn: boolean }
+
+function viewRows(view: TimelineView): PriorRows {
+ return { entry: (_, key) => view.entries.has(key), marked: (_, key) => view.marked.has(key), superseded: (_, key) => view.superseded.has(key) };
+}
+
+const PRIOR_ENTRY = 1, PRIOR_MARKED = 2, PRIOR_SUPERSEDED = 4;
/**
- * timelineView of a stored segmented page whose body is unread, block by block (page-body/segment-blocks.ts): each
- * block is sanitized alone, as the segmenter scans it, and extractTimeline's two passes are merged in its order
- * (every bullet and heading entry, then parseTimelineEntries' readings over them). A `###` dated entry's detail ends
- * at its block. The takes rows are parsed per field, as canonicalTakeRows does (page-body/segment-takes.ts).
+ * The segmented prior view per snapshot page object, for the stored rows it was asked about (their keys' SHA-256): a
+ * write asks for it at preparation, materialization and removal reporting, and each call reads the same revision.
*/
-async function segmentedPriorView(engine: BrainEngine, page: { id: number; slug: string; source_id: string }, slug: string): Promise<PriorView> {
+const segmentedPriors = new WeakMap<object, { digest: string; view: PriorView }>();
+
+/**
+ * The prior view of a stored segmented page whose body is unread, in one pass block by block (page-body/segment-blocks.ts)
+ * and cached for the snapshot (segmentedPriors). Each block is sanitized alone, as the segmenter scans it; every bullet
+ * and heading entry and parseTimelineEntries' readings of it count as the body's entries. Only the stored rows asked
+ * about are kept, one flag byte each, never the body's entries. A `###` dated entry's detail ends at its block. The
+ * takes rows are parsed per field, as canonicalTakeRows does (page-body/segment-takes.ts), in the same pass.
+ */
+async function segmentedPriorView(engine: BrainEngine, page: { id: number; slug: string; source_id: string }, slug: string, keys: readonly string[]): Promise<PriorView> {
+ const digest = createHash('sha256').update(keys.join('\0')).digest('hex');
+ const cached = segmentedPriors.get(page);
+ if (cached?.digest === digest) return cached.view;
+ const index = new Map<string, number[]>();
+ keys.forEach((key, i) => { const at = index.get(key); if (at) at.push(i); else index.set(key, [i]); });
+ const flags = new Uint8Array(keys.length);
+ const mark = (key: string, bit: number) => { for (const i of index.get(key) ?? []) flags[i]! |= bit; };
+ const takes: Record<BodyRegion, TakesFenceScan> = { truth: new TakesFenceScan(page), timeline: new TakesFenceScan(page) };
+ let region: BodyRegion | null = null;
+ let regionAt = 0;
+ for await (const block of bodyBlocks(engine, page)) {
+ if (block.region && block.region !== region) { region = block.region; regionAt = block.at; }
+ if (block.region) takes[block.region].push({ text: block.text, at: block.at - regionAt });
+ const safe = sanitizeRemoteBody(block.text, { keepMaterializedMarkers: true });
+ for (const t of extractTimelineFromContent(safe, slug)) mark(timelineKey(t), PRIOR_ENTRY);
+ for (const t of parseTimelineEntries(safe)) mark(timelineKey({ ...t, source: t.source ?? 'markdown' }), PRIOR_ENTRY);
+ for (const key of markedTimeline(safe, slug)) mark(key, PRIOR_MARKED);
+ for (const t of supersededCitationTimeline(safe)) mark(timelineKey(t), PRIOR_SUPERSEDED);
+ }
+ const fields = [takes.truth.result(), takes.timeline.result()];
+ const view: PriorView = {
+ rows: { entry: i => (flags[i]! & PRIOR_ENTRY) !== 0, marked: i => (flags[i]! & PRIOR_MARKED) !== 0, superseded: i => (flags[i]! & PRIOR_SUPERSEDED) !== 0 },
+ takeRows: new Set(fields.flatMap(field => field.parsed.takes.map(t => t.rowNum))), takesWarn: fields.some(field => field.parsed.warnings.length > 0),
+ };
+ segmentedPriors.set(page, { digest, view });
+ return view;
+}
+
+/** The prior snapshot's view of `rows` (its stored timeline rows): from its strings, or streamed when its segmented body is unread. */
+async function priorView(engine: BrainEngine, page: PageSnapshot['page'], slug: string, rows: readonly StoredTimelineRow[]): Promise<PriorView> {
+ if (bodyUnread(page)) return segmentedPriorView(engine, page, slug, rows.map(row => timelineKey(row)));
+ const fields = [page.compiled_truth, page.timeline ?? ''].map(field => parseTakesFence(field));
+ return { rows: viewRows(timelineView(page, slug)),
+ takeRows: new Set(fields.flatMap(field => field.takes.map(t => t.rowNum))), takesWarn: fields.some(field => field.warnings.length > 0) };
+}
+
+/**
+ * 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).
+ */
+async function segmentedCanonicalTimeline(engine: BrainEngine, page: { id: number; slug: string; source_id: string }, slug: string): Promise<Map<string, ExtractedTimelineEntry>> {
const extracted = new Map<string, ExtractedTimelineEntry>();
const parsed = new Map<string, ExtractedTimelineEntry>();
- const marked = new Set<string>();
- const superseded = new Set<string>();
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 }));
- markedTimeline(safe, slug, marked);
- for (const t of supersededCitationTimeline(safe)) superseded.add(timelineKey(t));
}
- const entries = new Map(extracted);
- for (const [key, entry] of parsed) entries.set(key, entry);
- const fields = await Promise.all((['truth', 'timeline'] as const).map(region => parseTakesFenceBlocks(bodyBlocks(engine, page, { regions: [region] }), page)));
- return { entries, marked, superseded, takeRows: new Set(fields.flatMap(field => field.parsed.takes.map(t => t.rowNum))),
- takesWarn: fields.some(field => field.parsed.warnings.length > 0) };
-}
-
-/** The prior snapshot's view: from its strings, or streamed when its segmented body is unread. */
-async function priorView(engine: BrainEngine, page: PageSnapshot['page'], slug: string): Promise<PriorView> {
- if (bodyUnread(page)) return segmentedPriorView(engine, page, slug);
- const fields = [page.compiled_truth, page.timeline ?? ''].map(field => parseTakesFence(field));
- return { ...timelineView(page, slug), takeRows: new Set(fields.flatMap(field => field.takes.map(t => t.rowNum))),
- takesWarn: fields.some(field => field.warnings.length > 0) };
+ for (const [key, entry] of parsed) extracted.set(key, entry);
+ return extracted;
}
/**
@@ -191,7 +238,7 @@ async function priorView(engine: BrainEngine, page: PageSnapshot['page'], slug:
* before a transaction; unrecordedCanonicalTimeline filters it inside one.
*/
export async function storedCanonicalTimeline(engine: BrainEngine, page: PageSnapshot['page'], slug: string): Promise<Map<string, ExtractedTimelineEntry>> {
- return bodyUnread(page) ? (await segmentedPriorView(engine, page, slug)).entries : canonicalTimeline(page, slug);
+ return bodyUnread(page) ? segmentedCanonicalTimeline(engine, page, slug) : canonicalTimeline(page, slug);
}
/**
@@ -238,19 +285,16 @@ export async function unrecordedCanonicalTimeline(engine: BrainEngine, pageId: n
}
/** Classify stored rows against a new body and the writer's prior snapshot's view. */
-function classifyTimeline(rows: StoredTimelineRow[], body: CanonicalBody, prior: TimelineView | null, slug: string, writer: ProjectionWriter,
+function classifyTimeline(rows: StoredTimelineRow[], body: CanonicalBody, prior: PriorRows | null, slug: string, writer: ProjectionWriter,
policy?: TimelineWritePolicy) {
const incoming = timelineView(body, slug);
const timeline = incoming.entries;
const exactIncoming = new Map([...timeline.values()].map(t => [exactTimelineKey(t), sanitizeForJsonb(t.detail ?? '')]));
- const priorTimeline = new Set(prior?.entries.keys() ?? []);
- const priorMarked = prior?.marked ?? new Set<string>();
- const superseded = new Set([...incoming.superseded, ...(prior?.superseded ?? [])]);
- const pinned = rows.map(row => {
+ const pinned = rows.map((row, i) => {
const key = timelineKey(row);
const state: TimelineRowState = exactIncoming.has(exactTimelineKey(row)) ? 'in_body' : timeline.has(key) ? 'drifted'
- : priorMarked.has(key) ? 'removed_marked' : priorTimeline.has(key) ? 'removed'
- : superseded.has(key) ? (hasExtractorDetail(row) ? 'superseded' : 'superseded_annotated') : 'database_only';
+ : prior?.marked(i, key) ? 'removed_marked' : prior?.entry(i, key) ? 'removed'
+ : incoming.superseded.has(key) || prior?.superseded(i, key) ? (hasExtractorDetail(row) ? 'superseded' : 'superseded_annotated') : 'database_only';
return { ...row, key, state, action: timelineRowAction(writer, state, policy) };
});
return { timeline, exactIncoming, pinned };
@@ -273,7 +317,8 @@ function removedSummary(dates: string[]): TimelineRowsRemoved | null {
/** The stored rows this writer would delete because the new body dropped their bullets, judged now. */
export async function timelineRowsToRemove(engine: BrainEngine, body: CanonicalBody, prior: PageSnapshot, slug: string,
writer: ProjectionWriter, policy?: TimelineWritePolicy): Promise<TimelineRowsRemoved | null> {
- const { pinned } = classifyTimeline(await storedTimeline(engine, prior.page.id), body, await priorView(engine, prior.page, slug), slug, writer, policy);
+ const rows = await storedTimeline(engine, prior.page.id);
+ const { pinned } = classifyTimeline(rows, body, (await priorView(engine, prior.page, slug, rows)).rows, slug, writer, policy);
return removedSummary(pinned.filter(row => row.action === 'delete' && (row.state === 'removed' || row.state === 'removed_marked')).map(row => row.date));
}
@@ -314,7 +359,8 @@ export async function materializeTimeline(engine: BrainEngine, body: CanonicalBo
prior: PageSnapshot | null, writer: ProjectionWriter, policy?: TimelineWritePolicy): Promise<TimelineMaterialization> {
const timelineText = body.timeline ?? '';
if (!prior) return { timeline: timelineText, materialized: 0, unrenderable: 0 };
- const { pinned } = classifyTimeline(await storedTimeline(engine, prior.page.id), body, await priorView(engine, prior.page, slug), slug, writer, policy);
+ const rows = await storedTimeline(engine, prior.page.id);
+ const { pinned } = classifyTimeline(rows, body, (await priorView(engine, prior.page, slug, rows)).rows, slug, writer, policy);
const blocks: string[] = [];
const seen = new Set<string>();
let unrenderable = 0;
@@ -332,7 +378,7 @@ export async function materializeTimeline(engine: BrainEngine, body: CanonicalBo
/** Database-only timeline rows on one page, split by whether they can be materialized. */
export async function pendingTimelineRows(engine: BrainEngine, page: { id: number; slug: string } & CanonicalBody, exclude: ReadonlySet<number> = new Set()) {
- const { pinned } = classifyTimeline(await storedTimeline(engine, page.id), page, timelineView(page, page.slug), page.slug, 'editing');
+ const { pinned } = classifyTimeline(await storedTimeline(engine, page.id), page, viewRows(timelineView(page, page.slug)), page.slug, 'editing');
const renderable = new Set<string>();
let unrenderable = 0;
for (const row of pinned) {
@@ -424,9 +470,9 @@ export async function prepareCanonicalProjections(engine: BrainEngine, page: Par
// #6259: a page the content-quality gate hid as junk projects no facts or takes. Rows projected before it
// was quarantined are left as they are (hiding them would need a new row state); only new projection stops.
const projectFences = !isQuarantined(page.frontmatter);
- const prior_ = prior ? await priorView(engine, prior.page, slug) : null;
- const { timeline, exactIncoming, pinned } = classifyTimeline(prior ? await storedTimeline(engine, prior.page.id) : [],
- page, prior_, slug, writer, policy);
+ const storedRows = prior ? await storedTimeline(engine, prior.page.id) : [];
+ const prior_ = prior ? await priorView(engine, prior.page, slug, storedRows) : null;
+ const { timeline, exactIncoming, pinned } = classifyTimeline(storedRows, page, prior_?.rows ?? null, slug, writer, policy);
const deletions = JSON.stringify(pinned.filter(row => row.action === 'delete')
.map(({ id, date, source, summary, detail, state }) => ({ id, date, source, summary, detail, removed: state === 'removed' || state === 'removed_marked' })));
const refreshes = JSON.stringify(pinned.filter(row => row.action === 'refresh_detail')
diff --git a/test/large-pages/segmented-prior-view.test.ts b/test/large-pages/segmented-prior-view.test.ts
new file mode 100644
index 0000000000..217efe6acc
--- /dev/null
+++ b/test/large-pages/segmented-prior-view.test.ts
@@ -0,0 +1,105 @@
+/**
+ * Wave B PR 2 fix lane C1 (finding C4): a write over a segmented prior reads its body once and keeps no copy of its
+ * timeline.
+ *
+ * 1. Protects: the write path's three prior-view calls for one snapshot (materializeTimeline, timelineRowsToRemove,
+ * prepareCanonicalProjections) read the prior segmented body once between them (the view is cached for the
+ * snapshot and its stored rows), in one pass for the timeline and both takes fields; while the view is alive the
+ * heap holds one flag per stored row, not the prior body's timeline entries; and the rows a write drops are still
+ * reported removed.
+ * 2. Fails when: each call rebuilds the view and each view reads the body twice (six reads per write), or the view
+ * keeps every entry of the prior body (key, summary, detail and slug copies: 12.8x the body for a 6 MiB page).
+ * Seams: segmentedPassWork.bytes (segment-blocks.ts) counts bytes read; the heap is sampled after a full collection
+ * when classification first reads the new body, with the prior view built and alive, against a baseline taken after a
+ * warm-up call on another snapshot (so driver buffers a segment read leaves allocated count in both).
+ */
+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 { parseMarkdown } from '../../src/core/markdown.ts';
+import { segmentedPassWork } from '../../src/core/page-body/segment-blocks.ts';
+import { materializeTimeline, prepareCanonicalProjections, timelineRowsToRemove } from '../../src/core/persistence/canonical-projections.ts';
+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';
+import { testBackends } from '../helpers/test-backends.ts';
+
+const MB = 1024 * 1024;
+const SLUG = 'notes/prior-view';
+const KEPT_ROWS = 50;
+const DROPPED = 10;
+
+function bullet(i: number): string {
+ return '- **20' + String(10 + (i % 15)) + '-0' + (1 + (i % 9)) + '-1' + (i % 10) + '** | Met acme-example about item ' + i + ' and the widget plan';
+}
+
+/** A short truth and about 6 MiB of dated bullets. */
+function page(from: number, count: number): string {
+ return '---\ntitle: Prior view\ntype: note\n---\nA short truth.\n\n<!-- timeline -->\n\n' + Array.from({ length: count }, (_, i) => bullet(from + i)).join('\n') + '\n';
+}
+
+const BULLETS = Math.ceil(6 * MB / 80);
+
+for (const kind of testBackends()) {
+ describe('prior view of a segmented page (' + kind + ')', () => {
+ let engine: BrainEngine;
+ let close: () => Promise<void>;
+ let bodyBytes = 0;
+
+ 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');
+ expect((await importFromContent(engine, SLUG, page(0, BULLETS), { sourceId: 'default', noEmbed: true })).status).toBe('imported');
+ const [row] = await engine.executeRaw<{ id: number; body_bytes: number; body_storage: string }>('SELECT id, body_bytes, body_storage FROM pages WHERE slug=$1', [SLUG]);
+ expect(row!.body_storage).toBe('segmented');
+ bodyBytes = Number(row!.body_bytes);
+ await engine.executeRaw('DELETE FROM timeline_entries WHERE page_id=$1', [row!.id]);
+ for (let i = 0; i < KEPT_ROWS; i++) {
+ const date = '20' + String(10 + (i % 15)) + '-0' + (1 + (i % 9)) + '-1' + (i % 10);
+ await engine.executeRaw("INSERT INTO timeline_entries (page_id, date, source, summary, detail) VALUES ($1, $2::date, 'markdown', $3, '')",
+ [row!.id, date, 'Met acme-example about item ' + i + ' and the widget plan']);
+ }
+ }, 300_000);
+
+ afterAll(async () => { await close(); });
+
+ test('the three prior-view calls of one write read the prior body once', async () => {
+ const snapshot = (await engine.readPageSnapshot(SLUG, { sourceId: 'default' }))!;
+ const next = parseMarkdown(page(DROPPED, BULLETS - DROPPED), SLUG);
+ segmentedPassWork.bytes = 0;
+ await materializeTimeline(engine, next, SLUG, snapshot, 'editing');
+ expect((await timelineRowsToRemove(engine, next, snapshot, SLUG, 'editing'))?.count).toBe(DROPPED);
+ await prepareCanonicalProjections(engine, next, SLUG, 'default', snapshot, 'editing');
+ console.log('[segmented-prior-view] ' + kind + ': ' + segmentedPassWork.bytes + ' bytes read for a ' + bodyBytes + '-byte prior (' + (segmentedPassWork.bytes / bodyBytes).toFixed(2) + ' reads)');
+ expect(segmentedPassWork.bytes).toBeLessThanOrEqual(bodyBytes);
+ }, 300_000);
+
+ test('while the prior view is alive the heap holds no copy of the prior timeline', async () => {
+ const parsed = parseMarkdown(page(DROPPED, BULLETS - DROPPED), SLUG);
+ const warm = (await engine.readPageSnapshot(SLUG, { sourceId: 'default' }))!;
+ expect((await timelineRowsToRemove(engine, parsed, warm, SLUG, 'editing'))?.count).toBe(DROPPED);
+ const snapshot = (await engine.readPageSnapshot(SLUG, { sourceId: 'default' }))!;
+ let peak = 0;
+ const body = { compiled_truth: parsed.compiled_truth, get timeline() {
+ Bun.gc(true);
+ peak = Math.max(peak, process.memoryUsage().heapUsed);
+ return parsed.timeline;
+ } };
+ Bun.gc(true);
+ const base = process.memoryUsage().heapUsed;
+ expect((await timelineRowsToRemove(engine, body, snapshot, SLUG, 'editing'))?.count).toBe(DROPPED);
+ const held = peak - base;
+ console.log('[segmented-prior-view] ' + kind + ': heap held with the prior view alive ' + (held / MB).toFixed(1) + ' MiB for a ' + (bodyBytes / MB).toFixed(1) + ' MiB prior');
+ expect(peak).toBeGreaterThan(0);
+ expect(held).toBeLessThan(bodyBytes);
+ }, 300_000);
+ });
+}