Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

bench: production-shaped scale soak (fixture, topology, record-only scoreboard, nightly workflow)

garrytan6f4d23cbb068
diff --git a/.github/workflows/nightly-watch.yml b/.github/workflows/nightly-watch.yml
index f6f0c1323a..d614d4f210 100644
--- a/.github/workflows/nightly-watch.yml
+++ b/.github/workflows/nightly-watch.yml
@@ -51,6 +51,7 @@ on:
- Scale tier
- Convergence nightly
- Sync freshness gate
+ - Production soak
- macOS 26 validation
- Semgrep
- OSV-Scanner
diff --git a/.github/workflows/production-soak.yml b/.github/workflows/production-soak.yml
new file mode 100644
index 0000000000..334c6b3b47
--- /dev/null
+++ b/.github/workflows/production-soak.yml
@@ -0,0 +1,97 @@
+name: Production soak
+
+# Production-shaped scale soak (GBRA-174; harness and procedure in
+# scripts/bench/production-soak/README.md). One cell per injected latency, each on
+# its own ephemeral Ubicloud runner (torn down when the job ends): a
+# deterministic large personal brain with years of git history and
+# database-side drift, Postgres behind a session-mode PgBouncer capped at 25 and
+# a transaction-mode PgBouncer, toxiproxy latency, and the production topology
+# (one resident serve owning sync, a jobs worker, CLI and MCP readers, an
+# external writer, put/remember, extract/embed --stale) for N hours.
+# Writes a JSON scoreboard per cell. Every gate is record-only: this workflow
+# never fails on a gate; it fails only when the harness itself breaks.
+# Nightly and on dispatch; never in the PR tier.
+
+on:
+ schedule:
+ - cron: '17 6 * * *'
+ workflow_dispatch:
+ inputs:
+ pages:
+ description: Fixture pages across the three sources (600000 is 2x the 300k bench)
+ type: string
+ default: '600000'
+ hours:
+ description: Soak duration per cell in hours
+ type: string
+ default: '2'
+ rtts:
+ description: Injected round-trip latencies in ms, comma-separated
+ type: string
+ default: '65,2'
+
+permissions:
+ contents: read
+
+concurrency:
+ group: ${{ github.workflow }}-${{ github.ref }}
+ cancel-in-progress: false
+
+jobs:
+ plan:
+ runs-on: ubicloud-standard-2-ubuntu-2404
+ timeout-minutes: 5
+ outputs:
+ rtts: ${{ steps.plan.outputs.rtts }}
+ pages: ${{ steps.plan.outputs.pages }}
+ hours: ${{ steps.plan.outputs.hours }}
+ steps:
+ - id: plan
+ env:
+ RTTS: ${{ inputs.rtts || '65,2' }}
+ PAGES: ${{ inputs.pages || '600000' }}
+ HOURS: ${{ inputs.hours || '2' }}
+ run: |
+ set -euo pipefail
+ [[ "$RTTS" =~ ^[0-9]+(,[0-9]+)*$ ]] || { echo "::error::rtts must be comma-separated integers, got '$RTTS'"; exit 1; }
+ [[ "$PAGES" =~ ^[0-9]+$ ]] && [ "$PAGES" -ge 2000 ] || { echo "::error::pages must be an integer >= 2000, got '$PAGES'"; exit 1; }
+ [[ "$HOURS" =~ ^[0-9]+(\.[0-9]+)?$ ]] || { echo "::error::hours must be a number, got '$HOURS'"; exit 1; }
+ {
+ echo "rtts=$(printf '%s' "$RTTS" | jq -Rc 'split(",") | map(tonumber)')"
+ echo "pages=$PAGES"
+ echo "hours=$HOURS"
+ } >> "$GITHUB_OUTPUT"
+
+ soak:
+ needs: plan
+ name: Soak (${{ matrix.rtt }} ms RTT)
+ runs-on: ubicloud-standard-16-ubuntu-2404
+ timeout-minutes: 600
+ strategy:
+ fail-fast: false
+ matrix:
+ rtt: ${{ fromJSON(needs.plan.outputs.rtts) }}
+ steps:
+ - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262
+ - name: Bootstrap (Docker images, bun, frozen dependencies)
+ timeout-minutes: 20
+ run: bash scripts/bench/production-soak/vm-setup.sh
+ - name: Fixture, load and soak
+ env:
+ PAGES: ${{ needs.plan.outputs.pages }}
+ HOURS: ${{ needs.plan.outputs.hours }}
+ RTT: ${{ matrix.rtt }}
+ run: |
+ set -o pipefail
+ bash scripts/bench/production-soak/run.sh --pages "$PAGES" --rtt-ms "$RTT" --hours "$HOURS" --out "$RUNNER_TEMP/soak-out" --label "rtt$RTT"
+ cat "$RUNNER_TEMP/soak-out/scoreboard.md" >> "$GITHUB_STEP_SUMMARY"
+ - name: Stop the topology
+ if: always()
+ run: docker rm -f soak-pg soak-bouncer-session soak-bouncer-txn soak-toxiproxy >/dev/null 2>&1 || true
+ - name: Upload the scoreboard, events and logs
+ if: always()
+ uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02
+ with:
+ name: production-soak-rtt${{ matrix.rtt }}
+ path: ${{ runner.temp }}/soak-out
+ if-no-files-found: warn
diff --git a/scripts/bench/production-soak/README.md b/scripts/bench/production-soak/README.md
new file mode 100644
index 0000000000..bdb8057922
--- /dev/null
+++ b/scripts/bench/production-soak/README.md
@@ -0,0 +1,53 @@
+# Production-shaped scale soak
+
+Opt-in harness that runs gbrain the way a large personal brain runs in
+production, for hours, and writes a pass/fail scoreboard. It exists because
+50k-300k clean synthetic pages never show the bugs a brain with years of
+history, connectors, private pages, held items and concurrent writers shows.
+Nightly in `.github/workflows/production-soak.yml`; never in the PR tier.
+
+## Pieces
+
+| File | Does |
+|---|---|
+| `fixture.ts` | Deterministic brain: three git sources built with `git fast-import` (52% / 43% / 5% of `--pages`). The `default` source has years of daily history with bulk imports, edits, moves, culls into `archive/<year>/`, plain deletes and merge commits whose side branches move and delete files; private pages (`visibility: private`, `access:` and `confidentiality:` aliases) with canary tokens; connector pages with facts fences; long meetings; timeline pages with hundreds of entries; megabyte chat archives, two over the 24 MB page limit. Its last `--backlog-days` come after the `import-base` tag and include files gbrain must hold. `source-b` is mostly static with cross-source twins; `source-c` is connector pages rewritten daily. `drift.jsonl` lists database-only pages (never committed) and pages history deleted that the database kept. |
+| `load.ts` | Imports each source with gbrain's own classic sync (the default source at `import-base`), writes the drift through the importer, activates managed persistence, runs the first managed sync, settles links and embeds through the loopback mock provider, then fast-forwards the default source so the soak starts with a backlog. |
+| `lib.ts` | Topology: Postgres, a session-mode PgBouncer capped at 25 clients (the 26th is refused, the EMAXCONNSESSION shape), a transaction-mode PgBouncer, and toxiproxy latency in front of both. `database_url` is the transaction lane and `GBRAIN_DIRECT_DATABASE_URL` the session lane. |
+| `soak.ts` | The production topology for `--hours`: one resident `gbrain serve --http` that owns sync (`sync.on_commit=true`), one `gbrain jobs work`, MCP stdio readers (warm, remote callers), CLI readers (cold), an external writer committing named paths every few minutes, put/remember through CLI and MCP, `extract --stale` and `embed --stale`, and samplers. |
+| `scoreboard.ts` | Turns `events.jsonl` into `scoreboard.json` and `scoreboard.md`; `--combine <dir>` merges cells. |
+| `run.sh`, `vm-setup.sh`, `ubicloud.sh` | One cell end to end; VM bootstrap; one Ubicloud VM per latency with an expiring name. |
+
+## Scoreboard
+
+Freshness (commit to keyword-searchable, p50/p95, unresolved commits, the
+longest watermark stall and whether holds froze it), search and query p50/p95
+cold (CLI) and warm (MCP), put and remember latency and pending writes,
+session-lane peak and refusals, holds over time by code, managed import-record
+coverage, managed sync jobs that stopped without applying anything and who
+owned the commit notifier, doctor red checks, version skew, resident memory,
+and the privacy invariant: every remote (MCP) response is scanned for any
+private page's canary or search token.
+
+Every gate is `record` mode: computed, printed, never failing a run. Moving a
+gate to `block` is a reviewed edit of `GATES` in `scoreboard.ts` after the
+release owner has seen several nightly runs.
+
+## Run it
+
+```bash
+# One machine (Docker required), small: about 20 minutes
+bash scripts/bench/production-soak/run.sh --pages 20000 --rtt-ms 65 --hours 0.5 --out /tmp/soak-out
+
+# Ubicloud, 600k pages, both latencies in parallel, VMs expire after 14 h
+scripts/ubicloud/ubi-runner.sh usage
+UBI_OWNER=<thread> scripts/bench/production-soak/ubicloud.sh start --pages 600000 --hours 3 --rtts 65,2
+scripts/bench/production-soak/ubicloud.sh status # tail of each cell's log
+scripts/bench/production-soak/ubicloud.sh collect # copy finished cells back, destroy their VMs, combine
+```
+
+`start` launches each cell detached on its VM, so the soak survives this
+machine sleeping; `collect` tears a VM down only after its cell finished, and
+the expiring VM name lets the reaper clean up a cell nobody collects.
+A 600k fixture builds in about 14 minutes on a standard-16 VM.
+Everything is keyless: embeddings and rerank go to a loopback mock provider.
+A fixture loads once; regenerate it for another load.
diff --git a/scripts/bench/production-soak/fixture.ts b/scripts/bench/production-soak/fixture.ts
new file mode 100644
index 0000000000..b57a9eeaca
--- /dev/null
+++ b/scripts/bench/production-soak/fixture.ts
@@ -0,0 +1,404 @@
+#!/usr/bin/env bun
+/**
+ * Production-shaped scale soak, step 1: a deterministic "large personal brain"
+ * fixture (GBRA-174). Opt-in bench code, never run in CI.
+ *
+ * bun scripts/bench/production-soak/fixture.ts --out <dir> [--pages 600000] [--seed 7]
+ * [--years 5] [--backlog-days 14] [--huge-mb 6] [--oversized 2]
+ *
+ * Writes three git sources under <dir>/<source>/repo with git fast-import, the
+ * database-side drift in <dir>/drift.jsonl and <dir>/manifest.json:
+ *
+ * default 52% of the pages, years of daily history: bulk connector imports,
+ * edits, moves (inbox triage, renamed people), culls into
+ * archive/<year>/, plain deletes, and merge commits whose side branch
+ * carries moves and deletes (the shape a commit-push integration
+ * leaves, which hides those deletions from a plain
+ * git log --diff-filter=D). Private pages (visibility: private, and
+ * the access / confidentiality aliases) carry canary tokens, connector
+ * pages carry facts fences, meetings run long, timeline pages carry
+ * hundreds of dated entries, and a few chat-archive pages are
+ * megabytes, two of them over the 24 MB page limit. The last
+ * --backlog-days of history come after the import-base tag, with a
+ * few files gbrain must hold (unreadable frontmatter, a broken facts
+ * fence, a frontmatter slug naming another page) and paths that a
+ * commit recreates after an earlier delete.
+ * source-b 43%, mostly static (a few bulk imports and sparse edits); 10% of
+ * its pages share a slug with a default page (cross-source twins).
+ * source-c 5%, connector pages whose facts fences a daily commit rewrites.
+ *
+ * drift.jsonl lists the pages the loader writes into the database only
+ * (load.ts): "db_only" pages no commit ever held, and "kept_deleted" pages whose
+ * files history deleted (half of them inside merged side branches) while the
+ * database kept them. These are the file-side/database-side disagreements
+ * behind held-deletion backlogs.
+ *
+ * Same --seed and --pages give the same commits (same SHAs), files and drift.
+ * Everything is generated words and placeholder names; nothing comes from a
+ * real brain.
+ */
+import { closeSync, mkdirSync, openSync, rmSync, writeFileSync, writeSync } from 'node:fs';
+import { join } from 'node:path';
+import { execFileSync } from 'node:child_process';
+import { renderFactsTable, type ParsedFact } from '../../../src/core/facts-fence.ts';
+import { PAGE_MAX_BYTES } from '../../../src/core/page-size-policy.ts';
+import { hash32, Rng } from '../hnsw-latent-corpus.ts';
+
+export interface FixtureOptions { pages: number; seed: number; years: number; backlogDays: number; hugeMb: number; oversized: number }
+export const DEFAULTS: FixtureOptions = { pages: 600_000, seed: 7, years: 5, backlogDays: 14, hugeMb: 6, oversized: 2 };
+export const SOURCES = [
+ { id: 'default', share: 0.52, history: 'daily' },
+ { id: 'source-b', share: 0.43, history: 'static' },
+ { id: 'source-c', share: 0.05, history: 'connector' },
+] as const;
+export type SourceId = typeof SOURCES[number]['id'];
+
+export const KINDS = ['person', 'company', 'meeting', 'note', 'concept', 'transcript', 'original', 'connector', 'timeline', 'chat'] as const;
+export type Kind = typeof KINDS[number];
+const MIX: Record<SourceId, number[]> = {
+ 'default': [0.14, 0.07, 0.18, 0.22, 0.09, 0.10, 0.08, 0.07, 0.05, 0],
+ 'source-b': [0.15, 0.08, 0.20, 0.25, 0.10, 0.12, 0.10, 0, 0, 0],
+ 'source-c': [0.10, 0.05, 0, 0, 0, 0, 0, 0.85, 0, 0],
+};
+export const PRIVATE_CLASSES = ['', 'visibility', 'access', 'confidentiality'] as const;
+export type PrivateClass = typeof PRIVATE_CLASSES[number];
+const DELETE_SHARE = 0.08, MOVE_SHARE = 0.06, CULL_SHARE = 0.07, TWIN_SHARE = 0.10;
+const T0 = Date.UTC(2021, 0, 4) / 1000;
+
+const SYL = ['ka', 'lo', 'mi', 'ten', 'ar', 'vis', 'no', 're', 'shu', 'pa', 'der', 'qui', 'lan', 'mo', 'zet', 'ri', 'bo', 'ex', 'ul', 'fen', 'tor', 'gal', 'sen', 'dra'];
+const FIRST = ['alice', 'bob', 'carol', 'dave', 'erin', 'frank', 'grace', 'heidi', 'ivan', 'judy', 'mallory', 'niaj', 'olivia', 'peggy', 'rupert', 'sybil', 'trent', 'victor', 'walter', 'yolanda'];
+const TOPICS = ['product', 'hiring', 'research', 'travel', 'health', 'finance', 'family', 'reading', 'ops', 'ideas'];
+const PROVIDERS = ['crm', 'calendar', 'email', 'notes-app'];
+/** A Zipf-ish vocabulary: drawing index floor(V * u^2) makes the first words common, the way real brains have hot terms. */
+const VOCAB = (() => { const rng = new Rng(0x5eed); const out: string[] = []; const seen = new Set<string>();
+ while (out.length < 6000) { let w = ''; const n = 2 + Math.floor(rng.next() * 3); for (let i = 0; i < n; i++) w += SYL[Math.floor(rng.next() * SYL.length)]; if (!seen.has(w)) { seen.add(w); out.push(w); } }
+ return out; })();
+const cap = (s: string) => s[0]!.toUpperCase() + s.slice(1);
+const b36 = (n: number, w = 7) => (n >>> 0).toString(36).padStart(w, '0');
+
+export interface SourcePlan { id: SourceId; lives: number; days: number; kind: Uint8Array; birth: Uint16Array; edits: Uint8Array; move: Uint16Array; cull: Uint16Array; del: Uint16Array; priv: Uint8Array; twinOf: Int32Array }
+const NEVER = 0xffff;
+
+/** Deterministic lifecycle of every page that ever lived in a source. */
+export function planSource(o: FixtureOptions, s: number): SourcePlan {
+ const src = SOURCES[s]!;
+ const days = Math.round(o.years * 365.25);
+ const target = Math.max(20, Math.round(o.pages * src.share));
+ const lives = src.history === 'daily' ? Math.round(target / (1 - DELETE_SHARE)) : target;
+ const p: SourcePlan = { id: src.id, lives, days, kind: new Uint8Array(lives), birth: new Uint16Array(lives), edits: new Uint8Array(lives), move: new Uint16Array(lives).fill(NEVER),
+ cull: new Uint16Array(lives).fill(NEVER), del: new Uint16Array(lives).fill(NEVER), priv: new Uint8Array(lives), twinOf: new Int32Array(lives).fill(-1) };
+ const mix = MIX[src.id];
+ const chats = src.history === 'daily' ? Math.max(o.oversized + 2, Math.round(o.pages / 30_000)) : 0;
+ const bulkDays = [0.05, 0.2, 0.35, 0.5, 0.7, 0.85].map(f => Math.floor(days * f));
+ const lastHistoryDay = days - o.backlogDays - 1;
+ for (let i = 0; i < lives; i++) {
+ const rng = new Rng(hash32(o.seed, s, i, 0x11fe));
+ let r = rng.next(), k = 0;
+ while (k < mix.length - 1 && r > mix[k]!) { r -= mix[k]!; k++; }
+ if (i < chats) k = KINDS.indexOf('chat');
+ p.kind[i] = k;
+ if (src.history === 'static') p.birth[i] = bulkDays[Math.floor(rng.next() * 3)]!;
+ else if (src.history === 'connector') p.birth[i] = Math.floor(days * rng.next() * 0.9);
+ else if (i >= chats && rng.next() < 0.24) p.birth[i] = bulkDays[Math.floor(rng.next() * bulkDays.length)]!;
+ else p.birth[i] = Math.min(days - 2, Math.floor(days * Math.sqrt(rng.next())));
+ if (p.birth[i]! >= lastHistoryDay && i % 4 !== 0) p.birth[i] = Math.floor(lastHistoryDay * rng.next());
+ const span = (from: number, to: number) => to - from > 1 ? from + 1 + Math.floor(rng.next() * (to - from - 1)) : NEVER;
+ let end = days;
+ if (src.history === 'daily' && i >= chats && rng.next() < DELETE_SHARE) { const d = span(p.birth[i]!, days); if (d !== NEVER) { p.del[i] = d; end = d; } }
+ let e = 0; for (let u = rng.next(); u < 0.5 && e < 6; u *= 2) e++;
+ if (src.history === 'static') e = rng.next() < 0.05 ? 1 : 0;
+ if (src.history === 'connector') e = 2 + Math.floor(rng.next() * 6);
+ p.edits[i] = e;
+ if (src.history === 'daily' && i >= chats) {
+ if (rng.next() < MOVE_SHARE) p.move[i] = span(p.birth[i]!, end);
+ if (rng.next() < CULL_SHARE) p.cull[i] = span(p.move[i] === NEVER ? p.birth[i]! : p.move[i]!, end);
+ }
+ const u = rng.next();
+ p.priv[i] = u < 0.03 ? 1 : u < 0.05 ? 2 : u < 0.055 ? 3 : 0;
+ if (src.history === 'static' && rng.next() < TWIN_SHARE) p.twinOf[i] = hash32(o.seed, i, 0x7717) % Math.round(target * 0.9);
+ }
+ return p;
+}
+
+/** Page header shared by every version: kind, names, birth date, privacy class, the unique search token and (private pages) a canary. */
+export function pageHead(o: FixtureOptions, p: SourcePlan, i: number) {
+ const s = SOURCES.findIndex(x => x.id === p.id);
+ const rng = new Rng(hash32(o.seed, s, i, 0xbead));
+ const kind = KINDS[p.kind[i]!]!;
+ const w = () => VOCAB[Math.floor(rng.next() * VOCAB.length)]!;
+ const first = FIRST[Math.floor(rng.next() * FIRST.length)]!, surname = w(), w1 = w(), w2 = w();
+ const date = new Date((T0 + p.birth[i]! * 86_400) * 1000).toISOString().slice(0, 10);
+ const id = b36(hash32(o.seed, s, i, 0x1d));
+ const priv = PRIVATE_CLASSES[p.priv[i]!]!;
+ const title = kind === 'person' ? cap(first) + ' ' + cap(surname) + '-example'
+ : kind === 'company' ? cap(w1) + cap(w2) + ' Example'
+ : kind === 'meeting' ? 'Meeting with ' + cap(first) + ' ' + cap(surname) + ' on ' + w1
+ : kind === 'transcript' ? 'Transcript ' + date + ' ' + w1 + ' ' + w2
+ : kind === 'chat' ? 'Chat archive ' + date + ' ' + w1
+ : kind === 'timeline' ? 'Timeline of ' + w1 + ' ' + w2
+ : cap(w1) + ' ' + w2 + ' ' + surname;
+ return { s, kind, first, surname, w1, w2, date, id, priv, title, token: 'zqpg' + id, canary: priv ? 'zqpv' + b36(hash32(o.seed, s, i, 0xca9a)) : '',
+ topic: TOPICS[hash32(o.seed, s, i, 0x70) % TOPICS.length]!, provider: PROVIDERS[hash32(o.seed, s, i, 0x9) % PROVIDERS.length]! };
+}
+
+/** Path of page i at a lifecycle stage: 0 born, 1 moved, 2 culled into archive/<year of the cull>/. */
+export function pagePath(o: FixtureOptions, p: SourcePlan, i: number, stage: 0 | 1 | 2, twinPlan?: SourcePlan): string {
+ if (p.twinOf[i]! >= 0 && twinPlan) { const t = p.twinOf[i]! % twinPlan.lives; return pagePath(o, twinPlan, t, 0); }
+ const h = pageHead(o, p, i);
+ const y = h.date.slice(0, 4), m = h.date.slice(5, 7);
+ const moved = stage >= 1 && p.move[i] !== NEVER;
+ let path: string;
+ switch (h.kind) {
+ case 'person': path = 'people/' + h.first + (moved ? '-' + h.w2[0] : '') + '-' + h.surname + '-' + h.id + '.md'; break;
+ case 'company': path = 'companies/' + (moved ? h.topic + '/' : '') + h.w1 + h.w2 + '-' + h.id + '.md'; break;
+ case 'meeting': path = 'meetings/' + y + '/' + m + '/' + h.date + '-' + h.w1 + '-' + h.id + '.md'; break;
+ case 'note': path = 'notes/' + (moved || p.move[i] === NEVER ? h.topic : 'inbox') + '/' + h.w1 + '-' + h.w2 + '-' + h.id + '.md'; break;
+ case 'concept': path = 'concepts/' + (moved ? h.topic + '/' : '') + h.w1 + '-' + h.w2 + '-' + h.id + '.md'; break;
+ case 'transcript': path = 'transcripts/' + y + '/' + h.date + '-' + h.w1 + '-' + h.id + '.md'; break;
+ case 'original': path = 'originals/' + (moved ? y + '/' : '') + h.w1 + '-' + h.id + '.md'; break;
+ case 'connector': path = 'connectors/' + h.provider + '/' + h.w1 + '-' + h.id + '.md'; break;
+ case 'timeline': path = 'timelines/' + h.w1 + '-' + h.w2 + '-' + h.id + '.md'; break;
+ case 'chat': path = 'archive/chats/' + y + '/' + h.w1 + '-' + h.id + '.md'; break;
+ }
+ if (stage === 2 && p.cull[i] !== NEVER) path = 'archive/' + new Date((T0 + p.cull[i]! * 86_400) * 1000).getUTCFullYear() + '/' + path;
+ return path;
+}
+
+function prose(rng: Rng, bytes: number, extra: string[] = []): string {
+ const out: string[] = [];
+ let n = 0, sentence = 0;
+ while (n < bytes) {
+ const len = 8 + Math.floor(rng.next() * 10);
+ const words: string[] = [];
+ for (let k = 0; k < len; k++) { const u = rng.next(); words.push(VOCAB[Math.floor(VOCAB.length * u * u)]!); }
+ if (extra.length && sentence % 7 === 3) words.splice(2, 0, extra[sentence % extra.length]!);
+ const line = cap(words.join(' ')) + '.';
+ out.push(line); n += line.length + 1; sentence++;
+ if (sentence % 5 === 0) { out.push(''); n++; }
+ }
+ return out.join(sentence % 5 === 0 ? '\n' : ' ').replace(/\. \n/g, '.\n');
+}
+
+/** Approximate body size per kind; meetings occasionally run long, chats are megabytes. */
+function bodyBytes(o: FixtureOptions, h: ReturnType<typeof pageHead>, rng: Rng, i: number): number {
+ const r = rng.next();
+ switch (h.kind) {
+ case 'person': return 1200 + r * 2500;
+ case 'company': return 800 + r * 2000;
+ case 'meeting': return rng.next() < 0.05 ? 40_000 + r * 40_000 : 2500 + r * 6000;
+ case 'transcript': return 6000 + r * 14_000;
+ case 'original': return 1500 + r * 5000;
+ case 'timeline': return 600;
+ case 'chat': return i < o.oversized ? PAGE_MAX_BYTES + 2 * 1024 ** 2 : (0.5 + r) * o.hugeMb * 1024 ** 2;
+ default: return 700 + r * 2500;
+ }
+}
+
+/** Markdown of page i at edit version v. Private pages repeat their canary in the body and, where fenced, in fact claims. */
+export function pageContent(o: FixtureOptions, p: SourcePlan, i: number, v: number): string {
+ const h = pageHead(o, p, i);
+ const rng = new Rng(hash32(o.seed, h.s, i, v, 0xc0de));
+ const fm: string[] = ['---', 'title: ' + JSON.stringify(h.title), 'type: ' + h.kind, 'date: ' + h.date, 'tags: [' + h.topic + ']'];
+ if (h.priv === 'visibility') fm.push('visibility: private');
+ if (h.priv === 'access') fm.push('access: ' + ['private', 'restricted', 'confidential'][i % 3]);
+ if (h.priv === 'confidentiality') fm.push('confidentiality: secret');
+ if (h.kind === 'connector') fm.push('source: ' + h.provider + '-connector');
+ if (h.kind === 'person' && i % 9 === 0) fm.push('aliases: [' + JSON.stringify(cap(h.first[0]!) + '. ' + cap(h.surname)) + ']');
+ fm.push('---', '');
+ const tokens = [h.token, ...(h.canary ? [h.canary] : [])];
+ const parts = [fm.join('\n'), '# ' + h.title, '', prose(rng, bodyBytes(o, h, rng, i), tokens), ''];
+ if (v > 0) parts.push('Update ' + v + ': ' + prose(rng, 200), '');
+ const links = 1 + (i % 3);
+ for (let k = 0; k < links; k++) parts.push('See [[' + pagePath(o, p, hash32(o.seed, i, k, 0x11) % p.lives, 0).replace(/\.md$/, '') + ']].');
+ parts.push('');
+ const fenced = h.kind === 'connector' || (h.kind === 'person' && i % 3 === 0) || (h.priv && i % 2 === 0);
+ if (fenced) {
+ const rows = 3 + (i % 6);
+ parts.push('## Facts', '', renderFactsTable(Array.from({ length: rows }, (_, r) => ({
+ rowNum: r + 1, claim: (h.canary && r === 0 ? h.canary + ' ' : '') + cap(VOCAB[hash32(i, r, v) % 400]!) + ' ' + VOCAB[hash32(i, r, 3) % 900]! + ' for ' + h.title.toLowerCase() + ' (' + h.token + ')',
+ kind: 'fact', confidence: 1, visibility: 'world', notability: 'medium', validFrom: h.date, source: h.kind === 'connector' ? h.provider + '-connector' : 'fixture', active: true,
+ } satisfies ParsedFact))), '');
+ }
+ const entries = h.kind === 'timeline' ? 200 + (i % 600) : h.kind === 'person' || h.kind === 'meeting' ? 2 + (i % 4) : 0;
+ if (entries) {
+ parts.push('## Timeline', '');
+ for (let k = 0; k < entries; k++) {
+ const d = new Date((T0 + ((hash32(i, k, 0xd8) % (p.birth[i]! + 30)) * 86_400)) * 1000).toISOString().slice(0, 10);
+ parts.push('- **' + d + '** | ' + cap(VOCAB[hash32(i, k) % 700]!) + ' ' + VOCAB[hash32(k, i) % 1500]! + ' with ' + h.title.toLowerCase());
+ }
+ parts.push('');
+ }
+ return parts.join('\n');
+}
+
+/** Files the importer must hold rather than import, committed in the backlog. */
+export function problemFiles(o: FixtureOptions, n: number): Array<{ path: string; content: string; expect: string }> {
+ const out: Array<{ path: string; content: string; expect: string }> = [];
+ for (let k = 0; k < n; k++) {
+ const id = b36(hash32(o.seed, k, 0xbad));
+ const kind = k % 3;
+ if (kind === 0) out.push({ path: 'notes/inbox/broken-frontmatter-' + id + '.md', expect: 'invalid_frontmatter', content: '---\ntitle: "unterminated ' + id + '\ntype: note\ntags: [a, b\n---\n# Broken ' + id + '\n\nBody zqpb' + id + '.\n' });
+ else if (kind === 1) out.push({ path: 'connectors/crm/broken-fence-' + id + '.md', expect: 'invalid_fence', content: '---\ntitle: Broken fence ' + id + '\ntype: connector\n---\n# Broken fence ' + id + '\n\nzqpb' + id + '\n\n## Facts\n\n<!--- gbrain:facts:begin -->\n\n| # | claim | kind |\n|---|---|\n| 1 | half a row\n<!--- gbrain:facts:end -->\n' });
+ else out.push({ path: 'notes/inbox/slug-conflict-' + id + '.md', expect: 'frontmatter_slug_conflict', content: '---\ntitle: Slug conflict ' + id + '\ntype: note\nslug: notes/inbox/broken-frontmatter-' + b36(hash32(o.seed, k - 2, 0xbad)) + '\n---\n# Slug conflict ' + id + '\n\nzqpb' + id + '\n' });
+ }
+ return out;
+}
+
+interface Ev { life: number; type: number }
+const ADD = 0, MOVE = 1, CULL = 2, EDIT = 3, DEL = 4;
+
+class FastImport {
+ private fd: number; private mark = 0; private buf: Buffer[] = []; private size = 0;
+ constructor(file: string) { this.fd = openSync(file, 'w'); }
+ private out(b: string | Buffer) { const x = typeof b === 'string' ? Buffer.from(b) : b; this.buf.push(x); this.size += x.length; if (this.size > 8 << 20) this.flush(); }
+ flush() { if (this.size) { writeSync(this.fd, Buffer.concat(this.buf)); this.buf = []; this.size = 0; } }
+ blob(content: string): number { const data = Buffer.from(content); const m = ++this.mark; this.out('blob\nmark :' + m + '\ndata ' + data.length + '\n'); this.out(data); this.out('\n'); return m; }
+ commit(ref: string, day: number, seq: number, msg: string, ops: string[], from?: number, merge?: number): number {
+ const m = ++this.mark, t = T0 + day * 86_400 + 9 * 3600 + seq * 97;
+ this.out('commit ' + ref + '\nmark :' + m + '\nauthor Brain Writer <[email protected]> ' + t + ' +0000\ncommitter Brain Writer <[email protected]> ' + t + ' +0000\ndata ' + Buffer.byteLength(msg) + '\n' + msg + '\n'
+ + (from ? 'from :' + from + '\n' : '') + (merge ? 'merge :' + merge + '\n' : '') + ops.join('\n') + (ops.length ? '\n' : '') + '\n');
+ return m;
+ }
+ close() { this.flush(); writeSync(this.fd, 'done\n'); closeSync(this.fd); }
+}
+
+export interface SourceResult { id: SourceId; repo: string; head: string; import_base: string; commits: number; merges: number; live_pages: number; lives: number;
+ deleted: number; moved: number; culled: number; private: Record<string, number>; kinds: Record<string, number>; bytes: number; side_deleted: number }
+
+/** Builds one source's repository; returns its summary plus the lives the drift draws from. */
+export function buildSource(o: FixtureOptions, s: number, dir: string, plans: SourcePlan[], drift: (row: object) => void, canaries: object[], privateTokens: string[]): SourceResult {
+ const p = plans[s]!, src = SOURCES[s]!;
+ const repo = join(dir, src.id, 'repo');
+ rmSync(join(dir, src.id), { recursive: true, force: true });
+ mkdirSync(repo, { recursive: true });
+ execFileSync('git', ['init', '-q', '-b', 'master', repo]);
+ const streamFile = join(dir, src.id, 'fast-import.stream');
+ const fi = new FastImport(streamFile);
+ const twin = src.history === 'static' ? plans[0] : undefined;
+ const byDay: Ev[][] = Array.from({ length: p.days }, () => []);
+ for (let i = 0; i < p.lives; i++) {
+ byDay[p.birth[i]!]!.push({ life: i, type: ADD });
+ if (p.move[i] !== NEVER) byDay[p.move[i]!]!.push({ life: i, type: MOVE });
+ if (p.cull[i] !== NEVER) byDay[p.cull[i]!]!.push({ life: i, type: CULL });
+ if (p.del[i] !== NEVER) byDay[p.del[i]!]!.push({ life: i, type: DEL });
+ const end = p.del[i] !== NEVER ? p.del[i]! : p.days;
+ for (let e = 0; e < p.edits[i]!; e++) { const d = p.birth[i]! + 1 + (hash32(o.seed, s, i, e, 0xed) % Math.max(1, end - p.birth[i]! - 1)); if (d < end) byDay[d]!.push({ life: i, type: EDIT }); }
+ }
+ const ver = new Uint8Array(p.lives), stage = new Uint8Array(p.lives), blob = new Int32Array(p.lives), sideDel = new Uint8Array(p.lives);
+ const path = (i: number) => pagePath(o, p, i, stage[i] as 0 | 1 | 2, twin);
+ const live = new Map<string, number>();
+ let tip = 0, commits = 0, merges = 0, importBase = 0, bytes = 0;
+ const baseDay = p.days - o.backlogDays;
+ const apply = (ev: Ev, ops: string[]) => {
+ const i = ev.life;
+ if (ev.type === ADD || ev.type === EDIT) {
+ if (ev.type === EDIT) ver[i]++;
+ const c = pageContent(o, p, i, ver[i]!); bytes += c.length;
+ blob[i] = fi.blob(c);
+ ops.push('M 100644 :' + blob[i] + ' ' + path(i)); live.set(path(i), i);
+ } else if (ev.type === MOVE || ev.type === CULL) {
+ const from = path(i); stage[i] = ev.type === MOVE ? 1 : 2; const to = path(i);
+ if (from !== to) { ops.push('D ' + from, 'M 100644 :' + blob[i] + ' ' + to); live.delete(from); live.set(to, i); }
+ } else { ops.push('D ' + path(i)); live.delete(path(i)); }
+ };
+ const recreated: number[] = [];
+ for (let day = 0; day < p.days; day++) {
+ if (day === baseDay) importBase = tip;
+ const evs = byDay[day]!.sort((a, b) => a.type - b.type || a.life - b.life);
+ if (src.history === 'daily' && day >= baseDay && day === baseDay + 1) {
+ const ops: string[] = [];
+ for (const f of problemFiles(o, 6 + Math.round(o.pages / 100_000) * 3)) ops.push('M 100644 :' + fi.blob(f.content) + ' ' + f.path);
+ for (let i = 0; i < p.lives && recreated.length < Math.max(3, Math.round(o.pages / 20_000)); i++) if (p.del[i]! < baseDay - 30 && hash32(o.seed, i, 0x4ec) % 50 === 0) {
+ recreated.push(i); const pth = path(i); ops.push('M 100644 :' + fi.blob(pageContent(o, p, i, ver[i]! + 1)) + ' ' + pth); live.set(pth, i);
+ }
+ tip = fi.commit('refs/heads/master', day, 0, 'agent writes (backlog)', ops, tip || undefined); commits++;
+ }
+ if (!evs.length) continue;
+ const side = src.history === 'daily' && day % 9 === 4 && evs.length >= 4;
+ if (side) {
+ const mainLives = new Set(evs.filter(e => e.type === EDIT && e.life % 2 === 0).map(e => e.life));
+ for (const e of evs) if (e.type !== EDIT) mainLives.delete(e.life);
+ const mainOps: string[] = [], sideOps: string[] = [];
+ for (const e of evs) { if (mainLives.has(e.life)) apply(e, mainOps); else { apply(e, sideOps); if (e.type === DEL) sideDel[e.life] = 1; } }
+ const sideMark = fi.commit('refs/heads/side', day, 1, 'integrate remote writes', sideOps, tip || undefined);
+ if (mainOps.length) tip = fi.commit('refs/heads/master', day, 2, 'librarian: commit edits', mainOps, tip || undefined);
+ tip = fi.commit('refs/heads/master', day, 3, 'Merge remote-tracking branch', sideOps, tip, sideMark);
+ commits += mainOps.length ? 3 : 2; merges++;
+ continue;
+ }
+ const perCommit = evs.length > 3000 ? 5000 : Math.ceil(evs.length / (1 + (hash32(o.seed, s, day) % 3)));
+ for (let c = 0, seq = 0; c < evs.length; c += perCommit, seq++) {
+ const ops: string[] = [];
+ for (const e of evs.slice(c, c + perCommit)) apply(e, ops);
+ const msg = src.history === 'connector' ? 'connector sync' : evs.length > 3000 ? 'bulk import' : 'brain update';
+ tip = fi.commit('refs/heads/master', day, seq, msg, ops);
+ commits++;
+ }
+ }
+ if (!importBase) importBase = tip;
+ fi.close();
+ const marksFile = join(dir, src.id, 'marks');
+ execFileSync('sh', ['-c', 'git -C "$1" fast-import --quiet --export-marks="$2" < "$3"', 'sh', repo, marksFile, streamFile], { stdio: ['ignore', 'inherit', 'inherit'], maxBuffer: 1 << 30 });
+ rmSync(streamFile);
+ const sha = (mark: number) => execFileSync('sh', ['-c', 'grep "^:$1 " "$2" | cut -d" " -f2', 'sh', String(mark), marksFile], { encoding: 'utf8' }).trim();
+ const head = sha(tip), base = sha(importBase);
+ execFileSync('git', ['-C', repo, 'tag', 'import-base', base]);
+ execFileSync('git', ['-C', repo, 'branch', '-f', 'final', head]);
+ if (merges) execFileSync('git', ['-C', repo, 'branch', '-D', 'side'], { stdio: 'ignore' });
+ rmSync(marksFile);
+ const kinds: Record<string, number> = {}, priv: Record<string, number> = { visibility: 0, access: 0, confidentiality: 0 };
+ for (const [pth, i] of live) {
+ const h = pageHead(o, p, i);
+ kinds[h.kind] = (kinds[h.kind] ?? 0) + 1;
+ if (h.priv) { priv[h.priv]!++; if (canaries.length < 600 && hash32(o.seed, s, i, 0x5a) % 16 === 0) canaries.push({ source: src.id, slug: pth.replace(/\.md$/, ''), class: h.priv, token: h.canary, page_token: h.token }); }
+ }
+ for (let i = 0; i < p.lives; i++) if (p.priv[i]) { const h = pageHead(o, p, i); privateTokens.push(h.canary, h.token); }
+ let sideDeleted = 0;
+ if (src.history === 'daily') {
+ const dbOnly = Math.max(10, Math.round(o.pages * 0.0024)), kept = Math.max(10, Math.round(o.pages * 0.0016));
+ for (let k = 0; k < dbOnly; k++) {
+ const i = hash32(o.seed, k, 0xdb0) % p.lives, h = pageHead(o, p, i);
+ const slugPath = 'notes/agent/' + h.w1 + '-' + h.w2 + '-db' + b36(hash32(o.seed, k, 0xdb1)) + '.md';
+ const token = 'zqpd' + b36(hash32(o.seed, k, 0xdb2));
+ if (h.priv) privateTokens.push(token);
+ drift({ kind: 'db_only', source: src.id, path: slugPath, private: h.priv || undefined, content: pageContent(o, p, i, 0).replaceAll(h.token, token) });
+ }
+ const deletedBeforeBase = [...Array(p.lives).keys()].filter(i => p.del[i]! < baseDay && !recreated.includes(i));
+ sideDeleted = deletedBeforeBase.filter(i => sideDel[i]).length;
+ const side = deletedBeforeBase.filter(i => sideDel[i]), plain = deletedBeforeBase.filter(i => !sideDel[i]);
+ const pick = [...side.slice(0, Math.ceil(kept / 2)), ...plain.slice(0, kept)].slice(0, kept);
+ for (const i of pick) { const st = (p.cull[i]! < p.del[i]! ? 2 : p.move[i]! < p.del[i]! ? 1 : 0) as 0 | 1 | 2; stage[i] = st;
+ drift({ kind: 'kept_deleted', source: src.id, path: pagePath(o, p, i, st), side_branch: !!sideDel[i], content: pageContent(o, p, i, ver[i]!) }); }
+ }
+ let deleted = 0, moved = 0, culled = 0;
+ for (let i = 0; i < p.lives; i++) { if (p.del[i] !== NEVER) deleted++; if (p.move[i] !== NEVER) moved++; if (p.cull[i] !== NEVER) culled++; }
+ return { id: src.id, repo, head, import_base: base, commits, merges, live_pages: live.size, lives: p.lives, deleted, moved, culled, private: priv, kinds, bytes, side_deleted: sideDeleted };
+}
+
+export function buildFixture(o: FixtureOptions, dir: string): Record<string, unknown> {
+ mkdirSync(dir, { recursive: true });
+ const t0 = performance.now();
+ const plans = SOURCES.map((_, s) => planSource(o, s));
+ const driftFd = openSync(join(dir, 'drift.jsonl'), 'w');
+ const counts: Record<string, number> = {};
+ const drift = (row: object) => { const k = (row as { kind: string }).kind; counts[k] = (counts[k] ?? 0) + 1; writeSync(driftFd, JSON.stringify(row) + '\n'); };
+ const canaries: object[] = [], privateTokens: string[] = [];
+ const sources = SOURCES.map((_, s) => { const r = buildSource(o, s, dir, plans, drift, canaries, privateTokens); console.error('[soak-fixture] ' + r.id + ': ' + r.live_pages + ' pages, ' + r.commits + ' commits, ' + r.merges + ' merges (' + Math.round((performance.now() - t0) / 1000) + ' s)'); return r; });
+ closeSync(driftFd);
+ writeFileSync(join(dir, 'private-tokens.json'), JSON.stringify(privateTokens));
+ const manifest = { schema: 'gbrain-production-soak-fixture/1', options: o, sources, drift: counts, privacy: { canaries, private_tokens: privateTokens.length }, problem_files: problemFiles(o, 6 + Math.round(o.pages / 100_000) * 3).map(f => ({ path: f.path, expect: f.expect })),
+ pages: sources.reduce((a, r) => a + r.live_pages, 0), build_s: Math.round((performance.now() - t0) / 1000) };
+ writeFileSync(join(dir, 'manifest.json'), JSON.stringify(manifest, null, 2));
+ return manifest;
+}
+
+if (import.meta.main) {
+ const argv = process.argv.slice(2);
+ const flag = (n: string) => { const i = argv.indexOf('--' + n); return i >= 0 ? argv[i + 1] : undefined; };
+ const out = flag('out');
+ if (!out) { console.error('usage: fixture.ts --out <dir> [--pages N] [--seed N] [--years N] [--backlog-days N] [--huge-mb N] [--oversized N]'); process.exit(2); }
+ const o: FixtureOptions = { pages: Number(flag('pages') ?? DEFAULTS.pages), seed: Number(flag('seed') ?? DEFAULTS.seed), years: Number(flag('years') ?? DEFAULTS.years),
+ backlogDays: Number(flag('backlog-days') ?? DEFAULTS.backlogDays), hugeMb: Number(flag('huge-mb') ?? DEFAULTS.hugeMb), oversized: Number(flag('oversized') ?? DEFAULTS.oversized) };
+ const m = buildFixture(o, out);
+ console.log(JSON.stringify({ pages: m.pages, drift: m.drift, build_s: m.build_s }));
+}
diff --git a/scripts/bench/production-soak/lib.ts b/scripts/bench/production-soak/lib.ts
new file mode 100644
index 0000000000..994b31eaf1
--- /dev/null
+++ b/scripts/bench/production-soak/lib.ts
@@ -0,0 +1,159 @@
+/**
+ * Shared helpers for the production-shaped scale soak (GBRA-174): the database
+ * topology (Postgres, a session-mode PgBouncer capped like a session pooler, a
+ * transaction-mode PgBouncer, and toxiproxy latency in front of both), the
+ * gbrain CLI runner and the child environment. Every listener binds loopback.
+ */
+import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { spawnSync } from 'node:child_process';
+import postgres from '#postgres';
+import { PGBOUNCER_IMAGE } from '../managed-sync-catchup-lib.ts';
+
+export const REPO = join(import.meta.dir, '..', '..', '..');
+export const now = () => performance.timeOrigin + performance.now();
+export const sleep = (ms: number) => new Promise<void>(r => setTimeout(r, ms));
+export const log = (tag: string, m: string) => console.error('[' + tag + ' ' + new Date().toISOString().slice(11, 19) + '] ' + m);
+
+export interface Ports { pg: number; session: number; txn: number; sessionProxy: number; txnProxy: number; toxiproxyApi: number }
+export const DEFAULT_PORTS: Ports = { pg: 5434, session: 6432, txn: 6543, sessionProxy: 15432, txnProxy: 16543, toxiproxyApi: 8475 };
+/** The session lane mirrors a hosted session pooler: pool_size 25, and a 26th client is refused rather than queued. */
+export interface LaneSizes { sessionPool: number; txnPool: number }
+export const DEFAULT_LANES: LaneSizes = { sessionPool: 25, txnPool: 20 };
+export const SESSION_ROLE = 'lane_session', TXN_ROLE = 'lane_txn';
+const C = { pg: 'soak-pg', session: 'soak-bouncer-session', txn: 'soak-bouncer-txn', toxi: 'soak-toxiproxy' };
+
+function docker(args: string[], allowFail = false): string {
+ const r = spawnSync('docker', args, { encoding: 'utf8' });
+ if (r.status !== 0 && !allowFail) throw new Error('docker ' + args.join(' ') + ' failed: ' + (r.stderr || r.stdout));
+ return (r.stdout ?? '').trim();
+}
+const running = (name: string) => !!docker(['ps', '-q', '-f', 'name=^' + name + '$'], true);
+
+export interface Topology {
+ ports: Ports; lanes: LaneSizes;
+ /** Direct (unproxied, unpooled) URL: the loader, the samplers and the probes use it. */
+ direct(db: string): string;
+ /** Session lane through toxiproxy: what GBRAIN_DIRECT_DATABASE_URL points at, like the session pooler port. */
+ session(db: string): string;
+ /** Transaction lane through toxiproxy: the brain's database_url, like the transaction pooler port. */
+ txn(db: string): string;
+ setRtt(ms: number): Promise<void>;
+ /** Client connections each PgBouncer refused at its cap since it started. */
+ refusals(): { session: number; txn: number };
+ stop(): void;
+}
+
+function bouncerIni(dir: string, name: string, mode: 'session' | 'transaction', role: string, ports: Ports, listen: number, pool: number, maxClients: number): string {
+ mkdirSync(dir, { recursive: true });
+ writeFileSync(join(dir, 'pgbouncer.ini'), [
+ '[databases]', '* = host=127.0.0.1 port=' + ports.pg + ' user=' + role + ' password=lane', '',
+ '[pgbouncer]', 'listen_addr = 127.0.0.1', 'listen_port = ' + listen, 'auth_type = plain', 'auth_file = /etc/pgbouncer/userlist.txt',
+ 'pool_mode = ' + mode, 'default_pool_size = ' + pool, 'max_client_conn = ' + maxClients, 'max_db_connections = ' + pool, 'reserve_pool_size = 0',
+ 'ignore_startup_parameters = extra_float_digits,options,statement_timeout,idle_in_transaction_session_timeout,search_path,lock_timeout,maintenance_work_mem',
+ 'server_reset_query = DISCARD ALL', 'query_wait_timeout = 120', 'log_connections = 0', 'log_disconnections = 0', 'admin_users = postgres', '',
+ ].join('\n'));
+ writeFileSync(join(dir, 'userlist.txt'), '"postgres" "postgres"\n');
+ return name;
+}
+
+/** Starts (or reuses) the four containers. Session clients beyond lanes.sessionPool are refused, the EMAXCONNSESSION shape. */
+export async function startTopology(workDir: string, ports: Ports = DEFAULT_PORTS, lanes: LaneSizes = DEFAULT_LANES, keep = false): Promise<Topology> {
+ if (!running(C.pg)) {
+ docker(['rm', '-f', C.pg], true);
+ docker(['run', '-d', '--name', C.pg, '--network', 'host', '-e', 'POSTGRES_PASSWORD=postgres', '--shm-size=4g', 'pgvector/pgvector:pg16',
+ '-c', 'port=' + ports.pg, '-c', 'listen_addresses=127.0.0.1', '-c', 'max_connections=300', '-c', 'shared_preload_libraries=pg_stat_statements',
+ '-c', 'shared_buffers=' + (process.env.SOAK_PG_SHARED_BUFFERS ?? '4GB'), '-c', 'maintenance_work_mem=1GB', '-c', 'max_wal_size=8GB', '-c', 'checkpoint_timeout=15min']);
+ }
+ const admin = 'postgresql://postgres:[email protected]:' + ports.pg + '/postgres';
+ for (let i = 0; ; i++) {
+ try { const s = postgres(admin, { max: 1, onnotice: () => {}, connect_timeout: 2 }); await s`SELECT 1`; await s.end(); break; } catch (e) { if (i > 90) throw e; await sleep(1000); }
+ }
+ {
+ const s = postgres(admin, { max: 1, onnotice: () => {} });
+ for (const role of [SESSION_ROLE, TXN_ROLE]) await s.unsafe("DO $$ BEGIN IF NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = '" + role + "') THEN CREATE ROLE " + role + " LOGIN SUPERUSER PASSWORD 'lane'; END IF; END $$");
+ await s.end();
+ }
+ const bouncers: Array<[string, 'session' | 'transaction', string, number, number, number]> = [
+ [C.session, 'session', SESSION_ROLE, ports.session, lanes.sessionPool, lanes.sessionPool],
+ [C.txn, 'transaction', TXN_ROLE, ports.txn, lanes.txnPool, 2000],
+ ];
+ for (const [name, mode, role, listen, pool, maxClients] of bouncers) {
+ const dir = join(workDir, 'pgbouncer', name);
+ bouncerIni(dir, name, mode, role, ports, listen, pool, maxClients);
+ docker(['rm', '-f', name], true);
+ docker(['run', '-d', '--name', name, '--network', 'host', '-v', dir + ':/etc/pgbouncer:ro', PGBOUNCER_IMAGE]);
+ }
+ if (!running(C.toxi)) {
+ docker(['rm', '-f', C.toxi], true);
+ docker(['run', '-d', '--name', C.toxi, '--network', 'host', 'ghcr.io/shopify/toxiproxy:2.12.0', '-host', '127.0.0.1', '-port', String(ports.toxiproxyApi)]);
+ }
+ const api = 'http://127.0.0.1:' + ports.toxiproxyApi;
+ for (let i = 0; ; i++) { try { if ((await fetch(api + '/version')).ok) break; } catch (e) { if (i > 60) throw e; } await sleep(500); }
+ const proxies: Array<[string, number, number]> = [['session', ports.sessionProxy, ports.session], ['txn', ports.txnProxy, ports.txn]];
+ for (const [name, listen, upstream] of proxies) {
+ await fetch(api + '/proxies/' + name, { method: 'DELETE' });
+ const r = await fetch(api + '/proxies', { method: 'POST', body: JSON.stringify({ name, listen: '127.0.0.1:' + listen, upstream: '127.0.0.1:' + upstream, enabled: true }) });
+ if (!r.ok) throw new Error('toxiproxy proxy ' + name + ': ' + await r.text());
+ }
+ const url = (port: number, db: string, q = '') => 'postgresql://postgres:[email protected]:' + port + '/' + db + q;
+ for (const port of [ports.sessionProxy, ports.txnProxy]) {
+ for (let i = 0; ; i++) {
+ try { const s = postgres(url(port, 'postgres'), { max: 1, onnotice: () => {}, connect_timeout: 3, prepare: false }); await s`SELECT 1`; await s.end(); break; } catch (e) { if (i > 60) throw e; await sleep(1000); }
+ }
+ }
+ const countRefused = (name: string) => { const r = spawnSync('docker', ['logs', name], { encoding: 'utf8', maxBuffer: 1 << 28 }); return ((r.stdout ?? '') + (r.stderr ?? '')).split('\n').filter(l => /no more connections allowed/.test(l)).length; };
+ return {
+ ports, lanes,
+ direct: db => url(ports.pg, db),
+ session: db => url(ports.sessionProxy, db),
+ txn: db => url(ports.txnProxy, db, '?prepare=false'),
+ async setRtt(ms: number) {
+ for (const [name] of proxies) for (const [stream, part] of [['upstream', Math.floor(ms / 2)], ['downstream', Math.ceil(ms / 2)]] as const) {
+ await fetch(api + '/proxies/' + name + '/toxics/lat_' + stream, { method: 'DELETE' });
+ if (part <= 0) continue;
+ const r = await fetch(api + '/proxies/' + name + '/toxics', { method: 'POST', body: JSON.stringify({ name: 'lat_' + stream, type: 'latency', stream, toxicity: 1, attributes: { latency: part, jitter: 0 } }) });
+ if (!r.ok) throw new Error('toxiproxy toxic: ' + await r.text());
+ }
+ },
+ refusals: () => ({ session: countRefused(C.session), txn: countRefused(C.txn) }),
+ stop() { if (!keep) for (const name of Object.values(C)) docker(['rm', '-f', name], true); },
+ };
+}
+
+/** Child environment: provider keys and database variables stripped, the bench home and the mock provider set. */
+export function childEnv(home: string, mockUrl: string, extra: Record<string, string | undefined> = {}): Record<string, string> {
+ const env: Record<string, string | undefined> = { ...process.env };
+ for (const k of Object.keys(env)) if (/_API_KEY$|_API_TOKEN$|^DATABASE_URL$|^GBRAIN_DATABASE_URL$|^GBRAIN_DIRECT_DATABASE_URL$|^OPENAI_BASE_URL$|^GBRAIN_HOME$/.test(k)) delete env[k];
+ const out = { ...env, GBRAIN_HOME: home, GBRAIN_NO_BANNER: '1', GBRAIN_BACKUP_CHECK: '0', GBRAIN_NO_UPDATE_CHECK: '1', GBRAIN_TELEMETRY: '0', GBRAIN_SKILLS_DIR: join(home, 'skills'), NO_COLOR: '1',
+ OPENAI_API_KEY: 'sk-soak-mock-not-a-key', OPENAI_BASE_URL: mockUrl + '/v1', VOYAGE_API_KEY: 'pa-soak-mock-not-a-key', ...extra };
+ return Object.fromEntries(Object.entries(out).filter(([, v]) => v !== undefined)) as Record<string, string>;
+}
+
+export function writeConfig(home: string, databaseUrl: string, mockUrl: 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'), '# Soak fixture skills\n');
+ const file = join(home, '.gbrain', 'config.json');
+ const prior = existsSync(file) ? JSON.parse(readFileSync(file, 'utf8')) : {};
+ writeFileSync(file, JSON.stringify({ ...prior, engine: 'postgres', database_url: databaseUrl, embedding_disabled: false, embedding_model: 'openai:text-embedding-3-small', embedding_dimensions: 1536,
+ provider_base_urls: { voyage: mockUrl + '/v1' }, self_upgrade: { mode: 'off' } }, null, 2) + '\n');
+}
+
+export interface GbResult { code: number; stdout: string; stderr: string; ms: number; json: any }
+export async function gb(cli: string, home: string, env: Record<string, string>, args: string[], opts: { allowFail?: boolean; timeoutMs?: number } = {}): Promise<GbResult> {
+ const t = now();
+ const p = Bun.spawn([process.execPath, cli, ...args], { cwd: home, env, stdin: 'ignore', stdout: 'pipe', stderr: 'pipe', timeout: opts.timeoutMs ?? 4 * 3600_000 });
+ const [stdout, stderr, code] = await Promise.all([new Response(p.stdout).text(), new Response(p.stderr).text(), p.exited]);
+ let json: any = null;
+ try { json = JSON.parse(stdout); } catch { const last = stdout.trim().split('\n').reverse().find(l => l.startsWith('{')); try { json = last ? JSON.parse(last) : null; } catch { json = null; } }
+ if (code !== 0 && !opts.allowFail) throw new Error('gbrain ' + args.join(' ') + ' exited ' + code + '\n' + stdout.slice(-1500) + '\n' + stderr.slice(-1500));
+ return { code: code ?? -1, stdout, stderr, ms: now() - t, json };
+}
+
+export function pct(xs: number[], p: number): number | null {
+ if (!xs.length) return null;
+ const s = [...xs].sort((a, b) => a - b);
+ const rank = (p / 100) * (s.length - 1), lo = Math.floor(rank), hi = Math.ceil(rank);
+ return Math.round((s[lo]! + (s[hi]! - s[lo]!) * (rank - lo)) * 10) / 10;
+}
diff --git a/scripts/bench/production-soak/load.ts b/scripts/bench/production-soak/load.ts
new file mode 100644
index 0000000000..2ae2667694
--- /dev/null
+++ b/scripts/bench/production-soak/load.ts
@@ -0,0 +1,163 @@
+#!/usr/bin/env bun
+/**
+ * Production-shaped scale soak, step 2: load a fixture.ts brain into Postgres
+ * the way production got there (GBRA-174). Opt-in bench code, never run in CI.
+ *
+ * bun scripts/bench/production-soak/load.ts --fixture <dir> --work <dir> [--db soak_brain] [--skip-embed]
+ *
+ * 1. Starts the topology (lib.ts): Postgres, the session and transaction
+ * PgBouncers and toxiproxy (no latency while loading).
+ * 2. Checks the default source out at its import-base tag and the other sources at HEAD,
+ * registers each with gbrain sources add and imports it with gbrain's own
+ * classic sync, then federates it.
+ * 3. Writes the drift (fixture drift.jsonl) through the importer, database
+ * only: db_only pages no commit ever held, and kept_deleted pages whose
+ * files history deleted.
+ * 4. Activates managed persistence (sources writer claim / activate) and runs
+ * the first managed sync of every source to its end state, then settles the
+ * mention-link pass and embeds every stale chunk through the loopback mock
+ * provider (keyless; nothing leaves the machine).
+ * 5. Fast-forwards the default source to the final history, so the soak starts with the
+ * backlog a production brain carries (commits after import-base, including
+ * merges whose side branches move and delete files, and files gbrain holds).
+ *
+ * Writes <work>/ready.json with every phase's timing and the starting counts
+ * (pages, chunks, holds, drift rows written). Reuses nothing: every run is a
+ * fresh database, and a fixture loads once (managed activation leaves ownership
+ * markers in its checkouts), so regenerate it for another load.
+ */
+import { appendFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
+import { join, resolve } from 'node:path';
+import { execFileSync } from 'node:child_process';
+import postgres from '#postgres';
+import { startMockProviders } from '../retrieval-scale/mock-providers.ts';
+import { childEnv, gb, log as baseLog, now, REPO, startTopology, writeConfig, type Topology } from './lib.ts';
+
+const argv = process.argv.slice(2);
+const flag = (n: string, f?: string) => { const i = argv.indexOf('--' + n); return i >= 0 ? argv[i + 1] : f; };
+const FIXTURE = resolve(flag('fixture') ?? '');
+const WORK = resolve(flag('work') ?? '');
+const DB = flag('db', 'soak_brain')!;
+const CLI = join(resolve(flag('gbrain-root', REPO)!), 'src', 'cli.ts');
+const log = (m: string) => baseLog('soak-load', m);
+if (!flag('fixture') || !flag('work') || !/^[a-z0-9_]+$/.test(DB)) { console.error('usage: load.ts --fixture <dir> --work <dir> [--db name] [--skip-embed]'); process.exit(2); }
+
+interface SourceRow { id: string; repo: string; head: string; import_base: string; live_pages: number }
+const manifest = JSON.parse(readFileSync(join(FIXTURE, 'manifest.json'), 'utf8'));
+const sources: SourceRow[] = manifest.sources;
+const git = (repo: string, ...args: string[]) => execFileSync('git', ['-C', repo, ...args], { encoding: 'utf8', maxBuffer: 1 << 28 }).trim();
+
+export async function syncUntilSettled(cli: string, home: string, env: Record<string, string>, source: string, label: string, maxPasses: number, extra: string[] = []) {
+ const t = now();
+ const passes: Array<{ status: string; ms: number; code: number }> = [];
+ for (let i = 0; i < maxPasses; i++) {
+ const r = await gb(cli, home, env, ['sync', '--source', source, '--no-pull', '--no-embed', '--json', ...extra], { allowFail: true });
+ const status = String(r.json?.sync_status ?? r.json?.outcome ?? r.json?.status ?? 'exit_' + r.code);
+ passes.push({ status, ms: Math.round(r.ms), code: r.code });
+ log(label + ' pass ' + (i + 1) + ': ' + status + ' (' + Math.round(r.ms / 1000) + ' s)');
+ if (['synced', 'first_sync', 'up_to_date'].includes(status)) break;
+ if (r.code !== 0 && status !== 'partial' && !/blocked/.test(status)) { appendFileSync(join(WORK, 'load-errors.log'), label + '\n' + r.stdout.slice(-4000) + '\n' + r.stderr.slice(-4000) + '\n'); break; }
+ }
+ return { ms: Math.round(now() - t), passes };
+}
+
+async function main() {
+ mkdirSync(WORK, { recursive: true });
+ const t0 = now();
+ const ready: Record<string, unknown> = { fixture: { pages: manifest.pages, options: manifest.options, drift: manifest.drift }, db: DB, gbrain_rev: git(REPO, 'rev-parse', 'HEAD'), started_at: new Date().toISOString() };
+ const topo: Topology = await startTopology(WORK, undefined, undefined, true);
+ await topo.setRtt(0);
+ const admin = postgres(topo.direct('postgres'), { max: 1, onnotice: () => {} });
+ await admin.unsafe('DROP DATABASE IF EXISTS ' + DB + ' WITH (FORCE)');
+ await admin.unsafe('CREATE DATABASE ' + DB);
+ await admin.end();
+ for (const s of sources) {
+ const t = now();
+ git(s.repo, 'checkout', '-q', '-f', '-B', 'master', s.id === 'default' ? 'import-base' : 'final');
+ git(s.repo, 'config', 'user.name', 'Brain Writer'); git(s.repo, 'config', 'user.email', '[email protected]');
+ ready['checkout_' + s.id + '_ms'] = Math.round(now() - t);
+ }
+ const mock = startMockProviders({ manifest: { seed: manifest.options.seed, chunks: manifest.pages * 4, pages: manifest.pages, dims: 1536 } });
+ const home = join(WORK, 'home');
+ writeConfig(home, topo.direct(DB), mock.url);
+ const env = childEnv(home, mock.url);
+ await gb(CLI, home, env, ['config', 'set', 'search.mode', 'tokenmax'], { allowFail: true });
+ for (const s of sources) {
+ await gb(CLI, home, env, ['sources', 'add', s.id, '--path', s.repo, '--no-federated']);
+ ready['import_' + s.id] = await syncUntilSettled(CLI, home, env, s.id, 'import ' + s.id, 50);
+ await gb(CLI, home, env, ['sources', 'federate', s.id, '--brain', 'host'], { allowFail: true });
+ }
+ ready.import_ms = Math.round(now() - t0);
+
+ const t1 = now();
+ const { PostgresEngine } = await import('../../../src/core/postgres-engine.ts');
+ const { importFromContent } = await import('../../../src/core/import-file.ts');
+ const { slugifyPath } = await import('../../../src/core/sync.ts');
+ const engine = new PostgresEngine();
+ process.env.GBRAIN_HOME = home;
+ await engine.connect({ database_url: topo.direct(DB), poolSize: 4 });
+ const written: Record<string, number> = {}, failed: Record<string, number> = {};
+ for (const line of readFileSync(join(FIXTURE, 'drift.jsonl'), 'utf8').split('\n')) {
+ if (!line) continue;
+ const row = JSON.parse(line) as { kind: string; source: string; path: string; content: string };
+ try {
+ await importFromContent(engine, slugifyPath(row.path), row.content, { sourceId: row.source, sourcePath: row.path, noEmbed: true, filename: row.path.split('/').pop()!.replace(/\.md$/, '') });
+ written[row.kind] = (written[row.kind] ?? 0) + 1;
+ } catch (e) { failed[row.kind] = (failed[row.kind] ?? 0) + 1; if ((failed[row.kind] ?? 0) <= 3) log('drift ' + row.kind + ' ' + row.path + ' failed: ' + String(e).slice(0, 300)); }
+ }
+ await engine.disconnect();
+ ready.drift = { written, failed, ms: Math.round(now() - t1) };
+ log('drift written ' + JSON.stringify(written) + ' failed ' + JSON.stringify(failed));
+
+ const t2 = now();
+ let state = '';
+ for (const s of sources) {
+ state = (await gb(CLI, home, env, ['sources', 'writer', 'status', '--json'])).json.admin_state as string;
+ await gb(CLI, home, env, ['sources', 'writer', 'claim', s.id, '--path', s.repo, '--admin-intent', 'writer_claim', '--expected-state', state, '--json']);
+ }
+ state = (await gb(CLI, home, env, ['sources', 'writer', 'status', '--json'])).json.admin_state as string;
+ const a = await gb(CLI, home, env, ['sources', 'writer', 'activate', '--confirm-quiesced', '--admin-intent', 'writer_activate', '--expected-state', state, '--json']);
+ if (a.json?.enabled !== true) throw new Error('activation did not enable managed persistence: ' + a.stdout.slice(-1500));
+ ready.activate_ms = Math.round(now() - t2);
+ for (const s of sources) {
+ ready['first_managed_sync_' + s.id] = await syncUntilSettled(CLI, home, env, s.id, 'first managed sync ' + s.id, 20);
+ const st = await gb(CLI, home, env, ['sync', 'status', '--source', s.id, '--json'], { allowFail: true });
+ ready['after_activation_' + s.id] = { state: st.json?.state ?? null, reason: st.json?.reason ?? null, holds: Array.isArray(st.json?.holds) ? st.json.holds.length : null, legacy_swept: st.json?.convergence?.counts?.legacy_swept ?? null, legacy_recorded: st.json?.convergence?.counts?.legacy_recorded ?? null };
+ }
+
+ const t3 = now();
+ for (const s of sources) {
+ for (let i = 0; i < 30; i++) {
+ const r = await gb(CLI, home, env, ['extract', '--stale', '--catch-up', '--source-id', s.id, '--brain', 'host'], { allowFail: true });
+ if (r.code !== 0 || !/Actionable: [1-9]\d* page\(s\) still need|[1-9]\d* page\(s\) due for the mention pass/.test(r.stdout + r.stderr)) break;
+ }
+ }
+ ready.extract_ms = Math.round(now() - t3);
+ if (!argv.includes('--skip-embed')) {
+ const t4 = now();
+ const passes: number[] = [];
+ for (let i = 0; i < 20; i++) {
+ const r = await gb(CLI, home, env, ['embed', '--stale', '--yes'], { allowFail: true });
+ passes.push(r.code);
+ log('embed --stale pass ' + (i + 1) + ' exit ' + r.code + ' (' + Math.round(r.ms / 1000) + ' s): ' + (r.stdout + r.stderr).trim().split('\n').slice(-2).join(' | ').slice(0, 300));
+ if (r.code === 0) break;
+ }
+ ready.embed = { ms: Math.round(now() - t4), exits: passes, provider: mock.stats };
+ }
+ const sa = sources.find(s => s.id === 'default')!;
+ git(sa.repo, 'merge', '-q', '--ff-only', 'final');
+ ready.backlog_commits = Number(git(sa.repo, 'rev-list', '--count', 'import-base..HEAD'));
+
+ const sql = postgres(topo.direct(DB), { max: 1, onnotice: () => {} });
+ await sql.unsafe('ANALYZE');
+ ready.import_records = await sql.unsafe("SELECT p.source_id, count(*)::int AS pages, count(o.fingerprint)::int AS recorded FROM pages p LEFT JOIN op_checkpoints o ON o.op = 'sync-import-provenance' AND (o.completed_keys->0->>'page_id')::bigint = p.id WHERE p.deleted_at IS NULL GROUP BY 1 ORDER BY 1");
+ const [c] = await sql.unsafe("SELECT (SELECT count(*) FROM pages WHERE deleted_at IS NULL)::int AS pages, (SELECT count(*) FROM content_chunks)::int AS chunks, (SELECT count(*) FROM content_chunks WHERE embedding IS NULL)::int AS unembedded, pg_database_size(current_database())::bigint AS bytes") as any[];
+ await sql.end();
+ mock.stop();
+ ready.counts = { ...c, bytes: Number(c.bytes) };
+ ready.load_s = Math.round((now() - t0) / 1000);
+ writeFileSync(join(WORK, 'ready.json'), JSON.stringify(ready, null, 2));
+ log('ready: ' + JSON.stringify(ready.counts) + ' in ' + ready.load_s + ' s');
+}
+
+if (import.meta.main) await main();
diff --git a/scripts/bench/production-soak/run.sh b/scripts/bench/production-soak/run.sh
new file mode 100755
index 0000000000..bb5bb06b43
--- /dev/null
+++ b/scripts/bench/production-soak/run.sh
@@ -0,0 +1,37 @@
+#!/usr/bin/env bash
+# scripts/bench/production-soak/run.sh — one soak cell end to end on one
+# machine (GBRA-174): generate the fixture, load it, soak it, and leave the
+# scoreboard in <out>. Every step is deterministic up to the soak itself.
+#
+# bash scripts/bench/production-soak/run.sh [--pages 600000] [--rtt-ms 65] [--hours 3] [--seed 7] [--out ~/soak/out] [--label name]
+#
+# Postgres gets a quarter of the machine's RAM as shared_buffers. The fixture
+# and the database stay on the machine; only <out> (events, scoreboard, logs)
+# is meant to be copied back.
+set -euo pipefail
+cd "$(dirname "$0")/../../.."
+export PATH="$HOME/.bun/bin:$PATH"
+PAGES=600000 RTT=65 HOURS=3 SEED=7 OUT="$HOME/soak/out" LABEL="" EXTRA=()
+while [ $# -gt 0 ]; do
+ case $1 in
+ --pages) PAGES=$2; shift 2 ;;
+ --rtt-ms) RTT=$2; shift 2 ;;
+ --hours) HOURS=$2; shift 2 ;;
+ --seed) SEED=$2; shift 2 ;;
+ --out) OUT=$2; shift 2 ;;
+ --label) LABEL=$2; shift 2 ;;
+ *) EXTRA+=("$1"); shift ;;
+ esac
+done
+ROOT="${SOAK_ROOT:-$HOME/soak}"
+mkdir -p "$ROOT" "$OUT"
+export SOAK_PG_SHARED_BUFFERS="$(( $(awk '/MemTotal/ {print $2}' /proc/meminfo) / 4096 ))MB"
+t0=$(date +%s)
+echo "[soak-run] fixture: $PAGES pages, seed $SEED"
+bun scripts/bench/production-soak/fixture.ts --out "$ROOT/fixture" --pages "$PAGES" --seed "$SEED" 2>&1 | tee "$OUT/fixture.log"
+echo "[soak-run] load (+$(( $(date +%s) - t0 ))s)"
+bun scripts/bench/production-soak/load.ts --fixture "$ROOT/fixture" --work "$ROOT/work" 2>&1 | tee "$OUT/load.log"
+cp "$ROOT/work/ready.json" "$OUT/ready.json"
+echo "[soak-run] soak $HOURS h at $RTT ms (+$(( $(date +%s) - t0 ))s)"
+bun scripts/bench/production-soak/soak.ts --fixture "$ROOT/fixture" --work "$ROOT/work" --out "$OUT" --rtt-ms "$RTT" --hours "$HOURS" --label "${LABEL:-rtt$RTT}" "${EXTRA[@]}" 2>&1 | tee "$OUT/soak.log"
+echo "[soak-run] done in $(( $(date +%s) - t0 ))s"
diff --git a/scripts/bench/production-soak/scoreboard.ts b/scripts/bench/production-soak/scoreboard.ts
new file mode 100644
index 0000000000..03b3763ea0
--- /dev/null
+++ b/scripts/bench/production-soak/scoreboard.ts
@@ -0,0 +1,170 @@
+/**
+ * Production-shaped scale soak, step 4: turn a soak's events.jsonl into the
+ * scoreboard (GBRA-174). Pure functions: buildScoreboard(events) and
+ * renderScoreboard(board); soak.ts writes both at the end of a run, and
+ * bun scripts/bench/production-soak/scoreboard.ts <events.jsonl> [--json]
+ * rebuilds them from a saved run.
+ *
+ * Every gate starts in "record" mode: it is computed and printed, and never
+ * fails a run. Moving a gate to "block" is a reviewed edit of GATES, decided
+ * by the release owner after several nightly runs show the threshold is
+ * stable.
+ */
+import { existsSync, readdirSync, readFileSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { pct } from './lib.ts';
+
+export type Ev = Record<string, any> & { t: number; kind: string };
+export interface Gate { id: string; metric: string; op: '<=' | '>=' | '=='; threshold: number | boolean; mode: 'record' | 'block'; why: string }
+
+/** Initial thresholds come from the stabilization plan and the agent wishlist; all record-only. */
+export const GATES: Gate[] = [
+ { id: 'freshness_p95', metric: 'freshness.lag_p95_s', op: '<=', threshold: 900, mode: 'record', why: 'commit -> searchable p95 under 15 minutes' },
+ { id: 'freshness_unresolved', metric: 'freshness.unresolved', op: '<=', threshold: 0, mode: 'record', why: 'every committed change becomes searchable before the run ends' },
+ { id: 'freshness_not_frozen', metric: 'freshness.frozen_by_hold', op: '==', threshold: false, mode: 'record', why: 'a held item never freezes the source watermark' },
+ { id: 'search_warm_p95', metric: 'reads.mcp.search.p95_ms', op: '<=', threshold: 2000, mode: 'record', why: 'warm search p95 under 2 s' },
+ { id: 'search_cold_p50', metric: 'reads.cli.search.p50_ms', op: '<=', threshold: 3000, mode: 'record', why: 'cold CLI search p50 under 3 s' },
+ { id: 'query_warm_p95', metric: 'reads.mcp.query.p95_ms', op: '<=', threshold: 3000, mode: 'record', why: 'warm query p95 under 3 s' },
+ { id: 'query_cold_p50', metric: 'reads.cli.query.p50_ms', op: '<=', threshold: 4000, mode: 'record', why: 'cold CLI query p50 under 4 s' },
+ { id: 'read_errors', metric: 'reads.error_rate', op: '<=', threshold: 0.01, mode: 'record', why: 'under 1% of reads fail' },
+ { id: 'put_p95', metric: 'writes.put.p95_ms', op: '<=', threshold: 10_000, mode: 'record', why: 'put p95 under 10 s' },
+ { id: 'remember_p95', metric: 'writes.remember.p95_ms', op: '<=', threshold: 10_000, mode: 'record', why: 'remember p95 under 10 s' },
+ { id: 'write_errors', metric: 'writes.error_rate', op: '<=', threshold: 0.01, mode: 'record', why: 'under 1% of writes fail' },
+ { id: 'session_pool_headroom', metric: 'pool.session_peak', op: '<=', threshold: 20, mode: 'record', why: 'session lane peak leaves 5 of 25 free' },
+ { id: 'session_refusals', metric: 'pool.session_refusals', op: '<=', threshold: 0, mode: 'record', why: 'no EMAXCONNSESSION-shaped refusal' },
+ { id: 'doctor_red', metric: 'doctor.red_end', op: '<=', threshold: 0, mode: 'record', why: 'doctor has no red check at the end' },
+ { id: 'version_skew', metric: 'version.skew', op: '==', threshold: false, mode: 'record', why: 'every process runs one build' },
+ { id: 'serve_rss', metric: 'memory.serve.peak_mb', op: '<=', threshold: 2048, mode: 'record', why: 'resident serve stays under 2 GiB' },
+ { id: 'serve_growth', metric: 'memory.serve.growth_mb_per_h', op: '<=', threshold: 100, mode: 'record', why: 'resident serve grows under 100 MiB per hour' },
+ { id: 'sync_jobs_progress', metric: 'sync_jobs.zero_progress', op: '<=', threshold: 0, mode: 'record', why: 'no managed sync job ends having applied nothing while the source is behind' },
+ { id: 'residents_alive', metric: 'residents.exits', op: '<=', threshold: 0, mode: 'record', why: 'serve and the worker never exit' },
+ { id: 'privacy_leaks', metric: 'privacy.leaks', op: '<=', threshold: 0, mode: 'record', why: 'no private or alias-private canary is readable by a remote caller' },
+];
+
+const stat = (xs: number[]) => ({ n: xs.length, p50: pct(xs, 50), p95: pct(xs, 95), max: xs.length ? Math.max(...xs) : null });
+const latency = (rows: Ev[]) => { const ok = rows.filter(r => r.ok); const s = stat(ok.map(r => r.ms)); const pending = rows.filter(r => r.outcome === 'pending').length; return { n: rows.length, errors: rows.length - ok.length - pending, pending, p50_ms: s.p50, p95_ms: s.p95, max_ms: s.max }; };
+const r1 = (x: number | null) => x === null ? null : Math.round(x * 10) / 10;
+
+export function buildScoreboard(events: Ev[]) {
+ const start = events.find(e => e.kind === 'start');
+ const end = events.find(e => e.kind === 'end');
+ const of = (k: string) => events.filter(e => e.kind === k);
+ const fresh = of('freshness'), unresolved = of('freshness_unresolved'), commits = of('commit'), status = of('status');
+ const lags = fresh.map(e => e.lag_ms / 1000);
+ // Watermark stall: the longest run of status samples where HEAD moved past sources.last_commit and last_commit did not change.
+ let stall = 0, stallStart: number | null = null, stallCommit: string | null = null, holdsDuringStall = 0, maxStallHolds = 0;
+ for (const s of status) {
+ const behind = s.head && s.last_commit && s.head !== s.last_commit;
+ if (behind && s.last_commit === stallCommit && stallStart !== null) { holdsDuringStall = Math.max(holdsDuringStall, s.holds ?? 0); if (s.at_s - stallStart > stall) { stall = s.at_s - stallStart; maxStallHolds = holdsDuringStall; } }
+ else if (behind) { stallStart = s.at_s; stallCommit = s.last_commit; holdsDuringStall = s.holds ?? 0; }
+ else { stallStart = null; stallCommit = null; holdsDuringStall = 0; }
+ }
+ const commitEvery = start?.config?.commit_every_s ?? 180;
+ const frozen = stall > Math.max(1800, 4 * commitEvery) && maxStallHolds > 0;
+ const firstProblem = commits.find(c => c.problem);
+ const afterProblem = firstProblem ? commits.filter(c => c.n > firstProblem.n && !c.problem) : [];
+ const resolvedAfter = afterProblem.filter(c => fresh.some(f => f.n === c.n)).length;
+ const reads = of('read');
+ const readsBy: Record<string, Record<string, ReturnType<typeof latency>>> = {};
+ for (const surface of ['cli', 'mcp']) { readsBy[surface] = {}; for (const op of [...new Set(reads.filter(r => r.surface === surface).map(r => r.op))]) readsBy[surface]![op === 'get_page' ? 'get' : op] = latency(reads.filter(r => r.surface === surface && r.op === op)); }
+ const writes = of('write');
+ const writesBy: Record<string, ReturnType<typeof latency> & { by_surface: Record<string, ReturnType<typeof latency>> }> = {};
+ for (const op of ['put', 'remember']) writesBy[op] = { ...latency(writes.filter(w => w.op === op)), by_surface: Object.fromEntries(['cli', 'mcp'].map(s => [s, latency(writes.filter(w => w.op === op && w.surface === s))])) };
+ const samples = of('sample');
+ const memFor = (name: string) => {
+ const xs = samples.filter(s => s.mem?.[name]).map(s => ({ at: s.at_s, mb: s.mem[name].rss_mb, hwm: s.mem[name].hwm_mb }));
+ if (!xs.length) return { peak_mb: null, end_mb: null, growth_mb_per_h: null };
+ const warm = xs.filter(x => x.at >= 600), a = warm[0] ?? xs[0]!, b = xs[xs.length - 1]!;
+ return { peak_mb: Math.max(...xs.map(x => Math.max(x.mb, x.hwm))), end_mb: b.mb, growth_mb_per_h: b.at > a.at ? Math.round(((b.mb - a.mb) / ((b.at - a.at) / 3600)) * 10) / 10 : null };
+ };
+ const doctors = of('doctor');
+ const docEnd = doctors.find(d => d.at === 'end') ?? doctors[doctors.length - 1];
+ const priv = of('privacy'), passive = of('privacy_passive');
+ const leaks: Ev[] = [...priv.filter(p => p.leaked), ...passive.map(p => ({ ...p, class: 'passive' }))];
+ const holds = status.map(s => s.holds ?? 0);
+ const skewChecks = doctors.flatMap(d => [...(d.red ?? []).map((r: { name: string }) => r.name), ...(d.warn ?? [])]).filter((n: string) => /skew|build_drift|version/.test(n));
+ const maint = of('maintenance');
+ const board = {
+ schema: 'gbrain-production-soak-scoreboard/1',
+ label: start?.config?.label || null, gbrain_rev: start?.gbrain_rev ?? null, gbrain_version: start?.version ?? null, rtt_ms: start?.config?.rtt_ms ?? null,
+ hours: start?.config?.hours ?? null, elapsed_s: end?.elapsed_s ?? null, config: start?.config ?? null, brain: start?.ready ?? null,
+ freshness: {
+ commits: commits.length, resolved: fresh.length, unresolved: unresolved.length, unresolved_max_age_s: unresolved.length ? Math.round(Math.max(...unresolved.map(u => u.age_ms)) / 1000) : 0,
+ lag_p50_s: r1(pct(lags, 50)), lag_p95_s: r1(pct(lags, 95)), lag_max_s: r1(lags.length ? Math.max(...lags) : null), first_hit_p50_s: r1(pct(fresh.map(e => e.first_ms / 1000), 50)),
+ writer_errors: of('writer_error').length, watermark_stall_max_s: stall, holds_during_stall: maxStallHolds, frozen_by_hold: frozen,
+ after_first_hold_commit: firstProblem ? { commits: afterProblem.length, resolved: resolvedAfter } : null,
+ gbrain_reported: status.length ? { c2s_p50_s: status[status.length - 1]!.gbrain_c2s_p50_s, c2s_p95_s: status[status.length - 1]!.gbrain_c2s_p95_s, behind_commits_end: status[status.length - 1]!.behind_commits } : null,
+ },
+ reads: { ...readsBy, error_rate: reads.length ? Math.round((reads.filter(r => !r.ok).length / reads.length) * 10_000) / 10_000 : null, errors_top: topErrors(reads) },
+ writes: { ...writesBy, pending: writes.filter(w => w.outcome === 'pending').length, error_rate: writes.length ? Math.round((writes.filter(w => w.outcome === 'error' || (w.outcome === undefined && !w.ok)).length / writes.length) * 10_000) / 10_000 : null, errors_top: topErrors(writes) },
+ pool: { session_peak: samples.length ? Math.max(...samples.map(s => s.session)) : null, session_active_peak: samples.length ? Math.max(...samples.map(s => s.session_active)) : null,
+ txn_peak: samples.length ? Math.max(...samples.map(s => s.txn)) : null, backends_peak: samples.length ? Math.max(...samples.map(s => s.backends)) : null,
+ session_refusals: end?.refused?.session ?? null, txn_refusals: end?.refused?.txn ?? null, log_hits: end?.log_hits ?? null },
+ holds: { start: holds[0] ?? null, max: holds.length ? Math.max(...holds) : null, end: holds[holds.length - 1] ?? null, codes_end: status[status.length - 1]?.hold_codes ?? null,
+ states: [...new Set(status.map(s => s.state + '/' + s.reason))], status_p50_ms: pct(status.map(s => s.ms), 50), status_max_ms: status.length ? Math.max(...status.map(s => s.ms)) : null },
+ version: { versions: [start?.version].filter(Boolean), skew: skewChecks.length > 0, doctor_flags: [...new Set(skewChecks)] },
+ doctor: { runs: doctors.map(d => ({ at: d.at, ms: d.ms, code: d.code, health_score: d.health_score, red: d.red, warn: d.warn?.length ?? 0, unfinished: Array.isArray(d.unfinished) ? d.unfinished.length : d.unfinished, total: d.total })), red_end: docEnd ? (docEnd.red ?? []).length : null },
+ memory: { serve: memFor('serve'), worker: memFor('worker') },
+ residents: { exits: of('resident_exit').length, detail: of('resident_exit'), serve_owned_notifier: of('notifier_owner')[0]?.owned ?? null },
+ sync_jobs: of('sync_jobs')[0] ?? null,
+ import_records: { start: status[0]?.import_records ?? null, end: status[status.length - 1]?.import_records ?? null },
+ maintenance: Object.fromEntries([...new Set(maint.map(m => m.op))].map(op => { const xs = maint.filter(m => m.op === op); return [op, { runs: xs.length, failures: xs.filter(m => m.code !== 0).length, p50_ms: pct(xs.map(m => m.ms), 50), max_ms: xs.length ? Math.max(...xs.map(m => m.ms)) : null }]; })),
+ privacy: { probes: priv.length, passive_scanned: end?.privacy_passive_scanned ?? null, leaks: leaks.length, examples: leaks.slice(0, 3).map(l => ({ op: l.op, class: l.class, tokens: l.tokens, snippet: l.snippet })), by_class: count(leaks.map(l => l.class)), by_op: count(leaks.map(l => l.op)), probe_errors: priv.filter(p => p.error).length },
+ gates: [] as Array<Gate & { value: unknown; pass: boolean | null }>,
+ };
+ board.gates = GATES.map(g => { const value = g.metric.split('.').reduce<any>((o, k) => o?.[k], board); return { ...g, value, pass: value === null || value === undefined ? null : g.op === '<=' ? value <= g.threshold : g.op === '>=' ? value >= g.threshold : value === g.threshold }; });
+ return board;
+}
+
+function count(xs: string[]): Record<string, number> { const o: Record<string, number> = {}; for (const x of xs) o[x] = (o[x] ?? 0) + 1; return o; }
+function topErrors(rows: Ev[]): Array<{ err: string; n: number }> {
+ return Object.entries(count(rows.filter(r => !r.ok).map(r => String(r.err ?? 'exit ' + r.code).replace(/[0-9a-f]{8}-[0-9a-f-]{27}/g, '<id>').replace(/\d+/g, 'N').slice(0, 140)))).sort((a, b) => b[1] - a[1]).slice(0, 5).map(([err, n]) => ({ err, n }));
+}
+
+export function renderScoreboard(b: ReturnType<typeof buildScoreboard>): string {
+ const f = b.freshness, cell = (x: unknown) => x === null || x === undefined ? '-' : typeof x === 'object' ? JSON.stringify(x) : String(x);
+ const lines = ['# Production soak scoreboard' + (b.label ? ' (' + b.label + ')' : ''), '',
+ cell(b.gbrain_version) + ' at ' + cell(b.gbrain_rev).slice(0, 12) + ', ' + cell(b.rtt_ms) + ' ms RTT, ' + cell(b.elapsed_s) + ' s, ' + cell((b.brain as any)?.counts?.pages) + ' pages / ' + cell((b.brain as any)?.counts?.chunks) + ' chunks, ' + cell((b.brain as any)?.backlog_commits) + ' backlog commits at start.', '',
+ '| gate | value | threshold | result (record only) |', '|---|---|---|---|',
+ ...b.gates.map(g => '| ' + g.id + ' | ' + cell(g.value) + ' | ' + g.op + ' ' + cell(g.threshold) + ' | ' + (g.pass === null ? 'no data' : g.pass ? 'pass' : 'FAIL') + ' |'), '',
+ '**Freshness** (commit -> keyword-searchable): ' + f.resolved + '/' + f.commits + ' resolved, p50 ' + cell(f.lag_p50_s) + ' s, p95 ' + cell(f.lag_p95_s) + ' s, max ' + cell(f.lag_max_s) + ' s; ' + f.unresolved + ' unresolved (oldest ' + f.unresolved_max_age_s + ' s); longest watermark stall ' + f.watermark_stall_max_s + ' s with ' + f.holds_during_stall + ' holds.', '',
+ '| reads | op | n | errors | p50 ms | p95 ms |', '|---|---|---|---|---|---|'];
+ for (const surface of ['cli', 'mcp'] as const) for (const [op, s] of Object.entries((b.reads as any)[surface] ?? {})) { const x = s as any; lines.push('| ' + (surface === 'cli' ? 'cold CLI' : 'warm MCP') + ' | ' + op + ' | ' + x.n + ' | ' + x.errors + ' | ' + cell(x.p50_ms) + ' | ' + cell(x.p95_ms) + ' |'); }
+ lines.push('', '| writes | n | errors | p50 ms | p95 ms |', '|---|---|---|---|---|');
+ for (const op of ['put', 'remember'] as const) { const x = (b.writes as any)[op]; lines.push('| ' + op + ' | ' + x.n + ' | ' + x.errors + ' | ' + cell(x.p50_ms) + ' | ' + cell(x.p95_ms) + ' |'); }
+ lines.push('', '**Pool**: session peak ' + cell(b.pool.session_peak) + '/25 (active ' + cell(b.pool.session_active_peak) + '), transaction-lane server peak ' + cell(b.pool.txn_peak) + ', refusals ' + cell(b.pool.session_refusals) + ' session / ' + cell(b.pool.txn_refusals) + ' transaction, log hits ' + cell(b.pool.log_hits) + '.',
+ '**Holds**: start ' + cell(b.holds.start) + ', max ' + cell(b.holds.max) + ', end ' + cell(b.holds.end) + ' ' + cell(b.holds.codes_end) + '; states ' + b.holds.states.join(', ') + '.',
+ '**Doctor**: ' + b.doctor.runs.map(d => d.at + ' ' + Math.round((d.ms ?? 0) / 1000) + ' s, ' + (d.red ?? []).length + ' red' + ((d.red ?? []).length ? ' (' + (d.red as Array<{ name: string }>).map(r => r.name).join(', ') + ')' : '')).join('; ') + '.',
+ '**Memory**: serve peak ' + cell(b.memory.serve.peak_mb) + ' MiB (growth ' + cell(b.memory.serve.growth_mb_per_h) + ' MiB/h), worker peak ' + cell(b.memory.worker.peak_mb) + ' MiB.',
+ '**Sync jobs**: ' + cell((b.sync_jobs as any)?.jobs) + ' jobs ' + cell((b.sync_jobs as any)?.by_status) + ', ' + cell((b.sync_jobs as any)?.zero_progress) + ' stopped without applying anything, longest ' + cell((b.sync_jobs as any)?.max_s) + ' s; notifier owners ' + cell(((b.sync_jobs as any)?.notifier_owners ?? []).map((o: { log: string }) => o.log)) + '; serve owned the notifier at start: ' + cell(b.residents.serve_owned_notifier) + '.',
+ '**Import records** (managed provenance, pages with a record / live pages): start ' + cell(b.import_records.start) + ', end ' + cell(b.import_records.end) + '.',
+ '**Privacy**: ' + b.privacy.probes + ' remote probes, ' + b.privacy.leaks + ' leaks ' + cell(b.privacy.by_class) + '.',
+ '**Maintenance**: ' + Object.entries(b.maintenance).map(([op, m]) => op + ' ' + (m as any).runs + ' runs, ' + (m as any).failures + ' failed, p50 ' + Math.round(((m as any).p50_ms ?? 0) / 1000) + ' s').join('; ') + '.');
+ if (b.reads.errors_top.length) lines.push('', 'Top read errors: ' + b.reads.errors_top.map(e => e.n + 'x ' + e.err).join('; '));
+ if (b.writes.errors_top.length) lines.push('', 'Top write errors: ' + b.writes.errors_top.map(e => e.n + 'x ' + e.err).join('; '));
+ return lines.join('\n') + '\n';
+}
+
+/** One JSON document holding every cell's scoreboard (ubicloud.sh and the workflow write one cell per latency). */
+export function combineScoreboards(dir: string): { schema: string; cells: Array<ReturnType<typeof buildScoreboard>> } {
+ const cells: Array<ReturnType<typeof buildScoreboard>> = [];
+ for (const sub of readdirSync(dir).sort()) for (const rel of ['scoreboard.json', 'out/scoreboard.json']) {
+ const file = join(dir, sub, rel);
+ if (existsSync(file)) { cells.push(JSON.parse(readFileSync(file, 'utf8'))); break; }
+ }
+ return { schema: 'gbrain-production-soak-scoreboards/1', cells };
+}
+
+if (import.meta.main) {
+ if (process.argv[2] === '--combine') {
+ const dir = process.argv[3]!;
+ const all = combineScoreboards(dir);
+ writeFileSync(join(dir, 'scoreboard.json'), JSON.stringify(all, null, 2));
+ console.log(all.cells.map(renderScoreboard).join('\n'));
+ process.exit(0);
+ }
+ const file = process.argv[2];
+ if (!file) { console.error('usage: scoreboard.ts <events.jsonl> [--json] | --combine <dir>'); process.exit(2); }
+ const board = buildScoreboard(readFileSync(file, 'utf8').split('\n').filter(Boolean).map(l => JSON.parse(l)));
+ console.log(process.argv.includes('--json') ? JSON.stringify(board, null, 2) : renderScoreboard(board));
+}
diff --git a/scripts/bench/production-soak/soak.ts b/scripts/bench/production-soak/soak.ts
new file mode 100644
index 0000000000..c749af7992
--- /dev/null
+++ b/scripts/bench/production-soak/soak.ts
@@ -0,0 +1,411 @@
+#!/usr/bin/env bun
+/**
+ * Production-shaped scale soak, step 3: run the production topology against a
+ * load.ts brain for N hours and record every measurement (GBRA-174). Opt-in
+ * bench code, never run in CI.
+ *
+ * bun scripts/bench/production-soak/soak.ts --fixture <dir> --work <dir> --out <dir>
+ * [--rtt-ms 65] [--hours 2] [--commit-every-s 180] [--cli-readers 2] [--mcp-readers 2]
+ * [--read-gap-s 4] [--write-every-s 60] [--stale-every-s 600] [--status-every-s 120]
+ * [--embed-ms 0] [--rerank-ms 0] [--resident http|stdio] [--label <name>]
+ *
+ * Database: database_url is the transaction lane and GBRAIN_DIRECT_DATABASE_URL
+ * the session lane (pool 25, a 26th client refused), both through toxiproxy at
+ * --rtt-ms round trip. Processes, all from this checkout:
+ * - one resident gbrain serve (--http by default) with sync.on_commit=true, the
+ * only process that syncs;
+ * - one gbrain jobs work worker;
+ * - --mcp-readers gbrain serve stdio clients (remote callers) looping
+ * search / query / get_page / recall (warm latency), plus privacy probes
+ * that look for the fixture's private canaries;
+ * - --cli-readers loops of one-shot gbrain search / query / get (cold);
+ * - an external writer committing edits, new pages, moves, archive culls,
+ * deletes and now and then a file gbrain must hold, every --commit-every-s;
+ * - put / remember writes through the CLI and MCP every --write-every-s;
+ * - extract --stale and embed --stale every --stale-every-s;
+ * - samplers: session-lane and transaction-lane server connections each 5 s,
+ * resident RSS, sync status (holds, state, behind) each --status-every-s,
+ * and doctor --json at start, midpoint and end.
+ * Freshness is commit -> keyword-searchable for every token the writer commits,
+ * probed on a direct connection so the probe adds no latency.
+ *
+ * Writes <out>/events.jsonl (one row per measurement), <out>/logs/ and then
+ * <out>/scoreboard.json + scoreboard.md (scoreboard.ts). Embedding and rerank go
+ * to the loopback mock provider; nothing leaves the machine.
+ */
+import { appendFileSync, existsSync, mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs';
+import { dirname, join, resolve } from 'node:path';
+import { execFileSync } from 'node:child_process';
+import postgres from '#postgres';
+import { startMockProviders } from '../retrieval-scale/mock-providers.ts';
+import { McpClient, spawnChild, type Child } from '../sync-freshness-lib.ts';
+import { childEnv, gb, log as baseLog, now, REPO, SESSION_ROLE, sleep, startTopology, TXN_ROLE, writeConfig } from './lib.ts';
+import { buildScoreboard, renderScoreboard } from './scoreboard.ts';
+
+const argv = process.argv.slice(2);
+const flag = (n: string, f: string) => { const i = argv.indexOf('--' + n); return i >= 0 && argv[i + 1] ? argv[i + 1]! : f; };
+const num = (n: string, f: number) => Number(flag(n, String(f)));
+const FIXTURE = resolve(flag('fixture', '')), WORK = resolve(flag('work', '')), OUT = resolve(flag('out', ''));
+if (!argv.includes('--fixture') || !argv.includes('--work') || !argv.includes('--out')) { console.error('usage: see the header of scripts/bench/production-soak/soak.ts'); process.exit(2); }
+export const CONFIG = {
+ rtt_ms: num('rtt-ms', 65), hours: num('hours', 2), commit_every_s: num('commit-every-s', 180), cli_readers: num('cli-readers', 2), mcp_readers: num('mcp-readers', 2),
+ read_gap_s: num('read-gap-s', 4), write_every_s: num('write-every-s', 60), stale_every_s: num('stale-every-s', 600), status_every_s: num('status-every-s', 120),
+ embed_ms: num('embed-ms', 0), rerank_ms: num('rerank-ms', 0), resident: flag('resident', 'http') as 'http' | 'stdio', label: flag('label', ''),
+};
+const CLI = join(REPO, 'src', 'cli.ts');
+const log = (m: string) => baseLog('soak', m);
+const ready = JSON.parse(readFileSync(join(WORK, 'ready.json'), 'utf8'));
+const manifest = JSON.parse(readFileSync(join(FIXTURE, 'manifest.json'), 'utf8'));
+const DB: string = ready.db;
+const HOME = join(WORK, 'home');
+const WRITER_SOURCE = 'default';
+const REPO_A: string = manifest.sources.find((s: { id: string }) => s.id === WRITER_SOURCE).repo;
+const EVENTS = join(OUT, 'events.jsonl');
+const LOGS = join(OUT, 'logs');
+let deadline = 0, stopping = false, passiveScanned = 0;
+const PRIVATE = new Set<string>(JSON.parse(readFileSync(join(FIXTURE, 'private-tokens.json'), 'utf8')));
+/** Private tokens (canaries and private pages' search tokens) in a remote caller's response, minus the token the caller itself sent. */
+export function leakedTokens(text: string, sent = ''): string[] { return [...new Set(text.match(/zq(?:pv|pg|pd)[0-9a-z]{7}/g) ?? [])].filter(t => PRIVATE.has(t) && t !== sent); }
+const live = () => now() < deadline;
+export function emit(kind: string, data: Record<string, unknown>): void { appendFileSync(EVENTS, JSON.stringify({ t: Math.round(now()), kind, ...data }) + '\n'); }
+const rnd = (n: number) => Math.floor(Math.random() * n);
+const pick = <T>(xs: T[]): T => xs[rnd(xs.length)]!;
+const git = (...args: string[]) => execFileSync('git', ['-C', REPO_A, ...args], { encoding: 'utf8', maxBuffer: 1 << 26 }).trim();
+
+interface Target { slug: string; source: string; title: string; text: string; path: string | null; token: string | null }
+
+async function sampleTargets(directUrl: string): Promise<Target[]> {
+ const sql = postgres(directUrl, { max: 1, onnotice: () => {} });
+ const rows = await sql.unsafe("SELECT p.slug, p.source_id, p.title, p.source_path, left(c.chunk_text, 600) AS text FROM pages p JOIN content_chunks c ON c.page_id = p.id AND c.chunk_index = 0 WHERE p.deleted_at IS NULL AND p.frontmatter->>'visibility' IS NULL AND p.frontmatter->>'access' IS NULL AND p.frontmatter->>'confidentiality' IS NULL AND p.type <> 'chat' ORDER BY md5(p.id::text) LIMIT 1500") as Array<{ slug: string; source_id: string; title: string; source_path: string | null; text: string }>;
+ await sql.end();
+ return rows.map(r => ({ slug: r.slug, source: r.source_id, title: r.title, text: r.text, path: r.source_path, token: /zqpg[0-9a-z]{7}/.exec(r.text)?.[0] ?? null }));
+}
+function queryFor(t: Target, i: number): string {
+ if (i % 5 === 0 && t.token) return t.token;
+ const words = t.text.replace(/[^a-z\s]/gi, ' ').split(/\s+/).filter(w => w.length > 3);
+ const k = 2 + (i % 3), at = (i * 7919) % Math.max(1, words.length - k);
+ const titleWord = t.title.split(/\s+/).find(w => w.length > 3);
+ return [...(i % 2 === 0 && titleWord ? [titleWord.toLowerCase()] : []), ...words.slice(at, at + k)].join(' ') || t.title;
+}
+
+async function main() {
+ rmSync(OUT, { recursive: true, force: true });
+ mkdirSync(LOGS, { recursive: true });
+ const topo = await startTopology(WORK, undefined, undefined, true);
+ await topo.setRtt(0);
+ const directUrl = topo.direct(DB);
+ const targets = await sampleTargets(directUrl);
+ const mock = startMockProviders({ manifest: { seed: manifest.options.seed, chunks: manifest.pages * 4, pages: manifest.pages, dims: 1536 }, embedMs: CONFIG.embed_ms, rerankMs: CONFIG.rerank_ms });
+ writeConfig(HOME, topo.txn(DB), mock.url);
+ const env = childEnv(HOME, mock.url, { GBRAIN_DIRECT_DATABASE_URL: topo.session(DB) });
+ await gb(CLI, HOME, env, ['config', 'set', 'sync.on_commit', 'true']);
+ await topo.setRtt(CONFIG.rtt_ms);
+ const startedAt = now();
+ deadline = startedAt + CONFIG.hours * 3600_000;
+ emit('start', { config: CONFIG, ready: { counts: ready.counts, backlog_commits: ready.backlog_commits, drift: ready.drift, fixture: ready.fixture }, gbrain_rev: execFileSync('git', ['-C', REPO, 'rev-parse', 'HEAD'], { encoding: 'utf8' }).trim(),
+ version: (await gb(CLI, HOME, env, ['--version'], { allowFail: true })).stdout.trim(), targets: targets.length, canaries: manifest.privacy.canaries.length });
+ log('soak ' + CONFIG.hours + ' h at ' + CONFIG.rtt_ms + ' ms RTT on ' + ready.counts?.pages + ' pages (' + ready.backlog_commits + ' backlog commits)');
+
+ const residents: Record<string, Child> = {};
+ const port = 3131 + rnd(500);
+ residents.serve = spawnChild([process.execPath, CLI, 'serve', ...(CONFIG.resident === 'http' ? ['--http', '--bind', '127.0.0.1', '--port', String(port)] : [])], { cwd: HOME, env, logFile: join(LOGS, 'serve.log'), stdin: true });
+ const owned = await waitForLine(residents.serve, /owner of this host's notifier/, 180_000);
+ emit('notifier_owner', { name: 'serve', owned, wait_ms: Math.round(now() - startedAt) });
+ if (!owned) log('resident serve did not take the notifier within 180 s; continuing (the scoreboard records it)');
+ residents.worker = spawnChild([process.execPath, CLI, 'jobs', 'work'], { cwd: HOME, env, logFile: join(LOGS, 'worker.log') });
+ for (const [name, c] of Object.entries(residents)) void c.exited.then(code => { if (stopping) return; emit('resident_exit', { name, code, at_s: Math.round((now() - startedAt) / 1000) }); log(name + ' exited ' + code); });
+
+ const tasks: Promise<unknown>[] = [];
+ tasks.push(doctorAt(env, startedAt, [0, 0.5]));
+ tasks.push(sampler(directUrl, residents, startedAt));
+ tasks.push(statusLoop(env, directUrl, startedAt));
+ tasks.push(writerLoop(directUrl, startedAt));
+ for (let r = 0; r < CONFIG.cli_readers; r++) tasks.push(cliReader(env, targets, r));
+ for (let r = 0; r < CONFIG.mcp_readers; r++) tasks.push(mcpReader(env, targets, r));
+ tasks.push(writeLoop(env, targets));
+ tasks.push(staleLoop(env));
+ await Promise.allSettled(tasks);
+
+ await doctorOnce(env, startedAt, 'end');
+ const refused = topo.refusals();
+ const logHits = grepLogs(/EMAXCONNSESSION|no more connections allowed|max_client_conn|remaining connection slots|too many clients/i);
+ emit('sync_jobs', syncJobs());
+ emit('end', { refused, log_hits: logHits, elapsed_s: Math.round((now() - startedAt) / 1000), provider: mock.stats, privacy_passive_scanned: passiveScanned });
+ stopping = true;
+ for (const c of Object.values(residents)) c.kill('SIGTERM');
+ await Promise.race([Promise.all(Object.values(residents).map(c => c.exited)), sleep(15_000)]);
+ for (const c of Object.values(residents)) c.kill('SIGKILL');
+ mock.stop();
+ await topo.setRtt(0);
+ const board = buildScoreboard(readFileSync(EVENTS, 'utf8').split('\n').filter(Boolean).map(l => JSON.parse(l)));
+ writeFileSync(join(OUT, 'scoreboard.json'), JSON.stringify(board, null, 2));
+ writeFileSync(join(OUT, 'scoreboard.md'), renderScoreboard(board));
+ console.log(renderScoreboard(board));
+ process.exit(0);
+}
+
+function waitForLine(c: Child, re: RegExp, ms: number): Promise<boolean> {
+ if (c.lines.some(l => re.test(l.text))) return Promise.resolve(true);
+ return new Promise(resolve => { const t = setTimeout(() => resolve(false), ms); c.onLine(l => { if (re.test(l.text)) { clearTimeout(t); resolve(true); } }); });
+}
+
+/** Every managed sync job any process ran (its done line) and every notifier ownership change, from the process logs. */
+function syncJobs(): Record<string, unknown> {
+ const jobs: Array<{ log: string; status: string; added: number; modified: number; deleted: number; s: number }> = [];
+ const owners: Array<{ log: string; at: string }> = [];
+ for (const f of readdirSync(LOGS)) {
+ if (!f.endsWith('.log')) continue;
+ for (const l of readFileSync(join(LOGS, f), 'utf8').split('\n')) {
+ const m = /\[serve-sync\] done job=\S+ status=(\S+) added=(\d+) modified=(\d+) deleted=(\d+).* in=(\d+)s/.exec(l);
+ if (m) jobs.push({ log: f, status: m[1]!, added: +m[2]!, modified: +m[3]!, deleted: +m[4]!, s: +m[5]! });
+ if (/owner of this host's notifier/.test(l)) owners.push({ log: f, at: l.slice(0, 24) });
+ }
+ }
+ return { jobs: jobs.length, by_status: jobs.reduce<Record<string, number>>((o, j) => { o[j.status] = (o[j.status] ?? 0) + 1; return o; }, {}),
+ zero_progress: jobs.filter(j => j.added + j.modified + j.deleted === 0 && !['synced', 'up_to_date', 'first_sync'].includes(j.status)).length, max_s: jobs.length ? Math.max(...jobs.map(j => j.s)) : null,
+ applied: jobs.reduce((a, j) => a + j.added + j.modified + j.deleted, 0), notifier_owners: owners };
+}
+
+function grepLogs(re: RegExp): Record<string, number> {
+ const out: Record<string, number> = {};
+ for (const f of readdirSync(LOGS)) { const n = readFileSync(join(LOGS, f), 'utf8').split('\n').filter(l => re.test(l)).length; if (n) out[f] = n; }
+ return out;
+}
+
+async function doctorOnce(env: Record<string, string>, startedAt: number, at: string): Promise<void> {
+ const r = await gb(CLI, HOME, env, ['doctor', '--json'], { allowFail: true, timeoutMs: 20 * 60_000 });
+ writeFileSync(join(LOGS, 'doctor-' + at + '.json'), r.stdout);
+ const checks: Array<{ name: string; status: string; message?: string; details?: { reason?: string } }> = r.json?.checks ?? [];
+ const unfinished = (c: typeof checks[number]) => c.details?.reason === 'budget' || ['skipped', 'timeout', 'unfinished'].includes(String(c.status));
+ emit('doctor', { at, at_s: Math.round((now() - startedAt) / 1000), ms: Math.round(r.ms), code: r.code, health_score: r.json?.health_score ?? r.json?.score ?? null, status: r.json?.status ?? null,
+ red: checks.filter(c => ['fail', 'error', 'red'].includes(String(c.status)) && !unfinished(c)).map(c => ({ name: c.name, message: String(c.message ?? '').slice(0, 300) })),
+ warn: checks.filter(c => ['warn', 'yellow'].includes(String(c.status)) && !unfinished(c)).map(c => c.name), unfinished: checks.filter(unfinished).map(c => c.name), total: checks.length });
+}
+async function doctorAt(env: Record<string, string>, startedAt: number, fractions: number[]): Promise<void> {
+ for (const f of fractions) {
+ const at = startedAt + f * CONFIG.hours * 3600_000;
+ while (now() < at && live()) await sleep(5000);
+ if (!live()) return;
+ await doctorOnce(env, startedAt, f === 0 ? 'start' : 'mid');
+ }
+}
+
+/** /proc RSS of a process and its live descendants, in MiB, plus the process's own peak (VmHWM). */
+function rssTree(pid: number): { rss_mb: number; hwm_mb: number } {
+ const kids = new Map<number, number[]>();
+ const rss = new Map<number, number>();
+ let hwm = 0;
+ for (const name of readdirSync('/proc')) {
+ if (!/^\d+$/.test(name)) continue;
+ try {
+ const status = readFileSync('/proc/' + name + '/status', 'utf8');
+ const ppid = Number(/PPid:\s+(\d+)/.exec(status)?.[1]);
+ rss.set(Number(name), Number(/VmRSS:\s+(\d+)/.exec(status)?.[1] ?? 0));
+ if (Number(name) === pid) hwm = Number(/VmHWM:\s+(\d+)/.exec(status)?.[1] ?? 0);
+ kids.set(ppid, [...(kids.get(ppid) ?? []), Number(name)]);
+ } catch { /* exited */ }
+ }
+ let total = 0;
+ for (const q = [pid]; q.length;) { const p = q.pop()!; total += rss.get(p) ?? 0; q.push(...(kids.get(p) ?? [])); }
+ return { rss_mb: Math.round(total / 1024), hwm_mb: Math.round(hwm / 1024) };
+}
+
+async function sampler(directUrl: string, residents: Record<string, Child>, startedAt: number): Promise<void> {
+ const sql = postgres(directUrl, { max: 1, onnotice: () => {} });
+ while (live()) {
+ try {
+ const rows = await sql.unsafe("SELECT usename, state, count(*)::int AS n FROM pg_stat_activity WHERE datname = $1 GROUP BY 1, 2", [DB]) as Array<{ usename: string; state: string | null; n: number }>;
+ const sum = (u: string, active?: boolean) => rows.filter(r => r.usename === u && (active === undefined || (r.state === 'active' || r.state === 'idle in transaction') === active)).reduce((a, r) => a + r.n, 0);
+ const mem = Object.fromEntries(Object.entries(residents).map(([k, c]) => [k, c.exitAt === null ? rssTree(c.proc.pid) : null]));
+ emit('sample', { at_s: Math.round((now() - startedAt) / 1000), session: sum(SESSION_ROLE), session_active: sum(SESSION_ROLE, true), txn: sum(TXN_ROLE), txn_active: sum(TXN_ROLE, true), backends: rows.reduce((a, r) => a + r.n, 0), mem });
+ } catch (e) { emit('sample_error', { error: String(e).slice(0, 200) }); }
+ await sleep(5000);
+ }
+ await sql.end();
+}
+
+async function statusLoop(env: Record<string, string>, directUrl: string, startedAt: number): Promise<void> {
+ const sql = postgres(directUrl, { max: 1, onnotice: () => {} });
+ while (live()) {
+ const r = await gb(CLI, HOME, env, ['sync', 'status', '--source', WRITER_SOURCE, '--json'], { allowFail: true, timeoutMs: 10 * 60_000 });
+ const j = r.json ?? {};
+ const holds: Array<{ code: string }> = Array.isArray(j.holds) ? j.holds : [];
+ const codes: Record<string, number> = {};
+ for (const h of holds) codes[h.code] = (codes[h.code] ?? 0) + 1;
+ const src = await sql.unsafe('SELECT id, last_commit, last_sync_at FROM sources ORDER BY id').catch(() => []) as Array<{ id: string; last_commit: string | null; last_sync_at: Date | null }>;
+ let head = '';
+ try { head = git('rev-parse', 'HEAD'); } catch { /* writer mid-commit */ }
+ const a = src.find(s => s.id === WRITER_SOURCE);
+ const coverage = await sql.unsafe("SELECT p.source_id, count(*)::int AS pages, count(o.fingerprint)::int AS recorded FROM pages p LEFT JOIN op_checkpoints o ON o.op = 'sync-import-provenance' AND (o.completed_keys->0->>'page_id')::bigint = p.id WHERE p.deleted_at IS NULL GROUP BY 1 ORDER BY 1").catch(() => []) as Array<{ source_id: string; pages: number; recorded: number }>;
+ emit('status', { at_s: Math.round((now() - startedAt) / 1000), ms: Math.round(r.ms), code: r.code, state: j.state ?? null, reason: j.reason ?? null, holds: holds.length, hold_codes: codes,
+ needs_human: j.needs_human ?? null, behind_commits: j.freshness?.behind?.commits ?? null, behind_oldest_s: j.freshness?.behind?.oldest_seconds ?? null,
+ gbrain_c2s_p50_s: j.freshness?.commit_to_searchable?.p50_seconds ?? null, gbrain_c2s_p95_s: j.freshness?.commit_to_searchable?.p95_seconds ?? null,
+ notifier_state: j.notifier?.state ?? null, notifier_stalled: j.notifier?.stalled ?? null, last_error: j.last_error ? JSON.stringify(j.last_error).slice(0, 300) : null,
+ import_records: Object.fromEntries(coverage.map(c => [c.source_id, { pages: c.pages, recorded: c.recorded }])), legacy_swept: j.convergence?.counts?.legacy_swept ?? null,
+ head, last_commit: a?.last_commit ?? null, last_sync_at: a?.last_sync_at ? new Date(a.last_sync_at).toISOString() : null,
+ sources: src.map(s => ({ id: s.id, last_commit: s.last_commit, last_sync_at: s.last_sync_at ? new Date(s.last_sync_at).toISOString() : null })) });
+ const until = now() + CONFIG.status_every_s * 1000;
+ while (live() && now() < until) await sleep(2000);
+ }
+ await sql.end();
+}
+
+/** External writer: named-path commits to the default source's checkout, like an agent editing files plus a librarian committing them. */
+async function writerLoop(directUrl: string, startedAt: number): Promise<void> {
+ const { PostgresEngine } = await import('../../../src/core/postgres-engine.ts');
+ const engine = new PostgresEngine();
+ await engine.connect({ database_url: directUrl, poolSize: 2 });
+ const sql = postgres(directUrl, { max: 1, onnotice: () => {} });
+ const paths = (await sql.unsafe("SELECT source_path FROM pages WHERE source_id = $1 AND deleted_at IS NULL AND source_path IS NOT NULL AND type NOT IN ('chat') AND source_path NOT LIKE 'archive/%' ORDER BY md5(id::text) LIMIT 4000", [WRITER_SOURCE]) as Array<{ source_path: string }>)
+ .map(r => r.source_path).filter(p => existsSync(join(REPO_A, p)));
+ await sql.end();
+ const pending: Array<{ n: number; sha: string; token: string; t_commit: number; expect: number; files: number; problem: boolean; first?: number }> = [];
+ let n = 0;
+ const probe = (async () => {
+ while (live() || pending.length) {
+ for (const c of [...pending]) {
+ const hits = await engine.searchKeyword(c.token, { limit: 100, sourceId: WRITER_SOURCE }).catch(() => []) as Array<{ slug: string }>;
+ const found = new Set(hits.map(h => h.slug)).size;
+ if (found > 0 && c.first === undefined) c.first = now();
+ if (found >= c.expect) {
+ emit('freshness', { n: c.n, sha: c.sha, lag_ms: Math.round(now() - c.t_commit), first_ms: Math.round((c.first ?? now()) - c.t_commit), files: c.files, problem: c.problem, at_s: Math.round((c.t_commit - startedAt) / 1000) });
+ pending.splice(pending.indexOf(c), 1);
+ }
+ }
+ if (!live() && pending.length) { for (const c of pending) emit('freshness_unresolved', { n: c.n, sha: c.sha, age_ms: Math.round(now() - c.t_commit), first_ms: c.first === undefined ? null : Math.round(c.first - c.t_commit), files: c.files, at_s: Math.round((c.t_commit - startedAt) / 1000) }); break; }
+ await sleep(2000);
+ }
+ })();
+ while (live()) {
+ n++;
+ const token = 'zqfr' + n.toString(36).padStart(3, '0') + Math.random().toString(36).slice(2, 8);
+ const touched: string[] = [], removed: string[] = [];
+ let expect = 0;
+ const edits = 5 + rnd(16);
+ for (let k = 0; k < edits && paths.length; k++) {
+ const p = pick(paths);
+ if (touched.includes(p) || !existsSync(join(REPO_A, p))) continue;
+ appendFileSync(join(REPO_A, p), '\nEdited in soak commit ' + n + ': ' + token + ' follow-up on the plan.\n');
+ touched.push(p); expect++;
+ }
+ for (let k = 0; k < 1 + rnd(3); k++) {
+ const p = 'notes/inbox/soak-' + token + '-' + k + '.md';
+ mkdirSync(dirname(join(REPO_A, p)), { recursive: true });
+ writeFileSync(join(REPO_A, p), '---\ntitle: "Soak note ' + n + '-' + k + '"\ntype: note\n---\n# Soak note ' + n + '-' + k + '\n\nNew note ' + token + ' written during the soak.\n');
+ touched.push(p); paths.push(p); expect++;
+ }
+ const move = (to: (p: string) => string) => { const p = pick(paths); if (!existsSync(join(REPO_A, p)) || touched.includes(p)) return; const dest = to(p); mkdirSync(dirname(join(REPO_A, dest)), { recursive: true }); try { git('mv', p, dest); removed.push(p); touched.push(dest); paths.splice(paths.indexOf(p), 1, dest); } catch { /* raced */ } };
+ if (n % 3 === 0) move(p => p.replace(/^notes\/[^/]+\//, 'notes/ops/').replace(/^(?!notes\/)/, 'moved/'));
+ if (n % 5 === 0) move(p => 'archive/2026/' + p);
+ if (n % 4 === 0) { const p = pick(paths); if (existsSync(join(REPO_A, p)) && !touched.includes(p)) { try { git('rm', '-q', p); removed.push(p); paths.splice(paths.indexOf(p), 1); } catch { /* raced */ } } }
+ const problem = n % 10 === 0;
+ if (problem) { const p = 'notes/inbox/soak-broken-' + token + '.md'; writeFileSync(join(REPO_A, p), '---\ntitle: "unterminated ' + token + '\ntype: note\n---\n# Broken\n'); touched.push(p); }
+ const t0 = now();
+ let sha = '', err = '';
+ for (let attempt = 0; attempt < 10 && !sha; attempt++) {
+ try {
+ git('add', '-A', '--', ...touched, ...removed);
+ git('commit', '-q', '-m', 'soak writer ' + n + ' ' + token);
+ sha = git('rev-parse', 'HEAD');
+ } catch (e) { err = String(e).slice(0, 300); await sleep(2000); }
+ }
+ if (!sha) { emit('writer_error', { n, error: err }); continue; }
+ const t_commit = now();
+ pending.push({ n, sha, token, t_commit, expect, files: touched.length + removed.length, problem });
+ emit('commit', { n, sha, files: touched.length + removed.length, edits: expect, removed: removed.length, problem, commit_ms: Math.round(t_commit - t0), at_s: Math.round((t_commit - startedAt) / 1000) });
+ const until = now() + CONFIG.commit_every_s * 1000;
+ while (live() && now() < until) await sleep(1000);
+ }
+ await probe;
+ await engine.disconnect();
+}
+
+async function cliReader(env: Record<string, string>, targets: Target[], r: number): Promise<void> {
+ let i = r * 1000;
+ while (live()) {
+ const t = targets[i % targets.length]!;
+ const op = ['search', 'query', 'get', 'search', 'query'][i % 5]!;
+ const args = op === 'get' ? ['get', t.slug, '--source', t.source] : [op, queryFor(t, i), '--json'];
+ const res = await gb(CLI, HOME, env, args, { allowFail: true, timeoutMs: 120_000 });
+ emit('read', { surface: 'cli', mode: 'cold', op, ms: Math.round(res.ms), ok: res.code === 0, code: res.code, err: res.code === 0 ? undefined : (res.stderr || res.stdout).trim().split('\n').slice(-1)[0]?.slice(0, 200) });
+ i++;
+ await sleep(CONFIG.read_gap_s * 1000);
+ }
+}
+
+/** A stdio MCP client; only its stderr is logged (stdout carries every response). */
+function mcpChild(env: Record<string, string>, name: string): { child: Child; client: McpClient } {
+ const child = spawnChild([process.execPath, CLI, 'serve'], { cwd: HOME, env, stdin: true });
+ child.onLine(l => { if (l.stream === 'err') appendFileSync(join(LOGS, name + '.log'), new Date(l.t).toISOString() + ' err ' + l.text + '\n'); });
+ return { child, client: new McpClient(child) };
+}
+
+async function mcpReader(env: Record<string, string>, targets: Target[], r: number): Promise<void> {
+ const { child, client } = mcpChild(env, 'mcp-reader-' + r);
+ try { await client.init(); } catch (e) { emit('mcp_error', { reader: r, error: String(e).slice(0, 300) }); child.kill(); return; }
+ const canaries: Array<{ source: string; slug: string; class: string; token: string }> = manifest.privacy.canaries;
+ let i = r * 1000;
+ while (live() && child.exitAt === null) {
+ const t = targets[i % targets.length]!;
+ const op = ['search', 'query', 'get_page', 'recall', 'search'][i % 5]!;
+ const args: Record<string, unknown> = op === 'get_page' ? { slug: t.slug, source_id: t.source } : { query: queryFor(t, i) };
+ const t0 = now();
+ const text = await client.call(op, args).catch(e => 'ERROR ' + String(e));
+ emit('read', { surface: 'mcp', mode: 'warm', op, ms: Math.round(now() - t0), ok: !text.startsWith('ERROR'), err: text.startsWith('ERROR') ? text.slice(0, 200) : undefined });
+ passiveScanned++;
+ const passive = leakedTokens(text);
+ if (passive.length) emit('privacy_passive', { op, tokens: passive.slice(0, 5), snippet: text.slice(Math.max(0, text.indexOf(passive[0]!) - 300), text.indexOf(passive[0]!) + 100) });
+ if (i % 3 === 0 && canaries.length) {
+ const c = canaries[(i / 3 + r) % canaries.length]!;
+ for (const [probeOp, probeArgs] of [['search', { query: c.token }], ['query', { query: c.token }], ['get_page', { slug: c.slug, source_id: c.source }], ['recall', { query: c.token }]] as const) {
+ const out = await client.call(probeOp, probeArgs as Record<string, unknown>).catch(e => 'ERROR ' + String(e));
+ const found = leakedTokens(out, probeOp === 'get_page' ? '' : c.token);
+ emit('privacy', { op: probeOp, class: c.class, leaked: found.length > 0, error: out.startsWith('ERROR') ? out.slice(0, 120) : undefined, ...(found.length ? { slug: c.slug, tokens: found.slice(0, 5), snippet: out.slice(Math.max(0, out.indexOf(found[0]!) - 300), out.indexOf(found[0]!) + 100) } : {}) });
+ }
+ }
+ i++;
+ await sleep(CONFIG.read_gap_s * 1000);
+ }
+ child.kill();
+}
+
+async function writeLoop(env: Record<string, string>, targets: Target[]): Promise<void> {
+ const { child, client } = mcpChild(env, 'mcp-writer');
+ const ok = await client.init().then(() => true, e => { emit('mcp_error', { reader: 'writer', error: String(e).slice(0, 300) }); return false; });
+ const people = targets.filter(t => t.slug.startsWith('people/') && t.source === WRITER_SOURCE);
+ let i = 0;
+ while (live()) {
+ const kind = i % 4;
+ const slug = 'notes/soak-writes/w-' + i + '-' + Math.random().toString(36).slice(2, 7);
+ const body = '---\ntitle: "Soak write ' + i + '"\ntype: note\n---\n# Soak write ' + i + '\n\nA page written through ' + (kind < 2 ? 'the CLI' : 'MCP') + ' during the soak.\n';
+ const entity = people.length ? pick(people).slug : undefined;
+ const fact = 'Soak fact ' + i + ': prefers the ' + pick(['harbor', 'quartz', 'meadow', 'signal']) + ' plan';
+ const t0 = now();
+ let outcome = 'error' as 'ok' | 'pending' | 'error', detail = '';
+ const cliOutcome = (r: { code: number; stdout: string; stderr: string }) => { outcome = r.code === 0 ? 'ok' : r.code === 10 ? 'pending' : 'error'; detail = r.code === 0 ? '' : (r.stderr || r.stdout).trim().split('\n').filter(l => !/^Docs: /.test(l)).slice(-2).join(' ').slice(0, 300); };
+ const mcpOutcome = (out: string) => { outcome = /write_pending|accepted and awaiting completion|"status"\s*:\s*"(pending|accepted)"/.test(out) ? 'pending' : /^ERROR|"error"\s*:/.test(out) ? 'error' : 'ok'; detail = outcome === 'ok' ? '' : out.slice(0, 300); };
+ if (kind === 0) cliOutcome(await gb(CLI, HOME, env, ['put', slug, '--source-id', WRITER_SOURCE, '--content-origin', 'inferred', '--wait', '300', '--content', body], { allowFail: true, timeoutMs: 600_000 }));
+ else if (kind === 1) cliOutcome(await gb(CLI, HOME, env, ['remember', fact, ...(entity ? ['--entity', entity] : []), '--provenance', 'soak writer', '--source-id', WRITER_SOURCE, '--content-origin', 'inferred', '--wait', '300'], { allowFail: true, timeoutMs: 600_000 }));
+ else if (ok && kind === 2) mcpOutcome(await client.call('put_page', { slug, content: body, content_origin: 'inferred' }).catch(e => 'ERROR ' + String(e)));
+ else if (ok) mcpOutcome(await client.call('remember', { fact, ...(entity ? { entity } : {}), provenance: 'soak writer', content_origin: 'inferred' }).catch(e => 'ERROR ' + String(e)));
+ emit('write', { surface: kind < 2 ? 'cli' : 'mcp', op: kind % 2 === 0 ? 'put' : 'remember', ms: Math.round(now() - t0), ok: outcome === 'ok', outcome, err: detail || undefined });
+ i++;
+ const until = now() + CONFIG.write_every_s * 1000;
+ while (live() && now() < until) await sleep(1000);
+ }
+ child.kill();
+}
+
+async function staleLoop(env: Record<string, string>): Promise<void> {
+ while (live()) {
+ for (const args of [['extract', '--stale', '--source-id', WRITER_SOURCE], ['embed', '--stale', '--yes']]) {
+ if (!live()) break;
+ const r = await gb(CLI, HOME, env, args, { allowFail: true, timeoutMs: 3600_000 });
+ emit('maintenance', { op: args.slice(0, 2).join(' '), ms: Math.round(r.ms), code: r.code, tail: (r.stdout + r.stderr).trim().split('\n').slice(-2).join(' | ').slice(0, 300) });
+ }
+ const until = now() + CONFIG.stale_every_s * 1000;
+ while (live() && now() < until) await sleep(2000);
+ }
+}
+
+if (import.meta.main) await main();
diff --git a/scripts/bench/production-soak/ubicloud.sh b/scripts/bench/production-soak/ubicloud.sh
new file mode 100755
index 0000000000..097cf51a80
--- /dev/null
+++ b/scripts/bench/production-soak/ubicloud.sh
@@ -0,0 +1,71 @@
+#!/usr/bin/env bash
+# scripts/bench/production-soak/ubicloud.sh — run the production-shaped soak
+# on ephemeral Ubicloud VMs, one VM per latency, in parallel (GBRA-174).
+#
+# UBI_OWNER=<thread> scripts/bench/production-soak/ubicloud.sh start [--pages 600000] [--hours 3]
+# [--rtts 65,2] [--size standard-16] [--storage 640] [--ttl-hours 14] [--out .context/production-soak]
+# scripts/bench/production-soak/ubicloud.sh status [--out DIR] # last lines of each cell's run log
+# scripts/bench/production-soak/ubicloud.sh collect [--out DIR] # copy each finished cell back, destroy its VM
+#
+# start creates one VM per latency, named with an expiry (--ttl-hours) so the
+# operator reaper destroys it if nobody collects it, syncs this checkout
+# (uncommitted edits included), bootstraps it (vm-setup.sh) and launches
+# run.sh detached on the VM, so the soak does not depend on this machine
+# staying awake. collect copies <out>/rtt<N>/out back for every cell whose run
+# finished, destroys those VMs and writes the combined <out>/scoreboard.json.
+# Check quota first: scripts/ubicloud/ubi-runner.sh usage.
+set -euo pipefail
+cd "$(dirname "$0")/../../.."
+UBI=scripts/ubicloud/ubi-runner.sh
+CMD=${1:-}; shift || true
+PAGES=600000 HOURS=3 RTTS=65,2 SIZE=standard-16 STORAGE=640 TTL=14 OUT=.context/production-soak EXTRA=()
+while [ $# -gt 0 ]; do
+ case $1 in
+ --pages) PAGES=$2; shift 2 ;;
+ --hours) HOURS=$2; shift 2 ;;
+ --rtts) RTTS=$2; shift 2 ;;
+ --size) SIZE=$2; shift 2 ;;
+ --storage) STORAGE=$2; shift 2 ;;
+ --ttl-hours) TTL=$2; shift 2 ;;
+ --out) OUT=$2; shift 2 ;;
+ *) EXTRA+=("$1"); shift ;;
+ esac
+done
+case $CMD in
+ start)
+ [ -n "${UBI_OWNER:-}" ] || { echo "set UBI_OWNER to your thread code" >&2; exit 2; }
+ mkdir -p "$OUT"
+ for rtt in ${RTTS//,/ }; do
+ cell="$OUT/rtt$rtt"; mkdir -p "$cell"
+ name=$($UBI up -s "$SIZE" -S "$STORAGE" --ttl-hours "$TTL")
+ echo "$name" > "$cell/vm"
+ echo "rtt $rtt: $name"
+ $UBI sync "$name" . >/dev/null
+ $UBI ssh "$name" 'cd work/gbrain && bash scripts/bench/production-soak/vm-setup.sh' > "$cell/setup.log" 2>&1
+ $UBI ssh "$name" "cd work/gbrain && setsid -f bash scripts/bench/production-soak/run.sh --pages $PAGES --rtt-ms $rtt --hours $HOURS --out \$HOME/soak/out --label rtt$rtt ${EXTRA[*]:-} > \$HOME/soak-run.log 2>&1 < /dev/null; echo launched"
+ done
+ ;;
+ status)
+ for cell in "$OUT"/rtt*; do
+ [ -f "$cell/vm" ] || continue
+ echo "== $(basename "$cell") ($(cat "$cell/vm"))"
+ $UBI ssh "$(cat "$cell/vm")" 'tail -n 3 ~/soak-run.log' 2>&1 | cut -c1-240 || true
+ done
+ ;;
+ collect)
+ for cell in "$OUT"/rtt*; do
+ [ -f "$cell/vm" ] || continue
+ name=$(cat "$cell/vm")
+ if $UBI ssh "$name" 'grep -q "\[soak-run\] done" ~/soak-run.log'; then
+ $UBI ssh "$name" 'cp ~/soak-run.log ~/soak/out/run.log'
+ $UBI pull "$name" soak/out "$cell"
+ $UBI down "$name" && rm "$cell/vm"
+ echo "$(basename "$cell"): collected"
+ else
+ echo "$(basename "$cell"): still running"
+ fi
+ done
+ bun scripts/bench/production-soak/scoreboard.ts --combine "$OUT" > "$OUT/scoreboard.md" || true
+ ;;
+ *) echo "usage: ubicloud.sh start|status|collect [options] (see the header)" >&2; exit 2 ;;
+esac
diff --git a/scripts/bench/production-soak/vm-setup.sh b/scripts/bench/production-soak/vm-setup.sh
new file mode 100755
index 0000000000..f1f7dd539a
--- /dev/null
+++ b/scripts/bench/production-soak/vm-setup.sh
@@ -0,0 +1,52 @@
+#!/usr/bin/env bash
+# scripts/bench/production-soak/vm-setup.sh — bootstrap one Ubicloud VM (or a
+# GitHub Actions Ubicloud runner) for the production-shaped scale soak
+# (GBRA-174). Runs as a sudo-capable user inside the synced checkout. Installs
+# Docker, bun and frozen dependencies, and pre-pulls the four images the
+# topology uses (lib.ts): pgvector, PgBouncer (pinned by digest) and toxiproxy.
+#
+# scripts/ubicloud/ubi-runner.sh run --setup scripts/bench/production-soak/vm-setup.sh -- 'bash scripts/bench/production-soak/run.sh ...'
+set -euo pipefail
+
+BUN_VERSION="${BUN_VERSION:-1.4.3}"
+t0=$(date +%s)
+step() { echo "[soak-setup +$(( $(date +%s) - t0 ))s] $*"; }
+
+echo force-unsafe-io | sudo tee /etc/dpkg/dpkg.cfg.d/99-gbrain-soak >/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; }
+
+if ! command -v docker >/dev/null; then
+ step "apt"
+ apt_get update
+ apt_get install -y --no-install-recommends docker.io git ca-certificates python3 procps postgresql-client jq unzip curl
+fi
+sudo systemctl start docker 2>/dev/null || true
+sudo chmod 666 /var/run/docker.sock
+
+step "images"
+for image in pgvector/pgvector:pg16 ghcr.io/shopify/toxiproxy:2.12.0 \
+ edoburu/pgbouncer@sha256:9c78945868a6a142c7fc40ccd843bbe5a606df163c7ffce4de70e0d628d696a2; do
+ docker pull -q "$image" >/dev/null &
+done
+
+step "bun ${BUN_VERSION}"
+if ! command -v bun >/dev/null || [ "$(bun --version)" != "$BUN_VERSION" ]; then
+ arch=x64
+ [ "$(uname -m)" = aarch64 ] && arch=aarch64
+ tmp=$(mktemp -d)
+ curl -fsSL --retry 5 --retry-all-errors --retry-delay 1 -o "$tmp/bun.zip" "https://github.com/oven-sh/bun/releases/download/bun-v${BUN_VERSION}/bun-linux-${arch}.zip"
+ python3 -m zipfile -e "$tmp/bun.zip" "$tmp"
+ mkdir -p "$HOME/.bun/bin"
+ install -m 755 "$tmp/bun-linux-${arch}/bun" "$HOME/.bun/bin/bun"
+ rm -rf "$tmp"
+fi
+export PATH="$HOME/.bun/bin:$PATH"
+grep -q '.bun/bin' "$HOME/.profile" 2>/dev/null || echo 'export PATH="$HOME/.bun/bin:$PATH"' >> "$HOME/.profile"
+
+step "dependencies"
+bun scripts/ci-bun-install.ts --frozen-lockfile --ignore-scripts >/dev/null
+git config --global user.name "Brain Writer"
+git config --global user.email [email protected]
+wait
+step "done: $(nproc) cores, $(( $(awk '/MemTotal/ {print $2}' /proc/meminfo) / 1024 )) MB RAM, $(df -h --output=avail / | tail -1) free"
diff --git a/test/bench/production-soak-fixture.test.ts b/test/bench/production-soak-fixture.test.ts
new file mode 100644
index 0000000000..1144daaa69
--- /dev/null
+++ b/test/bench/production-soak-fixture.test.ts
@@ -0,0 +1,76 @@
+import { describe, expect, test } from 'bun:test';
+import { execFileSync } from 'node:child_process';
+import { mkdtempSync, readFileSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { buildFixture, type FixtureOptions } from '../../scripts/bench/production-soak/fixture.ts';
+
+const OPTS: FixtureOptions = { pages: 3000, seed: 11, years: 2, backlogDays: 14, hugeMb: 0.05, oversized: 0 };
+const git = (repo: string, ...args: string[]) => execFileSync('git', ['-C', repo, ...args], { encoding: 'utf8', maxBuffer: 1 << 26 }).trim();
+
+describe('production soak fixture', () => {
+ const a = mkdtempSync(join(tmpdir(), 'soak-fixture-a-'));
+ const b = mkdtempSync(join(tmpdir(), 'soak-fixture-b-'));
+ const ma = buildFixture(OPTS, a) as any;
+ const mb = buildFixture(OPTS, b) as any;
+
+ test('the same seed and size give the same commits and drift', () => {
+ expect(ma.sources.map((s: any) => s.head)).toEqual(mb.sources.map((s: any) => s.head));
+ expect(ma.sources.map((s: any) => s.import_base)).toEqual(mb.sources.map((s: any) => s.import_base));
+ expect(readFileSync(join(a, 'drift.jsonl'), 'utf8')).toBe(readFileSync(join(b, 'drift.jsonl'), 'utf8'));
+ expect(ma.pages).toBe(mb.pages);
+ });
+
+ test('the main source carries years of moves, archive culls, deletes and merged side branches', () => {
+ const main = ma.sources.find((s: any) => s.id === 'default');
+ const repo = main.repo;
+ expect(main.merges).toBeGreaterThan(10);
+ expect(main.moved).toBeGreaterThan(0);
+ expect(main.culled).toBeGreaterThan(0);
+ expect(main.deleted).toBeGreaterThan(0);
+ expect(main.side_deleted).toBeGreaterThan(0);
+ expect(Number(git(repo, 'rev-list', '--count', '--merges', 'final'))).toBe(main.merges);
+ const paths = git(repo, 'ls-tree', '-r', '--name-only', 'final').split('\n');
+ expect(paths.some(p => /^archive\/\d{4}\//.test(p))).toBe(true);
+ expect(paths.some(p => p.startsWith('connectors/'))).toBe(true);
+ expect(paths.some(p => p.startsWith('timelines/'))).toBe(true);
+ const first = git(repo, 'log', '--reverse', '--format=%ad', '--date=short', 'final').split('\n')[0]!;
+ const last = git(repo, 'log', '-1', '--format=%ad', '--date=short', 'final');
+ expect(Number(last.slice(0, 4)) - Number(first.slice(0, 4))).toBeGreaterThanOrEqual(1);
+ });
+
+ test('the backlog after import-base commits the files gbrain must hold', () => {
+ const repo = ma.sources.find((s: any) => s.id === 'default').repo;
+ const backlog = git(repo, 'diff', '--name-only', 'import-base', 'final').split('\n');
+ for (const f of ma.problem_files) expect(backlog).toContain(f.path);
+ expect(new Set(ma.problem_files.map((f: any) => f.expect))).toEqual(new Set(['invalid_frontmatter', 'invalid_fence', 'frontmatter_slug_conflict']));
+ });
+
+ test('private, alias-private and connector pages are present, and every canary is listed as private', () => {
+ const main = ma.sources.find((s: any) => s.id === 'default');
+ expect(main.private.visibility).toBeGreaterThan(0);
+ expect(main.private.access).toBeGreaterThan(0);
+ expect(main.private.confidentiality).toBeGreaterThan(0);
+ expect(main.kinds.connector).toBeGreaterThan(0);
+ const tokens = new Set(JSON.parse(readFileSync(join(a, 'private-tokens.json'), 'utf8')) as string[]);
+ for (const c of ma.privacy.canaries) { expect(tokens.has(c.token)).toBe(true); expect(tokens.has(c.page_token)).toBe(true); }
+ const sample = ma.privacy.canaries[0];
+ const file = git(main.repo, 'show', 'final:' + sample.slug + '.md');
+ expect(file).toContain(sample.token);
+ expect(/^(visibility: private|access: (private|restricted|confidential)|confidentiality: secret)$/m.test(file)).toBe(true);
+ });
+
+ test('the drift holds database-only pages no commit held and kept pages whose files history deleted', () => {
+ const rows = readFileSync(join(a, 'drift.jsonl'), 'utf8').trim().split('\n').map(l => JSON.parse(l));
+ const repo = ma.sources.find((s: any) => s.id === 'default').repo;
+ const dbOnly = rows.filter(r => r.kind === 'db_only'), kept = rows.filter(r => r.kind === 'kept_deleted');
+ expect(dbOnly.length).toBeGreaterThan(0);
+ expect(kept.length).toBeGreaterThan(0);
+ expect(git(repo, 'log', '--all', '--format=%h', '--', dbOnly[0].path)).toBe('');
+ const tip = git(repo, 'ls-tree', '-r', '--name-only', 'final').split('\n');
+ for (const r of kept) { expect(tip).not.toContain(r.path); expect(git(repo, 'log', '--all', '--format=%h', '-1', '--', r.path)).not.toBe(''); }
+ expect(kept.some(r => r.side_branch)).toBe(true);
+ });
+
+ test('cleanup', () => { rmSync(a, { recursive: true, force: true }); rmSync(b, { recursive: true, force: true }); });
+});
diff --git a/test/bench/production-soak-scoreboard.test.ts b/test/bench/production-soak-scoreboard.test.ts
new file mode 100644
index 0000000000..a40155c538
--- /dev/null
+++ b/test/bench/production-soak-scoreboard.test.ts
@@ -0,0 +1,47 @@
+import { describe, expect, test } from 'bun:test';
+import { buildScoreboard, GATES, renderScoreboard, type Ev } from '../../scripts/bench/production-soak/scoreboard.ts';
+
+const start: Ev = { t: 0, kind: 'start', config: { rtt_ms: 65, hours: 1, commit_every_s: 180, label: 'unit' }, version: 'gbrain 0.0.0', gbrain_rev: 'abc' };
+const status = (at_s: number, head: string, last_commit: string, holds: number): Ev => ({ t: at_s * 1000, kind: 'status', at_s, head, last_commit, holds, ms: 100, state: 'resumable', reason: 'pass_unfinished', hold_codes: { file_drift: holds } });
+
+describe('production soak scoreboard', () => {
+ test('every gate is record-only', () => {
+ expect(GATES.every(g => g.mode === 'record')).toBe(true);
+ });
+
+ test('a watermark that stays behind HEAD while holds exist is frozen', () => {
+ const events: Ev[] = [start, status(0, 'h1', 'b0', 3), status(1200, 'h2', 'b0', 5), status(2400, 'h3', 'b0', 5),
+ { t: 1, kind: 'commit', n: 1, problem: true }, { t: 2, kind: 'commit', n: 2, problem: false }, { t: 3, kind: 'freshness_unresolved', n: 2, age_ms: 2_000_000 }];
+ const b = buildScoreboard(events);
+ expect(b.freshness.watermark_stall_max_s).toBe(2400);
+ expect(b.freshness.frozen_by_hold).toBe(true);
+ expect(b.freshness.after_first_hold_commit).toEqual({ commits: 1, resolved: 0 });
+ expect(b.gates.find(g => g.id === 'freshness_not_frozen')!.pass).toBe(false);
+ });
+
+ test('a watermark that keeps up is not frozen, and latencies split by surface and op', () => {
+ const events: Ev[] = [start, status(0, 'h1', 'h1', 2), status(1200, 'h2', 'h2', 2),
+ { t: 1, kind: 'freshness', n: 1, lag_ms: 30_000, first_ms: 20_000 }, { t: 2, kind: 'freshness', n: 2, lag_ms: 90_000, first_ms: 50_000 },
+ ...[100, 200, 300].map((ms, i) => ({ t: 10 + i, kind: 'read', surface: 'mcp', op: 'search', ms, ok: true })),
+ { t: 20, kind: 'read', surface: 'cli', op: 'search', ms: 2500, ok: true }, { t: 21, kind: 'read', surface: 'cli', op: 'search', ms: 9000, ok: false },
+ { t: 30, kind: 'write', surface: 'cli', op: 'put', ms: 4000, ok: false, outcome: 'pending' }];
+ const b = buildScoreboard(events);
+ expect(b.freshness.frozen_by_hold).toBe(false);
+ expect(b.freshness.lag_p50_s).toBe(60);
+ expect((b.reads as any).mcp.search.p50_ms).toBe(200);
+ expect((b.reads as any).cli.search).toMatchObject({ n: 2, errors: 1, p50_ms: 2500 });
+ expect((b.writes as any).put).toMatchObject({ n: 1, errors: 0, pending: 1 });
+ expect(b.writes.error_rate).toBe(0);
+ expect(renderScoreboard(b)).toContain('| freshness_p95 |');
+ });
+
+ test('a canary in a remote response counts as a leak, and pool refusals are read from the end event', () => {
+ const events: Ev[] = [start, { t: 1, kind: 'privacy', op: 'search', class: 'access', leaked: true, tokens: ['zqpvaaaaaaa'] }, { t: 2, kind: 'privacy', op: 'get_page', class: 'visibility', leaked: false },
+ { t: 3, kind: 'privacy_passive', op: 'query', tokens: ['zqpgbbbbbbb'] }, { t: 4, kind: 'sample', session: 26, session_active: 9, txn: 18, backends: 50, mem: {} },
+ { t: 5, kind: 'end', refused: { session: 4, txn: 0 }, log_hits: { 'serve.log': 4 }, elapsed_s: 10 }];
+ const b = buildScoreboard(events);
+ expect(b.privacy).toMatchObject({ probes: 2, leaks: 2, by_class: { access: 1, passive: 1 } });
+ expect(b.pool).toMatchObject({ session_peak: 26, session_refusals: 4 });
+ expect(b.gates.find(g => g.id === 'session_refusals')!.pass).toBe(false);
+ });
+});