Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

crash robot: drop a passed run's database at once so the pooler releases its server connections

garrytan196d29700a99
diff --git a/CHANGELOG.md b/CHANGELOG.md
index e0f30d312d..3dc9ea3f72 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,6 +10,18 @@ credits are retained; no result has been reassigned to another provider. Origina
identifiers and attribution are available in the pre-removal Git revision
`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).
+## [0.60.143.0] - 2026-10-10
+
+**The crash robot drops each run's database as soon as the run passes, so a transaction-mode pooler no longer holds every run's server connections until the budget ends. Harness only; no product behavior changes.**
+
+Master `f250a517c` failed the `Crash robot / postgres / Bun 1.4.0` cell with `FATAL: sorry, too many clients already` 25 runs into its 600 s budget. The robot gives every run its own database and, until now, kept all of them until the phase ended. Through the CI PgBouncer (wildcard `[databases]`, transaction mode) each run's database gets its own server pool, and PgBouncer keeps those connections for `server_idle_timeout` (600 s by default, the length of a full robot budget), so the server held about four idle backends per finished run: 111 server connections across 26 fixture databases in the failing cell against `max_connections=100`. The previous green masters ran the same cases with the same per-run counts and passed only because their slower early runs reached 22 cases before the budget closed; in the passing Bun 1.4.2 sibling, started at the same moment, PgBouncer's first `server idle timeout` closes came at 06:22:23, 46 s after the Bun 1.4.0 cell's first refusal at 06:21:37. Nothing in `#6412` (v0.60.142.0) changed how many connections a run opens.
+
+### Itemized changes
+
+- `scripts/persistence/robot-driver.ts`: a run that passes has its database dropped (`WITH (FORCE)`) before the next run starts, which ends the pooler's server connections to it. A failing run keeps its database for the retained-fixture metadata as before.
+- `scripts/persistence/validate.ts`, `scripts/persistence/failure-diagnostics.ts`: a failed Postgres gate records `connection_diagnostic` in the manifest: `max_connections`, the backend total and counts per database class (this harness's fixtures or other), state and wait class. No database name, query text or client address is included.
+- `test/e2e/persistence-robot-fixture-release.test.ts`: one replayed run through the pooler when `GBRAIN_PGBOUNCER_URL` names one (direct otherwise); the passed run's database must be gone with no backend attached (four idle pooler backends remained before the fix), and the connection diagnostic's shape is pinned.
+
## [0.60.142.0] - 2026-10-10
**A file write's publication takes its request-row lock and its `publication_started` stamp in one statement instead of two. No behavior changes; one UPDATE fewer per published file.**
diff --git a/scripts/persistence/failure-diagnostics.ts b/scripts/persistence/failure-diagnostics.ts
index 59e2a80800..c97f8f5aa0 100644
--- a/scripts/persistence/failure-diagnostics.ts
+++ b/scripts/persistence/failure-diagnostics.ts
@@ -63,6 +63,27 @@ export async function ownerDatabaseDiagnostic(engine: Pick<BrainEngine, 'execute
.map(key => [key, decimal(row.counters![key])])) : null };
}
+/**
+ * How the server's connection slots were spent when a Postgres gate failed:
+ * counts per database class (this harness's fixtures or everything else),
+ * backend state and wait class, next to `max_connections`. A pooler holding
+ * a passed run's connections shows up as idle fixture backends; no database
+ * name, query text or client address leaves the server.
+ */
+export async function connectionDiagnostic(admin: { unsafe(query: string): Promise<Iterable<Record<string, unknown>>> }) {
+ const rows = [...await admin.unsafe(`
+ SELECT current_setting('max_connections') AS max_connections,
+ CASE WHEN datname LIKE 'gbrain_persistence_test_%' THEN 'fixture' ELSE 'other' END AS databases,
+ count(DISTINCT datname)::text AS database_count, coalesce(state, 'none') AS state,
+ coalesce(wait_event_type, 'none') AS wait_event_type, count(*)::text AS backends
+ FROM pg_stat_activity WHERE backend_type = 'client backend'
+ GROUP BY 2, 4, 5 ORDER BY 2, 4, 5 LIMIT 32`)];
+ return { max_connections: decimal(rows[0]?.max_connections ?? null),
+ backends: rows.reduce((sum, row) => sum + Number(row.backends), 0),
+ groups: rows.map(row => ({ databases: diagnosticCode(row.databases), database_count: decimal(row.database_count),
+ state: diagnosticCode(String(row.state).replaceAll(' ', '_')), wait_event_type: diagnosticCode(row.wait_event_type), backends: decimal(row.backends) })) };
+}
+
export function retentionMetadata(scratch: string, databases: string[]) {
// Only names created by this harness can appear in an executable cleanup command.
if (!databases.every(name => /^gbrain_persistence_test_[0-9a-f]{32}$/.test(name))) throw new Error('Invalid retained fixture database name');
diff --git a/scripts/persistence/robot-driver.ts b/scripts/persistence/robot-driver.ts
index fbf2463332..3d61f4569e 100644
--- a/scripts/persistence/robot-driver.ts
+++ b/scripts/persistence/robot-driver.ts
@@ -82,37 +82,52 @@ 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; directUrl?: string }> {
+ async function fresh(name: string): Promise<{ root: string; dataDir: string; databaseUrl?: string; directUrl?: string; database?: string }> {
const root = join(o.scratch, `robot-${name}-${randomUUID().slice(0, 8)}`); mkdirSync(root, { recursive: true });
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() };
+ return { root, dataDir: join(root, 'data'), databaseUrl: (pooled ?? direct).toString(), directUrl: direct.toString(), database };
+ }
+ // A transaction-mode pooler keeps every server connection a run opened in
+ // that run's per-database pool until its own idle timeout (PgBouncer: 600 s,
+ // the length of a full robot budget), so a run's database is released the
+ // moment the run passes: DROP ... WITH (FORCE) ends those backends. A
+ // failing run keeps its database for the retained-fixture metadata.
+ async function release(database: string | undefined) {
+ if (!database || !o.admin) return;
+ await o.admin.unsafe(`DROP DATABASE IF EXISTS ${database} WITH (FORCE)`);
+ const index = o.databases.indexOf(database); if (index >= 0) o.databases.splice(index, 1);
}
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}`);
+ const { database, ...place } = await fresh(`${schedule.label}-${role}`);
const config: RobotConfig = { kind: o.engine, ...place, schedule, worktrees: o.worktrees ?? 2, statePath: join(place.root, 'state.json'), ...extra };
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], 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, deferred: result.deferred, trace: result.trace, duration_ms: performance.now() - at };
+ const outcome = async (): Promise<RobotRun & { counts?: Record<string, number> }> => {
+ if (role === 'run' && extra.fault) {
+ const reached = await Promise.race([child.event('fault', 600_000).then(e => ({ fault: e })), child.event('done', 600_000).then(e => ({ done: e }))]);
+ if ('done' in reached) {
+ const result = reached.done.result as RobotOutcome;
+ return { ...base, crashed: false, violations: result.violations, deferred: result.deferred, trace: result.trace, duration_ms: performance.now() - at };
+ }
+ await child.kill();
+ 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, deferred: result.deferred, trace: result.trace, duration_ms: performance.now() - at };
}
- await child.kill();
- const recovered = o.spawn(path, o.home, 'robot', ['recover'], environment); o.track(recovered);
- const result = (await recovered.done()).result as RobotOutcome;
- return { ...base, crashed: true, violations: result.violations, deferred: result.deferred, trace: result.trace, duration_ms: performance.now() - at };
- }
- const result = (await child.done()).result as RobotOutcome;
- return { ...base, crashed: false, violations: result.violations, deferred: result.deferred, trace: result.trace, counts: result.counts, duration_ms: performance.now() - at };
+ const result = (await child.done()).result as RobotOutcome;
+ return { ...base, crashed: false, violations: result.violations, deferred: result.deferred, trace: result.trace, counts: result.counts, duration_ms: performance.now() - at };
+ };
+ const run = await outcome();
+ if (!run.violations.length) await release(database);
+ return run;
}
const record = (run: RobotRun) => {
runs.push(run);
diff --git a/scripts/persistence/validate.ts b/scripts/persistence/validate.ts
index de376e06b2..77000ca53b 100644
--- a/scripts/persistence/validate.ts
+++ b/scripts/persistence/validate.ts
@@ -7,7 +7,7 @@ import postgres from '#postgres'
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, diagnosticError, retentionMetadata } from './failure-diagnostics.ts';
+import { boundedDiagnostic, connectionDiagnostic, diagnosticError, retentionMetadata } from './failure-diagnostics.ts';
import { FULL_ROBOT_SECONDS, replayEntries, runDigest, runRobotPhase, type RobotRun } from './robot-driver.ts';
import { shrinkRun } from './shrink.ts';
@@ -215,6 +215,7 @@ export async function runValidation(options: ValidationOptions) {
assert(response.ok, 'Owner diagnostic endpoint failed'); return response.json();
}, 1_750))),
}));
+ if (admin) manifest.connection_diagnostic = await boundedDiagnostic(() => connectionDiagnostic(admin!));
throw error;
}
finally {
diff --git a/test/e2e/persistence-robot-fixture-release.test.ts b/test/e2e/persistence-robot-fixture-release.test.ts
new file mode 100644
index 0000000000..1027694ad7
--- /dev/null
+++ b/test/e2e/persistence-robot-fixture-release.test.ts
@@ -0,0 +1,75 @@
+/**
+ * The crash robot gives each run its own database. Through a transaction-mode
+ * pooler every server connection a run opened stays in that database's pool
+ * until the pooler's idle timeout (PgBouncer: 600 s, a full robot budget), so
+ * a 600 s run that kept every passed run's database alive until the end
+ * crossed `max_connections` at about the 25th run (master f250a517c, the
+ * postgres / Bun 1.4.0 cell). The driver now drops a run's database as soon as
+ * the run passes, which ends those backends with it.
+ *
+ * Fails before the fix: the passed run's database is still listed and still
+ * exists when the phase returns. After: the list is empty, the database is
+ * gone and no backend is attached to it, through the pooler too when
+ * GBRAIN_PGBOUNCER_URL names one.
+ */
+import { describe, expect, test } from 'bun:test';
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import postgres from '#postgres'
+import { crossBoundarySequences } from '../../scripts/persistence/generator.ts';
+import { connectionDiagnostic } from '../../scripts/persistence/failure-diagnostics.ts';
+import { ROBOT_TOPOLOGY, runRobotPhase, type RobotRun } from '../../scripts/persistence/robot-driver.ts';
+import { spawnWorker } from '../../scripts/persistence/validate.ts';
+import { assertSafeE2eDatabaseUrl } from '../helpers/db-guard.ts';
+import { hasDatabase } from './helpers.ts';
+
+const direct = process.env.DATABASE_URL;
+const pooled = process.env.GBRAIN_PGBOUNCER_URL;
+
+describe.skipIf(!hasDatabase())('crash robot fixture databases', () => {
+ test(`a passed run's database is dropped before the next run starts${pooled ? ' (through the pooler)' : ''}`, async () => {
+ assertSafeE2eDatabaseUrl(direct!);
+ const created: string[] = [];
+ const admin = postgres(direct!, { max: 1, onnotice() {} });
+ const recording = new Proxy(admin, { get(target, key, receiver) {
+ if (key !== 'unsafe') return Reflect.get(target, key, receiver);
+ return (query: string, ...rest: unknown[]) => {
+ const match = /^CREATE DATABASE (\S+)/.exec(query); if (match) created.push(match[1]);
+ return (target.unsafe as (...args: unknown[]) => unknown)(query, ...rest);
+ };
+ } }) as typeof admin;
+ const scratch = mkdtempSync(join(tmpdir(), 'gbrain-robot-release-')); const home = join(scratch, 'home');
+ const children: ReturnType<typeof spawnWorker>[] = []; const databases: string[] = [];
+ const schedule = crossBoundarySequences(ROBOT_TOPOLOGY, 5105)[0];
+ const replay: RobotRun[] = [{ schedule: schedule.label, seed: schedule.seed, length: schedule.ops.length, crashed: false, violations: [], duration_ms: 0 }];
+ try {
+ const result = await runRobotPhase({ engine: 'postgres', seed: 5105, seconds: 0, scratch, home, admin: recording, databaseUrl: direct, databases,
+ pooledUrl: pooled, spawn: spawnWorker, track: child => { children.push(child); }, replay, log() {} });
+ expect(result.runs.map(run => run.violations)).toEqual([[]]);
+ expect(created).toHaveLength(1);
+ const [attached] = await admin`SELECT count(*)::int AS backends FROM pg_stat_activity WHERE datname = ${created[0]}`;
+ expect(attached.backends).toBe(0);
+ const [exists] = await admin`SELECT count(*)::int AS databases FROM pg_database WHERE datname = ${created[0]}`;
+ expect(exists.databases).toBe(0);
+ expect(databases).toEqual([]);
+ } finally {
+ await Promise.allSettled(children.map(child => child.kill()));
+ for (const database of databases) await admin.unsafe(`DROP DATABASE IF EXISTS ${database} WITH (FORCE)`);
+ await admin.end();
+ rmSync(scratch, { recursive: true, force: true });
+ }
+ }, 120_000);
+
+ test('the connection diagnostic reports slots by database class, state and wait class only', async () => {
+ const admin = postgres(direct!, { max: 1, onnotice() {} });
+ try {
+ await admin`SELECT 1`;
+ const report = await connectionDiagnostic(admin);
+ expect(report.max_connections).toMatch(/^\d+$/);
+ expect(report.backends).toBeGreaterThanOrEqual(1);
+ expect(report.groups.some(group => group.databases === 'other' && group.state === 'active')).toBe(true);
+ for (const group of report.groups) expect(Object.keys(group).sort()).toEqual(['backends', 'database_count', 'databases', 'state', 'wait_event_type']);
+ } finally { await admin.end(); }
+ });
+});