Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(persistence-robot): retry only the session drops the robot injected

garrytande25af39c6e1
diff --git a/docs/architecture/key-files/tooling-and-tests.md b/docs/architecture/key-files/tooling-and-tests.md
index f2189feb79..45853152bd 100644
--- a/docs/architecture/key-files/tooling-and-tests.md
+++ b/docs/architecture/key-files/tooling-and-tests.md
@@ -62,7 +62,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. `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`, 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/{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/scripts/persistence/README.md b/scripts/persistence/README.md
index 32d0400839..21508b7e69 100644
--- a/scripts/persistence/README.md
+++ b/scripts/persistence/README.md
@@ -107,6 +107,11 @@ database dropped every 400 ms, and the owner killed right after a
`facts-absorb` job's extraction commits (deterministic chat and embedding
stubs); the job then runs again and every absorbed fact must be active
exactly once.
+The robot records each session-drop round it injects. Its own reads (oracle
+checks, drain polls, `$current` revision lookups, token re-verification)
+retry a closed connection only after a round that began before the error
+terminated a session; any other close fails the run with the next step,
+so a database, pooler or product-side close is never retried away.
The reference model (`model.ts`) checks: a committed receipt is visible at
once and later revisions move only through committed ops; a late receipt
diff --git a/scripts/persistence/crash-robot.ts b/scripts/persistence/crash-robot.ts
index 250dda5ad8..167d96cfb1 100644
--- a/scripts/persistence/crash-robot.ts
+++ b/scripts/persistence/crash-robot.ts
@@ -20,8 +20,8 @@ import { assertSafeE2eDatabaseUrl } from '../../test/helpers/db-guard.ts';
import postgres from '#postgres';
import { prepareTopology } from './history-fixture.ts';
import { installLockOrderTrace, lockOrderReport } from './lock-order.ts';
-import { executeOp, type OpDescriptor, type OpObservation, type World } from './ops.ts';
-import { KNOWN_DEFERRALS, ReferenceModel, retryingRead, SAFETY_CLASSES, type Violation } from './model.ts';
+import { executeOp, retryingRead, SessionDrops, type OpDescriptor, type OpObservation, type World } from './ops.ts';
+import { KNOWN_DEFERRALS, ReferenceModel, SAFETY_CLASSES, type Violation } from './model.ts';
import type { Schedule } from './generator.ts';
import { pageBody } from './generator.ts';
import { descriptor } from './ops.ts';
@@ -43,7 +43,7 @@ export async function drain(engine: BrainEngine, world: World, timeoutMs = 60_00
startPersistenceConsumer(engine, world.config).wake();
const deadline = Date.now() + timeoutMs;
for (;;) {
- const [row] = await retryingRead(() => engine.executeRaw<{ n: number }>(`SELECT
+ const [row] = await retryingRead(world, () => engine.executeRaw<{ n: number }>(`SELECT
(SELECT count(*) FROM persistence_requests WHERE state IN ('queued','running','recovering'))
+ (SELECT count(*) FROM persistence_effects WHERE (state IN ('queued','running') AND next_attempt_at <= now() + interval '30 seconds') OR recovery IS NOT NULL) AS n`));
if (Number(row.n) === 0) return true;
@@ -216,7 +216,7 @@ async function stubFactsProviders(): Promise<void> {
/** Run the queued facts-absorb job through its registered handler, as a worker does after claiming it. */
async function runAbsorbJob(engine: BrainEngine, attempts: number): Promise<unknown> {
- const [job] = await retryingRead(() => engine.executeRaw<{ id: number; data: Record<string, unknown> }>("SELECT id,data FROM minion_jobs WHERE name='facts-absorb' ORDER BY id LIMIT 1"));
+ const [job] = await retryingRead({}, () => engine.executeRaw<{ id: number; data: Record<string, unknown> }>("SELECT id,data FROM minion_jobs WHERE name='facts-absorb' ORDER BY id LIMIT 1"));
if (!job) throw new Error('facts_absorb_kill: no facts-absorb job was queued');
const { MinionWorker } = await import('../../src/core/minions/worker.ts');
const { registerBuiltinHandlers } = await import('../../src/commands/jobs.ts');
@@ -279,7 +279,7 @@ async function processFault(config: RobotConfig, world: World, model: ReferenceM
args: { slug: ABSORB_SLUG, content: `---\ntype: meeting\ntitle: Robot review\n---\n\n${body}\n` } });
if (put.status !== 'committed') throw new Error(`facts_absorb_kill: the meeting page did not commit (${put.code})`);
const deadline = Date.now() + 30_000;
- while (!(await retryingRead(() => engine.executeRaw("SELECT 1 FROM minion_jobs WHERE name='facts-absorb'"))).length) {
+ while (!(await retryingRead(world, () => engine.executeRaw("SELECT 1 FROM minion_jobs WHERE name='facts-absorb'"))).length) {
if (Date.now() > deadline) throw new Error('facts_absorb_kill: the facts-backstop effect never queued a facts-absorb job');
await Bun.sleep(100);
}
@@ -287,14 +287,15 @@ async function processFault(config: RobotConfig, world: World, model: ReferenceM
await checkAbsorbedOnce(model, 'facts_absorb_kill (no crash reached)');
} else if (config.process === 'pooler_disconnect') {
// Every 400 ms the server drops every other session of this database, as a pooler or failover does.
+ // Each round is recorded, so harness reads retry only the closes this fault caused.
const admin = postgres(config.directUrl!, { max: 1, onnotice() {} });
+ const drops = world.sessionDrops = new SessionDrops();
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;
+ dropped += await drops.inject(() => admin.unsafe(`SELECT pg_terminate_backend(pid) FROM pg_stat_activity
+ WHERE datname=current_database() AND pid<>pg_backend_pid()`).then(rows => rows.length));
}
})();
try { await runSteps(world, model, config.schedule); }
diff --git a/scripts/persistence/model.ts b/scripts/persistence/model.ts
index 7189d7e752..cf88cc2d3e 100644
--- a/scripts/persistence/model.ts
+++ b/scripts/persistence/model.ts
@@ -17,7 +17,7 @@ import { operationsByName } from '../../src/core/operations.ts';
import { parseFactsFence } from '../../src/core/facts-fence.ts';
import { parseTakesFence } from '../../src/core/takes-fence.ts';
import { isRegistryCode } from '../../src/core/error-catalogue.ts';
-import { CONNECTOR_SLUG, contextFor, type OpDescriptor, type OpKind, type OpObservation, type World } from './ops.ts';
+import { CONNECTOR_SLUG, contextFor, retryingRead, 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
@@ -35,17 +35,6 @@ export const EFFECT_SEAMS = {
links: { op: 'put_page', point: EFFECT_FAULT_POINTS.links },
} as const satisfies Record<EffectKind, { op: OpKind; point: FaultPoint }>;
-/** Retry a harness read across a dropped connection (the pooler_disconnect fault); other errors propagate. */
-export async function retryingRead<T>(read: () => Promise<T>): Promise<T> {
- for (let attempt = 0; ; attempt++) {
- try { return await read(); } catch (error) {
- const text = `${(error as { code?: string }).code ?? ''} ${String((error as Error).message)}`;
- if (attempt >= 8 || !/CONNECTION_CLOSED|CONNECTION_ENDED|ECONNRESET|57P01|08P01|08006|server conn crashed|terminating connection|Connection terminated/i.test(text)) throw error;
- await Bun.sleep(150 * (attempt + 1));
- }
- }
-}
-
/** Non-error outcomes a sync or connector run reports as its status (not error codes). */
const EXTERNAL_RESULT_CODES = new Set(['blocked_by_failures', 'dry_run']);
@@ -272,11 +261,11 @@ export class ReferenceModel {
/** Read surfaces an agent uses, under a given actor. */
/**
- * The oracle's own reads retry a dropped connection (the pooler_disconnect
- * fault terminates sessions between statements); only the system under test
- * is judged on such errors.
+ * The oracle's own reads retry a session drop the robot injected (the
+ * pooler_disconnect fault); only the system under test is judged on such
+ * errors, and any other close fails the run.
*/
- private retrying<T>(read: () => Promise<T>): Promise<T> { return retryingRead(read); }
+ private retrying<T>(read: () => Promise<T>): Promise<T> { return retryingRead(this.world, read); }
q<R = Record<string, unknown>>(sql: string, params?: unknown[]): Promise<R[]> {
return this.retrying(() => this.world.engine.executeRaw<R>(sql, params));
}
diff --git a/scripts/persistence/ops.ts b/scripts/persistence/ops.ts
index 39e16596ef..14e803836f 100644
--- a/scripts/persistence/ops.ts
+++ b/scripts/persistence/ops.ts
@@ -100,6 +100,61 @@ export interface World {
roots?: Record<string, string>;
/** The connector source, when the topology has one. */
connector?: { sourceId: string; root: string };
+ /** Session drops this robot injects (the pooler_disconnect fault); absent in every other run. */
+ sessionDrops?: SessionDrops;
+}
+
+/**
+ * The robot's own session drops. A harness read treats a closed connection as
+ * injected only once a drop round that began before the error terminated at
+ * least one session; any other close is unexpected and fails the run.
+ */
+export class SessionDrops {
+ private killed = 0;
+ private readonly inFlight = new Set<Promise<number>>();
+ /** Run one drop round; resolves to the number of sessions it terminated (0 when the round itself failed). */
+ inject(terminate: () => Promise<number>): Promise<number> {
+ const round: Promise<number> = terminate().catch(() => 0).then(n => { this.killed += n; this.inFlight.delete(round); return n; });
+ this.inFlight.add(round);
+ return round;
+ }
+ /** Whether a round started before this call terminated a session. */
+ async injectedBefore(): Promise<boolean> {
+ if (!this.killed) await Promise.all([...this.inFlight]);
+ return this.killed > 0;
+ }
+}
+
+const DROPPED_CONNECTION = /CONNECTION_CLOSED|CONNECTION_ENDED|ECONNRESET|57P01|08P01|08006|server conn crashed|terminating connection|Connection terminated/i;
+const DROP_RETRIES = 8;
+
+/**
+ * Run a harness read (an oracle check, a drain poll, an argument lookup) across
+ * a session drop the robot injected; only the system under test is judged on
+ * such errors. A close the robot did not inject, or one that outlasts the
+ * retries, fails the run with the next step.
+ */
+export async function retryingRead<T>(world: Pick<World, 'sessionDrops'>, read: () => Promise<T>): Promise<T> {
+ for (let attempt = 0; ; attempt++) {
+ try { return await read(); } catch (error) {
+ const code = (error as { code?: string }).code;
+ const seen = `${code ?? 'error'}: ${String((error as Error).message).slice(0, 200)}`;
+ if (!DROPPED_CONNECTION.test(seen)) throw error;
+ if (!(await world.sessionDrops?.injectedBefore())) {
+ throw new Error(`crash robot: a harness read lost its database connection (${seen}), but the robot had dropped no session `
+ + 'before it, so the database, the pooler or the code under test closed it. Check the Postgres and PgBouncer logs for a restart '
+ + 'at that time, then re-run the crash robot: bun --no-env-file scripts/persistence/validate.ts --engine=postgres --schedules=0 '
+ + '--operations=0 --no-crashes. Docs: scripts/persistence/README.md#crash-robot', { cause: error });
+ }
+ if (attempt >= DROP_RETRIES) {
+ throw new Error(`crash robot: a harness read still lost its connection after ${DROP_RETRIES + 1} attempts across injected session `
+ + `drops (${seen}), so the database stayed unreachable between drop rounds. Check that Postgres and PgBouncer are up, then re-run `
+ + 'the crash robot: bun --no-env-file scripts/persistence/validate.ts --engine=postgres --schedules=0 --operations=0 --no-crashes. '
+ + 'Docs: scripts/persistence/README.md#crash-robot', { cause: error });
+ }
+ await Bun.sleep(150 * (attempt + 1));
+ }
+ }
}
/** The GitHub item the connector fixture serves; its page is `CONNECTOR_SLUG` in the connector source. */
@@ -179,14 +234,8 @@ async function reauthenticate(world: World, actor: string): Promise<void> {
const remote = world.remotes.find(r => r.name === actor);
if (!remote) return;
const provider = new GBrainOAuthProvider({ sql: sqlQueryForEngine(world.engine) });
- // The transport's own verification retries a dropped connection; only the operation is under test.
- for (let attempt = 0; ; attempt++) {
- try { world.auth.set(actor, await provider.verifyAccessToken(remote.token) as unknown as AuthInfo); return; }
- catch (error) {
- if (attempt >= 8 || !/CONNECTION_CLOSED|ECONNRESET|08P01|57P01|server conn crashed/i.test(`${(error as { code?: string }).code} ${(error as Error).message}`)) throw error;
- await Bun.sleep(150 * (attempt + 1));
- }
- }
+ // The transport's own verification retries an injected session drop; only the operation is under test.
+ world.auth.set(actor, await retryingRead(world, () => provider.verifyAccessToken(remote.token)) as unknown as AuthInfo);
}
/** Revoke a remote actor's credential through the owner's real revocation path. */
@@ -237,7 +286,7 @@ export async function paramsFor(world: World, d: OpDescriptor): Promise<{ op: st
const a = resolveArg(world, d.args as OpArg) as Record<string, unknown>;
if (a.content === '$stale_content') a.content = world.observations.get(String(a.stale_of))?.pageContent ?? 'missing stale content';
if (a.expected_revision === '$current') {
- const snapshot = await world.engine.readPageSnapshot(String(a.slug), { sourceId: d.source, includeDeleted: true });
+ const snapshot = await retryingRead(world, () => world.engine.readPageSnapshot(String(a.slug), { sourceId: d.source, includeDeleted: true }));
a.expected_revision = snapshot?.revision ?? 'missing-page';
}
const revision = a.expected_revision === undefined ? {} : { expected_revision: a.expected_revision };
@@ -340,8 +389,8 @@ export async function executeOp(world: World, d: OpDescriptor): Promise<OpObserv
const slug = typeof params.slug === 'string' ? params.slug : typeof params.entity === 'string' ? params.entity : null;
if (observation.status === 'committed' && slug) {
try {
- const page = await operationsByName.get_page.handler(contextFor(world, 'local', d.source),
- { slug, include_content: true, source_id: d.source }) as Record<string, unknown>;
+ const page = await retryingRead(world, () => operationsByName.get_page.handler(contextFor(world, 'local', d.source),
+ { slug, include_content: true, source_id: d.source })) as Record<string, unknown>;
if (typeof page?.content === 'string') observation.pageContent = page.content;
} catch { /* deleted or not a page */ }
}
diff --git a/test/persistence-crash-robot.test.ts b/test/persistence-crash-robot.test.ts
index 5450aa20c4..473308a38e 100644
--- a/test/persistence-crash-robot.test.ts
+++ b/test/persistence-crash-robot.test.ts
@@ -17,9 +17,9 @@ import { describe, expect, test } from 'bun:test';
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
-import { descriptor, executeOp, parseDescriptor } from '../scripts/persistence/ops.ts';
+import { descriptor, executeOp, parseDescriptor, SessionDrops } from '../scripts/persistence/ops.ts';
import { ReferenceModel } from '../scripts/persistence/model.ts';
-import { crossBoundarySequences, randomSchedule } from '../scripts/persistence/generator.ts';
+import { crossBoundarySequences, pageBody, randomSchedule } from '../scripts/persistence/generator.ts';
import { ROBOT_TOPOLOGY, restrict } from '../scripts/persistence/robot-driver.ts';
import { shrinkRun } from '../scripts/persistence/shrink.ts';
import { runSchedule, runSteps } from '../scripts/persistence/crash-robot.ts';
@@ -131,6 +131,59 @@ describe('concurrent connector publish and direct write', () => {
}, 120_000);
});
+describe('injected session drops', () => {
+ // CI jobs 111669020132 and 111702893848: a pooler_disconnect drop landed on the robot's own `$current`
+ // revision read, which had no retry, and the worker died with `write CONNECTION_CLOSED 127.0.0.1:55433`.
+ const closed = () => Object.assign(new Error('write CONNECTION_CLOSED 127.0.0.1:55433'), { code: 'CONNECTION_CLOSED' });
+ const dropOnce = (world: { engine: { readPageSnapshot: (...a: never[]) => Promise<unknown> } }) => {
+ const engine = world.engine;
+ const read = engine.readPageSnapshot;
+ let calls = 0;
+ engine.readPageSnapshot = (async (...args: never[]) => {
+ calls++;
+ engine.readPageSnapshot = read;
+ throw closed();
+ }) as never;
+ return () => calls;
+ };
+
+ test('an injected drop on the robot\'s own revision read is retried; a close it did not inject fails the run', async () => {
+ await robotBrain(async ({ world }) => {
+ const source = world.remotes[0].sourceId;
+ const put = await executeOp(world, descriptor('seed', 'put_page', 'local', source, { slug: 'notes/alpha', content: pageBody('notes/alpha', 'mk-seed0') }));
+ expect(put.status).toBe('committed');
+ const edit = (id: string) => descriptor(id, 'put_page', 'local', source,
+ { slug: 'notes/alpha', content: pageBody('notes/alpha', `mk-${id}0`), expected_revision: '$current' });
+
+ const unexpectedCalls = dropOnce(world);
+ await expect(executeOp(world, edit('unexpected'))).rejects.toThrow(/robot had dropped no session before it[\s\S]*validate\.ts --engine=postgres/);
+ expect(unexpectedCalls()).toBe(1);
+ expect(world.submitted?.has('unexpected')).toBe(false);
+
+ world.sessionDrops = new SessionDrops();
+ expect(await world.sessionDrops.inject(async () => 1)).toBe(1);
+ const injectedCalls = dropOnce(world);
+ const seen = await executeOp(world, edit('injected'));
+ expect(injectedCalls()).toBe(1);
+ expect(seen.status).toBe('committed');
+ expect(world.submitted?.get('injected')?.expected_revision).toBe(put.receipt?.revision);
+ });
+ }, 120_000);
+
+ test('a drop round counts once it terminated a session, including a round still in flight', async () => {
+ const drops = new SessionDrops();
+ expect(await drops.injectedBefore()).toBe(false);
+ expect(await drops.inject(async () => 0)).toBe(0);
+ expect(await drops.inject(() => Promise.reject(new Error('admin connection lost')))).toBe(0);
+ expect(await drops.injectedBefore()).toBe(false);
+ let finish!: (killed: number) => void;
+ void drops.inject(() => new Promise<number>(done => { finish = done; }));
+ const asked = drops.injectedBefore();
+ finish(2);
+ expect(await asked).toBe(true);
+ });
+});
+
describe('lock order', () => {
test('real publications keep worktree > sources-by-id order; an inversion is reported', async () => {
await robotBrain(async ({ world }) => {