Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(large-pages): collect during a streamed import's pass 1 so its garbage does not follow the page
garrytan13dbca66dc37
diff --git a/src/core/page-body/segment-blocks.ts b/src/core/page-body/segment-blocks.tsindex c394abd031..05b1783fc9 100644--- a/src/core/page-body/segment-blocks.ts+++ b/src/core/page-body/segment-blocks.ts@@ -35,15 +35,16 @@ const COLLECT_EVERY_BYTES = 4 * 1024 * 1024;/*** A full collection every COLLECT_EVERY_BYTES read. Each segment read leaves garbage several times its size (driver* buffers, decoded texts), and JSC sizes its threshold to a heap PGLite's WASM memory makes large, so a pass over a- * 40 MiB page peaked ~0.8 GB above its live heap without this. Feed it the bytes of each piece read.+ * 40 MiB page peaked ~0.8 GB above its live heap without this. Feed it the bytes of each piece read; true when it collected.*/-export function readGarbageCollector(): (bytes: number) => void {+export function readGarbageCollector(): (bytes: number) => boolean {let since = 0;return bytes => {since += bytes;- if (since < COLLECT_EVERY_BYTES) return;+ if (since < COLLECT_EVERY_BYTES) return false;since = 0;Bun.gc(true);+ return true;};}diff --git a/src/core/page-body/streamed-import.ts b/src/core/page-body/streamed-import.tsindex 8e0a439968..3a00bd5796 100644--- a/src/core/page-body/streamed-import.ts+++ b/src/core/page-body/streamed-import.ts@@ -75,6 +75,7 @@ import { sanitizeText } from '../batch-rows.ts';import { applySegmentedBody, sealSegmentedPage, segmentedLivePage } from '../persistence/segmented-apply.ts';import { buildSegmentedProjection } from './projection.ts';import { prepareSegmentedBody, segmentWriteScope, utf8Prefix, type SegmentedStagingOwner } from './ingest.ts';+import { readGarbageCollector } from './segment-blocks.ts';import type { JsonObject } from './types.ts';const READ_BYTES = 1024 * 1024;@@ -82,9 +83,10 @@ const FENCE_MARKER = /gbrain:(facts|takes):begin/;/*** @internal Work the checked reads after pass 1 do, for the drift test: file blocks read and hashed against their- * pass-1 digests (`blocks`) and their bytes (`bytes`). Counts, not time.+ * pass-1 digests (`blocks`) and their bytes (`bytes`); and, for the scan memory test, the most file bytes pass 1+ * read between two full collections (`scanUncollected`). Counts, not time.*/-export const streamedImportWork = { blocks: 0, bytes: 0 };+export const streamedImportWork = { blocks: 0, bytes: 0, scanUncollected: 0 };type StreamedImportOptions = {noEmbed?: boolean;@@ -241,16 +243,25 @@ class CodeRefLines {/*** Pass 1 over the virtual stream; `prefix` is inferred frontmatter (empty when none). `hash` and `blocks` receive the- * file's bytes after its BOM.+ * file's bytes after its BOM. A full collection every few MiB read (readGarbageCollector), as the staging batches+ * after it collect: each read leaves its buffer and the scanner's decoded text behind, and JSC's own collector rarely+ * runs during the pass, so a 32 MiB file's pass 1 left ~170 MiB of garbage under the first staging batch, the import's+ * peak; the peak grew with the file (segmented-ingest-memory: ~310 MiB above a 1 MiB import at 32 MiB, ~400 at 48 MiB;+ * ~230 at both with the collection).*/async function scanFile(file: FileHandle, bom: number, prefix: Uint8Array, size: number, relativePath: string, opts: StreamedImportOptions, hash: Hash | null,blocks: BlockDigests) {const scanner = new BodyScanner(relativePath, { validate: true, ...(opts.activePack ? { activePack: opts.activePack } : {}) });if (prefix.length) scanner.push(prefix);+ const collect = readGarbageCollector();+ let uncollected = 0;for await (const part of readVirtual(file, bom, new Uint8Array(0), 0, size - bom)) {hash?.update(part);blocks.push(part);scanner.push(part);+ uncollected += part.length;+ streamedImportWork.scanUncollected = Math.max(streamedImportWork.scanUncollected, uncollected);+ if (collect(part.length)) uncollected = 0;}return scanner.finish();}diff --git a/test/large-pages/streamed-scan-collect.test.ts b/test/large-pages/streamed-scan-collect.test.tsnew file mode 100644index 0000000000..2ea1e6026f--- /dev/null+++ b/test/large-pages/streamed-scan-collect.test.ts@@ -0,0 +1,67 @@+/**+ * Wave B (spec 2.2, 3.1): a streamed import's pass 1 collects as it reads, so its garbage does not follow the page.+ *+ * 1. Protects: pass 1 over a file above PAGE_MAX_BYTES (`scanFile`) reads at most COLLECT_EVERY_BYTES plus one read+ * between two full collections (`streamedImportWork.scanUncollected`), the same at 25 MiB and at 50 MiB.+ * 2. Fails when: pass 1 reads the whole file with no collection, leaving each read's buffer and decoded text to JSC's+ * own collector, which rarely runs during the pass: a 32 MiB import's peak then sat on ~170 MiB of pass-1 garbage,+ * and segmented-ingest-memory.slow.test.ts's delta grew with the page (~310 MiB at 32 MiB, ~400 at 48; ~230 at+ * both with the collection).+ * 3. Existing coverage: segmented-ingest-memory.slow.test.ts measures VmHWM, which moves with whether JSC collected+ * during the pass; body-scan-memory.test.ts checks what the scanner retains, not the reads' garbage.+ * 4. No production seam: a wrapped engine.getPage, which importScanned calls right after pass 1, stops the import+ * there. Pass 1 reads only the file, so PGLite alone covers it.+ */+import { afterAll, beforeAll, expect, test } from 'bun:test';+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';+import { importFromFile } from '../../src/core/import-file.ts';+import { PAGE_MAX_BYTES } from '../../src/core/page-size-policy.ts';+import { readPageBodyPolicy } from '../../src/core/page-body/limits.ts';+import { streamedImportWork } from '../../src/core/page-body/streamed-import.ts';+import { conversationPage } from '../helpers/conversation-page.ts';++const MiB = 1024 * 1024;+const BOUND = 4 * MiB + MiB;+const dir = mkdtempSync(join(tmpdir(), 'gbrain-streamed-scan-'));+let engine: PGLiteEngine;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ await engine.setConfig('pages.segmented_storage', 'on');+}, 120_000);++afterAll(async () => {+ await engine.disconnect();+ rmSync(dir, { recursive: true, force: true });+});++async function scanUncollected(bytes: number): Promise<number> {+ const file = join(dir, `page-${bytes}.md`);+ writeFileSync(file, conversationPage(bytes, { seed: 7 }));+ const stop = new Error('stop after pass 1');+ const getPage = engine.getPage;+ engine.getPage = (async () => { throw stop; }) as typeof engine.getPage;+ streamedImportWork.scanUncollected = 0;+ try {+ await importFromFile(engine, file, 'notes/scan-example.md', { noEmbed: true, bodyPolicy: await readPageBodyPolicy(engine) }).catch(error => {+ if (error !== stop) throw error;+ });+ } finally {+ engine.getPage = getPage;+ rmSync(file, { force: true });+ }+ return streamedImportWork.scanUncollected;+}++test(`pass 1 reads at most ${BOUND / MiB} MiB between collections, whatever the file size`, async () => {+ const small = await scanUncollected(PAGE_MAX_BYTES + MiB);+ const large = await scanUncollected(2 * PAGE_MAX_BYTES + 2 * MiB);+ expect(small).toBeGreaterThan(0);+ expect(small).toBeLessThanOrEqual(BOUND);+ expect(large).toBeLessThanOrEqual(BOUND);+}, 300_000);