Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

refactor(import): batch settlement lives in import-mutations; test lanes and isolation

time-attack6594060ab5ad
diff --git a/src/commands/import.ts b/src/commands/import.ts
index a16a37516a..23b76e48fe 100644
--- a/src/commands/import.ts
+++ b/src/commands/import.ts
@@ -39,7 +39,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, importManagedFiles, nextImportBatch } from '../core/persistence/import-mutations.ts';
+import { importManagedFile, nextImportBatch, settleManagedImportBatch } 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';
@@ -832,22 +832,11 @@ 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)]);
+ const settled = batch.length > 1 && !signal?.aborted ? await settleManagedImportBatch(eng, batch, file => opts.slugRoot ? relative(opts.slugRoot, file)
+ : relative(importRoot, file), rel => !!opts.heldPaths?.has(rel), { noEmbed, sourceId, activePack: importActivePack, signal, slugRoot: opts.slugRoot }) : undefined;
+ for (const [i, file] of batch.entries()) await processFile(eng, file, settled?.[i]);
}
-
let workerError: unknown;
let workerFailed = false;
try {
@@ -857,7 +846,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 (let i = 0, batch: string[]; i < files.length && !signal?.aborted; i += batch.length) await processBatch(engine, batch = take(i));
+ for (let i = 0, batch: string[]; i < files.length && !signal?.aborted; i += batch.length) await processBatch(engine, batch = nextImportBatch(files, i, managedImport && !company));
} else {
const { PostgresEngine } = await import('../core/postgres-engine.ts');
const { connectWithRetry, resolvePoolSize } = await import('../core/db.ts');
@@ -888,8 +877,7 @@ export async function runImport(
try {
while (!stopWorkers && !signal?.aborted) {
if (queueIndex >= files.length) break;
- const batch = take(queueIndex);
- queueIndex += batch.length;
+ const batch = nextImportBatch(files, queueIndex, managedImport && !company); queueIndex += batch.length;
await processBatch(eng, batch);
}
} catch (error) {
@@ -916,7 +904,7 @@ export async function runImport(
} // end else (postgres parallel)
} else {
// Sequential: use the provided engine
- for (let i = 0, batch: string[]; i < files.length && !signal?.aborted; i += batch.length) await processBatch(engine, batch = take(i));
+ for (let i = 0, batch: string[]; i < files.length && !signal?.aborted; i += batch.length) await processBatch(engine, batch = nextImportBatch(files, i, managedImport && !company));
}
} catch (error) {
workerFailed = true;
diff --git a/src/core/persistence/import-mutations.ts b/src/core/persistence/import-mutations.ts
index 7fdebe1d1e..8139fdd33d 100644
--- a/src/core/persistence/import-mutations.ts
+++ b/src/core/persistence/import-mutations.ts
@@ -27,8 +27,13 @@ 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[] {
+/**
+ * The files of `queue` from `start` that one `runImport` batch takes: at least one, at most the page and byte caps;
+ * exactly one when the import is not a managed one (`batched` false). `runImport` accounts each file of a batch, in
+ * order, through its per-file bookkeeping.
+ */
+export function nextImportBatch(queue: readonly string[], start: number, batched = true): string[] {
+ if (!batched) return [queue[start]!];
const batch: string[] = [];
let bytes = 0;
for (let i = start; i < queue.length && batch.length < IMPORT_BATCH_MAX_PAGES; i++) {
@@ -39,6 +44,19 @@ export function nextImportBatch(queue: readonly string[], start: number): string
}
return batch;
}
+/**
+ * One `runImport` batch: the result of every file of `batch` in its order, undefined for a held path (the caller
+ * accounts it as held). A batch that fails as a whole settles each of its files with that failure.
+ */
+export async function settleManagedImportBatch(engine: BrainEngine, batch: readonly string[], sourcePathOf: (file: string) => string,
+ held: (sourcePath: string) => boolean, opts: Parameters<typeof importManagedFiles>[2]): Promise<Array<PromiseSettledResult<ImportResult> | undefined>> {
+ const open = batch.filter(file => !held(sourcePathOf(file)));
+ const t0 = Date.now();
+ const settled: PromiseSettledResult<ImportResult>[] = !open.length ? [] : await importManagedFiles(engine, open.map(filePath => ({ filePath, sourcePath: sourcePathOf(filePath) })), opts)
+ .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=${sourcePathOf(open[0]!)}`);
+ return batch.map(file => settled[open.indexOf(file)]);
+}
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;
diff --git a/test/persistence-import-batch.test.ts b/test/persistence-import-batch.test.ts
index cf9f7b36b0..f5ed539401 100644
--- a/test/persistence-import-batch.test.ts
+++ b/test/persistence-import-batch.test.ts
@@ -25,18 +25,20 @@ const env = { GBRAIN_HOME: home, OPENAI_API_KEY: undefined, VOYAGE_API_KEY: unde
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')]);
+ const lite: Brain[] = [];
+ for (const label of ['pglite-one-by-one', 'pglite-batched']) {
+ const engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema();
+ lite.push({ label, engine, close: () => engine.disconnect() });
+ }
+ pairs.push([lite[0]!, lite[1]!]);
+ if (!process.env.DATABASE_URL) return;
+ const pg: Brain[] = [];
+ for (const label of ['postgres-one-by-one', 'postgres-batched']) {
+ const db = await isolatedPersistencePostgres(process.env.DATABASE_URL);
+ pg.push({ label, engine: db.engine, close: db.close });
+ }
+ pairs.push([pg[0]!, pg[1]!]);
}, 180_000);
afterAll(async () => {
await withEnv(env, async () => {
diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txt
index 622d62e476..3a2467de22 100644
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@ -77,6 +77,7 @@ test/persistence-git-subdir-origin.test.ts
test/persistence-graph-publication.test.ts
test/persistence-history-fixture.test.ts
test/persistence-image-import.serial.test.ts
+test/persistence-import-batch.test.ts
test/persistence-managed-lifecycle.test.ts
test/persistence-managed-sync.test.ts
test/persistence-manifest-git-scope.test.ts