Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(persistence-gate): crash robot fails closed on BigInt fault payloads, hook errors and unreached faults (#6584)

time-attack99b53b5ebd63
diff --git a/scripts/persistence/README.md b/scripts/persistence/README.md
index 953176bdfc..1fb3da0262 100644
--- a/scripts/persistence/README.md
+++ b/scripts/persistence/README.md
@@ -142,7 +142,12 @@ fault. Full runs crash every seam and run every fault. The manifest's `robot`
key lists every run (schedule, seed, seam and occurrence or process fault),
`sequences_x_crash_points`, `lease_bound_seams_skipped`,
`lease_bound_faults_skipped` and violations with the observed trace;
-`robot_full_gate` is true for a full-budget run with no violations.
+`robot_full_gate` is true for a full-budget run with no violations, no
+`fault_hook_errors` (a fault hook that threw instead of freezing the worker)
+and no `faults_not_reached` (a worker that finished without reaching its
+requested seam, outside the per-scenario `UNREACHED_FAULT_ALLOWLIST` in
+`robot-driver.ts`); either kind of run also fails validation with a nonzero
+exit and is listed in `failing_runs` for `--replay`.
A failing run prints two commands. `--replay=<manifest>` re-runs exactly the
manifest's failing runs. `--shrink=<manifest>` removes ops from the first
diff --git a/scripts/persistence/crash-robot.ts b/scripts/persistence/crash-robot.ts
index 964109adfc..43c1b78b74 100644
--- a/scripts/persistence/crash-robot.ts
+++ b/scripts/persistence/crash-robot.ts
@@ -15,7 +15,8 @@ import type { GBrainConfig } from '../../src/core/config.ts';
import { PGLiteEngine } from '../../src/core/pglite-engine.ts';
import { PostgresEngine } from '../../src/core/postgres-engine.ts';
import { disposePersistenceConsumer, startPersistenceConsumer } from '../../src/core/persistence/service.ts';
-import { installFaultHook, type FaultPoint } from '../../src/core/persistence/fault-points.ts';
+import { installFaultHook, type FaultDetail, type FaultPoint } from '../../src/core/persistence/fault-points.ts';
+import { bigintToStringReplacer } from '../../src/core/utils.ts';
import { assertSafeE2eDatabaseUrl } from '../../test/helpers/db-guard.ts';
import postgres from '#postgres';
import { prepareTopology } from './history-fixture.ts';
@@ -158,12 +159,28 @@ async function openRobotEngine(config: RobotConfig, initialize: boolean): Promis
/** Freeze the whole process at a seam until the driver's SIGKILL arrives; nothing after this point runs. */
function freeze(event: Record<string, unknown>): never {
- const bytes = Buffer.from(`${JSON.stringify(event)}\n`);
+ const bytes = Buffer.from(`${JSON.stringify(event, bigintToStringReplacer)}\n`);
for (let offset = 0; offset < bytes.length;) offset += writeSync(1, bytes, offset, bytes.length - offset);
const blocked = new Int32Array(new SharedArrayBuffer(4));
for (;;) Atomics.wait(blocked, 0, 0);
}
+/**
+ * The `run` role's hook: freeze at the nth matching seam. A hook that throws
+ * would unwind into the code under test, which then keeps running as if no
+ * crash were requested (#6584), so the error is reported as a
+ * `fault_hook_error` event and the process freezes anyway; the driver counts
+ * such a run as a gate failure.
+ */
+export function robotFaultHook(fault: NonNullable<RobotConfig['fault']>): (point: FaultPoint, detail: FaultDetail) => void {
+ let seen = 0;
+ return (point, detail) => {
+ if (point !== fault.point || (fault.operation && detail.operation !== fault.operation) || ++seen !== fault.nth) return;
+ try { freeze({ event: 'fault', point, nth: seen, detail }); }
+ catch (error) { freeze({ event: 'fault_hook_error', point, nth: seen, message: error instanceof Error ? error.message : String(error) }); }
+ };
+}
+
function finalize(config: RobotConfig, model: ReferenceModel, extra: Partial<RobotOutcome>): RobotOutcome {
const locks = lockOrderReport();
for (const v of locks.violations) model.violate({ class: 'lock_order', detail: `${v.rule}: ${v.detail}` });
@@ -329,13 +346,7 @@ export async function robotWorker(role: 'count' | 'run' | 'recover', config: Rob
installLockOrderTrace();
const counts: Record<string, number> = {};
if (role === 'count') installFaultHook(point => { counts[point] = (counts[point] ?? 0) + 1; });
- if (role === 'run' && config.fault) {
- let seen = 0; const fault = config.fault;
- installFaultHook((point, detail) => {
- if (point !== fault.point || (fault.operation && detail.operation !== fault.operation) || ++seen !== fault.nth) return;
- freeze({ event: 'fault', point, nth: seen, detail });
- });
- }
+ if (role === 'run' && config.fault) installFaultHook(robotFaultHook(config.fault));
if (role === 'run') {
let next = 0; let inFlight: string[] = [];
world.onSubmit = () => writeState(config, world, model, checkouts, next, inFlight);
diff --git a/scripts/persistence/robot-driver.ts b/scripts/persistence/robot-driver.ts
index 3d61f4569e..1145bced4d 100644
--- a/scripts/persistence/robot-driver.ts
+++ b/scripts/persistence/robot-driver.ts
@@ -44,6 +44,24 @@ export interface RobotRun {
schedule: string; seed: number; length: number; fault?: { point: FaultPoint; nth: number }; process?: ProcessFault;
ops?: string[]; crashed: boolean; violations: RobotOutcome['violations']; duration_ms: number; trace?: string[];
deferred?: RobotOutcome['deferred'];
+ /** The worker finished without reaching its requested fault (#6584): nothing was crashed or recovered. */
+ fault_not_reached?: boolean;
+ /** The worker's fault hook threw at the requested seam (`fault_hook_error`); the run proves nothing. */
+ hook_error?: string;
+}
+
+/**
+ * Requested faults a scenario (a schedule label, or a process fault) may
+ * legitimately finish without reaching, each with its reason. Any other
+ * unreached fault fails the run and the full gate.
+ */
+export const UNREACHED_FAULT_ALLOWLIST: readonly { scenario: string; point: FaultPoint; reason: string }[] = [];
+export function unreachedAllowed(run: Pick<RobotRun, 'schedule' | 'process' | 'fault'>): boolean {
+ return UNREACHED_FAULT_ALLOWLIST.some(entry => entry.scenario === (run.process ?? run.schedule) && entry.point === run.fault?.point);
+}
+/** A run fails the gate when it found violations, its hook threw, or it never reached a fault it was not allowed to miss. */
+export function runFailed(run: RobotRun): boolean {
+ return run.violations.length > 0 || run.hook_error !== undefined || (run.fault_not_reached === true && !unreachedAllowed(run));
}
export interface RobotOptions {
engine: 'pglite' | 'postgres'; seed: number; seconds: number; scratch: string; home: string;
@@ -112,10 +130,15 @@ export async function runRobotPhase(o: RobotOptions) {
const child = o.spawn(path, o.home, 'robot', [role], environment); o.track(child);
const outcome = async (): Promise<RobotRun & { counts?: Record<string, number> }> => {
if (role === 'run' && extra.fault) {
- const reached = await Promise.race([child.event('fault', 600_000).then(e => ({ fault: e })), child.event('done', 600_000).then(e => ({ done: e }))]);
+ const reached = await Promise.race([child.event('fault', 600_000).then(e => ({ fault: e })),
+ child.event('fault_hook_error', 600_000).then(e => ({ hookError: e })), child.event('done', 600_000).then(e => ({ done: e }))]);
+ if ('hookError' in reached) {
+ await child.kill();
+ return { ...base, crashed: false, hook_error: String(reached.hookError.message), violations: [], duration_ms: performance.now() - at };
+ }
if ('done' in reached) {
const result = reached.done.result as RobotOutcome;
- return { ...base, crashed: false, violations: result.violations, deferred: result.deferred, trace: result.trace, duration_ms: performance.now() - at };
+ return { ...base, crashed: false, fault_not_reached: true, violations: result.violations, deferred: result.deferred, trace: result.trace, duration_ms: performance.now() - at };
}
await child.kill();
const recovered = o.spawn(path, o.home, 'robot', ['recover'], environment); o.track(recovered);
@@ -126,13 +149,16 @@ export async function runRobotPhase(o: RobotOptions) {
return { ...base, crashed: false, violations: result.violations, deferred: result.deferred, trace: result.trace, counts: result.counts, duration_ms: performance.now() - at };
};
const run = await outcome();
- if (!run.violations.length) await release(database);
+ if (!runFailed(run)) await release(database);
return run;
}
const record = (run: RobotRun) => {
runs.push(run);
const what = run.fault ? `${run.fault.point}#${run.fault.nth}` : run.process ?? 'no crash';
- log(`${run.schedule} ${what}: ${run.violations.length ? `${run.violations.length} VIOLATION(S) ${run.violations.map(v => v.class).join(',')}` : 'ok'} (${Math.round(run.duration_ms)} ms)`);
+ const verdict = run.violations.length ? `${run.violations.length} VIOLATION(S) ${run.violations.map(v => v.class).join(',')}`
+ : run.hook_error !== undefined ? `FAULT HOOK ERROR ${run.hook_error}`
+ : run.fault_not_reached ? (unreachedAllowed(run) ? 'fault not reached (allowed)' : 'FAULT NOT REACHED') : 'ok';
+ log(`${run.schedule} ${what}: ${verdict} (${Math.round(run.duration_ms)} ms)`);
};
if (o.replay) {
@@ -198,10 +224,13 @@ function summarize(runs: RobotRun[], started: number, o: RobotOptions) {
seed: o.seed, budget_seconds: o.seconds, duration_ms: performance.now() - started,
schedules: new Set(runs.map(r => `${r.schedule}:${r.seed}`)).size,
crash_runs: crashRuns.length, crashed_runs: crashRuns.filter(r => r.crashed).length,
+ fault_hook_errors: runs.filter(r => r.hook_error !== undefined),
+ faults_not_reached: runs.filter(r => r.fault_not_reached && !unreachedAllowed(r)),
+ faults_not_reached_allowed: runs.filter(r => r.fault_not_reached && unreachedAllowed(r)),
sequences_x_crash_points: crashRuns.length, distinct_crash_points: [...points].sort(),
process_faults: runs.filter(r => r.process).map(r => ({ fault: r.process, violations: r.violations.length })),
violations, deferred: runs.flatMap(r => (r.deferred ?? []).map(v => ({ ...v, schedule: r.schedule, seed: r.seed, fault: r.fault }))),
- failing_runs: runs.filter(r => r.violations.length), runs,
+ failing_runs: runs.filter(runFailed), runs,
};
}
diff --git a/scripts/persistence/validate.ts b/scripts/persistence/validate.ts
index 77000ca53b..a2edd3c05f 100644
--- a/scripts/persistence/validate.ts
+++ b/scripts/persistence/validate.ts
@@ -66,12 +66,21 @@ export function spawnWorker(configPath: string, home: string, role: string, args
async kill() { if (child.exitCode === null) child.kill('SIGKILL'); await child.exited; await reading; } };
}
+/** A full robot gate ran the whole budget, skipped nothing, and every requested crash happened and recovered cleanly (#6584). */
+export function robotFullGate(robot: Pick<Awaited<ReturnType<typeof runRobotPhase>>, 'violations' | 'fault_hook_errors' | 'faults_not_reached'>
+ & { lease_bound_seams_skipped?: string[]; lease_bound_faults_skipped?: string[] }, robotSeconds: number): boolean {
+ return robotSeconds >= FULL_ROBOT_SECONDS && robot.violations.length === 0
+ && robot.fault_hook_errors.length === 0 && robot.faults_not_reached.length === 0
+ && (robot.lease_bound_seams_skipped ?? []).length === 0 && (robot.lease_bound_faults_skipped ?? []).length === 0;
+}
+
/** The failing runs plus the exact command that replays them and the one that shrinks the first. */
export function robotFailure(failing: RobotRun[], options: ValidationOptions): string {
const manifest = options.manifest ?? `.context/persistence-${options.engine}-manifest.json`;
const env = options.engine === 'postgres' ? 'DATABASE_URL=<test url> ' : '';
const lines = failing.slice(0, 5).map(run => ` ${run.schedule} seed=${run.seed} ${run.fault ? `${run.fault.point}#${run.fault.nth}` : run.process ?? 'no crash'} [${runDigest(run)}]: `
- + run.violations.slice(0, 3).map(v => `${v.class}: ${v.detail}`).join(' | '));
+ + (run.violations.length ? run.violations.slice(0, 3).map(v => `${v.class}: ${v.detail}`).join(' | ')
+ : run.hook_error !== undefined ? `fault_hook_error: ${run.hook_error}` : 'fault_not_reached: the worker finished without reaching the requested fault'));
return [`Crash robot found ${failing.length} failing run(s):`, ...lines,
`Replay: ${env}bun --no-env-file scripts/persistence/validate.ts --engine=${options.engine} --replay=${manifest}`,
`Shrink: ${env}bun --no-env-file scripts/persistence/validate.ts --engine=${options.engine} --shrink=${manifest} (writes ${manifest}.shrunk.json)`].join('\n');
@@ -138,14 +147,14 @@ export async function runValidation(options: ValidationOptions) {
manifest.status = manifest.shrink.accepted ? 'passed' : 'failed'; manifest.full_gate = false; return manifest;
}
manifest.robot = await runRobotPhase(robotOptions({ replay: entries }));
- manifest.status = manifest.robot.violations.length ? 'failed' : 'passed'; manifest.full_gate = false;
- if (manifest.robot.violations.length) throw new Error(robotFailure(manifest.robot.failing_runs, options));
+ manifest.status = manifest.robot.failing_runs.length ? 'failed' : 'passed'; manifest.full_gate = false;
+ if (manifest.robot.failing_runs.length) throw new Error(robotFailure(manifest.robot.failing_runs, options));
return manifest;
}
if (options.robotSeconds) {
manifest.robot = await runRobotPhase(robotOptions());
process.stderr.write(`[persistence] ${options.engine}: crash robot ran ${manifest.robot.sequences_x_crash_points} sequence x crash point runs over ${manifest.robot.schedules} schedules\n`);
- if (manifest.robot.violations.length) throw new Error(robotFailure(manifest.robot.failing_runs, options));
+ if (manifest.robot.failing_runs.length) throw new Error(robotFailure(manifest.robot.failing_runs, options));
}
if (options.crashes !== false) for (const boundary of CRASH_BOUNDARIES) {
const { path } = await phase(`crash-${boundary}`); const requestId = randomUUID();
@@ -195,8 +204,7 @@ export async function runValidation(options: ValidationOptions) {
manifest.status = 'passed';
const executedBoundaries = manifest.crash_cases.map((entry: { boundary: string }) => entry.boundary);
if (options.crashes !== false) assert.deepEqual(executedBoundaries, [...CRASH_BOUNDARIES]);
- if (manifest.robot) manifest.robot_full_gate = (options.robotSeconds ?? 0) >= FULL_ROBOT_SECONDS && manifest.robot.violations.length === 0
- && (manifest.robot.lease_bound_seams_skipped ?? []).length === 0 && (manifest.robot.lease_bound_faults_skipped ?? []).length === 0;
+ if (manifest.robot) manifest.robot_full_gate = robotFullGate(manifest.robot, options.robotSeconds ?? 0);
manifest.full_gate = counts.schedules >= 1000 && counts.operations >= 10_000
&& executedBoundaries.length === CRASH_BOUNDARIES.length && CRASH_BOUNDARIES.every((boundary, index) => executedBoundaries[index] === boundary)
&& manifest.crash_cases.every((entry: { staging_cleanup_verified?: boolean }) => entry.staging_cleanup_verified === true)
diff --git a/src/core/persistence/fault-points.ts b/src/core/persistence/fault-points.ts
index df0f15d25d..c93681e1a3 100644
--- a/src/core/persistence/fault-points.ts
+++ b/src/core/persistence/fault-points.ts
@@ -28,7 +28,9 @@ export type FaultPoint = `publication:${PublicationBoundary}` | `effect:${Effect
* a stalling hook can model both the reporter's cases: a preparer that honours
* cancellation (settle on abort) and one that ignores it (hang on).
*/
-export interface FaultDetail { requestId?: string; effectId?: string | number; sourceId?: string; operation?: string | null; signal?: AbortSignal }
+export interface FaultDetail { requestId?: string; effectId?: string; sourceId?: string; operation?: string | null; signal?: AbortSignal }
+/** Postgres returns `persistence_effects.id` (bigserial) as a BigInt; `faultPoint` hands hooks its decimal string (#6584). */
+export type FaultDetailInput = Omit<FaultDetail, 'effectId'> & { effectId?: string | number | bigint };
type FaultHook = (point: FaultPoint, detail: FaultDetail) => Promise<void> | void;
/** The mid-effect seam of every effect kind; a new kind without one fails typecheck. */
@@ -43,8 +45,10 @@ export const EFFECT_FAULT_POINTS: Record<EffectKind, FaultPoint> = {
let installed: FaultHook | undefined;
/** Gate workers only. */
export function installFaultHook(hook: FaultHook | undefined): void { installed = hook; }
-export async function faultPoint(point: FaultPoint, detail: FaultDetail = {}): Promise<void> {
- if (installed) await installed(point, detail);
+export async function faultPoint(point: FaultPoint, detail: FaultDetailInput = {}): Promise<void> {
+ if (!installed) return;
+ const { effectId, ...rest } = detail;
+ await installed(point, effectId === undefined ? rest : { ...rest, effectId: String(effectId) });
}
/** Publication hooks that also reach the installed seam; returns the caller's hooks unchanged when none is installed. */
export function withFaultPoints(hooks: PublicationHooks): PublicationHooks {
diff --git a/test/persistence-crash-robot.test.ts b/test/persistence-crash-robot.test.ts
index 70a82ffb97..d6f6321a1b 100644
--- a/test/persistence-crash-robot.test.ts
+++ b/test/persistence-crash-robot.test.ts
@@ -14,13 +14,15 @@
* Seams: none (the fault hook stays uninstalled); PGLite.
*/
import { describe, expect, test } from 'bun:test';
-import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { descriptor, executeOp, parseDescriptor, SessionDrops } from '../scripts/persistence/ops.ts';
import { ReferenceModel } from '../scripts/persistence/model.ts';
import { crossBoundarySequences, pageBody, randomSchedule } from '../scripts/persistence/generator.ts';
-import { ROBOT_TOPOLOGY, restrict } from '../scripts/persistence/robot-driver.ts';
+import { FULL_ROBOT_SECONDS, ROBOT_TOPOLOGY, restrict, runRobotPhase, type RobotRun } from '../scripts/persistence/robot-driver.ts';
+import { robotFailure, robotFullGate, runValidation, spawnWorker } from '../scripts/persistence/validate.ts';
+import { faultPoint, installFaultHook, type FaultDetail, type FaultPoint } from '../src/core/persistence/fault-points.ts';
import { shrinkRun } from '../scripts/persistence/shrink.ts';
import { runSchedule, runSteps } from '../scripts/persistence/crash-robot.ts';
import { installLockOrderTrace, lockOrderReport } from '../scripts/persistence/lock-order.ts';
@@ -291,3 +293,118 @@ describe('PGLite releases claims a dead owner left behind', () => {
});
}, 60_000);
});
+
+describe('requested faults are reported, never silently skipped (#6584)', () => {
+ const replayRun = (fault: { point: FaultPoint; nth: number }): RobotRun =>
+ ({ schedule: 'caller_bound_replay', seed: 5105, length: 0, fault, crashed: false, violations: [], duration_ms: 0 });
+ function fakeSpawn(script: Record<string, Record<string, unknown>>[]) {
+ const spawned: { role: string; killed: boolean }[] = [];
+ const spawn = ((_path: string, _home: string, _mode: string, [role]: string[]) => {
+ const events = script[spawned.length] ?? {}; const entry = { role, killed: false }; spawned.push(entry);
+ const event = (name: string) => name in events ? Promise.resolve({ event: name, ...events[name] }) : new Promise<never>(() => {});
+ return { child: { pid: 0 }, event, done: () => event('done'), failureDiagnostics: () => [], async kill() { entry.killed = true; } };
+ }) as unknown as typeof spawnWorker;
+ return { spawn, spawned };
+ }
+ async function phase(spawn: typeof spawnWorker, fault: { point: FaultPoint; nth: number }) {
+ const scratch = mkdtempSync(join(tmpdir(), 'gbrain-crash-robot-fake-'));
+ try {
+ return await runRobotPhase({ engine: 'pglite', seed: 0, seconds: 0, scratch, home: scratch, databases: [],
+ spawn, track: () => {}, replay: [replayRun(fault)], log: () => {} });
+ } finally { rmSync(scratch, { recursive: true, force: true }); }
+ }
+ const clean = { result: { violations: [], deferred: [] } };
+
+ test('faultPoint hands the hook a Postgres bigserial effect id as its decimal string', async () => {
+ const seen: FaultDetail[] = [];
+ installFaultHook((_point, detail) => { seen.push(detail); });
+ try { await faultPoint('effect:git:mid', { effectId: 9007199254740993n, requestId: 'r1' }); }
+ finally { installFaultHook(undefined); }
+ expect(seen).toEqual([{ effectId: '9007199254740993', requestId: 'r1' }]);
+ });
+
+ async function hookChild(detail: string) {
+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-crash-robot-hook-'));
+ const path = join(dir, 'hook.ts');
+ writeFileSync(path, `import { faultPoint, installFaultHook } from ${JSON.stringify(join(import.meta.dir, '../src/core/persistence/fault-points.ts'))};
+import { robotFaultHook } from ${JSON.stringify(join(import.meta.dir, '../scripts/persistence/crash-robot.ts'))};
+installFaultHook(robotFaultHook({ point: 'effect:git:mid', nth: 2 }));
+await faultPoint('effect:git:mid', { effectId: 41n });
+${detail}
+process.stdout.write('{"event":"continued"}\\n');
+`);
+ const child = Bun.spawn([process.execPath, '--no-env-file', path], { stdin: 'ignore', stdout: 'pipe', stderr: 'pipe' });
+ const lines: Record<string, unknown>[] = [];
+ try {
+ const reader = child.stdout.getReader(); const decoder = new TextDecoder(); let pending = '';
+ const deadline = Date.now() + 60_000;
+ while (!lines.length && Date.now() < deadline) {
+ const chunk = await Promise.race([reader.read(), Bun.sleep(deadline - Date.now()).then(() => null)]);
+ if (!chunk || chunk.done) break;
+ pending += decoder.decode(chunk.value, { stream: true });
+ for (let newline = pending.indexOf('\n'); newline >= 0; newline = pending.indexOf('\n')) {
+ lines.push(JSON.parse(pending.slice(0, newline))); pending = pending.slice(newline + 1);
+ }
+ }
+ reader.releaseLock();
+ await Bun.sleep(500);
+ return { lines, alive: child.exitCode === null, stderr: child.exitCode === null ? '' : await new Response(child.stderr).text() };
+ } finally { child.kill('SIGKILL'); await child.exited; rmSync(dir, { recursive: true, force: true }); }
+ }
+
+ test('the run hook freezes at the requested seam with a BigInt effect id and reports it', async () => {
+ const { lines, alive, stderr } = await hookChild(`await faultPoint('effect:git:mid', { effectId: 42n, requestId: 'r1' });`);
+ expect({ lines, alive, stderr }).toEqual({ lines: [{ event: 'fault', point: 'effect:git:mid', nth: 2, detail: { effectId: '42', requestId: 'r1' } }], alive: true, stderr: '' });
+ }, 90_000);
+
+ test('a hook that cannot report its fault emits fault_hook_error and still freezes', async () => {
+ const { lines, alive } = await hookChild(`const cyclic: Record<string, unknown> = {}; cyclic.self = cyclic;
+await faultPoint('effect:git:mid', { requestId: 'r1', signal: cyclic as never });`);
+ expect(alive).toBe(true);
+ expect(lines).toHaveLength(1);
+ expect(lines[0]).toMatchObject({ event: 'fault_hook_error', point: 'effect:git:mid', nth: 2 });
+ expect(String(lines[0].message)).toMatch(/cyclic|circular/i);
+ }, 90_000);
+
+ test('a worker that finishes before its requested fault fails the run and the full gate', async () => {
+ const { spawn, spawned } = fakeSpawn([{ done: clean }]);
+ const robot = await phase(spawn, { point: 'effect:git:mid', nth: 1 });
+ expect(spawned.map(s => s.role)).toEqual(['run']);
+ expect(robot.runs[0]).toMatchObject({ crashed: false, fault_not_reached: true });
+ expect({ crashed: robot.crashed_runs, unreached: robot.faults_not_reached.length, failing: robot.failing_runs.length })
+ .toEqual({ crashed: 0, unreached: 1, failing: 1 });
+ expect(robotFullGate(robot, FULL_ROBOT_SECONDS)).toBe(false);
+ expect(robotFailure(robot.failing_runs, { engine: 'pglite' })).toContain('fault_not_reached');
+ });
+
+ test('a fault_hook_error kills the worker and fails the run and the full gate', async () => {
+ const { spawn, spawned } = fakeSpawn([{ fault_hook_error: { point: 'effect:git:mid', nth: 1, message: 'JSON.stringify cannot serialize BigInt.' } }]);
+ const robot = await phase(spawn, { point: 'effect:git:mid', nth: 1 });
+ expect(spawned).toEqual([{ role: 'run', killed: true }]);
+ expect(robot.fault_hook_errors.map(r => r.hook_error)).toEqual(['JSON.stringify cannot serialize BigInt.']);
+ expect(robot.failing_runs).toHaveLength(1);
+ expect(robotFullGate(robot, FULL_ROBOT_SECONDS)).toBe(false);
+ expect(robotFailure(robot.failing_runs, { engine: 'pglite' })).toContain('fault_hook_error: JSON.stringify cannot serialize BigInt.');
+ });
+
+ test('control: a reached fault that recovers cleanly keeps the full gate', async () => {
+ const { spawn, spawned } = fakeSpawn([{ fault: { point: 'effect:git:mid', nth: 1 } }, { done: clean }]);
+ const robot = await phase(spawn, { point: 'effect:git:mid', nth: 1 });
+ expect(spawned).toEqual([{ role: 'run', killed: true }, { role: 'recover', killed: false }]);
+ expect({ crashed: robot.crashed_runs, failing: robot.failing_runs.length }).toEqual({ crashed: 1, failing: 0 });
+ expect(robotFullGate(robot, FULL_ROBOT_SECONDS)).toBe(true);
+ });
+
+ test('validation exits nonzero when a replayed fault is never reached by a real worker', async () => {
+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-crash-robot-unreached-'));
+ try {
+ const manifest = join(dir, 'manifest.json');
+ writeFileSync(manifest, JSON.stringify({ engine: 'pglite', robot: { runs: [replayRun({ point: 'effect:git:mid', nth: 9999 })] } }));
+ const out = join(dir, 'out.json');
+ const error = await runValidation({ engine: 'pglite', replay: manifest, manifest: out }).then(() => null, (e: Error) => e);
+ expect(error?.message).toContain('fault_not_reached');
+ expect(JSON.parse(readFileSync(out, 'utf8'))).toMatchObject({ status: 'failed', full_gate: false });
+ rmSync(JSON.parse(readFileSync(`${out}.retained.json`, 'utf8')).scratch_root, { recursive: true, force: true });
+ } finally { rmSync(dir, { recursive: true, force: true }); }
+ }, 180_000);
+});