Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Fix lane K: no seal over a deferred retirement, get_versions of demoted pages, bounded managed timeline read

garrytanc32f14da36be
diff --git a/src/core/page-body/projection.ts b/src/core/page-body/projection.ts
index 8a8cb0a5d8..ac693edc67 100644
--- a/src/core/page-body/projection.ts
+++ b/src/core/page-body/projection.ts
@@ -70,6 +70,12 @@ export const STALE_CHUNKS_SQL = `WITH RECURSIVE occ(o) AS (
SELECT c.id FROM content_chunks c -- chunk-visibility-ok: retirement selects the rows the live generation does not hold
WHERE c.page_id=$1 AND c.occurrence_id IS NULL AND (c.body_generation IS NULL OR (cardinality($3::bigint[])=0 AND c.body_generation<=$2::bigint))`;
+/** The occurrence ids of page $1's manifest at generation $2. */
+export async function liveOccurrenceIds(engine: Pick<BrainEngine, 'executeRaw'>, pageId: number, generation: number): Promise<number[]> {
+ return (await engine.executeRaw<{ occurrence_id: number | string }>(`SELECT occurrence_id FROM page_body_manifest WHERE page_id=$1 AND staging_id IS NULL
+ AND gen_from <= $2 AND (gen_to IS NULL OR gen_to > $2)`, [pageId, generation])).map(row => Number(row.occurrence_id));
+}
+
/** The page still stores a chunk row its live generation does not hold (a deferred retirement): sealing it would show the row. */
export async function hasStaleChunks(engine: Pick<BrainEngine, 'executeRaw'>, pageId: number, generation: number, live: readonly number[]): Promise<boolean> {
return (await engine.executeRaw(`${STALE_CHUNKS_SQL} LIMIT 1`, [pageId, generation, live])).length > 0;
@@ -135,7 +141,11 @@ async function projectSegmentedPage(engine: BrainEngine, ref: { sourceId: string
opts: { expectedRevision?: string }): Promise<SegmentedProjectionResult> {
const page = await readProjectionPage(engine, ref);
if (!page || (opts.expectedRevision !== undefined && page.knowledge_revision !== opts.expectedRevision)) return { chunks: 0, retired: 0, sealed: false };
- if (page.text_projection_revision === page.knowledge_revision) return { chunks: 0, retired: 0, sealed: true };
+ // A sealed page holding a retired occurrence's row (sealed by an older binary over a deferred retirement) is built again to retire it.
+ if (page.text_projection_revision === page.knowledge_revision
+ && !await hasStaleChunks(engine, Number(page.id), Number(page.body_generation), await liveOccurrenceIds(engine, Number(page.id), Number(page.body_generation)))) {
+ return { chunks: 0, retired: 0, sealed: true };
+ }
if (!await claimProjection(engine, ref)) return { chunks: 0, retired: 0, sealed: false };
try {
return await buildClaimedProjection(engine, ref, page);
diff --git a/src/core/page-body/read-range.ts b/src/core/page-body/read-range.ts
index 6df7a268e8..14dea92081 100644
--- a/src/core/page-body/read-range.ts
+++ b/src/core/page-body/read-range.ts
@@ -176,8 +176,9 @@ export async function openSegmentedBody(engine: BrainEngine, opts: { pageId: num
const [page] = await engine.executeRaw<Record<string, unknown>>(`SELECT id, source_id, slug, body_storage, body_generation, body_bytes, body_lines, truth_bytes,
body_flags, segmenter_version, knowledge_revision::text AS revision FROM pages WHERE id=$1`, [opts.pageId]);
if (opts.pin) await checkPin(opts.pin, page, opts.pageId);
- if (!page || page.body_storage !== 'segmented') throw new Error(`Page ${opts.pageId} is not a segmented page.`);
- const generation = opts.pin?.generation ?? opts.generation ?? Number(page.body_generation);
+ const generation = opts.pin?.generation ?? opts.generation ?? Number(page?.body_generation);
+ // An earlier generation (a segmented version) keeps its manifest rows after the page was demoted to inline storage.
+ if (!page || (page.body_storage !== 'segmented' && generation === Number(page.body_generation))) throw new Error(`Page ${opts.pageId} is not a segmented page.`);
const rows = await engine.executeRaw<Record<string, unknown>>(`SELECT m.seq, m.occurrence_id, m.region, m.sha256, m.byte_start, m.byte_len,
m.line_start, m.line_count, m.static_proj_bytes, m.static_proj_lines, jsonb_array_length(m.outline) AS outline_count,
jsonb_array_length(m.facts_slots) > 0 AS has_facts, m.date_min IS NOT NULL AS has_date
diff --git a/src/core/persistence/canonical-projections.ts b/src/core/persistence/canonical-projections.ts
index cc5ab27bbd..b63a438407 100644
--- a/src/core/persistence/canonical-projections.ts
+++ b/src/core/persistence/canonical-projections.ts
@@ -8,7 +8,8 @@ import { TAKES_FENCE_BEGIN, TAKES_FENCE_END, parseTakesFence } from '../takes-fe
import { extractFactsFromFenceText } from '../facts/extract-from-fence.ts';
import { takesPreparation } from '../takes-write.ts';
import { parseTimelineEntries } from '../link-extraction.ts';
-import { extractTimelineFromContent, hasExtractorDetail, supersededCitationTimeline, type ExtractedTimelineEntry } from '../timeline-extract.ts';
+import { eachStoredTimelineRow, extractTimelineFromContent, hasExtractorDetail, supersededCitationTimeline, TimelineKeySet,
+ type ExtractedTimelineEntry } from '../timeline-extract.ts';
import { sanitizeRemoteBody } from '../remote-body.ts';
import { sanitizeForJsonb } from '../batch-rows.ts';
import { bodyUnread } from '../page-body/page-shape.ts';
@@ -246,16 +247,35 @@ export function segmentedCanonicalCollector(slug: string, recorded?: { has(key:
};
}
-/** The canonical timeline of a stored segmented page whose body is unread, block by block (segmentedCanonicalCollector). */
+/**
+ * @internal Work of the managed timeline extraction over a page (`storedRows`: stored rows walked by
+ * unrecordedCanonicalTimeline and segmentedCanonicalTimeline; `kept`: canonical entries a segmented body's read kept).
+ * Counts, not time.
+ */
+export const canonicalTimelineWork = { storedRows: 0, kept: 0 };
+
+/**
+ * The canonical timeline of a stored segmented page whose body is unread, block by block (segmentedCanonicalCollector),
+ * less the entries a stored row of the page records: the rows are walked in pages and held as key digests
+ * (TimelineKeySet), so the read keeps what an insert-only caller may add, never every entry the body yields.
+ */
async function segmentedCanonicalTimeline(engine: BrainEngine, page: { id: number; slug: string; source_id: string }, slug: string): Promise<Map<string, ExtractedTimelineEntry>> {
- const collector = segmentedCanonicalCollector(slug);
+ const recorded = new TimelineKeySet();
+ await eachStoredTimelineRow(engine, Number(page.id), row => {
+ canonicalTimelineWork.storedRows++;
+ recorded.add(timelineKey({ date: row.date_text, source: row.source, summary: row.summary }));
+ });
+ const collector = segmentedCanonicalCollector(slug, recorded);
for await (const block of bodyBlocks(engine, page)) collector.add(block.text);
- return collector.result();
+ const kept = collector.result();
+ canonicalTimelineWork.kept += kept.size;
+ return kept;
}
/**
- * The canonical timeline of a stored page (a snapshot's page): a segmented body is read block by block. Read it
- * before a transaction; unrecordedCanonicalTimeline filters it inside one.
+ * The canonical timeline of a stored page (a snapshot's page) for an insert-only caller: a segmented body is read
+ * block by block and keeps only entries no stored row records. Read it 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) ? segmentedCanonicalTimeline(engine, page, slug) : canonicalTimeline(page, slug);
@@ -296,12 +316,22 @@ function storedTimeline(engine: BrainEngine, pageId: number): Promise<StoredTime
* have no stored row on the page under the same normalized key. Insert-only
* callers (managed `extract --stale`) add exactly these, so a stored row that
* differs only by whitespace is not duplicated. `storedRows` is the caller's
- * own read of the page's non-event rows (a batched walk).
+ * own read of the page's non-event rows (a batched walk); without it the rows
+ * are walked in pages (eachStoredTimelineRow), never held as one array.
*/
export async function unrecordedCanonicalTimeline(engine: BrainEngine, pageId: number, body: CanonicalBody | ReadonlyMap<string, ExtractedTimelineEntry>,
slug: string, storedRows?: ReadonlyArray<Pick<StoredTimelineRow, 'date' | 'source' | 'summary'>>): Promise<ExtractedTimelineEntry[]> {
- const stored = new Set((storedRows ?? await storedTimeline(engine, pageId)).map(row => timelineKey(row)));
- return [...(body instanceof Map ? body : canonicalTimeline(body as CanonicalBody, slug))].filter(([key]) => !stored.has(key)).map(([, entry]) => entry);
+ const entries = body instanceof Map ? body : canonicalTimeline(body as CanonicalBody, slug);
+ if (storedRows) {
+ const stored = new Set(storedRows.map(row => timelineKey(row)));
+ return [...entries].filter(([key]) => !stored.has(key)).map(([, entry]) => entry);
+ }
+ const unrecorded = new Map(entries);
+ await eachStoredTimelineRow(engine, pageId, row => {
+ canonicalTimelineWork.storedRows++;
+ unrecorded.delete(timelineKey({ date: row.date_text, source: row.source, summary: row.summary }));
+ });
+ return [...unrecorded.values()];
}
/** Classify stored rows against a new body and the writer's prior snapshot's view. */
diff --git a/src/core/persistence/segmented-apply.ts b/src/core/persistence/segmented-apply.ts
index 8e05af507e..bbf5bebccb 100644
--- a/src/core/persistence/segmented-apply.ts
+++ b/src/core/persistence/segmented-apply.ts
@@ -25,7 +25,7 @@ import type { PageSnapshot } from '../page-state/types.ts';
import type { JsonObject, SegmentedPageMeta } from '../page-body/types.ts';
import type { PreparedSegmentedBody, SegmentChunkingContext, SegmentedLivePage, SegmentedStagingOwner } from '../page-body/ingest.ts';
import { materializeSegmentedBody, prepareSegmentedBody, segmentWriteScope, stringBodyFlags, stringRegion } from '../page-body/ingest.ts';
-import { buildSegmentedProjection } from '../page-body/projection.ts';
+import { buildSegmentedProjection, hasStaleChunks, liveOccurrenceIds } from '../page-body/projection.ts';
import { maintenanceAttribution } from './attribution.ts';
import { readPageBodyPolicy, chooseBodyStorage, SEGMENTED_DEMOTE_AT_OR_BELOW_BYTES, type PageBodyPolicy } from '../page-body/limits.ts';
import { SEGMENTED_CHUNKER_VERSION } from '../page-body/segment-chunks.ts';
@@ -127,7 +127,7 @@ export interface SegmentedApplyInput {
requestId?: string | null;
}
-/** `complete`: every occurrence has chunks and the flip retired the old rows, so the caller seals as its last step (`sealSegmentedPage`). */
+/** `complete`: every occurrence has chunks and no retired occurrence's row is still stored, so the caller seals as its last step (`sealSegmentedPage`). */
export interface SegmentedApplied { pageId: number; complete: boolean; retireDeferred: boolean }
/**
@@ -168,7 +168,10 @@ export async function applySegmentedBody(tx: BrainEngine, input: SegmentedApplyI
await faultPoint('segmented:flipped', { sourceId: input.sourceId });
await tx.setBodyStagingState(prepared.stagingId, 'committed', { commitRequestId: input.requestId ?? null });
const chunked = prepared.createRows ? createChunks !== null : prepared.unchunked === 0;
- return { pageId, complete: chunked && !flip.retireDeferred, retireDeferred: flip.retireDeferred };
+ // The flip retires only the occurrences this write closes: rows an earlier write's deferred retirement left keep the page unsealed.
+ const complete = chunked && !flip.retireDeferred
+ && !await hasStaleChunks(tx, pageId, prepared.newGeneration, await liveOccurrenceIds(tx, pageId, prepared.newGeneration));
+ return { pageId, complete, retireDeferred: flip.retireDeferred };
}
/**
diff --git a/test/large-pages/managed-links-timeline-heap.test.ts b/test/large-pages/managed-links-timeline-heap.test.ts
new file mode 100644
index 0000000000..cd19f9df58
--- /dev/null
+++ b/test/large-pages/managed-links-timeline-heap.test.ts
@@ -0,0 +1,146 @@
+/**
+ * Wave B PR 2 fix lane K (finding TR1): managed stale-link extraction (sync, extract --stale) over a segmented page
+ * keeps, while it reads the body, only the canonical timeline entries no stored row records.
+ *
+ * 1. Protects: on an 8 MiB page of dated bullets whose rows are all stored, the extraction's canonical timeline read
+ * (storedCanonicalTimeline, then unrecordedCanonicalTimeline's filter inside the transaction) holds less than the
+ * page (heap after a full collection, sampled before each segment read and with its result held): the stored rows
+ * are walked in pages and held as key digests (TimelineKeySet), and the read keeps no entry. The full
+ * extractManagedStaleLinks run keeps no entry (canonicalTimelineWork.kept 0) and walks every stored row once per
+ * pass; with rows deleted, the read keeps exactly those entries and the extraction inserts them back.
+ * 2. Fails when: storedCanonicalTimeline keeps every canonical entry of the body, or unrecordedCanonicalTimeline reads
+ * every stored row as one array (several times the page held, about 200 MiB at 24 MiB).
+ * 3. 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); the work counter counts entries and rows.
+ */
+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 { extractManagedStaleLinks } from '../../src/core/persistence/links-maintenance.ts';
+import { canonicalTimelineWork, storedCanonicalTimeline, unrecordedCanonicalTimeline } from '../../src/core/persistence/canonical-projections.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 SLUG = 'notes/managed-links-timeline';
+
+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: Managed links timeline\ntype: note\n---\nA short truth.\n\n<!-- timeline -->\n\n' + bullets.join(''), bullets: bullets.length };
+}
+
+for (const kind of testBackends()) {
+ describe('managed stale-link extraction timeline heap over a segmented page (' + kind + ')', () => {
+ let engine: BrainEngine;
+ let close: () => Promise<void>;
+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-managed-links-timeline-'));
+
+ beforeAll(async () => {
+ if (kind === 'postgres') ({ engine, close } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));
+ 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 lowest heap seen (before `fn`, or at a sample: a collection right after the warm-up
+ * run can leave its garbage), sampled after a full collection before each segment read and once more with its result
+ * still held. `fn` runs once first unmeasured, so code it loads 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;
+ let low = Infinity;
+ const sample = () => { Bun.gc(true); const heap = jsHeap(); peak = Math.max(peak, heap); low = Math.min(low, heap); samples++; };
+ engine.readSegmentTexts = (async (sourceId: string, shas: Uint8Array[]) => {
+ sample();
+ return original(sourceId, shas);
+ }) as BrainEngine['readSegmentTexts'];
+ Bun.gc(true);
+ low = jsHeap();
+ let result: unknown;
+ try {
+ result = await fn();
+ sample();
+ } finally {
+ delete (engine as { readSegmentTexts?: unknown }).readSegmentTexts;
+ }
+ expect(result).toBeDefined();
+ return { held: peak - low, samples };
+ }
+
+ test('an 8 MiB page of stored bullets: the canonical timeline read keeps no entry and holds less than the page', async () => {
+ const root = join(dir, 'brain');
+ mkdirSync(root, { recursive: true });
+ const sourceId = 'links-' + 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(8 * MB);
+ expect((await importFromContent(engine, SLUG, content, { sourceId, noEmbed: true })).status).toBe('imported');
+ await extractTimelineFromDB(engine, { dryRun: false, jsonMode: false, quiet: true, sourceIdFilter: sourceId, slugs: [SLUG] });
+ const rows = async () => (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=$2 AND p.source_id=$1', [sourceId, SLUG]))[0]!;
+ const page = await rows();
+ expect(page.rows).toBe(bullets);
+ const bytes = Number(page.body_bytes);
+ const snapshot = (await engine.readPageSnapshot(SLUG, { sourceId }))!;
+
+ const read = await heldWhile(async () => {
+ const canonical = await storedCanonicalTimeline(engine, snapshot.page, SLUG);
+ return { canonical, unrecorded: await unrecordedCanonicalTimeline(engine, Number(snapshot.page.id), canonical, SLUG) };
+ });
+ console.log('[managed-links-timeline] ' + kind + ': ' + (read.held / MB).toFixed(1) + ' MiB held over ' + read.samples + ' samples of a '
+ + (bytes / MB).toFixed(1) + ' MiB page with ' + bullets + ' rows');
+ expect(read.samples).toBeGreaterThan(1);
+ expect(read.held).toBeLessThan(bytes);
+
+ const extract = () => extractManagedStaleLinks(engine, { sourceId, slugs: [SLUG], mentions: false });
+ canonicalTimelineWork.storedRows = canonicalTimelineWork.kept = 0;
+ expect((await extract()).timeline).toBe(0);
+ expect(canonicalTimelineWork.kept).toBe(0);
+ expect(canonicalTimelineWork.storedRows).toBe(2 * bullets);
+
+ const gone = (await engine.executeRaw<{ id: number }>(
+ 'DELETE FROM timeline_entries WHERE id IN (SELECT t.id FROM timeline_entries t JOIN pages p ON p.id=t.page_id WHERE p.slug=$1 AND p.source_id=$2 ORDER BY t.id LIMIT 7) RETURNING id',
+ [SLUG, sourceId])).length;
+ expect(gone).toBe(7);
+ canonicalTimelineWork.storedRows = canonicalTimelineWork.kept = 0;
+ expect((await extract()).timeline).toBe(7);
+ expect(canonicalTimelineWork.kept).toBe(7);
+ expect((await rows()).rows).toBe(bullets);
+ });
+ }, 1_200_000);
+ });
+}
diff --git a/test/large-pages/remote-versions-storage-change.test.ts b/test/large-pages/remote-versions-storage-change.test.ts
new file mode 100644
index 0000000000..d3b37e0c4d
--- /dev/null
+++ b/test/large-pages/remote-versions-storage-change.test.ts
@@ -0,0 +1,98 @@
+/**
+ * Remote get_versions of a page whose storage changed since a version was taken (Wave B PR 2, fix lane K, review O1).
+ *
+ * 1. Protects: a remote caller's get_versions (metadata and include_body) lists a segmented version of a page that was
+ * later demoted to inline storage with its read-projection size (total_bytes, the size get_page reported while it
+ * was live), never its stored body_bytes; and lists an inline version of a page later promoted to segmented storage
+ * as the inline snapshot it is. Local reads list both too.
+ * 2. Fails when: openSegmentedBody refuses every generation of a page whose live row is inline ("Page N is not a
+ * segmented page"), so remote get_versions throws for every page that was segmented and later demoted.
+ * 3. Runs on PGLite, and on Postgres when DATABASE_URL is set.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import type { BrainEngine } from '../../src/core/engine.ts';
+import type { GBrainConfig } from '../../src/core/config.ts';
+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';
+import { operations, type OperationContext } from '../../src/core/operations.ts';
+import { importFromContent } from '../../src/core/import-file.ts';
+import { withCoordinatedWrite } from '../../src/core/persistence/context.ts';
+import { TEST_WRITE_ATTRIBUTION } from '../helpers/write-attribution.ts';
+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';
+import { testBackends } from '../helpers/test-backends.ts';
+import { importSegmented } from '../helpers/segmented-privacy-fixture.ts';
+
+const op = (name: string) => operations.find(o => o.name === name)!;
+let engine: BrainEngine;
+const ctx = (remote: boolean): OperationContext => ({ engine, config: {} as GBrainConfig, logger: { info() {}, warn() {}, error() {} }, dryRun: false, remote,
+ sourceId: 'default', emitResponseMeta: () => {}, transport: remote ? 'http' : 'cli', ...(remote ? { auth: { token: 'fixture', clientId: 'versions-client',
+ principal: { kind: 'oauth_client', id: 'versions-client' }, scopes: ['read'], sourceId: 'default', allowedSources: ['default'] } } : {}) } as unknown as OperationContext);
+const call = async (name: string, params: Record<string, unknown>, remote = true) => await op(name).handler(ctx(remote), params) as any;
+
+function filler(bytes: number, tag: string): string {
+ const parts: string[] = [];
+ for (let i = 0, n = 0; n < bytes; i++) {
+ const part = `## Section ${tag} ${i}\n\n${`Public notes on launch planning and roadmap review for week ${i}. `.repeat(30)}\n\n`;
+ parts.push(part);
+ n += part.length;
+ }
+ return parts.join('');
+}
+const takes = `<!--- gbrain:takes:begin -->\n${'Hidden take about pricing strategy. '.repeat(8000)}\n<!--- gbrain:takes:end -->\n`;
+const content = (body: string) => `---\ntitle: Versions probe\ntype: note\n---\n\n${body}`;
+const storage = async (slug: string) => (await engine.executeRaw<{ body_storage: string }>(
+ "SELECT body_storage FROM pages WHERE source_id='default' AND slug=$1", [slug]))[0]!.body_storage;
+const snapshot = (slug: string) => engine.transaction(tx => withCoordinatedWrite(tx, ['default'], () => tx.createVersion(slug, { sourceId: 'default' }), TEST_WRITE_ATTRIBUTION));
+
+for (const kind of testBackends()) {
+ describe(`get_versions across a storage change (${kind})`, () => {
+ let close: () => Promise<void>;
+ beforeAll(async () => {
+ if (kind === 'postgres') ({ engine, close } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));
+ else { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); close = () => engine.disconnect(); }
+ }, 120_000);
+ afterAll(async () => { await close(); });
+
+ test('a segmented version of a page demoted to inline reports its projected size', async () => {
+ const slug = 'notes/demoted-versions';
+ const id = await importSegmented(engine, slug, content(`${filler(1_400_000, 'big')}\n\n${takes}`));
+ await snapshot(slug);
+ const projected = (await call('get_page', { slug, body: 'none' })).size.total_bytes as number;
+ const [stored] = await engine.executeRaw<{ body_bytes: number }>('SELECT body_bytes FROM pages WHERE id=$1', [id]);
+ expect(projected).toBeLessThan(Number(stored!.body_bytes));
+
+ await importFromContent(engine, slug, content('A short page now.\n'), { sourceId: 'default', noEmbed: true });
+ expect(await storage(slug)).toBe('inline');
+
+ const meta = (await call('get_versions', { slug })) as Array<Record<string, unknown>>;
+ const segmented = meta.filter(v => v.body_storage === 'segmented');
+ expect(segmented.length).toBeGreaterThan(0);
+ for (const v of segmented) {
+ expect(v.body_bytes).toBeUndefined();
+ expect(v.total_bytes).toBe(projected);
+ }
+ const full = (await call('get_versions', { slug, include_body: true })) as Array<Record<string, any>>;
+ const fullSegmented = full.filter(v => v.body_storage === 'segmented');
+ expect(fullSegmented.length).toBe(segmented.length);
+ for (const v of fullSegmented) {
+ expect(v.body_bytes).toBeUndefined();
+ expect(v.body_ref.total_bytes).toBe(projected);
+ }
+ expect(JSON.stringify([meta, full])).not.toContain(String(stored!.body_bytes));
+ const local = (await call('get_versions', { slug }, false)) as Array<Record<string, unknown>>;
+ expect(local.filter(v => v.body_storage === 'segmented').every(v => Number(v.body_bytes) === Number(stored!.body_bytes))).toBe(true);
+ }, 240_000);
+
+ test('an inline version of a page promoted to segmented storage lists as an inline snapshot', async () => {
+ const slug = 'notes/promoted-versions';
+ await importFromContent(engine, slug, content('Small first draft about inline history.\n'), { sourceId: 'default', noEmbed: true });
+ await snapshot(slug);
+ await importSegmented(engine, slug, content(filler(1_400_000, 'grown')));
+ expect(await storage(slug)).toBe('segmented');
+ const meta = (await call('get_versions', { slug })) as Array<Record<string, unknown>>;
+ expect(meta.length).toBeGreaterThan(0);
+ expect(meta.some(v => v.body_storage === 'segmented')).toBe(false);
+ const full = (await call('get_versions', { slug, include_body: true })) as Array<Record<string, any>>;
+ expect(full.some(v => String(v.compiled_truth).includes('Small first draft about inline history.'))).toBe(true);
+ }, 240_000);
+ });
+}
diff --git a/test/large-pages/second-write-deferred-retire.test.ts b/test/large-pages/second-write-deferred-retire.test.ts
new file mode 100644
index 0000000000..71e3610bc5
--- /dev/null
+++ b/test/large-pages/second-write-deferred-retire.test.ts
@@ -0,0 +1,130 @@
+/**
+ * A segmented write after a write whose chunk retirement was deferred (Wave B PR 2, fix lane K, review finding I1).
+ *
+ * 1. Protects: W1 replaces a segmented page with more stale chunk rows than pages.flip_retire_max_rows (retirement
+ * deferred) and its projection never runs; W2 then edits another part of the page. W2's flip retires only the
+ * occurrences W2 closes, so W2 leaves the page unsealed while W1's rows are still stored, W1's removed text is never
+ * a keyword hit, and the projection build retires those rows and seals. A page an older binary sealed over such rows
+ * is built again (not short-circuited as sealed), so the build retires them.
+ * 2. Fails when: applySegmentedBody marks the write complete from its own flip alone (W2 seals over W1's rows and
+ * chunkVisibleFilter shows them), or buildSegmentedProjection returns "sealed" for a sealed page that still stores
+ * retired occurrences' rows (they are never retired).
+ * 3. Runs on PGLite, and on Postgres when DATABASE_URL is set. The lost projections are forced: each write runs on an
+ * engine whose projection page read throws (as a process death after commit, or a claim another process holds).
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } 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 { importFromFile } from '../../src/core/import-file.ts';
+import { readPageBodyPolicy } from '../../src/core/page-body/limits.ts';
+import { buildSegmentedProjection } from '../../src/core/page-body/projection.ts';
+import { sealSegmentedPage } from '../../src/core/persistence/segmented-apply.ts';
+import { registerLocalWriter } from '../../src/core/persistence/identity.ts';
+import { disposePersistenceConsumer } from '../../src/core/persistence/service.ts';
+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';
+import { conversationPage } from '../helpers/conversation-page.ts';
+import { segmentedPageRow } from '../helpers/segmented-page-checks.ts';
+import { testBackends } from '../helpers/test-backends.ts';
+import { withEnv } from '../helpers/with-env.ts';
+
+const home = mkdtempSync(join(tmpdir(), 'gbrain-second-write-deferred-'));
+const env = { GBRAIN_HOME: home, OPENAI_API_KEY: undefined, VOYAGE_API_KEY: undefined, ANTHROPIC_API_KEY: undefined };
+const PROJECTION_PAGE_READ = "FROM pages WHERE source_id=$1 AND slug=$2 AND deleted_at IS NULL AND body_storage='segmented'";
+
+/** The engine with the segmented projection's page read failing: the post-commit projection is lost. */
+function projectionLost(engine: BrainEngine): BrainEngine {
+ return new Proxy(engine, {
+ get(target, prop) {
+ if (prop === 'executeRaw') {
+ return (sql: string, params?: unknown[]) => sql.includes(PROJECTION_PAGE_READ)
+ ? Promise.reject(new Error('projection lost (probe)')) : target.executeRaw(sql, params);
+ }
+ const value = Reflect.get(target, prop, target);
+ return typeof value === 'function' ? value.bind(target) : value;
+ },
+ });
+}
+
+const v0 = conversationPage(3 * 1024 * 1024, { seed: 41, needles: [{ at: 0.2, word: 'oldmarkerquokka' }, { at: 0.8, word: 'farmarkerwalrus' }] });
+const v1 = v0.replace('oldmarkerquokka', 'newmarkernarwhal');
+const v2 = v1.replace('farmarkerwalrus', 'farmarkerpangolin');
+afterAll(() => { rmSync(home, { recursive: true, force: true }); });
+
+for (const kind of testBackends()) describe(`a segmented write after a deferred retirement (${kind})`, () => {
+ let engine: BrainEngine;
+ let close: () => Promise<void>;
+ beforeAll(async () => withEnv(env, async () => {
+ if (kind === 'postgres') ({ engine, close } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));
+ else { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); close = () => engine.disconnect(); }
+ await registerLocalWriter(engine, 'cli');
+ await engine.setConfig('pages.segmented_storage', 'on');
+ }), 120_000);
+ afterAll(async () => withEnv(env, async () => { await disposePersistenceConsumer(engine); await close?.(); }));
+
+ const found = async (slug: string, word: string) => (await engine.searchKeyword(word, { limit: 10 })).filter(r => r.slug === slug).length;
+ const staleRows = async (pageId: number) => Number((await engine.executeRaw<{ n: number }>(
+ "SELECT count(*)::int AS n FROM content_chunks WHERE page_id=$1 AND strpos(chunk_text, 'oldmarkerquokka') > 0", [pageId]))[0]!.n);
+
+ /** v0 imported and projected, then W1 (v1) with its retirement deferred and its projection lost. */
+ async function deferredPage(): Promise<{ slug: string; file: string }> {
+ const dir = join(home, `page-${randomUUID().slice(0, 8)}`);
+ mkdirSync(dir, { recursive: true });
+ const file = join(dir, 'huge.md');
+ const slug = `notes/huge-${randomUUID().slice(0, 8)}`;
+ const write = async (body: string, on: BrainEngine) => {
+ writeFileSync(file, body);
+ expect(await importFromFile(on, file, `${slug}.md`, { noEmbed: true, bodyPolicy: await readPageBodyPolicy(engine) })).toMatchObject({ status: 'imported' });
+ };
+ await write(v0, engine);
+ expect(await found(slug, 'oldmarkerquokka')).toBeGreaterThan(0);
+ await engine.setConfig('pages.flip_retire_max_rows', '1');
+ await write(v1, projectionLost(engine));
+ await engine.setConfig('pages.flip_retire_max_rows', '20000');
+ const page = await segmentedPageRow(engine, slug);
+ expect(page.text_projection_revision).not.toBe(page.knowledge_revision);
+ expect(await staleRows(page.id)).toBeGreaterThan(0);
+ expect(await found(slug, 'oldmarkerquokka')).toBe(0);
+ return { slug, file };
+ }
+
+ test("W2 leaves the page unsealed over W1's stored rows; the build retires them and seals", async () => withEnv(env, async () => {
+ const { slug, file } = await deferredPage();
+ writeFileSync(file, v2);
+ expect(await importFromFile(projectionLost(engine), file, `${slug}.md`, { noEmbed: true, bodyPolicy: await readPageBodyPolicy(engine) }))
+ .toMatchObject({ status: 'imported' });
+ const afterW2 = await segmentedPageRow(engine, slug);
+ expect(await staleRows(afterW2.id)).toBeGreaterThan(0);
+ expect(await found(slug, 'oldmarkerquokka')).toBe(0);
+ expect(afterW2.text_projection_revision).not.toBe(afterW2.knowledge_revision);
+
+ const built = await buildSegmentedProjection(engine, { sourceId: 'default', slug });
+ expect(built.sealed).toBe(true);
+ expect(built.retired).toBeGreaterThan(0);
+ const sealed = await segmentedPageRow(engine, slug);
+ expect(sealed.text_projection_revision).toBe(sealed.knowledge_revision);
+ expect(await staleRows(sealed.id)).toBe(0);
+ expect(await found(slug, 'oldmarkerquokka')).toBe(0);
+ expect(await found(slug, 'farmarkerwalrus')).toBe(0);
+ expect(await found(slug, 'newmarkernarwhal')).toBeGreaterThan(0);
+ expect(await found(slug, 'farmarkerpangolin')).toBeGreaterThan(0);
+ }), 1_200_000);
+
+ test("a page sealed over retired occurrences' rows is built again, not reported sealed", async () => withEnv(env, async () => {
+ const { slug } = await deferredPage();
+ const page = await segmentedPageRow(engine, slug);
+ // The state an earlier binary left: sealed while W1's rows are still stored.
+ await engine.transaction(tx => sealSegmentedPage(tx, page.id));
+ expect(await found(slug, 'oldmarkerquokka')).toBeGreaterThan(0);
+
+ const built = await buildSegmentedProjection(engine, { sourceId: 'default', slug });
+ expect(built.sealed).toBe(true);
+ expect(built.retired).toBeGreaterThan(0);
+ expect(await staleRows(page.id)).toBe(0);
+ expect(await found(slug, 'oldmarkerquokka')).toBe(0);
+ expect(await found(slug, 'newmarkernarwhal')).toBeGreaterThan(0);
+ }), 1_200_000);
+});
diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txt
index 7cc729e8c5..4fbc0e19c1 100644
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@ -73,6 +73,7 @@ test/large-pages/forget-reason-segmented.test.ts
test/large-pages/forget-scope.test.ts
test/large-pages/held-budget-shrink.test.ts
test/large-pages/managed-import-outside-root.test.ts
+test/large-pages/managed-links-timeline-heap.test.ts
test/large-pages/managed-streamed-import.test.ts
test/large-pages/managed-sync-segmented-rename.test.ts
test/large-pages/managed-sync-streamed.test.ts
@@ -87,9 +88,11 @@ test/large-pages/purge-segment-residue.test.ts
test/large-pages/purge-segmented-versions-batch.test.ts
test/large-pages/purge-segments.test.ts
test/large-pages/remote-get-page-privacy.test.ts
+test/large-pages/remote-versions-storage-change.test.ts
test/large-pages/remote-window-privacy.test.ts
test/large-pages/restore-deferred-retire.test.ts
test/large-pages/sealed-segmented-search.test.ts
+test/large-pages/second-write-deferred-retire.test.ts
test/large-pages/segment-rewrite-cr-tier.test.ts
test/large-pages/segment-vector-reuse.test.ts
test/large-pages/segmented-append-reembed.test.ts