Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(migrate): long migration transactions stop blocking their own heartbeat (#6587)

time-attackcb6a60abd59d
diff --git a/src/commands/migrate-embeddings.ts b/src/commands/migrate-embeddings.ts
index c2fd10168a..aac21dc360 100644
--- a/src/commands/migrate-embeddings.ts
+++ b/src/commands/migrate-embeddings.ts
@@ -40,7 +40,7 @@ import { prepareEmbeddingProjections } from '../core/embedding-readiness.ts';
import { assertRetainedEmbeddingRebuildability } from '../core/embedding-migration-retention.ts';
import { embedStaleFacts } from '../core/embed-facts.ts';
import { countStaleFactEmbeddings } from '../core/facts/embedding-identity.ts';
-import { authorizeMigrationBudget, assertMigrationLeases, ceilCents, MigrationBudgetRefusal, type MigrationBudgetRefusalDetails, type MigrationWorstCase } from '../core/embedding-migration-budget.ts';
+import { authorizeMigrationBudget, assertMigrationLeases, ceilCents, MigrationBudgetRefusal, withMigrationLeaseTransaction, type MigrationBudgetRefusalDetails, type MigrationLeaseAssert, type MigrationWorstCase } from '../core/embedding-migration-budget.ts';
import { planMigrationWorstCase, MIGRATION_PROBE_TEXT, RERANKER_PROBE } from '../core/embedding-migration-worst-case.ts';
import { withAIInvocationGuard } from '../core/ai/invocation-guard.ts';
@@ -293,6 +293,14 @@ export async function probeTargetProvider(
}
return { ok: true };
} catch (e) {
+ // #6587: the invocation guard refuses dispatch once the migration lost its lease; that is not a provider
+ // fault, so say so (provider error text stays private).
+ if (e instanceof Error && /lease lost/i.test(e.message)) {
+ return {
+ ok: false,
+ message: `Preflight embed against ${toModel} stopped because the migration lost its lock lease (another process took it, or the heartbeat could not renew it); no migration invalidation performed. Any authorized request debit is retained for safe resume. Inspect migration status before retrying.`,
+ };
+ }
return {
ok: false,
message: `Preflight embed against ${toModel} failed; no migration invalidation performed. Any authorized request debit is retained for safe resume. Check provider configuration and migration status before retrying.`,
@@ -602,10 +610,10 @@ export async function executeMigrationFlow(
let expectedSources: string | undefined;
let lost = false;
let renewing: Promise<void> | undefined;
- const assertOwned = async (tx?: BrainEngine) => {
+ const assertOwned: MigrationLeaseAssert = async (tx, lease) => {
if (!tx && renewing) await renewing;
if (lost) throw new Error('Migration lock lease lost; durable work retained. Inspect --status before resuming.');
- if (tx) await assertMigrationLeases(tx, heldLocks);
+ if (tx) await assertMigrationLeases(tx, heldLocks, lease);
else for (const lock of heldLocks) {
if (!await lock.refresh({ signal: AbortSignal.timeout(30_000) })) { lost = true; controller.abort(); throw new Error('Migration lock lease lost; further mutations refused.'); }
}
@@ -671,7 +679,8 @@ export async function executeMigrationFlow(
if (runtimeConfig?.embedding_disabled || disabled !== null && disabled !== 'false') {
return { status: 'apply_failed', reason: 'Embedding is disabled or its policy is invalid; no provider requests or migration invalidation performed. Review the selected brain embedding configuration before retrying.' };
}
- await engine.transaction(async tx => { await assertOwned(tx); await assertRetainedEmbeddingRebuildability(tx, plan.to_dims, plan.to_model, plan); });
+ await withMigrationLeaseTransaction(engine, assertOwned,
+ tx => assertRetainedEmbeddingRebuildability(tx, plan.to_dims, plan.to_model, plan), { deadlockRetries: 3 });
const rerankerModel = ctx.rerankerPlan.action.kind === 'switch' ? ctx.rerankerPlan.action.to : undefined;
let debit: Awaited<ReturnType<typeof authorizeMigrationBudget>>;
try {
diff --git a/src/core/embedding-migration-budget.ts b/src/core/embedding-migration-budget.ts
index 7a4a4bfd66..a794e5f234 100644
--- a/src/core/embedding-migration-budget.ts
+++ b/src/core/embedding-migration-budget.ts
@@ -45,15 +45,51 @@ export class MigrationBudgetRefusal extends Error {
}
}
-export async function assertMigrationLeases(engine: BrainEngine, locks: DbLockHandle[]) {
+/** Lease options for `assertMigrationLeases`: `rowLock: false` checks ownership without holding the lease rows (#6587). */
+export interface MigrationLeaseCheck { rowLock?: boolean }
+export type MigrationLeaseAssert = (tx?: BrainEngine, lease?: MigrationLeaseCheck) => Promise<void>;
+
+/**
+ * The migration still owns every lease. By default the lease rows stay `FOR SHARE` until the transaction
+ * ends, so a steal (an ON CONFLICT update after expiry) waits for the commit; that lock also blocks the
+ * migration's own heartbeat refresh, so it belongs only at the end of a transaction (#6587,
+ * `withMigrationLeaseTransaction`). `rowLock: false` checks without holding them.
+ */
+export async function assertMigrationLeases(engine: BrainEngine, locks: DbLockHandle[], lease: MigrationLeaseCheck = {}) {
if (!locks.length) return;
const owned = await engine.executeRaw<{ id: string; token: string }>(`SELECT id,acquisition_token::text AS token
- FROM gbrain_cycle_locks WHERE id=ANY($1::text[]) AND ttl_expires_at>now() ORDER BY id FOR SHARE`, [locks.map(lock => lock.id)]);
+ FROM gbrain_cycle_locks WHERE id=ANY($1::text[]) AND ttl_expires_at>now() ORDER BY id${lease.rowLock === false ? '' : ' FOR SHARE'}`, [locks.map(lock => lock.id)]);
if (owned.length !== locks.length || locks.some(lock => !owned.some(row => row.id === lock.id && row.token === lock.acquisitionToken))) {
throw new Error('Migration lease lost; authorization debit and provider dispatch refused');
}
}
+const isDeadlock = (error: unknown) => typeof error === 'object' && error !== null && (error as { code?: unknown }).code === '40P01';
+
+/**
+ * #6587: one migration transaction whose work (the retained-vector census, an invalidation) can run for
+ * minutes. The lease is checked without a row lock first, so the 15 s heartbeat can refresh it meanwhile,
+ * and checked again with `FOR SHARE` right before commit, so a lease lost or stolen during the work rolls
+ * the transaction back and a steal cannot land before the commit. `deadlockRetries` reruns a work function
+ * with no side effects outside the transaction when Postgres picks it as a deadlock victim (40P01) against
+ * concurrent writers; mutating work passes 0.
+ */
+export async function withMigrationLeaseTransaction<T>(engine: BrainEngine, assertOwned: MigrationLeaseAssert | undefined,
+ work: (tx: BrainEngine) => Promise<T>, opts: { deadlockRetries?: number } = {}): Promise<T> {
+ for (let attempt = 0; ; attempt++) {
+ try {
+ return await engine.transaction(async tx => {
+ await assertOwned?.(tx, { rowLock: false });
+ const result = await work(tx);
+ await assertOwned?.(tx);
+ return result;
+ });
+ } catch (error) {
+ if (attempt >= (opts.deadlockRetries ?? 0) || !isDeadlock(error)) throw error;
+ }
+ }
+}
+
type MigrationBudget = NonNullable<MigrationState['budget']>;
function budgetIsValid(budget: MigrationBudget): boolean {
diff --git a/src/core/embedding-migration-retention.ts b/src/core/embedding-migration-retention.ts
index 70ebfea28d..235b489a3e 100644
--- a/src/core/embedding-migration-retention.ts
+++ b/src/core/embedding-migration-retention.ts
@@ -82,8 +82,12 @@ export async function assertRetainedEmbeddingRebuildability(tx: BrainEngine, dim
counts = row;
if (model !== undefined) archivedWork = await countArchivedEmbeddingWork(tx,
{ signature: `${model}:${dimensions}`, includeNullSignature: true, includeUnsealed: true }, activeExists ? active : null);
- } catch {
- throw new Error('retained_vector_check_failed: Cannot determine whether retained vectors can be rebuilt; migration mutations refused. Inspect the selected brain and database/schema access before retrying.');
+ } catch (error) {
+ // #6587: a deadlock is retryable by the caller (withMigrationLeaseTransaction); keep it recognizable.
+ if (typeof error === 'object' && error !== null && (error as { code?: unknown }).code === '40P01') throw error;
+ // The message stays content-free (a data error can quote stored text); the SQLSTATE names the class.
+ const code = typeof error === 'object' && error !== null && typeof (error as { code?: unknown }).code === 'string' ? (error as { code: string }).code : null;
+ throw new Error(`retained_vector_check_failed: Cannot determine whether retained vectors can be rebuilt; migration mutations refused.${code ? ` Database error SQLSTATE ${code}.` : ''} Inspect the selected brain and database/schema access before retrying.`, { cause: error });
}
if (counts.pages + counts.facts + counts.takes + archivedWork > 0) {
throw new Error(`retained_vectors_blocked: ${counts.pages} page chunk(s), ${counts.facts} fact(s), ${counts.takes} take(s) cannot be rebuilt by this migration; ${archivedWork} archived page(s) have blocked embedding work. No invalidation is permitted. Inspect the blockers: archived sources require deliberate gbrain sources restore <id>; embed_skip, importer-only media, and deleted pages require an explicit retention/recovery decision. No source or page is restored automatically. See docs/guides/embedding-migration.md#recovery.`);
diff --git a/src/core/embedding-migration.ts b/src/core/embedding-migration.ts
index 8a993322b0..3f8d85b4f2 100644
--- a/src/core/embedding-migration.ts
+++ b/src/core/embedding-migration.ts
@@ -21,6 +21,7 @@ import { AUDIT_ROW_SOURCES } from './facts/audit-sources.ts';
import { countStaleFactEmbeddings } from './facts/embedding-identity.ts';
import { prepareEmbeddingProjections } from './embedding-readiness.ts';
import { assertRetainedEmbeddingRebuildability } from './embedding-migration-retention.ts';
+import { withMigrationLeaseTransaction, type MigrationLeaseAssert } from './embedding-migration-budget.ts';
import { annIndexValidity, canonicalChunkAnnIndex, mergeDeferredAnnIndexes, parseDeferredAnnIndexes, type DeferredAnnIndex } from './embedding-ann-build.ts';
import { SMOKE_QUERY_CHUNK_UNITS, SMOKE_QUERY_TITLE_UNITS } from './embedding-migration-worst-case.ts';
@@ -1197,7 +1198,7 @@ export async function applyEmbeddingMigration(
ignoreEnvOverride?: boolean;
/** Persist target model+dims to the file plane + reconfigure the gateway. */
persistConfig?: (toModel: string, toDims: number, tx: BrainEngine) => void | Promise<void>;
- assertOwned?: (tx?: BrainEngine) => Promise<void>;
+ assertOwned?: MigrationLeaseAssert;
} = {},
): Promise<MigrationApplyResult> {
const envWarning = detectEnvOverride(plan.to_model, plan.to_dims);
@@ -1207,7 +1208,8 @@ export async function applyEmbeddingMigration(
try {
await opts.assertOwned?.();
- await engine.transaction(async tx => { await opts.assertOwned?.(tx); await assertRetainedEmbeddingRebuildability(tx, plan.to_dims, plan.to_model, plan); });
+ await withMigrationLeaseTransaction(engine, opts.assertOwned,
+ tx => assertRetainedEmbeddingRebuildability(tx, plan.to_dims, plan.to_model, plan), { deadlockRetries: 3 });
const readiness = await prepareEmbeddingProjections(engine, { repair: true, assertOwned: opts.assertOwned });
if (readiness.blocked) return { status: 'failed', reason: `projection_blocked: ${readiness.blocked} page(s) remain; no embedding invalidation performed. Canonical projection recovery may have made durable progress. Inspect blockers before retrying: archived sources require deliberate gbrain sources restore <id>; unsupported media requires its source importer. See docs/guides/embedding-migration.md#recovery.` };
await opts.assertOwned?.();
@@ -1251,8 +1253,7 @@ export async function applyEmbeddingMigration(
{ to_model: prior.state.to_model, to_dims: prior.state.to_dims, started_at: prior.state.started_at },
];
}
- await engine.transaction(async tx => {
- await opts.assertOwned?.(tx);
+ await withMigrationLeaseTransaction(engine, opts.assertOwned, async tx => {
await assertRetainedEmbeddingRebuildability(tx, plan.to_dims, plan.to_model, plan);
await tx.setConfig(MIGRATION_STATE_KEY, JSON.stringify(state));
});
@@ -1272,8 +1273,7 @@ export async function applyEmbeddingMigration(
const pinned = await readDimPinnedWidths(engine);
const stalePinned = pinned.filter((p) => schemaRebuildNeeded(p.dims, plan.to_dims));
if (stalePinned.length > 0) {
- await engine.transaction(async (tx) => {
- await opts.assertOwned?.(tx);
+ await withMigrationLeaseTransaction(engine, opts.assertOwned, async (tx) => {
await assertRetainedEmbeddingRebuildability(tx, plan.to_dims, plan.to_model, plan);
const stalePinned = (await readDimPinnedWidths(tx)).filter(p => schemaRebuildNeeded(p.dims, plan.to_dims));
const ann: DeferredAnnIndex[] = [];
@@ -1299,8 +1299,7 @@ export async function applyEmbeddingMigration(
// vectors are invisible to every stale selector, so NULLing them
// would be permanent loss.
//
- const invalidated = await engine.transaction(async tx => {
- await opts.assertOwned?.(tx);
+ const invalidated = await withMigrationLeaseTransaction(engine, opts.assertOwned, async tx => {
await assertRetainedEmbeddingRebuildability(tx, plan.to_dims, plan.to_model, plan);
await clearFalseStampedSignatures(tx, plan.to_model, plan.to_dims);
return invalidateStaleSignatureEmbeddingsGuarded(tx, {
@@ -1310,8 +1309,7 @@ export async function applyEmbeddingMigration(
});
let cacheCleared = 0;
- await engine.transaction(async (tx) => {
- await opts.assertOwned?.(tx);
+ await withMigrationLeaseTransaction(engine, opts.assertOwned, async (tx) => {
const clearCompanions = await assertRetainedEmbeddingRebuildability(tx, plan.to_dims, plan.to_model, plan);
const stores = await readPrimaryEmbeddingStores(tx);
if (clearCompanions) {
diff --git a/test/e2e/migrate-embeddings-lease-heartbeat.test.ts b/test/e2e/migrate-embeddings-lease-heartbeat.test.ts
new file mode 100644
index 0000000000..ddcfb76b8f
--- /dev/null
+++ b/test/e2e/migrate-embeddings-lease-heartbeat.test.ts
@@ -0,0 +1,82 @@
+/**
+ * #6587: the embedding migration's long transactions (the retained-vector
+ * census, ~88 s on a large remote brain) held the lease rows FOR SHARE from
+ * the start, so the 15 s heartbeat's refresh UPDATE blocked, was cancelled at
+ * its timeout and the migration aborted as lease-lost. Real Postgres: the row
+ * lock semantics are the bug. Timings are scaled (census = pg_sleep(4),
+ * refresh timeout 1.5 s instead of 30 s).
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { hasDatabase, setupDB, teardownDB, getEngine } from './helpers.ts';
+import { tryAcquireDbLock, type DbLockHandle } from '../../src/core/db-lock.ts';
+import { assertMigrationLeases, withMigrationLeaseTransaction, type MigrationLeaseAssert } from '../../src/core/embedding-migration-budget.ts';
+
+const skip = !hasDatabase();
+beforeAll(async () => { if (!skip) await setupDB(); }, 120_000);
+afterAll(async () => { if (!skip) await teardownDB(); });
+
+const owned = (lock: DbLockHandle): MigrationLeaseAssert => async (tx, lease) => {
+ if (tx) await assertMigrationLeases(tx, [lock], lease);
+};
+async function refreshDuring(census: Promise<unknown>, lock: DbLockHandle): Promise<unknown> {
+ await new Promise(r => setTimeout(r, 300));
+ let refreshed: unknown;
+ try { refreshed = await lock.refresh({ signal: AbortSignal.timeout(1500) }); } catch (e) { refreshed = `threw: ${(e as Error).message}`; }
+ await census.catch(() => {});
+ return refreshed;
+}
+
+describe.skipIf(skip)('migration lease transactions (#6587)', () => {
+ test('the heartbeat refreshes the lease while a long census transaction runs', async () => {
+ const engine = getEngine();
+ const lock = (await tryAcquireDbLock(engine, 'w17-6587-census', 60))!;
+ try {
+ const census = withMigrationLeaseTransaction(engine, owned(lock), tx => tx.executeRaw('SELECT pg_sleep(4)'));
+ expect(await refreshDuring(census, lock)).toBe(true);
+ await census;
+ } finally { await lock.release(); }
+ }, 30_000);
+
+ test('forced probe: holding the lease rows FOR SHARE across the census (the old shape) blocks the heartbeat', async () => {
+ const engine = getEngine();
+ const lock = (await tryAcquireDbLock(engine, 'w17-6587-old-shape', 60))!;
+ try {
+ const census = engine.transaction(async tx => {
+ await assertMigrationLeases(tx, [lock]);
+ await tx.executeRaw('SELECT pg_sleep(4)');
+ });
+ expect(String(await refreshDuring(census, lock))).toContain('threw');
+ } finally { await lock.release(); }
+ }, 30_000);
+
+ test('a lease stolen during the work rolls the transaction back', async () => {
+ const engine = getEngine();
+ const lock = (await tryAcquireDbLock(engine, 'w17-6587-stolen', 60))!;
+ try {
+ await expect(withMigrationLeaseTransaction(engine, owned(lock), async tx => {
+ await tx.executeRaw(`INSERT INTO config(key,value) VALUES('w17.6587.marker','written') ON CONFLICT (key) DO UPDATE SET value=EXCLUDED.value`);
+ await engine.executeRaw(`UPDATE gbrain_cycle_locks SET acquisition_token=gen_random_uuid() WHERE id=$1`, [lock.id]);
+ })).rejects.toThrow('Migration lease lost');
+ expect(await engine.executeRaw(`SELECT value FROM config WHERE key='w17.6587.marker'`)).toEqual([]);
+ } finally {
+ await engine.executeRaw(`DELETE FROM gbrain_cycle_locks WHERE id=$1`, [lock.id]);
+ }
+ }, 30_000);
+
+ test('a deadlock victim reruns side-effect-free work; mutating work is not retried', async () => {
+ const engine = getEngine();
+ const lock = (await tryAcquireDbLock(engine, 'w17-6587-deadlock', 60))!;
+ try {
+ const deadlock = () => Object.assign(new Error('deadlock detected'), { code: '40P01' });
+ let attempts = 0;
+ const result = await withMigrationLeaseTransaction(engine, owned(lock), async () => {
+ if (++attempts === 1) throw deadlock();
+ return 'census-ok';
+ }, { deadlockRetries: 3 });
+ expect({ result, attempts }).toEqual({ result: 'census-ok', attempts: 2 });
+ let mutating = 0;
+ await expect(withMigrationLeaseTransaction(engine, owned(lock), async () => { mutating++; throw deadlock(); })).rejects.toThrow('deadlock detected');
+ expect(mutating).toBe(1);
+ } finally { await lock.release(); }
+ }, 30_000);
+});
diff --git a/test/migrate-embeddings-lease-messages.test.ts b/test/migrate-embeddings-lease-messages.test.ts
new file mode 100644
index 0000000000..37208b8651
--- /dev/null
+++ b/test/migrate-embeddings-lease-messages.test.ts
@@ -0,0 +1,51 @@
+/**
+ * #6587: lease loss and census failures say what happened. A preflight probe
+ * the invocation guard refused because the lease was lost names the lease
+ * (status stays probe_failed); a census database error names its SQLSTATE but
+ * never the error text (a data error can quote stored content); a deadlock
+ * victim stays recognizable so withMigrationLeaseTransaction can rerun it.
+ */
+import { afterAll, beforeAll, afterEach, expect, test } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { probeTargetProvider } from '../src/commands/migrate-embeddings.ts';
+import { assertRetainedEmbeddingRebuildability } from '../src/core/embedding-migration-retention.ts';
+import { configureGateway, resetGateway, __setEmbedTransportForTests } from '../src/core/ai/gateway.ts';
+
+let engine: PGLiteEngine;
+beforeAll(async () => {
+ engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema();
+ configureGateway({ embedding_model: 'openai:text-embedding-3-small', embedding_dimensions: 1536, env: { OPENAI_API_KEY: 'synthetic-only' } });
+}, 120_000);
+afterAll(async () => { resetGateway(); await engine.disconnect(); });
+afterEach(() => { __setEmbedTransportForTests(null); });
+
+test('a probe refused for a lost lease names the lease, not the provider', async () => {
+ __setEmbedTransportForTests(async () => { throw new Error('Migration lock lease lost; further mutations refused.'); });
+ const lost = await probeTargetProvider('openai:text-embedding-3-small', 1536);
+ expect(lost.ok).toBe(false);
+ expect(!lost.ok && lost.message).toContain('lost its lock lease');
+ __setEmbedTransportForTests(async () => { throw new Error('SYNTHETIC_PRIVATE_PROVIDER_BODY'); });
+ const outage = await probeTargetProvider('openai:text-embedding-3-small', 1536);
+ expect(!outage.ok && outage.message).toContain('Check provider configuration');
+ expect(!outage.ok && outage.message).not.toContain('SYNTHETIC_PRIVATE_PROVIDER_BODY');
+});
+
+const failingCensus = (base: BrainEngine, error: Error) => new Proxy(base, { get(target, key) {
+ if (key === 'executeRaw') return async (sql: string, params?: unknown[]) => {
+ if (sql.includes('AS pages')) throw error;
+ return target.executeRaw(sql, params as never);
+ };
+ const value = Reflect.get(target, key); return typeof value === 'function' ? value.bind(target) : value;
+} }) as unknown as BrainEngine;
+
+test('a census database error names its SQLSTATE and keeps stored text out; a deadlock is rethrown as-is', async () => {
+ const data = Object.assign(new Error('invalid input syntax for type integer: "SYNTHETIC_STORED_TEXT"'), { code: '22P02' });
+ const error = await engine.transaction(tx => assertRetainedEmbeddingRebuildability(failingCensus(tx, data), 1536, 'openai:text-embedding-3-small').then(() => null)).catch((e: unknown) => e as Error);
+ if (!error) throw new Error('the census error did not propagate');
+ expect(error.message).toContain('retained_vector_check_failed');
+ expect(error.message).toContain('SQLSTATE 22P02');
+ expect(error.message).not.toContain('SYNTHETIC_STORED_TEXT');
+ const deadlock = Object.assign(new Error('deadlock detected'), { code: '40P01' });
+ await expect(engine.transaction(tx => assertRetainedEmbeddingRebuildability(failingCensus(tx, deadlock), 1536, 'openai:text-embedding-3-small'))).rejects.toBe(deadlock);
+});