Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

bench: #6278 managed-sync stall reproduction (Phase 0.2) and its Ubicloud VM bootstrap

garrytand99e2b435ba0
diff --git a/scripts/bench/managed-sync-stall-repro.ts b/scripts/bench/managed-sync-stall-repro.ts
new file mode 100755
index 0000000000..5724e7bb46
--- /dev/null
+++ b/scripts/bench/managed-sync-stall-repro.ts
@@ -0,0 +1,566 @@
+#!/usr/bin/env bun
+/**
+ * #6278 managed-sync stall reproduction (plan Phase 0.2–0.5). Opt-in, never
+ * run in CI. Builds the reporter's shape and records what a stuck preparation
+ * is waiting on, without fixing anything.
+ *
+ * bun scripts/bench/managed-sync-stall-repro.ts [--files 15000] [--history 1500] [--legacy-facts 1000]
+ * [--marker-pages 20] [--doomed-pages 12] [--drip-rows 20] [--backlog-marker-pages 20] [--rtt 57] [--pool-size 10] [--pooler pgbouncer|none]
+ * [--cli-repo <checkout>] [--max-minutes 90] [--passes 3] [--sample-seconds 30] [--adoption-interval 60]
+ * [--stall-minutes 5] [--stall-kill-minutes 15] [--seed 1] [--label <name>] [--out <dir>] [--keep] [--inspect] [--inspect-port 6499]
+ * [--pg-port 55432] [--proxy-port 55433] [--api-port 58474] [--pooler-port 55434]
+ *
+ * Topology: pgvector Postgres in Docker, a transaction-mode PgBouncer in front
+ * of it (startup parameters such as statement_timeout ignored, as Supavisor
+ * does), toxiproxy in front of the pooler with `--rtt` ms of round trip, and
+ * every gbrain process pointed at the proxy with GBRAIN_POOL_SIZE=--pool-size.
+ * `--cli-repo` names the gbrain checkout under test (default: this one), so the
+ * same fixture runs on a release commit and on a branch head; that checkout's
+ * engine initializes the schema.
+ *
+ * Fixture (one git source, `bench`): `--history` pages imported in classic
+ * mode before activation, then `--files` new pages committed as the backlog.
+ * Seeded on the history pages, before activation:
+ * (a) `--marker-pages` entity pages whose timeline section carries two facts
+ * fences (a `repeated_marker` defect in the stored body) and legacy rows,
+ * so a fact-adoption write targets a page whose body cannot compile;
+ * (b) `--legacy-facts` unfenced fact rows (`row_num IS NULL`) spread over the
+ * other entity pages: one of the four shapes that do not round-trip
+ * through renderFactsTable → parseFactsFence (trailing whitespace, leading
+ * whitespace, whitespace-only, CRLF) on each of `--doomed-pages` pages, and
+ * round-tripping controls (pipes, newlines, backslashes, backticks, plain)
+ * everywhere, so most adoptions succeed and the doomed pages are refused
+ * on every replan. After activation the adoption loop drips `--drip-rows`
+ * more control rows before each run (the inline writer's DB-only
+ * fallback keeps producing such rows), so adoption writes keep landing
+ * mid-sync instead of only in the first minute.
+ * The backlog also carries `--backlog-marker-pages` repeated-marker pages, to
+ * see whether the managed screen holds a sync member before admission.
+ *
+ * Drive: `timeout 3600 gbrain sync --source bench --no-pull --no-embed` in a
+ * non-TTY (stdout/stderr piped), re-run up to `--passes` times until synced,
+ * while a second process runs `gbrain dream --phase extract_facts --source bench`
+ * every `--adoption-interval` seconds so adoption writes land mid-sync. Every
+ * `--sample-seconds` the sampler records, through the pooler: the running
+ * requests (request_id, operation, kind, claim_phase, blocked_reason),
+ * pg_stat_activity (pid, state, wait event, xact/query age, query head), the
+ * queue state counts and `gbrain sources writer status --probe --json`; and from
+ * the admin connection: lock waits with their blockers. `SHOW statement_timeout`
+ * is read once through the pooler. Every gbrain process writes GBRAIN_SQL_TRACE,
+ * so the sync process's last completed round trips are known at any moment.
+ *
+ * A stall is `--stall-minutes` without a new committed sync request while a
+ * sync pass runs; on detection a deep capture (pg_locks, pg_stat_activity,
+ * blocking pids, the sync process's last 50 trace records, writer status) goes
+ * to `stall-<pass>.json`, and after `--stall-kill-minutes` of stall the pass is
+ * killed (SIGTERM, the watchdog would otherwise take an hour). The report
+ * (`report.json`) carries pages/min per pass, time to stall, failed receipts by
+ * kind and error, holds written and the adoption outcomes (Phase 0.5).
+ */
+import { appendFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { dirname, join, resolve } from 'node:path';
+import { execFileSync } from 'node:child_process';
+import { randomBytes } from 'node:crypto';
+import postgres from '#postgres';
+import { generateScaleFixture } from '../scale/fixture.ts';
+import { renderFactsTable, type ParsedFact } from '../../src/core/facts-fence.ts';
+import { resolveSessionTimeouts } from '../../src/core/db.ts';
+import { BENCH_SQL, readTrace, round1, startHarness, type Harness, type TraceRecord } from './managed-sync-catchup-lib.ts';
+
+const REPO = resolve(import.meta.dir, '../..');
+function flag(name: string, fallback: string): string {
+ const i = process.argv.indexOf(`--${name}`);
+ return i >= 0 && process.argv[i + 1] ? process.argv[i + 1]! : fallback;
+}
+const worker = flag('worker', '');
+if (worker) await runWorker(worker);
+
+const CLI_REPO = resolve(flag('cli-repo', REPO));
+const CLI = join(CLI_REPO, 'src/cli.ts');
+if (!existsSync(CLI)) { console.error(`--cli-repo has no src/cli.ts: ${CLI_REPO}`); process.exit(2); }
+const CLI_VERSION = existsSync(join(CLI_REPO, 'VERSION')) ? readFileSync(join(CLI_REPO, 'VERSION'), 'utf8').trim() : 'unknown';
+const FILES = Number(flag('files', '15000'));
+const HISTORY = Number(flag('history', '1500'));
+const LEGACY_FACTS = Number(flag('legacy-facts', '1000'));
+const MARKER_PAGES = Number(flag('marker-pages', '20'));
+const DOOMED_PAGES = Number(flag('doomed-pages', '12'));
+const DRIP_ROWS = Number(flag('drip-rows', '20'));
+const BACKLOG_MARKER_PAGES = Number(flag('backlog-marker-pages', '20'));
+const RTT = Number(flag('rtt', '57'));
+const POOL_SIZE = flag('pool-size', '10');
+const POOLER = flag('pooler', 'pgbouncer');
+const MAX_MS = Number(flag('max-minutes', '90')) * 60_000;
+const PASSES = Number(flag('passes', '3'));
+const SAMPLE_MS = Number(flag('sample-seconds', '30')) * 1000;
+const ADOPTION_INTERVAL_MS = Number(flag('adoption-interval', '60')) * 1000;
+const STALL_MS = Number(flag('stall-minutes', '5')) * 60_000;
+const STALL_KILL_MS = Number(flag('stall-kill-minutes', '15')) * 60_000;
+const SEED = Number(flag('seed', '1'));
+const KEEP = process.argv.includes('--keep');
+/** `--inspect`: start each sync pass with Bun's inspector on 127.0.0.1:<--inspect-port> so a stalled process can be examined in place (Runtime.evaluate). */
+const INSPECT = process.argv.includes('--inspect');
+const INSPECT_PORT = Number(flag('inspect-port', '6499'));
+const LABEL = flag('label', `${gitDescribe(CLI_REPO)}-pool${POOL_SIZE}-${POOLER}`).replace(/[^\w.-]/g, '_');
+const OUT = resolve(flag('out', join(REPO, '.context', 'bench', `stall-repro-${LABEL}-${Date.now()}`)));
+if (POOLER !== 'pgbouncer' && POOLER !== 'none') { console.error(`--pooler takes pgbouncer or none; got ${POOLER}`); process.exit(2); }
+const SOURCE = 'bench';
+const SYNC_ARGS = ['sync', '--source', SOURCE, '--no-pull', '--no-embed'];
+
+function gitDescribe(repo: string): string {
+ try {
+ return execFileSync('git', ['-C', repo, 'rev-parse', '--abbrev-ref', 'HEAD'], { encoding: 'utf8' }).trim() + '@'
+ + execFileSync('git', ['-C', repo, 'rev-parse', '--short', 'HEAD'], { encoding: 'utf8' }).trim();
+ } catch { return 'unknown'; }
+}
+function git(root: string, ...args: string[]): string {
+ return execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
+}
+function commitAll(root: string, message: string): string {
+ git(root, 'add', '-A');
+ git(root, '-c', 'user.name=Bench Example', '-c', '[email protected]', 'commit', '-qm', message);
+ return git(root, 'rev-parse', 'HEAD');
+}
+const log = (msg: string) => { const line = `[stall-repro ${new Date().toISOString().slice(11, 19)}] ${msg}`; console.error(line); try { appendFileSync(join(OUT, 'log.txt'), line + '\n'); } catch { /* before OUT exists */ } };
+
+/** Child environment: hermetic home, no ambient database URL or provider keys, the pool size under test, unprepared behind the pooler. */
+function childEnv(home: string, extra: Record<string, string | undefined> = {}): Record<string, string | undefined> {
+ const env: Record<string, string | undefined> = { ...process.env };
+ for (const key of Object.keys(env)) if (/_API_KEY$|_API_TOKEN$|^DATABASE_URL$|^GBRAIN_DATABASE_URL$|^OPENAI_BASE_URL$/.test(key)) delete env[key];
+ return { ...env, GBRAIN_HOME: home, GBRAIN_NO_BANNER: '1', GBRAIN_BACKUP_CHECK: '0', GBRAIN_SKILLS_DIR: join(home, 'skills'), NO_COLOR: '1',
+ GBRAIN_POOL_SIZE: POOL_SIZE, ...(POOLER === 'pgbouncer' ? { GBRAIN_PREPARE: 'false' } : {}), ...extra };
+}
+
+interface CliRun { killed: boolean; code: number; stdout: string; stderr: string; wallMs: number; json: Record<string, unknown> | null }
+async function runCli(home: string, args: string[], env: Record<string, string | undefined> = {}, timeoutMs = 30 * 60_000): Promise<CliRun> {
+ const started = performance.now();
+ const child = Bun.spawn([process.execPath, CLI, ...args], { cwd: home, env: childEnv(home, env), stdin: 'ignore', stdout: 'pipe', stderr: 'pipe' });
+ let killed = false;
+ const timer = setTimeout(() => { killed = true; child.kill('SIGTERM'); setTimeout(() => child.kill('SIGKILL'), 30_000).unref(); }, timeoutMs);
+ const [stdout, stderr, code] = await Promise.all([new Response(child.stdout).text(), new Response(child.stderr).text(), child.exited]);
+ clearTimeout(timer);
+ const lastJson = stdout.trim().split('\n').reverse().find(l => l.startsWith('{'));
+ let json: Record<string, unknown> | null = null;
+ try { json = JSON.parse(stdout); } catch { try { json = lastJson ? JSON.parse(lastJson) : null; } catch { json = null; } }
+ return { killed, code, stdout, stderr, wallMs: performance.now() - started, json };
+}
+async function mustCli(home: string, args: string[], env: Record<string, string | undefined> = {}): Promise<CliRun> {
+ const r = await runCli(home, args, env);
+ if (r.code !== 0) throw new Error(`gbrain ${args.join(' ')} exited ${r.code}\nstdout: ${r.stdout.slice(-1500)}\nstderr: ${r.stderr.slice(-1500)}`);
+ return r;
+}
+
+function writeConfig(home: string, url: string): void {
+ mkdirSync(join(home, '.gbrain'), { recursive: true });
+ mkdirSync(join(home, 'skills'), { recursive: true });
+ if (!existsSync(join(home, 'skills', 'RESOLVER.md'))) writeFileSync(join(home, 'skills', 'RESOLVER.md'), '# Bench fixture skills\n');
+ writeFileSync(join(home, '.gbrain', 'config.json'), JSON.stringify({ engine: 'postgres', database_url: url, self_upgrade: { mode: 'off' }, embedding_disabled: true }, null, 2) + '\n');
+}
+
+/** Schema initialization and the worker side of the fixture run inside the checkout under test. */
+async function runWorker(kind: string): Promise<never> {
+ const cliRepo = process.env.REPRO_CLI_REPO!;
+ if (kind === 'init-schema') {
+ const { PostgresEngine } = await import(join(cliRepo, 'src/core/postgres-engine.ts'));
+ const engine = new PostgresEngine();
+ await engine.connect({ database_url: process.env.REPRO_DB_URL!, poolSize: 2 });
+ await engine.initSchema();
+ await engine.disconnect();
+ process.exit(0);
+ }
+ console.error(`unknown worker ${kind}`);
+ process.exit(2);
+}
+
+// ── Fixture ──────────────────────────────────────────────────────────────────
+
+const fixture = generateScaleFixture({ pages: Math.max(20, 2 * (HISTORY + FILES) + 4), seed: SEED });
+const defaultPages = fixture.pages.filter(p => p.sourceId === 'default');
+const historyPages = defaultPages.slice(0, HISTORY);
+const backlogPages = defaultPages.slice(HISTORY, HISTORY + FILES);
+const isEntity = (slug: string) => slug.startsWith('people/') || slug.startsWith('companies/');
+
+/** Two facts fences inside the timeline section: the `repeated_marker` defect the reporter saw at line 896 of a timeline. */
+function withRepeatedTimelineMarker(content: string, i: number): string {
+ const cut = content.indexOf('## Timeline');
+ const head = cut >= 0 ? content.slice(0, cut).trimEnd() : content.trimEnd();
+ const fence = (rowNum: number) => renderFactsTable([{ rowNum, claim: `Timeline fact ${rowNum} for page ${i}`, kind: 'fact', confidence: 1, visibility: 'world', notability: 'medium',
+ validFrom: '2025-01-01', source: 'bench-fixture', active: true } satisfies ParsedFact]);
+ return [head, '', '<!-- timeline -->', '', '## Timeline', '', `- **2025-03-0${1 + i % 9}** | Scale event ${i} recorded`, '', fence(1), '', `- **2025-04-0${1 + i % 9}** | Scale follow-up ${i}`, '', fence(2), ''].join('\n');
+}
+
+const markerHistory = new Set(historyPages.filter(p => isEntity(p.slug)).slice(0, MARKER_PAGES).map(p => p.slug));
+const markerBacklog = new Set(backlogPages.slice(0, BACKLOG_MARKER_PAGES).map(p => p.slug));
+function files(pages: typeof defaultPages, markers: Set<string>): Array<{ path: string; content: string }> {
+ return pages.map((p, i) => ({ path: `${p.slug}.md`, content: markers.has(p.slug) ? withRepeatedTimelineMarker(p.content, i) : p.content }));
+}
+function writeFiles(root: string, list: Array<{ path: string; content: string }>): void {
+ for (const p of list) { mkdirSync(dirname(join(root, p.path)), { recursive: true }); writeFileSync(join(root, p.path), p.content); }
+}
+
+/** Legacy claim shapes. `roundtrips: false` are the four shapes the parser normalizes and the renderer does not (plan 0.4). */
+const SHAPES: Array<{ name: string; roundtrips: boolean; make: (i: number) => string }> = [
+ { name: 'trailing_ws', roundtrips: false, make: i => `Legacy fact ${i} with trailing space ` },
+ { name: 'leading_ws', roundtrips: false, make: i => ` Legacy fact ${i} with leading space` },
+ { name: 'whitespace_only', roundtrips: false, make: () => ' ' },
+ { name: 'crlf', roundtrips: false, make: i => `Legacy fact ${i} line one\r\nline two` },
+ { name: 'plain', roundtrips: true, make: i => `Legacy fact ${i} plain` },
+ { name: 'pipe', roundtrips: true, make: i => `Legacy fact ${i} with a | pipe` },
+ { name: 'newline', roundtrips: true, make: i => `Legacy fact ${i} line one\nline two` },
+ { name: 'backslash', roundtrips: true, make: i => `Legacy fact ${i} with a \\ backslash` },
+ { name: 'backtick', roundtrips: true, make: i => `Legacy fact ${i} with \`code\`` },
+];
+interface LegacyRow { slug: string; fact: string; shape: string; roundtrips: boolean; doomedPage: boolean; markerPage: boolean }
+/**
+ * `--legacy-facts` rows over the history entity pages: the marker pages first
+ * (controls only, so the adoption targets the stored defect), then
+ * `--doomed-pages` pages carrying one failing shape each (the reporter saw nine
+ * such refusals per pass) plus controls, then controls over the rest, so most
+ * adoptions succeed and land as maintenance writes.
+ */
+function planLegacyRows(): LegacyRow[] {
+ const entities = historyPages.filter(p => isEntity(p.slug)).map(p => p.slug);
+ const rows: LegacyRow[] = [];
+ if (!entities.length) return rows;
+ const perPage = Math.max(2, Math.ceil(LEGACY_FACTS / Math.max(1, Math.min(entities.length, Math.ceil(LEGACY_FACTS / 4)))));
+ const failing = SHAPES.filter(s => !s.roundtrips), controls = SHAPES.filter(s => s.roundtrips);
+ const ordered = [...entities.filter(slug => markerHistory.has(slug)), ...entities.filter(slug => !markerHistory.has(slug))];
+ for (let page = 0, i = 0; rows.length < LEGACY_FACTS; page++) {
+ const slug = ordered[page % ordered.length]!;
+ const marker = markerHistory.has(slug);
+ const doomed = !marker && page >= markerHistory.size && page < markerHistory.size + DOOMED_PAGES;
+ for (let k = 0; k < perPage && rows.length < LEGACY_FACTS; k++, i++) {
+ const shape = doomed && k === 0 ? failing[(page - markerHistory.size) % failing.length]! : controls[i % controls.length]!;
+ rows.push({ slug, fact: shape.make(i), shape: shape.name, roundtrips: shape.roundtrips, doomedPage: doomed, markerPage: marker });
+ }
+ }
+ return rows;
+}
+/** Pages the drip feeds after activation: entity pages that are neither marker nor doomed pages. */
+function dripPages(legacy: LegacyRow[]): string[] {
+ const excluded = new Set(legacy.filter(r => r.doomedPage || r.markerPage).map(r => r.slug));
+ return historyPages.filter(p => isEntity(p.slug) && !excluded.has(p.slug) && !markerHistory.has(p.slug)).map(p => p.slug);
+}
+
+// ── Run ──────────────────────────────────────────────────────────────────────
+
+interface Row { db: string; home: string; root: string; trace: string; proxyUrl: string; directUrl: string; poolerUrl: string | null }
+
+let harness: Harness;
+
+async function admin<T>(url: string, fn: (sql: ReturnType<typeof postgres>) => Promise<T>, prepare = true, connection?: Record<string, string>): Promise<T> {
+ const sql = postgres(url, { max: 1, onnotice: () => {}, prepare, connect_timeout: 20, ...(connection ? { connection } : {}) });
+ try { return await fn(sql); } finally { await sql.end({ timeout: 5 }).catch(() => undefined); }
+}
+
+async function setup(): Promise<{ row: Row; legacy: LegacyRow[] }> {
+ const db = `gbrain_stall_${randomBytes(3).toString('hex')}`;
+ await admin(harness.adminUrl, sql => sql.unsafe(`CREATE DATABASE ${db}`));
+ const directUrl = harness.directUrl(db);
+ const home = mkdtempSync(join(tmpdir(), 'gbrain-stall-'));
+ writeConfig(home, directUrl);
+ const started = performance.now();
+ const init = Bun.spawnSync([process.execPath, import.meta.path, '--worker', 'init-schema'], { cwd: CLI_REPO, stdout: 'pipe', stderr: 'pipe',
+ env: { ...childEnv(home), REPRO_CLI_REPO: CLI_REPO, REPRO_DB_URL: directUrl } });
+ if (init.exitCode !== 0) throw new Error(`schema init in ${CLI_REPO} failed: ${init.stderr.toString().slice(-2000)}`);
+ log(`schema initialized by ${CLI_REPO} (${CLI_VERSION}) in ${round1((performance.now() - started) / 1000)} s`);
+
+ const root = join(home, `repo-${SOURCE}`);
+ mkdirSync(root, { recursive: true });
+ git(root, 'init', '-q');
+ writeFiles(root, files(historyPages, markerHistory));
+ writeFileSync(join(root, 'README.md'), '# Bench source\n');
+ commitAll(root, 'history');
+ await mustCli(home, ['sources', 'add', SOURCE, '--path', root, '--no-federated']);
+ const classic = await mustCli(home, [...SYNC_ARGS, '--json'], { GBRAIN_SQL_TRACE_LABEL: 'setup' });
+ log(`classic history sync: ${HISTORY} pages in ${round1(classic.wallMs / 1000)} s`);
+
+ const legacy = planLegacyRows();
+ await admin(directUrl, async sql => {
+ for (let at = 0; at < legacy.length; at += 200) {
+ const batch = legacy.slice(at, at + 200);
+ await sql.unsafe(`INSERT INTO facts (source_id, entity_slug, fact, kind, visibility, notability, valid_from, source, confidence)
+ SELECT $1, slug, fact, 'fact', 'private', 'medium', '2026-02-05T13:45:12Z', 'mcp:remember', 0.9 FROM unnest($2::text[], $3::text[]) AS t(slug, fact)`,
+ [SOURCE, batch.map(r => r.slug), batch.map(r => r.fact)]);
+ }
+ });
+ const pending = await admin(directUrl, async sql => Number((await sql.unsafe(`SELECT count(*)::int AS n FROM facts WHERE source_id=$1 AND row_num IS NULL AND expired_at IS NULL`, [SOURCE]))[0]!.n));
+ log(`seeded ${legacy.length} legacy fact rows (${pending} pending) over ${new Set(legacy.map(r => r.slug)).size} pages; ${markerHistory.size} history + ${markerBacklog.size} backlog repeated-marker pages`);
+
+ const state = (await mustCli(home, ['sources', 'writer', 'status', '--json'])).json!.admin_state as string;
+ await mustCli(home, ['sources', 'writer', 'claim', SOURCE, '--path', root, '--admin-intent', 'writer_claim', '--expected-state', state, '--json']);
+ const state2 = (await mustCli(home, ['sources', 'writer', 'status', '--json'])).json!.admin_state as string;
+ const activated = await mustCli(home, ['sources', 'writer', 'activate', '--confirm-quiesced', '--admin-intent', 'writer_activate', '--expected-state', state2, '--json']);
+ if (activated.json?.enabled !== true) throw new Error(`activation did not enable managed persistence: ${activated.stdout}`);
+ writeFiles(root, files(backlogPages, markerBacklog));
+ commitAll(root, 'backlog');
+ log(`backlog committed: ${backlogPages.length} pages`);
+
+ const proxyUrl = harness.proxyUrl(db);
+ writeConfig(home, proxyUrl);
+ await harness.setRtt(RTT);
+ const poolerUrl = harness.pooler ? (() => { const u = new URL(harness.adminUrl); u.hostname = '127.0.0.1'; u.port = String(harness.pooler!.listen).split(':')[1]!; u.pathname = `/${db}`; return u.toString(); })() : null;
+ return { row: { db, home, root, trace: join(OUT, 'sql-trace.log'), proxyUrl, directUrl, poolerUrl }, legacy };
+}
+
+const SAMPLE_SQL = {
+ running: `${BENCH_SQL} SELECT request_id, operation, intent->>'kind' AS kind, intent->>'group' AS grp, claim_phase, blocked_reason, state, publication_started,
+ claim_expires_at < now() AS claim_lapsed, (extract(epoch FROM now()-created_at)*1000)::int AS age_ms, (extract(epoch FROM now()-updated_at)*1000)::int AS since_update_ms
+ FROM persistence_requests WHERE state IN ('running','recovering') ORDER BY sequence`,
+ activity: `${BENCH_SQL} SELECT pid, state, application_name, backend_type, wait_event_type, wait_event, (extract(epoch FROM now()-xact_start)*1000)::int AS xact_age_ms,
+ (extract(epoch FROM now()-query_start)*1000)::int AS query_age_ms, (extract(epoch FROM now()-state_change)*1000)::int AS state_age_ms, left(query, 200) AS query,
+ pg_blocking_pids(pid) AS blocked_by
+ FROM pg_stat_activity WHERE datname = current_database() AND pid <> pg_backend_pid() ORDER BY xact_start NULLS LAST`,
+ states: `${BENCH_SQL} SELECT coalesce(intent->>'kind', operation) AS kind, state, count(*)::int AS n FROM persistence_requests GROUP BY 1,2 ORDER BY 1,2`,
+ committedSync: `${BENCH_SQL} SELECT count(*)::int AS n FROM persistence_requests WHERE state='committed' AND intent->>'kind' IN ('managed_sync_import','managed_sync_delete')`,
+ failed: `${BENCH_SQL} SELECT request_id, operation, intent->>'kind' AS kind, slug, error_code, left(error_message, 240) AS error_message, blocked_reason, completed_at
+ FROM persistence_requests WHERE state IN ('failed','conflict','cancelled') ORDER BY completed_at DESC NULLS LAST LIMIT 40`,
+ holds: `${BENCH_SQL} SELECT op, fingerprint, completed_keys->0 AS record FROM op_checkpoints WHERE op IN ('sync-hold','sync-hold-summary') ORDER BY op, fingerprint`,
+ locks: `${BENCH_SQL} SELECT w.pid, w.application_name AS waiting_app, left(w.query, 300) AS waiting_query, (extract(epoch FROM now()-w.query_start)*1000)::int AS wait_ms,
+ b.pid AS blocker_pid, coalesce(b.application_name,'') AS blocker_app, coalesce(b.state,'') AS blocker_state, left(coalesce(b.query,''), 300) AS blocker_query,
+ (extract(epoch FROM now()-b.xact_start)*1000)::int AS blocker_xact_ms
+ FROM pg_stat_activity w CROSS JOIN LATERAL unnest(pg_blocking_pids(w.pid)) AS bp(pid) LEFT JOIN pg_stat_activity b ON b.pid = bp.pid
+ WHERE w.datname = $1 AND w.wait_event_type = 'Lock'`,
+};
+
+interface SyncPass { pass: number; pid: number; inspect?: string; startedAt: number; endedAt?: number; code?: number; killedBy?: string; committedAtStart: number; committedAtEnd?: number; stallAt?: number; stallCaptured?: boolean }
+const state = { committed: 0, committedChangedAt: Date.now(), pass: null as SyncPass | null, samples: 0, stalls: [] as Array<Record<string, unknown>>, lastSample: null as Record<string, unknown> | null };
+
+function append(file: string, record: Record<string, unknown>): void { appendFileSync(join(OUT, file), JSON.stringify(record) + '\n'); }
+
+async function sampleOnce(row: Row, deep: boolean): Promise<Record<string, unknown>> {
+ const t = Date.now();
+ const via = row.poolerUrl ?? row.directUrl;
+ const pooled = await admin(via, async sql => ({
+ running: await sql.unsafe(SAMPLE_SQL.running), activity: await sql.unsafe(SAMPLE_SQL.activity), states: await sql.unsafe(SAMPLE_SQL.states),
+ committed: Number((await sql.unsafe(SAMPLE_SQL.committedSync))[0]!.n),
+ ...(deep ? { failed: await sql.unsafe(SAMPLE_SQL.failed), holds: await sql.unsafe(SAMPLE_SQL.holds) } : {}),
+ }), false).catch(error => ({ error: String(error instanceof Error ? error.message : error) }));
+ const locks = await admin(harness.adminUrl, sql => sql.unsafe(SAMPLE_SQL.locks, [row.db])).catch(error => [{ error: String(error) }]);
+ const sample: Record<string, unknown> = { t, at: new Date(t).toISOString(), pass: state.pass?.pass ?? null, sync_pid: state.pass?.pid ?? null, via: row.poolerUrl ? 'pooler' : 'direct', ...pooled, locks };
+ if ('committed' in pooled && typeof pooled.committed === 'number') {
+ if (pooled.committed !== state.committed) { state.committed = pooled.committed; state.committedChangedAt = t; }
+ sample.committed_stale_ms = t - state.committedChangedAt;
+ }
+ if (deep) {
+ const status = await runCli(row.home, ['sources', 'writer', 'status', '--probe', '--json'], { GBRAIN_SQL_TRACE: row.trace, GBRAIN_SQL_TRACE_LABEL: 'writer-status' }, 120_000);
+ sample.writer_status = status.json ?? { exit: status.code, stdout: status.stdout.slice(-2000), stderr: status.stderr.slice(-2000) };
+ }
+ return sample;
+}
+
+/** The sync process's most recent completed round trips and the time since its last one (a renewal every 10 s is expected while it holds a claim). */
+function traceTail(trace: string, pid: number | null, n = 60): Record<string, unknown> {
+ if (!pid || !existsSync(trace)) return { records: [] };
+ const records = readTrace(trace, r => r.pid === pid);
+ const last = records.at(-1);
+ const now = Date.now();
+ const byClass = new Map<string, { n: number; last_t: number }>();
+ for (const r of records.slice(-2000)) {
+ const head = r.sql.replace(/\s+/g, ' ').slice(0, 80);
+ const e = byClass.get(head) ?? { n: 0, last_t: 0 }; e.n++; e.last_t = Math.max(e.last_t, r.t); byClass.set(head, e);
+ }
+ return { total_round_trips: records.length, last_round_trip_age_ms: last ? now - last.t : null, in_flight_hint: 'a statement in flight is not yet in the trace; see activity[] for the backend side',
+ recent_statement_classes: [...byClass.entries()].sort((a, b) => b[1].last_t - a[1].last_t).slice(0, 25).map(([sql, e]) => ({ sql, n: e.n, last_age_ms: now - e.last_t })),
+ tail: records.slice(-n).map((r: TraceRecord) => ({ age_ms: now - r.t, ms: r.ms, pool: r.pool, conn: r.conn, backend: r.backend, kind: r.kind, sql: r.sql.replace(/\s+/g, ' ').slice(0, 300), ...(r.err ? { err: r.err } : {}) })) };
+}
+
+async function sampler(row: Row, stop: () => boolean): Promise<void> {
+ let n = 0;
+ while (!stop()) {
+ const deep = n % 2 === 0;
+ try {
+ const sample = await sampleOnce(row, deep);
+ state.lastSample = sample;
+ state.samples++;
+ append('samples.jsonl', sample);
+ const running = Array.isArray(sample.running) ? sample.running as Array<Record<string, unknown>> : [];
+ const stale = Number(sample.committed_stale_ms ?? 0);
+ log(`sample ${n}: pass=${sample.pass} committed=${state.committed} stale=${Math.round(stale / 1000)}s running=${running.length}`
+ + (running.length ? ` [${running.slice(0, 4).map(r => `${r.kind ?? r.operation}:${(r.claim_phase as { phase?: string } | null)?.phase ?? '?'}${r.blocked_reason ? '/' + r.blocked_reason : ''}`).join(', ')}]` : '')
+ + ` activity=${Array.isArray(sample.activity) ? (sample.activity as unknown[]).length : '?'} locks=${Array.isArray(sample.locks) ? (sample.locks as unknown[]).length : '?'}`);
+ const pass = state.pass;
+ if (pass && !pass.endedAt && stale >= STALL_MS) {
+ if (!pass.stallAt) { pass.stallAt = Date.now() - stale; log(`STALL: no committed sync request for ${Math.round(stale / 1000)} s in pass ${pass.pass} (pid ${pass.pid})`); }
+ if (!pass.stallCaptured) {
+ pass.stallCaptured = true;
+ const capture: Record<string, unknown> = { ...await sampleOnce(row, true), stall_since: new Date(pass.stallAt).toISOString(), trace: traceTail(row.trace, pass.pid),
+ running_detail: await admin(row.poolerUrl ?? row.directUrl, sql => sql.unsafe(`${BENCH_SQL} SELECT * FROM persistence_requests WHERE state IN ('running','recovering') ORDER BY sequence`), false).catch(e => String(e)),
+ queued_head: await admin(row.poolerUrl ?? row.directUrl, sql => sql.unsafe(`${BENCH_SQL} SELECT request_id, operation, intent->>'kind' AS kind, intent->>'group' AS grp, blocked_reason, created_at FROM persistence_requests WHERE state='queued' ORDER BY sequence LIMIT 10`), false).catch(e => String(e)) };
+ writeFileSync(join(OUT, `stall-${pass.pass}.json`), JSON.stringify(capture, null, 2) + '\n');
+ state.stalls.push({ pass: pass.pass, stall_since: capture.stall_since, running: capture.running, activity_summary: summarizeActivity(capture.activity), locks: capture.locks,
+ trace_last_round_trip_age_ms: (capture.trace as { last_round_trip_age_ms?: number }).last_round_trip_age_ms });
+ log(`stall capture written: stall-${pass.pass}.json`);
+ } else if (stale >= STALL_KILL_MS) {
+ log(`killing pass ${pass.pass} (pid ${pass.pid}) after ${Math.round(stale / 1000)} s without progress`);
+ pass.killedBy = 'stall_kill';
+ try { process.kill(pass.pid, 'SIGTERM'); } catch { /* already gone */ }
+ setTimeout(() => { try { process.kill(pass.pid, 'SIGKILL'); } catch { /* gone */ } }, 30_000).unref();
+ // second capture 20 s later, after the TERM: does the preparation settle or hang past shutdown?
+ setTimeout(() => { void sampleOnce(row, true).then(s => writeFileSync(join(OUT, `stall-${pass.pass}-after-term.json`), JSON.stringify({ ...s, trace: traceTail(row.trace, pass.pid) }, null, 2) + '\n')).catch(() => undefined); }, 20_000).unref();
+ }
+ }
+ } catch (error) { log(`sample failed: ${error instanceof Error ? error.message : String(error)}`); }
+ n++;
+ const until = Date.now() + SAMPLE_MS;
+ while (!stop() && Date.now() < until) await Bun.sleep(500);
+ }
+}
+
+function summarizeActivity(activity: unknown): unknown {
+ if (!Array.isArray(activity)) return activity;
+ return (activity as Array<Record<string, unknown>>).map(a => `${a.pid} ${a.application_name} ${a.state} ${a.wait_event_type ?? '-'}/${a.wait_event ?? '-'} xact=${a.xact_age_ms}ms q=${a.query_age_ms}ms blocked_by=${JSON.stringify(a.blocked_by)} :: ${String(a.query).slice(0, 120)}`);
+}
+
+/** `gbrain dream --phase extract_facts` on a cadence: the fact-adoption writes that land mid-sync (and the Phase 0.5 refusals). */
+async function adoptionLoop(row: Row, legacy: LegacyRow[], stop: () => boolean): Promise<void> {
+ if (ADOPTION_INTERVAL_MS <= 0) return;
+ const pool = dripPages(legacy);
+ const controls = SHAPES.filter(s => s.roundtrips);
+ for (let i = 0; !stop(); i++) {
+ let dripped = 0;
+ if (i > 0 && DRIP_ROWS > 0 && pool.length) {
+ const pages = Math.max(1, Math.ceil(DRIP_ROWS / 4));
+ const slugs = Array.from({ length: DRIP_ROWS }, (_, k) => pool[((i - 1) * pages + Math.floor(k / 4)) % pool.length]!);
+ const facts = slugs.map((_, k) => controls[k % controls.length]!.make(100_000 + i * 1000 + k));
+ // The managed writer guard allowlists the source for this transaction only; the seeded rows stand in for the inline writer's DB-only fallback.
+ dripped = await admin(row.directUrl, sql => sql.begin(async tx => {
+ await tx.unsafe(`SELECT set_config('gbrain.write_sources', $1, true)`, [JSON.stringify([SOURCE])]);
+ const inserted = await tx.unsafe(`INSERT INTO facts (source_id, entity_slug, fact, kind, visibility, notability, valid_from, source, confidence)
+ SELECT $1, slug, fact, 'fact', 'private', 'medium', '2026-02-05T13:45:12Z', 'mcp:remember', 0.9 FROM unnest($2::text[], $3::text[]) AS t(slug, fact) RETURNING id`, [SOURCE, slugs, facts]);
+ return inserted.length;
+ })).catch(error => { log(`drip failed: ${error instanceof Error ? error.message : String(error)}`); return 0; });
+ }
+ const r = await runCli(row.home, ['dream', '--phase', 'extract_facts', '--source', SOURCE, '--json'], { GBRAIN_SQL_TRACE: row.trace, GBRAIN_SQL_TRACE_LABEL: 'dream' }, 20 * 60_000);
+ const phases = (r.json?.phases as Array<Record<string, unknown>> | undefined) ?? (r.json?.phase_results as Array<Record<string, unknown>> | undefined) ?? [];
+ const xf = phases.find(p => p.phase === 'extract_facts') ?? null;
+ const details = (xf?.details ?? {}) as Record<string, unknown>;
+ const warnings = ((details.warnings as string[] | undefined) ?? (xf?.warnings as string[] | undefined) ?? []);
+ const record = { i, t: Date.now(), at: new Date().toISOString(), code: r.code, wall_ms: round1(r.wallMs), dripped, status: xf?.status ?? null, summary: xf?.summary ?? null,
+ unfenced_rows_fenced: details.unfencedRowsFenced ?? null, legacy_rows_pending: details.legacyRowsPending ?? null, pages_failed: details.pagesFailed ?? null,
+ fence_failed: warnings.filter(w => w.startsWith('FACTS_FENCE_FAILED')).length, warnings_sample: warnings.slice(0, 12), stderr_tail: r.stderr.slice(-1200), ...(r.json ? {} : { stdout_tail: r.stdout.slice(-1200) }) };
+ append('adoption.jsonl', record);
+ log(`adoption ${i}: exit=${r.code} dripped=${dripped} status=${record.status} fenced=${record.unfenced_rows_fenced} pending=${record.legacy_rows_pending} fence_failed=${record.fence_failed} ${round1(r.wallMs / 1000)}s`);
+ const until = Date.now() + ADOPTION_INTERVAL_MS;
+ while (!stop() && Date.now() < until) await Bun.sleep(500);
+ }
+}
+
+async function committedCount(row: Row): Promise<number> {
+ return admin(row.directUrl, async sql => Number((await sql.unsafe(SAMPLE_SQL.committedSync))[0]!.n));
+}
+
+async function syncPass(row: Row, pass: number): Promise<SyncPass> {
+ const out = Bun.file(join(OUT, `pass-${pass}.stdout`)).writer();
+ const err = Bun.file(join(OUT, `pass-${pass}.stderr`)).writer();
+ const child = Bun.spawn(['timeout', '3600', process.execPath, ...(INSPECT ? [`--inspect=127.0.0.1:${INSPECT_PORT}`] : []), CLI, ...SYNC_ARGS], { cwd: row.home, stdin: 'ignore', stdout: 'pipe', stderr: 'pipe',
+ env: childEnv(row.home, { GBRAIN_SQL_TRACE: row.trace, GBRAIN_SQL_TRACE_LABEL: 'cli-sync' }) });
+ // `timeout` is the parent; the gbrain process is its child. Find it for the kill and trace attribution.
+ await Bun.sleep(1500);
+ let gbrainPid = child.pid;
+ try { const kids = execFileSync('pgrep', ['-P', String(child.pid)], { encoding: 'utf8' }).trim().split('\n').filter(Boolean); if (kids[0]) gbrainPid = Number(kids[0]); } catch { /* keep the timeout pid */ }
+ const record: SyncPass = { pass, pid: gbrainPid, startedAt: Date.now(), committedAtStart: await committedCount(row), ...(INSPECT ? { inspect: `127.0.0.1:${INSPECT_PORT}` } : {}) };
+ state.pass = record;
+ state.committedChangedAt = Date.now();
+ log(`pass ${pass} started: timeout pid ${child.pid}, gbrain pid ${gbrainPid}`);
+ const pump = async (stream: ReadableStream<Uint8Array>, sink: { write(chunk: Uint8Array): unknown; flush(): unknown; end(): unknown }) => {
+ for await (const chunk of stream) { sink.write(chunk); await sink.flush(); }
+ await sink.end();
+ };
+ const [code] = await Promise.all([child.exited, pump(child.stdout as ReadableStream<Uint8Array>, out), pump(child.stderr as ReadableStream<Uint8Array>, err)]);
+ record.endedAt = Date.now();
+ record.code = code;
+ record.committedAtEnd = await committedCount(row);
+ if (code === 124 && !record.killedBy) record.killedBy = 'timeout_3600';
+ state.pass = null;
+ const stderr = readFileSync(join(OUT, `pass-${pass}.stderr`), 'utf8');
+ const stdout = readFileSync(join(OUT, `pass-${pass}.stdout`), 'utf8');
+ log(`pass ${pass} ended: code=${code} ${record.killedBy ?? ''} committed ${record.committedAtStart} -> ${record.committedAtEnd} in ${round1((record.endedAt - record.startedAt) / 1000)} s; stderr tail: ${stderr.slice(-300).replace(/\n/g, ' | ')}`);
+ append('passes.jsonl', { ...record, stdout_tail: stdout.slice(-1500), stderr_persistence_lines: stderr.split('\n').filter(l => l.includes('[persistence]')).slice(0, 40),
+ stderr_tail: stderr.slice(-1500) });
+ return record;
+}
+
+function statusOf(pass: number): string | null {
+ const text = readFileSync(join(OUT, `pass-${pass}.stdout`), 'utf8') + readFileSync(join(OUT, `pass-${pass}.stderr`), 'utf8');
+ const m = text.match(/"sync_status"\s*:\s*"(\w+)"/) ?? text.match(/\b(synced|up to date|up_to_date|first_sync|partial|stopped)\b/i);
+ return m ? m[1]!.toLowerCase() : null;
+}
+
+mkdirSync(OUT, { recursive: true });
+log(`out: ${OUT}`);
+log(`cli: ${CLI_REPO} (${CLI_VERSION}, ${gitDescribe(CLI_REPO)}); files=${FILES} history=${HISTORY} legacy=${LEGACY_FACTS} markers=${MARKER_PAGES}+${BACKLOG_MARKER_PAGES} rtt=${RTT} pool=${POOL_SIZE} pooler=${POOLER}`);
+harness = await startHarness({ pgPort: Number(flag('pg-port', '55432')), proxyPort: Number(flag('proxy-port', '55433')), apiPort: Number(flag('api-port', '58474')),
+ keep: KEEP, poolerPort: POOLER === 'pgbouncer' ? Number(flag('pooler-port', '55434')) : undefined });
+const report: Record<string, unknown> = {
+ schema: 'gbrain.bench.managed-sync-stall-repro/v1', label: LABEL, cli_repo: CLI_REPO, cli_version: CLI_VERSION, cli_commit: gitDescribe(CLI_REPO), harness_commit: gitDescribe(REPO),
+ started_at: new Date().toISOString(),
+ params: { files: FILES, history: HISTORY, legacy_facts: LEGACY_FACTS, marker_pages: MARKER_PAGES, backlog_marker_pages: BACKLOG_MARKER_PAGES, rtt_ms: RTT, pool_size: Number(POOL_SIZE), pooler: POOLER,
+ doomed_pages: DOOMED_PAGES, drip_rows: DRIP_ROWS, max_minutes: MAX_MS / 60_000, passes: PASSES, sample_seconds: SAMPLE_MS / 1000, adoption_interval_s: ADOPTION_INTERVAL_MS / 1000, stall_minutes: STALL_MS / 60_000, stall_kill_minutes: STALL_KILL_MS / 60_000, seed: SEED },
+ pooler: harness.pooler, host: { cpus: navigator.hardwareConcurrency, platform: process.platform, bun: Bun.version },
+ rerun: `bun scripts/bench/managed-sync-stall-repro.ts ${process.argv.slice(2).join(' ')}`,
+};
+const save = () => writeFileSync(join(OUT, 'report.json'), JSON.stringify(report, null, 2) + '\n');
+let row: Row | null = null;
+let stopped = false;
+try {
+ const built = await setup();
+ row = built.row;
+ report.fixture = { database: row.db, home: row.home, root: row.root, backlog_entries: backlogPages.length, history_pages: historyPages.length,
+ legacy_rows: built.legacy.length, legacy_pages: new Set(built.legacy.map(r => r.slug)).size,
+ legacy_by_shape: Object.fromEntries(SHAPES.map(s => [s.name, built.legacy.filter(r => r.shape === s.name).length])),
+ doomed_pages: new Set(built.legacy.filter(r => r.doomedPage).map(r => r.slug)).size, adoptable_pages: new Set(built.legacy.filter(r => !r.doomedPage && !r.markerPage).map(r => r.slug)).size,
+ drip_pool_pages: dripPages(built.legacy).length, drip_rows_per_run: DRIP_ROWS,
+ marker_history_pages: [...markerHistory], marker_backlog_pages: [...markerBacklog] };
+ // The same startup parameters gbrain sends (db.ts resolveSessionTimeouts), through the pooler and directly: does the pooler keep them?
+ const showTimeouts = async (sql: ReturnType<typeof postgres>) => ({
+ statement_timeout: (await sql.unsafe('SHOW statement_timeout'))[0]!.statement_timeout, idle_in_transaction_session_timeout: (await sql.unsafe('SHOW idle_in_transaction_session_timeout'))[0]!.idle_in_transaction_session_timeout,
+ lock_timeout: (await sql.unsafe('SHOW lock_timeout'))[0]!.lock_timeout });
+ report.session_timeouts = { requested_startup_parameters: resolveSessionTimeouts(),
+ via_pooler: await admin(row.poolerUrl ?? row.proxyUrl, showTimeouts, false, resolveSessionTimeouts()).catch(e => String(e)),
+ direct: await admin(row.directUrl, showTimeouts, true, resolveSessionTimeouts()).catch(e => String(e)) };
+ log(`session timeouts: ${JSON.stringify(report.session_timeouts)}`);
+ save();
+ const stop = () => stopped;
+ const background = Promise.allSettled([sampler(row, stop), adoptionLoop(row, built.legacy, stop)]);
+ const passes: SyncPass[] = [];
+ const started = Date.now();
+ for (let pass = 1; pass <= PASSES && Date.now() - started < MAX_MS; pass++) {
+ const result = await syncPass(row, pass);
+ passes.push(result);
+ const status = statusOf(pass);
+ log(`pass ${pass} status: ${status}`);
+ report.passes = passes.map(p => ({ ...p, status: statusOf(p.pass), wall_s: p.endedAt ? round1((p.endedAt - p.startedAt) / 1000) : null,
+ pages_per_min: p.endedAt && p.committedAtEnd !== undefined ? round1((p.committedAtEnd - p.committedAtStart) / ((p.endedAt - p.startedAt) / 60_000)) : null,
+ time_to_stall_s: p.stallAt ? round1((p.stallAt - p.startedAt) / 1000) : null }));
+ save();
+ if (status && ['synced', 'up_to_date', 'up to date', 'first_sync'].includes(status)) break;
+ await Bun.sleep(5000);
+ }
+ stopped = true;
+ await background;
+ const final = await sampleOnce(row, true);
+ const failed = (final.failed as Array<Record<string, unknown>> | undefined) ?? [];
+ const failedAll = await admin(row.directUrl, sql => sql.unsafe(`${BENCH_SQL} SELECT operation, intent->>'kind' AS kind, error_code, state,
+ CASE WHEN error_message ~ 'repeated_marker' THEN 'repeated_marker' WHEN error_message ~ 'does not render its legacy fact' THEN 'adoption_roundtrip' ELSE left(error_message, 80) END AS error_class, count(*)::int AS n
+ FROM persistence_requests WHERE state IN ('failed','conflict','cancelled') GROUP BY 1,2,3,4,5 ORDER BY n DESC`));
+ const adoption = existsSync(join(OUT, 'adoption.jsonl')) ? readFileSync(join(OUT, 'adoption.jsonl'), 'utf8').trim().split('\n').filter(Boolean).map(l => JSON.parse(l)) : [];
+ report.result = { committed_sync_requests: state.committed, backlog_entries: backlogPages.length, states: final.states, stalls: state.stalls,
+ failed_receipts_by_kind_and_error: failedAll, failed_receipts_recent: failed, holds: final.holds, samples: state.samples,
+ adoption_runs: adoption.length, adoption_summary: adoption.map((a: Record<string, unknown>) => ({ i: a.i, status: a.status, dripped: a.dripped, fenced: a.unfenced_rows_fenced, pending: a.legacy_rows_pending, fence_failed: a.fence_failed, code: a.code })),
+ legacy_pending_at_end: await admin(row.directUrl, async sql => Number((await sql.unsafe(`SELECT count(*)::int AS n FROM facts WHERE source_id=$1 AND row_num IS NULL AND expired_at IS NULL`, [SOURCE]))[0]!.n)) };
+} catch (error) {
+ log(`failed: ${error instanceof Error ? error.stack : String(error)}`);
+ report.error = String(error instanceof Error ? error.stack : error).slice(0, 4000);
+} finally {
+ stopped = true;
+ report.finished_at = new Date().toISOString();
+ save();
+ log(`report: ${join(OUT, 'report.json')}`);
+ if (!KEEP && row) {
+ await admin(harness.adminUrl, sql => sql.unsafe(`DROP DATABASE IF EXISTS ${row!.db} WITH (FORCE)`)).catch(() => undefined);
+ rmSync(row.home, { recursive: true, force: true });
+ }
+ harness.stop();
+}
+process.exit(report.error ? 1 : 0);
diff --git a/scripts/bench/stall-repro-vm-setup.sh b/scripts/bench/stall-repro-vm-setup.sh
new file mode 100755
index 0000000000..a9bc652de0
--- /dev/null
+++ b/scripts/bench/stall-repro-vm-setup.sh
@@ -0,0 +1,56 @@
+#!/usr/bin/env bash
+# scripts/bench/stall-repro-vm-setup.sh — bootstrap one Ubicloud VM for
+# scripts/bench/managed-sync-stall-repro.ts (#6278 Phase 0). Runs as user
+# `ubi` (passwordless sudo) on a stock Ubuntu 24.04 image, inside the synced
+# checkout (~/work/gbrain). Installs Docker, git, bun, pulls the harness images,
+# installs frozen dependencies, and when RELEASE_COMMIT is set adds a worktree
+# of that commit beside the checkout (../gbrain-release) with its own
+# dependencies, so the same fixture runs on a release and on this branch.
+#
+# scripts/ubicloud/ubi-runner.sh run --setup scripts/bench/stall-repro-vm-setup.sh \
+# --env RELEASE_COMMIT=8e11aa1f -- 'bun scripts/bench/managed-sync-stall-repro.ts --cli-repo ../gbrain-release ...'
+set -euo pipefail
+
+BUN_VERSION="${BUN_VERSION:-1.4.2}"
+RELEASE_COMMIT="${RELEASE_COMMIT:-}"
+t0=$(date +%s)
+step() { echo "[stall-repro-setup +$(( $(date +%s) - t0 ))s] $*"; }
+
+echo force-unsafe-io | sudo tee /etc/dpkg/dpkg.cfg.d/99-gbrain-bench >/dev/null
+sudo rm -f /var/lib/man-db/auto-update
+apt_get() { sudo DEBIAN_FRONTEND=noninteractive NEEDRESTART_SUSPEND=1 apt-get -qq -o Acquire::Languages=none "$@" >/dev/null; }
+
+step "apt"
+apt_get update
+apt_get install -y --no-install-recommends docker.io git ca-certificates python3 procps postgresql-client jq unzip curl
+sudo usermod -aG docker "$USER" || true
+sudo systemctl start docker
+
+step "bun ${BUN_VERSION}"
+if ! command -v bun >/dev/null || [ "$(bun --version)" != "$BUN_VERSION" ]; then
+ curl -fsSL https://bun.sh/install | BUN_INSTALL="$HOME/.bun" bash -s "bun-v${BUN_VERSION}" >/dev/null
+fi
+export PATH="$HOME/.bun/bin:$PATH"
+grep -q '.bun/bin' "$HOME/.bashrc" || echo 'export PATH="$HOME/.bun/bin:$PATH"' >> "$HOME/.bashrc"
+grep -q '.bun/bin' "$HOME/.profile" || echo 'export PATH="$HOME/.bun/bin:$PATH"' >> "$HOME/.profile"
+bun --version
+
+step "docker images"
+sudo docker pull -q pgvector/pgvector:pg16 >/dev/null &
+sudo docker pull -q ghcr.io/shopify/toxiproxy:2.12.0 >/dev/null &
+sudo docker pull -q edoburu/pgbouncer@sha256:9c78945868a6a142c7fc40ccd843bbe5a606df163c7ffce4de70e0d628d696a2 >/dev/null &
+
+step "dependencies"
+bun install --frozen-lockfile >/dev/null
+
+if [ -n "$RELEASE_COMMIT" ]; then
+ step "release worktree ${RELEASE_COMMIT}"
+ git cat-file -e "${RELEASE_COMMIT}^{commit}" 2>/dev/null || git fetch -q origin "$RELEASE_COMMIT"
+ rm -rf ../gbrain-release
+ git worktree add -q --detach ../gbrain-release "$RELEASE_COMMIT"
+ (cd ../gbrain-release && bun install --frozen-lockfile >/dev/null && echo "release VERSION $(cat VERSION)")
+fi
+wait
+# The docker socket group takes effect on the next login; the bench shells out to `docker` directly, so make the socket world-usable on this throwaway VM.
+sudo chmod 666 /var/run/docker.sock
+step "ready: $(nproc) vCPU, $(free -g | awk '/Mem:/ {print $2}') GiB"