Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(import): check streamed pass-2 blocks against pass-1 digests

garrytan12349e4bcb5a
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index bf03957699..05341355d8 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -668,6 +668,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }
{ since: 'TBD', text: 'On Postgres, title search, the source-scoped vector scan, the chunk windows search reads around its hits and `get_page` now read the new `page_body_manifest` table for every page, inline ones included, whether or not `pages.segmented_storage` is on. A database role that neither owns the tables nor bypasses row level security needs `SELECT` on it, or those reads fail with `permission_denied` (42501). Row level security is on for the new segment tables (`page_segment_texts`, `page_body_manifest`, `page_body_stagings`, `page_body_staging_parts`, `page_view_digests`) and is re-enabled on every schema replay, as for `pages`, so a role without a policy reads none of their rows. Grant the table together with the source-scoped policies in docs/ENGINES.md ("Segmented page tables"), never with an open policy, or the role reads every source\'s segment text. A runtime role that owns the tables or bypasses row level security, the default setup, needs nothing.' },
{ since: 'TBD', text: 'MCP `get_page` of a page stored in segments no longer reports `size.body_bytes` or `size.body_lines` (the stored body) to a remote caller, and its `page_body_segmented` refusal names the size of the body that caller may read, as for an inline page; the difference told how much text privacy fences and withdrawals hide. A local `gbrain get` still reports both.' },
{ since: 'TBD', text: '`gbrain get` against a remote brain of a page too large for one response holds one window in memory instead of the whole page: the windows wait in a temp file readable only by you in the system temp directory (`TMPDIR`), as large as the page and removed when the command ends, until their size and sha256 verify. Nothing prints before they do, as before. `--json` still refuses a page over 24 MiB.' },
+ { since: 'TBD', text: 'A streamed `gbrain import` or `gbrain sync` of a Markdown file over 24 MiB (`pages.segmented_storage` on) checks every block it stores against the sha256 its first read of the file recorded. A file rewritten during the import that keeps its size and modification time is now held as `file_too_large` ("the file changed while it was imported (import it again)") instead of being stored as the first version\'s frontmatter over the second version\'s body.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/page-body/streamed-import.ts b/src/core/page-body/streamed-import.ts
index 8a94919cdb..16c72af86e 100644
--- a/src/core/page-body/streamed-import.ts
+++ b/src/core/page-body/streamed-import.ts
@@ -4,8 +4,11 @@
* over `PAGE_MAX_BYTES` and at most `readPageBodyPolicy().maxBytes` is read
* twice through one descriptor and never held as one string. Pass 1
* (`BodyScanner`) parses the bounded head and decides the timeline split and
- * fence trust; pass 2 streams the stored regions through the segmenter, the
- * hash and the staging (`prepareSegmentedBody`). The publication runs in one
+ * fence trust, and records the sha256 of each READ_BYTES block of the file;
+ * pass 2 streams the stored regions through the segmenter, the hash and the
+ * staging (`prepareSegmentedBody`), reading whole blocks and checking each
+ * against its pass-1 digest, so a rewrite that keeps the size and mtime is
+ * held rather than stored as a mix of both versions. The publication runs in one
* maintenance transaction, as `importFromContent` does on an unmanaged brain.
*
* Every `importFromFile` / `importFromContent` step either runs here on the
@@ -76,6 +79,12 @@ import type { JsonObject } from './types.ts';
const READ_BYTES = 1024 * 1024;
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.
+ */
+export const streamedImportWork = { blocks: 0, bytes: 0 };
+
type StreamedImportOptions = {
noEmbed?: boolean;
inferFrontmatter?: boolean;
@@ -116,6 +125,57 @@ async function* readVirtual(file: FileHandle, bom: number, prefix: Uint8Array, s
}
}
+/** sha256 of each READ_BYTES block of the file after its BOM, from pass 1's reads whatever their sizes. */
+class BlockDigests {
+ readonly digests: string[] = [];
+ private hash = createHash('sha256');
+ private filled = 0;
+
+ push(bytes: Uint8Array): void {
+ for (let at = 0; at < bytes.length;) {
+ const take = Math.min(READ_BYTES - this.filled, bytes.length - at);
+ this.hash.update(bytes.subarray(at, at + take));
+ this.filled += take;
+ at += take;
+ if (this.filled === READ_BYTES) this.flush();
+ }
+ }
+
+ end(): readonly string[] {
+ if (this.filled) this.flush();
+ return this.digests;
+ }
+
+ private flush(): void {
+ this.digests.push(this.hash.digest('hex'));
+ this.hash = createHash('sha256');
+ this.filled = 0;
+ }
+}
+
+/**
+ * Bytes `[start, end)` of the virtual stream after pass 1, read in whole READ_BYTES blocks of the file; a block whose
+ * sha256 differs from its pass-1 digest sets `drift.changed`, and the caller holds the import.
+ */
+async function* readChecked(file: FileHandle, bom: number, prefix: Uint8Array, size: number, digests: readonly string[], drift: { changed: boolean },
+ start: number, end: number): AsyncIterable<Uint8Array> {
+ if (start < prefix.length) yield prefix.subarray(start, Math.min(end, prefix.length));
+ const from = Math.max(start, prefix.length) - prefix.length, to = end - prefix.length;
+ for (let block = Math.floor(from / READ_BYTES); from < to && block * READ_BYTES < to; block++) {
+ const offset = block * READ_BYTES;
+ const buffer = Buffer.allocUnsafe(Math.min(READ_BYTES, size - bom - offset));
+ for (let filled = 0; filled < buffer.length;) {
+ const { bytesRead } = await file.read(buffer, filled, buffer.length - filled, bom + offset + filled);
+ if (bytesRead === 0) throw new Error('The file shrank while it was imported.');
+ filled += bytesRead;
+ }
+ streamedImportWork.blocks++;
+ streamedImportWork.bytes += buffer.length;
+ if (createHash('sha256').update(buffer).digest('hex') !== digests[block]) drift.changed = true;
+ yield buffer.subarray(Math.max(from - offset, 0), Math.min(to - offset, buffer.length));
+ }
+}
+
/** One stored region: its pieces in order, NUL bytes stripped (`sanitizeText` on a valid UTF-8 stream), every chunk passed to `inspect`. */
async function* regionStream(pieces: readonly BodyPiece[], read: (start: number, end: number) => AsyncIterable<Uint8Array>,
inspect: (bytes: Uint8Array) => void): AsyncIterable<Uint8Array> {
@@ -178,12 +238,17 @@ class CodeRefLines {
}
}
-/** Pass 1 over the virtual stream; `prefix` is inferred frontmatter (empty when none). `hash` receives the file's bytes after its BOM. */
-async function scanFile(file: FileHandle, bom: number, prefix: Uint8Array, size: number, relativePath: string, opts: StreamedImportOptions, hash: Hash | null) {
+/**
+ * Pass 1 over the virtual stream; `prefix` is inferred frontmatter (empty when none). `hash` and `blocks` receive the
+ * file's bytes after its BOM.
+ */
+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);
for await (const part of readVirtual(file, bom, new Uint8Array(0), 0, size - bom)) {
hash?.update(part);
+ blocks.push(part);
scanner.push(part);
}
return scanner.finish();
@@ -228,22 +293,23 @@ export async function importStreamedMarkdownFile(engine: BrainEngine, filePath:
const prefix = opts.inferFrontmatter !== false ? await inferredPrefix(file, bom, size, relativePath) : new Uint8Array(0);
if (!prefix) return hold(expectedSlug, size, 'frontmatter inference reads the first 20 lines, and they are not within the file head');
const hash = opts.coordinated ? createHash('sha256').update(bomBytes.subarray(0, bom)) : null;
- const scan = await scanFile(file, bom, prefix, size, relativePath, opts, hash);
+ const blocks = new BlockDigests();
+ const scan = await scanFile(file, bom, prefix, size, relativePath, opts, hash, blocks);
if (hash && hash.digest('hex') !== opts.coordinated!.sha256) throw opError('source_changed', 'The input file changed after import admission.',
`${relativePath} no longer has the bytes its import request admitted, so the request published nothing. Import it again to publish the current bytes.`);
if (scan.kind === 'frontmatter_head_unbounded') {
return { slug: expectedSlug, status: 'skipped', chunks: 0, error: scan.message, refusal: { code: 'invalid_frontmatter', message: scan.message }, skip_reason: 'invalid_frontmatter' };
}
if (scan.kind === 'invalid_utf8') return hold(expectedSlug, size, `the file is not valid UTF-8 at byte ${scan.offset} (the text path decodes it lossily)`);
- return await importScanned(engine, { file, bom, prefix, size, scan, relativePath, filePath, expectedSlug, stat, policy, opts });
+ return await importScanned(engine, { file, bom, prefix, size, digests: blocks.end(), scan, relativePath, filePath, expectedSlug, stat, policy, opts });
} finally {
await file.close();
}
}
-async function importScanned(engine: BrainEngine, input: { file: FileHandle; bom: number; prefix: Uint8Array; size: number; scan: BodyScan;
+async function importScanned(engine: BrainEngine, input: { file: FileHandle; bom: number; prefix: Uint8Array; size: number; digests: readonly string[]; scan: BodyScan;
relativePath: string; filePath: string; expectedSlug: string; stat: { mtimeMs: number; birthtime: Date; mtime: Date }; policy: PageBodyPolicy; opts: StreamedImportOptions }): Promise<ImportResult> {
- const { file, bom, prefix, size, scan, relativePath, expectedSlug, opts } = input;
+ const { file, bom, prefix, size, digests, scan, relativePath, expectedSlug, opts } = input;
const sourceId = opts.sourceId ?? 'default';
const parsed = { ...scan.parsed, compiled_truth: '', timeline: '' } as ParsedMarkdown;
const frontmatterHold = classifyImportHold(parsed);
@@ -264,7 +330,8 @@ async function importScanned(engine: BrainEngine, input: { file: FileHandle; bom
}
if (hasGuardrails()) return hold(slug, size, 'a registered guardrail reads the whole payload');
if (scan.bodyFlags.has_nul) return hold(slug, size, 'NUL bytes change the stored size the content gate measures');
- const read = (start: number, end: number) => readVirtual(file, bom, prefix, start, end);
+ const drift = { changed: false };
+ const read = (start: number, end: number) => readChecked(file, bom, prefix, size, digests, drift, start, end);
parsed.title = sanitizeText(parsed.title);
delete parsed.frontmatter[QUARANTINE_OVERRIDE_KEY];
const writeGate = await ownerSourceGateInput(engine, sourceId, parsed.frontmatter);
@@ -326,7 +393,7 @@ async function importScanned(engine: BrainEngine, input: { file: FileHandle; bom
codeRefs.end();
const abort = async () => { await engine.setBodyStagingState(prepared.stagingId, 'aborted').catch(() => undefined); };
const after = await file.stat();
- if (after.size !== size || after.mtimeMs !== input.stat.mtimeMs) { await abort(); return hold(slug, size, 'the file changed while it was imported (import it again)'); }
+ if (drift.changed || after.size !== size || after.mtimeMs !== input.stat.mtimeMs) { await abort(); return hold(slug, size, 'the file changed while it was imported (import it again)'); }
if (fenced) { await abort(); return hold(slug, size, 'facts and takes fences are normalized and checked against withdrawals over the whole body'); }
const hash = prepared.body.content_hash;
if (existing && !existing.deleted_at && !opts.forceRechunk && existing.content_hash === hash && existing.text_projection_revision === existing.knowledge_revision
diff --git a/test/large-pages/streamed-import-drift.test.ts b/test/large-pages/streamed-import-drift.test.ts
new file mode 100644
index 0000000000..7ede7cc927
--- /dev/null
+++ b/test/large-pages/streamed-import-drift.test.ts
@@ -0,0 +1,92 @@
+/**
+ * A streamed import (a Markdown file over PAGE_MAX_BYTES, `pages.segmented_storage` on) reads its file twice;
+ * a rewrite between the passes that keeps the size and the mtime is held, never stored as a mix of both versions.
+ *
+ * 1. Protects: pass 2 reads whole file blocks and checks each against the sha256 pass 1 recorded, so a file
+ * rewritten after pass 1 (same size, mtime restored with utimes) is held as `file_too_large` "the file changed
+ * while it was imported" with nothing stored, and imports whole once it holds still; an unchanged file reads
+ * each block after pass 1 about once (streamedImportWork).
+ * 2. Fails when: pass 2 trusts size and mtime alone, which stores the pass-1 frontmatter (title) over the
+ * pass-2 body.
+ * 3. Existing coverage: managed-streamed-import.test.ts checks a managed import's admitted sha256 on pass 1 only.
+ * 4. No production seam: the rewrite runs in a wrapped engine.getPage (unbound, so a transaction derived from
+ * the engine keeps its own connection), which importScanned calls after pass 1 and before pass 2. Runs on
+ * PGLite, and on Postgres when DATABASE_URL is set.
+ */
+import { afterAll, beforeAll, expect, test } from 'bun:test';
+import { mkdtempSync, rmSync, statSync, utimesSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';
+import type { BrainEngine } from '../../src/core/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 { conversationBody } from '../helpers/conversation-page.ts';
+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';
+
+const MiB = 1024 * 1024;
+const SLUG = 'notes/drift-example';
+const MTIME = 1_700_000_000;
+const body = conversationBody(PAGE_MAX_BYTES + MiB, { seed: 41 });
+const version = (tag: 'old' | 'new') => `---\ntype: note\ntitle: Drift ${tag}\n---\n\nhead-${tag}-marker\n\n${body}\n\ntail-${tag}-marker\n`;
+
+const dir = mkdtempSync(join(tmpdir(), 'gbrain-streamed-drift-'));
+const engines: BrainEngine[] = [];
+let closePostgres: (() => Promise<void>) | undefined;
+
+beforeAll(async () => {
+ const lite = new PGLiteEngine(); await lite.connect({}); await lite.initSchema(); engines.push(lite);
+ if (process.env.DATABASE_URL) { const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL); engines.push(pg.engine); closePostgres = pg.close; }
+ for (const engine of engines) await engine.setConfig('pages.segmented_storage', 'on');
+}, 120_000);
+
+afterAll(async () => {
+ for (const engine of engines) if (engine.kind === 'pglite') await engine.disconnect();
+ await closePostgres?.();
+ rmSync(dir, { recursive: true, force: true });
+});
+
+function writeVersion(file: string, tag: 'old' | 'new'): void {
+ writeFileSync(file, version(tag));
+ utimesSync(file, MTIME, MTIME);
+}
+
+async function stored(engine: BrainEngine) {
+ const [row] = await engine.executeRaw<{ title: string; body_storage: string }>('SELECT title, body_storage FROM pages WHERE slug=$1', [SLUG]);
+ return row ?? null;
+}
+
+const importFile = async (engine: BrainEngine, file: string) =>
+ importFromFile(engine, file, `${SLUG}.md`, { noEmbed: true, bodyPolicy: await readPageBodyPolicy(engine) });
+
+test('a file rewritten between the passes with the same size and mtime is held, then imports whole', async () => {
+ for (const engine of engines) {
+ await engine.executeRaw('DELETE FROM pages');
+ const file = join(dir, `${engine.kind}.md`);
+ writeVersion(file, 'old');
+ const before = statSync(file);
+ const getPage = engine.getPage;
+ let rewritten = false;
+ engine.getPage = (async function (this: BrainEngine, slug: string, opts?: Parameters<BrainEngine['getPage']>[1]) {
+ if (slug === SLUG && !rewritten) { rewritten = true; writeVersion(file, 'new'); }
+ return getPage.call(this, slug, opts);
+ }) as BrainEngine['getPage'];
+ let result;
+ try { result = await importFile(engine, file); } finally { engine.getPage = getPage; }
+ const after = statSync(file);
+ expect(rewritten).toBe(true);
+ expect([after.size, after.mtimeMs]).toEqual([before.size, before.mtimeMs]);
+ const page = await stored(engine);
+ expect<Record<string, unknown>>({ status: result.status, title: page?.title ?? null }).toEqual({ status: 'skipped', title: null });
+ expect(result.refusal?.code).toBe('file_too_large');
+ expect(result.error).toContain('the file changed while it was imported');
+
+ Object.assign(streamedImportWork, { blocks: 0, bytes: 0 });
+ expect((await importFile(engine, file)).status).toBe('imported');
+ expect(await stored(engine)).toEqual({ title: 'Drift new', body_storage: 'segmented' });
+ expect(streamedImportWork.bytes).toBeGreaterThanOrEqual(PAGE_MAX_BYTES);
+ expect(streamedImportWork.bytes).toBeLessThanOrEqual(after.size + 10 * MiB);
+ }
+}, 600_000);
diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txt
index c988f9609f..9c5054463c 100644
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@ -122,6 +122,7 @@ test/large-pages/segmented-switch.test.ts
test/large-pages/segmented-think-compile-leads.serial.test.ts
test/large-pages/segmented-timeline-retract-versions.test.ts
test/large-pages/segmented-versions.test.ts
+test/large-pages/streamed-import-drift.test.ts
test/large-pages/v249-master-reader-compat.test.ts
test/link-cross-source.test.ts
test/link-preparation-shared-index.test.ts