Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(persistence-gate): sync and connector ops, PgBouncer route, process faults, would-have-caught runner

garrytan94c8d1c182f0
diff --git a/scripts/persistence/crash-robot.ts b/scripts/persistence/crash-robot.ts
index b33ea273c6..c5638737a7 100644
--- a/scripts/persistence/crash-robot.ts
+++ b/scripts/persistence/crash-robot.ts
@@ -17,6 +17,7 @@ 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 { assertSafeE2eDatabaseUrl } from '../../test/helpers/db-guard.ts';
+import postgres from '#postgres';
import { prepareTopology } from './history-fixture.ts';
import { executeOp, type OpDescriptor, type OpObservation, type World } from './ops.ts';
import { ReferenceModel, SAFETY_CLASSES, type Violation } from './model.ts';
@@ -28,11 +29,13 @@ import { randomUUID } from 'node:crypto';
export interface ScheduleResult { label: string; seed: number; steps: number; violations: Violation[]; safety: Violation[]; observations: OpObservation[] }
/**
- * How long a drain may take before the robot calls it a wedge. Every claim a
- * dead owner left behind must be resumable well inside this bound; a lease
- * that only expires later (requests 30 s, effects 2 min) is reported.
+ * How long a drain may take before the robot calls it a wedge. On PGLite a
+ * restarted owner proves its predecessor exited (one process per datastore),
+ * so every claim must resume within 20 s. Postgres owners run concurrently and
+ * wait out a dead owner's claim lease (requests 30 s, effects 2 minutes), so
+ * the bound there is the effect lease plus margin.
*/
-export const DRAIN_BOUND_MS = 20_000;
+export const DRAIN_BOUND_MS = { pglite: 20_000, postgres: 140_000 } as const;
/** Wait until no request is pending and no effect is runnable; false when the bound passes (a wedge). */
export async function drain(engine: BrainEngine, world: World, timeoutMs = 60_000): Promise<boolean> {
@@ -76,16 +79,18 @@ export async function runSteps(world: World, model: ReferenceModel, schedule: Sc
export async function settlePending(world: World, model: ReferenceModel): Promise<void> {
const pending = [...model.pending.values()];
if (!pending.length) return;
- model.beginStep(false);
+ model.beginStep(true);
+ const observed: OpObservation[] = [];
for (const d of pending) {
- const seen = await executeOp(world, d);
+ const seen = await executeOp(world, d); observed.push(seen);
await model.observe({ ...d, replayOf: undefined }, seen);
if (seen.status === 'pending') model.violate({ class: 'wedge', op: d.id, detail: `request ${d.requestId} still pending after the drain` });
}
+ await model.settleLate(pending, observed);
}
/** Finish a schedule: drain, check drained invariants, prove a fresh write still admits. */
-export async function finish(world: World, model: ReferenceModel, label: string, drainMs = DRAIN_BOUND_MS): Promise<void> {
+export async function finish(world: World, model: ReferenceModel, label: string, drainMs: number = DRAIN_BOUND_MS[world.engine.kind]): Promise<void> {
const drained = await drain(world.engine, world, drainMs);
if (!drained) model.violate({ class: 'wedge', detail: `${label}: requests or effects did not drain within ${drainMs / 1000} s` });
await settlePending(world, model);
@@ -111,24 +116,28 @@ export async function runSchedule(world: World, schedule: Schedule): Promise<Sch
/* Process-separated crash mode: the worker side. */
/* ------------------------------------------------------------------------ */
-export type ProcessFault = 'stale_index_lock' | 'hung_git';
+export type ProcessFault = 'stale_index_lock' | 'hung_git' | 'pooler_disconnect';
export interface RobotConfig {
kind: 'pglite' | 'postgres'; root: string; dataDir: string; databaseUrl?: string;
+ /** Direct (unpooled) URL of the run database, for administrative fault injection. */
+ directUrl?: string;
schedule: Schedule; worktrees: number; statePath: string;
/** SIGKILL at the nth time this seam is reached (1-based). */
fault?: { point: FaultPoint; nth: number };
process?: ProcessFault;
}
interface RobotState {
- remotes: World['remotes']; checkouts: string[]; next: number; inFlight: string[];
+ remotes: World['remotes']; checkouts: string[]; roots?: World['roots']; connector?: World['connector']; next: number; inFlight: string[];
model: Record<string, unknown>; observations: [string, OpObservation][]; submitted: [string, Record<string, unknown>][];
}
export interface RobotOutcome extends Omit<ScheduleResult, 'observations'> {
crashed: boolean; fault?: RobotConfig['fault']; process?: ProcessFault; counts?: Record<string, number>; inFlight?: string[];
+ /** What each caller observed, kept only for a run with violations. */
+ trace?: string[];
}
function writeState(config: RobotConfig, world: World, model: ReferenceModel, checkouts: string[], next: number, inFlight: string[]): void {
- const state: RobotState = { remotes: world.remotes, checkouts, next, inFlight, model: model.toJSON(),
+ const state: RobotState = { remotes: world.remotes, checkouts, roots: world.roots, connector: world.connector, next, inFlight, model: model.toJSON(),
observations: [...world.observations], submitted: [...(world.submitted ?? [])] };
const staged = `${config.statePath}.tmp`;
writeFileSync(staged, JSON.stringify(state), { mode: 0o600 }); renameSync(staged, config.statePath);
@@ -153,15 +162,32 @@ function freeze(event: Record<string, unknown>): never {
}
function finalize(config: RobotConfig, model: ReferenceModel, extra: Partial<RobotOutcome>): RobotOutcome {
+ const trace = model.violations.length ? [...model.world.observations.values()].map(o =>
+ `${o.id} ${o.kind} ${o.actor}@${o.source} ${o.status}${o.code ? `/${o.code}` : ''}${o.values.revision ? ` rev=${o.values.revision}` : ''}`
+ + `${o.receipt ? ` receipt=${o.receipt.state}` : ''}${o.status === 'refused' ? ` ${JSON.stringify(o.raw).slice(0, 300)}` : ''}`) : undefined;
return { label: config.schedule.label, seed: config.schedule.seed, steps: config.schedule.ops.length, crashed: false,
- violations: model.violations, safety: model.violations.filter(v => SAFETY_CLASSES.has(v.class)), ...extra };
+ violations: model.violations, safety: model.violations.filter(v => SAFETY_CLASSES.has(v.class)), ...extra, ...(trace ? { trace } : {}) };
}
-/** A git shim that hangs `git commit` while the marker file exists (a stuck child, never answering). */
+/**
+ * A git shim whose `git commit` hangs while the marker file exists, holding the
+ * checkout's index.lock the way a real stuck git does: SIGTERM lets it remove
+ * its lock and exit, SIGKILL leaves the lock behind.
+ */
function installHungGit(root: string): { marker: string; release(): void } {
const dir = join(root, 'hung-git-bin'); mkdirSync(dir, { recursive: true });
const real = Bun.which('git')!; const marker = join(root, 'hung-git.marker');
- writeFileSync(join(dir, 'git'), `#!/bin/sh\nfor a in "$@"; do if [ "$a" = commit ] && [ -e '${marker}' ]; then echo $$ >> '${marker}.pids'; exec sleep 600; fi; done\nexec '${real}' "$@"\n`);
+ writeFileSync(join(dir, 'git'), `#!/bin/sh
+repo=.; prev=; commit=
+for a in "$@"; do [ "$prev" = -C ] && repo="$a"; [ "$a" = commit ] && commit=1; prev="$a"; done
+if [ -n "$commit" ] && [ -e '${marker}' ]; then
+ lock="$repo/.git/index.lock"; : > "$lock"; echo $$ >> '${marker}.pids'
+ trap 'kill $! 2>/dev/null; rm -f "$lock"; exit 143' TERM
+ sleep 600 >/dev/null 2>&1 & wait
+ exit 1
+fi
+exec '${real}' "$@"
+`);
chmodSync(join(dir, 'git'), 0o755); writeFileSync(marker, '');
process.env.PATH = `${dir}:${process.env.PATH}`;
return { marker, release: () => rmSync(marker, { force: true }) };
@@ -201,6 +227,21 @@ async function processFault(config: RobotConfig, world: World, model: ReferenceM
}
shim.release();
await engine.executeRaw("UPDATE persistence_effects SET next_attempt_at=now() WHERE kind='git' AND state='queued'");
+ } else if (config.process === 'pooler_disconnect') {
+ // Every 400 ms the server drops every other session of this database, as a pooler or failover does.
+ const admin = postgres(config.directUrl!, { max: 1, onnotice() {} });
+ let stop = false; let dropped = 0;
+ const dropping = (async () => {
+ while (!stop) {
+ await Bun.sleep(400);
+ const rows = await admin.unsafe(`SELECT pg_terminate_backend(pid) FROM pg_stat_activity
+ WHERE datname=current_database() AND pid<>pg_backend_pid()`).catch(() => []);
+ dropped += rows.length;
+ }
+ })();
+ try { await runSteps(world, model, config.schedule); }
+ finally { stop = true; await dropping; await admin.end({ timeout: 1 }); }
+ if (!dropped) model.violate({ class: 'wedge', detail: 'pooler_disconnect: no session was dropped; the fault did not run' });
}
await finish(world, model, `${config.schedule.label}+${config.process}`);
}
@@ -217,12 +258,12 @@ export async function robotWorker(role: 'count' | 'run' | 'recover', config: Rob
try {
let world: World; let model: ReferenceModel; let checkouts: string[]; let state: RobotState | undefined;
if (fresh) {
- const topology = await prepareTopology(engine, { sources: 2, worktrees: config.worktrees, root: join(config.root, 'checkouts'), prefix: 'robot' });
+ const topology = await prepareTopology(engine, { sources: 2, worktrees: config.worktrees, root: join(config.root, 'checkouts'), prefix: 'robot', connector: true });
world = topology.world; checkouts = topology.checkouts; model = new ReferenceModel(world);
} else {
state = JSON.parse(readFileSync(config.statePath, 'utf8')) as RobotState;
world = { engine, config: { engine: engine.kind, embedding_disabled: true } as GBrainConfig, remotes: state.remotes, auth: new Map(),
- observations: new Map(state.observations), submitted: new Map(state.submitted) };
+ observations: new Map(state.observations), submitted: new Map(state.submitted), roots: state.roots, connector: state.connector };
checkouts = state.checkouts; model = ReferenceModel.fromJSON(world, state.model);
}
world.descriptors = new Map(config.schedule.ops.map(d => [d.id, d]));
@@ -254,8 +295,9 @@ export async function robotWorker(role: 'count' | 'run' | 'recover', config: Rob
model.beginStep(inFlight.length > 1);
model.allowInFlight(inFlight); model.relaxInFlight(inFlight);
await model.checkGlobal('after SIGKILL, before recovery');
- const drained = await drain(engine, world, DRAIN_BOUND_MS);
- if (!drained) model.violate({ class: 'wedge', detail: `recovery: requests or effects did not drain within ${DRAIN_BOUND_MS / 1000} s after restart` });
+ const bound = DRAIN_BOUND_MS[engine.kind];
+ const drained = await drain(engine, world, bound);
+ if (!drained) model.violate({ class: 'wedge', detail: `recovery: requests or effects did not drain within ${bound / 1000} s after restart` });
await model.checkDrained('recovered');
await settlePending(world, model);
model.allowInFlight(inFlight);
@@ -263,9 +305,9 @@ export async function robotWorker(role: 'count' | 'run' | 'recover', config: Rob
// The interrupted callers resubmit with their original request ids.
if (inFlight.length) {
const observed = await Promise.all(inFlight.map(d => executeOp(world, d)));
- model.beginStep(inFlight.length > 1);
+ model.beginStep(true);
for (let k = 0; k < inFlight.length; k++) await model.observe(inFlight[k], observed[k], inFlight[k].replayOf ? world.observations.get(inFlight[k].replayOf!) : undefined);
- if (inFlight.length > 1) await model.settleGroup(inFlight, observed);
+ await model.settleLate(inFlight, observed);
await model.checkGlobal('after resubmission');
}
await runSteps(world, model, config.schedule, state!.next + inFlight.length);
diff --git a/scripts/persistence/generator.ts b/scripts/persistence/generator.ts
index 4d985375b3..b0cc0a2cc4 100644
--- a/scripts/persistence/generator.ts
+++ b/scripts/persistence/generator.ts
@@ -8,9 +8,9 @@
*/
import { createHash } from 'node:crypto';
import { random } from './harness.ts';
-import { descriptor, type OpArg, type OpDescriptor, type OpKind } from './ops.ts';
+import { CONNECTOR_SLUG, descriptor, type OpArg, type OpDescriptor, type OpKind } from './ops.ts';
-export interface GeneratorTopology { sources: string[]; remotes: { name: string; sourceId: string }[] }
+export interface GeneratorTopology { sources: string[]; remotes: { name: string; sourceId: string }[]; connector?: string }
/** A schedule: descriptors plus the concurrent groups among them (ids that run together). */
export interface Schedule { seed: number; ops: OpDescriptor[]; groups: string[][]; label: string }
@@ -48,9 +48,8 @@ class Builder {
* The irreducible cross-boundary sequences (never cut): withdrawal followed
* by a stale publication; two sources with overlapping slugs; competing
* writers on one page; an authority change while effects are pending
- * (writer revoked mid-sequence); a direct write racing a replayed request.
- * Sync and connector publish racing a direct write are added by the sync
- * family in `families.ts` once their seams exist.
+ * (writer revoked mid-sequence); sync and connector publish racing a direct
+ * write. Caller-bound replay runs beside them as its own sequence.
*/
export function crossBoundarySequences(topology: GeneratorTopology, seed = 1): Schedule[] {
const [a, b] = topology.sources;
@@ -114,6 +113,22 @@ export function crossBoundarySequences(topology: GeneratorTopology, seed = 1): S
s.edit('local', a, 'meetings/standup', '$current', [p.id]);
out.push({ seed, ops: s.ops, groups: s.groups, label: 'authority_change_pending_effects' });
}
+ if (topology.connector) {
+ const s = new Builder(seed, 'sy'); const gh = topology.connector;
+ const p = s.put('local', a, 'notes/alpha');
+ // A user commits an edit of the page file and syncs while an agent writes the same page.
+ const synced = s.next('sync', 'local', a, { slug: 'notes/alpha', content: pageBody('notes/alpha', s.marker()), extra: 24 }, [p.id]);
+ const direct = s.edit(remoteA, a, 'notes/alpha', '$current', [p.id]);
+ s.groups.push([synced.id, direct.id]);
+ s.next('sync', 'local', a, { slug: 'notes/beta', content: pageBody('notes/beta', s.marker()) });
+ s.edit('local', a, 'notes/beta', '$current');
+ // The connector imports an item, then republishes it while a direct write targets the same page.
+ const first = s.next('connector_publish', 'local', gh, { body: `Issue body ${s.marker()}`, updated_at: '2026-09-02T00:00:00Z' });
+ const again = s.next('connector_publish', 'local', gh, { body: `Issue body ${s.marker()}`, updated_at: '2026-09-03T00:00:00Z' }, [first.id]);
+ const racing = s.next('put_page', 'local', gh, { slug: CONNECTOR_SLUG, content: pageBody(CONNECTOR_SLUG, s.marker()), expected_revision: '$current' }, [first.id]);
+ s.groups.push([again.id, racing.id]);
+ out.push({ seed, ops: s.ops, groups: s.groups, label: 'sync_and_connector_race_direct_write' });
+ }
return out;
}
diff --git a/scripts/persistence/history-fixture.ts b/scripts/persistence/history-fixture.ts
index 907f5d176f..8490832c56 100644
--- a/scripts/persistence/history-fixture.ts
+++ b/scripts/persistence/history-fixture.ts
@@ -49,7 +49,7 @@ import { GBrainOAuthProvider } from '../../src/core/oauth-provider.ts';
import { sqlQueryForEngine } from '../../src/core/sql-query.ts';
import { mintLegacyToken } from '../../src/core/token-mint.ts';
import { random } from './harness.ts';
-import { authenticateRemotes, contextFor, descriptor, executeOp, type OpDescriptor,
+import { authenticateRemotes, connectorSourceConfig, contextFor, descriptor, executeOp, type OpDescriptor,
type OpObservation, type RemoteActor, type World } from './ops.ts';
export interface HistoryFixtureOptions {
@@ -171,8 +171,8 @@ export interface ManagedTopology { world: World; checkouts: string[]; sources: H
* remote agents through the production token verifier: an OAuth client on the
* first source and a legacy access token (unified grant columns) on the second.
*/
-export async function prepareTopology(engine: BrainEngine, { sources, worktrees, root, prefix = 'history' }:
- { sources: number; worktrees: number; root: string; prefix?: string }): Promise<ManagedTopology> {
+export async function prepareTopology(engine: BrainEngine, { sources, worktrees, root, prefix = 'history', connector = false }:
+ { sources: number; worktrees: number; root: string; prefix?: string; connector?: boolean }): Promise<ManagedTopology> {
const checkouts = Array.from({ length: worktrees }, (_, k) => { const dir = join(root, `worktree-${k}`); mkdirSync(dir, { recursive: true }); durableGitRepo(dir); return dir; });
const fixtureSources: HistoryFixtureSource[] = Array.from({ length: sources }, (_, i) => {
const worktree = i % worktrees; const dir = join(checkouts[worktree], `source-${i}`); mkdirSync(dir, { recursive: true });
@@ -182,6 +182,14 @@ export async function prepareTopology(engine: BrainEngine, { sources, worktrees,
await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', [source.id, source.root]);
await claimWorktree(engine, source.id, source.root);
}
+ // A GitHub connector source in its own checkout; its items publish through the coordinator.
+ const connectorSource = connector ? { sourceId: `${prefix}-gh`, root: join(root, 'connector') } : undefined;
+ if (connectorSource) {
+ mkdirSync(connectorSource.root, { recursive: true }); durableGitRepo(connectorSource.root);
+ await engine.executeRaw('INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,$3::text::jsonb)',
+ [connectorSource.sourceId, connectorSource.root, JSON.stringify(connectorSourceConfig())]);
+ await claimWorktree(engine, connectorSource.sourceId, connectorSource.root);
+ }
assert.equal((await activatePersistence(engine, { confirmQuiesced: true })).enabled, true);
const sql = sqlQueryForEngine(engine);
const provider = new GBrainOAuthProvider({ sql, transaction: fn => engine.transaction(tx => fn(sqlQueryForEngine(tx))) });
@@ -191,7 +199,8 @@ export async function prepareTopology(engine: BrainEngine, { sources, worktrees,
const minted = await mintLegacyToken(engine, { name: `${prefix}-fixture-token`, scopes: ['read', 'write'], takesHolders: ['world'], sourceGrant: [tokenSource] });
const remotes: RemoteActor[] = [{ name: 'agent-oauth', kind: 'oauth_client', sourceId: fixtureSources[0].id, token: oauth.access_token },
{ name: 'agent-token', kind: 'legacy_token', sourceId: tokenSource, token: minted.token }];
- const world: World = { engine, config: { engine: engine.kind, embedding_disabled: true } as GBrainConfig, remotes, auth: new Map(), observations: new Map() };
+ const world: World = { engine, config: { engine: engine.kind, embedding_disabled: true } as GBrainConfig, remotes, auth: new Map(), observations: new Map(),
+ roots: Object.fromEntries(fixtureSources.map(s => [s.id, s.root])), ...(connectorSource ? { connector: connectorSource } : {}) };
await authenticateRemotes(world);
return { world, checkouts, sources: fixtureSources, accessTokenId: minted.id, oauthClientId: client.clientId };
}
diff --git a/scripts/persistence/model.ts b/scripts/persistence/model.ts
index adb35d819e..66caf05cb2 100644
--- a/scripts/persistence/model.ts
+++ b/scripts/persistence/model.ts
@@ -16,7 +16,7 @@ import { EFFECT_FAULT_POINTS, type FaultPoint } from '../../src/core/persistence
import { operationsByName } from '../../src/core/operations.ts';
import { parseFactsFence } from '../../src/core/facts-fence.ts';
import { parseTakesFence } from '../../src/core/takes-fence.ts';
-import { contextFor, type OpDescriptor, type OpKind, type OpObservation, type World } from './ops.ts';
+import { CONNECTOR_SLUG, contextFor, type OpDescriptor, type OpKind, type OpObservation, type World } from './ops.ts';
/**
* How the generator reaches each effect kind's mid-effect seam: the op that
@@ -32,7 +32,8 @@ export const EFFECT_SEAMS = {
} as const satisfies Record<EffectKind, { op: OpKind; point: FaultPoint }>;
export type ViolationClass = 'lost_write' | 'duplicate_apply' | 'untrue_receipt' | 'wedge' | 'withdrawal_permanence'
- | 'source_isolation' | 'authorization' | 'caller_bound_replay' | 'projection_drift' | 'missing_attribution' | 'orphan_rows' | 'effects_not_terminal';
+ | 'source_isolation' | 'authorization' | 'caller_bound_replay' | 'projection_drift' | 'missing_attribution' | 'orphan_rows' | 'effects_not_terminal'
+ | 'untyped_error';
/** Violations that always block a ship (see the plan's bug-fix bound). */
export const SAFETY_CLASSES: ReadonlySet<ViolationClass> = new Set(['lost_write', 'duplicate_apply', 'untrue_receipt', 'wedge',
'withdrawal_permanence', 'source_isolation', 'authorization', 'caller_bound_replay']);
@@ -43,6 +44,7 @@ interface FactModel { id: string; source: string; text: string; entity: string;
const MARKER = /mk-[a-z]+\d+/g;
const key = (source: string, slug: string) => `${source}\u0000${slug}`;
+function memberMarkersOf(members: { d: OpDescriptor }[]): string[] { return members.flatMap(x => markersIn(JSON.stringify(x.d.args))); }
function markersIn(text: string | undefined | null): string[] { return text ? [...text.matchAll(MARKER)].map(m => m[0]) : []; }
/** The newest page-body marker: edits insert theirs right after "Marker: ". */
function bodyMarker(text: string | undefined | null): string | null { return /Marker: (mk-[a-z]+\d+)/.exec(text ?? '')?.[1] ?? null; }
@@ -83,14 +85,14 @@ export class ReferenceModel {
/** Pages an in-flight op names: a crash may or may not have committed it, so their revision may move. */
allowInFlight(ops: OpDescriptor[]): void {
for (const d of ops) {
- const slug = d.args.slug ?? d.args.entity;
+ const slug = d.kind === 'connector_publish' ? CONNECTOR_SLUG : d.args.slug ?? d.args.entity;
if (typeof slug === 'string') this.touched.add(key(d.source, slug));
if (d.kind === 'forget') for (const f of this.facts.values()) if (f.source === d.source) this.touched.add(key(f.source, f.entity));
}
}
/** Forget pending page-liveness expectations an in-flight delete/restore may have settled either way. */
relaxInFlight(ops: OpDescriptor[]): void {
- for (const d of ops) if ((d.kind === 'delete_page' || d.kind === 'restore_page' || d.kind === 'put_page') && typeof d.args.slug === 'string') {
+ for (const d of ops) if (['delete_page', 'restore_page', 'put_page', 'sync'].includes(d.kind) && typeof d.args.slug === 'string') {
this.pages.delete(key(d.source, d.args.slug));
}
}
@@ -119,7 +121,9 @@ export class ReferenceModel {
this.pending.delete(d.id);
if (o.status !== 'committed') {
if (marker && !this.committedMarkers.has(marker)) this.refusedMarkers.add(marker);
- if (o.status === 'refused' && !o.code) this.violate({ class: 'untrue_receipt', op: d.id, detail: 'refusal without a typed code' });
+ if (o.status === 'refused' && (!o.code || o.code === 'uncoded_error')) {
+ this.violate({ class: 'untyped_error', op: d.id, detail: `${d.kind} failed without a typed code: ${JSON.stringify(o.raw).slice(0, 300)}` });
+ }
return;
}
if (marker) { this.committedMarkers.set(marker, d.source); this.refusedMarkers.delete(marker); }
@@ -142,7 +146,7 @@ export class ReferenceModel {
const committed = batch.map((d, i) => ({ d, o: observed[i] })).filter(x => x.o.status === 'committed');
const bySlug = new Map<string, typeof committed>();
for (const x of committed) {
- const slug = String(x.d.args.slug ?? x.d.args.entity ?? '');
+ const slug = x.d.kind === 'connector_publish' ? CONNECTOR_SLUG : String(x.d.args.slug ?? x.d.args.entity ?? '');
if (slug) bySlug.set(key(x.d.source, slug), [...(bySlug.get(key(x.d.source, slug)) ?? []), x]);
}
for (const [k, members] of bySlug) {
@@ -152,9 +156,15 @@ export class ReferenceModel {
if (revisions.length && !revisions.includes(String(read?.revision))) {
this.violate({ class: 'lost_write', op: members.map(x => x.d.id).join('+'), detail: `concurrent group left ${source}/${slug} at ${String(read?.revision)}, none of the committed revisions ${revisions.join(',')}` });
}
- for (const x of members) {
- const marker = x.d.kind === 'edit_page' || x.d.kind === 'put_page' ? markersIn(JSON.stringify(x.d.args)).at(-1) : null;
- if (marker && !markersIn(String(read?.content)).includes(marker)) this.violate({ class: 'lost_write', op: x.d.id, detail: `committed concurrent ${x.d.kind} marker ${marker} is not visible` });
+ // Whole-page writers (put, sync, connector) may legally replace each other; edits and fact writes compose.
+ const replacing = members.some(x => ['put_page', 'sync', 'connector_publish'].includes(x.d.kind));
+ const memberMarkers = members.map(x => ['edit_page', 'put_page', 'sync', 'connector_publish'].includes(x.d.kind) ? markersIn(JSON.stringify(x.d.args)).at(-1) : null);
+ if (replacing && memberMarkers.some(Boolean) && !memberMarkers.some(mk => mk && markersIn(String(read?.content)).includes(mk))) {
+ this.violate({ class: 'lost_write', op: members.map(x => x.d.id).join('+'), detail: `no committed whole-page write of the group is visible in ${source}/${slug}` });
+ }
+ for (const [i, x] of members.entries()) {
+ const marker = memberMarkers[i];
+ if (!replacing && marker && !markersIn(String(read?.content)).includes(marker)) this.violate({ class: 'lost_write', op: x.d.id, detail: `committed concurrent ${x.d.kind} marker ${marker} is not visible` });
if (x.o.values.revision && x.o.values.revision !== read?.revision) {
const [kept] = await this.world.engine.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM page_versions v JOIN pages p ON p.id=v.page_id
WHERE p.source_id=$1 AND p.slug=$2 AND v.knowledge_revision::text=$3`, [source, slug, x.o.values.revision]);
@@ -163,7 +173,36 @@ export class ReferenceModel {
}
const page = this.page(source, slug);
page.revision = read?.revision ? String(read.revision) : null;
- if (members.some(x => x.d.kind === 'edit_page' || x.d.kind === 'put_page')) page.lastMarker = bodyMarker(String(read?.content)) ?? page.lastMarker;
+ if (members.some(x => ['edit_page', 'put_page', 'sync', 'connector_publish'].includes(x.d.kind))) page.lastMarker = bodyMarker(String(read?.content)) ?? markersIn(String(read?.content)).find(mk => memberMarkersOf(members).includes(mk)) ?? page.lastMarker;
+ }
+ this.deferred = false;
+ }
+
+ /**
+ * Requests whose receipts the caller sees late (a pending write settled after
+ * the drain, or an interrupted request resubmitted after a crash) were
+ * committed in queue order with writes observed since. Their receipt must
+ * name a revision the page really had (current or archived in page_versions);
+ * the page's current state is then adopted as the model's.
+ */
+ async settleLate(batch: OpDescriptor[], observed: OpObservation[]): Promise<void> {
+ for (const [i, d] of batch.entries()) {
+ const o = observed[i];
+ if (o.status !== 'committed' || !o.values.revision) continue;
+ const slug = d.kind === 'connector_publish' ? CONNECTOR_SLUG : String(d.args.slug ?? d.args.entity ?? '');
+ const [seen] = await this.world.engine.executeRaw<{ n: number }>(`SELECT
+ (SELECT count(*)::int FROM pages p WHERE p.source_id=$1 AND p.slug=$2 AND p.knowledge_revision::text=$3)
+ + (SELECT count(*)::int FROM page_versions v JOIN pages p ON p.id=v.page_id WHERE p.source_id=$1 AND p.slug=$2 AND v.knowledge_revision::text=$3) AS n`,
+ [d.source, slug, o.values.revision]);
+ if (!seen.n) this.violate({ class: 'untrue_receipt', op: d.id, detail: `late receipt names revision ${o.values.revision} that ${d.source}/${slug} never had` });
+ }
+ for (const d of batch) {
+ const slug = d.kind === 'connector_publish' ? CONNECTOR_SLUG : d.args.slug ?? d.args.entity;
+ if (typeof slug !== 'string') continue;
+ const page = this.page(d.source, slug); const read = await this.readPage('local', d.source, slug);
+ this.touched.add(key(d.source, slug));
+ page.live = read !== null; page.revision = read?.revision ? String(read.revision) : null;
+ page.lastMarker = read ? bodyMarker(String(read.content)) : null;
}
this.deferred = false;
}
@@ -188,11 +227,18 @@ export class ReferenceModel {
}
/** Read surfaces an agent uses, under a given actor. */
+ /** The last read error, quoted in a violation so a failed read is never mistaken for a missing page. */
+ lastReadError: string | null = null;
async readPage(actor: string, source: string, slug: string): Promise<Record<string, unknown> | null> {
+ this.lastReadError = null;
try {
return await operationsByName.get_page.handler(contextFor(this.world, actor, source),
{ slug, include_content: true, ...(actor === 'local' ? { source_id: source } : {}) }) as Record<string, unknown>;
- } catch { return null; }
+ } catch (error) {
+ const e = error as { code?: string; message?: string };
+ this.lastReadError = `${e.code ?? 'error'}: ${String(e.message).slice(0, 160)}`;
+ return null;
+ }
}
async recall(actor: string, source: string, entity: string): Promise<string[]> {
try {
@@ -302,7 +348,11 @@ const pageWrite = (kind: 'put' | 'edit'): Fold => async (m, d, o) => {
page.lastMarker = marker;
if (m.deferringVisibility) return;
const read = await m.readPage(d.actor === 'local' || m.revoked.has(d.actor) ? 'local' : d.actor, d.source, slug);
- if (!read || read.revision !== o.values.revision) m.violate({ class: 'untrue_receipt', op: d.id, detail: `committed ${d.kind} revision ${o.values.revision} not visible (read ${String(read?.revision)})` });
+ if (!read || read.revision !== o.values.revision) {
+ const [row] = await m.world.engine.executeRaw<Record<string, unknown>>(`SELECT knowledge_revision::text AS revision,deleted_at IS NOT NULL AS deleted,
+ source_path FROM pages WHERE source_id=$1 AND slug=$2`, [d.source, slug]);
+ m.violate({ class: 'untrue_receipt', op: d.id, detail: `committed ${d.kind} revision ${o.values.revision} not visible (read ${String(read?.revision)}${m.lastReadError ? `; ${m.lastReadError}` : ''}; row ${JSON.stringify(row ?? null)})` });
+ }
else if (page.lastMarker && !markersIn(String(read.content)).includes(page.lastMarker)) m.violate({ class: 'untrue_receipt', op: d.id, detail: `committed ${d.kind} marker ${page.lastMarker} not visible` });
};
const touch = (slugOf: (d: OpDescriptor) => string): Fold => async (m, d, o) => {
@@ -312,6 +362,20 @@ const touch = (slugOf: (d: OpDescriptor) => string): Fold => async (m, d, o) =>
else page.revision = null;
};
+/** A file edit picked up by sync, or a connector item: the page now carries its marker. */
+function externalWrite(target: (d: OpDescriptor) => [string, string, string]): Fold {
+ return async (m, d) => {
+ const [source, slug, text] = target(d);
+ const marker = markersIn(text).at(-1) ?? null;
+ const page = m.page(source, slug); m.touched.add(key(source, slug));
+ page.live = true; page.revision = null; page.lastMarker = marker;
+ if (marker) { page.markers.add(marker); m.committedMarkers.set(marker, source); }
+ if (m.deferringVisibility) return;
+ const read = await m.readPage('local', source, slug);
+ if (marker && !markersIn(String(read?.content)).includes(marker)) m.violate({ class: 'untrue_receipt', op: d.id, detail: `${d.kind} reported success but ${source}/${slug} lacks ${marker}` });
+ };
+}
+
/** One fold per op kind: how a committed observation moves the model, plus its observation-point check. */
export const MODEL: Record<OpKind, Fold> = {
put_page: pageWrite('put'),
@@ -341,4 +405,6 @@ export const MODEL: Record<OpKind, Fold> = {
delete_page: async (m, d, o) => { await touch(d => String(d.args.slug))(m, d, o); m.page(d.source, String(d.args.slug)).live = false; },
restore_page: async (m, d, o) => { await touch(d => String(d.args.slug))(m, d, o); m.page(d.source, String(d.args.slug)).live = true; },
revoke_access: async (m, d) => { m.revoked.add(String(d.args.actor)); },
+ sync: externalWrite(d => [d.source, String(d.args.slug), String(d.args.content)]),
+ connector_publish: externalWrite(d => [d.source, CONNECTOR_SLUG, String(d.args.body)]),
};
diff --git a/scripts/persistence/ops.ts b/scripts/persistence/ops.ts
index de4ffc9605..10f11f492b 100644
--- a/scripts/persistence/ops.ts
+++ b/scripts/persistence/ops.ts
@@ -12,6 +12,8 @@
* Nothing here calls a preparer or `tx.*` directly.
*/
import { randomUUID } from 'node:crypto';
+import { mkdirSync, writeFileSync } from 'node:fs';
+import { dirname, join } from 'node:path';
import type { BrainEngine } from '../../src/core/engine.ts';
import type { GBrainConfig } from '../../src/core/config.ts';
import type { AuthInfo, OperationContext } from '../../src/core/ops/contract.ts';
@@ -21,7 +23,7 @@ import { sqlQueryForEngine } from '../../src/core/sql-query.ts';
import { revokeLegacyTokenById } from '../../src/core/token-mint.ts';
export const OP_KINDS = ['put_page', 'edit_page', 'remember', 'forget', 'takes_add', 'takes_supersede',
- 'add_timeline_entry', 'delete_page', 'restore_page', 'revoke_access'] as const;
+ 'add_timeline_entry', 'delete_page', 'restore_page', 'revoke_access', 'sync', 'connector_publish'] as const;
export type OpKind = typeof OP_KINDS[number];
/** Read surfaces the oracle checks; they never mutate. */
export const READ_KINDS = ['get_page', 'recall', 'takes_list'] as const;
@@ -90,6 +92,58 @@ export interface World {
submitted?: Map<string, Record<string, unknown>>;
/** Called with the exact parameters right before submission (a crash worker persists them). */
onSubmit?: (d: OpDescriptor, params: Record<string, unknown>) => void;
+ /** Checkout roots by source id: `sync` edits and commits files there as a user would. */
+ roots?: Record<string, string>;
+ /** The connector source, when the topology has one. */
+ connector?: { sourceId: string; root: string };
+}
+
+/** The GitHub item the connector fixture serves; its page is `CONNECTOR_SLUG` in the connector source. */
+export const CONNECTOR_SLUG = 'gh/acme-example/app/1';
+const CONNECTOR_CONFIG = { kind: 'github', gh_scope: 'repos', gh_repos: 'acme-example/app', gh_token_env: 'CRASH_ROBOT_CONNECTOR_TOKEN' };
+export function connectorSourceConfig(): Record<string, string> { return { ...CONNECTOR_CONFIG }; }
+
+/** A user edits a page file in the checkout and commits it, then the owner syncs through the real `sync_brain` handler. */
+async function runSync(world: World, d: OpDescriptor): Promise<Record<string, unknown>> {
+ const root = world.roots?.[d.source];
+ if (!root) throw new Error(`op descriptor ${d.id}: source ${d.source} has no checkout`);
+ const slug = String(d.args.slug);
+ const path = join(root, `${slug}.md`);
+ mkdirSync(dirname(path), { recursive: true });
+ writeFileSync(path, String(d.args.content));
+ // `extra` sibling files make a backlog, so a managed Postgres sync publishes in bulk groups.
+ const files = [`${slug}.md`];
+ for (let i = 0; i < Number(d.args.extra ?? 0); i++) {
+ const sibling = `${slug}-batch-${i}.md`; files.push(sibling);
+ writeFileSync(join(root, sibling), `---\ntype: note\ntitle: batch ${i}\n---\n\nBatch page ${i} of ${slug}.\n`);
+ }
+ const git = (...args: string[]) => Bun.spawnSync(['git', '-C', root, ...args], { stdout: 'pipe', stderr: 'pipe' });
+ git('add', '--', ...files);
+ git('-c', 'user.name=Crash Robot', '-c', '[email protected]', 'commit', '-q', '-m', `edit ${slug}`, '--', ...files);
+ return await operationsByName.sync_brain.handler(contextFor(world, 'local', d.source),
+ { source_id: d.source, no_pull: true, no_embed: true }) as Record<string, unknown>;
+}
+
+/** The connector fetches one issue whose body carries the descriptor's marker and publishes it through the coordinator. */
+async function runConnector(world: World, d: OpDescriptor): Promise<Record<string, unknown>> {
+ if (!world.connector) throw new Error(`op descriptor ${d.id}: the topology has no connector source`);
+ const { runGitHubSync } = await import('../../src/core/github-source.ts');
+ const { parseGitHubSourceConfig } = await import('../../src/core/github-source-config.ts');
+ const issue = { number: 1, title: 'Robot issue', state: 'open', body: String(d.args.body), created_at: '2026-09-01T00:00:00Z',
+ updated_at: String(d.args.updated_at ?? '2026-09-02T00:00:00Z'), labels: [], assignees: [], user: { login: 'example-user' },
+ html_url: 'https://github.com/acme-example/app/issues/1' };
+ const json = (body: unknown) => new Response(JSON.stringify(body), { status: 200, headers: { 'content-type': 'application/json' } });
+ const fetchImpl = async (url: string) => {
+ const path = new URL(url).pathname;
+ if (path.endsWith('/issues/1')) return json(issue);
+ if (path.endsWith('/issues')) return json([issue]);
+ if (path.endsWith('/pulls') || path.endsWith('/comments')) return json([]);
+ if (path === '/repos/acme-example/app') return json({ full_name: 'acme-example/app', private: true, default_branch: 'main' });
+ throw new Error(`crash-robot connector fixture: unexpected route ${path}`);
+ };
+ process.env.CRASH_ROBOT_CONNECTOR_TOKEN ??= 'synthetic-local-fixture';
+ return await runGitHubSync(world.engine, world.connector.sourceId, parseGitHubSourceConfig(CONNECTOR_CONFIG, world.connector.root),
+ { noEmbed: true, noExtract: true, noSchemaPack: true, githubItem: { repo: 'acme-example/app', number: 1, kind: 'issue' } } as never, fetchImpl as never) as unknown as Record<string, unknown>;
}
export function descriptor(id: string, kind: OpKind, actor: string, source: string, args: Record<string, OpArg>,
@@ -189,6 +243,8 @@ export async function paramsFor(world: World, d: OpDescriptor): Promise<{ op: st
case 'delete_page': return { op: 'delete_page', params: { ...base, ...revision, slug: a.slug } };
case 'restore_page': return { op: 'restore_page', params: { ...base, ...revision, slug: a.slug } };
case 'revoke_access': return { op: 'revoke_access', params: { actor: a.actor } };
+ case 'sync': return { op: 'sync', params: { slug: a.slug, content: a.content, ...(a.extra ? { extra: a.extra } : {}) } };
+ case 'connector_publish': return { op: 'connector_publish', params: { body: a.body, updated_at: a.updated_at } };
}
}
@@ -215,6 +271,24 @@ export async function executeOp(world: World, d: OpDescriptor): Promise<OpObserv
world.observations.set(d.id, observation);
return observation;
}
+ if (d.kind === 'sync' || d.kind === 'connector_publish') {
+ const { params } = await paramsFor(world, d);
+ (world.submitted ??= new Map()).set(d.id, params);
+ world.onSubmit?.(d, params);
+ let observation: OpObservation;
+ try {
+ const run = { ...d, args: params as OpDescriptor['args'] };
+ const result = d.kind === 'sync' ? await runSync(world, run) : await runConnector(world, run);
+ const status = String(result.status);
+ observation = { ...base, status: ['synced', 'first_sync', 'up_to_date'].includes(status) ? 'committed' : status === 'partial' ? 'pending' : 'refused',
+ ...(['synced', 'first_sync', 'up_to_date', 'partial'].includes(status) ? {} : { code: status }), values: {}, raw: jsonSafe({ status, reason: result.reason }) };
+ } catch (error) {
+ const e = error as { code?: string; message?: string };
+ observation = { ...base, status: 'refused', code: e.code ?? 'uncoded_error', values: {}, raw: { code: e.code, message: e.message?.slice(0, 400) } };
+ }
+ world.observations.set(d.id, observation);
+ return observation;
+ }
const { op, params } = await paramsFor(world, d);
(world.submitted ??= new Map()).set(d.id, params);
world.onSubmit?.(d, params);
@@ -238,7 +312,9 @@ export async function executeOp(world: World, d: OpDescriptor): Promise<OpObserv
// The HTTP transport answers a token the verifier rejects with 401 invalid_token.
if (!e.code && e.name === 'InvalidTokenError') e.code = 'invalid_token';
const receipt = receiptOf(e.writeRequest);
- observation = { ...base, status: e.code === 'write_pending' ? 'pending' : 'refused', code: e.code ?? 'uncoded_error',
+ // A memory verb reports an accepted, unfinished write as `unavailable` carrying its pending receipt.
+ const pending = e.code === 'write_pending' || (receipt !== undefined && !['committed', 'failed', 'conflict', 'cancelled'].includes(receipt.state));
+ observation = { ...base, status: pending ? 'pending' : 'refused', code: e.code ?? 'uncoded_error',
receipt, values: {}, raw: { code: e.code, message: e.message?.slice(0, 400) } };
}
const slug = typeof params.slug === 'string' ? params.slug : typeof params.entity === 'string' ? params.entity : null;
diff --git a/scripts/persistence/robot-driver.ts b/scripts/persistence/robot-driver.ts
index 1a944955ed..8bf4b3cf48 100644
--- a/scripts/persistence/robot-driver.ts
+++ b/scripts/persistence/robot-driver.ts
@@ -20,17 +20,19 @@ import type { OpDescriptor } from './ops.ts';
import type { spawnWorker as SpawnWorker } from './validate.ts';
export const ROBOT_TOPOLOGY: GeneratorTopology = { sources: ['robot-0', 'robot-1'],
- remotes: [{ name: 'agent-oauth', sourceId: 'robot-0' }, { name: 'agent-token', sourceId: 'robot-1' }] };
-export const PROCESS_FAULTS: ProcessFault[] = ['stale_index_lock', 'hung_git'];
+ remotes: [{ name: 'agent-oauth', sourceId: 'robot-0' }, { name: 'agent-token', sourceId: 'robot-1' }], connector: 'robot-gh' };
+export const PROCESS_FAULTS: ProcessFault[] = ['stale_index_lock', 'hung_git', 'pooler_disconnect'];
/** One executed run, enough to replay it exactly: `--replay` re-injects this entry. */
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;
+ ops?: string[]; crashed: boolean; violations: RobotOutcome['violations']; duration_ms: number; trace?: string[];
}
export interface RobotOptions {
engine: 'pglite' | 'postgres'; seed: number; seconds: number; scratch: string; home: string;
admin?: ReturnType<typeof postgres>; databaseUrl?: string; databases: string[];
+ /** A transaction-mode PgBouncer URL: Postgres workers then connect through it (prepared statements off). */
+ pooledUrl?: string;
spawn: typeof SpawnWorker; track: (child: ReturnType<typeof SpawnWorker>) => void;
/** Re-run exactly these entries instead of generating. */
replay?: RobotRun[];
@@ -63,16 +65,16 @@ export async function runRobotPhase(o: RobotOptions) {
const started = performance.now();
const runs: RobotRun[] = [];
const log = o.log ?? (line => process.stderr.write(`[crash-robot] ${o.engine}: ${line}\n`));
- async function fresh(name: string): Promise<{ root: string; dataDir: string; databaseUrl?: string }> {
+ async function fresh(name: string): Promise<{ root: string; dataDir: string; databaseUrl?: string; directUrl?: string }> {
const root = join(o.scratch, `robot-${name}-${randomUUID().slice(0, 8)}`); mkdirSync(root, { recursive: true });
- let databaseUrl: string | undefined;
- if (o.admin) {
- const database = `gbrain_persistence_test_${randomUUID().replaceAll('-', '')}`;
- await o.admin.unsafe(`CREATE DATABASE ${database}`); o.databases.push(database);
- const url = new URL(o.databaseUrl!); url.pathname = `/${database}`; databaseUrl = url.toString();
- }
- return { root, dataDir: join(root, 'data'), databaseUrl };
+ if (!o.admin) return { root, dataDir: join(root, 'data') };
+ const database = `gbrain_persistence_test_${randomUUID().replaceAll('-', '')}`;
+ await o.admin.unsafe(`CREATE DATABASE ${database}`); o.databases.push(database);
+ const direct = new URL(o.databaseUrl!); direct.pathname = `/${database}`;
+ const pooled = o.pooledUrl ? new URL(o.pooledUrl) : null; if (pooled) pooled.pathname = `/${database}`;
+ return { root, dataDir: join(root, 'data'), databaseUrl: (pooled ?? direct).toString(), directUrl: direct.toString() };
}
+ const environment: Record<string, string> = o.pooledUrl ? { GBRAIN_PREPARE: 'false' } : {};
async function execute(schedule: Schedule, role: 'count' | 'run', extra: Partial<RobotConfig> = {}): Promise<RobotRun & { counts?: Record<string, number> }> {
const at = performance.now();
const place = await fresh(`${schedule.label}-${role}`);
@@ -80,20 +82,20 @@ export async function runRobotPhase(o: RobotOptions) {
const path = join(place.root, 'robot.json'); writeFileSync(path, JSON.stringify(config), { mode: 0o600 });
const base = { schedule: schedule.label, seed: schedule.seed, length: schedule.ops.length, ...(extra.fault ? { fault: extra.fault } : {}),
...(extra.process ? { process: extra.process } : {}), ...(o.keep?.has(schedule.label) ? { ops: schedule.ops.map(d => d.id) } : {}) };
- const child = o.spawn(path, o.home, 'robot', [role]); o.track(child);
+ const child = o.spawn(path, o.home, 'robot', [role], environment); o.track(child);
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 }))]);
if ('done' in reached) {
const result = reached.done.result as RobotOutcome;
- return { ...base, crashed: false, violations: result.violations, duration_ms: performance.now() - at };
+ return { ...base, crashed: false, violations: result.violations, trace: result.trace, duration_ms: performance.now() - at };
}
await child.kill();
- const recovered = o.spawn(path, o.home, 'robot', ['recover']); o.track(recovered);
+ const recovered = o.spawn(path, o.home, 'robot', ['recover'], environment); o.track(recovered);
const result = (await recovered.done()).result as RobotOutcome;
- return { ...base, crashed: true, violations: result.violations, duration_ms: performance.now() - at };
+ return { ...base, crashed: true, violations: result.violations, trace: result.trace, duration_ms: performance.now() - at };
}
const result = (await child.done()).result as RobotOutcome;
- return { ...base, crashed: false, violations: result.violations, counts: result.counts, duration_ms: performance.now() - at };
+ return { ...base, crashed: false, violations: result.violations, trace: result.trace, counts: result.counts, duration_ms: performance.now() - at };
}
const record = (run: RobotRun) => {
runs.push(run);
@@ -111,22 +113,38 @@ export async function runRobotPhase(o: RobotOptions) {
const rand = random(o.seed);
const budgetMs = o.seconds * 1000;
- const schedules = function* (): Generator<Schedule> {
- yield* crossBoundarySequences(ROBOT_TOPOLOGY, o.seed);
- for (let i = 0; ; i++) yield randomSchedule(ROBOT_TOPOLOGY, (o.seed + 1 + i) >>> 0, 24);
- };
- const crossBoundary = new Set(crossBoundarySequences(ROBOT_TOPOLOGY, o.seed).map(s => s.label));
- for (const schedule of schedules()) {
- // The cross-boundary sequences always run; random sequences fill the remaining budget.
- if (!crossBoundary.has(schedule.label) && performance.now() - started > budgetMs) break;
+ const over = () => performance.now() - started > budgetMs;
+ // 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 }[] = [];
+ for (const schedule of fixed) {
const counted = await execute(schedule, 'count'); record(counted);
- const points = Object.entries(counted.counts ?? {}).sort(([a], [b]) => a.localeCompare(b)) as [FaultPoint, number][];
- for (const [point, count] of points) {
- if (!crossBoundary.has(schedule.label) && performance.now() - started > budgetMs) break;
- record(await execute(schedule, 'run', { fault: { point, nth: 1 + Math.floor(rand() * count) } }));
- }
+ for (const [point, count] of Object.entries(counted.counts ?? {}) as [FaultPoint, number][]) plan.push({ schedule, point, count });
+ }
+ // The seed rotates which sequence covers each seam first.
+ const turn = (x: (typeof plan)[number]) => (fixed.indexOf(x.schedule) + o.seed) % fixed.length;
+ 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;
+ record(await execute(item.schedule, 'run', { fault: { point: item.point, nth: 1 + Math.floor(rand() * item.count) } }));
+ }
+ for (const fault of PROCESS_FAULTS) {
+ if (fault === 'pooler_disconnect' && !o.admin) continue;
+ record(await execute(fixed[1], 'run', { process: fault }));
+ }
+ // 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);
+ const counted = await execute(schedule, 'count'); record(counted);
+ const points = Object.entries(counted.counts ?? {}) as [FaultPoint, number][];
+ if (!points.length || over()) continue;
+ const [point, count] = points[Math.floor(rand() * points.length)];
+ record(await execute(schedule, 'run', { fault: { point, nth: 1 + Math.floor(rand() * count) } }));
}
- for (const fault of PROCESS_FAULTS) record(await execute(crossBoundarySequences(ROBOT_TOPOLOGY, o.seed)[1], 'run', { process: fault }));
return summarize(runs, started, o);
}
diff --git a/scripts/persistence/validate.ts b/scripts/persistence/validate.ts
index ac550fcbdf..576a7b1cc6 100644
--- a/scripts/persistence/validate.ts
+++ b/scripts/persistence/validate.ts
@@ -124,6 +124,7 @@ 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 ?? 300, 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) {
const entries = replayEntries((options.replay ?? options.shrink)!, options.engine);
diff --git a/scripts/persistence/would-have-caught.ts b/scripts/persistence/would-have-caught.ts
new file mode 100644
index 0000000000..705da59122
--- /dev/null
+++ b/scripts/persistence/would-have-caught.ts
@@ -0,0 +1,99 @@
+/**
+ * "Would-have-caught" measurement for the persistence gate. For every frozen
+ * fix in would-have-caught.json, a scratch worktree of HEAD reverse-applies
+ * the fix's src/ hunks (tests stay), then runs the gate as it stood before
+ * the crash robot (1,000 schedules, eight SIGKILL boundaries, the write soak)
+ * and the crash robot phase on its own. A run that fails catches the revert.
+ * HEAD itself runs first as the control: both gates must pass there.
+ *
+ * bun scripts/persistence/would-have-caught.ts --engine=pglite [--only=<sha>,..] [--jobs=2]
+ * [--operations=2500] [--robot-seconds=300] [--out=.context/would-have-caught-<engine>.json]
+ *
+ * Postgres needs the gate's DATABASE_URL (and GBRAIN_PGBOUNCER_URL for the pooled route).
+ */
+import { spawnSync } from 'node:child_process';
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join, resolve } from 'node:path';
+
+interface Fix { sha: string; date: string; subject: string; src_files: string[] }
+interface GateResult { caught: boolean; exit: number; seconds: number; first_failure?: string }
+export interface FixResult { sha: string; subject: string; reverted: boolean; current?: GateResult; robot?: GateResult; extended_caught?: boolean; note?: string }
+
+const repo = resolve(import.meta.dir, '../..');
+const args = new Map(process.argv.slice(2).map(arg => { const [k, ...v] = arg.replace(/^--/, '').split('='); return [k, v.join('=')]; }));
+const engine = args.get('engine') ?? 'pglite';
+const operations = Number(args.get('operations') ?? 2500);
+const robotSeconds = Number(args.get('robot-seconds') ?? 300);
+const jobs = Number(args.get('jobs') ?? 1);
+const only = args.get('only')?.split(',').filter(Boolean);
+const out = args.get('out') ?? join(repo, '.context', `would-have-caught-${engine}.json`);
+const frozen = JSON.parse(readFileSync(join(import.meta.dir, 'would-have-caught.json'), 'utf8')) as { fixes: Fix[] };
+const fixes = frozen.fixes.filter(fix => !only || only.some(prefix => fix.sha.startsWith(prefix)));
+
+function git(cwd: string, ...rest: string[]) { return spawnSync('git', ['-C', cwd, ...rest], { encoding: 'utf8' }); }
+
+function worktree(label: string): string {
+ const dir = mkdtempSync(join(tmpdir(), `gbrain-whc-${label}-`));
+ rmSync(dir, { recursive: true });
+ const added = git(repo, 'worktree', 'add', '--detach', dir, 'HEAD');
+ if (added.status) throw new Error(`git worktree add failed: ${added.stderr}`);
+ symlinkSync(join(repo, 'node_modules'), join(dir, 'node_modules'));
+ return dir;
+}
+
+async function gate(dir: string, kind: 'current' | 'robot', label: string): Promise<GateResult> {
+ const manifest = join(dir, '.context', `${kind}.json`); mkdirSync(join(dir, '.context'), { recursive: true });
+ const flags = kind === 'current' ? [`--operations=${operations}`, '--robot-seconds=0']
+ : ['--schedules=0', '--operations=0', '--no-crashes', `--robot-seconds=${robotSeconds}`];
+ const started = performance.now();
+ const child = Bun.spawn([process.execPath, '--no-env-file', 'scripts/persistence/validate.ts', `--engine=${engine}`, ...flags, `--manifest=${manifest}`],
+ { cwd: dir, stdout: 'ignore', stderr: 'pipe', env: process.env });
+ const stderr = await new Response(child.stderr).text();
+ const exit = await child.exited;
+ const seconds = (performance.now() - started) / 1000;
+ let firstFailure: string | undefined;
+ if (exit !== 0) {
+ try { firstFailure = String(JSON.parse(readFileSync(manifest, 'utf8')).failure ?? '').split('\n').slice(0, 3).join(' | ').slice(0, 600); }
+ catch { firstFailure = stderr.split('\n').filter(Boolean).slice(-3).join(' | ').slice(0, 600); }
+ }
+ process.stderr.write(`[would-have-caught] ${engine} ${label} ${kind}: ${exit === 0 ? 'passed' : 'FAILED'} (${seconds.toFixed(0)} s)\n`);
+ return { caught: exit !== 0, exit, seconds, ...(firstFailure ? { first_failure: firstFailure } : {}) };
+}
+
+async function measure(fix: Fix | null): Promise<FixResult> {
+ const label = fix ? fix.sha.slice(0, 9) : 'control';
+ const dir = worktree(label);
+ try {
+ if (fix) {
+ const diff = git(repo, 'diff', `${fix.sha}^`, fix.sha, '--', 'src');
+ const apply = spawnSync('git', ['-C', dir, 'apply', '-R', '-3'], { input: diff.stdout, encoding: 'utf8' });
+ if (apply.status) return { sha: fix.sha, subject: fix.subject, reverted: false, note: apply.stderr.slice(0, 300) };
+ }
+ const [current, robot] = [await gate(dir, 'current', label), await gate(dir, 'robot', label)];
+ return { sha: fix?.sha ?? 'HEAD', subject: fix?.subject ?? 'control (no revert)', reverted: !!fix, current, robot,
+ extended_caught: current.caught || robot.caught };
+ } finally {
+ git(repo, 'worktree', 'remove', '--force', dir);
+ if (existsSync(dir)) rmSync(dir, { recursive: true, force: true });
+ }
+}
+
+const queue: (Fix | null)[] = [null, ...fixes];
+const results: FixResult[] = [];
+await Promise.all(Array.from({ length: Math.max(1, jobs) }, async () => {
+ for (;;) { const next = queue.shift(); if (next === undefined) return; results.push(await measure(next)); }
+}));
+const measured = results.filter(r => r.reverted);
+const summary = {
+ engine, operations, robot_seconds: robotSeconds, head: git(repo, 'rev-parse', 'HEAD').stdout.trim(),
+ control: results.find(r => !r.reverted && r.sha === 'HEAD'),
+ fixes: measured.length, not_reverted: results.filter(r => r.reverted === false && r.sha !== 'HEAD').map(r => r.sha),
+ current_caught: measured.filter(r => r.current?.caught).length,
+ extended_caught: measured.filter(r => r.extended_caught).length,
+ marginal: measured.filter(r => r.extended_caught && !r.current?.caught).map(r => r.sha.slice(0, 9)),
+ results: results.sort((a, b) => a.sha.localeCompare(b.sha)),
+};
+mkdirSync(resolve(out, '..'), { recursive: true });
+writeFileSync(out, `${JSON.stringify(summary, null, 2)}\n`);
+process.stdout.write(`${JSON.stringify({ ...summary, results: undefined }, null, 2)}\n`);
diff --git a/test/persistence-crash-robot.test.ts b/test/persistence-crash-robot.test.ts
index 97c56e890f..9c3db769c4 100644
--- a/test/persistence-crash-robot.test.ts
+++ b/test/persistence-crash-robot.test.ts
@@ -33,7 +33,7 @@ async function robotBrain<T>(run: (brain: Awaited<ReturnType<typeof prepareTopol
try {
return await withEnv({ GBRAIN_HOME: home, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined }, async () => {
const { engine, close } = await isolatedSharedSkillsEngine();
- try { return await run(await prepareTopology(engine, { sources: 2, worktrees: 2, root: join(home, 'checkouts'), prefix: 'robot' })); }
+ try { return await run(await prepareTopology(engine, { sources: 2, worktrees: 2, root: join(home, 'checkouts'), prefix: 'robot', connector: true })); }
finally { await disposePersistenceConsumer(engine); await close(); }
});
} finally { rmSync(home, { recursive: true, force: true }); }
@@ -51,9 +51,10 @@ describe('op-descriptor protocol', () => {
});
describe('generator', () => {
- test('the five cross-boundary sequences are always generated', () => {
+ test('the cross-boundary sequences are always generated', () => {
expect(crossBoundarySequences(ROBOT_TOPOLOGY).map(s => s.label)).toEqual(['withdrawal_then_stale_publication',
- 'overlapping_slugs_two_sources', 'competing_writers_one_page', 'caller_bound_replay', 'authority_change_pending_effects']);
+ 'overlapping_slugs_two_sources', 'competing_writers_one_page', 'caller_bound_replay', 'authority_change_pending_effects',
+ 'sync_and_connector_race_direct_write']);
});
test('a random schedule is a function of its seed and covers every write op', () => {
expect(JSON.stringify(randomSchedule(ROBOT_TOPOLOGY, 9))).toBe(JSON.stringify(randomSchedule(ROBOT_TOPOLOGY, 9)));