Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(migrations): --export-db-only ignores the runner's own orchestration lease (#5842)

garrytan59381622044b
diff --git a/scripts/e2e-test-map.ts b/scripts/e2e-test-map.ts
index db040f7166..1e2850d846 100644
--- a/scripts/e2e-test-map.ts
+++ b/scripts/e2e-test-map.ts
@@ -26,7 +26,7 @@ const MIGRATION_WAVE_TESTS = [
export const E2E_TEST_MAP: Record<string, string[]> = {
// Fix wave 4, Lane D: the apply-migrations orchestration lease (#5693), source deletes and
// orphan bindings (#5732), and deactivate racing admission (#5455).
- "src/core/migration-orchestration-lock.ts": ["test/e2e/apply-migrations-orchestration-lock.test.ts"],
+ "src/core/migration-orchestration-lock.ts": ["test/e2e/apply-migrations-orchestration-lock.test.ts", "test/e2e/export-db-only-own-lease-postgres.test.ts"],
"src/core/source-delete.ts": ["test/e2e/sources-remove-bindings.test.ts"],
"src/core/persistence/orphan-bindings.ts": ["test/e2e/sources-remove-bindings.test.ts"],
// Fix wave 5 shared commit: preview-bound approved sets in op_checkpoints.
@@ -79,7 +79,7 @@ export const E2E_TEST_MAP: Record<string, string[]> = {
"src/core/company-brain/receipt-schema.ts": ["test/e2e/company-brain-receipts.test.ts"],
"src/core/minions/errors.ts": ["test/e2e/subagent-gateway-path.test.ts", "test/e2e/delegated-http-worker.test.ts", "test/e2e/subagent-crash-replay-multi-provider.test.ts"],
"src/core/harness/**": ["test/e2e/harness-access.test.ts", "test/e2e/shared-skills-transports.test.ts"],
- "src/core/shared-skills/**": ["test/e2e/shared-skills-transports.test.ts", "test/e2e/shared-skills-rls.test.ts", "test/e2e/persistence-skill-bundles-postgres.test.ts", "test/e2e/knowledge-source-uri-postgres.test.ts"],
+ "src/core/shared-skills/**": ["test/e2e/export-db-only-own-lease-postgres.test.ts", "test/e2e/shared-skills-transports.test.ts", "test/e2e/shared-skills-rls.test.ts", "test/e2e/persistence-skill-bundles-postgres.test.ts", "test/e2e/knowledge-source-uri-postgres.test.ts"],
"src/mcp/skill-resources.ts": ["test/e2e/shared-skills-transports.test.ts"],
"src/core/scope.ts": ["test/e2e/client-grants.test.ts", "test/e2e/shared-skills-transports.test.ts"],
"src/core/grants/**": ["test/e2e/client-grants.test.ts", "test/e2e/harness-access.test.ts", "test/e2e/delegated-grants-withdrawal.test.ts", "test/e2e/delegated-http-worker.test.ts"],
@@ -486,6 +486,7 @@ export const E2E_TEST_MAP: Record<string, string[]> = {
],
"src/commands/apply-migrations.ts": [
"test/e2e/apply-migrations-orchestration-lock.test.ts",
+ "test/e2e/export-db-only-own-lease-postgres.test.ts",
"test/e2e/migration-preview-safety.test.ts",
"test/e2e/migrate-chain.test.ts",
"test/e2e/migration-flow.test.ts",
diff --git a/skills/migrations/v0.53.0.0.md b/skills/migrations/v0.53.0.0.md
index 9ec8f71737..29abd444f0 100644
--- a/skills/migrations/v0.53.0.0.md
+++ b/skills/migrations/v0.53.0.0.md
@@ -90,6 +90,11 @@ gbrain apply-migrations --migration 0.53.0 --export-db-only \
--confirm-quiesced --backup-confirmed --yes
```
+The export refuses with `writer_not_quiesced` while any maintenance lock row or
+queued, running or recovering durable write remains. The runner's own
+`apply-migrations` lease is not counted; on Postgres, inspect the others with
+`SELECT id, holder_host, holder_pid FROM gbrain_cycle_locks`.
+
`--acknowledge-no-backup` is the explicit alternative to `--backup-confirmed`,
not an equivalent safety claim. An agent must not choose it for the user.
The flag records operator testimony; it does not create or verify a backup.
diff --git a/src/commands/apply-migrations.ts b/src/commands/apply-migrations.ts
index 8d0a1e6251..017bbe3151 100644
--- a/src/commands/apply-migrations.ts
+++ b/src/commands/apply-migrations.ts
@@ -318,14 +318,14 @@ async function resolveSchemaBehind(opts: {
return true;
}
-function orchestratorOptsFrom(cli: ApplyMigrationsArgs): OrchestratorOpts {
+function orchestratorOptsFrom(cli: ApplyMigrationsArgs, ownLeaseToken?: string): OrchestratorOpts {
return {
yes: cli.yes || cli.nonInteractive,
mode: cli.mode,
dryRun: cli.dryRun,
hostDir: cli.hostDir,
noAutopilotInstall: cli.noAutopilotInstall,
- dbOnlyExport: cli.dbOnlyExport,
+ dbOnlyExport: cli.dbOnlyExport && { ...cli.dbOnlyExport, ownLeaseToken },
};
}
@@ -381,7 +381,7 @@ export async function runApplyMigrations(args: string[]): Promise<void> {
let exitCode: number | undefined;
try {
await holdLock();
- exitCode = await runLockedMigrations(cli, installed, holdLock, () => held.lock !== null);
+ exitCode = await runLockedMigrations(cli, installed, holdLock, () => held.lock);
} catch (error) {
if (!(error instanceof MigrationsRunningError)) throw error;
console.error(`apply-migrations refused: ${error.message}`);
@@ -401,12 +401,12 @@ async function runLockedMigrations(
cli: ReturnType<typeof parseArgs>,
installed: string,
holdLock: () => Promise<void>,
- hasLock: () => boolean,
+ heldLock: () => MigrationOrchestrationLock | null,
): Promise<number | undefined> {
// Without the orchestration lease (a schema too old for it), schema work goes
// through initSchema(), which serializes on the schema lock.
const migrateSchema = async (eng: BrainEngine, from: number): Promise<{ applied: number; current: number }> => {
- if (hasLock()) { const { runMigrations } = await import('../core/migrate.ts'); return runMigrations(eng); }
+ if (heldLock()) { const { runMigrations } = await import('../core/migrate.ts'); return runMigrations(eng); }
await eng.initSchema();
const current = parseInt(await eng.getConfig('version') || String(from), 10);
return { applied: Math.max(0, current - from), current };
@@ -611,7 +611,7 @@ async function runLockedMigrations(
const recordCheckpoint = !m.reconcile || !plan.applied.includes(m);
console.log(`\n=== Applying migration v${m.version}: ${m.featurePitch.headline} ===`);
try {
- const result = await m.orchestrator(orchestratorOptsFrom(cli));
+ const result = await m.orchestrator(orchestratorOptsFrom(cli, heldLock()?.leaseToken));
if (result.status === 'failed' || result.phases.some(p => p.status === 'failed')) {
console.error(result.status === 'failed'
? `Migration v${m.version} reported status=failed.`
diff --git a/src/commands/migrations/types.ts b/src/commands/migrations/types.ts
index 84fa6a6475..3e33bba21e 100644
--- a/src/commands/migrations/types.ts
+++ b/src/commands/migrations/types.ts
@@ -37,6 +37,8 @@ export interface OrchestratorOpts {
sourceId: string;
confirmQuiesced: boolean;
backup?: 'operator_verified' | 'acknowledged_unprotected';
+ /** The runner's own orchestration lease, which the quiescence check ignores. */
+ ownLeaseToken?: string;
};
}
diff --git a/src/core/migration-orchestration-lock.ts b/src/core/migration-orchestration-lock.ts
index 059ecb536e..5cdeac9588 100644
--- a/src/core/migration-orchestration-lock.ts
+++ b/src/core/migration-orchestration-lock.ts
@@ -50,6 +50,8 @@ export class MigrationsRunningError extends Error {
}
export interface MigrationOrchestrationLock {
+ /** Postgres lease acquisition token; quiescence checks exclude this runner's own row by it. */
+ leaseToken?: string;
/** Throws MigrationsRunningError when the lease was lost to another runner. */
assertHeld(): Promise<void>;
release(): Promise<void>;
@@ -125,6 +127,7 @@ async function acquirePostgres(config: GBrainConfig): Promise<MigrationOrchestra
}, LEASE_REFRESH_MS);
timer.unref?.();
return {
+ leaseToken: handle.acquisitionToken,
assertHeld: async () => {
if (await handle.refresh()) return;
const snapshot = await inspectLock(engine, MIGRATION_ORCHESTRATION_LOCK_ID).catch(() => null);
diff --git a/src/core/shared-skills/migration-export.ts b/src/core/shared-skills/migration-export.ts
index c817603bc3..1a68245ba8 100644
--- a/src/core/shared-skills/migration-export.ts
+++ b/src/core/shared-skills/migration-export.ts
@@ -28,6 +28,8 @@ export interface DatabaseContentExportOptions {
dryRun?: boolean;
confirmQuiesced?: boolean;
backup?: 'operator_verified' | 'acknowledged_unprotected';
+ /** Acquisition token of the calling runner's own `gbrain_cycle_locks` lease. */
+ ownLeaseToken?: string;
}
export interface DatabaseContentExportReceipt {
version: 1;
@@ -135,7 +137,9 @@ export async function exportDatabaseContent(ctx: OperationContext, options: Data
const [source] = await ctx.engine.executeRaw<{ incarnation: string; local_path: string | null }>('SELECT incarnation,local_path FROM sources WHERE id=$1 AND NOT archived', [options.sourceId]);
if (!brain || !source) throw new OperationError('source_changed', 'The selected brain/source is not active.');
await assertPackagedSkillSource(ctx.engine, options.sourceId);
- if (!options.dryRun && options.confirmQuiesced && ((await ctx.engine.executeRaw('SELECT id FROM gbrain_cycle_locks LIMIT 1')).length ||
+ if (!options.dryRun && options.confirmQuiesced && ((await ctx.engine.executeRaw(
+ 'SELECT id FROM gbrain_cycle_locks WHERE $1::uuid IS NULL OR acquisition_token IS DISTINCT FROM $1::uuid LIMIT 1',
+ [options.ownLeaseToken ?? null])).length ||
(await ctx.engine.executeRaw("SELECT id FROM persistence_requests WHERE state IN ('queued','running','recovering') OR recovery IS NOT NULL LIMIT 1")).length)) {
throw new OperationError('writer_not_quiesced', 'Active maintenance locks or durable writes remain; finish or recover them before exporting.');
}
diff --git a/test/e2e/export-db-only-own-lease-postgres.test.ts b/test/e2e/export-db-only-own-lease-postgres.test.ts
new file mode 100644
index 0000000000..5966174f84
--- /dev/null
+++ b/test/e2e/export-db-only-own-lease-postgres.test.ts
@@ -0,0 +1,82 @@
+/**
+ * #5842: on Postgres, `apply-migrations --export-db-only` holds its own
+ * orchestration lease (a `gbrain_cycle_locks` row) while the export's
+ * quiescence check refused on ANY lock row, so the export could never run.
+ *
+ * Protects: the runner's own lease (matched by id and acquisition token) does
+ * not count as activity; any other lock row still refuses with
+ * writer_not_quiesced. Regression that fails it: a quiescence query that
+ * counts every row, or one that ignores the token and so also excludes a
+ * foreign holder of the same lock id.
+ */
+import { afterEach, describe, expect, test } from 'bun:test';
+import { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join, resolve } from 'node:path';
+import postgres from '#postgres';
+import { assertSafeE2eDatabaseUrl } from '../helpers/db-guard.ts';
+import { getEngine, setupDB, teardownDB } from './helpers.ts';
+import { SHARED_CONTENT_MIGRATION_VERSION } from '../../src/commands/migrations/shared-content.ts';
+
+const databaseUrl = process.env.DATABASE_URL;
+const cli = resolve(import.meta.dir, '../../src/cli.ts');
+
+describe.skipIf(!databaseUrl)('#5842 export-db-only quiescence on Postgres', () => {
+ let home = '';
+ afterEach(async () => {
+ if (home) rmSync(home, { recursive: true, force: true });
+ await teardownDB();
+ });
+
+ async function run(args: string[]) {
+ const env: NodeJS.ProcessEnv = {
+ PATH: process.env.PATH!, HOME: home, GBRAIN_HOME: home,
+ DATABASE_URL: databaseUrl!, GBRAIN_DATABASE_URL: databaseUrl!,
+ GBRAIN_SKIP_STARTUP_HOOKS: '1', GBRAIN_NO_GITIGNORE: '1',
+ };
+ const proc = Bun.spawn([process.execPath, cli, ...args], { cwd: home, env, stdin: 'ignore', stdout: 'pipe', stderr: 'pipe' });
+ const [code, stdout, stderr] = await Promise.all([proc.exited, new Response(proc.stdout).text(), new Response(proc.stderr).text()]);
+ return { code, out: stdout + stderr };
+ }
+
+ async function prepare() {
+ assertSafeE2eDatabaseUrl(databaseUrl!);
+ await setupDB();
+ home = mkdtempSync(join(tmpdir(), 'gbrain-5842-'));
+ const init = await run(['init', '--non-interactive', '--no-embedding', '--url', databaseUrl!]);
+ expect({ code: init.code, out: init.code ? init.out : '' }).toEqual({ code: 0, out: '' });
+ const sql = postgres(databaseUrl!, { max: 1, onnotice: () => {} });
+ try {
+ await sql`UPDATE sources SET local_path = NULL WHERE id = 'default'`;
+ await sql`DELETE FROM config WHERE key = 'sync.repo_path'`;
+ await sql`DELETE FROM gbrain_cycle_locks`;
+ await sql`TRUNCATE persistence_requests CASCADE`;
+ } finally { await sql.end(); }
+ await getEngine().putPage('notes/fixture', { type: 'note', title: 'Fixture', compiled_truth: 'Saved before the export.', timeline: '' }, { sourceId: 'default' });
+ }
+
+ const exportArgs = (root: string) => ['apply-migrations', '--migration', SHARED_CONTENT_MIGRATION_VERSION, '--export-db-only',
+ '--content-root', root, '--export-source', 'default', '--confirm-quiesced', '--acknowledge-no-backup', '--yes'];
+
+ test('the runner\'s own orchestration lease does not block the export', async () => {
+ await prepare();
+ const root = join(home, 'canonical');
+ const result = await run(exportArgs(root));
+ expect(result.out).not.toContain('Active maintenance locks or durable writes remain');
+ expect(existsSync(join(root, 'notes/fixture.md'))).toBe(true);
+ expect(readFileSync(join(root, 'notes/fixture.md'), 'utf8')).toContain('Saved before the export.');
+ }, 180_000);
+
+ test('a foreign lock row still refuses with writer_not_quiesced', async () => {
+ await prepare();
+ const sql = postgres(databaseUrl!, { max: 1, onnotice: () => {} });
+ try {
+ await sql`INSERT INTO gbrain_cycle_locks (id, holder_pid, holder_host, acquired_at, ttl_expires_at, last_refreshed_at, acquisition_token)
+ VALUES ('gbrain-cycle', 1, 'other-host', now(), now() + interval '1 hour', now(), gen_random_uuid())`;
+ } finally { await sql.end(); }
+ const root = join(home, 'canonical');
+ const result = await run(exportArgs(root));
+ expect(result.out).toContain('Active maintenance locks or durable writes remain');
+ expect(existsSync(root)).toBe(false);
+ }, 180_000);
+});