Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

perf(import): admit managed import files in batches and publish them as independent groups

time-attack6d076a023cec
diff --git a/src/commands/import.ts b/src/commands/import.ts
index d35c7bbbe0..9b6a2acecb 100644
--- a/src/commands/import.ts
+++ b/src/commands/import.ts
@@ -38,7 +38,7 @@ import { realpathOrResolve } from '../core/path-confine.ts';
import { slog } from '../core/console-prefix.ts';
import { refreshProjectionStatistics } from '../core/search/projection-statistics.ts';
import { importAnalyzeEveryPages, maybeRefreshPlannerStats, PLANNER_STATS_REPAIR_COMMAND } from '../core/planner-stats.ts';
-import { importManagedFile } from '../core/persistence/import-mutations.ts';
+import { importManagedFile, importManagedFiles, nextImportBatch } from '../core/persistence/import-mutations.ts';
import { acceptedPendingReceipt } from '../core/persistence/accepted-pending.ts';
import { estimateCostFromChars, lookupEmbeddingPrice } from '../core/embedding-pricing.ts';
import { getEmbeddingModel } from '../core/ai/gateway.ts';
@@ -701,8 +701,8 @@ export async function runImport(
// never plans against the empty tables it started with (O-CEO-17).
const analyzeEvery = await importAnalyzeEveryPages(engine);
- async function processFile(eng: BrainEngine, filePath: string) {
- if (signal?.aborted) return;
+ async function processFile(eng: BrainEngine, filePath: string, settled?: PromiseSettledResult<ImportResult>) {
+ if (!settled && signal?.aborted) return;
const relativePath = singleFile ? basename(filePath) : relative(dir, filePath);
// #753/#774: slug + source_path base. When performFullSync syncs a
// monorepo subdir, slugRoot is the git root so slugs stay git-root-
@@ -719,7 +719,8 @@ export async function runImport(
// multimodal is enabled. The walker (collectMarkdownFiles) only picks
// up images when GBRAIN_EMBEDDING_MULTIMODAL=true so this branch is
// unreachable when the gate is off; defense-in-depth check anyway.
- const result = company ? await importCompanyBrainFile(eng, filePath, sourceId!) : managedImport
+ if (settled?.status === 'rejected') throw settled.reason;
+ const result = settled ? settled.value : company ? await importCompanyBrainFile(eng, filePath, sourceId!) : managedImport
? await importManagedFile(eng, filePath, importRelPath, { noEmbed, sourceId, activePack: importActivePack, signal, slugRoot: opts.slugRoot })
: isImageFilePath(relativePath) && process.env.GBRAIN_EMBEDDING_MULTIMODAL === 'true'
? await importImageFile(eng, filePath, importRelPath, { noEmbed, sourceId })
@@ -728,7 +729,7 @@ export async function runImport(
// Account for it before stopping, so resume never loses a successful path.
noteTypeWarning((result as { type_warning?: Parameters<typeof noteTypeWarning>[0] }).type_warning); fenceTally.note(importRelPath, result);
const _fileMs = Date.now() - _fileT0;
- if (_fileMs > 5000) {
+ if (!settled && _fileMs > 5000) {
console.error(`[gbrain phase] import.process_file slow ${_fileMs}ms ${relativePath}`);
}
if (await opts.onFileResult?.(importRelPath, filePath, result) === 'held') {
@@ -830,6 +831,22 @@ export async function runImport(
}
}
+ // A managed import admits and publishes its files in batches (import-mutations.ts importManagedFiles);
+ // each file is still accounted, in order, exactly as processFile accounts one file.
+ const batched = managedImport && !company;
+ const take = (start: number) => batched ? nextImportBatch(files, start) : [files[start]!];
+ async function processBatch(eng: BrainEngine, batch: string[]) {
+ if (batch.length === 1) return processFile(eng, batch[0]!);
+ if (signal?.aborted) return;
+ const open = batch.filter(file => !opts.heldPaths?.has(opts.slugRoot ? relative(opts.slugRoot, file) : relative(importRoot, file)));
+ const t0 = Date.now();
+ const settled: PromiseSettledResult<ImportResult>[] = !open.length ? [] : await importManagedFiles(eng, open.map(filePath => ({
+ filePath, sourcePath: opts.slugRoot ? relative(opts.slugRoot, filePath) : relative(importRoot, filePath) })),
+ { noEmbed, sourceId, activePack: importActivePack, signal, slugRoot: opts.slugRoot }).catch(reason => open.map(() => ({ status: 'rejected' as const, reason })));
+ if (Date.now() - t0 > 5000 * open.length) console.error(`[gbrain phase] import.process_batch slow ${Date.now() - t0}ms files=${open.length} first=${relative(dir, open[0]!)}`);
+ for (const file of batch) await processFile(eng, file, settled[open.indexOf(file)]);
+ }
+
let workerError: unknown;
let workerFailed = false;
try {
@@ -839,10 +856,7 @@ export async function runImport(
// checks belt-and-suspenders so we never crash on a null assertion.
const config = loadConfig();
if (engine.kind === 'pglite' || !config?.database_url) {
- for (const file of files) {
- if (signal?.aborted) break;
- await processFile(engine, file);
- }
+ for (let i = 0, batch: string[]; i < files.length && !signal?.aborted; i += batch.length) await processBatch(engine, batch = take(i));
} else {
const { PostgresEngine } = await import('../core/postgres-engine.ts');
const { connectWithRetry, resolvePoolSize } = await import('../core/db.ts');
@@ -872,9 +886,10 @@ export async function runImport(
const outcomes = await Promise.allSettled(workerEngines.map(async (eng) => {
try {
while (!stopWorkers && !signal?.aborted) {
- const idx = queueIndex++;
- if (idx >= files.length) break;
- await processFile(eng, files[idx]);
+ if (queueIndex >= files.length) break;
+ const batch = take(queueIndex);
+ queueIndex += batch.length;
+ await processBatch(eng, batch);
}
} catch (error) {
stopWorkers = true;
@@ -900,10 +915,7 @@ export async function runImport(
} // end else (postgres parallel)
} else {
// Sequential: use the provided engine
- for (const filePath of files) {
- if (signal?.aborted) break;
- await processFile(engine, filePath);
- }
+ for (let i = 0, batch: string[]; i < files.length && !signal?.aborted; i += batch.length) await processBatch(engine, batch = take(i));
}
} catch (error) {
workerFailed = true;
diff --git a/src/core/persistence/consumer.ts b/src/core/persistence/consumer.ts
index 081a745d55..df2ea5be96 100644
--- a/src/core/persistence/consumer.ts
+++ b/src/core/persistence/consumer.ts
@@ -1,6 +1,6 @@
import type { BrainEngine, ReservedConnection } from '../engine.ts';
import type { GBrainConfig } from '../config.ts';
-import { claimableWriteSql, foregroundPrioritySql, claimGroupFollowers, claimNextLaneHead, claimNextWrite, publicationGroupKey, compactWriteReceipts, floorPreparationAttempts, hasClaimableWrite, getWriteRequestById, releaseUnpublishedClaim, renewWriteClaim, vacuumPersistenceQueues } from './journal.ts';
+import { claimableWriteSql, foregroundPrioritySql, claimGroupFollowers, claimNextLaneHead, claimNextWrite, independentGroup, publicationGroupKey, compactWriteReceipts, floorPreparationAttempts, hasClaimableWrite, getWriteRequestById, releaseUnpublishedClaim, renewWriteClaim, vacuumPersistenceQueues } from './journal.ts';
import { finishPreparationStalled, finishUnpublishedFailure, preparationAbortReason, recoverPublication, type PreparedMutation } from './coordinator.ts';
import { localHostId } from './identity.ts';
import { executeClaimedGroup, PAGE_BATCH_GROUP_MAX, publishSingleWrite, singleWrite } from './group-publish.ts';
@@ -878,9 +878,10 @@ export class PersistenceConsumer implements PersistenceConsumerLike {
if (order === 'wait') { await releaseUnpublishedClaim(this.statements, row, 'group_member_waiting'); return false; }
if (order) { for (const done of order) this.settled(done); return true; }
const group = publicationGroupKey(row);
- if (!group || this.engine.kind !== 'postgres') return this.execute(row, root);
- // #6007: a put_pages batch publishes in groups of at most PAGE_BATCH_GROUP_MAX pages.
- const followers = await claimGroupFollowers(this.engine, row, group, group.startsWith('batch:') ? PAGE_BATCH_GROUP_MAX - 1 : 63);
+ // A managed import batch also groups on PGLite: its members share one transaction's guards there too.
+ if (!group || this.engine.kind !== 'postgres' && !group.startsWith('import:')) return this.execute(row, root);
+ // #6007: a put_pages or import batch publishes in groups of at most PAGE_BATCH_GROUP_MAX pages.
+ const followers = await claimGroupFollowers(this.engine, row, group, independentGroup(group) ? PAGE_BATCH_GROUP_MAX - 1 : 63);
if (!followers.length && !lane) return this.execute(row, root);
const rows = [row, ...followers];
for (const member of rows) this.executing.add(member.id);
diff --git a/src/core/persistence/group-publish.ts b/src/core/persistence/group-publish.ts
index 48d15ba6b5..373b49e3d5 100644
--- a/src/core/persistence/group-publish.ts
+++ b/src/core/persistence/group-publish.ts
@@ -39,7 +39,7 @@ import { acquireWorktree, acquireWorktreeShared, getWorktreeBinding, guardOwners
import { awaitLaneBegin, awaitLaneTurn, LaneAbort, laneApplyBegin, laneClaimed, laneFinished, lanePolicy, stepDownLanes, type LaneState } from './sync-lanes.ts';
import { cancelRows, windowPredecessor } from './sync-window.ts';
import { clearResolvedRecoveries, completeWrite, ENSURE_COUNTERS_SQL, getWriteRequestById, LOCK_COUNTERS_SQL, markDispatched, markRecovering, prepareRecoveries,
- foregroundPriority, publicationGroupKey, reclaimReleasedWrite, releaseUnpublishedClaim, renewGroupClaims } from './journal.ts';
+ foregroundPriority, independentGroup, publicationGroupKey, reclaimReleasedWrite, releaseUnpublishedClaim, renewGroupClaims } from './journal.ts';
import { principalKey, requestPrincipal, type FileRecoveryRecord, type WriteRequest } from './model.ts';
import { CLAIM_LOST, DEFAULT_CLAIM_LEASE_TIMING, endLostLease, startClaimLease, type ClaimLeaseTiming } from './claim-lease.ts';
import { claimPhaseStamp, enterClaimPhase, startClaimPhase, type ClaimPhaseClock } from './claim-phase.ts';
@@ -67,7 +67,7 @@ import { faultPoint, type PublicationBoundary } from './fault-points.ts';
import { assertMutationProtocol } from './protocol.ts';
import { writeSwitchOn } from './switches.ts';
-/** A `put_pages` group publishes at most this many pages per transaction, so one commit stays a few seconds long. */
+/** A `put_pages` or managed import group publishes at most this many pages per transaction, so one commit stays a few seconds long. */
export const PAGE_BATCH_GROUP_MAX = 8;
function syncMember(row: WriteRequest): boolean {
@@ -84,7 +84,7 @@ export function singleWrite(row: Pick<WriteRequest, 'operation' | 'intent'>): bo
export function groupable(row: WriteRequest, prepared: PreparedMutation): boolean {
if ((row.target_kind ?? 'page') !== 'page' || prepared.target === 'skill_bundle' || prepared.sourceExclusive || prepared.exclusiveSources?.length) return false;
if (syncMember(row)) return !prepared.file && typeof prepared.validate === 'function';
- return publicationGroupKey(row)?.startsWith('batch:') === true || singleWrite(row);
+ return independentGroup(publicationGroupKey(row)) || singleWrite(row);
}
const flat = (sql: string) => sql.replace(/\s+/g, ' ').trim();
@@ -542,15 +542,15 @@ export async function executeClaimedGroup(engine: BrainEngine, rows: WriteReques
return (await renewGroupClaims(engine, live.map(([row]) => row), 30_000, signal, live.map(([, i]) => stampOf(i)))).size === live.length;
}, run.lease ?? DEFAULT_CLAIM_LEASE_TIMING, () => { for (const prep of inFlight.values()) prep.abort({ code: 'claim_lost' }); });
if (run.lane) laneClaimed(run.lane, rows);
- // A put_pages batch is independent page writes: one page's failure never cancels its siblings.
- const independent = publicationGroupKey(rows[0]!)?.startsWith('batch:') === true;
+ // A put_pages batch or a managed import batch is independent page writes: one page's failure never cancels its siblings.
+ const independent = independentGroup(publicationGroupKey(rows[0]!));
const prepared: MemberOutcome[] = new Array(rows.length);
// The first member whose deadline passed in an ordered group: nothing after it is dispatched or published this pass.
let cut: number | null = null;
const abandon = (i: number, work: Promise<unknown>) => run.leftRunning?.(work, true, { row: rows[i]!, clock: clocks[i]! });
try {
const reads = preparationReads(engine);
- // A put_pages group prepares all of its (at most PAGE_BATCH_GROUP_MAX) pages at once.
+ // A put_pages or import group prepares all of its (at most PAGE_BATCH_GROUP_MAX) pages at once.
const width = independent ? PAGE_BATCH_GROUP_MAX : 4;
const preparing = (async () => {
for (let start = 0; start < rows.length && (independent || cut === null); start += width) {
diff --git a/src/core/persistence/import-mutations.ts b/src/core/persistence/import-mutations.ts
index 7e551cb006..bc991ab77e 100644
--- a/src/core/persistence/import-mutations.ts
+++ b/src/core/persistence/import-mutations.ts
@@ -1,5 +1,5 @@
import { randomUUID } from 'node:crypto';
-import { existsSync } from 'node:fs';
+import { existsSync, lstatSync } from 'node:fs';
import { isAbsolute, join, relative, resolve, sep } from 'node:path';
import type { BrainEngine } from '../engine.ts';
import { isImageFilePath, type ImportResult } from '../import-file.ts';
@@ -8,7 +8,11 @@ import { opError, OperationError, type OperationContext } from '../ops/contract.
import { currentSubmissionAuthority } from '../minions/submission-authority.ts';
import { currentVerifiedLocalWriter, localHostId } from './identity.ts';
import { getWorktreeBinding } from './ownership.ts';
-import { initializeLocalPersistence, requestPrincipalForContext, submitPageMutation } from './page-mutations.ts';
+import { batchSharedReads, emitFenceNotice, initializeLocalPersistence, pendingAwareResponse, preparePageAdmission, requestPrincipalForContext, withBatchAdmission } from './page-mutations.ts';
+import { admitBatch } from './page-batch.ts';
+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 { submissionAuthority } from './authority.ts';
@@ -17,70 +21,204 @@ import type { WorktreeBinding } from './ownership.ts';
import type { PageSnapshot } from '../page-state/types.ts';
import { readFix, trustedCliRequired } from '../ops/op-fix.ts';
+/** One file of a managed import batch: its path and the source-relative path its slug is derived from. */
+export interface ManagedImportFile { filePath: string; sourcePath: string }
+/** A managed import admits at most this many files in one transaction; their publication groups hold PAGE_BATCH_GROUP_MAX pages each. */
+export const IMPORT_BATCH_MAX_PAGES = 32;
+export const IMPORT_BATCH_MAX_BYTES = 8 * 1024 * 1024;
+/** The files of `queue` from `start` that one batch takes: at least one, at most the page and byte caps. */
+export function nextImportBatch(queue: readonly string[], start: number): string[] {
+ const batch: string[] = [];
+ let bytes = 0;
+ for (let i = start; i < queue.length && batch.length < IMPORT_BATCH_MAX_PAGES; i++) {
+ const size = lstatSync(queue[i]!, { throwIfNoEntry: false })?.size ?? 0;
+ if (batch.length && bytes + size > IMPORT_BATCH_MAX_BYTES) break;
+ batch.push(queue[i]!);
+ bytes += size;
+ }
+ return batch;
+}
+const IMPORT_OP = 'managed-file-import';
+/** How long an import waits for one file's publication, as a single import always has. */
+const IMPORT_WAIT_MS = 30_000;
+type PendingImport = ManagedImportIntent & { request_id: string; source_id: string };
+
export async function importManagedFile(engine: BrainEngine, filePath: string, sourcePath: string,
opts: { sourceId?: string; noEmbed?: boolean; activePack?: ImportPack; signal?: AbortSignal; slugRoot?: string } = {}): Promise<ImportResult> {
+ const [settled] = await importManagedFiles(engine, [{ filePath, sourcePath }], opts);
+ if (settled!.status === 'rejected') throw settled!.reason;
+ return settled!.value;
+}
+
+/**
+ * Imports files through the source's canonical owner. Every file keeps its own
+ * durable intent (op_checkpoints), request, receipt and result; a batch admits
+ * its new requests in one transaction, marked with one `import_batch` id so the
+ * owner publishes them in groups (journal.ts publicationGroupKey). A file's
+ * refusal settles that file only. A slug a batch already holds ends the batch
+ * there; that file and the rest import after it, as they would one by one.
+ */
+export async function importManagedFiles(engine: BrainEngine, files: readonly ManagedImportFile[],
+ opts: { sourceId?: string; noEmbed?: boolean; activePack?: ImportPack; signal?: AbortSignal; slugRoot?: string } = {}): Promise<PromiseSettledResult<ImportResult>[]> {
const caller = currentSubmissionAuthority();
if (caller && caller.kind !== 'application' || currentVerifiedLocalWriter()?.remote) {
throw trustedCliRequired('Managed filesystem import requires the trusted local CLI.');
}
opts.signal?.throwIfAborted();
- if (isImageFilePath(sourcePath) && process.env.GBRAIN_EMBEDDING_MULTIMODAL !== 'true') {
- throw opError('invalid_params', 'Image import requires GBRAIN_EMBEDDING_MULTIMODAL=true.',
- `${sourcePath} is an image and multimodal embeddings are off, so it was not imported. Import only text files, or ask the user whether to enable GBRAIN_EMBEDDING_MULTIMODAL=true for the gbrain process (image embeddings can cost money).`);
- }
+ const settled: PromiseSettledResult<ImportResult>[] = new Array(files.length);
+ const fail = (i: number, reason: unknown) => { settled[i] = { status: 'rejected', reason }; };
const sourceId = opts.sourceId ?? 'default';
const binding = await getWorktreeBinding(engine, sourceId);
- if (!binding?.local_path || binding.owner_host_id !== localHostId() || binding.state !== 'active') {
- throw opError('owner_unavailable', 'Managed import must run on the active canonical owner for the selected source.',
+ const unowned = !binding?.local_path || binding.owner_host_id !== localHostId() || binding.state !== 'active'
+ ? opError('owner_unavailable', 'Managed import must run on the active canonical owner for the selected source.',
`This host is not the active owner of source ${sourceId}, so nothing was imported. Run the import on the owner host that writer status names, or wait until its owner is active.`,
- { fix: readFix(`Shows source ${sourceId}'s owner host and state, read-only.`, { argv: ['gbrain', 'sources', 'writer', 'status', '--source', sourceId, '--json'] }) });
- }
- const root = join(binding.local_path, binding.relative_path);
- const inputPath = resolve(filePath);
- const canonicalRelative = relative(root, inputPath);
- const canonicalInput = canonicalRelative && !isAbsolute(canonicalRelative) && canonicalRelative !== '..' && !canonicalRelative.startsWith(`..${sep}`);
- if (canonicalInput && !opts.slugRoot) sourcePath = canonicalRelative;
- const path = canonicalInput ? canonicalRelative : sourcePath;
- const target = resolve(root, path);
- await assertImportPaths(engine, sourceId, root, inputPath, target);
- const bytes = readImportBytes(inputPath);
- const inputHash = sha256(bytes);
- const { slug, content } = managedImportContent(sourcePath, bytes, opts.activePack);
+ { 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;
- await initializeLocalPersistence(ctx);
- const principal = await requestPrincipalForContext(ctx);
- const key = digest({ principal, incarnation: binding.source_incarnation, inputPath, sourcePath, path, inputHash, noEmbed: !!opts.noEmbed, activePack: opts.activePack ?? null });
- const op = 'managed-file-import';
- const readPending = async () => {
- const [row] = await engine.executeRaw<{ completed_keys: [ManagedImportIntent & { request_id: string; source_id: string }] }>(
- 'SELECT completed_keys FROM op_checkpoints WHERE op=$1 AND fingerprint=$2', [op, key]);
- return row?.completed_keys[0];
- };
- let params = await readPending();
- if (!params) {
- const snapshot = await engine.readPageSnapshot(slug, { sourceId, includeDeleted: true });
- const intent: ManagedImportIntent = { kind: 'managed_file_import', slug, content, sourcePath, path, inputPath, inputHash,
- targetHash: existsSync(target) ? sha256(readImportBytes(target)) : null,
- ownerEpoch: String(binding.owner_epoch), ...(snapshot ? { expected_revision: snapshot.revision } : {}),
- noEmbed: !!opts.noEmbed, ...(opts.activePack ? { activePack: opts.activePack } : {}) };
- // #5470: an import whose publication would change nothing takes no admission.
- if (await unchangedManagedImport(ctx, binding, intent, snapshot)) return { slug, status: 'skipped', chunks: 0 };
- params = { ...intent, request_id: randomUUID(), source_id: sourceId };
- await engine.executeRaw('INSERT INTO op_checkpoints(op,fingerprint,completed_keys) VALUES($1,$2,$3::text::jsonb) ON CONFLICT DO NOTHING', [op, key, JSON.stringify([params])]);
- params = (await readPending())!;
+ const reads = batchSharedReads(engine);
+ const planned: Array<{ i: number; slug: string; content: string; sourcePath: string; path: string; inputPath: string; inputHash: string; target: string }> = [];
+ const slugs = new Set<string>();
+ let rest = files.length;
+ for (let i = 0; i < files.length; i++) {
+ let { filePath, sourcePath } = files[i]!;
+ try {
+ if (isImageFilePath(sourcePath) && process.env.GBRAIN_EMBEDDING_MULTIMODAL !== 'true') {
+ throw opError('invalid_params', 'Image import requires GBRAIN_EMBEDDING_MULTIMODAL=true.',
+ `${sourcePath} is an image and multimodal embeddings are off, so it was not imported. Import only text files, or ask the user whether to enable GBRAIN_EMBEDDING_MULTIMODAL=true for the gbrain process (image embeddings can cost money).`);
+ }
+ if (unowned) throw unowned;
+ const root = join(binding!.local_path!, binding!.relative_path);
+ const inputPath = resolve(filePath);
+ const canonicalRelative = relative(root, inputPath);
+ const canonicalInput = canonicalRelative && !isAbsolute(canonicalRelative) && canonicalRelative !== '..' && !canonicalRelative.startsWith(`..${sep}`);
+ if (canonicalInput && !opts.slugRoot) sourcePath = canonicalRelative;
+ 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);
+ if (slugs.has(slug)) { rest = i; break; }
+ slugs.add(slug);
+ planned.push({ i, slug, content, sourcePath, path, inputPath, inputHash: 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 }; });
+ if (rest < files.length) settled.splice(rest, files.length - rest, ...await importManagedFiles(engine, files.slice(rest), opts));
+ return settled;
+}
+
+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 }>,
+ opts: { noEmbed?: boolean; activePack?: ImportPack },
+ fail: (i: number, reason: unknown) => void, done: (i: number, value: ImportResult) => void): Promise<void> {
+ const { engine } = ctx;
+ const sourceId = binding.source_id;
+ let principal: Awaited<ReturnType<typeof requestPrincipalForContext>>;
+ try {
+ await initializeLocalPersistence(ctx);
+ principal = await requestPrincipalForContext(ctx);
+ } catch (error) { for (const entry of planned) fail(entry.i, error); return; }
+ const members = planned.map(entry => ({ ...entry, key: digest({ principal, incarnation: binding.source_incarnation, inputPath: entry.inputPath, sourcePath: entry.sourcePath,
+ path: entry.path, inputHash: entry.inputHash, noEmbed: !!opts.noEmbed, activePack: opts.activePack ?? null }), params: undefined as PendingImport | undefined }));
+ const readPending = async (keys: string[]) => new Map((await engine.executeRaw<{ fingerprint: string; completed_keys: [PendingImport] }>(
+ 'SELECT fingerprint,completed_keys FROM op_checkpoints WHERE op=$1 AND fingerprint=ANY($2::text[])', [IMPORT_OP, keys])).map(row => [row.fingerprint, row.completed_keys[0]]));
+ const open = new Set(members);
+ const settle = (member: (typeof members)[number], value: ImportResult) => { open.delete(member); done(member.i, value); };
+ const refuse = (member: (typeof members)[number], reason: unknown) => { open.delete(member); fail(member.i, reason); };
+ const batch = randomUUID();
try {
- const outcome = await submitPageMutation(ctx, { operation: 'put_page', params, waitMs: 30_000, managedFileImport: true });
- await engine.executeRaw('DELETE FROM op_checkpoints WHERE op=$1 AND fingerprint=$2 AND completed_keys=$3::text::jsonb', [op, key, JSON.stringify([params])]);
- return { slug: String(outcome.slug), status: outcome.status as ImportResult['status'], chunks: Number(outcome.chunks ?? 0),
- ...(typeof outcome.error === 'string' ? { error: outcome.error } : {}),
- ...(outcome.type_warning ? { type_warning: outcome.type_warning as ImportResult['type_warning'] } : {}) };
- } catch (error) {
- if (error instanceof OperationError && error.writeRequest && ['failed', 'conflict', 'cancelled'].includes(error.writeRequest.state)) {
- await engine.executeRaw('DELETE FROM op_checkpoints WHERE op=$1 AND fingerprint=$2 AND completed_keys=$3::text::jsonb', [op, key, JSON.stringify([params])]);
+ const pending = await readPending(members.map(member => member.key));
+ const fresh: typeof members = [];
+ for (const member of members) {
+ member.params = pending.get(member.key);
+ if (member.params) continue;
+ try {
+ const snapshot = await engine.readPageSnapshot(member.slug, { sourceId, includeDeleted: true });
+ const intent: ManagedImportIntent = { kind: 'managed_file_import', slug: member.slug, content: member.content, sourcePath: member.sourcePath, path: member.path,
+ inputPath: member.inputPath, inputHash: member.inputHash, targetHash: existsSync(member.target) ? sha256(readImportBytes(member.target)) : null,
+ ownerEpoch: String(binding.owner_epoch), ...(snapshot ? { expected_revision: snapshot.revision } : {}),
+ noEmbed: !!opts.noEmbed, ...(opts.activePack ? { activePack: opts.activePack } : {}) };
+ // #5470: an import whose publication would change nothing takes no admission.
+ if (await unchangedManagedImport(ctx, binding, intent, snapshot)) { settle(member, { slug: member.slug, status: 'skipped', chunks: 0 }); continue; }
+ member.params = { ...intent, ...(members.length > 1 ? { import_batch: batch } : {}), request_id: randomUUID(), source_id: sourceId };
+ fresh.push(member);
+ } catch (error) { refuse(member, error); }
+ }
+ if (fresh.length) {
+ await engine.executeRaw(`INSERT INTO op_checkpoints(op,fingerprint,completed_keys)
+ SELECT $1,k,c::jsonb FROM unnest($2::text[],$3::text[]) AS u(k,c) ON CONFLICT DO NOTHING`,
+ [IMPORT_OP, fresh.map(member => member.key), fresh.map(member => JSON.stringify([member.params]))]);
+ const stored = await readPending(fresh.map(member => member.key));
+ for (const member of fresh) member.params = stored.get(member.key)!;
+ }
+ } catch (error) { for (const member of [...open]) refuse(member, error); return; }
+ const submitted = members.filter(member => open.has(member));
+ if (!submitted.length) return;
+ const outcomes = await submitManagedImports(ctx, batch, submitted.map(member => member.params!));
+ const cleared: typeof submitted = [];
+ submitted.forEach((member, position) => {
+ const outcome = outcomes[position]!;
+ if (outcome.status === 'fulfilled') {
+ cleared.push(member);
+ const value = outcome.value;
+ done(member.i, { slug: String(value.slug), status: value.status as ImportResult['status'], chunks: Number(value.chunks ?? 0),
+ ...(typeof value.error === 'string' ? { error: value.error } : {}),
+ ...(value.type_warning ? { type_warning: value.type_warning as ImportResult['type_warning'] } : {}) });
+ return;
}
- throw error;
+ const error = outcome.reason;
+ if (error instanceof OperationError && error.writeRequest && ['failed', 'conflict', 'cancelled'].includes(error.writeRequest.state)) cleared.push(member);
+ fail(member.i, error);
+ });
+ if (!cleared.length) return;
+ try {
+ await engine.executeRaw(`DELETE FROM op_checkpoints o USING unnest($2::text[],$3::text[]) AS d(k,c)
+ WHERE o.op=$1 AND o.fingerprint=d.k AND o.completed_keys=d.c::jsonb`,
+ [IMPORT_OP, cleared.map(member => member.key), cleared.map(member => JSON.stringify([member.params]))]);
+ } catch (error) { for (const member of cleared) fail(member.i, error); }
+}
+
+/**
+ * The batch's owner-file `put_page` intents prepared under one writer
+ * verification, the new ones admitted in one transaction (page-batch.ts
+ * admitBatch) and awaited together. Each settles as submitPageMutation
+ * would settle it alone; a request still pending after its share of the
+ * wait settles as `write_pending`.
+ */
+async function submitManagedImports(ctx: OperationContext, batch: string, params: readonly PendingImport[]): Promise<PromiseSettledResult<Record<string, unknown>>[]> {
+ const settled: PromiseSettledResult<Record<string, unknown>>[] = new Array(params.length);
+ const rows: Array<{ index: number; row: WriteRequest; admitted: boolean; typeWarning?: unknown; slugAdvisory?: unknown }> = [];
+ try {
+ assertPersistenceAccepting(ctx.engine);
+ await withBatchAdmission(ctx, async (own, shared) => {
+ const admissions: Array<{ index: number; admission: WriteAdmission; typeWarning: unknown; slugAdvisory: unknown }> = [];
+ for (let index = 0; index < params.length; index++) {
+ try {
+ const prepared = await preparePageAdmission(index === 0 ? own : shared, { operation: 'put_page', params: params[index]!, managedFileImport: true });
+ if (prepared.prior) rows.push({ index, row: prepared.prior, admitted: false });
+ else admissions.push({ index, admission: prepared.admission, typeWarning: prepared.typeWarning, slugAdvisory: prepared.slugAdvisory });
+ } catch (reason) { settled[index] = { status: 'rejected', reason }; }
+ }
+ if (!admissions.length) return;
+ try {
+ const admitted = await admitBatch(ctx, batch, admissions.map(entry => entry.admission));
+ admissions.forEach((entry, position) => rows.push({ index: entry.index, row: admitted[position]!, admitted: true, typeWarning: entry.typeWarning, slugAdvisory: entry.slugAdvisory }));
+ } catch (reason) { for (const entry of admissions) settled[entry.index] = { status: 'rejected', reason }; }
+ });
+ } catch (reason) {
+ for (let index = 0; index < params.length; index++) settled[index] ??= { status: 'rejected', reason };
+ return settled;
}
+ rows.sort((a, b) => a.index - b.index);
+ const done = await waitForWrites(ctx.engine, rows.map(entry => entry.row), ctx.config, IMPORT_WAIT_MS * rows.length);
+ rows.forEach((entry, position) => {
+ try {
+ const response = pendingAwareResponse(ctx, done[position]!);
+ if (entry.admitted) emitFenceNotice(ctx, response, done[position]!.slug);
+ settled[entry.index] = { status: 'fulfilled', value: { ...response, ...(entry.typeWarning ? { type_warning: entry.typeWarning } : {}),
+ ...(entry.slugAdvisory ? { slug_advisory: entry.slugAdvisory } : {}) } };
+ } catch (reason) { settled[entry.index] = { status: 'rejected', reason }; }
+ });
+ return settled;
}
/** Runs the managed-import preparer on an unadmitted request; true only when the no-op kernel finds nothing to publish. */
diff --git a/src/core/persistence/import-prepare.ts b/src/core/persistence/import-prepare.ts
index e216586a10..e65518b775 100644
--- a/src/core/persistence/import-prepare.ts
+++ b/src/core/persistence/import-prepare.ts
@@ -3,7 +3,7 @@ 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 { importCodeFile, importFromContent, importImageFile, isImageFilePath, MAX_FILE_SIZE, MAX_IMAGE_BYTES } from '../import-file.ts';
+import { importCodeFile, importFromContent, importImageFile, isImageFilePath, MAX_FILE_SIZE, MAX_IMAGE_BYTES, verifyPageReadable } from '../import-file.ts';
import { parseMarkdown, serializePageToMarkdown } from '../markdown.ts';
import { applyInference } from '../frontmatter-inference.ts';
import { getCompanyBrainProfile } from '../company-brain/profile.ts';
@@ -182,7 +182,7 @@ export async function prepareManagedImportMutation(engine: BrainEngine, row: Wri
: 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',
- activePack: p.activePack, sourcePath: p.sourcePath, filename: basename(p.sourcePath, '.md'), allowEmptyOverwrite: true });
+ coordinated: true, existingSnapshot: snapshot, activePack: p.activePack, sourcePath: p.sourcePath, filename: basename(p.sourcePath, '.md'), allowEmptyOverwrite: true });
if (!prepared && result.refusal?.code === 'invalid_fence') throw managedImportRefusal(result.refusal, p.sourcePath);
if (!prepared) 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.`,
@@ -199,16 +199,28 @@ export async function prepareManagedImportMutation(engine: BrainEngine, row: Wri
...(snapshot?.page ?? { id: 0, 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');
- return { observedRevision: ready.observedRevision, noop: ready.noop && p.targetHash === sha256(rendered),
+ const mutation: PreparedMutation = { observedRevision: ready.observedRevision, noop: ready.noop && p.targetHash === sha256(rendered),
deferEmbedding: image || p.noEmbed, validate: async tx => { await checkPaths(tx); await ready.validate(tx); },
file: { root, path, content: rendered, expectedBeforeHash: p.targetHash },
apply: async tx => {
await ready.apply(tx);
await tx.executeRaw('UPDATE pages SET source_path=$3 WHERE source_id=$1 AND slug=$2 AND source_path IS DISTINCT FROM $3', [row.source_id, row.slug, p.sourcePath]);
- if (!ready.noop && project) await project(tx);
- if (!ready.noop && !image) await sealPageTextProjection(tx, row.slug, row.source_id);
+ if (project) {
+ // The coordinator proved the base revision under its page guard (importFromContent `coordinated`); this is the
+ // one read of the page after its last page write (the projections and the seal leave its revision unchanged):
+ // read-back check, projection target, seal input and the receipt's postimage.
+ const final = await tx.readPageSnapshot(row.slug, { ...source, includeDeleted: true });
+ const live = final && final.page.deleted_at == null ? final : null;
+ if (!ready.noop) {
+ await verifyPageReadable(tx, row.slug, ready.contentHash!, row.source_id, 'importFromContent', live?.page ?? null);
+ await project(tx, final?.page.id);
+ if (live) await sealPageTextProjection(tx, row.slug, row.source_id, live);
+ }
+ mutation.postimage = final;
+ } else if (!ready.noop && !image) await sealPageTextProjection(tx, row.slug, row.source_id);
// #6188: the canonical file is written from the normalized page; the outcome reports what Tier 1 rewrote.
return { ...result, parsedPage: undefined, imported_file: true, source_id: row.source_id, fences_normalized: result.fences_normalized?.length
? pageFencesNormalized({ sourceId: row.source_id, slug: row.slug, fixes: result.fences_normalized, writer: row.principal_kind, path: p.sourcePath, remote: false }) : undefined };
} };
+ return mutation;
}
diff --git a/src/core/persistence/journal.ts b/src/core/persistence/journal.ts
index d49289f983..4e423dcbbf 100644
--- a/src/core/persistence/journal.ts
+++ b/src/core/persistence/journal.ts
@@ -318,16 +318,24 @@ export async function admitWriteGroupInTransaction(tx: BrainEngine, inputs: Writ
* is never claimed past an unfinished non-member, so the FIFO order holds.
*/
/**
- * The publication group key of a request: a bulk sync's `intent.group`, or the
- * batch id of a `put_pages` child (`intent.page_batch.id`, #6007). Null when it
+ * The publication group key of a request: a bulk sync's `intent.group`, the
+ * batch id of a `put_pages` child (`intent.page_batch.id`, #6007), or the
+ * batch id of a managed file import (`intent.import_batch`). Null when it
* publishes alone.
*/
export function publicationGroupKey(row: Pick<WriteRequest, 'operation' | 'intent'>): string | null {
if (typeof row.intent?.group === 'string') return `sync:${row.intent.group}`;
+ if (row.operation !== 'put_page') return null;
+ if (row.intent?.kind === 'managed_file_import') return typeof row.intent.import_batch === 'string' ? `import:${row.intent.import_batch}` : null;
const batch = row.intent?.page_batch as { id?: unknown } | undefined;
- return row.operation === 'put_page' && !row.intent?.kind && typeof batch?.id === 'string' ? `batch:${batch.id}` : null;
+ return !row.intent?.kind && typeof batch?.id === 'string' ? `batch:${batch.id}` : null;
+}
+/** Groups whose members are independent page writes: one member's failure never cancels the others. */
+export function independentGroup(key: string | null): boolean {
+ return key !== null && (key.startsWith('batch:') || key.startsWith('import:'));
}
const GROUP_KEY_SQL = `CASE WHEN intent ? 'group' THEN 'sync:'||(intent->>'group')
+ WHEN operation='put_page' AND intent->>'kind'='managed_file_import' AND jsonb_typeof(intent->'import_batch')='string' THEN 'import:'||(intent->>'import_batch')
WHEN operation='put_page' AND NOT (intent ? 'kind') AND jsonb_typeof(intent->'page_batch'->'id')='string' THEN 'batch:'||(intent->'page_batch'->>'id') END`;
export async function claimGroupFollowers(engine: BrainEngine, head: WriteRequest, group: string, max: number, leaseMs = 30_000): Promise<WriteRequest[]> {
if (!head.worktree_id || max <= 0) return [];
diff --git a/src/core/persistence/page-batch.ts b/src/core/persistence/page-batch.ts
index 2c81d6a580..cb631ddbb6 100644
--- a/src/core/persistence/page-batch.ts
+++ b/src/core/persistence/page-batch.ts
@@ -153,7 +153,7 @@ function batchReceipt(ctx: OperationContext, batchId: string, sourceId: string,
* all of them or none. Pages whose stored authority differs (for example one
* page is database-only) are admitted as separate groups inside it.
*/
-async function admitBatch(ctx: OperationContext, batchId: string, admissions: WriteAdmission[]): Promise<WriteRequest[]> {
+export async function admitBatch(ctx: OperationContext, batchId: string, admissions: WriteAdmission[]): Promise<WriteRequest[]> {
const groups = new Map<string, number[]>();
admissions.forEach((admission, index) => {
const key = digest(admission.authority);
diff --git a/src/core/persistence/page-mutations.ts b/src/core/persistence/page-mutations.ts
index 5bce8d18b9..ad92b4a482 100644
--- a/src/core/persistence/page-mutations.ts
+++ b/src/core/persistence/page-mutations.ts
@@ -54,8 +54,9 @@ const flatSql = (sql: string) => sql.replace(/\s+/g, ' ').trim();
/**
* Pre-admission reads every page of one batch makes with the same arguments:
* the source row, the worktree binding, the writer registration, the shared
- * skillpack roots, the persistence identity and config values. All of them
- * are rechecked under lock by the admission transaction.
+ * skillpack roots, the persistence identity and config values, and a managed
+ * import's source-root and company-profile checks. All of them are rechecked
+ * under lock by the admission transaction or by publication.
*/
const BATCH_SHARED_READS = new Set([
"SELECT incarnation,archived,local_path,config->>'kind' AS kind FROM sources WHERE id=$1",
@@ -64,8 +65,11 @@ const BATCH_SHARED_READS = new Set([
'SELECT local_path FROM sources WHERE id=$1 AND incarnation=$2::uuid',
'SELECT brain_id FROM persistence_brain WHERE singleton=1',
'SELECT value FROM config WHERE key=$1',
+ "SELECT config,incarnation FROM sources WHERE id=$1",
+ "SELECT id FROM source_ingestion_receipts WHERE source_id=$1 AND source_incarnation=$2::uuid AND profile='company-brain' LIMIT 1",
+ 'SELECT s.id,s.local_path,h.local_path AS worktree_path,b.relative_path FROM sources s LEFT JOIN persistence_source_bindings b ON b.source_id=s.id AND b.source_incarnation=s.incarnation LEFT JOIN persistence_host_bindings h ON h.worktree_id=b.worktree_id AND h.host_id=$1::uuid WHERE NOT s.archived',
]);
-function batchSharedReads(engine: BrainEngine): BrainEngine {
+export function batchSharedReads(engine: BrainEngine): BrainEngine {
const reads = new Map<string, Promise<unknown>>();
const once = <T>(id: string, read: () => Promise<T>): Promise<T> => {
let value = reads.get(id) as Promise<T> | undefined;
@@ -152,7 +156,7 @@ async function resolveCaptureFile(ctx: OperationContext, sourceId: string, p: Re
return resolveSlugForPath(scannerSourcePath(canonicalRoot, join(canonicalRoot, capturePath), await scannerSlugRootMode(ctx.engine, sourceId, canonicalRoot)));
}
-function pendingAwareResponse(ctx: OperationContext, row: WriteRequest): Record<string, unknown> {
+export function pendingAwareResponse(ctx: OperationContext, row: WriteRequest): Record<string, unknown> {
try { return writeResponse(row, { retryAfterMs: estimatedRetryAfterMs(ctx.engine, 1), waiterOnlyOwner: waiterOnlyOwner(ctx.engine) }); } catch (error) {
// #5929: a trusted local caller is told when an owner on another build ran the failed attempt.
const mismatch = ctx.remote === false ? ownerBuildMismatch(row.error_detail, VERSION) : null;
diff --git a/test/persistence-import-batch.test.ts b/test/persistence-import-batch.test.ts
new file mode 100644
index 0000000000..8b600c735a
--- /dev/null
+++ b/test/persistence-import-batch.test.ts
@@ -0,0 +1,224 @@
+import { afterAll, beforeAll, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { dirname, join, relative } from 'node:path';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { withEnv } from './helpers/with-env.ts';
+import { importManagedFile, importManagedFiles } from '../src/core/persistence/import-mutations.ts';
+import { claimWorktree, getWorktreeBinding } from '../src/core/persistence/ownership.ts';
+import { localHostId, registerLocalWriter } from '../src/core/persistence/identity.ts';
+import { claimGroupFollowers, claimNextWrite, independentGroup, publicationGroupKey, releaseUnpublishedClaim } from '../src/core/persistence/journal.ts';
+import { disposePersistenceConsumer, waitForWrites } from '../src/core/persistence/service.ts';
+import { managedImportContent } from '../src/core/persistence/import-prepare.ts';
+import { preparePageAdmission } from '../src/core/persistence/page-mutations.ts';
+import { admitBatch } from '../src/core/persistence/page-batch.ts';
+import { sha256 } from '../src/core/persistence/digest.ts';
+import type { OperationContext } from '../src/core/ops/contract.ts';
+import { renderFactsTable } from '../src/core/facts-fence.ts';
+import { runImport } from '../src/commands/import.ts';
+
+const home = mkdtempSync(join(tmpdir(), 'gbrain-import-batch-'));
+const env = { GBRAIN_HOME: home, OPENAI_API_KEY: undefined, VOYAGE_API_KEY: undefined, ANTHROPIC_API_KEY: undefined };
+type Brain = { label: string; engine: BrainEngine; close: () => Promise<void> };
+const pairs: Array<[Brain, Brain]> = [];
+
+async function pglite(label: string): Promise<Brain> {
+ const engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema();
+ return { label, engine, close: () => engine.disconnect() };
+}
+async function postgres(label: string): Promise<Brain> {
+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!);
+ return { label, engine: pg.engine, close: pg.close };
+}
+
+beforeAll(async () => {
+ pairs.push([await pglite('pglite-one-by-one'), await pglite('pglite-batched')]);
+ if (process.env.DATABASE_URL) pairs.push([await postgres('postgres-one-by-one'), await postgres('postgres-batched')]);
+}, 180_000);
+afterAll(async () => {
+ await withEnv(env, async () => {
+ for (const brain of pairs.flat()) { await disposePersistenceConsumer(brain.engine); await brain.close(); }
+ });
+ rmSync(home, { recursive: true, force: true });
+});
+
+async function managedSource(engine: BrainEngine, sourceId: string, label: string) {
+ const root = join(home, `${label}-${sourceId}`);
+ mkdirSync(root, { 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 root;
+}
+
+const fact = (rowNum: number, claim: string) => renderFactsTable([{ rowNum, claim, kind: 'fact', confidence: 1, visibility: 'world', notability: 'medium', active: true, context: 'fixture' }]);
+function page(title: string, opts: { type?: string; tags?: string[]; links?: string[]; facts?: string; timeline?: string[]; body?: string } = {}): string {
+ const fm = ['---', `type: ${opts.type ?? 'note'}`, `title: "${title}"`, ...(opts.tags?.length ? [`tags: [${opts.tags.join(', ')}]`] : []), '---', ''];
+ const body = [`# ${title}`, '', opts.body ?? `Notes about ${title} for the import fixture.`, '',
+ ...(opts.links ?? []).map(link => `- Related: [[${link}]]`), ...(opts.facts ? ['', `Facts: ${opts.facts}`] : [])];
+ const timeline = opts.timeline?.length ? ['', '<!-- timeline -->', '', ...opts.timeline.map(line => `- **${line}**`)] : [];
+ return [...fm, ...body, ...timeline, ''].join('\n');
+}
+
+/** A first import, then a second pass that updates, adds, collides on a slug and carries a refused file. */
+const FIRST: Record<string, string> = {
+ 'people/alice-example.md': page('Alice Example', { type: 'person', tags: ['team'], links: ['companies/acme-example'], timeline: ['2024-01-02** | joined acme-example'] }),
+ 'notes/kept.md': page('Kept note', { body: 'Unchanged between passes.' }),
+ 'notes/edited.md': page('Edited note', { body: 'The first version.' }),
+};
+const SECOND: Record<string, string> = {
+ 'notes/kept.md': FIRST['notes/kept.md']!,
+ 'notes/edited.md': page('Edited note', { body: 'The second version links forward.', links: ['notes/topic-11'], tags: ['changed'] }),
+ 'companies/acme-example.md': page('Acme Example', { type: 'company', links: ['people/alice-example', 'people/bob-example'],
+ facts: fact(1, 'acme-example builds example widgets'), timeline: ['2024-02-03** | met alice-example', '2024-03-04** | shipped widgets'] }),
+ 'people/bob-example.md': page('Bob Example', { type: 'person', links: ['companies/acme-example', 'notes/topic-3'], timeline: ['2024-05-06** | joined'] }),
+ 'notes/Foo Bar.md': page('Foo Bar spaced', { body: 'First file with the foo-bar slug.' }),
+ 'notes/foo-bar.md': page('Foo Bar dashed', { body: 'Second file with the same slug.' }),
+ 'broken.md': '---\ntags:\n - a\n - b\n---\nBody\n',
+ ...Object.fromEntries(Array.from({ length: 14 }, (_, i) => [`notes/topic-${i}.md`,
+ page(`Topic ${i}`, { tags: [`tag-${i % 3}`], links: [`notes/topic-${(i + 5) % 14}`, 'people/alice-example'], facts: i % 4 === 0 ? fact(1, `topic ${i} is about examples`) : undefined,
+ timeline: i % 3 === 0 ? [`2024-0${1 + (i % 9)}-1${i % 10}** | topic ${i} event`] : [] })])),
+};
+
+function write(root: string, files: Record<string, string>) {
+ for (const [path, content] of Object.entries(files)) { mkdirSync(dirname(join(root, path)), { recursive: true }); writeFileSync(join(root, path), content); }
+ return Object.keys(files).sort().map(path => ({ filePath: join(root, path), sourcePath: path }));
+}
+const UUID = /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi;
+function normalize(value: unknown): unknown {
+ if (value instanceof Date) return '<time>';
+ if (typeof value === 'string') return value.replace(UUID, '<uuid>');
+ if (typeof value === 'bigint') return String(value);
+ if (Array.isArray(value)) return value.map(normalize);
+ if (value && typeof value === 'object') return Object.fromEntries(Object.entries(value).filter(([key]) => !/(_at|^updated|^created)$/.test(key)).map(([key, v]) => [key, normalize(v)]));
+ return value;
+}
+const TABLES = ['pages', 'content_chunks', 'links', 'timeline_entries', 'facts', 'takes', 'tags', 'page_aliases', 'slug_aliases', 'page_versions'];
+/** Every row of every table the import writes, all columns (timestamps dropped, generated ids masked), in a stable order. */
+async function state(engine: BrainEngine, root: string) {
+ const out: Record<string, string[]> = {};
+ for (const table of TABLES) {
+ const columns = await engine.executeRaw<{ column_name: string; data_type: string }>(
+ "SELECT column_name,data_type FROM information_schema.columns WHERE table_schema='public' AND table_name=$1 ORDER BY ordinal_position", [table]);
+ const select = columns.map(c => ['USER-DEFINED', 'tsvector'].includes(c.data_type) ? `"${c.column_name}"::text AS "${c.column_name}"` : `"${c.column_name}"`).join(',');
+ out[table] = (await engine.executeRaw(`SELECT ${select} FROM ${table}`)).map(row => JSON.stringify(normalize(row))).sort();
+ }
+ const walk = (dir: string): string[] => readdirSync(dir).filter(name => !name.startsWith('.gbrain')).flatMap(name => statSync(join(dir, name)).isDirectory() ? walk(join(dir, name)) : [join(dir, name)]);
+ out.files = walk(root).map(file => `${relative(root, file)}\n${readFileSync(file, 'utf8')}`).sort();
+ return out;
+}
+const outcome = (settled: PromiseSettledResult<unknown>) => settled.status === 'fulfilled' ? { ok: settled.value }
+ : { error: (settled.reason as { code?: string }).code ?? null, message: String((settled.reason as Error).message).replace(UUID, '<uuid>') };
+
+test('a batched managed import leaves exactly the rows, files and per-file results of importing the files one by one', async () => withEnv(env, async () => {
+ for (const [one, batched] of pairs) {
+ const sourceId = `batch-${randomUUID().slice(0, 8)}`;
+ const roots = { one: await managedSource(one.engine, sourceId, one.label), batched: await managedSource(batched.engine, sourceId, batched.label) };
+ for (const [brain, root] of [[one, roots.one], [batched, roots.batched]] as const) {
+ for (const file of write(root, FIRST)) await importManagedFile(brain.engine, file.filePath, file.sourcePath, { sourceId, noEmbed: true });
+ }
+ const sequential: PromiseSettledResult<unknown>[] = [];
+ for (const file of write(roots.one, SECOND)) {
+ sequential.push(await importManagedFile(one.engine, file.filePath, file.sourcePath, { sourceId, noEmbed: true })
+ .then(value => ({ status: 'fulfilled' as const, value }), reason => ({ status: 'rejected' as const, reason })));
+ }
+ const files = write(roots.batched, SECOND);
+ const together = await importManagedFiles(batched.engine, files, { sourceId, noEmbed: true });
+ expect(together.map(outcome)).toEqual(sequential.map(outcome));
+ expect(together.filter(result => result.status === 'fulfilled' && result.value.status === 'imported').length).toBeGreaterThan(16);
+ expect(together.map(outcome).find(result => 'error' in result && result.message?.includes('Invalid YAML'))).toBeDefined();
+ expect(await state(batched.engine, roots.batched)).toEqual(await state(one.engine, roots.one));
+ // Every new request of the call carries one batch marker, so the owner publishes them as independent groups.
+ const markers = await batched.engine.executeRaw<{ marker: string | null }>(
+ "SELECT DISTINCT intent->>'import_batch' AS marker FROM persistence_requests WHERE source_id=$1 AND intent->>'import_batch' IS NOT NULL", [sourceId]);
+ expect(markers.length).toBeGreaterThanOrEqual(1);
+ expect(await batched.engine.executeRaw("SELECT fingerprint FROM op_checkpoints WHERE op='managed-file-import'")).toHaveLength(
+ (await one.engine.executeRaw("SELECT fingerprint FROM op_checkpoints WHERE op='managed-file-import'")).length);
+ // A repeated import settles every file as the one-by-one import does, and admits the same (refused-file) requests.
+ const requests = async (brain: Brain) => (await brain.engine.executeRaw('SELECT id FROM persistence_requests WHERE source_id=$1', [sourceId])).length;
+ const before = await requests(batched);
+ expect(before).toBe(await requests(one));
+ const againOne: PromiseSettledResult<unknown>[] = [];
+ for (const file of write(roots.one, SECOND)) {
+ againOne.push(await importManagedFile(one.engine, file.filePath, file.sourcePath, { sourceId, noEmbed: true })
+ .then(value => ({ status: 'fulfilled' as const, value }), reason => ({ status: 'rejected' as const, reason })));
+ }
+ const againBatched = await importManagedFiles(batched.engine, write(roots.batched, SECOND), { sourceId, noEmbed: true });
+ expect(againBatched.map(outcome)).toEqual(againOne.map(outcome));
+ expect(againBatched.filter(result => result.status === 'fulfilled').every(result => (result as PromiseFulfilledResult<{ status: string }>).value.status === 'skipped')).toBe(true);
+ expect(await requests(batched)).toBe(await requests(one));
+ expect(await state(batched.engine, roots.batched)).toEqual(await state(one.engine, roots.one));
+ }
+}), 300_000);
+
+test('runImport accounts every file of a batched directory import', async () => withEnv(env, async () => {
+ for (const [, brain] of pairs) {
+ const sourceId = `dir-${randomUUID().slice(0, 8)}`;
+ const root = await managedSource(brain.engine, sourceId, brain.label);
+ write(root, SECOND);
+ const result = await runImport(brain.engine, [root, '--no-embed', '--fresh'], { sourceId });
+ expect(result).toMatchObject({ imported: Object.keys(SECOND).length - 2, errors: 2 });
+ const failed = (result as { failures: Array<{ path: string }> }).failures.map(failure => failure.path);
+ expect(failed).toContain('broken.md');
+ expect(failed.filter(path => path === 'notes/foo-bar.md' || path === 'notes/Foo Bar.md')).toHaveLength(1);
+ expect(await runImport(brain.engine, [root, '--no-embed', '--fresh'], { sourceId })).toMatchObject({ imported: 0, errors: 2 });
+ }
+}), 300_000);
+
+test('a batch that is interrupted after admission resumes its accepted requests', async () => withEnv(env, async () => {
+ for (const [, brain] of pairs) {
+ const sourceId = `resume-${randomUUID().slice(0, 8)}`;
+ await managedSource(brain.engine, sourceId, brain.label);
+ // Input outside the canonical root: publication writes the root's copy, so the input bytes (and the durable intent's key) stay put.
+ const input = join(home, `${brain.label}-${sourceId}-input`);
+ const files = write(input, Object.fromEntries(Array.from({ length: 5 }, (_, i) => [`resume-${i}.md`, page(`Resume ${i}`)])));
+ const original = brain.engine.executeRaw;
+ let fail = true;
+ brain.engine.executeRaw = async function(this: BrainEngine, sql, params) {
+ if (fail && sql.startsWith('DELETE FROM op_checkpoints') && params?.[0] === 'managed-file-import') { fail = false; throw new Error('simulated caller interruption'); }
+ return original.call(this, sql, params);
+ } as BrainEngine['executeRaw'];
+ let first: PromiseSettledResult<unknown>[];
+ try { first = await importManagedFiles(brain.engine, files, { sourceId, noEmbed: true }); } finally { brain.engine.executeRaw = original; }
+ expect(first.map(outcome)).toEqual(files.map(() => ({ error: null, message: 'simulated caller interruption' })));
+ const resumed = await importManagedFiles(brain.engine, files, { sourceId, noEmbed: true });
+ expect(resumed.map(result => result.status === 'fulfilled' && result.value.status)).toEqual(files.map(() => 'imported'));
+ expect(await brain.engine.executeRaw('SELECT id FROM persistence_requests WHERE source_id=$1', [sourceId])).toHaveLength(files.length);
+ expect(await brain.engine.executeRaw("SELECT fingerprint FROM op_checkpoints WHERE op='managed-file-import' AND completed_keys->0->>'source_id'=$1", [sourceId])).toHaveLength(0);
+ }
+}), 300_000);
+
+test('an import batch admits its members as one independent publication group', async () => withEnv(env, async () => {
+ const [, brain] = pairs[0]!;
+ const sourceId = `group-${randomUUID().slice(0, 8)}`;
+ const root = await managedSource(brain.engine, sourceId, brain.label);
+ const files = write(root, Object.fromEntries(Array.from({ length: 10 }, (_, i) => [`group-${i}.md`, page(`Group ${i}`)])));
+ await disposePersistenceConsumer(brain.engine);
+ const binding = (await getWorktreeBinding(brain.engine, sourceId))!;
+ const ctx = { engine: brain.engine, remote: false, sourceId, config: { engine: brain.engine.kind } } as OperationContext;
+ const batch = randomUUID();
+ const admissions = await Promise.all(files.map(async file => {
+ const bytes = readFileSync(file.filePath);
+ const { slug, content } = managedImportContent(file.sourcePath, bytes);
+ const prepared = await preparePageAdmission(ctx, { operation: 'put_page', managedFileImport: true, params: { kind: 'managed_file_import', slug, content,
+ sourcePath: file.sourcePath, path: file.sourcePath, inputPath: file.filePath, inputHash: sha256(bytes), targetHash: sha256(bytes),
+ ownerEpoch: String(binding.owner_epoch), noEmbed: true, import_batch: batch, request_id: randomUUID(), source_id: sourceId } });
+ return prepared.admission!;
+ }));
+ const rows = await admitBatch(ctx, batch, admissions);
+ const head = (await claimNextWrite(brain.engine, localHostId()))!;
+ expect(head.id).toBe(rows[0]!.id);
+ const key = publicationGroupKey(head);
+ expect(key).toBe(`import:${batch}`);
+ expect(independentGroup(key)).toBe(true);
+ const followers = await claimGroupFollowers(brain.engine, head, key!, 7);
+ expect(followers.map(row => row.id)).toEqual(rows.slice(1, 8).map(row => row.id));
+ for (const row of [head, ...followers]) await releaseUnpublishedClaim(brain.engine, row, 'group_member_waiting');
+ const settled = await waitForWrites(brain.engine, rows, ctx.config, 60_000);
+ expect(settled.map(row => row.state)).toEqual(files.map(() => 'committed'));
+}), 300_000);