Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Wave B lane 1d: streamed import memory flat in page size (outline/date strings no longer pin segment texts, a collection per staging batch, 4 MiB Postgres batches, Buffer bytea codec on PGLite); memory slow test; bench RSS baseline is a 1 MiB import

garrytand60350deb9c7
diff --git a/docs/architecture/key-files/engines-1.md b/docs/architecture/key-files/engines-1.md
index f12a374e8b..ff9058cc7a 100644
--- a/docs/architecture/key-files/engines-1.md
+++ b/docs/architecture/key-files/engines-1.md
@@ -41,7 +41,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/pglite-lock.ts` — persistent datastore ownership uses a canonical sibling `.gbrain-owner.lock` retained inode and the native kernel binding. `.gbrain-lock/lock` retains PID, structured argv, command/subcommand and heartbeat diagnostics for `inspectLockHolder`/`peekLock` and engine-free IPC routing; `peekLock` also reports a serve holder's transport (`http` from its recorded `--http` argv) and `acquiredAt`, in one metadata read. `heldLockFor(dataDir)` answers "does this process hold it" from the in-memory retained handles (no file access while none are held). The exported ps/proc/Windows CIM process probe is diagnostic compatibility only; ownership and takeover never consult it. Metadata age, corruption and PID reuse never override a kernel owner. The initial protocol upgrade refuses live/unknown legacy owners; all older processes must be stopped. Handles remain strongly retained until explicit release, so GC cannot unlock a datastore after a close timeout. Dead legacy migration keeps the one-acquisition WAL-repair quarantine; `msSinceLastReap` reads older persisted quarantine markers. Tests: `test/pglite-lock.test.ts` (real paused/crashed process, replacement/aliases, migration, metadata).
-- `src/core/pglite-statements.ts` — `PgliteStatementCache`, the PGLite counterpart of postgres.js prepared statements. `PGLiteEngine._attachDatabase` routes the root handle's `query`/`exec` through it and `transaction()` routes each transaction handle. A statement text seen twice is prepared once as a named server-side statement; later calls send one Bind/Execute/Sync batch and parse rows with parsers resolved at prepare time, instead of PGlite's parse/describe round trips and its per-query copy of `db.parsers`. PostgreSQL's plan cache replans on invalidation; a changed result shape (`0A000`) or missing statement (`26000`) drops the entry and retries outside a transaction. `ALTER`/`CREATE`/`DROP`/`DO`/`DISCARD`/`DEALLOCATE` text, `ANALYZE`/`VACUUM` (PostgreSQL keeps a prepared plan across a statistics refresh, so a plan made before the table had statistics would outlive planner-stats' first-read ANALYZE) and any non-transaction-control `exec` clear the cache, retired names are closed in the next prepare batch, an instance-level `query`/`exec` override (test seams) takes precedence on the root handle, and `_closeInternal` drops the cache with the database so a disconnected engine does not retain its PGLite instance. `dropRowTypeArrayParsers` removes composite-row array parsers after connect, since gbrain never selects those arrays. Pinned by `test/pglite-statements.test.ts`.
+- `src/core/pglite-statements.ts` — `PgliteStatementCache`, the PGLite counterpart of postgres.js prepared statements. `PGLiteEngine._attachDatabase` routes the root handle's `query`/`exec` through it and `transaction()` routes each transaction handle. A statement text seen twice is prepared once as a named server-side statement; later calls send one Bind/Execute/Sync batch and parse rows with parsers resolved at prepare time, instead of PGlite's parse/describe round trips and its per-query copy of `db.parsers`. PostgreSQL's plan cache replans on invalidation; a changed result shape (`0A000`) or missing statement (`26000`) drops the entry and retries outside a transaction. `ALTER`/`CREATE`/`DROP`/`DO`/`DISCARD`/`DEALLOCATE` text, `ANALYZE`/`VACUUM` (PostgreSQL keeps a prepared plan across a statistics refresh, so a plan made before the table had statistics would outlive planner-stats' first-read ANALYZE) and any non-transaction-control `exec` clear the cache, retired names are closed in the next prepare batch, an instance-level `query`/`exec` override (test seams) takes precedence on the root handle, and `_closeInternal` drops the cache with the database so a disconnected engine does not retain its PGLite instance. `configurePgliteCodecs` removes composite-row array parsers after connect, since gbrain never selects those arrays, and replaces PGlite's per-byte bytea codec with Buffer's hex codec (a 4 MiB bytea batch no longer allocates ~250 MB of garbage). Pinned by `test/pglite-statements.test.ts`.
- `src/core/pglite-repair.ts` — WAL-repair orchestrator wrapping the resetWal port with the safety layers that make it runnable automatically from `connect()`: `validateWalRepairTarget` (read-only, fail-closed; refuses symlinked dataDir/pg_wal/`global`/pg_control — lstat follows INTERMEDIATE symlinks, so `global/` itself must be checked or surgery would write pg_control through it into a foreign dir; tolerates the in-dir `.gbrain-lock`), rename-based backup (the ENTIRE `pg_wal/` dir + postmaster.pid renamed into a sibling `<dataDir>.wal-repair-backup-<ts>/`, only the 8KB pg_control copied — zero transient disk cost), `restoreWalBackup` (overwrite order: control first via atomic tmp+rename, then a pg_wal dir swap with the reset dir set ASIDE inside the backup — nothing is ever deleted during restore; mtime guard refuses when a foreign segment is newer than the backup; a missing/empty backup NEVER reports `restored:true`), `WalRepairError` (thrown when resetWal fails AFTER the backup — carries the receipt + the best-effort restore's REAL result so the seam's `restored` flag and the `failed-restored`/`failed-not-restored` message arms never lie), a cooldown sidecar `<dataDir>.wal-repair-attempt.json` (skip `'recently-failed'` inside `GBRAIN_PGLITE_WAL_REPAIR_COOLDOWN_SECONDS`, default 3600 — bounds the autopilot/supervisor reconnect loops) with episode-scoped backups (attempts within one corruption episode REUSE the episode's first backup — the pre-damage forensic state, honored only when the sidecar's path is a real non-symlink `<dataDir>.wal-repair-backup-*` sibling since the sidecar is user-writable JSON; retention keeps the newest 3 episodes, never pruning the open episode's), and `attemptWalRepairAndRetry` — the engine seam that NEVER throws (gates: kill-switch → reaped-lock `'possibly-live-writer'` → 10-minute reap-marker quarantine (`msSinceLastReap`, cross-process) → validation → cooldown; then repair → retry create once → restore-and-record on failure; prints a repair-start stderr line so a timeout-killed attempt is self-explaining). `inspectPgliteDataDir` is the read-only diagnosis for `gbrain doctor` + `pglite-repair --dry-run`. Imports runtime values only from `pglite-lock.ts`/`pglite-resetwal.ts`/node:fs — never from `pglite-engine.ts` (no cycle; the engine statically imports THIS file per the engine-live rule). Pinned by `test/pglite-repair.test.ts` + `test/pglite-wal-repair.serial.test.ts`.
- `src/core/pglite-repair-consent.ts` + the repair-failed marker in `src/core/pglite-repair.ts` — when automatic WAL repair fails (or a recent failure put it on cooldown) `recordFailedAutoRepair` writes the sibling `<dataDir>.repair-failed.json`; while it exists `PGLiteEngine.connect()` refuses before `acquireLock` (zero writes to the data dir) with `repairFailedRefusal`: the exit-3 consent payload (effects `destructive`, fix `gbrain pglite-repair [--path] --yes --expect <plan_hash>` from the same `walRepairPlan` the command binds, preview `--dry-run --json`, and the hands-off text `HANDS_OFF_BRAIN_FILES`). The CLI's `exitOnRepairFailed` (`src/cli/cli-error.ts`) exits 3 on it from `connectEngine`; stdio serve maps it to status reason `repair_failed`. Cleared by a completed `pglite-repair` or `reinit-pglite`. Pinned by `test/agent-operator-gate-fixes.{,serial.}test.ts`.
diff --git a/scripts/bench-large-pages.ts b/scripts/bench-large-pages.ts
index ed150fdbfe..07e8857a7e 100644
--- a/scripts/bench-large-pages.ts
+++ b/scripts/bench-large-pages.ts
@@ -5,9 +5,10 @@
*
* - `ingest_ms`: wall time of the streamed import (pass 1, pass 2, staging,
* flip, projection), no provider calls.
- * - `rss`: peak RSS of a fresh child process ingesting `--size` and one
- * ingesting a page 2 MiB over PAGE_MAX_BYTES through the same path, and
- * their difference (the slope: ingest memory must not grow with the page).
+ * - `rss`: peak RSS (VmHWM, reset after a full GC once the engine is open) of a fresh child
+ * process importing `--size` through importFromFile, of one importing a
+ * 1 MiB page through it (the single-string path), and their difference
+ * (target: under 500 MB at 100 MB; ingest memory must not grow with the page).
* - `rows`: distinct segment texts and manifest rows of the live generation, and live chunk rows.
* - `append_10kb`: time, and the manifest and chunk rows the new generation staged, of re-importing the file with 10 KB
* appended (only the tail should be restaged).
@@ -32,7 +33,7 @@ import { appendFileSync, existsSync, mkdtempSync, readFileSync, rmSync, statSync
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import type { BrainEngine } from '../src/core/engine.ts';
-import { importFromContent } from '../src/core/import-file.ts';
+import { importFromContent, importFromFile } from '../src/core/import-file.ts';
import { readPageBodyPolicy } from '../src/core/page-body/limits.ts';
import { PAGE_MAX_BYTES } from '../src/core/page-size-policy.ts';
import { importStreamedMarkdownFile } from '../src/core/page-body/streamed-import.ts';
@@ -157,14 +158,18 @@ async function flipRetireCells(engine: BrainEngine) {
return cells;
}
-/** Child mode: ingest `--file` in a fresh process (the parent generated it) and report its peak RSS. */
+/** Child mode: import `--file` in a fresh process (the parent generated it) and report its peak RSS from the open engine on. */
async function child(file: string, kind: string): Promise<void> {
const dir = mkdtempSync(join(tmpdir(), 'gbrain-bench-large-'));
const engine = await openEngine(kind, dir);
try {
await engine.setConfig('pages.segmented_storage', 'on');
await engine.executeRaw('DELETE FROM pages WHERE slug=$1', [SLUG]);
- await ingest(engine, file);
+ const bodyPolicy = await readPageBodyPolicy(engine);
+ Bun.gc(true);
+ if (existsSync('/proc/self/clear_refs')) writeFileSync('/proc/self/clear_refs', '5');
+ const result = await importFromFile(engine, file, `${SLUG}.md`, { noEmbed: true, bodyPolicy });
+ if (result.status !== 'imported') throw new Error(`the bench page was not imported: ${result.error ?? result.status}`);
process.stdout.write(JSON.stringify({ peak_rss_bytes: peakRssBytes() }) + '\n');
} finally {
await engine.disconnect();
@@ -230,12 +235,12 @@ async function main(): Promise<void> {
const pct = (p: number) => latencies.length ? round(latencies[Math.min(latencies.length - 1, Math.floor(latencies.length * p))]!) : null;
const reference = join(dir, 'page-reference.md');
writeFileSync(file, conversationPage(size, { seed: 1 }));
- writeFileSync(reference, conversationPage(PAGE_MAX_BYTES + 2 * 1024 * 1024, { seed: 1 }));
+ writeFileSync(reference, conversationPage(1024 * 1024, { seed: 1 }));
const rssLarge = childRss(file, kind);
const rssSmall = childRss(reference, kind);
const report = {
engine: kind, size_bytes: statSync(file).size, ingest_ms: round(ingestMs),
- rss: { peak_bytes: rssLarge, peak_reference_bytes: rssSmall, slope_bytes: rssLarge - rssSmall },
+ rss: { peak_bytes: rssLarge, peak_reference_bytes: rssSmall, delta_bytes: rssLarge - rssSmall },
rows: { texts: rows.texts, manifest: rows.manifest, chunks: rows.chunks },
append_10kb: { ms: round(appendMs), manifest: appended.manifestAtGeneration, chunks: appended.chunksAtGeneration },
concurrent_small_put: { writes: latencies.length, p50_ms: pct(0.5), p95_ms: pct(0.95), max_ms: pct(1) },
diff --git a/src/core/page-body/ingest.ts b/src/core/page-body/ingest.ts
index bf5c5d1aa5..f25747d99c 100644
--- a/src/core/page-body/ingest.ts
+++ b/src/core/page-body/ingest.ts
@@ -180,6 +180,16 @@ export async function openSegmentedStaging(engine: BrainEngine, input: Pick<Segm
return id;
}
+/**
+ * A full collection after each staging batch. A batch leaves garbage several times its payload (driver parameter
+ * text, protocol buffers, decoded segment texts, chunk strings), and JSC sizes its collection threshold to the heap,
+ * which PGLite's WASM memory makes large, so batches piled up uncollected: a 100 MiB import peaked ~1.1 GB on PGLite
+ * without this and ~0.75 GB with it (scripts/bench-large-pages.ts). One collection of a small live heap per 4 MiB.
+ */
+function collectBatchGarbage(): void {
+ Bun.gc(true);
+}
+
/**
* Pass 2 for one write: segment both regions, hash, stage texts, diff against
* the live manifest, stage the changed manifest rows and (replace) the chunks
@@ -219,6 +229,7 @@ async function stageBody(engine: BrainEngine, input: SegmentedBodyInput, staging
if (!pending.length) return;
const batch = pending.splice(0);
await writes(exec => exec.stageSegmentTexts(input.sourceId, batch));
+ collectBatchGarbage();
pendingBytes = 0;
if (engine.kind === 'pglite') await new Promise(resolve => setImmediate(resolve));
};
@@ -385,6 +396,7 @@ export async function stageOccurrenceChunks(engine: BrainEngine, input: { pageId
});
rows += chunks.length;
done += batch.length;
+ collectBatchGarbage();
if (engine.kind === 'pglite') await new Promise(resolve => setImmediate(resolve));
}
return { rows, occurrences: done, indexes };
diff --git a/src/core/page-body/limits.ts b/src/core/page-body/limits.ts
index b9654988db..638acce5a2 100644
--- a/src/core/page-body/limits.ts
+++ b/src/core/page-body/limits.ts
@@ -47,9 +47,13 @@ export const SEGMENTED_PAGE_CEILING_BYTES: Readonly<Record<'postgres' | 'pglite'
pglite: 128 * 1024 ** 2,
};
-/** Rows one staging statement may carry, by payload bytes (PGLite shares one connection, so smaller). */
+/**
+ * Rows one staging statement may carry, by payload bytes. A statement's transient memory is many times its payload
+ * (driver hex text, protocol buffers, decoded texts, chunk strings): at 16 MiB a 100 MiB Postgres import peaked
+ * ~400 MB above one at 4 MiB (scripts/bench-large-pages.ts), for 3% more ingest time.
+ */
export const STAGE_BATCH_BYTES: Readonly<Record<'postgres' | 'pglite', number>> = {
- postgres: 16 * 1024 ** 2,
+ postgres: 4 * 1024 ** 2,
pglite: 4 * 1024 ** 2,
};
diff --git a/src/core/page-body/segmenter.ts b/src/core/page-body/segmenter.ts
index 64dd93b6fb..847c207407 100644
--- a/src/core/page-body/segmenter.ts
+++ b/src/core/page-body/segmenter.ts
@@ -543,7 +543,7 @@ export class Segmenter {
if (FENCE.test(line)) this.outline.fence = !this.outline.fence;
else if (!this.outline.fence && outline.length < OUTLINE_MAX_HEADINGS) {
const h = HEADING.exec(line);
- if (h) outline.push({ proj_byte: byte, level: h[1]!.length, text: clip(h[2]!, HEADING_MAX_CHARS) });
+ if (h) outline.push({ proj_byte: byte, level: h[1]!.length, text: detached(clip(h[2]!, HEADING_MAX_CHARS)) });
}
}
skip = false;
@@ -558,10 +558,19 @@ export class Segmenter {
if (dateMin === null || m[0] < dateMin) dateMin = m[0];
if (dateMax === null || m[0] > dateMax) dateMax = m[0];
}
- return { outline, dateMin, dateMax };
+ return { outline, dateMin: dateMin && detached(dateMin), dateMax: dateMax && detached(dateMax) };
}
}
+/**
+ * A copy of `slice` that does not share the string it was cut from. A substring (slice, regex match) keeps its whole
+ * parent alive, and segment metadata outlives the segment: a write holds every manifest row until it publishes, so an
+ * outline heading cut from a segment's projection would pin that projection, the whole body across all rows.
+ */
+function detached(slice: string): string {
+ return Buffer.from(slice, 'utf8').toString('utf8');
+}
+
/** The longest prefix of `text` whose UTF-8 bytes fit in `room` (chars and bytes), never splitting a surrogate pair. */
function fitChars(text: string, room: number): { chars: number; bytes: number } {
let bytes = 0;
diff --git a/src/core/pglite-engine.ts b/src/core/pglite-engine.ts
index fad4f16a53..07bcb5e4d6 100644
--- a/src/core/pglite-engine.ts
+++ b/src/core/pglite-engine.ts
@@ -11,7 +11,7 @@ import { readPageSnapshotsBatch } from './page-snapshot-batch.ts';
import { createPageVersion } from './page-state/versions.ts';
import { moveSlugBindings, recordRenameAlias } from './page-state/rename-alias.ts';
import { composablePgliteTransaction, transactionMemo } from './page-state/transactions.ts';
-import { dropRowTypeArrayParsers, PgliteStatementCache } from './pglite-statements.ts';
+import { configurePgliteCodecs, PgliteStatementCache } from './pglite-statements.ts';
import { snapshotSchemaInputs } from './snapshot-schema-inputs.ts';
import type { PageReadScope } from './types.ts';
import type { PageReadPolicy } from './types.ts';
@@ -793,7 +793,7 @@ export class PGLiteEngine implements BrainEngine {
this.vectorIterativeScan = undefined;
const opening = this._connectInternal(config).then(async () => {
try {
- await dropRowTypeArrayParsers(this.db);
+ await configurePgliteCodecs(this.db);
if (registerRoots) await registerManagedFilesystemEngine(this, config.database_path);
}
catch (error) {
diff --git a/src/core/pglite-statements.ts b/src/core/pglite-statements.ts
index 835f3ff4d0..c36abe0684 100644
--- a/src/core/pglite-statements.ts
+++ b/src/core/pglite-statements.ts
@@ -191,14 +191,34 @@ export class PgliteStatementCache {
}
/**
- * PGlite copies `db.parsers` into a fresh object for every query result. Its
+ * Codec setup after connect. PGlite copies `db.parsers` into a fresh object for every query result. Its
* array-type init registers one parser per composite (table row) array type,
* most of the map in a gbrain schema, and gbrain never selects those arrays;
* the per-query copy then dominated short statements. Their values would only
- * have been split into unparsed strings, so drop them after connect.
+ * have been split into unparsed strings, so drop them. Then install the
+ * Buffer bytea codec below.
*/
-export async function dropRowTypeArrayParsers(db: PGlite): Promise<void> {
+export async function configurePgliteCodecs(db: PGlite): Promise<void> {
const { rows } = await db.query<{ oid: number }>(`SELECT a.oid::int AS oid FROM pg_type a
JOIN pg_type e ON e.oid=a.typelem WHERE a.typcategory='A' AND e.typtype='c'`);
for (const { oid } of rows) delete db.parsers[oid];
+ useBufferByteaCodec(db);
+}
+
+/**
+ * PGlite's bytea codec walks every byte through a JS array of two-character
+ * strings (serialize) or a substring per byte (parse): a 4 MiB segment-text
+ * batch allocated ~250 MB of garbage per statement. Buffer's hex codec writes
+ * the same hex text in one pass. A parsed value is a Uint8Array over its own
+ * buffer, as before.
+ */
+function useBufferByteaCodec(db: PGlite): void {
+ db.serializers[types.BYTEA] = (value: unknown) => {
+ if (!(value instanceof Uint8Array)) throw new Error('Invalid input for bytea type');
+ return `\\x${Buffer.from(value.buffer, value.byteOffset, value.byteLength).toString('hex')}`;
+ };
+ (db.parsers as unknown as Record<number, Parser>)[types.BYTEA] = (value: string) => {
+ const bytes = Buffer.from(value.slice(2), 'hex');
+ return bytes.byteOffset === 0 && bytes.byteLength === bytes.buffer.byteLength ? new Uint8Array(bytes.buffer) : new Uint8Array(bytes);
+ };
}
diff --git a/test/large-pages/segmented-ingest-memory.slow.test.ts b/test/large-pages/segmented-ingest-memory.slow.test.ts
new file mode 100644
index 0000000000..ee9a0c1eca
--- /dev/null
+++ b/test/large-pages/segmented-ingest-memory.slow.test.ts
@@ -0,0 +1,81 @@
+/**
+ * Wave B (spec 2.2, 3.1): a streamed import's memory does not follow the page.
+ *
+ * Protects: importing a 32 MiB conversation page through importFromFile on
+ * PGLite (the streamed segmented path), in a fresh child process,
+ * - holds under 32 MiB of live heap more than before the import once every
+ * segment text is staged (after a full GC; ~12 MiB measured, ~117 MiB when
+ * outline headings pinned their segment texts), and
+ * - peaks (VmHWM, reset after schema init) under 450 MiB above the same child
+ * importing a 1 MiB page through the same entry point (the single-string
+ * path; the streamed path starts above PAGE_MAX_BYTES): ~300 MiB measured,
+ * ~600 with PGLite's own bytea codec, ~860 without a collection per staging
+ * batch, ~1180 with neither fix.
+ * Fails when: segment metadata keeps substrings of the segment text (outline
+ * headings, dates: the manifest rows pinned the whole decoded body), staging
+ * batches pile up garbage between collections, or PGLite's per-byte bytea
+ * codec comes back.
+ * Why existing coverage misses it: segmented-ingest.test.ts checks rows and
+ * bytes, body-scan-memory.test.ts only pass 1.
+ * Seams: a child process per import (VmHWM is per process); bun:jsc heapStats
+ * after Bun.gc(true) at the `segmented:texts_staged` fault point; no mocks.
+ */
+import { afterAll, describe, expect, test } from 'bun:test';
+import { spawnSync } from 'node:child_process';
+import { existsSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join, resolve } from 'node:path';
+import { conversationPage } from '../helpers/conversation-page.ts';
+
+const REPO = resolve(import.meta.dir, '../..');
+const RETAINED_LIMIT_MIB = 32;
+const PEAK_DELTA_LIMIT_MIB = 450;
+const dir = mkdtempSync(join(tmpdir(), 'segmented-ingest-memory-'));
+afterAll(() => rmSync(dir, { recursive: true, force: true }));
+
+const CHILD = `
+import { readFileSync, writeFileSync } from 'node:fs';
+import { heapStats } from 'bun:jsc';
+import { createEngine } from ${JSON.stringify(join(REPO, 'src/core/engine-factory.ts'))};
+import { importFromFile } from ${JSON.stringify(join(REPO, 'src/core/import-file.ts'))};
+import { readPageBodyPolicy } from ${JSON.stringify(join(REPO, 'src/core/page-body/limits.ts'))};
+import { installFaultHook } from ${JSON.stringify(join(REPO, 'src/core/persistence/fault-points.ts'))};
+const [file, brain] = process.argv.slice(-2);
+const live = () => { Bun.gc(true); const s = heapStats(); return (s.heapSize + s.extraMemorySize) / 2 ** 20; };
+const engine = await createEngine({ engine: 'pglite', database_path: brain });
+await engine.connect({ engine: 'pglite', database_path: brain });
+await engine.initSchema();
+await engine.setConfig('pages.segmented_storage', 'on');
+const bodyPolicy = await readPageBodyPolicy(engine);
+const start = live();
+writeFileSync('/proc/self/clear_refs', '5');
+let retained = null;
+installFaultHook(async point => { if (point === 'segmented:texts_staged') retained = live() - start; });
+const result = await importFromFile(engine, file, 'notes/memory-example.md', { noEmbed: true, bodyPolicy });
+const peak = Number(/^VmHWM:\\s+(\\d+) kB$/m.exec(readFileSync('/proc/self/status', 'utf8'))[1]) / 1024;
+await engine.disconnect();
+console.log(JSON.stringify({ status: result.status, error: result.error ?? null, peak, retained }));
+`;
+
+function importInChild(mib: number): { status: string; error: string | null; peak: number; retained: number | null } {
+ const file = join(dir, `page-${mib}.md`);
+ writeFileSync(file, conversationPage(mib * 2 ** 20, { seed: 1 }));
+ const run = spawnSync(process.execPath, ['--no-env-file', '-e', CHILD, file, join(dir, `brain-${mib}`)],
+ { cwd: REPO, encoding: 'utf8', timeout: 300_000, maxBuffer: 1 << 22 });
+ rmSync(file, { force: true });
+ const line = run.stdout.trim().split('\n').pop() ?? '';
+ if (run.status !== 0 || !line.startsWith('{')) throw new Error(`child import of ${mib} MiB failed (${run.status}):\n${run.stderr.slice(-2000)}`);
+ return JSON.parse(line);
+}
+
+describe.skipIf(!existsSync('/proc/self/status'))('segmented ingest memory', () => {
+ test(`a 32 MiB import retains under ${RETAINED_LIMIT_MIB} MiB while staged and peaks under ${PEAK_DELTA_LIMIT_MIB} MiB above a 1 MiB one`, () => {
+ const small = importInChild(1);
+ const large = importInChild(32);
+ expect(small.status).toBe('imported');
+ expect(large).toMatchObject({ status: 'imported', error: null });
+ expect(large.retained).not.toBeNull();
+ expect(large.retained!).toBeLessThan(RETAINED_LIMIT_MIB);
+ expect(large.peak - small.peak).toBeLessThan(PEAK_DELTA_LIMIT_MIB);
+ }, 600_000);
+});