Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Wave B PR 1: the flip deletes the chunk rows it retires; scaling probes under the median-of-rounds ratio
garrytan168a3c749ac2
diff --git a/scripts/bench-large-pages.ts b/scripts/bench-large-pages.tsindex ed150fdbfe..cafc52ee29 100644--- a/scripts/bench-large-pages.ts+++ b/scripts/bench-large-pages.ts@@ -124,7 +124,10 @@ async function flipRetire(engine: BrainEngine, rows: number, embedded: boolean)const texts = Array.from({ length: Math.ceil(rows / FLIP_CHUNKS_PER_OCCURRENCE) }, (_, i) => segmentText(`## Part ${i}\n\nSegment ${i} of ${slug}.\n`));const page = await publishSegmentedPage(engine, slug, texts);const samples = Array.from({ length: 64 }, (_, i) => conversationBody(FLIP_CHUNK_BYTES, { seed: 100 + i }));- const embedding = embedded ? "('[' || array_to_string(ARRAY(SELECT round(random()::numeric, 4) FROM generate_series(1, 1024) WHERE g >= 0), ',') || ']')::vector" : 'NULL';+ const [column] = await engine.executeRaw<{ type: string }>(`SELECT format_type(atttypid, atttypmod) AS type FROM pg_attribute+ WHERE attrelid = 'content_chunks'::regclass AND attname = 'embedding'`);+ const dims = Number(/\((\d+)\)/.exec(column?.type ?? '')?.[1] ?? 1024);+ const embedding = embedded ? `('[' || array_to_string(ARRAY(SELECT round(random()::numeric, 4) FROM generate_series(1, ${dims}) WHERE g >= 0), ',') || ']')::vector` : 'NULL';for (let from = 0; from < rows; from += 5000) {await engine.executeRaw(`INSERT INTO content_chunks (page_id, chunk_index, chunk_text, chunk_source, occurrence_id, local_ordinal, raw_byte_start, raw_byte_end, body_generation, embedding, embedded_at)SELECT $1, g, ($2::text[])[1 + g % 64], 'compiled_truth', ($3::bigint[])[1 + g / ${FLIP_CHUNKS_PER_OCCURRENCE}], g % ${FLIP_CHUNKS_PER_OCCURRENCE}, 0, ${FLIP_CHUNK_BYTES}, 1,diff --git a/src/core/engine-sql/page-body.ts b/src/core/engine-sql/page-body.tsindex a15a64328b..a86995ccbf 100644--- a/src/core/engine-sql/page-body.ts+++ b/src/core/engine-sql/page-body.ts@@ -276,8 +276,9 @@ export async function flipBodyGeneration(exec: SqlExecutor, input: BodyFlipInputconst retireDeferred = toRetire > input.retireMaxRows;await tx.run(sqlFragment`UPDATE page_body_manifest SET gen_to = ${input.newGeneration}::bigintWHERE page_id = ${input.pageId} AND gen_to IS NULL AND staging_id IS NULL AND occurrence_id = ANY(${[...input.closeOccurrences]}::bigint[])`);- const retired = retireDeferred || toRetire === 0 ? 0 : (await tx.run(sqlFragment`UPDATE content_chunks c- SET retired_generation = ${input.newGeneration}::bigint, body_generation = COALESCE(c.body_generation, 0) WHERE ${retire}`)).affectedRows;+ // Retired rows are deleted, not marked: GC would delete a marked row at once (retired_generation <= the live generation),+ // nothing reads one (vector reuse runs during preparation, against live rows), and marking rewrote each row's HNSW entry.+ const retired = retireDeferred || toRetire === 0 ? 0 : (await tx.run(sqlFragment`DELETE FROM content_chunks c WHERE ${retire}`)).affectedRows;await tx.run(sqlFragment`UPDATE page_body_manifest SET staging_id = NULL WHERE page_id = ${input.pageId} AND staging_id = ${input.stagingId}::uuid`);const m = metaParams(input.meta);const b = input.body;diff --git a/src/core/page-body/limits.ts b/src/core/page-body/limits.tsindex b9654988db..e668c2f824 100644--- a/src/core/page-body/limits.ts+++ b/src/core/page-body/limits.ts@@ -54,12 +54,13 @@ export const STAGE_BATCH_BYTES: Readonly<Record<'postgres' | 'pglite', number>>};/**- * Chunk rows the generation flip retires inside the publication transaction; above it the page publishes unsealed and a- * projection job retires the rest, this many rows per statement. Retiring an embedded row cannot be a HOT update, so it- * writes a new `idx_chunks_embedding` (HNSW) entry: `scripts/bench-large-pages.ts` measured 1,000 embedded rows at 1.4 s- * on PGLite and 0.6 s on Postgres, 20,000 at 129 s on PGLite and over the 5 s statement timeout on Postgres.+ * Chunk rows the generation flip deletes inside the publication transaction; above it the page publishes unsealed and a+ * projection job deletes the rest, this many rows per statement. Deleting leaves `idx_chunks_embedding` (HNSW) alone+ * (marking rows retired rewrote each entry: 20,000 embedded rows took 129 s on PGLite). `scripts/bench-large-pages.ts+ * --flip-only` measured 20,000 embedded rows at 0.88 s on PGLite and 0.51 s on Postgres, 40,000 at 1.83 s and 1.47 s,+ * under the publication's 5 s statement timeout.*/-export const DEFAULT_FLIP_RETIRE_MAX_ROWS = 1_000;+export const DEFAULT_FLIP_RETIRE_MAX_ROWS = 20_000;/*** Snapshots of an inline page over the inline cap kept per page (Wave A). Eachdiff --git a/src/core/page-body/projection.ts b/src/core/page-body/projection.tsindex 1e15b0f1af..a1f1c115e4 100644--- a/src/core/page-body/projection.ts+++ b/src/core/page-body/projection.ts@@ -8,11 +8,11 @@* projection job for a page left unsealed (crash, deferred retirement), and by* rebuilds.*- * Retirement runs in bounded statements: rows of occurrences outside the live- * generation, inline rows a promotion deferred, and older duplicates of a live- * occurrence (a projection that raced a flip) get `retired_generation` = the- * live generation, so they leave every reader's visibility filter at once and- * GC deletes them later. Nothing is deleted here.+ * Retirement runs in bounded statements and deletes, as the flip does: rows of+ * occurrences outside the live generation, inline rows a promotion deferred,+ * and older duplicates of a live occurrence (a projection that raced a flip).+ * GC would delete a marked row at once, and a delete leaves the HNSW index+ * alone where marking rewrote each row's entry.*/import type { BrainEngine } from '../engine.ts';import { isQuarantined } from '../quarantine.ts';@@ -37,12 +37,11 @@ async function readProjectionPage(engine: Pick<BrainEngine, 'executeRaw'>, ref:return page ?? null;}-/** Retire, in bounded batches, chunk rows the live generation does not hold: other occurrences, inline rows, older duplicates. */+/** Delete, in bounded batches, chunk rows the live generation does not hold: other occurrences, inline rows, older duplicates. */async function retireStaleChunks(engine: Pick<BrainEngine, 'executeRaw' | 'kind'>, pageId: number, generation: number, live: readonly number[]): Promise<number> {let retired = 0;for (;;) {- const rows = await engine.executeRaw<{ id: number }>(`UPDATE content_chunks c SET retired_generation=$2,- body_generation=COALESCE(c.body_generation, 0)+ const rows = await engine.executeRaw<{ id: number }>(`DELETE FROM content_chunks cWHERE c.id IN (SELECT s.id FROM content_chunks s -- chunk-visibility-ok: retirement selects the rows the live generation does not holdWHERE s.page_id=$1 AND s.retired_generation IS NULLAND (s.body_generation IS NULLdiff --git a/src/core/page-body/types.ts b/src/core/page-body/types.tsindex 35b634ebe2..341b461d70 100644--- a/src/core/page-body/types.ts+++ b/src/core/page-body/types.ts@@ -112,17 +112,18 @@ export interface BodyFlipInput {stagingId: string;/** Live manifest rows closed at newGeneration (retired and shifted occurrences). */closeOccurrences: readonly number[];- /** Occurrences whose chunk rows retire at newGeneration (retired, not shifted). */+ /** Occurrences whose chunk rows the flip deletes (retired, not shifted). */retireChunkOccurrences: readonly number[];- /** Promotion from inline: the page's inline chunk rows (body_generation NULL) retire too. */+ /** Promotion from inline: the page's inline chunk rows (body_generation NULL) are deleted too. */retireInlineChunks?: boolean;- /** Retire at most this many chunk rows in the transaction; above it the flip retires none and reports `retireDeferred`. */+ /** Delete at most this many retired chunk rows in the transaction; above it the flip deletes none and reports `retireDeferred`. */retireMaxRows: number;body: SegmentedBodyColumns;meta: SegmentedPageMeta;}export interface BodyFlipResult {+ /** Retired chunk rows the flip deleted. */retiredChunks: number;/** True when retirement exceeded `retireMaxRows`: the caller leaves the projection unsealed and queues the retirement. */retireDeferred: boolean;diff --git a/test/engine-sql-page-body.test.ts b/test/engine-sql-page-body.test.tsindex f8e31993b0..7252152fc7 100644--- a/test/engine-sql-page-body.test.ts+++ b/test/engine-sql-page-body.test.ts@@ -137,7 +137,7 @@ describe('manifest and flip', () => {expect(() => engine.flipBodyGeneration(flipInput(page.pageId, 1, staged.stagingId, t, { newGeneration: 3 }))).toThrow(TypeError);});- test('retirement above retireMaxRows retires none and reports retireDeferred; within the bound it retires them', async () => {+ test('retirement above retireMaxRows deletes none and reports retireDeferred; within the bound it deletes them', async () => {const t = [segmentText('# A\na\n'), segmentText('# B\nb\n'), segmentText('# C\nc\n')];const page = await publishSegmentedPage(engine, 'notes/flip-retire-bound', t, { chunkTexts: true });const replacement = [segmentText('# A2\na\n'), segmentText('# B2\nb\n'), segmentText('# C2\nc\n')];@@ -155,11 +155,10 @@ describe('manifest and flip', () => {{ closeOccurrences: staged.occurrences, retireChunkOccurrences: [...page.occurrences, ...staged.occurrences], retireMaxRows: 6 }));expect(retired).toEqual({ retiredChunks: 6, retireDeferred: false });const after = await chunkRows(page.pageId);- expect(after.filter(r => r.retired_generation === 3).length).toBe(6);- expect(after.filter(r => r.retired_generation === null).map(r => r.occurrence_id)).toEqual(staged3.occurrences);+ expect(after.map(r => [r.occurrence_id, r.retired_generation])).toEqual(staged3.occurrences.map(occurrence => [occurrence, null]));});- test('two preparers at one generation: the loser\'s staged chunk rows retire with the winner\'s flip', async () => {+ test('two preparers at one generation: the loser\'s staged chunk rows are deleted with the winner\'s flip', async () => {const t = [segmentText('# Race\nbase\n')];const page = await publishSegmentedPage(engine, 'notes/flip-two-stagings', t, { chunkTexts: true });const winner = await stageGeneration(engine, { pageId: page.pageId, slug: 'notes/flip-two-stagings', genFrom: 2, texts: [segmentText('# Race\nwinner\n')], chunkTexts: true });@@ -168,14 +167,11 @@ describe('manifest and flip', () => {{ closeOccurrences: page.occurrences, retireChunkOccurrences: page.occurrences }));expect(result).toEqual({ retiredChunks: 2, retireDeferred: false });const rows = await chunkRows(page.pageId);- const byOccurrence = new Map(rows.map(r => [r.occurrence_id, r]));- expect(byOccurrence.get(winner.occurrences[0]!)?.retired_generation).toBeNull();- expect(byOccurrence.get(loser.occurrences[0]!)?.retired_generation).toBe(2);- expect(byOccurrence.get(page.occurrences[0]!)?.retired_generation).toBe(2);+ expect(rows.map(r => [r.occurrence_id, r.retired_generation])).toEqual([[winner.occurrences[0]!, null]]);expect((await engine.readManifest(page.pageId)).map(r => r.occurrenceId)).toEqual(winner.occurrences);});- test('promotion from inline retires the inline chunk rows (body_generation 0) and NULLs the body columns', async () => {+ test('promotion from inline deletes the inline chunk rows and NULLs the body columns', async () => {await engine.putPage('notes/promote-inline', { type: 'note', title: 'Promote', compiled_truth: 'inline body', timeline: '' });const [{ id: pageId }] = await engine.executeRaw<{ id: number }>("SELECT id FROM pages WHERE slug = 'notes/promote-inline' AND source_id = 'default'");await engine.upsertChunks('notes/promote-inline', [{ chunk_index: 0, chunk_text: 'inline body', chunk_source: 'compiled_truth' }]);@@ -184,7 +180,7 @@ describe('manifest and flip', () => {const result = await engine.flipBodyGeneration(flipInput(pageId, 0, staged.stagingId, t, { retireInlineChunks: true }));expect(result).toEqual({ retiredChunks: 1, retireDeferred: false });const rows = await chunkRows(pageId);- expect(rows.map(r => [r.chunk_index, r.body_generation, r.retired_generation])).toEqual([[0, 0, 1], [1, 1, null]]);+ expect(rows.map(r => [r.chunk_index, r.body_generation, r.retired_generation])).toEqual([[1, 1, null]]);const page = await pageRow(pageId);expect([page.body_storage, page.compiled_truth, page.timeline, page.body_generation]).toEqual(['segmented', null, null, 1]);});diff --git a/test/helpers/cpu-time.ts b/test/helpers/cpu-time.tsindex 4cbda061a7..d4bfac35d5 100644--- a/test/helpers/cpu-time.ts+++ b/test/helpers/cpu-time.ts@@ -13,21 +13,24 @@ export function cpuMs(fn: () => unknown): number {}/**- * CPU-time scaling ratio `large / small` for a linearity bound: after one warm-up run of each, `runs` interleaved pairs,- * each call on a freshly collected heap, and the best of each side. Collecting first keeps the previous call's garbage- * out of the measured call (thread CPU time counts collection work done on the calling thread), and interleaving keeps- * a slow stretch of a loaded VM from landing on one side only.+ * CPU-time scaling ratio `large / small` for a linearity bound: after one warm-up run of each, `rounds` independent+ * ratios, each the best of `runs` calls at the large size over the best of `runs` at the small size, and their median.+ * A collection landing in one call skews one round's best at most, and the median drops that round; collecting before+ * each call made it worse, because every measured call then regrew the heap (allocation-heavy shapes went from a 2.30x+ * to a 2.98x worst case in 36 runs).*/-export function cpuScalingRatio(small: () => unknown, large: () => unknown, runs = 5): number {+export function cpuScalingRatio(small: () => unknown, large: () => unknown, opts: { rounds?: number; runs?: number } = {}): number {+ const rounds = opts.rounds ?? 3;+ const runs = opts.runs ?? 3;small();large();- let bestSmall = Infinity;- let bestLarge = Infinity;- for (let k = 0; k < runs; k++) {- Bun.gc(true);- bestSmall = Math.min(bestSmall, cpuMs(small));- Bun.gc(true);- bestLarge = Math.min(bestLarge, cpuMs(large));- }- return bestLarge / bestSmall;+ const best = (fn: () => unknown) => {+ let ms = Infinity;+ for (let k = 0; k < runs; k++) ms = Math.min(ms, cpuMs(fn));+ return ms;+ };+ const ratios: number[] = [];+ for (let round = 0; round < rounds; round++) ratios.push(best(large) / best(small));+ ratios.sort((a, b) => a - b);+ return ratios[Math.floor(rounds / 2)]!;}diff --git a/test/helpers/segment-gc-cases.ts b/test/helpers/segment-gc-cases.tsindex d36ae30bb6..f65048fb33 100644--- a/test/helpers/segment-gc-cases.ts+++ b/test/helpers/segment-gc-cases.ts@@ -151,7 +151,7 @@ export function defineSegmentGcCases(opts: { getEngine: () => BrainEngine; concuexpect(left).toEqual([{ id: held.stagingId, state: 'expired' }]);});- test('a closed manifest row a retained version references survives; unreferenced closed rows and retired chunks go', async () => {+ test('a closed manifest row a retained version references survives; unreferenced closed rows go, and the flips already deleted the retired chunks', async () => {const engine = opts.getEngine();const sourceId = await freshSource(engine);const v1 = [segmentText('# One\nfirst\n'), segmentText('# Two\nsecond\n')];@@ -167,10 +167,13 @@ export function defineSegmentGcCases(opts: { getEngine: () => BrainEngine; concuawait engine.executeRaw('UPDATE page_body_manifest SET seq = 1 WHERE staging_id = $1::uuid', [s3.stagingId]);await engine.flipBodyGeneration(flipInput(page.pageId, 2, s3.stagingId, v3, { closeOccurrences: s2.occurrences, retireChunkOccurrences: s2.occurrences }));await ageTexts(engine, sourceId);+ const chunkOccurrences = async () => (await engine.executeRaw<{ occurrence_id: number }>(+ 'SELECT DISTINCT occurrence_id::int AS occurrence_id FROM content_chunks WHERE page_id = $1 ORDER BY 1', [page.pageId])).map(r => r.occurrence_id);+ expect(await chunkOccurrences()).toEqual([page.occurrences[0]!, s3.occurrences[0]!]);const first = await engine.sweepSegments({ pageId: page.pageId, graceMs: 0 });expect(first.manifestRowsDeleted).toBe(1);- expect(first.retiredChunksDeleted).toBe(2);+ expect(first.retiredChunksDeleted).toBe(0);expect(first.textsDeleted).toBe(1);expect(await textExists(engine, sourceId, v2[0]!)).toBe(false);expect((await engine.readManifest(page.pageId, { generation: 1 })).map(r => r.occurrenceId)).toEqual(page.occurrences);diff --git a/test/large-pages/body-scan-linear.test.ts b/test/large-pages/body-scan-linear.test.tsindex 48d0c57c3a..013978ae7d 100644--- a/test/large-pages/body-scan-linear.test.ts+++ b/test/large-pages/body-scan-linear.test.ts@@ -2,7 +2,7 @@* Wave B (spec 3.1): pass 1 stays linear in the file size.** Protects: the streamed body scan does O(bytes) work: CPU time at 2n bytes is- * under 2.5x the time at n bytes (n = 4 MiB, best of five interleaved runs) on a page dense with every state the scan+ * under 2.5x the time at n bytes (n = 4 MiB, median of three best-of-three ratios) on a page dense with every state the scan* carries (quoted sentinels inside fences, `---` lines awaiting a Timeline* H2, bare-section headings that fail their lookahead, CRLF, astral text).* Fails when: a step re-reads buffered input per line or per chunk (a@@ -11,6 +11,8 @@* Why existing coverage misses it: split-body-linear covers the whole-string* splitBody, not the streaming scanner.* Seams: none; the quadratic variant wraps the public push API.+ * Measured (12 runs, 4 in parallel on a 4-core machine, cpuScalingRatio): the+ * scan 1.94-2.04x, the prefix-re-reading probe 3.30-3.65x.*/import { describe, expect, test } from 'bun:test';import { BodyScanner } from '../../src/core/page-body/body-scan.ts';@@ -48,15 +50,19 @@ function quadraticScan(bytes: Uint8Array): void {function ratio(run: (bytes: Uint8Array) => void, n: number, runs: number): number {const small = page(n);const large = page(2 * n);- return cpuScalingRatio(() => run(small), () => run(large), runs);+ return cpuScalingRatio(() => run(small), () => run(large), { runs });}describe('body scan cost', () => {test(`CPU time at 2n stays under ${RATIO_LIMIT}x the time at n`, () => {- expect(ratio(scan, 4 * MB, 5)).toBeLessThan(RATIO_LIMIT);+ const r = ratio(scan, 4 * MB, 3);+ console.log(`[body-scan-linear] scan: ${r.toFixed(2)}x`);+ expect(r).toBeLessThan(RATIO_LIMIT);}, 60_000);test('forced probe: the same ratio fails a scan that re-reads its buffered prefix', () => {- expect(ratio(quadraticScan, MB, 3)).toBeGreaterThan(RATIO_LIMIT);+ const r = ratio(quadraticScan, MB, 3);+ console.log(`[body-scan-linear] prefix-re-reading scan (quadratic probe): ${r.toFixed(2)}x`);+ expect(r).toBeGreaterThan(RATIO_LIMIT);}, 120_000);});diff --git a/test/large-pages/segmented-ingest.test.ts b/test/large-pages/segmented-ingest.test.tsindex d420b6630b..5b7d406ece 100644--- a/test/large-pages/segmented-ingest.test.ts+++ b/test/large-pages/segmented-ingest.test.ts@@ -24,6 +24,8 @@ import { readPageBodyPolicy, SEGMENTED_DEMOTE_AT_OR_BELOW_BYTES, SEGMENTED_PROMOimport { abortSegmentedStaging, stageSegmentedImport } from '../../src/core/persistence/segmented-apply.ts';import { conversationBody, conversationPage } from '../helpers/conversation-page.ts';import { fakeEmbedPage, reconstructedPage, segmentedPageRow, visibleChunks } from '../helpers/segmented-page-checks.ts';+import { embeddingInputHash } from '../../src/core/embedding-input-hash.ts';+import { embeddingInputContext, embeddingWriteTarget } from '../../src/core/page-state/projections.ts';let engine: PGLiteEngine;let dir: string;@@ -98,6 +100,64 @@ describe('string path: create, no-op, append', () => {expect(chunks.filter(chunk => !chunk.embedded).length).toBeLessThanOrEqual(result.chunks);}, 180_000);+ /**+ * The flip deletes the rows it retires, so vector reuse must read them before it: during preparation, when they are+ * still live. Every chunk gets its own vector and the recorded input hash reuse admits; after the append, each new tail+ * chunk whose text was in a retired occurrence carries that chunk's vector, and no row of a retired occurrence is left.+ */+ async function embedDistinct(pageId: number): Promise<void> {+ const [page] = await engine.executeRaw<{ title: string; contextual_retrieval_mode: string | null; corpus_generation: string | null }>(+ 'SELECT title, contextual_retrieval_mode, corpus_generation FROM pages WHERE id=$1', [pageId]);+ const provenance = embeddingInputContext(await embeddingWriteTarget(engine), page!.title, page!.corpus_generation, []);+ const tier = page!.contextual_retrieval_mode === 'title' ? 'title' : 'none';+ const rows = await engine.executeRaw<{ id: number; chunk_text: string; chunk_source: string }>(+ 'SELECT id, chunk_text, chunk_source FROM content_chunks WHERE page_id=$1', [pageId]);+ for (const row of rows) {+ await engine.executeRaw(`UPDATE content_chunks SET embedding = (array_fill(0::float4, ARRAY[$3::int - 1]) || ARRAY[$2::float4])::vector,+ embedding_input_hash = $4, embedded_at = now() WHERE id = $1`,+ [row.id, 1 + row.id / 1e6, (await embeddingWriteTarget(engine)).column.dimensions,+ embeddingInputHash(provenance, tier, { chunk_text: row.chunk_text, chunk_source: row.chunk_source })]);+ }+ }+ const vectorsByText = async (pageId: number, occurrences: number[]) => new Map((await engine.executeRaw<{ key: string; embedding: string | null }>(+ `SELECT chunk_source || '|' || chunk_text AS key, embedding::text AS embedding FROM content_chunks WHERE page_id=$1 AND occurrence_id=ANY($2::bigint[])`,+ [pageId, occurrences])).map(row => [row.key, row.embedding]));++ async function appendAfterDistinctEmbed(dropTailVectors: boolean) {+ await importFromContent(engine, 'notes/big', content, { sourceId: 'default', noEmbed: true });+ const before = await segmentedPageRow(engine, 'notes/big');+ await embedDistinct(before.id);+ const liveBefore = (await engine.readManifest(before.id)).map(row => Number(row.occurrenceId));+ const tail = liveBefore.slice(-2);+ if (dropTailVectors) await engine.executeRaw('UPDATE content_chunks SET embedding = NULL WHERE page_id=$1 AND occurrence_id=ANY($2::bigint[])', [before.id, tail]);+ const oldByOccurrence = new Map(await Promise.all(tail.map(async id => [id, await vectorsByText(before.id, [id])] as const)));+ const appended = `${content.trimEnd()}\n\n${conversationBody(10 * 1024, { seed: 99 })}\n`;+ expect((await importFromContent(engine, 'notes/big', appended, { sourceId: 'default', noEmbed: true })).status).toBe('imported');+ const live = (await engine.readManifest(before.id)).map(row => Number(row.occurrenceId));+ const retired = liveBefore.filter(id => !live.includes(id));+ const old = new Map(retired.flatMap(id => [...(oldByOccurrence.get(id) ?? new Map())]));+ const fresh = await vectorsByText(before.id, live.filter(id => !liveBefore.includes(id)));+ const shared = [...fresh.keys()].filter(key => old.has(key));+ const left = await engine.executeRaw('SELECT 1 FROM content_chunks WHERE page_id=$1 AND occurrence_id=ANY($2::bigint[])', [before.id, retired]);+ expect(retired.length).toBeGreaterThan(0);+ expect(retired.every(id => tail.includes(id))).toBe(true);+ return { old, fresh, shared, left: left.length };+ }++ test('a rewritten tail keeps the vectors of its unchanged chunks, read before the flip deletes the rows it retires', async () => {+ const { old, fresh, shared, left } = await appendAfterDistinctEmbed(false);+ expect(left).toBe(0);+ expect(shared.length).toBeGreaterThan(0);+ for (const key of shared) expect(fresh.get(key)).toBe(old.get(key)!);+ }, 180_000);++ test('forced probe: with the retired rows\' vectors gone before preparation, no tail chunk gets one', async () => {+ const { fresh, shared, left } = await appendAfterDistinctEmbed(true);+ expect(left).toBe(0);+ expect(shared.length).toBeGreaterThan(0);+ for (const key of shared) expect(fresh.get(key)).toBeNull();+ }, 180_000);+test('staged rows stay out of the live manifest and the page until the flip', async () => {await importFromContent(engine, 'notes/big', content, { sourceId: 'default', noEmbed: true });const before = await segmentedPageRow(engine, 'notes/big');diff --git a/test/large-pages/segmenter-linear.slow.test.ts b/test/large-pages/segmenter-linear.slow.test.tsindex f3dfdf709c..19c00b28e0 100644--- a/test/large-pages/segmenter-linear.slow.test.ts+++ b/test/large-pages/segmenter-linear.slow.test.ts@@ -8,11 +8,16 @@* 2. Fails when: doubling the input more than 2.5x the CPU time (linear is* 2x, quadratic 4x), for prose, short lines, one newline-free line, a* giant fence, an unterminated protected region and key-dense text.- * 3. Forced probe: the same ratio check run on an append path that- * resegments the whole prefix on each append (the quadratic variant)- * exceeds the bound, so the check can tell the two apart.- * 4. After one warm-up run, each size takes its best of five interleaved runs- * in thread CPU time, each on a freshly collected heap (cpuScalingRatio).+ * 3. Forced probes: the same ratio check run on a cut search that rescans+ * everything pushed so far, and on an append path that resegments the whole+ * prefix on each append (the quadratic variants), exceeds the bound, so the+ * check can tell the two apart.+ * 4. After one warm-up run of each size, the ratio is the median of three+ * rounds, each the best of three runs per size in thread CPU time+ * (cpuScalingRatio).+ * 5. Measured (8 runs, 4 in parallel on a 4-core machine): every shape and the+ * resuming append 1.84-2.18x; the probes, a cut search that rescans the+ * pushed input 2.85-3.04x and whole-page resegmenting per append 3.52-3.77x.*/import { describe, expect, test } from 'bun:test';import { initialEntryState } from '../../src/core/page-body/entry-state.ts';@@ -43,6 +48,22 @@ function segmentStreaming(body: string): number {return n + seg.finish().length;}+/**+ * The quadratic cut search: before each 4 KiB push it searches everything pushed so far for the last heading cut+ * candidate, as a cut decision that rescans the open input instead of carrying its scan state would.+ */+function segmentRescanningCuts(body: string): number {+ const seg = new Segmenter(entry(), segmentOptions('trusted'));+ let n = 0;+ let candidates = 0;+ for (let i = 0; i < body.length; i += 4 * 1024) {+ const pushed = body.slice(0, i);+ for (const cut = /\n## /g; cut.exec(pushed);) candidates++;+ n += seg.push(body.slice(i, i + 4 * 1024)).length;+ }+ return n + seg.finish().length + (candidates & 0);+}+describe('the segmenter scales linearly', () => {const shapes: Array<[string, (bytes: number) => string, number]> = [['mixed page', prefix, 2 * MB],@@ -59,6 +80,13 @@ describe('the segmenter scales linearly', () => {expect(r).toBeLessThan(BOUND);}, 120_000);}++ test('forced probe: a cut search that rescans the pushed input exceeds the bound', () => {+ const giantFence = shapes.find(([name]) => name === 'giant fence')!;+ const r = ratio(giantFence[1], giantFence[2], segmentRescanningCuts);+ console.log(`[segmenter-linear] giant fence, rescanning cut search (quadratic probe): ${r.toFixed(2)}x`);+ expect(r).toBeGreaterThan(BOUND);+ }, 120_000);});const STEP = 64 * 1024;