Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(migrate): facts phase drains every source; a wall-clock stop is not a failure (#6588)
time-attackc63c6fd1008a
diff --git a/docs/embedding-migrations.md b/docs/embedding-migrations.mdindex ce1061bc48..6868140bfd 100644--- a/docs/embedding-migrations.md+++ b/docs/embedding-migrations.md@@ -94,9 +94,14 @@ gbrain embed --stale --facts --source source-example \The cap must be finite and nonnegative. `--max-facts` limits attempted facts(default 100, range 1–10,000); `--batch-size` bounds each batch (default 100,range 1–100); `--budget-ms` limits run time (default 60,000, range 1–3,600,000).-All three accept integers. These limits do not authorize spend. Standalone+All three accept integers. These limits do not authorize spend. A run that+reaches `--budget-ms` stops with `stopped: "time_budget"` and no failures; its+unfinished facts stay in `remaining` for the next run. Standalonerepair is bounded per invocation; use brain-wide migration when durable total-authorization across interruptions is required.+authorization across interruptions is required. The migration's fact phase has+no per-run fact cap or wall-clock budget: it drains each source's stale facts as+counted at the start of the phase, bounded by the migration lease and cost cap,+so a slow source no longer stops the sources after it.Each provider attempt rechecks source identity, authority, selected-brain anddatabase off switches, model identity and spend allowance. Installation rechecksdiff --git a/scripts/serial-files.tsv b/scripts/serial-files.tsvindex 86ea1d7069..35d60b2b21 100644--- a/scripts/serial-files.tsv+++ b/scripts/serial-files.tsv@@ -257,6 +257,7 @@ test/memory-safety-wave.serial.test.ts global-state global-state: process-wide ttest/migrate-embeddings-ann-deferred-5088.serial.test.ts R1 R1: mutates process.env (GBRAIN_HOME)test/migrate-embeddings-boundary.serial.test.ts R1 R1: mutates process.env (GBRAIN_HOME)test/migrate-embeddings-dry-run-split-5226.serial.test.ts global-state global-state: process-wide test seams __setEmbedTransportForTests; configureGateway changes the process-wide AI gateway; spyOn console.log, console.error+test/migrate-embeddings-facts-drain.serial.test.ts global-state global-state: configureGateway and __setEmbedTransportForTests replace the process-wide AI gateway; spyOn AbortSignal.timeout compresses the standalone repair timertest/migrate-embeddings-flow.serial.test.ts R1 R1: mutates process.env (GBRAIN_HOME)test/migrate-embeddings-hardening.serial.test.ts R1 R1: mutates process.env (GBRAIN_HOME, GBRAIN_EMBEDDING_MODEL, GBRAIN_EMBEDDING_DIMENSIONS, GBRAIN_EMBED_LOCK_HEARTBEAT_MS (+3 more))test/migrate-embeddings-op-contract.serial.test.ts R1 R1: mutates process.env (GBRAIN_HOME, GBRAIN_EMBEDDING_MODEL, GBRAIN_EMBEDDING_DIMENSIONS)diff --git a/src/commands/migrate-embeddings.ts b/src/commands/migrate-embeddings.tsindex aac21dc360..957f22e824 100644--- a/src/commands/migrate-embeddings.ts+++ b/src/commands/migrate-embeddings.ts@@ -766,7 +766,9 @@ export async function executeMigrationFlow(const [active] = await engine.executeRaw('SELECT id FROM sources WHERE id=$1 AND NOT archived', [sourceId]);if (!active) continue;await assertOwned();- const facts = await embedStaleFacts(engine, { sourceId, yes: true, maxCostUsd: opts.maxCostUsd ?? marker.state?.budget?.max_cost_usd ?? 0, maxFacts: 10_000, signal: controller.signal, assertOwned });+ const facts = await embedStaleFacts(engine, { sourceId, yes: true,+ maxCostUsd: opts.maxCostUsd ?? marker.state?.budget?.max_cost_usd ?? 0,+ migrationDrain: { signal: controller.signal, assertOwned } });embeddedFacts += facts.embedded;if (facts.failures) break;}diff --git a/src/core/embed-facts.ts b/src/core/embed-facts.tsindex 227d300b43..fa6c799220 100644--- a/src/core/embed-facts.ts+++ b/src/core/embed-facts.ts@@ -1,7 +1,7 @@import type { BrainEngine } from './engine.ts';import { embed, getEmbeddingDimensions, getEmbeddingModel } from './ai/gateway.ts';import { withAIInvocationGuard } from './ai/invocation-guard.ts';-import { BudgetTracker, loadPricingOverrides } from './budget/budget-tracker.ts';+import { BudgetExhausted, BudgetTracker, loadPricingOverrides } from './budget/budget-tracker.ts';import { assertEmbeddingEnabled, readFactsEmbeddingDim } from './embedding-dim-check.ts';import type { GBrainConfig } from './config.ts';import { redactConnectionInfo } from './audit/redact-connection-info.ts';@@ -21,6 +21,8 @@ import { eligibleFactEmbedding, staleFactEmbedding } from './facts/embedding-ideexport interface EmbedFactsOpts extends EmbedFactsOptions {signal?: AbortSignal;assertOwned?: (tx: BrainEngine) => Promise<void>;+ /** Internal full migration: drain the finite census under the migration's lease and signal, with no wall-clock budget. */+ migrationDrain?: { signal: AbortSignal; assertOwned: (tx: BrainEngine) => Promise<void> };}export interface EmbedFactsResult {@@ -35,7 +37,7 @@ export interface EmbedFactsResult {failure_samples: string[];cost_usd: number;cost_estimated: boolean;- stopped: 'preview' | 'complete' | 'limit' | 'aborted' | 'failed';+ stopped: 'preview' | 'complete' | 'limit' | 'time_budget' | 'aborted' | 'failed';}interface PendingFact {@@ -47,11 +49,11 @@ interface PendingFact {const eligible = `f.source_id = $1 AND ${eligibleFactEmbedding} AND ${staleFactEmbedding}`;export async function embedStaleFacts(engine: BrainEngine, opts: EmbedFactsOpts, selectedConfig: GBrainConfig | null = null): Promise<EmbedFactsResult> {- const { signal: externalSignal, assertOwned, ...wireOptions } = opts;- opts = { ...validateEmbedFactsOptions(wireOptions), signal: externalSignal, assertOwned };- const maxFacts = opts.maxFacts ?? 100;+ const { signal: externalSignal, assertOwned, migrationDrain, ...wireOptions } = opts;+ opts = { ...validateEmbedFactsOptions(wireOptions), signal: migrationDrain?.signal ?? externalSignal,+ assertOwned: migrationDrain?.assertOwned ?? assertOwned };const batchSize = opts.batchSize ?? 100;- const budgetMs = opts.budgetMs ?? 60_000;+ const budgetMs = migrationDrain ? undefined : opts.budgetMs ?? 60_000;const dryRun = opts.dryRun === true || opts.yes !== true;const verified = currentVerifiedLocalWriter();if (verified && (verified.remote || verified.principal.kind !== 'local_cli' || verified.grant.slugPrefixes !== null@@ -85,6 +87,7 @@ export async function embedStaleFacts(engine: BrainEngine, opts: EmbedFactsOpts,return { count: Number(row.count), lastId: row.last_id };};const initial = await census();+ const maxFacts = migrationDrain ? initial.count : opts.maxFacts ?? 100;const result: EmbedFactsResult = {source_id: opts.sourceId, dryRun, total_stale: initial.count,would_embed: dryRun ? Math.min(initial.count, maxFacts) : 0,@@ -116,10 +119,14 @@ export async function embedStaleFacts(engine: BrainEngine, opts: EmbedFactsOpts,label: 'embed.facts', maxCostUsd: opts.maxCostUsd, maxRuntimeMs: budgetMs,pricingOverrides: await loadPricingOverrides(engine),});- const signal = AbortSignal.any([AbortSignal.timeout(budgetMs), ...(opts.signal ? [opts.signal] : [])]);+ const budgetTimer = budgetMs === undefined ? null : AbortSignal.timeout(budgetMs);+ const signal = AbortSignal.any([...(budgetTimer ? [budgetTimer] : []), ...(opts.signal ? [opts.signal] : [])]);+ const budgetStop = (error?: unknown) => opts.signal?.aborted !== true+ && (budgetTimer?.aborted === true || error instanceof BudgetExhausted && error.reason === 'runtime');const maxTokens = resolveMaxChunkTokens();let afterId = '0';while (result.attempted < maxFacts) {+ if (budgetStop()) { result.stopped = 'time_budget'; break; }if (signal.aborted) { result.stopped = 'aborted'; result.failures++; break; }const batch = await engine.executeRaw<PendingFact>(`SELECT f.id::text, f.fact, f.xmin::text AS version FROM facts f@@ -190,6 +197,7 @@ export async function embedStaleFacts(engine: BrainEngine, opts: EmbedFactsOpts,}afterId = batch[batch.length - 1].id;} catch (error) {+ if (budgetStop(error)) { result.stopped = 'time_budget'; break; }result.failures += batch.length;result.failure_samples.push(redactUrlsInText(redactConnectionInfo(redactFindings(error instanceof Error ? error.message : String(error), { highEntropy: true }).text,diff --git a/test/migrate-embeddings-facts-drain.serial.test.ts b/test/migrate-embeddings-facts-drain.serial.test.tsnew file mode 100644index 0000000000..5f87d24406--- /dev/null+++ b/test/migrate-embeddings-facts-drain.serial.test.ts@@ -0,0 +1,185 @@+import { afterAll, afterEach, beforeAll, beforeEach, expect, spyOn, test } from 'bun:test';+import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';+import { tmpdir } from 'node:os';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { resetPgliteState } from './helpers/reset-pglite.ts';+import { withEnv } from './helpers/with-env.ts';+import { configureGateway, resetGateway, __setEmbedTransportForTests } from '../src/core/ai/gateway.ts';+import { runSchemaTransition, MIGRATION_STATE_KEY, MIGRATION_COMPLETED_KEY } from '../src/core/embedding-migration.ts';+import { executeMigrationFlow, planMigrationFlow, GLOBAL_MIGRATION_LOCK_ID } from '../src/commands/migrate-embeddings.ts';+import { embedStaleFacts } from '../src/core/embed-facts.ts';++const model = 'openai:text-embedding-3-small';+const dimensions = 8;+let engine: PGLiteEngine;+let home: string;+let calls: string[][];++function transport(before?: (values: string[]) => Promise<void>) {+ __setEmbedTransportForTests(async ({ values }) => {+ calls.push([...values]);+ await before?.(values);+ return { values, embeddings: values.map(() => Array(dimensions).fill(0.2)), usage: { tokens: values.length * 8 }, warnings: [] };+ });+}++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ await runSchemaTransition(engine, dimensions);+ home = mkdtempSync(join(tmpdir(), 'migration-facts-drain-'));+ mkdirSync(join(home, '.gbrain'));+ writeFileSync(join(home, '.gbrain', 'config.json'), JSON.stringify({ engine: 'pglite', embedding_model: model,+ embedding_dimensions: dimensions, openai_api_key: 'synthetic-only' }));+}, 60_000);++beforeEach(async () => {+ await resetPgliteState(engine);+ await engine.setConfig('embedding_model', model);+ await engine.setConfig('embedding_dimensions', String(dimensions));+ resetGateway();+ configureGateway({ embedding_model: model, embedding_dimensions: dimensions, env: { OPENAI_API_KEY: 'synthetic-only' } });+ calls = [];+ transport();+});++afterEach(() => { __setEmbedTransportForTests(null); resetGateway(); });+afterAll(async () => { await engine.disconnect(); rmSync(home, { recursive: true, force: true }); });++async function flow() {+ return withEnv({ GBRAIN_HOME: home, GBRAIN_EMBEDDING_MODEL: undefined, GBRAIN_EMBEDDING_DIMENSIONS: undefined }, async () => {+ const options = { to: model, dim: dimensions, reranker: 'off', maxCostUsd: 1, quiet: true };+ return executeMigrationFlow(engine, await planMigrationFlow(engine, options), options);+ });+}++async function seed(sourceId: string, count: number) {+ await engine.executeRaw('INSERT INTO sources(id,name) VALUES($1,$1) ON CONFLICT DO NOTHING', [sourceId]);+ await engine.executeRaw(`INSERT INTO facts(fact,source,source_id)+ SELECT $1 || ' claim ' || n, 'synthetic', $1 FROM generate_series(1,$2::int) n`, [sourceId, count]);+}++async function pending(sourceId: string) {+ const [row] = await engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM facts WHERE source_id=$1 AND embedding IS NULL', [sourceId]);+ return Number(row.n);+}++test('migration fact drain does not inherit the standalone timer and reaches the next source', async () => {+ await seed('a-slow', 2);+ await seed('z-neighbor', 1);+ transport(async values => { if (values.some(v => v.startsWith('a-slow'))) await Bun.sleep(10); });+ // Compress only the standalone 60s timer; migration heartbeat deadlines remain real.+ const original = AbortSignal.timeout.bind(AbortSignal);+ const timeout = spyOn(AbortSignal, 'timeout').mockImplementation(ms => original(ms === 60_000 ? 1 : ms));+ try {+ const result = await flow();+ expect(result.status).toBe('completed');+ expect(result).toMatchObject({ facts_embedded: 3, facts_remaining: 0 });+ expect(await pending('a-slow')).toBe(0);+ expect(await pending('z-neighbor')).toBe(0);+ expect(calls.flat().filter(v => v.includes(' claim '))).toHaveLength(3);+ expect(await engine.getConfig(MIGRATION_STATE_KEY)).toBeFalsy();+ expect(await engine.getConfig(MIGRATION_COMPLETED_KEY)).toBeTruthy();+ } finally { timeout.mockRestore(); }+});++test('migration fact drain covers more than 10000 facts without replay and completes later sources', async () => {+ await seed('a-large', 10_001);+ await seed('z-neighbor', 1);+ const result = await flow();+ expect(result.status).toBe('completed');+ expect(result).toMatchObject({ facts_embedded: 10_002, facts_remaining: 0 });+ const texts = calls.flat().filter(v => v.includes(' claim '));+ expect(texts).toHaveLength(10_002);+ expect(new Set(texts).size).toBe(10_002);+ expect(await pending('a-large')).toBe(0);+ expect(await pending('z-neighbor')).toBe(0);+ const receipt = JSON.parse((await engine.getConfig(MIGRATION_COMPLETED_KEY))!);+ expect(receipt.budget.requests).toBeGreaterThan(100);+}, 120_000);++test('standalone fact repair retains its explicit row and runtime bounds', async () => {+ await seed('default', 3);+ const bounded = await embedStaleFacts(engine, { sourceId: 'default', yes: true, maxCostUsd: 1, maxFacts: 1 });+ expect(bounded).toMatchObject({ embedded: 1, remaining: 2, stopped: 'limit' });+ transport(async () => { await Bun.sleep(10); });+ const timed = await embedStaleFacts(engine, { sourceId: 'default', yes: true, maxCostUsd: 1, budgetMs: 1 });+ expect(timed).toMatchObject({ embedded: 0, remaining: 2, failures: 0, stopped: 'time_budget' });+ expect(await pending('default')).toBe(2);+});++test('#6588 a standalone wall-clock stop is a time_budget stop, not a failure', async () => {+ await seed('default', 6);+ transport(async () => { await Bun.sleep(150); });+ const r = await embedStaleFacts(engine, { sourceId: 'default', yes: true, maxCostUsd: 1, batchSize: 1, budgetMs: 400 });+ expect(r.embedded).toBeGreaterThan(0);+ expect(r.remaining).toBe(6 - r.embedded);+ expect(r).toMatchObject({ failures: 0, failure_samples: [], stopped: 'time_budget' });+});++test('#6588 an external abort stays a failure', async () => {+ await seed('default', 2);+ const controller = new AbortController();+ transport(async () => { controller.abort(); });+ const r = await embedStaleFacts(engine, { sourceId: 'default', yes: true, maxCostUsd: 1, batchSize: 1, signal: controller.signal });+ expect(r.stopped).toBe('aborted');+ expect(r.failures).toBeGreaterThan(0);+ expect(await pending('default')).toBe(2);+});++test('provider failure retains committed batches and migration authorization for resume', async () => {+ await seed('a-partial', 101);+ await seed('z-neighbor', 1);+ transport(async values => { if (values.includes('a-partial claim 101')) throw new Error('synthetic provider failure'); });+ const first = await flow();+ expect(first.status).toBe('incomplete');+ expect(first).toMatchObject({ facts_embedded: 100, facts_remaining: 2 });+ expect(await pending('a-partial')).toBe(1);+ expect(await pending('z-neighbor')).toBe(1);+ const prior = JSON.parse((await engine.getConfig(MIGRATION_STATE_KEY))!).budget;+ expect(prior.requests).toBeGreaterThan(0);+ calls = [];+ transport();+ const resumed = await flow();+ expect(resumed.status).toBe('completed');+ expect(resumed).toMatchObject({ facts_embedded: 2, facts_remaining: 0 });+ expect(calls.flat().filter(v => v.includes(' claim '))).toEqual(['a-partial claim 101', 'z-neighbor claim 1']);+ const receipt = JSON.parse((await engine.getConfig(MIGRATION_COMPLETED_KEY))!);+ expect(receipt.budget.requests).toBeGreaterThan(prior.requests);+ expect(receipt.budget.debited_usd).toBeGreaterThanOrEqual(prior.debited_usd);+});++test('lease loss during a later fact batch refuses its vectors and preserves earlier progress', async () => {+ await seed('a-partial', 101);+ await seed('z-neighbor', 1);+ transport(async values => {+ if (values.includes('a-partial claim 101')) {+ await engine.executeRaw('DELETE FROM gbrain_cycle_locks WHERE id=$1', [GLOBAL_MIGRATION_LOCK_ID]);+ }+ });+ const result = await flow();+ expect(result.status).toBe('apply_failed');+ expect(JSON.stringify(result)).toContain('lease lost');+ expect(await pending('a-partial')).toBe(1);+ expect(await pending('z-neighbor')).toBe(1);+ expect(await engine.getConfig(MIGRATION_STATE_KEY)).toBeTruthy();+ expect(await engine.getConfig(MIGRATION_COMPLETED_KEY)).toBeFalsy();+});++test('new fact arrivals do not extend the initial drain census or falsely complete migration', async () => {+ await seed('default', 1);+ let inserted = false;+ transport(async values => {+ if (!inserted && values.includes('default claim 1')) {+ inserted = true;+ await engine.insertFact({ fact: 'Synthetic late arrival', source: 'synthetic' }, { source_id: 'default' });+ }+ });+ const result = await flow();+ expect(result).toMatchObject({ status: 'incomplete', facts_embedded: 1, facts_remaining: 1 });+ expect(calls.flat()).not.toContain('Synthetic late arrival');+ expect(await engine.getConfig(MIGRATION_STATE_KEY)).toBeTruthy();+ expect(await engine.getConfig(MIGRATION_COMPLETED_KEY)).toBeFalsy();+});