Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Wave B lane 1d: managed import over the single-string ceiling (body_ref intent, streamed preparer, database-only publication); segment writes and GC under the managed-writer guard

garrytan535b32baab63
diff --git a/src/core/page-body/ingest.ts b/src/core/page-body/ingest.ts
index d0350999db..bf5c5d1aa5 100644
--- a/src/core/page-body/ingest.ts
+++ b/src/core/page-body/ingest.ts
@@ -17,6 +17,10 @@ import { randomUUID } from 'node:crypto';
import type { BrainEngine } from '../engine.ts';
import { stableJson } from '../persistence/digest.ts';
import { faultPoint } from '../persistence/fault-points.ts';
+import { withCoordinatedWrite } from '../persistence/context.ts';
+import { readManagedMode } from '../persistence/managed-mode.ts';
+import { maintenanceAttribution, principalAttribution } from '../persistence/attribution.ts';
+import type { Principal } from '../persistence/model.ts';
import { stepFenceWalk, type FenceWalk } from '../fence-scan.ts';
import { BODY_LEAD_BYTES, BODY_STAGING_HARD_MS, BODY_STAGING_IDLE_MS, STAGE_BATCH_BYTES } from './limits.ts';
import type { BodyRegion, BodyStagingKind, BodyStorage, JsonObject, ManifestRow, ManifestRowInput, SegmentChunkInput,
@@ -85,6 +89,21 @@ export interface PreparedSegmentedBody {
stagedChunkIndexes: number[];
}
+/**
+ * Runs writes to the guarded segment tables (texts, manifest rows, sweeps) of
+ * `sourceId` outside a publication transaction. On a managed brain they run in
+ * a coordinated write for that source, as the writer guard requires
+ * (writer-guard-schema.ts); the caller is the source's owner preparing or
+ * collecting its own write (`principal`, else the local maintenance writer).
+ * On any other brain they run directly.
+ */
+export async function segmentWriteScope(engine: BrainEngine, sourceId: string, principal?: Principal):
+ Promise<<T>(fn: (exec: BrainEngine) => Promise<T>) => Promise<T>> {
+ if (!await readManagedMode(engine)) return fn => fn(engine);
+ const attribution = principal ? principalAttribution(principal) : await maintenanceAttribution(engine);
+ return fn => engine.transaction(tx => withCoordinatedWrite(tx, [sourceId], () => fn(tx), attribution));
+}
+
/** A region of a string as a byte stream, sliced on code-point boundaries. */
export async function* stringRegion(text: string, sliceChars = 256 * 1024): AsyncIterable<Uint8Array> {
const encoder = new TextEncoder();
@@ -185,6 +204,7 @@ async function stageBody(engine: BrainEngine, input: SegmentedBodyInput, staging
const same = byKey.get(key);
if (same) same.push(row); else byKey.set(key, [row]);
}
+ const writes = await segmentWriteScope(engine, input.sourceId, { kind: input.owner.principalKind as Principal['kind'], id: input.owner.principalId });
const batchBytes = STAGE_BATCH_BYTES[engine.kind];
const expectedGeneration = input.live?.generation ?? 0;
const newGeneration = expectedGeneration + 1;
@@ -197,7 +217,8 @@ async function stageBody(engine: BrainEngine, input: SegmentedBodyInput, staging
let pendingBytes = 0;
const flushTexts = async () => {
if (!pending.length) return;
- await engine.stageSegmentTexts(input.sourceId, pending.splice(0));
+ const batch = pending.splice(0);
+ await writes(exec => exec.stageSegmentTexts(input.sourceId, batch));
pendingBytes = 0;
if (engine.kind === 'pglite') await new Promise(resolve => setImmediate(resolve));
};
@@ -283,7 +304,7 @@ async function stageBody(engine: BrainEngine, input: SegmentedBodyInput, staging
return { stagingId, expectedGeneration, newGeneration, createRows: rows, closeOccurrences: [], retireChunkOccurrences: [],
unchunked: rows.length, body, bodyUnchanged: false, rows: { texts, manifest: rows.length, chunks: 0 }, stagedChunkIndexes: [] };
}
- if (changed.length) await engine.stageManifestRows(changed);
+ if (changed.length) await writes(exec => exec.stageManifestRows(changed));
await faultPoint('segmented:manifest_staged', { sourceId: input.sourceId });
const chunkable = await occurrencesWithoutChunks(engine, input.live.id, expectedGeneration, rows);
const chunks = await stageOccurrenceChunks(engine, { pageId: input.live.id, sourceId: input.sourceId, slug: input.slug, generation: newGeneration,
diff --git a/src/core/page-body/streamed-import.ts b/src/core/page-body/streamed-import.ts
index 73d9b4766e..e381830bf5 100644
--- a/src/core/page-body/streamed-import.ts
+++ b/src/core/page-body/streamed-import.ts
@@ -31,11 +31,15 @@
* (the string path decodes it lossily); a deleted existing page (a restore
* rewrites it through the inline writer); a file that changes between passes.
*/
-import { open, type FileHandle } from 'node:fs/promises';
+import { createHash, type Hash } from 'node:crypto';
+import { lstat, open, type FileHandle } from 'node:fs/promises';
import { constants } from 'node:fs';
import { basename, resolve } from 'node:path';
import type { BrainEngine } from '../engine.ts';
import type { ImportResult } from '../import-file.ts';
+import type { PreparedContentImport } from '../persistence/prepared-import.ts';
+import type { PageSnapshot } from '../page-state/types.ts';
+import { opError } from '../ops/contract.ts';
import { BodyScanner, type BodyPiece, type BodyScan } from './body-scan.ts';
import { FRONTMATTER_HEAD_MAX_BYTES, SEGMENT_MAX_BYTES, type PageBodyPolicy } from './limits.ts';
import { PAGE_MAX_BYTES } from '../page-size-policy.ts';
@@ -65,7 +69,7 @@ import { isEmbedSkipped } from '../embed-skip.ts';
import { sanitizeText } from '../batch-rows.ts';
import { applySegmentedBody, sealSegmentedPage, segmentedLivePage } from '../persistence/segmented-apply.ts';
import { buildSegmentedProjection } from './projection.ts';
-import { prepareSegmentedBody, utf8Prefix } from './ingest.ts';
+import { prepareSegmentedBody, segmentWriteScope, utf8Prefix, type SegmentedStagingOwner } from './ingest.ts';
import type { JsonObject } from './types.ts';
const READ_BYTES = 1024 * 1024;
@@ -78,8 +82,19 @@ type StreamedImportOptions = {
forceRechunk?: boolean;
activePack?: { page_types: ReadonlyArray<{ name: string; path_prefixes: ReadonlyArray<string>; aliases?: ReadonlyArray<string> }> };
firstCommitAt?: Date;
+ /**
+ * A managed import's preparation (import-prepare.ts): the file must hash to
+ * `sha256` (the admitted bytes), the page base is the caller's snapshot, and
+ * instead of publishing, the prepared write goes to `prepare`, whose apply
+ * runs in the coordinator's publication transaction.
+ */
+ coordinated?: { snapshot: PageSnapshot | null; owner: SegmentedStagingOwner; sha256: string;
+ prepare(prepared: StreamedPreparedImport): Promise<ImportResult> };
};
+/** A coordinated streamed import ready to publish: no parsed body strings exist, only the page's frontmatter. */
+export type StreamedPreparedImport = Omit<PreparedContentImport, 'parsedPage'> & { frontmatter: Record<string, unknown> };
+
/** Today's refusal of a file over the single-string ceiling, naming the step that needs the whole body. */
function hold(slug: string, size: number, reason: string): ImportResult {
const message = `File too large (${size} bytes, max ${PAGE_MAX_BYTES}): ${reason}, which needs the whole body as one string.`;
@@ -151,11 +166,14 @@ class CodeRefLines {
}
}
-/** Pass 1 over the virtual stream; `prefix` is inferred frontmatter (empty when none). */
-async function scanFile(file: FileHandle, bom: number, prefix: Uint8Array, size: number, relativePath: string, opts: StreamedImportOptions) {
+/** 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) {
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)) scanner.push(part);
+ for await (const part of readVirtual(file, bom, new Uint8Array(0), 0, size - bom)) {
+ hash?.update(part);
+ scanner.push(part);
+ }
return scanner.finish();
}
@@ -177,7 +195,7 @@ export async function importStreamedMarkdownFile(engine: BrainEngine, filePath:
return { slug: '', status: 'skipped', skip_reason: 'malformed_path', chunks: 0,
error: `Path "${relativePath}" contains bracket or control characters and cannot be imported. Rename the file to import it.` };
}
- await assertUnmanagedCanonicalWriter(engine, 'direct content import');
+ if (!opts.coordinated) await assertUnmanagedCanonicalWriter(engine, 'direct content import');
const expectedSlug = slugifyPath(relativePath);
const file = await open(assertSourceFilePath(filePath), constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
try {
@@ -189,7 +207,10 @@ export async function importStreamedMarkdownFile(engine: BrainEngine, filePath:
const bom = bomBytes[0] === 0xef && bomBytes[1] === 0xbb && bomBytes[2] === 0xbf ? 3 : 0;
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 scan = await scanFile(file, bom, prefix, size, relativePath, opts);
+ const hash = opts.coordinated ? createHash('sha256').update(bomBytes.subarray(0, bom)) : null;
+ const scan = await scanFile(file, bom, prefix, size, relativePath, opts, hash);
+ 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' };
}
@@ -235,7 +256,7 @@ async function importScanned(engine: BrainEngine, input: { file: FileHandle; bom
const truthHead = await regionHead(scan.truth, read, SCAN_HEAD_BYTES * 4);
const head = { ...parsed, compiled_truth: truthHead, timeline: truthHead.length >= SCAN_HEAD_BYTES ? '' : await regionHead(scan.timeline, read, SCAN_HEAD_BYTES * 4) };
const disposition = await settleContentDisposition(engine, head, { slug, sourceId, stripped: false, writeGate, bodyBytes });
- const existing = await engine.getPage(slug, { sourceId, includeDeleted: true });
+ const existing = opts.coordinated ? opts.coordinated.snapshot?.page ?? null : await engine.getPage(slug, { sourceId, includeDeleted: true });
if (existing?.deleted_at) return hold(slug, size, 'restoring a deleted page rewrites its body through the inline writer');
if (existing) stabilizeSafetyAssessments(parsed.frontmatter, existing.frontmatter);
const sourceRoot = resolve(input.filePath, ...relativePath.split(/[\\/]/).map(() => '..'));
@@ -257,7 +278,12 @@ async function importScanned(engine: BrainEngine, input: { file: FileHandle; bom
if (typeof fmId === 'string' && fmId.length > 0) return hold(slug, size, 'identity dedup by frontmatter id compares whole bodies');
parsed.tags.sort();
const { mode, corpusGeneration } = await resolveImportContextualMode(engine, sourceId, parsed.frontmatter, false);
- const { principal } = await maintenanceAttribution(engine);
+ let owner: SegmentedStagingOwner;
+ if (opts.coordinated) owner = opts.coordinated.owner;
+ else {
+ const { principal } = await maintenanceAttribution(engine);
+ owner = { kind: 'import', principalKind: principal.kind, principalId: principal.id, baseRevision: existing?.knowledge_revision ?? null };
+ }
const live = existing ? await segmentedLivePage(engine, Number(existing.id)) : null;
let fenced = false;
const codeRefs = new CodeRefLines();
@@ -274,7 +300,7 @@ async function importScanned(engine: BrainEngine, input: { file: FileHandle; bom
timeline: (async function* () { codeRefs.end(); carry = ''; yield* regionStream(scan.timeline, read, inspect); })(),
hasTimeline: scan.timelineBytes > 0, flags: { fence_trust: scan.bodyFlags.fence_trust, timeline_fence_trust: scan.bodyFlags.timeline_fence_trust, timeline_split: scan.bodyFlags.timeline_split },
declaredBytes: scan.truthBytes + scan.timelineBytes,
- owner: { kind: 'import', principalKind: principal.kind, principalId: principal.id, baseRevision: existing?.knowledge_revision ?? null },
+ owner,
chunking: { quarantined: disposition.quarantined, corpusGeneration, tier: mode === 'title' ? 'title' : 'none' } });
codeRefs.end();
const abort = async () => { await engine.setBodyStagingState(prepared.stagingId, 'aborted').catch(() => undefined); };
@@ -285,7 +311,9 @@ async function importScanned(engine: BrainEngine, input: { file: FileHandle; bom
if (existing && !existing.deleted_at && !opts.forceRechunk && existing.content_hash === hash && existing.text_projection_revision === existing.knowledge_revision
&& isEmbedSkipped(existing.frontmatter) === isEmbedSkipped(parsed.frontmatter) && !trustMarkerChanged(existing.frontmatter, parsed.frontmatter)) {
await abort();
- return { slug, status: 'skipped', chunks: 0, ...(typeWarning ? { type_warning: typeWarning } : {}) };
+ const skipped: ImportResult = { slug, status: 'skipped', chunks: 0, ...(typeWarning ? { type_warning: typeWarning } : {}) };
+ return opts.coordinated ? opts.coordinated.prepare({ slug, observedRevision: opts.coordinated.snapshot?.revision ?? null, noop: true, result: skipped, frontmatter: parsed.frontmatter,
+ validate: async () => {}, apply: async () => {} }) : skipped;
}
const identity = await decideImportIdentity(engine, { sourceId, slug, hash, frontmatterId: null, sourcePath: relativePath, sourceRoot, body: { title: parsed.title, compiled_truth: '', timeline: '' } });
if (identity.kind === 'shared_hash') process.stderr.write(`[import] WARNING: ${relativePath} shares content_hash with ${identity.dupSlug} in source ${sourceId}. Indexing both.\n`);
@@ -300,9 +328,8 @@ async function importScanned(engine: BrainEngine, input: { file: FileHandle; bom
source_kind: null, source_uri: fileOriginUri(existing?.source_uri, sourceRoot, relativePath), ingested_via: null };
const linkOpts = { fromSourceId: sourceId, toSourceId: sourceId, originSourceId: sourceId };
const refs = prepared.body.body_flags.has_protected ? [] : [...codeRefs.refs.values()];
- const applied = await maintenanceTransaction(engine, async tx => {
- await assertImportBase(tx, slug, sourceId, existing);
- if (existing) await tx.createVersion(slug, { sourceId });
+ const apply = async (tx: BrainEngine, preimage?: PageSnapshot | null) => {
+ if (existing) await tx.createVersion(slug, preimage ? { sourceId, preimage } : { sourceId });
const result = await applySegmentedBody(tx, { slug, sourceId, pageId: live?.id ?? null, prepared, meta, promotion: live?.storage === 'inline', retireMaxRows: input.policy.flipRetireMaxRows });
await tx.updatePageContextualRetrievalState(slug, sourceId, mode, corpusGeneration);
await tx.executeRaw(`DELETE FROM tags t USING pages p WHERE p.id = t.page_id AND p.source_id = $1 AND p.slug = $2
@@ -319,10 +346,32 @@ async function importScanned(engine: BrainEngine, input: { file: FileHandle; bom
await verifyPageReadable(tx, slug, hash, sourceId, 'importStreamedMarkdownFile');
await disposition.persistReceipt(tx, { existed: !!existing });
return result;
- }, writeTrustOfGate(writeGate)).catch(async error => { await abort(); throw error; });
- if (!applied.complete) await buildSegmentedProjection(engine, { sourceId, slug }).catch(() => undefined);
- await engine.sweepSegments({ pageId: applied.pageId }).catch(() => undefined);
- return { slug, status: 'imported', chunks: prepared.rows.chunks,
+ };
+ const afterCommit = async (target: BrainEngine, applied: { pageId: number; complete: boolean }) => {
+ if (!applied.complete) await buildSegmentedProjection(target, { sourceId, slug }).catch(() => undefined);
+ await segmentWriteScope(target, sourceId).then(writes => writes(exec => exec.sweepSegments({ pageId: applied.pageId }))).catch(() => undefined);
+ };
+ const imported: ImportResult = { slug, status: 'imported', chunks: prepared.rows.chunks,
...(disposition.quarantined ? { quarantined: true } : {}), ...(disposition.flagged ? { flagged: true, flag_reason: disposition.flagReason } : {}),
...(disposition.gate ? { gate: disposition.gate } : {}), ...(typeWarning ? { type_warning: typeWarning } : {}) };
+ if (opts.coordinated) {
+ let applied: { pageId: number; complete: boolean } | null = null;
+ return opts.coordinated.prepare({ slug, observedRevision: opts.coordinated.snapshot?.revision ?? null, noop: false, contentHash: hash, result: imported, frontmatter: parsed.frontmatter,
+ validate: async () => {
+ const now = await lstat(input.filePath);
+ if (now.size !== size || now.mtimeMs !== input.stat.mtimeMs) throw opError('source_changed', 'The input file changed after import preparation.',
+ `${relativePath} changed after its import request was prepared, so the request published nothing. Import it again to publish the current bytes.`);
+ },
+ apply: async (tx, preimage) => {
+ applied = await apply(tx, preimage);
+ return { pageId: applied.pageId, sealed: applied.complete, segmented: { complete: applied.complete } };
+ },
+ afterCommit: async target => { if (applied) await afterCommit(target, applied); } });
+ }
+ const applied = await maintenanceTransaction(engine, async tx => {
+ await assertImportBase(tx, slug, sourceId, existing);
+ return apply(tx);
+ }, writeTrustOfGate(writeGate)).catch(async error => { await abort(); throw error; });
+ await afterCommit(engine, applied);
+ return imported;
}
diff --git a/src/core/persistence/coordinator.ts b/src/core/persistence/coordinator.ts
index 40dbce05f2..5887e077ec 100644
--- a/src/core/persistence/coordinator.ts
+++ b/src/core/persistence/coordinator.ts
@@ -42,6 +42,7 @@ import { fenceFailureDetail } from '../fence-repair/refusal.ts';
import { withdrawalFailureDetail } from '../facts/withdrawal.ts';
import { faultPoint, withFaultPoints } from './fault-points.ts';
import { recordPublicationFenceTrend } from '../fence-repair/census-store.ts';
+import { segmentWriteScope } from '../page-body/ingest.ts';
interface PreparedMutationBase {
sourceExclusive?: boolean;
@@ -556,7 +557,8 @@ export async function recoverPublication(engine: BrainEngine, id: string, hostId
await faultPoint('publication_recovery:before_clear', { requestId: row.request_id, sourceId: row.source_id, operation: row.operation });
await clearResolvedRecovery(engine, id);
row = (await getWriteRequestById(engine, id))!;
- if (row.page_id !== null && row.state === 'committed') await engine.sweepSegments({ pageId: Number(row.page_id) }).catch(() => undefined);
+ const pageId = row.page_id === null || row.state !== 'committed' ? null : Number(row.page_id);
+ if (pageId !== null) await segmentWriteScope(engine, row.source_id).then(writes => writes(exec => exec.sweepSegments({ pageId }))).catch(() => undefined);
}
return row;
} finally { releaseCapacity?.(); await lock?.release(); }
diff --git a/src/core/persistence/import-mutations.ts b/src/core/persistence/import-mutations.ts
index ececb54882..b3f3a5bad3 100644
--- a/src/core/persistence/import-mutations.ts
+++ b/src/core/persistence/import-mutations.ts
@@ -15,7 +15,9 @@ import { assertPersistenceAccepting, waitForWrites } from './service.ts';
import type { WriteAdmission } from './journal.ts';
import type { WriteRequest } from './model.ts';
import { digest, sha256 } from './digest.ts';
-import { assertImportPaths, managedImportContent, prepareManagedImportMutation, readImportBytes, type ImportPack, type ManagedImportIntent } from './import-prepare.ts';
+import { assertImportPaths, managedImportContent, managedStreamedIdentity, prepareManagedImportMutation, readImportBytes, type ImportPack, type ManagedImportBodyRef,
+ type ManagedImportIntent } from './import-prepare.ts';
+import { readPageBodyPolicy } from '../page-body/limits.ts';
import { submissionAuthority } from './authority.ts';
import { inspectUnchanged, screeningRequest } from './noop-kernel.ts';
import { withScreeningPaths } from './screening-paths.ts';
@@ -104,7 +106,8 @@ export async function importManagedFiles(engine: BrainEngine, files: readonly Ma
{ fix: readFix(`Shows source ${sourceId}'s owner host and state, read-only.`, { argv: ['gbrain', 'sources', 'writer', 'status', '--source', sourceId, '--json'] }) }) : null;
const ctx = { engine, remote: false, sourceId, config: loadConfig() ?? { engine: engine.kind } } as OperationContext;
const reads = batchSharedReads(engine);
- const planned: Array<{ i: number; slug: string; content: string; sourcePath: string; path: string; inputPath: string; inputHash: string; target: string }> = [];
+ const bodyPolicy = await readPageBodyPolicy(engine);
+ const planned: Array<{ i: number; slug: string; content?: string; bodyRef?: ManagedImportBodyRef; sourcePath: string; path: string; inputPath: string; inputHash: string; target: string }> = [];
const slugs = new Set<string>();
let rest = files.length;
await withScreeningPaths(async () => { for (let i = 0; i < files.length; i++) {
@@ -123,11 +126,13 @@ export async function importManagedFiles(engine: BrainEngine, files: readonly Ma
const path = canonicalInput ? canonicalRelative : sourcePath;
const target = resolve(root, path);
await assertImportPaths(reads, sourceId, root, inputPath, target);
- const bytes = readImportBytes(inputPath);
- const { slug, content } = managedImportContent(sourcePath, bytes, opts.activePack);
+ const streamed = await managedStreamedIdentity(sourcePath, inputPath, target, bodyPolicy);
+ const bytes = streamed ? null : readImportBytes(inputPath);
+ const { slug, content } = streamed ? { slug: streamed.slug, content: undefined } : managedImportContent(sourcePath, bytes!, opts.activePack);
if (slugs.has(slug)) { rest = i; break; }
slugs.add(slug);
- planned.push({ i, slug, content, sourcePath, path, inputPath, inputHash: sha256(bytes), target });
+ planned.push({ i, slug, content, ...(streamed ? { bodyRef: streamed.bodyRef } : {}), sourcePath, path, inputPath,
+ inputHash: streamed ? streamed.bodyRef.sha256 : sha256(bytes!), target });
} catch (error) { fail(i, error); }
} });
if (planned.length) await importPlanned(ctx, binding!, planned, opts, fail, (i, value) => { settled[i] = { status: 'fulfilled', value }; });
@@ -136,7 +141,7 @@ export async function importManagedFiles(engine: BrainEngine, files: readonly Ma
}
async function importPlanned(ctx: OperationContext, binding: WorktreeBinding,
- planned: Array<{ i: number; slug: string; content: string; sourcePath: string; path: string; inputPath: string; inputHash: string; target: string }>,
+ planned: Array<{ i: number; slug: string; content?: string; bodyRef?: ManagedImportBodyRef; sourcePath: string; path: string; inputPath: string; inputHash: string; target: string }>,
opts: { noEmbed?: boolean; activePack?: ImportPack },
fail: (i: number, reason: unknown) => void, done: (i: number, value: ImportResult) => void): Promise<void> {
const { engine } = ctx;
@@ -156,7 +161,7 @@ async function importPlanned(ctx: OperationContext, binding: WorktreeBinding,
if (stored.inputHash !== member.inputHash || stored.slug !== member.slug) throw opError('internal_error', 'A pending import checkpoint does not match the file it is keyed by.',
`The checkpointed import of ${member.sourcePath} (request ${stored.request_id}) in source ${sourceId} records a different input than the bytes just read under the same key, so nothing was resubmitted. Report it with gbrain doctor --json.`);
member.stored = stored;
- member.params = { ...stored, content: member.content } as PendingImport;
+ member.params = { ...stored, ...(member.content !== undefined ? { content: member.content } : {}) } as PendingImport;
};
const open = new Set(members);
const settle = (member: (typeof members)[number], value: ImportResult) => { open.delete(member); done(member.i, value); };
@@ -178,7 +183,8 @@ async function importPlanned(ctx: OperationContext, binding: WorktreeBinding,
const snapshot = screened ? screened.get(pageSnapshotKey(sourceId, member.slug)) ?? null : await engine.readPageSnapshot(member.slug, { sourceId, includeDeleted: true });
// The input is the canonical file itself (the common case): its hash was taken from the bytes just read.
const targetHash = member.target === member.inputPath ? member.inputHash : existsSync(member.target) ? sha256(readImportBytes(member.target)) : null;
- const intent: ManagedImportIntent = { kind: 'managed_file_import', slug: member.slug, content: member.content, sourcePath: member.sourcePath, path: member.path,
+ const intent: ManagedImportIntent = { kind: 'managed_file_import', slug: member.slug, ...(member.bodyRef ? { body_ref: member.bodyRef } : { content: member.content }),
+ sourcePath: member.sourcePath, path: member.path,
inputPath: member.inputPath, inputHash: member.inputHash, targetHash,
ownerEpoch: String(binding.owner_epoch), ...(snapshot ? { expected_revision: snapshot.revision } : {}),
noEmbed: !!opts.noEmbed, ...(opts.activePack ? { activePack: opts.activePack } : {}) };
@@ -271,9 +277,13 @@ async function submitManagedImports(ctx: OperationContext, batch: string, params
return settled;
}
-/** Runs the managed-import preparer on an unadmitted request; true only when the no-op kernel finds nothing to publish. */
+/**
+ * Runs the managed-import preparer on an unadmitted request; true only when the no-op kernel finds nothing to publish.
+ * A file admitted by reference (`body_ref`) is not screened: its screen would stream and stage the whole body, so its
+ * publication decides the no-op.
+ */
async function unchangedManagedImport(ctx: OperationContext, binding: WorktreeBinding, intent: ManagedImportIntent, snapshot: PageSnapshot | null): Promise<boolean> {
- if (!snapshot) return false;
+ if (!snapshot || intent.body_ref) return false;
// #6529: an image's preparation is provider work (OCR, the multimodal vector) unless its index is already complete, so the
// screen would pay for every incomplete image and the owner would pay again. The owner decides the hash no-op (one importer call).
if (isImageFilePath(intent.sourcePath)) return false;
diff --git a/src/core/persistence/import-prepare.ts b/src/core/persistence/import-prepare.ts
index 95c9e438fb..95af40691b 100644
--- a/src/core/persistence/import-prepare.ts
+++ b/src/core/persistence/import-prepare.ts
@@ -1,11 +1,13 @@
-import { existsSync, lstatSync, readFileSync, realpathSync } from 'node:fs';
+import { closeSync, createReadStream, existsSync, lstatSync, openSync, readFileSync, readSync, realpathSync } from 'node:fs';
+import { createHash } from 'node:crypto';
+import { lstat } from 'node:fs/promises';
import { basename, isAbsolute, join, relative, resolve, sep } from 'node:path';
import type { BrainEngine } from '../engine.ts';
import type { GBrainConfig } from '../config.ts';
import type { Page } from '../types.ts';
import { ownerGateInput, ownerImportTrust } from '../trust/channel.ts';
import { importCodeFile, importFromContent, importImageFile, isImageFilePath, MAX_IMAGE_BYTES, verifyPageReadable } from '../import-file.ts';
-import { parseMarkdown, serializePageToMarkdown } from '../markdown.ts';
+import { parseMarkdown, parseMarkdownHead, serializePageToMarkdown } from '../markdown.ts';
import { applyInference } from '../frontmatter-inference.ts';
import { getCompanyBrainProfile } from '../company-brain/profile.ts';
import { hasMalformedPathSegment, isCodeFilePath, slugifyCodePath, slugifyPath } from '../sync.ts';
@@ -17,6 +19,9 @@ import { isWriteTargetContained } from '../path-confine.ts';
import { assertPageRevision } from '../page-state/types.ts';
import { sealImportedPage, sealPageTextProjection } from '../page-state/projections.ts';
import { materializedSnapshot, sealSegmentedPage } from './segmented-apply.ts';
+import { importStreamedMarkdownFile, type StreamedPreparedImport } from '../page-body/streamed-import.ts';
+import { FRONTMATTER_HEAD_MAX_BYTES, readPageBodyPolicy, type PageBodyPolicy } from '../page-body/limits.ts';
+import { PAGE_MAX_BYTES } from '../page-size-policy.ts';
import { assertKnowledgePublicationAllowed } from '../shared-skills/knowledge-guard.ts';
import { getWorktreeBinding } from './ownership.ts';
import { localHostId } from './identity.ts';
@@ -32,8 +37,11 @@ import { readFix, trustedCliRequired } from '../ops/op-fix.ts';
import type { Action } from '../agent-output.ts';
export type ImportPack = { page_types: ReadonlyArray<{ name: string; path_prefixes: ReadonlyArray<string>; aliases?: ReadonlyArray<string> }> };
+/** A Markdown file over the single-string ceiling, journaled by reference: the preparer streams and verifies it (Wave B). */
+export interface ManagedImportBodyRef { kind: 'input_file'; input_path: string; sha256: string; bytes: number }
+/** `content` (the normalized file) or `body_ref` (a file over the single-string ceiling, never held in the journal). */
export interface ManagedImportIntent extends Record<string, unknown> {
- kind: 'managed_file_import'; slug: string; content: string; sourcePath: string; path?: string;
+ kind: 'managed_file_import'; slug: string; content?: string; body_ref?: ManagedImportBodyRef; sourcePath: string; path?: string;
inputPath: string; inputHash: string; targetHash: string | null;
ownerEpoch: string; expected_revision?: string; noEmbed: boolean; activePack?: ImportPack;
}
@@ -71,7 +79,8 @@ function managedImportRefusal(refusal: ContentRefusal, sourcePath: string): Oper
return contentRefusalError(refusal, suggestion, { legacy_error: 'invalid_params' });
}
-export function managedImportContent(sourcePath: string, bytes: Buffer, activePack?: ImportPack): { slug: string; content: string } {
+/** The source-relative path refusals every managed import makes before reading the file. */
+function managedImportPathChecks(sourcePath: string): void {
if (isAbsolute(sourcePath) || sourcePath.split(/[\\/]/).some(part => part === '..') || hasMalformedPathSegment(sourcePath)) {
throw opError('invalid_params', 'The import path must be a well-formed source-relative path.',
`${JSON.stringify(sourcePath)} is absolute, climbs out with "..", or has a malformed segment, so it was not imported. Rename the file or import it from inside the source root.`);
@@ -80,6 +89,10 @@ export function managedImportContent(sourcePath: string, bytes: Buffer, activePa
throw opError('skill_bundle_required', 'Import cannot publish skill paths. Use the shared skill publisher.',
`${sourcePath} is a reserved skill path, so import skipped it. Publish skills with put_skill (CLI: gbrain put-skill) and the catalog expected_revision; skill text imported as knowledge is never published as instructions.`);
}
+}
+
+export function managedImportContent(sourcePath: string, bytes: Buffer, activePack?: ImportPack): { slug: string; content: string } {
+ managedImportPathChecks(sourcePath);
if (isImageFilePath(sourcePath)) return { slug: sourcePath.replaceAll('\\', '/').toLowerCase(), content: bytes.toString('base64') };
let content = bytes.toString('utf8').replace(/^\uFEFF/, '');
if (isCodeFilePath(sourcePath)) return { slug: slugifyCodePath(sourcePath), content };
@@ -97,6 +110,36 @@ export function managedImportContent(sourcePath: string, bytes: Buffer, activePa
return { slug, content };
}
+/**
+ * Wave B: the admission identity of a Markdown file over the single-string
+ * ceiling (decision 4), or null when the file takes the ordinary path (within
+ * the limit, not Markdown, or segmented storage off). The bytes are hashed as a
+ * stream and only the frontmatter head is parsed for the slug; the preparer
+ * re-derives both and refuses a mismatch. Such a file imports only from its own
+ * place in the canonical root (`input === target`), since its canonical file is
+ * never rewritten.
+ */
+export async function managedStreamedIdentity(sourcePath: string, input: string, target: string, policy: PageBodyPolicy):
+ Promise<{ slug: string; bodyRef: ManagedImportBodyRef } | null> {
+ if (!policy.segmented || !/\.mdx?$/i.test(sourcePath)) return null;
+ if (realpathSync(input) !== resolve(input) || !lstatSync(input).isFile()) return null;
+ const bytes = lstatSync(input).size;
+ if (bytes <= importSizeLimit(input) || bytes > policy.maxBytes) return null;
+ managedImportPathChecks(sourcePath);
+ if (target !== input) throw opError('invalid_params', `File too large (max ${PAGE_MAX_BYTES} bytes).`,
+ `${basename(input)} is over the single-string import limit, so it imports only from its place inside the source root (its canonical file is never rewritten). Move it into the source and import it there.`);
+ const hash = createHash('sha256');
+ for await (const part of createReadStream(input)) hash.update(part);
+ const head = Buffer.alloc(Math.min(FRONTMATTER_HEAD_MAX_BYTES, bytes));
+ const fd = openSync(input, 'r');
+ try { readSync(fd, head, 0, head.length, 0); } finally { closeSync(fd); }
+ const declared = parseMarkdownHead(head.toString('utf8').replace(/^\uFEFF/, '')).frontmatter.slug;
+ const slug = typeof declared === 'string' && declared ? declared : slugifyPath(sourcePath);
+ if (!slug) throw opError('invalid_params', 'The filename produces no usable slug; add a slug in frontmatter.',
+ `Rename ${sourcePath} to a name with letters or digits, or add a slug: line to its frontmatter, then import again.`);
+ return { slug, bodyRef: { kind: 'input_file', input_path: input, sha256: hash.digest('hex'), bytes } };
+}
+
export async function assertImportPaths(engine: BrainEngine, sourceId: string, root: string, input: string, target: string): Promise<void> {
if (await getCompanyBrainProfile(engine, sourceId)) throw opError('profile_incompatible', 'Company-brain sources require approved committed ingestion and never accept ordinary import writeback.',
`Source ${sourceId} ingests only committed content under its approved company-brain profile. Commit the file to that source's repository and sync it, or import it into a different source.`,
@@ -140,7 +183,9 @@ export async function prepareManagedImportMutation(engine: BrainEngine, row: Wri
screen?: { snapshot: PageSnapshot | null }): Promise<PreparedMutation> {
const p = row.intent as ManagedImportIntent | null;
if (row.authority.remote || row.principal_kind !== 'local_cli') throw trustedCliRequired('Filesystem import requires a trusted local CLI writer.');
- if (!p || p.kind !== 'managed_file_import' || typeof p.content !== 'string' || typeof p.inputPath !== 'string' || typeof p.sourcePath !== 'string') {
+ const bodyRef = p?.body_ref;
+ const refValid = !!bodyRef && bodyRef.kind === 'input_file' && bodyRef.input_path === p!.inputPath && typeof bodyRef.sha256 === 'string' && Number.isSafeInteger(bodyRef.bytes);
+ if (!p || p.kind !== 'managed_file_import' || (typeof p.content === 'string' ? bodyRef !== undefined : !refValid) || typeof p.inputPath !== 'string' || typeof p.sourcePath !== 'string') {
throw opError('invalid_params', 'The durable file import intent is incomplete.',
`Import request ${row.request_id} in source ${row.source_id} has no complete file intent, so it published nothing. Read its receipt, then import the file again with gbrain import --source ${row.source_id}.`,
{ fix: receiptFix(row) });
@@ -157,13 +202,18 @@ export async function prepareManagedImportMutation(engine: BrainEngine, row: Wri
{ fix: receiptFix(row) });
}
const path = resolve(root, physicalPath);
- const checkPaths = async (tx: BrainEngine) => {
+ const checkPlacement = async (tx: BrainEngine) => {
const current = await getWorktreeBinding(tx, row.source_id);
if (!current || current.worktree_id !== row.worktree_id || String(current.owner_epoch) !== p.ownerEpoch) throw opError('owner_unavailable', 'The import owner changed.',
`Source ${row.source_id}'s canonical owner changed while import request ${row.request_id} was prepared, so it published nothing. Check the owner, then import ${p.sourcePath} again on the host that owns the source.`,
{ fix: ownerStatusFix(row.source_id) });
await assertImportPaths(tx, row.source_id, root, p.inputPath, path);
await assertKnowledgePublicationAllowed(tx, row, { root, path });
+ };
+ if (bodyRef) return prepareStreamedManagedImport(engine, row, { ...p, body_ref: bodyRef }, path, checkPlacement, screen);
+ const content = p.content!;
+ const checkPaths = async (tx: BrainEngine) => {
+ await checkPlacement(tx);
if (sha256(readImportBytes(p.inputPath)) !== p.inputHash) throw opError('source_changed', 'The input file changed after import admission.',
`${p.sourcePath} was edited after import request ${row.request_id} was accepted, so the request published nothing. Import it again to publish the current bytes.`,
{ fix: reimportFix(p.inputPath, row.source_id) });
@@ -172,29 +222,23 @@ export async function prepareManagedImportMutation(engine: BrainEngine, row: Wri
{ fix: reimportFix(p.inputPath, row.source_id) });
};
if (!screen) await checkPaths(engine);
- const normalized = screen ? { slug: row.slug, content: p.content } : managedImportContent(p.sourcePath, readImportBytes(p.inputPath), p.activePack);
- if (normalized.slug !== row.slug || normalized.content !== p.content) throw opError('source_changed', 'The frozen file identity no longer matches the import.',
+ const normalized = screen ? { slug: row.slug, content } : managedImportContent(p.sourcePath, readImportBytes(p.inputPath), p.activePack);
+ if (normalized.slug !== row.slug || normalized.content !== content) throw opError('source_changed', 'The frozen file identity no longer matches the import.',
`${p.sourcePath} now normalizes to different content or slug than import request ${row.request_id} accepted for ${row.slug}, so it published nothing. Import it again to publish the current file.`,
{ fix: reimportFix(p.inputPath, row.source_id) });
const source = { sourceId: row.source_id };
const snapshot = await materializedSnapshot(engine, screen ? screen.snapshot : await engine.readPageSnapshot(row.slug, { ...source, includeDeleted: true }));
- assertPageRevision(snapshot, { expectedRevision: p.expected_revision ?? null }); // null: admitted against an absent page; still a revision_conflict if one appeared (#5385)
- if ((snapshot?.page.id ?? null) !== row.page_id || snapshot?.page.source_path && snapshot.page.source_path !== p.sourcePath) {
- throw opError('page_identity_changed', 'The imported path no longer names the accepted page.',
- `Page ${row.slug} in source ${row.source_id} was replaced, removed, or now maps to a different file than ${p.sourcePath}, so import request ${row.request_id} published nothing. Read the page before importing the file again.`,
- { fix: readFix(`Shows which page holds ${row.slug} in source ${row.source_id} now, with its source path and revision.`,
- { argv: ['gbrain', 'get', '--source', row.source_id, '--', row.slug] }) });
- }
+ assertImportBaseSnapshot(row, p, snapshot);
let prepared: (Omit<PreparedContentImport, 'parsedPage'> & { parsedPage?: PreparedContentImport['parsedPage'] }) | undefined;
const prepare = async (value: NonNullable<typeof prepared>) => { prepared = value; return value.result; };
const code = isCodeFilePath(p.sourcePath);
const image = isImageFilePath(p.sourcePath);
- const imageBytes = image ? Buffer.from(p.content, 'base64') : undefined;
+ const imageBytes = image ? Buffer.from(content, 'base64') : undefined;
const result = image
? await importImageFile(engine, p.inputPath, p.sourcePath, { ...source, noEmbed: p.noEmbed, bytes: imageBytes, prepare })
: code
- ? await importCodeFile(engine, p.sourcePath, p.content, { ...source, noEmbed: true, prepare })
- : await importFromContent(engine, row.slug, p.content, { ...source, noEmbed: true, remote: false, preserveGateMarkers: true, prepare, fences: 'coordinated', writeGate: await ownerGateInput(engine, row, parseMarkdown(p.content, row.slug).frontmatter, p.sourcePath),
+ ? await importCodeFile(engine, p.sourcePath, content, { ...source, noEmbed: true, prepare })
+ : await importFromContent(engine, row.slug, content, { ...source, noEmbed: true, remote: false, preserveGateMarkers: true, prepare, fences: 'coordinated', writeGate: await ownerGateInput(engine, row, parseMarkdown(content, row.slug).frontmatter, p.sourcePath),
coordinated: true, existingSnapshot: snapshot, activePack: p.activePack, sourcePath: p.sourcePath, filename: basename(p.sourcePath, '.md'), allowEmptyOverwrite: true,
segmentedOwner: { kind: 'import', principalKind: row.principal_kind, principalId: row.principal_id, baseRevision: snapshot?.revision ?? null } });
if (!prepared && result.refusal?.code === 'invalid_fence') throw managedImportRefusal(result.refusal, p.sourcePath);
@@ -209,7 +253,7 @@ export async function prepareManagedImportMutation(engine: BrainEngine, row: Wri
`Preparing ${p.sourcePath} for import request ${row.request_id} in source ${row.source_id} produced no page, so nothing was published. Read the receipt and report it to the user if importing the file again fails the same way.`,
{ fix: receiptFix(row) });
const tags = [...new Set([...(snapshot?.tags ?? []), ...(ready.parsedPage?.tags ?? [])])].sort();
- const rendered = imageBytes ?? (code ? p.content : serializePageToMarkdown({
+ const rendered = imageBytes ?? (code ? content : serializePageToMarkdown({
...(snapshot?.page ?? { id: 0, slug: row.slug, source_id: row.source_id, created_at: new Date(), updated_at: new Date() }), ...ready.parsedPage,
} as Page, tags));
const project = code || image ? undefined : await prepareCanonicalProjections(engine, ready.parsedPage!, row.slug, row.source_id, snapshot, 'file');
@@ -241,3 +285,61 @@ export async function prepareManagedImportMutation(engine: BrainEngine, row: Wri
} };
return mutation;
}
+
+/** The admitted page is still the import's base: its revision, its id and the file it maps to. */
+function assertImportBaseSnapshot(row: WriteRequest, p: ManagedImportIntent, snapshot: PageSnapshot | null): void {
+ assertPageRevision(snapshot, { expectedRevision: p.expected_revision ?? null }); // null: admitted against an absent page; still a revision_conflict if one appeared (#5385)
+ if ((snapshot?.page.id ?? null) !== row.page_id || snapshot?.page.source_path && snapshot.page.source_path !== p.sourcePath) {
+ throw opError('page_identity_changed', 'The imported path no longer names the accepted page.',
+ `Page ${row.slug} in source ${row.source_id} was replaced, removed, or now maps to a different file than ${p.sourcePath}, so import request ${row.request_id} published nothing. Read the page before importing the file again.`,
+ { fix: readFix(`Shows which page holds ${row.slug} in source ${row.source_id} now, with its source path and revision.`,
+ { argv: ['gbrain', 'get', '--source', row.source_id, '--', row.slug] }) });
+ }
+}
+
+/**
+ * Wave B: a Markdown file over the single-string ceiling, admitted by reference
+ * (`body_ref`). It is imported only from its own place in the canonical root,
+ * since the canonical file is never rewritten; the preparer streams it through
+ * the segmented import, which verifies the admitted sha256 on its first pass,
+ * and the publication is database-only. With the switch off by now, or the
+ * file over this brain's ceiling, it refuses as before admission would have.
+ */
+async function prepareStreamedManagedImport(engine: BrainEngine, row: WriteRequest, p: ManagedImportIntent & { body_ref: ManagedImportBodyRef }, path: string,
+ checkPlacement: (tx: BrainEngine) => Promise<void>, screen?: { snapshot: PageSnapshot | null }): Promise<PreparedMutation> {
+ const ref = p.body_ref;
+ const tooLarge = (why: string) => opError('invalid_params', `File too large (max ${PAGE_MAX_BYTES} bytes).`,
+ `${p.sourcePath} is ${ref.bytes} bytes, over the single-string import limit, and ${why}, so import request ${row.request_id} published nothing.`,
+ { fix: receiptFix(row) });
+ if (resolve(p.inputPath) !== path) throw tooLarge(`a file this size is imported only from its place inside source ${row.source_id}'s root (its canonical file is never rewritten); move it into the source and import it there`);
+ const policy = await readPageBodyPolicy(engine);
+ if (!policy.segmented || ref.bytes > policy.maxBytes) throw tooLarge(`segmented page storage (pages.segmented_storage) is off or the file is over pages.max_bytes`);
+ await checkPlacement(engine);
+ const stat = await lstat(path);
+ if (!stat.isFile() || stat.size !== ref.bytes) throw opError('source_changed', 'The input file changed after import admission.',
+ `${p.sourcePath} was edited after import request ${row.request_id} was accepted, so the request published nothing. Import it again to publish the current bytes.`,
+ { fix: reimportFix(p.inputPath, row.source_id) });
+ const snapshot = screen ? screen.snapshot : await engine.readPageSnapshot(row.slug, { sourceId: row.source_id, includeDeleted: true });
+ assertImportBaseSnapshot(row, p, snapshot);
+ let ready: StreamedPreparedImport | undefined;
+ const result = await importStreamedMarkdownFile(engine, path, p.sourcePath, { sourceId: row.source_id, noEmbed: true, ...(p.activePack ? { activePack: p.activePack } : {}),
+ coordinated: { snapshot, sha256: ref.sha256, prepare: async value => { ready = value; return value.result; },
+ owner: { kind: 'import', principalKind: row.principal_kind, principalId: row.principal_id, baseRevision: snapshot?.revision ?? null } } }, stat, policy);
+ if (!ready) throw opError('invalid_params', result.error ?? 'The file could not be prepared.',
+ `${p.sourcePath} was rejected while preparing import request ${row.request_id} for source ${row.source_id}; nothing was published. Fix the file content or frontmatter named in the message, then import it again.`,
+ { fix: reimportFix(p.inputPath, row.source_id) });
+ const prepared: StreamedPreparedImport = ready;
+ if (prepared.slug !== row.slug || prepared.observedRevision !== (snapshot?.revision ?? null)) throw opError('revision_conflict', 'The import identity changed during preparation.',
+ `Page ${row.slug} in source ${row.source_id} changed while import request ${row.request_id} was prepared, so it published nothing. Import ${p.sourcePath} again against the current page.`,
+ { fix: reimportFix(p.inputPath, row.source_id) });
+ const mutation: PreparedMutation = { observedRevision: prepared.observedRevision, noop: prepared.noop,
+ trust: await ownerImportTrust(engine, row, prepared.frontmatter, p.sourcePath), deferEmbedding: p.noEmbed,
+ validate: async tx => { await checkPlacement(tx); await prepared.validate(tx); },
+ ...(prepared.afterCommit ? { afterCommit: prepared.afterCommit } : {}),
+ apply: async tx => {
+ await prepared.apply(tx);
+ mutation.postimage = await tx.readPageSnapshot(row.slug, { sourceId: row.source_id, includeDeleted: true });
+ return { ...result, imported_file: true, source_id: row.source_id };
+ } };
+ return mutation;
+}
diff --git a/src/core/persistence/journal.ts b/src/core/persistence/journal.ts
index b3f5dbdbad..a55b55cebd 100644
--- a/src/core/persistence/journal.ts
+++ b/src/core/persistence/journal.ts
@@ -25,6 +25,9 @@ import { ACTIVE_REFRESH_STATES_SQL, refreshFenceClear } from './worktree-refresh
import { assertMutationProtocol, assertSharedSkillPersistence, declareDurablePersistence, declarePersistenceProtocol, PERSISTENCE_PROTOCOL_PREDICATE } from './protocol.ts';
import { assertGraduationAdmission } from './graduation-custody.ts';
import { CAPACITY_VERIFY } from './capacity-verify.ts';
+import { readManagedMode } from './managed-mode.ts';
+import { localHostId } from './identity.ts';
+import { segmentWriteScope } from '../page-body/ingest.ts';
import {
isTerminal, principalKey, requestPrincipal, recoveryFiles,
type JournalLimits, type Principal, type RecoveryRecord, type RequestState,
@@ -946,12 +949,21 @@ export async function vacuumPersistenceQueues(engine: BrainEngine): Promise<numb
* vacuum: expires body stagings past their deadlines (their staged manifest
* and chunk rows go with them), deletes retired chunk rows and manifest rows
* no retained generation needs, and unreferenced segment texts past the grace
- * window. A brain that never staged a segment pays one existence probe.
+ * window. On a managed brain it collects only the sources this host owns, each
+ * in a coordinated write. A brain that never staged a segment pays one
+ * existence probe.
*/
export async function sweepSegmentStorage(engine: BrainEngine): Promise<void> {
const [row] = await engine.executeRaw<{ present: boolean }>(
'SELECT EXISTS (SELECT 1 FROM page_body_stagings) OR EXISTS (SELECT 1 FROM page_segment_texts) AS present');
- if (row?.present) await engine.sweepSegments({ expireStagings: true });
+ if (!row?.present) return;
+ if (!await readManagedMode(engine)) { await engine.sweepSegments({ expireStagings: true }); return; }
+ const owned = await engine.executeRaw<{ source_id: string }>(`SELECT s.source_id FROM persistence_source_bindings s
+ JOIN persistence_worktrees w ON w.id=s.worktree_id WHERE w.owner_host_id=$1::uuid AND w.state='active'`, [localHostId()]);
+ for (const { source_id: sourceId } of owned) {
+ const writes = await segmentWriteScope(engine, sourceId);
+ await writes(exec => exec.sweepSegments({ sourceId, expireStagings: true }));
+ }
}
/**
diff --git a/src/core/persistence/segmented-apply.ts b/src/core/persistence/segmented-apply.ts
index 6612400bd8..e439d85e60 100644
--- a/src/core/persistence/segmented-apply.ts
+++ b/src/core/persistence/segmented-apply.ts
@@ -22,7 +22,7 @@ import type { Page } from '../types.ts';
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, stringBodyFlags, stringRegion } from '../page-body/ingest.ts';
+import { materializeSegmentedBody, prepareSegmentedBody, segmentWriteScope, stringBodyFlags, stringRegion } from '../page-body/ingest.ts';
import { buildSegmentedProjection } 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';
@@ -196,7 +196,8 @@ export async function stageSegmentedImport(engine: BrainEngine, input: { slug: s
afterCommit: async target => {
if (!staged.applied) return;
if (!staged.applied.complete) await buildSegmentedProjection(target, { sourceId: input.sourceId, slug: input.slug }).catch(() => undefined);
- await target.sweepSegments({ pageId: staged.applied.pageId }).catch(() => undefined);
+ const pageId = staged.applied.pageId;
+ await segmentWriteScope(target, input.sourceId).then(writes => writes(exec => exec.sweepSegments({ pageId }))).catch(() => undefined);
} };
return staged;
}
diff --git a/test/large-pages/managed-streamed-import.test.ts b/test/large-pages/managed-streamed-import.test.ts
new file mode 100644
index 0000000000..788c7af8fd
--- /dev/null
+++ b/test/large-pages/managed-streamed-import.test.ts
@@ -0,0 +1,204 @@
+/**
+ * Wave B managed import of a Markdown file over the single-string ceiling
+ * (decision 4, lane 1d).
+ *
+ * 1. Protects: on a managed brain with `pages.segmented_storage` on, a file
+ * over PAGE_MAX_BYTES inside the canonical root imports through its owner
+ * with an intent that holds a `body_ref` (sha256, bytes) and no content; the
+ * page round-trips byte-identical from its manifest, `content_hash` equals
+ * `contentHash`, and the canonical file is left untouched. A file within
+ * the ceiling stages its segments in the owner's preparation (the writer
+ * guard admits it) and publishes segmented. Segment GC on a managed brain
+ * collects an abandoned preparation's staged rows under the guard. A file that
+ * changes between admission and preparation publishes nothing; a request_id
+ * replayed with other bytes is `idempotency_conflict`; with the switch off
+ * the refusal is the one before Wave B.
+ * 2. Fails when: the journal carries the body, the preparer skips the hash
+ * check, the publication rewrites the canonical file, or the switch-off
+ * refusal changes.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, 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 type { OperationContext } from '../../src/core/ops/contract.ts';
+import { parseMarkdown } from '../../src/core/markdown.ts';
+import { PAGE_MAX_BYTES } from '../../src/core/page-size-policy.ts';
+import { importManagedFile } from '../../src/core/persistence/import-mutations.ts';
+import { prepareManagedImportMutation, type ManagedImportIntent } from '../../src/core/persistence/import-prepare.ts';
+import { claimWorktree, getWorktreeBinding } from '../../src/core/persistence/ownership.ts';
+import { localHostId, registerLocalWriter } from '../../src/core/persistence/identity.ts';
+import { admitWrite, claimNextWrite, sweepSegmentStorage } from '../../src/core/persistence/journal.ts';
+import { preparePageAdmission } from '../../src/core/persistence/page-mutations.ts';
+import { submissionAuthority } from '../../src/core/persistence/authority.ts';
+import { disposePersistenceConsumer } from '../../src/core/persistence/service.ts';
+import { sha256 } from '../../src/core/persistence/digest.ts';
+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';
+import { withEnv } from '../helpers/with-env.ts';
+import { conversationPage } from '../helpers/conversation-page.ts';
+import { reconstructedPage } from '../helpers/segmented-page-checks.ts';
+
+const home = mkdtempSync(join(tmpdir(), 'gbrain-managed-streamed-'));
+const engines: BrainEngine[] = [];
+let closePostgres: (() => Promise<void>) | undefined;
+const env = { GBRAIN_HOME: home, OPENAI_API_KEY: undefined, VOYAGE_API_KEY: undefined, ANTHROPIC_API_KEY: undefined };
+const content = conversationPage(PAGE_MAX_BYTES + 2 * 1024 * 1024, { seed: 51 });
+
+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; }
+}, 120_000);
+
+afterAll(async () => {
+ await withEnv(env, async () => {
+ for (const engine of engines) { await disposePersistenceConsumer(engine); await engine.disconnect(); }
+ await closePostgres?.();
+ });
+ rmSync(home, { recursive: true, force: true });
+});
+
+async function fixture(engine: BrainEngine) {
+ const sourceId = `streamed-${randomUUID().slice(0, 8)}`;
+ const root = join(home, sourceId);
+ mkdirSync(join(root, 'notes'), { recursive: true });
+ 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]);
+ await registerLocalWriter(engine, 'cli');
+ await claimWorktree(engine, sourceId, root);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ return { sourceId, root };
+}
+
+/** A body_ref intent for `file`, admitted and claimed (the owner's next request). */
+async function admitted(engine: BrainEngine, sourceId: string, file: string, sourcePath: string, bytes: Buffer, base?: { pageId: number; revision: string }) {
+ const binding = (await getWorktreeBinding(engine, sourceId))!;
+ const slug = sourcePath.replace(/\.md$/, '');
+ const ctx = { engine, remote: false, sourceId } as OperationContext;
+ const authority = await submissionAuthority(ctx, 'put_page', sourceId, binding.source_incarnation, slug);
+ const hash = sha256(bytes);
+ const intent: ManagedImportIntent = { kind: 'managed_file_import', slug, sourcePath, path: sourcePath, inputPath: file, inputHash: hash, targetHash: hash,
+ body_ref: { kind: 'input_file', input_path: file, sha256: hash, bytes: bytes.length }, ownerEpoch: String(binding.owner_epoch), noEmbed: true,
+ ...(base ? { expected_revision: base.revision } : {}) };
+ await admitWrite(engine, { principal: authority.principal, operation: 'put_page', sourceId, sourceIncarnation: binding.source_incarnation,
+ slug, pageId: base?.pageId ?? null, requestId: randomUUID(), callerIntent: intent, intent, authority, worktreeId: binding.worktree_id, topologyGeneration: binding.topology_generation });
+ return (await claimNextWrite(engine, localHostId()))!;
+}
+
+describe('managed import over the single-string ceiling', () => {
+ test('switch on: imports by reference, round-trips byte-identical, leaves the canonical file and keeps the intent small', async () => withEnv(env, async () => {
+ for (const engine of engines) {
+ await disposePersistenceConsumer(engine);
+ await engine.setConfig('pages.segmented_storage', 'on');
+ const f = await fixture(engine);
+ const file = join(f.root, 'notes/huge.md');
+ writeFileSync(file, content);
+ const before = statSync(file);
+ const result = await importManagedFile(engine, file, 'notes/huge.md', { sourceId: f.sourceId, noEmbed: true });
+ expect(result).toMatchObject({ slug: 'notes/huge', status: 'imported' });
+ const parsed = parseMarkdown(content, 'notes/huge.md');
+ const { page, body, hash } = await reconstructedPage(engine, 'notes/huge', f.sourceId);
+ expect(page.body_storage).toBe('segmented');
+ expect(body.compiled_truth).toBe(parsed.compiled_truth);
+ expect(body.timeline).toBe(parsed.timeline);
+ expect(page.content_hash).toBe(hash);
+ expect(page.text_projection_revision).toBe(page.knowledge_revision);
+ const after = statSync(file);
+ expect(after.mtimeMs).toBe(before.mtimeMs);
+ expect(sha256(readFileSync(file))).toBe(sha256(Buffer.from(content)));
+ const [request] = await engine.executeRaw<{ intent_bytes: string; intent: Record<string, unknown>; state: string }>(
+ `SELECT intent_bytes::text AS intent_bytes, intent, state FROM persistence_requests WHERE source_id=$1 AND slug=$2`, [f.sourceId, 'notes/huge']);
+ expect(request!.state).toBe('committed');
+ expect(Number(request!.intent_bytes)).toBeLessThan(16 * 1024);
+ expect(request!.intent.content).toBeUndefined();
+ expect(request!.intent.body_ref).toMatchObject({ kind: 'input_file', sha256: sha256(Buffer.from(content)), bytes: Buffer.byteLength(content) });
+
+ const again = await importManagedFile(engine, file, 'notes/huge.md', { sourceId: f.sourceId, noEmbed: true });
+ expect(again.status).toBe('skipped');
+ expect((await reconstructedPage(engine, 'notes/huge', f.sourceId)).page.body_generation).toBe(page.body_generation);
+
+ // An owner preparation that never publishes leaves staged rows; segment GC collects them under the writer guard.
+ await disposePersistenceConsumer(engine);
+ const appended = Buffer.from(`${content}\nA closing note.\n`);
+ writeFileSync(file, appended);
+ const snapshot = (await engine.readPageSnapshot('notes/huge', { sourceId: f.sourceId }))!;
+ await prepareManagedImportMutation(engine, await admitted(engine, f.sourceId, file, 'notes/huge.md', appended,
+ { pageId: Number(snapshot.page.id), revision: snapshot.revision }), { engine: engine.kind });
+ const staged = async () => Number((await engine.executeRaw<{ n: string }>(
+ 'SELECT count(*)::text AS n FROM page_body_manifest WHERE page_id=$1 AND staging_id IS NOT NULL', [page.id]))[0]!.n);
+ expect(await staged()).toBeGreaterThan(0);
+ await engine.executeRaw(`UPDATE page_body_stagings SET state='aborted' WHERE page_id=$1 AND state='open'`, [page.id]);
+ await sweepSegmentStorage(engine);
+ expect(await staged()).toBe(0);
+ }
+ }), 600_000);
+
+ test('a file within the ceiling stages segments in the owner\'s preparation and publishes segmented', async () => withEnv(env, async () => {
+ for (const engine of engines) {
+ await disposePersistenceConsumer(engine);
+ await engine.setConfig('pages.segmented_storage', 'on');
+ const f = await fixture(engine);
+ const file = join(f.root, 'notes/mid.md');
+ const mid = conversationPage(3 * 1024 * 1024, { seed: 52 });
+ writeFileSync(file, mid);
+ expect(await importManagedFile(engine, file, 'notes/mid.md', { sourceId: f.sourceId, noEmbed: true })).toMatchObject({ slug: 'notes/mid', status: 'imported' });
+ const parsed = parseMarkdown(mid, 'notes/mid.md');
+ const { page, body, hash } = await reconstructedPage(engine, 'notes/mid', f.sourceId);
+ expect(page.body_storage).toBe('segmented');
+ expect(body.compiled_truth).toBe(parsed.compiled_truth);
+ expect(page.content_hash).toBe(hash);
+ }
+ }), 600_000);
+
+ test('a file changed between admission and preparation is refused', async () => withEnv(env, async () => {
+ for (const engine of engines) {
+ await disposePersistenceConsumer(engine);
+ await engine.setConfig('pages.segmented_storage', 'on');
+ const f = await fixture(engine);
+ const file = join(f.root, 'notes/edited.md');
+ const bytes = Buffer.from(content);
+ writeFileSync(file, bytes);
+ const row = await admitted(engine, f.sourceId, file, 'notes/edited.md', bytes);
+ const edited = Buffer.from(bytes);
+ edited.write('Edited', bytes.length - 64, 'utf8');
+ writeFileSync(file, edited);
+ await expect(prepareManagedImportMutation(engine, row, { engine: engine.kind })).rejects.toMatchObject({ code: 'source_changed' });
+ expect(await engine.getPage('notes/edited', { sourceId: f.sourceId })).toBeNull();
+ }
+ }), 600_000);
+
+ test('a request_id replayed with other bytes is idempotency_conflict', async () => withEnv(env, async () => {
+ for (const engine of engines) {
+ await disposePersistenceConsumer(engine);
+ await engine.setConfig('pages.segmented_storage', 'on');
+ const f = await fixture(engine);
+ const binding = (await getWorktreeBinding(engine, f.sourceId))!;
+ const file = join(f.root, 'notes/replay.md');
+ const ctx = { engine, remote: false, sourceId: f.sourceId } as OperationContext;
+ const requestId = randomUUID();
+ const params = (hash: string) => ({ kind: 'managed_file_import', slug: 'notes/replay', sourcePath: 'notes/replay.md', path: 'notes/replay.md', inputPath: file,
+ inputHash: hash, targetHash: hash, body_ref: { kind: 'input_file', input_path: file, sha256: hash, bytes: 1 }, ownerEpoch: String(binding.owner_epoch),
+ noEmbed: true, source_id: f.sourceId, request_id: requestId });
+ const first = await preparePageAdmission(ctx, { operation: 'put_page', params: params('a'.repeat(64)), managedFileImport: true });
+ await admitWrite(engine, first.admission!);
+ await expect(preparePageAdmission(ctx, { operation: 'put_page', params: params('b'.repeat(64)), managedFileImport: true }))
+ .rejects.toMatchObject({ code: 'idempotency_conflict' });
+ expect((await preparePageAdmission(ctx, { operation: 'put_page', params: params('a'.repeat(64)), managedFileImport: true })).prior?.request_id).toBe(requestId);
+ }
+ }), 120_000);
+
+ test('switch off: the refusal is the one before segmented storage', async () => withEnv(env, async () => {
+ for (const engine of engines) {
+ await disposePersistenceConsumer(engine);
+ await engine.setConfig('pages.segmented_storage', 'off');
+ const f = await fixture(engine);
+ const file = join(f.root, 'notes/off.md');
+ writeFileSync(file, content);
+ await expect(importManagedFile(engine, file, 'notes/off.md', { sourceId: f.sourceId, noEmbed: true }))
+ .rejects.toMatchObject({ code: 'invalid_params', message: `File too large (max ${PAGE_MAX_BYTES} bytes).` });
+ expect(await engine.getPage('notes/off', { sourceId: f.sourceId })).toBeNull();
+ }
+ }), 120_000);
+});