Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
graduation(g2a): custody and rollback tests; harness carries a security table
garrytanf5d21c098a3c
diff --git a/test/graduation-custody.test.ts b/test/graduation-custody.test.tsnew file mode 100644index 0000000000..31a67cee69--- /dev/null+++ b/test/graduation-custody.test.ts@@ -0,0 +1,213 @@+/**+ * Engine graduation filesystem custody: intent marker, tombstone, lock-free+ * path inspection, lock-retaining close, held-lock move-aside and the PGLite+ * open-path refusals.+ *+ * Protects: the kernel lock never gaps between close, rename and tombstone+ * (no opener acquires it and none creates a data dir); the tombstone is+ * exclusive and 0600; a tombstoned path refuses with engine_graduated and is+ * never re-initialised; a live marker refuses opens before the lock while a+ * dead pre-cutover marker lets the source open; a dead marker past cutover is+ * graduation_interrupted with the lock released. Regressions that fail it: a+ * close that releases the lock, a tombstone write that overwrites, an opener+ * that mkdirs over the tombstone, a liveness check fooled by PID reuse.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, statSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import {+ assertPgliteGraduationOpenable, currentProcessIdentity, graduatedPath, graduationHandOffRequested, inspectGraduationPath,+ intentMarkerPath, moveAsideHeld, processStartTime, readIntentMarker, readTombstone, registerGraduationRunInProcess, removeTombstone,+ TombstonePathOccupiedError, writeIntentMarker, writeTombstone,+} from '../src/core/persistence/graduation-custody.ts';+import type { IntentMarker, ManifestState, Tombstone } from '../src/core/persistence/engine-graduation.types.ts';+import { acquireKernelLockOnly, acquireLock, PgliteBusyError, releaseLock, type LockHandle } from '../src/core/pglite-lock.ts';+import { moveHeldPglite } from '../src/core/persistence/maintenance.ts';+import { openPglite } from './helpers/graduation-harness.ts';++const target = { id: 'target-id', host: 'db.example.test', port: 5432, database: 'brain', user: 'alice-example' };+function marker(runId: string, state: ManifestState, identity: Partial<IntentMarker> = {}): IntentMarker {+ return { runId, state, ...currentProcessIdentity(), target, updatedAt: new Date().toISOString(), ...identity };+}+function tombstone(runId: string, movedTo: string): Tombstone {+ return { kind: 'gbrain-engine-graduated', runId, brainId: 'brain', movedTo, target, targetDisplayUrl: 'postgres://[email protected]:5432/brain',+ graduatedAt: new Date().toISOString(), fixArgv: ['gbrain', 'config', 'set', 'database_url', '<GBRAIN_TARGET_URL>'] };+}+function codeOf(error: unknown): string | undefined { return (error as { code?: string })?.code; }+function deadPid(): number {+ const child = Bun.spawnSync(['sh', '-c', 'echo $$']);+ return Number(child.stdout.toString().trim());+}++let root: string;+beforeAll(() => { root = mkdtempSync(join(tmpdir(), 'gbrain-custody-')); });+afterAll(() => {});++describe('intent marker and tombstone files', () => {+ test('the marker is replaced atomically with mode 0600; an unreadable one is never read as "no graduation"', () => {+ const dir = join(root, 'marker.pglite');+ mkdirSync(dir);+ expect(readIntentMarker(dir)).toBeNull();+ writeIntentMarker(dir, marker('run-a', 'planned'));+ writeIntentMarker(dir, marker('run-a', 'quiesced'));+ expect(readIntentMarker(dir)?.state).toBe('quiesced');+ expect(statSync(intentMarkerPath(dir)).mode & 0o777).toBe(0o600);+ writeFileSync(intentMarkerPath(dir), '{not json');+ expect(() => readIntentMarker(dir)).toThrow();+ expect(inspectGraduationPath(dir).kind).toBe('interrupted');+ });++ test('the tombstone is created exclusively, 0600, and only its own run removes it', () => {+ const path = join(root, 'tomb.pglite');+ writeTombstone(path, tombstone('run-t', `${path}.graduated-run-t`));+ expect(statSync(path).mode & 0o777).toBe(0o600);+ expect(() => writeTombstone(path, tombstone('run-u', 'x'))).toThrow(TombstonePathOccupiedError);+ expect(readTombstone(path)?.runId).toBe('run-t');+ expect(() => removeTombstone(path, 'run-u')).toThrow(/belongs to graduation run run-t/);+ removeTombstone(path, 'run-t');+ expect(existsSync(path)).toBe(false);+ mkdirSync(path);+ expect(() => writeTombstone(path, tombstone('run-t', 'x'))).toThrow(TombstonePathOccupiedError);+ expect(readTombstone(path)).toBeNull();+ });+});++describe('inspectGraduationPath and marker liveness', () => {+ test('none, in_progress, interrupted, graduated and split_brain', () => {+ const dir = join(root, 'inspect.pglite');+ mkdirSync(dir);+ expect(inspectGraduationPath(dir).kind).toBe('none');+ const unregister = registerGraduationRunInProcess('run-live');+ writeIntentMarker(dir, marker('run-live', 'copying'));+ expect(inspectGraduationPath(dir)).toMatchObject({ kind: 'in_progress', liveness: 'alive' });+ unregister();+ expect(inspectGraduationPath(dir)).toMatchObject({ kind: 'interrupted', liveness: 'dead' });+ writeIntentMarker(dir, marker('run-dead', 'copying', { pid: deadPid(), processStart: null }));+ expect(inspectGraduationPath(dir)).toMatchObject({ kind: 'interrupted', liveness: 'dead' });+ writeIntentMarker(dir, marker('run-reused', 'copying', { pid: process.ppid, processStart: '1' }));+ if (processStartTime(process.ppid)) expect(inspectGraduationPath(dir).liveness).toBe('dead');+ writeIntentMarker(dir, marker('run-other-host', 'copying', { pid: process.ppid, bootId: 'another-boot' }));+ expect(inspectGraduationPath(dir).liveness).toBe('unknown');+ writeIntentMarker(dir, marker('run-split', 'tombstoned', { pid: deadPid() }));+ mkdirSync(graduatedPath(dir, 'run-split'));+ expect(inspectGraduationPath(dir)).toMatchObject({ kind: 'split_brain', movedTo: graduatedPath(dir, 'run-split') });+ writeIntentMarker(dir, marker('run-split', 'rolled_back'));+ expect(inspectGraduationPath(dir).kind).toBe('none');+ const tombPath = join(root, 'inspect-tomb.pglite');+ writeTombstone(tombPath, tombstone('run-g', `${tombPath}.graduated-run-g`));+ expect(inspectGraduationPath(tombPath)).toMatchObject({ kind: 'graduated', tombstone: { runId: 'run-g' } });+ });++ test('a serve hands off only to a live requester on another process', () => {+ const dir = join(root, 'handoff.pglite');+ mkdirSync(dir);+ writeIntentMarker(dir, marker('run-self', 'planned'));+ expect(graduationHandOffRequested(dir)).toBeNull();+ writeIntentMarker(dir, marker('run-dead', 'planned', { pid: deadPid(), processStart: null }));+ expect(graduationHandOffRequested(dir)).toBeNull();+ writeIntentMarker(dir, marker('run-parent', 'planned', { pid: process.ppid, processStart: processStartTime(process.ppid) }));+ expect(graduationHandOffRequested(dir)?.runId).toBe('run-parent');+ });+});++describe('lock-retaining close and held-lock move-aside', () => {+ test('the kernel lock never gaps from close through rename and tombstone; the tombstone then refuses every opener', async () => {+ const dataDir = join(root, 'custody.pglite');+ const engine = await openPglite(dataDir);+ let lock: LockHandle | null = null;+ const attempts: string[] = [];+ let polling = true;+ const poller = (async () => {+ while (polling) {+ try { const stolen = await acquireLock(dataDir, { timeoutMs: 0 }); attempts.push('acquired'); await releaseLock(stolen); }+ catch (error) { attempts.push(error instanceof PgliteBusyError ? 'busy' : codeOf(error) ?? (error as Error).message); }+ await Bun.sleep(5);+ }+ })();+ try {+ await engine.executeRaw('CREATE TABLE kept (id int primary key)');+ await engine.executeRaw('INSERT INTO kept VALUES (1)');+ lock = await engine.closeRetainingLock();+ await engine.disconnect();+ expect(lock.acquired).toBe(true);+ await Bun.sleep(30);+ const movedTo = moveAsideHeld(dataDir, lock, 'run-c');+ expect(lock.lockDir).toBe(join(movedTo, '.gbrain-lock'));+ expect(existsSync(dataDir)).toBe(false);+ await Bun.sleep(30);+ writeTombstone(dataDir, tombstone('run-c', movedTo));+ await Bun.sleep(30);+ } finally {+ polling = false;+ await poller;+ if (lock) await releaseLock(lock);+ }+ expect(attempts.length).toBeGreaterThan(3);+ expect(attempts).not.toContain('acquired');+ expect(lstatSync(dataDir).isFile()).toBe(true);+ await expect(acquireLock(dataDir, { timeoutMs: 0 })).rejects.toThrow(/EEXIST|ENOTDIR|not a directory|file already exists/i);+ expect(lstatSync(dataDir).isFile()).toBe(true);+ expect(codeOf(await openPglite(dataDir).catch(e => e))).toBe('engine_graduated');+ const retained = await openPglite(graduatedPath(dataDir, 'run-c'));+ try { expect(await retained.executeRaw('SELECT id FROM kept')).toEqual([{ id: 1 }]); } finally { await retained.disconnect(); }+ }, 30_000);++ test('a held lock moves only its own datastore, and a held-lock open adopts it without a gap', async () => {+ const dataDir = join(root, 'adopt.pglite');+ const other = join(root, 'adopt-other.pglite');+ mkdirSync(other);+ const engine = await openPglite(dataDir);+ const lock = await engine.closeRetainingLock();+ await engine.disconnect();+ expect(() => moveHeldPglite(other, `${other}.moved`, lock)).toThrow(/does not belong/);+ const moved = `${dataDir}.graduated-run-adopt`;+ moveHeldPglite(dataDir, moved, lock);+ moveHeldPglite(moved, dataDir, lock);+ await expect(acquireLock(dataDir, { timeoutMs: 0 })).rejects.toBeInstanceOf(PgliteBusyError);+ const { PGLiteEngine } = await import('../src/core/pglite-engine.ts');+ const adopted = new PGLiteEngine();+ await adopted.connectWithHeldLock({ engine: 'pglite', database_path: dataDir }, lock);+ try { expect(await adopted.executeRaw('SELECT 1 AS one')).toEqual([{ one: 1 }]); } finally { await adopted.disconnect(); }+ const after = await openPglite(dataDir);+ await after.disconnect();+ }, 30_000);++ test('a kernel-only lock on a tombstoned path creates nothing and excludes openers', async () => {+ const path = join(root, 'kernel-only.pglite');+ writeTombstone(path, tombstone('run-k', `${path}.graduated-run-k`));+ const lock = await acquireKernelLockOnly(path, { lockDir: join(`${path}.graduated-run-k`, '.gbrain-lock'), timeoutMs: 0 });+ try {+ await expect(acquireKernelLockOnly(path, { lockDir: 'x', timeoutMs: 0 })).rejects.toBeInstanceOf(PgliteBusyError);+ expect(lstatSync(path).isFile()).toBe(true);+ } finally { await releaseLock(lock); }+ }, 30_000);+});++describe('PGLite open-path refusals', () => {+ test('a dead run before cutover lets the source open; past cutover it is interrupted and the lock is released', async () => {+ const dataDir = join(root, 'open.pglite');+ const first = await openPglite(dataDir);+ await first.disconnect();+ writeIntentMarker(dataDir, marker('run-o', 'verified', { pid: deadPid(), processStart: null }));+ const opened = await openPglite(dataDir);+ await opened.disconnect();+ writeIntentMarker(dataDir, marker('run-o', 'cutover', { pid: deadPid(), processStart: null }));+ const refused = await openPglite(dataDir).catch(e => e);+ expect(codeOf(refused)).toBe('graduation_interrupted');+ expect(refused.fix?.argv).toEqual(['gbrain', 'migrate', '--resume']);+ const lock = await acquireLock(dataDir, { timeoutMs: 0 });+ await releaseLock(lock);+ }, 30_000);++ test('a live run on another process refuses before the lock, and the refusal names the status command', () => {+ const dataDir = join(root, 'live.pglite');+ mkdirSync(dataDir);+ writeIntentMarker(dataDir, marker('run-p', 'copying', { pid: process.ppid, processStart: processStartTime(process.ppid) }));+ let error: unknown;+ try { assertPgliteGraduationOpenable(dataDir, 'pre_lock'); } catch (e) { error = e; }+ expect(codeOf(error)).toBe('graduation_in_progress');+ expect((error as { fix?: { argv?: string[]; actor?: string } }).fix).toMatchObject({ argv: ['gbrain', 'migrate', '--status', '--json'], actor: 'provider' });+ expect(readFileSync(intentMarkerPath(dataDir), 'utf8')).toContain('run-p');+ });+});diff --git a/test/graduation-rollback.test.ts b/test/graduation-rollback.test.tsnew file mode 100644index 0000000000..a1ce32db2b--- /dev/null+++ b/test/graduation-rollback.test.ts@@ -0,0 +1,186 @@+/**+ * Engine graduation rollback custody.+ *+ * Protects: rollback before cutover abandons the target (fence kept) and+ * leaves the source writable; after cutover it fences first, compares the+ * target with the graduation receipt and the retained source's security+ * state by identity and content, refuses finally on withdrawals and+ * revocations, needs `--yes --expect <hash>` for other user-data loss, never+ * writes back to the source, and returns the target to authority on every+ * refusal; durable substeps reconcile after a crash (back to authority before+ * approval, forward to rolled_back after it). Regressions that fail it: a+ * timestamp-based security check (revocations delete rows), a refusal that+ * strands the target fenced, a crash after approval that restores authority.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { existsSync, lstatSync, readFileSync } from 'node:fs';+import { join } from 'node:path';+import {+ planGraduation, readGraduationManifest, reconcileGraduation, rollbackGraduation, runGraduation, type GraduationRunOptions,+} from '../src/core/persistence/engine-graduation.ts';+import { assertGraduationConnectAllowed, readIntentMarker, readTombstone } from '../src/core/persistence/graduation-custody.ts';+import { graduationFenceStatus, readGraduationRow } from '../src/core/persistence/graduation-schema.ts';+import { assertSafeE2eDatabaseUrl } from './helpers/db-guard.ts';+import { crashAt, makeHarness, openPglite, probeRows, SOURCE_TOKEN_ID, TARGET_URL, type Harness } from './helpers/graduation-harness.ts';++function codeOf(error: unknown): string | undefined { return (error as { code?: string })?.code; }+async function refusal(promise: Promise<unknown>): Promise<{ code?: string; fix?: { argv?: string[]; plan_hash?: string; consent?: string[] }; message: string }> {+ try { await promise; } catch (error) { return { code: codeOf(error), fix: (error as { fix?: never }).fix, message: (error as Error).message }; }+ throw new Error('expected a refusal');+}++const POSTGRES_URL = process.env.DATABASE_URL;+const targets: Array<[string, string | undefined]> = [['pglite target', undefined]];+if (POSTGRES_URL) { assertSafeE2eDatabaseUrl(POSTGRES_URL); targets.push(['postgres target', POSTGRES_URL]); }++for (const [label, postgresUrl] of targets) {+ describe(`graduation rollback (${label})`, () => {+ let h: Harness;+ beforeAll(async () => { h = await makeHarness({ postgresUrl }); });+ afterAll(async () => { await h.close(); });++ async function fresh(): Promise<void> { await h.close(); h = await makeHarness({ postgresUrl }); }+ function runOpts(expect: string, extra: Partial<GraduationRunOptions> = {}): GraduationRunOptions {+ return { config: { engine: 'pglite', database_path: h.dataDir } as GraduationRunOptions['config'], url: TARGET_URL, env: {}, expect, deps: h.deps, handoffTimeoutMs: 1_000, ...extra };+ }+ async function graduate(extra: Partial<GraduationRunOptions> = {}): Promise<void> {+ const hash = (await planGraduation(runOpts(''))).planHash;+ await runGraduation(runOpts(hash, extra));+ }+ const rollbackOpts = (extra: Record<string, unknown> = {}) => ({ env: {}, deps: h.deps, handoffTimeoutMs: 1_000, ...extra });+ const manifest = () => readGraduationManifest(join(h.gbrainDir, 'graduation-manifest.json'))!;+ const config = () => JSON.parse(readFileSync(join(h.gbrainDir, 'config.json'), 'utf8'));++ async function assertTargetAuthoritative(): Promise<void> {+ expect((await readGraduationRow(h.target))?.state).toBe('authoritative');+ expect((await graduationFenceStatus(h.target)).fenced).toBe(0);+ await h.target.executeRaw(`INSERT INTO grad_probe VALUES (700 + (SELECT count(*) FROM grad_probe)::int, 'normal-client-write')`);+ expect(lstatSync(h.dataDir).isFile()).toBe(true);+ }+ async function assertRolledBack(): Promise<void> {+ expect(manifest().state).toBe('rolled_back');+ expect(lstatSync(h.dataDir).isDirectory()).toBe(true);+ expect(readTombstone(h.dataDir)).toBeNull();+ expect(readIntentMarker(h.dataDir)).toBeNull();+ expect(config()).toMatchObject({ engine: 'pglite', database_path: h.dataDir });+ expect(config().database_url).toBeUndefined();+ const mounts = JSON.parse(readFileSync(h.mountsPath, 'utf8'));+ expect(mounts.mounts[0]).toMatchObject({ engine: 'pglite', database_path: h.dataDir });+ expect(mounts.mounts[0].database_url).toBeUndefined();+ expect((await readGraduationRow(h.target))?.state).toBe('rolled_back');+ expect((await graduationFenceStatus(h.target)).unfenced).toEqual([]);+ expect(codeOf(await assertGraduationConnectAllowed(h.target, {}).catch(e => e))).toBe('graduation_in_progress');+ const source = await openPglite(h.dataDir);+ try {+ expect((await readGraduationRow(source))?.state).toBe('rolled_back');+ await source.executeRaw(`INSERT INTO grad_probe VALUES (900, 'source-writable-again')`);+ } finally { await source.disconnect(); }+ }++ test('before cutover: the target is abandoned and stays fenced; the source is released writable', async () => {+ await h.inHome(async () => {+ await expect(graduate({ pauseAt: 'verified', pauseHook: crashAt('verified') })).rejects.toThrow();+ const result = await rollbackGraduation(rollbackOpts());+ expect(result.state).toBe('abandoned');+ expect(manifest().state).toBe('abandoned');+ expect(readIntentMarker(h.dataDir)).toBeNull();+ expect((await readGraduationRow(h.target))?.state).toBe('abandoned');+ expect((await graduationFenceStatus(h.target)).unfenced).toEqual([]);+ await expect(h.target.executeRaw(`INSERT INTO grad_probe VALUES (50, 'x')`)).rejects.toThrow(/graduation_in_progress/);+ const source = await openPglite(h.dataDir);+ try {+ expect((await readGraduationRow(source))?.state).toBe('rolled_back');+ await source.executeRaw(`INSERT INTO grad_probe VALUES (51, 'writable')`);+ } finally { await source.disconnect(); }+ });+ }, 120_000);++ test('after graduation with no target writes: the datastore, routing and mounts are restored', async () => {+ await fresh();+ await h.inHome(async () => {+ await graduate();+ await h.target.executeRaw(`UPDATE access_tokens SET last_used_at = now() WHERE id = $1::uuid`, [SOURCE_TOKEN_ID]);+ const result = await rollbackGraduation(rollbackOpts());+ expect(result.state).toBe('rolled_back');+ await assertRolledBack();+ });+ }, 120_000);++ test('a target page-style edit is listed and rolls back only with the expect hash; it is never written back', async () => {+ await fresh();+ await h.inHome(async () => {+ await graduate();+ await h.target.executeRaw(`INSERT INTO grad_probe VALUES (10, 'written-on-target')`);+ const refused = await refusal(rollbackGraduation(rollbackOpts()));+ expect(refused.code).toBe('graduation_rollback_writes_lost');+ expect(refused.message).toContain('grad_probe');+ expect(refused.fix?.consent).toEqual(['destructive']);+ const hash = refused.fix!.plan_hash!;+ expect(refused.fix?.argv).toEqual(['gbrain', 'migrate', '--rollback-to-source', '--yes', '--expect', hash]);+ expect(manifest().state).toBe('graduated');+ await assertTargetAuthoritative();+ const wrong = await refusal(rollbackGraduation(rollbackOpts({ yes: true, expect: '0000000000000000' })));+ expect(wrong.code).toBe('graduation_rollback_writes_lost');+ const relisted = wrong.fix!.plan_hash!;+ await rollbackGraduation(rollbackOpts({ yes: true, expect: relisted }));+ await assertRolledBack();+ const source = await openPglite(h.dataDir);+ try { expect((await probeRows(source)).map(r => r.v)).not.toContain('written-on-target'); } finally { await source.disconnect(); }+ });+ }, 120_000);++ test('a fact withdrawal on the target refuses finally, with and without --yes', async () => {+ await fresh();+ await h.inHome(async () => {+ await graduate();+ await h.target.executeRaw(`INSERT INTO fact_withdrawals (source_id, visibility, subject, fact_hash) VALUES ('default', 'private', '*', 'hash-w1')`);+ for (const extra of [{}, { yes: true, expect: 'anything' }]) {+ const refused = await refusal(rollbackGraduation(rollbackOpts(extra)));+ expect(refused.code).toBe('graduation_rollback_writes_lost');+ expect(refused.fix?.argv).toBeUndefined();+ expect(refused.message).toContain('fact_withdrawals');+ await assertTargetAuthoritative();+ }+ });+ }, 120_000);++ test('a token revocation on the target (the row is deleted) refuses finally', async () => {+ await fresh();+ await h.inHome(async () => {+ await graduate();+ await h.target.executeRaw(`DELETE FROM access_tokens WHERE id = $1::uuid`, [SOURCE_TOKEN_ID]);+ const refused = await refusal(rollbackGraduation(rollbackOpts({ yes: true, expect: 'x' })));+ expect(refused.code).toBe('graduation_rollback_writes_lost');+ expect(refused.fix?.argv).toBeUndefined();+ expect(refused.message).toContain('access_tokens: 1 missing');+ await assertTargetAuthoritative();+ });+ }, 120_000);++ test('a crash after fencing returns the target to authority; a crash after approval rolls forward', async () => {+ await fresh();+ await h.inHome(async () => {+ await graduate();+ await expect(rollbackGraduation(rollbackOpts({ pauseAt: 'rollback_fenced', pauseHook: crashAt('rollback_fenced') }))).rejects.toThrow();+ expect((await readGraduationRow(h.target))?.state).toBe('rollback_fenced');+ await expect(h.target.executeRaw(`INSERT INTO grad_probe VALUES (60, 'x')`)).rejects.toThrow(/graduation_in_progress/);+ const reconciled = await reconcileGraduation(rollbackOpts());+ expect(reconciled.actions).toContain('returned target to authority');+ expect(manifest().state).toBe('graduated');+ await assertTargetAuthoritative();+ });+ for (const seam of ['rollback_approved', 'source_restoring']) {+ await fresh();+ await h.inHome(async () => {+ await graduate();+ await expect(rollbackGraduation(rollbackOpts({ pauseAt: seam, pauseHook: crashAt(seam) }))).rejects.toThrow();+ expect(manifest().state).toBe(seam);+ const reconciled = await reconcileGraduation(rollbackOpts());+ expect(reconciled.actions).toContain('finished rollback');+ await assertRolledBack();+ expect(existsSync(`${h.dataDir}.graduated-${manifest().runId}`)).toBe(false);+ });+ }+ }, 120_000);+ });+}diff --git a/test/graduation-state.test.ts b/test/graduation-state.test.tsindex e42dd06296..79cd03c968 100644--- a/test/graduation-state.test.ts+++ b/test/graduation-state.test.ts@@ -115,7 +115,7 @@ describe('row state machine, connect and admission checks', () => {await withGraduationRun(t, run, async tx => { await setTargetState(tx, run, 'verifying'); await setTargetState(tx, run, 'verified'); await setTargetState(tx, run, 'authoritative'); });await expect(assertGraduationConnectAllowed(t, {})).resolves.toBeUndefined();await expect(t.transaction(tx => assertGraduationAdmission(tx))).resolves.toBeUndefined();- });+ }, 60_000);test('a source row at cutover refuses: interrupted before the tombstone exists', async () => {const source = await openPglite(join(h.root, 'cutover-source.pglite'));@@ -129,7 +129,7 @@ describe('row state machine, connect and admission checks', () => {expect(codeOf(await source.transaction(tx => assertGraduationAdmission(tx)).catch(e => e))).toBe('graduation_interrupted');await expect(withGraduationRun(source, run, tx => setSourceState(tx, run, 'quiesced'))).resolves.toBeUndefined();} finally { await source.disconnect(); }- });+ }, 60_000);});const POSTGRES_URL = process.env.DATABASE_URL;@@ -185,7 +185,7 @@ for (const [label, postgresUrl] of targets) {try { expect((await readGraduationRow(retained))?.state).toBe('cutover'); } finally { await retained.disconnect(); }expect(h.calls.pause_released).toBe(1);});- });+ }, 60_000);test('the fence refuses other writers while the copy runs; the run itself writes', async () => {await fresh();@@ -206,7 +206,7 @@ for (const [label, postgresUrl] of targets) {expect(observed).toEqual({ write: 'graduation_in_progress', exempt: true, respawn: 'graduation_in_progress' });await assertGraduated();});- });+ }, 60_000);const seams = ['quiesced', 'draining', 'copying', 'copy_table', 'verifying', 'verified', 'cutover', 'before_rename', 'after_rename', 'tombstoned', 'authoritative', 'routing_flipped'];for (const seam of seams) {@@ -223,7 +223,7 @@ for (const [label, postgresUrl] of targets) {await resumeGraduation({ env: {}, deps: h.deps, handoffTimeoutMs: 1_000 });await assertGraduated();});- });+ }, 60_000);}test('a source write during a lock gap after verify reaches the target', async () => {@@ -231,14 +231,14 @@ for (const [label, postgresUrl] of targets) {await h.inHome(async () => {const hash = await plan();await expect(runGraduation(runOpts(hash, { pauseAt: 'verified', pauseHook: crashAt('verified') }))).rejects.toThrow();- const copiesBefore = h.calls.copy ?? 0;+ const copiesBefore = h.calls.copy_probe ?? 0;const source = await openPglite(h.dataDir);try { await source.executeRaw(`INSERT INTO grad_probe VALUES (4, 'written-in-gap')`); } finally { await source.disconnect(); }await resumeGraduation({ env: {}, deps: h.deps, handoffTimeoutMs: 1_000 });- expect(h.calls.copy).toBe(copiesBefore + 1);+ expect(h.calls.copy_probe).toBe(copiesBefore + 1);expect((await probeRows(h.target)).map(r => r.v)).toContain('written-in-gap');});- });+ }, 60_000);test('a stray datastore at the old path is split brain; the target stays non-authoritative', async () => {await fresh();@@ -252,7 +252,7 @@ for (const [label, postgresUrl] of targets) {expect((await readGraduationRow(h.target))?.state).toBe('verified');expect((await graduationStatus()).path?.kind).toBe('split_brain');});- });+ }, 60_000);test('a path occupied when the live run creates the tombstone refuses as split brain', async () => {await fresh();@@ -263,7 +263,7 @@ for (const [label, postgresUrl] of targets) {expect((await readGraduationRow(h.target))?.state).toBe('verified');expect((await graduationFenceStatus(h.target)).unfenced).toEqual([]);});- });+ }, 60_000);test('a changed plan refuses before anything is fenced and leaves the source writable', async () => {await fresh();@@ -276,7 +276,7 @@ for (const [label, postgresUrl] of targets) {try { await source.executeRaw(`INSERT INTO grad_probe VALUES (9, 'still-writable')`); } finally { await source.disconnect(); }expect(await readGraduationRow(h.target)).toBeNull();});- });+ }, 60_000);test('a live serve that never hands off refuses with the two-step writer-held fix; one that does is waited for', async () => {await fresh();@@ -297,7 +297,7 @@ for (const [label, postgresUrl] of targets) {await runGraduation(runOpts(hash, { deps: handOff, handoffTimeoutMs: 5_000 }));await assertGraduated();});- });+ }, 60_000);test('a drain timeout and a verify failure are resumable; the source stays writable in between', async () => {await fresh();@@ -318,7 +318,7 @@ for (const [label, postgresUrl] of targets) {expect((await probeRows(h.target)).map(r => r.v)).toContain('after-verify-failure');expect(lstatSync(h.dataDir).isFile()).toBe(true);});- });+ }, 60_000);test('--status performs zero mutations at a crash point', async () => {await fresh();@@ -334,6 +334,6 @@ for (const [label, postgresUrl] of targets) {expect(files.map(f => [readFileSync(f, 'utf8'), statSync(f).mtimeMs])).toEqual(before);expect(existsSync(graduatedPath(h.dataDir, status.runId!))).toBe(false);});- });+ }, 60_000);});}diff --git a/test/helpers/graduation-harness.ts b/test/helpers/graduation-harness.tsindex c00ee9f104..f3c8787e97 100644--- a/test/helpers/graduation-harness.ts+++ b/test/helpers/graduation-harness.ts@@ -38,10 +38,26 @@ export async function probeRows(engine: BrainEngine): Promise<Array<{ id: numberreturn engine.executeRaw<{ id: number; v: string }>('SELECT id, v FROM grad_probe ORDER BY id');}+export const TOKENS: InventoryEntry = {+ relation: 'access_tokens', kind: 'table', class: 'carry', engines: { pglite: true, postgres: true },+ lossKind: 'security', transforms: [], reason: 'harness security table',+};++async function tableRows(engine: BrainEngine, relation: string): Promise<string[]> {+ const [present] = await engine.executeRaw<{ ok: boolean }>('SELECT to_regclass($1) IS NOT NULL AS ok', [relation]);+ if (!present?.ok) return [];+ const rows = await engine.transaction(async tx => {+ await tx.executeRaw(`SELECT set_config('TimeZone', 'UTC', true)`);+ return tx.executeRaw<{ r: unknown }>(`SELECT to_jsonb(t) AS r FROM ${relation} t`);+ });+ const canonical = (v: unknown): unknown => Array.isArray(v) ? v.map(canonical)+ : v && typeof v === 'object' ? Object.fromEntries(Object.keys(v as object).sort().map(k => [k, canonical((v as Record<string, unknown>)[k])])) : v;+ return rows.map(({ r }) => JSON.stringify(canonical(typeof r === 'string' ? JSON.parse(r) : r))).sort();+}+async function digest(engine: BrainEngine, entry: InventoryEntry): Promise<TableReceipt> {- const rows = await probeRows(engine);- const text = rows.map(r => `${r.id}:${r.v}`).join('\n');- return { relation: entry.relation, rows: rows.length, rootSha256: createHash('sha256').update(text).digest('hex'), batches: [] };+ const rows = await tableRows(engine, entry.relation);+ return { relation: entry.relation, rows: rows.length, rootSha256: createHash('sha256').update(rows.join('\n')).digest('hex'), batches: [] };}/** A non-disconnecting view of the shared target, so the orchestrator's cleanup leaves it open for assertions. */@@ -109,17 +125,21 @@ export async function makeHarness(opts: HarnessOptions = {}): Promise<Harness> {const calls: Record<string, number> = {};const count = (name: string) => { calls[name] = (calls[name] ?? 0) + 1; };const deps: Partial<GraduationDeps> = {- inventory: { version: 900, entries: [PROBE] },+ inventory: { version: 900, entries: [PROBE, TOKENS] },assertRelationSet: async () => {},- copyOrder: async () => [PROBE],+ copyOrder: async () => [PROBE, TOKENS],fkClosure: async () => [],digestTable: async (engine, entry) => digest(engine, entry),verifyGraduation: async (e): Promise<VerifyResult> => {count('verify');- const [source, copied] = [await digest(e.source, PROBE), await digest(e.target, PROBE)];- const ok = source.rootSha256 === copied.rootSha256;- return { ok, tables: [copied], failures: ok ? [] : [{ relation: 'grad_probe', kind: 'digest', detail: 'probe differs' }],- replay: { status: 'not_available', reason: 'no_caller_input' }, doctorFailingChecks: [] };+ const tables: TableReceipt[] = [];+ const failures: VerifyResult['failures'][number][] = [];+ for (const entry of [PROBE, TOKENS]) {+ const [source, copied] = [await digest(e.source, entry), await digest(e.target, entry)];+ tables.push(copied);+ if (source.rootSha256 !== copied.rootSha256) failures.push({ relation: entry.relation, kind: 'digest', detail: 'differs' });+ }+ return { ok: failures.length === 0, tables, failures, replay: { status: 'not_available', reason: 'no_caller_input' }, doctorFailingChecks: [] };},resolveTargetRoutes: ({ url, urlEnv, env }) => {const mainUrl = url ?? (urlEnv ? env?.[urlEnv] : undefined) ?? TARGET_URL;@@ -134,10 +154,11 @@ export async function makeHarness(opts: HarnessOptions = {}): Promise<Harness> {detectTriggerBypass: async () => 'session_replication_role',copyTable: async (e, entry, o) => {count('copy');- const rows = await probeRows(e.source);+ if (entry.relation === PROBE.relation) count('copy_probe');+ const rows = await tableRows(e.source, entry.relation);await withGraduationRun(e.target, o.runId, async tx => {- await tx.executeRaw('DELETE FROM grad_probe');- for (const row of rows) await tx.executeRaw('INSERT INTO grad_probe (id, v) VALUES ($1, $2)', [row.id, row.v]);+ await tx.executeRaw(`DELETE FROM ${entry.relation}`);+ for (const row of rows) await tx.executeRaw(`INSERT INTO ${entry.relation} SELECT * FROM jsonb_populate_record(NULL::${entry.relation}, $1::text::jsonb)`, [row]);});return { rows: rows.length };},