Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(crash-robot): run a fixed schedule list on every event, fail past a ceiling

garrytan79b9c075c289
diff --git a/.github/workflows/persistence-validation.yml b/.github/workflows/persistence-validation.yml
index 1693f7c301..9a28c1626a 100644
--- a/.github/workflows/persistence-validation.yml
+++ b/.github/workflows/persistence-validation.yml
@@ -371,18 +371,25 @@ jobs:
timeout-minutes: 8
run: bun scripts/ci-bun-install.ts --frozen-lockfile --ignore-scripts
# The service password reaches every client through PGPASSWORD, so the URLs carry none.
- # Named exception (docs/TESTING.md#event-parity): ROBOT_SECONDS is 150 on pull
- # requests and merge-queue runs; pushes to master, the nightly Test schedule and
- # manual runs cover the 600 s budget that crashes every seam.
+ # Every run executes a fixed schedule list (scripts/persistence/robot-driver.ts
+ # ROBOT_RANDOM_SEEDS), so a passed run of a tree stands for any run of it and a
+ # master push may reuse it. ROBOT_SECONDS is the ceiling a run fails past, sized
+ # on ubicloud-standard-4: 480 s on pull requests and merge-queue runs (named
+ # exception, docs/TESTING.md#event-parity: scope pr skips the Postgres
+ # lease-bound seams), 960 s PGLite and 1600 s Postgres elsewhere. The nightly
+ # Test schedule adds that day's exploration seeds.
- name: Crash every reachable seam of the generated sequences
env:
PGPASSWORD: gbrain_test
DATABASE_URL: postgres://[email protected]:5432/gbrain_test
GBRAIN_PGBOUNCER_URL: postgres://[email protected]:55433/gbrain_test
- ROBOT_SECONDS: ${{ (github.event_name == 'pull_request' || github.event_name == 'merge_group') && '150' || '600' }}
+ ROBOT_SCOPE: ${{ (github.event_name == 'pull_request' || github.event_name == 'merge_group') && 'pr' || 'full' }}
+ ROBOT_SECONDS: ${{ (github.event_name == 'pull_request' || github.event_name == 'merge_group') && '480' || (matrix.engine == 'postgres' && '1600' || '960') }}
+ ROBOT_EXPLORE: ${{ github.event_name == 'schedule' && 'nightly' || '' }}
run: >-
bun --no-env-file scripts/persistence/validate.ts --engine=${{ matrix.engine }}
- --schedules=0 --operations=0 --no-crashes --robot-seconds="$ROBOT_SECONDS"
+ --schedules=0 --operations=0 --no-crashes --robot-scope="$ROBOT_SCOPE" --robot-seconds="$ROBOT_SECONDS"
+ ${ROBOT_EXPLORE:+--explore-day=$(( $(date -u +%s) / 86400 ))}
--manifest=.context/persistence-robot.json
- name: Replay every shrunk crash-robot failure and the history fixture
timeout-minutes: 10
diff --git a/docs/architecture/key-files/tooling-and-tests.md b/docs/architecture/key-files/tooling-and-tests.md
index 1146fcee50..a22b923444 100644
--- a/docs/architecture/key-files/tooling-and-tests.md
+++ b/docs/architecture/key-files/tooling-and-tests.md
@@ -63,7 +63,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `scripts/persistence/{harness,schedules,worker,validate,failure-diagnostics}.ts` — executable concurrency gate using real journal/coordinator APIs: 1,000 seeded schedules per engine, eight actual process-kill publication boundaries, and 10,000 writes from four producer processes. Each phase owns a temporary disk PGLite datastore or a fresh test Postgres database. Independent accounting queries verify conservation; every soak receipt is compared to its canonical snapshot and file. JSON manifests separate actual counts and latency measurements from the configured Linux/Bun CI matrix. Failed runs preserve private fixtures and collect bounded, allowlisted request/queue/owner diagnostics without changing deadlines or hiding the original error. Cleanup commands read the existing test URL from the environment. The PGLite loopback endpoint is a fixture transport, not production authentication coverage. Contract and commands: `scripts/persistence/README.md`; smoke entries: `test/persistence-chaos.slow.test.ts`, `test/e2e/persistence-chaos.test.ts`; diagnostic/retention contracts: `test/persistence-failure-diagnostics.test.ts`.
-- `scripts/persistence/{ops,generator,model,crash-robot,robot-driver,shrink,lock-order,history-fixture,would-have-caught}.ts` — the crash robot, a phase of `validate.ts` (`--robot-seconds`, default 300; CI runs it as its own `persistence-validation.yml` job). `ops.ts` is the JSON op-descriptor protocol between driver and workers: each descriptor names an op kind (put/edit/delete/restore page, remember/forget, takes add/supersede, timeline add, sync, connector publish, revoke access), an actor (the local CLI principal or a remote agent whose bearer token the production `verifyAccessToken` resolves), a source, a fixed request id and arguments whose `{ $ref }` values come from earlier observations; workers run every op through its registered operation handler. Its `retryingRead` runs the robot's own reads across a session drop the `SessionDrops` ledger shows it injected (the pooler disconnect fault); any other closed connection fails the run. `generator.ts` builds seeded schedules: the fixed cross-boundary sequences (withdrawal then stale republication, overlapping slugs across two sources, competing writers, caller-bound replay, authority revoked with effects pending, sync and connector publish racing direct writes) plus random sequences with concurrent groups. `model.ts` is the temporal oracle: receipts and revisions at the observation point, legal later transitions, late receipts against page history, withdrawal permanence on recall/get_page/facts, source isolation, caller-bound replay, takes/facts fence projections, attribution, orphans, drain and wedge bounds; `EFFECT_SEAMS` maps every `EffectKind` to its trigger op and seam (typecheck-exhaustive). `crash-robot.ts` runs a schedule in-process or as a worker role (`count`, `run` frozen at a `fault-points.ts` seam and SIGKILLed by the driver, `recover`), plus process faults (stale `index.lock`, a hung git commit holding `index.lock`, Postgres session drops, the owner killed after a `facts-absorb` job's extraction commits and the job re-run). `robot-driver.ts` crashes every seam the fixed sequences reach, then fills the budget with random sequences; Postgres connects through `GBRAIN_PGBOUNCER_URL` when set and, under a budget below 300 s, skips the seams and the pooler disconnect fault that can wait out a dead owner's claim lease (`effect:*`, `consumer:prepared`, three publication seams), listed in the manifest as `lease_bound_seams_skipped` and `lease_bound_faults_skipped`. `shrink.ts` is dependency-preserving ddmin accepted on 3/3 reproduction; `--replay`/`--shrink` re-run a manifest's failing runs. `lock-order.ts` traces each transaction's row locks (worktrees before sources, sources by id, no exclusive brain lock in a publication). `history-fixture.ts` exports `buildHistoryFixture(engine, { pages, seed, sources, worktrees })` (a managed brain with real persistence history up to 10k pages, used by engine graduation and attribution backfill) and `prepareTopology`. `would-have-caught.ts` reverts each fix in `would-have-caught.json` in a scratch worktree and runs the pre-robot gate and the robot against it. Tests: `test/persistence-crash-robot.test.ts`, `test/persistence-crash-robot.slow.test.ts` (shrunk regressions in `test/fixtures/crash-robot/`), `test/persistence-history-fixture.test.ts`.
+- `scripts/persistence/{ops,generator,model,crash-robot,robot-driver,shrink,lock-order,history-fixture,would-have-caught}.ts` — the crash robot, a phase of `validate.ts` (`--robot-seconds` is a ceiling the run fails past, default 960 on PGLite and 1600 on Postgres; `--robot-scope=pr|full`; `--explore-day=<UTC day>` adds that night's exploration seeds; CI runs it as its own `persistence-validation.yml` job). `ops.ts` is the JSON op-descriptor protocol between driver and workers: each descriptor names an op kind (put/edit/delete/restore page, remember/forget, takes add/supersede, timeline add, sync, connector publish, revoke access), an actor (the local CLI principal or a remote agent whose bearer token the production `verifyAccessToken` resolves), a source, a fixed request id and arguments whose `{ $ref }` values come from earlier observations; workers run every op through its registered operation handler. Its `retryingRead` runs the robot's own reads across a session drop the `SessionDrops` ledger shows it injected (the pooler disconnect fault); any other closed connection fails the run. `generator.ts` builds seeded schedules: the fixed cross-boundary sequences (withdrawal then stale republication, overlapping slugs across two sources, competing writers, caller-bound replay, authority revoked with effects pending, sync and connector publish racing direct writes) plus random sequences with concurrent groups. `model.ts` is the temporal oracle: receipts and revisions at the observation point, legal later transitions, late receipts against page history, withdrawal permanence on recall/get_page/facts, source isolation, caller-bound replay, takes/facts fence projections, attribution, orphans, drain and wedge bounds; `EFFECT_SEAMS` maps every `EffectKind` to its trigger op and seam (typecheck-exhaustive). `crash-robot.ts` runs a schedule in-process or as a worker role (`count`, `run` frozen at a `fault-points.ts` seam and SIGKILLed by the driver, `recover`), plus process faults (stale `index.lock`, a hung git commit holding `index.lock`, Postgres session drops, the owner killed after a `facts-absorb` job's extraction commits and the job re-run). `robot-driver.ts` runs a fixed schedule list on every event, so a passed run of a tree stands for any run of it (master-push reuse): it crashes each seam the cross-boundary sequences reach (every seam of every sequence on a full PGLite run), then counts and crashes once each random sequence in `ROBOT_RANDOM_SEEDS` (5105–5109, 5113, 5115, 5116; Postgres avoids the lease-bound seams there), plus `explorationSeeds(day)` on the nightly (one of `ROBOT_ROTATION_SEEDS` 5110–5112, 5114 each night, and 5117 + day); the manifest's `over_budget` makes `validate.ts` fail past `--robot-seconds` instead of covering less. Postgres connects through `GBRAIN_PGBOUNCER_URL` when set and, in the `pr` scope, skips the seams and the pooler disconnect fault that can wait out a dead owner's claim lease (`effect:*`, `consumer:prepared`, three publication seams), listed in the manifest as `lease_bound_seams_skipped` and `lease_bound_faults_skipped`. `shrink.ts` is dependency-preserving ddmin accepted on 3/3 reproduction; `--replay`/`--shrink` re-run a manifest's failing runs. `lock-order.ts` traces each transaction's row locks (worktrees before sources, sources by id, no exclusive brain lock in a publication). `history-fixture.ts` exports `buildHistoryFixture(engine, { pages, seed, sources, worktrees })` (a managed brain with real persistence history up to 10k pages, used by engine graduation and attribution backfill) and `prepareTopology`. `would-have-caught.ts` reverts each fix in `would-have-caught.json` in a scratch worktree and runs the pre-robot gate and the robot against it. Tests: `test/persistence-crash-robot.test.ts`, `test/persistence-crash-robot.slow.test.ts` (shrunk regressions in `test/fixtures/crash-robot/`), `test/persistence-history-fixture.test.ts`.
- `scripts/persistence/{graduation-fixture,graduation-process,graduation-ttv}.ts` — engine graduation test inputs and measurements. `graduation-fixture.ts` builds the 1k/10k history brains (`buildHistoryFixture` plus deterministic chunk vectors) or the hand-built legacy brain (`test/fixtures/graduation/`) in a keyless child process, caches each as a tarball keyed by its source files, schema version, seed and size, and re-homes a restore (database paths, managed-root records, owner stamps re-stamped with the new inode and birth time; sources marked synced). Its report lists bytes, chunks, versions, requests, effects and embeddings. `graduation-process.ts` spawns the real CLI or an older release with an isolated home and no provider keys, with optional boundary hooks, plus MCP stdio/HTTP clients and the JSON contract accessors. `graduation-ttv.ts` times plan to green doctor (five-minute gate at 1k pages; exit 1 under `--enforce`, 3 on a harness crash). Owners: `test/scripts/graduation-fixture.test.ts`, `test/graduation-legacy-fixture.test.ts`, `test/e2e/graduation-{crash,faults,clients,cli}.test.ts`, `tests/heavy/graduation_10k.sh`.
diff --git a/docs/ci-event-parity.md b/docs/ci-event-parity.md
index f6a1ae1a4b..336232541c 100644
--- a/docs/ci-event-parity.md
+++ b/docs/ci-event-parity.md
@@ -33,7 +33,7 @@ checks ([below](#full-ci-on-pull-requests)), never per-cell matrix names.
| `persistence-validation.yml` | `convergence` selected on pull requests by `scripts/ci-convergence-scope.sh` (test.yml `changes`; never by `package.json` alone) | Named exception | Every merge-queue run and every push to master; the nightly cell runs in `convergence-nightly.yml` |
| `convergence-nightly.yml` | The convergence gate's nightly cell (2,000 pages, 50 ms, 20 kills, run-id seed): schedule and dispatch only, outside `test-status`; the PR cell (200 pages, 10 ms, 6 kills, seed 6650) runs in `persistence-validation.yml` | Named exception | Itself (nightly Convergence schedule) |
| `persistence-validation.yml` | `SOAK_OPERATIONS` 2,500 vs 10,000 | Named exception | Every push to master and the nightly Test schedule |
-| `persistence-validation.yml` | `ROBOT_SECONDS` 150 vs 600 | Named exception | Every push to master and the nightly Test schedule |
+| `persistence-validation.yml` | Crash robot `--robot-scope=pr` (Postgres lease-bound seams skipped, 480 s ceiling) vs `full` (960 s PGLite, 1600 s Postgres); the nightly adds that day's exploration seeds | Named exception | The full-ci dispatch, every push to master (same fixed list, so it may reuse that run) and the nightly Test schedule |
| `native-locks.yml` | `inputs.scope` (OpenClaw, musl, Windows probes, Bun 1.4.0 and cross-target cells) | Named exception | Every push to master and the nightly Test schedule (`full`) |
| `e2e.yml` | Doc-only merge-queue entry selects no E2E file | Named exception | Every push to master (whole corpus) and the nightly E2E schedule |
| `e2e.yml` | Full-corpus coverage lanes and their `e2e-status` checks | Named exception | Nightly E2E schedule (or a `full_corpus` dispatch) |
diff --git a/scripts/persistence/robot-driver.ts b/scripts/persistence/robot-driver.ts
index 6dad276bae..ca09325cd6 100644
--- a/scripts/persistence/robot-driver.ts
+++ b/scripts/persistence/robot-driver.ts
@@ -1,7 +1,7 @@
/**
* Driver for the crash robot phase of the persistence gate. For each
- * schedule (the cross-boundary sequences first, then seeded random
- * sequences until the time budget runs out) it runs a counting pass that
+ * schedule (the cross-boundary sequences first, then the fixed list of seeded
+ * random sequences, ROBOT_RANDOM_SEEDS plus any exploration seeds) it runs a counting pass that
* finds every seam the schedule reaches, then one process-separated run per
* chosen crash point: a worker freezes at the seam, the driver SIGKILLs it,
* and a fresh worker recovers, resubmits the interrupted requests and
@@ -29,11 +29,24 @@ export const PROCESS_FAULTS: ProcessFault[] = ['stale_index_lock', 'hung_git', '
* owner's claim lease (requests 30 s, effects 2 minutes): a publication seam
* does when the dead owner also held an effect claim, and the pooler
* disconnect fault holds its run for about two minutes. A Postgres run with a
- * budget under FULL_ROBOT_SECONDS skips them and lists them in the manifest
+ * run of the `pr` scope skips them and lists them in the manifest
* (`lease_bound_seams_skipped`, `lease_bound_faults_skipped`); full runs
* (master, nightly, manual) crash every seam and run every fault.
*/
-export const FULL_ROBOT_SECONDS = 300;
+export type RobotScope = 'pr' | 'full';
+/**
+ * The random sequences every run executes, whatever its event, so two runs of
+ * one tree cover the same schedules and a passed run can be reused for an
+ * identical tree. 5108, 5109, 5113, 5115 and 5116 are the shrunk
+ * fence_absent fixtures of #7435.
+ */
+export const ROBOT_RANDOM_SEEDS: readonly number[] = [5105, 5106, 5107, 5108, 5109, 5113, 5115, 5116];
+/** Seeds from 5109 to 5116 not in ROBOT_RANDOM_SEEDS: the nightly runs one of them each night. */
+export const ROBOT_ROTATION_SEEDS: readonly number[] = [5110, 5111, 5112, 5114];
+/** The nightly's exploration seeds for a UTC day number: one rotation seed (each within four nights) and one never run before. */
+export function explorationSeeds(day: number): number[] {
+ return [ROBOT_ROTATION_SEEDS[day % ROBOT_ROTATION_SEEDS.length]!, 5117 + day];
+}
const LEASE_BOUND_PUBLICATION_SEAMS: readonly FaultPoint[] = ['publication:prepared', 'publication:before_publication', 'publication:after_publication'];
export function leaseBoundSeam(point: FaultPoint): boolean {
return point.startsWith('effect:') || point === 'consumer:prepared' || LEASE_BOUND_PUBLICATION_SEAMS.includes(point);
@@ -64,7 +77,12 @@ 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 {
+ /** `seconds` is the ceiling: a run past it is reported `over_budget`. */
engine: 'pglite' | 'postgres'; seed: number; seconds: number; scratch: string; home: string;
+ /** `full` (default) crashes every seam; `pr` skips the Postgres lease-bound ones. */
+ scope?: RobotScope;
+ /** Random seeds run after ROBOT_RANDOM_SEEDS (the nightly's explorationSeeds). */
+ extraSeeds?: readonly number[];
admin?: ReturnType<typeof postgres>; databaseUrl?: string; databases: string[];
/** A transaction-mode PgBouncer URL: Postgres workers then connect through it (prepared statements off). */
pooledUrl?: string;
@@ -170,13 +188,14 @@ export async function runRobotPhase(o: RobotOptions) {
}
const rand = random(o.seed);
- const budgetMs = o.seconds * 1000;
- const over = () => performance.now() - started > budgetMs;
+ const scope = o.scope ?? 'full';
// Every cross-boundary sequence runs uncrashed, then each seam it reaches is crashed once,
// seams first covered across sequences (a seam no run has crashed yet goes first).
const fixed = crossBoundarySequences(ROBOT_TOPOLOGY, o.seed);
const plan: { schedule: Schedule; point: FaultPoint; count: number }[] = [];
- const skipLease = o.engine === 'postgres' && o.seconds < FULL_ROBOT_SECONDS;
+ const skipLease = o.engine === 'postgres' && scope === 'pr';
+ // A full PGLite run crashes every seam of every sequence; Postgres and pull requests crash each seam once.
+ const everySeam = scope === 'full' && o.engine === 'pglite';
const skipped = new Set<string>();
for (const schedule of fixed) {
const counted = await execute(schedule, 'count'); record(counted);
@@ -190,9 +209,7 @@ export async function runRobotPhase(o: RobotOptions) {
plan.sort((x, y) => x.point.localeCompare(y.point) || turn(x) - turn(y));
const firsts = plan.filter((x, i) => plan.findIndex(y => y.point === x.point) === i);
const ordered = [...firsts, ...plan.filter(x => !firsts.includes(x))];
- for (const [i, item] of ordered.entries()) {
- const mandatory = i < firsts.length;
- if (!mandatory && over()) break;
+ for (const item of everySeam ? ordered : firsts) {
record(await execute(item.schedule, 'run', { fault: { point: item.point, nth: 1 + Math.floor(rand() * item.count) } }));
}
const skippedFaults = new Set<ProcessFault>();
@@ -204,16 +221,19 @@ export async function runRobotPhase(o: RobotOptions) {
// serve killed right after the facts-absorb job's extraction commits; the job then runs again.
record(await execute({ ...fixed[1], ops: [], groups: [] }, 'run', { process: 'facts_absorb_kill',
fault: { point: 'publication:after_commit', nth: 1, operation: 'extract_facts' } }));
- // Random sequences fill the rest of the budget.
- for (let i = 0; !over(); i++) {
- const schedule = randomSchedule(ROBOT_TOPOLOGY, (o.seed + 1 + i) >>> 0, 24);
+ // The fixed random sequences, each counted and crashed once. On Postgres the crash avoids the lease-bound
+ // seams: the cross-boundary sequences already crash each of them once.
+ for (const seed of [...ROBOT_RANDOM_SEEDS, ...(o.extraSeeds ?? [])]) {
+ const schedule = randomSchedule(ROBOT_TOPOLOGY, seed >>> 0, 24);
const counted = await execute(schedule, 'count'); record(counted);
- const points = (Object.entries(counted.counts ?? {}) as [FaultPoint, number][]).filter(([point]) => !(skipLease && leaseBoundSeam(point)));
- if (!points.length || over()) continue;
+ const points = (Object.entries(counted.counts ?? {}) as [FaultPoint, number][]).filter(([point]) => !(o.engine === 'postgres' && leaseBoundSeam(point)));
+ if (!points.length) continue;
const [point, count] = points[Math.floor(rand() * points.length)];
record(await execute(schedule, 'run', { fault: { point, nth: 1 + Math.floor(rand() * count) } }));
}
- return { ...summarize(runs, started, o), lease_bound_seams_skipped: [...skipped].sort(), lease_bound_faults_skipped: [...skippedFaults].sort() };
+ const summary = summarize(runs, started, o);
+ return { ...summary, scope, over_budget: o.seconds > 0 && summary.duration_ms > o.seconds * 1000,
+ lease_bound_seams_skipped: [...skipped].sort(), lease_bound_faults_skipped: [...skippedFaults].sort() };
}
function summarize(runs: RobotRun[], started: number, o: RobotOptions) {
diff --git a/scripts/persistence/validate.ts b/scripts/persistence/validate.ts
index a2edd3c05f..8288595935 100644
--- a/scripts/persistence/validate.ts
+++ b/scripts/persistence/validate.ts
@@ -8,14 +8,18 @@ import { assertSafeE2eDatabaseUrl } from '../../test/helpers/db-guard.ts';
import { distribution, type HarnessConfig } from './harness.ts';
import { keylessBrainEnv } from '../../test/helpers/provider-env.ts';
import { boundedDiagnostic, connectionDiagnostic, diagnosticError, retentionMetadata } from './failure-diagnostics.ts';
-import { FULL_ROBOT_SECONDS, replayEntries, runDigest, runRobotPhase, type RobotRun } from './robot-driver.ts';
+import { explorationSeeds, replayEntries, runDigest, runRobotPhase, type RobotRun, type RobotScope } from './robot-driver.ts';
import { shrinkRun } from './shrink.ts';
export interface ValidationOptions {
engine: 'pglite' | 'postgres'; schedules?: number; operations?: number; seed?: number;
crashes?: boolean; databaseUrl?: string; manifest?: string;
- /** Crash-robot time budget in seconds; omitted or 0 skips the phase (the CLI defaults to 300). */
+ /** Crash-robot ceiling in seconds: a run past it fails; omitted or 0 skips the phase (the CLI defaults to 960 on PGLite, 1600 on Postgres). */
robotSeconds?: number;
+ /** `pr` skips the Postgres lease-bound seams; `full` (default) crashes every seam. */
+ robotScope?: RobotScope;
+ /** A UTC day number: the robot also runs that day's explorationSeeds (the nightly). */
+ exploreDay?: number;
/** Re-run a recorded manifest's failing crash-robot runs (and nothing else). */
replay?: string;
/** Shrink the first failing crash-robot run of a manifest to a minimal reproducing sequence. */
@@ -68,12 +72,19 @@ export function spawnWorker(configPath: string, home: string, role: string, args
/** 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
+ & { lease_bound_seams_skipped?: string[]; lease_bound_faults_skipped?: string[] }, scope: RobotScope): boolean {
+ return scope === 'full' && 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;
}
+/** A run past its ceiling: the fixed schedule list no longer fits this runner class, so the gate fails instead of covering less. */
+export function robotOverBudget(durationMs: number, seconds: number): string {
+ return `Crash robot over its ceiling: ran ${Math.round(durationMs / 1000)} s against --robot-seconds=${seconds}. Why: every run executes the same `
+ + 'schedule list (scripts/persistence/robot-driver.ts ROBOT_RANDOM_SEEDS) so a passed run of a tree can be reused; past the ceiling the list '
+ + 'no longer fits this runner class. Fix: find the slow runs in the manifest; speed them up, or resize the list and the ceiling together.';
+}
+
/** 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`;
@@ -132,7 +143,8 @@ export async function runValidation(options: ValidationOptions) {
}
function start(path: string, role: string, ...args: string[]) { const child = spawnWorker(path, home, role, args); children.push(child); return child; }
const robotOptions = (extra: Partial<Parameters<typeof runRobotPhase>[0]> = {}) => ({ engine: options.engine, seed: options.seed ?? 5105,
- seconds: options.robotSeconds ?? 0, scratch, home, admin, databaseUrl: options.databaseUrl, databases,
+ seconds: options.robotSeconds ?? 0, scope: options.robotScope ?? 'full',
+ extraSeeds: options.exploreDay === undefined ? [] : explorationSeeds(options.exploreDay), scratch, home, admin, databaseUrl: options.databaseUrl, databases,
pooledUrl: options.engine === 'postgres' ? process.env.GBRAIN_PGBOUNCER_URL || undefined : undefined,
spawn: spawnWorker, track: (child: ReturnType<typeof spawnWorker>) => { children.push(child); }, ...extra });
if (options.replay || options.shrink) {
@@ -155,6 +167,7 @@ export async function runValidation(options: ValidationOptions) {
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.failing_runs.length) throw new Error(robotFailure(manifest.robot.failing_runs, options));
+ if (manifest.robot.over_budget) throw new Error(robotOverBudget(manifest.robot.duration_ms, options.robotSeconds));
}
if (options.crashes !== false) for (const boundary of CRASH_BOUNDARIES) {
const { path } = await phase(`crash-${boundary}`); const requestId = randomUUID();
@@ -204,7 +217,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 = robotFullGate(manifest.robot, options.robotSeconds ?? 0);
+ if (manifest.robot) manifest.robot_full_gate = robotFullGate(manifest.robot, options.robotScope ?? 'full');
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)
@@ -264,11 +277,13 @@ export async function runValidation(options: ValidationOptions) {
}
if (import.meta.main) {
const args = new Map(process.argv.slice(2).map(arg => { const [key, ...value] = arg.replace(/^--/, '').split('='); return [key, value.join('=')]; }));
- for (const key of args.keys()) assert(['engine', 'schedules', 'operations', 'seed', 'no-crashes', 'manifest', 'robot-seconds', 'replay', 'shrink'].includes(key), `Unknown option: ${key}`);
+ for (const key of args.keys()) assert(['engine', 'schedules', 'operations', 'seed', 'no-crashes', 'manifest', 'robot-seconds', 'robot-scope', 'explore-day', 'replay', 'shrink'].includes(key), `Unknown option: ${key}`);
const engine = args.get('engine') ?? 'pglite'; assert(engine === 'pglite' || engine === 'postgres');
+ assert(['pr', 'full'].includes(args.get('robot-scope') ?? 'full'), '--robot-scope is pr or full');
const result = await runValidation({ engine, schedules: Number(args.get('schedules') ?? 1000), operations: Number(args.get('operations') ?? 10_000),
seed: Number(args.get('seed') ?? 5105), crashes: !args.has('no-crashes'), databaseUrl: process.env.DATABASE_URL,
- robotSeconds: Number(args.get('robot-seconds') ?? 300), replay: args.get('replay') || undefined, shrink: args.get('shrink') || undefined,
+ robotSeconds: Number(args.get('robot-seconds') ?? (engine === 'postgres' ? 1600 : 960)),
+ robotScope: (args.get('robot-scope') ?? 'full') as RobotScope, exploreDay: args.has('explore-day') ? Number(args.get('explore-day')) : undefined, replay: args.get('replay') || undefined, shrink: args.get('shrink') || undefined,
manifest: args.get('manifest') ?? `.context/persistence-${engine}-manifest.json` });
process.stdout.write(`${JSON.stringify(result, null, 2)}\n`);
}
diff --git a/test/persistence-crash-robot.test.ts b/test/persistence-crash-robot.test.ts
index 0674f1bcfd..f92c21fa51 100644
--- a/test/persistence-crash-robot.test.ts
+++ b/test/persistence-crash-robot.test.ts
@@ -20,8 +20,8 @@ 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 { 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 { ROBOT_RANDOM_SEEDS, ROBOT_ROTATION_SEEDS, ROBOT_TOPOLOGY, explorationSeeds, restrict, runRobotPhase, type RobotRun } from '../scripts/persistence/robot-driver.ts';
+import { robotFailure, robotFullGate, robotOverBudget, 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 { finish, fixedChunks, LEVEL_CHUNK_BYTES, runSchedule, runSteps, seamCounter } from '../scripts/persistence/crash-robot.ts';
@@ -542,7 +542,7 @@ await faultPoint('effect:git:mid', { requestId: 'r1', signal: cyclic as never })
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(robotFullGate(robot, 'full')).toBe(false);
expect(robotFailure(robot.failing_runs, { engine: 'pglite' })).toContain('fault_not_reached');
});
@@ -552,7 +552,7 @@ await faultPoint('effect:git:mid', { requestId: 'r1', signal: cyclic as never })
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(robotFullGate(robot, 'full')).toBe(false);
expect(robotFailure(robot.failing_runs, { engine: 'pglite' })).toContain('fault_hook_error: JSON.stringify cannot serialize BigInt.');
});
@@ -561,7 +561,7 @@ await faultPoint('effect:git:mid', { requestId: 'r1', signal: cyclic as never })
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);
+ expect(robotFullGate(robot, 'full')).toBe(true);
});
test('validation exits nonzero when a replayed fault is never reached by a real worker', async () => {
@@ -577,3 +577,64 @@ await faultPoint('effect:git:mid', { requestId: 'r1', signal: cyclic as never })
} finally { rmSync(dir, { recursive: true, force: true }); }
}, 180_000);
});
+
+describe('every robot run covers a fixed schedule list (reuse of a passed run is sound)', () => {
+ const COUNTS = { 'consumer:claiming': 2, 'effect:git:mid': 1 };
+ const clean = { violations: [], deferred: [] };
+ async function plan(o: { engine?: 'pglite' | 'postgres'; seconds: number; scope?: 'pr' | 'full'; extraSeeds?: number[] }) {
+ const scratch = mkdtempSync(join(tmpdir(), 'gbrain-crash-robot-plan-'));
+ const calls: { schedule: string; role: string; point?: string; process?: string }[] = [];
+ const spawn = ((path: string, _home: string, _mode: string, [role]: string[]) => {
+ const config = JSON.parse(readFileSync(path, 'utf8'));
+ calls.push({ schedule: config.schedule.label, role, ...(config.fault ? { point: config.fault.point } : {}), ...(config.process ? { process: config.process } : {}) });
+ const events: Record<string, unknown> = role === 'count' ? { done: { result: { ...clean, counts: COUNTS } } }
+ : role === 'run' && config.fault ? { fault: config.fault } : { done: { result: clean } };
+ const event = (name: string) => name in events ? Promise.resolve({ event: name, ...(events[name] as object) }) : new Promise<never>(() => {});
+ return { child: { pid: 0 }, event, done: () => event('done'), failureDiagnostics: () => [], async kill() {} };
+ }) as unknown as typeof spawnWorker;
+ try {
+ const robot = await runRobotPhase({ engine: o.engine ?? 'pglite', seed: 0, seconds: o.seconds, scope: o.scope, extraSeeds: o.extraSeeds,
+ scratch, home: scratch, databases: [], spawn, track: () => {}, log: () => {} });
+ return { robot, calls };
+ } finally { rmSync(scratch, { recursive: true, force: true }); }
+ }
+ const randomLabels = (calls: { schedule: string; role: string }[]) => [...new Set(calls.filter(c => c.schedule.startsWith('random-')).map(c => c.schedule))];
+
+ test('the random sequences are ROBOT_RANDOM_SEEDS, each counted and crashed (and recovered) once, whatever the ceiling', async () => {
+ const short = await plan({ seconds: 1 });
+ const long = await plan({ seconds: 600 });
+ expect(randomLabels(short.calls)).toEqual(ROBOT_RANDOM_SEEDS.map(seed => `random-${seed}`));
+ expect(short.calls).toEqual(long.calls);
+ for (const label of randomLabels(short.calls)) expect(short.calls.filter(c => c.schedule === label).map(c => c.role)).toEqual(['count', 'run', 'recover']);
+ });
+
+ test('a full PGLite run crashes every seam of every sequence; a pr run and Postgres crash each seam once', async () => {
+ const fixed = crossBoundarySequences(ROBOT_TOPOLOGY, 0).map(s => s.label);
+ const fixedCrashes = (calls: { schedule: string; role: string; point?: string; process?: string }[]) => calls.filter(c => fixed.includes(c.schedule) && c.role === 'run' && c.point && !c.process);
+ expect(fixedCrashes((await plan({ seconds: 1 })).calls)).toHaveLength(fixed.length * Object.keys(COUNTS).length);
+ expect(fixedCrashes((await plan({ seconds: 1, scope: 'pr' })).calls)).toHaveLength(Object.keys(COUNTS).length);
+ expect(fixedCrashes((await plan({ engine: 'postgres', seconds: 1 })).calls)).toHaveLength(Object.keys(COUNTS).length);
+ });
+
+ test('Postgres random crashes avoid the lease-bound seams; a pr run skips them in the fixed sequences', async () => {
+ const full = await plan({ engine: 'postgres', seconds: 1 });
+ expect(full.calls.filter(c => c.schedule.startsWith('random-') && c.role === 'run').map(c => c.point)).toEqual(ROBOT_RANDOM_SEEDS.map(() => 'consumer:claiming'));
+ expect((full.robot as { lease_bound_seams_skipped?: string[] }).lease_bound_seams_skipped).toEqual([]);
+ expect(((await plan({ engine: 'postgres', seconds: 1, scope: 'pr' })).robot as { lease_bound_seams_skipped?: string[] }).lease_bound_seams_skipped).toEqual(['effect:git:mid']);
+ });
+
+ test('a run past its ceiling is over_budget, and validation fails it loudly', async () => {
+ expect((await plan({ seconds: 0.001 })).robot).toMatchObject({ over_budget: true });
+ expect((await plan({ seconds: 600 })).robot).toMatchObject({ over_budget: false });
+ expect(robotOverBudget(1_234_000, 960)).toMatch(/over its ceiling: ran 1234 s against --robot-seconds=960/);
+ });
+
+ test('the nightly adds one rotation seed (each within four nights) and one never-run seed after the fixed list', async () => {
+ const days = [0, 1, 2, 3].map(d => explorationSeeds(20_000 + d));
+ expect(new Set(days.map(([rotation]) => rotation))).toEqual(new Set(ROBOT_ROTATION_SEEDS));
+ expect(new Set(days.map(([, fresh]) => fresh)).size).toBe(4);
+ for (const [, fresh] of days) expect(fresh).toBeGreaterThan(Math.max(...ROBOT_RANDOM_SEEDS, ...ROBOT_ROTATION_SEEDS));
+ const { calls } = await plan({ seconds: 1, extraSeeds: days[0] });
+ expect(randomLabels(calls)).toEqual([...ROBOT_RANDOM_SEEDS, ...days[0]!].map(seed => `random-${seed}`));
+ });
+});
diff --git a/test/scripts/data-safety-native-workflow.test.ts b/test/scripts/data-safety-native-workflow.test.ts
index eac0825565..355503ce5f 100644
--- a/test/scripts/data-safety-native-workflow.test.ts
+++ b/test/scripts/data-safety-native-workflow.test.ts
@@ -310,20 +310,27 @@ describe('data-safety native CI coverage', () => {
}
});
- test('the crash robot runs beside the soak: 150 s on pull requests, 600 s elsewhere, Postgres through PgBouncer', () => {
+ test('the crash robot runs a fixed list beside the soak: scope pr under 480 s on pull requests, full under 960/1600 s elsewhere, exploration nightly, Postgres through PgBouncer', () => {
const persistence = load(readFileSync(join(import.meta.dir, '../../.github/workflows/persistence-validation.yml'), 'utf8')) as {
jobs: { 'crash-robot': { steps: Step[]; services: Record<string, { env?: Record<string, string> }> } };
};
const job = persistence.jobs['crash-robot'];
expect(job.services.pgbouncer?.env?.POOL_MODE).toBe('transaction');
const step = job.steps.find(entry => entry.run?.includes('scripts/persistence/validate.ts'));
- expect(step?.env?.ROBOT_SECONDS).toBe("${{ (github.event_name == 'pull_request' || github.event_name == 'merge_group') && '150' || '600' }}");
+ expect(step?.env?.ROBOT_SCOPE).toBe("${{ (github.event_name == 'pull_request' || github.event_name == 'merge_group') && 'pr' || 'full' }}");
+ expect(step?.env?.ROBOT_SECONDS).toBe("${{ (github.event_name == 'pull_request' || github.event_name == 'merge_group') && '480' || (matrix.engine == 'postgres' && '1600' || '960') }}");
+ expect(step?.env?.ROBOT_EXPLORE).toBe("${{ github.event_name == 'schedule' && 'nightly' || '' }}");
expect(step?.env?.GBRAIN_PGBOUNCER_URL).toContain(':55433/');
- const result = Bun.spawnSync(['bash', '-e', '-o', 'pipefail', '-c', `
+ const argv = (env: Record<string, string>) => Bun.spawnSync(['bash', '-e', '-o', 'pipefail', '-c', `
bun() { printf '%s\\n' "$@"; }
${step!.run!.replaceAll('${{ matrix.engine }}', 'postgres')}
- `], { env: { PATH: process.env.PATH ?? '', ROBOT_SECONDS: '150' } });
- expect(result.stdout.toString().trim().split('\n')).toEqual(['--no-env-file', 'scripts/persistence/validate.ts', '--engine=postgres',
- '--schedules=0', '--operations=0', '--no-crashes', '--robot-seconds=150', '--manifest=.context/persistence-robot.json']);
+ `], { env: { PATH: process.env.PATH ?? '', ...env } }).stdout.toString().trim().split('\n');
+ const head = ['--no-env-file', 'scripts/persistence/validate.ts', '--engine=postgres', '--schedules=0', '--operations=0', '--no-crashes'];
+ expect(argv({ ROBOT_SCOPE: 'pr', ROBOT_SECONDS: '480', ROBOT_EXPLORE: '' })).toEqual([...head, '--robot-scope=pr', '--robot-seconds=480',
+ '--manifest=.context/persistence-robot.json']);
+ const nightly = argv({ ROBOT_SCOPE: 'full', ROBOT_SECONDS: '1600', ROBOT_EXPLORE: 'nightly' });
+ expect(nightly.slice(0, -2)).toEqual([...head, '--robot-scope=full', '--robot-seconds=1600']);
+ expect(nightly.at(-2)).toBe(`--explore-day=${Math.floor(Date.now() / 86_400_000)}`);
+ expect(nightly.at(-1)).toBe('--manifest=.context/persistence-robot.json');
});
});