Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
bench(managed-sync-catchup): Phase 0 instrumentation for catch-up and put_page
garrytanc53f0dde2b22
diff --git a/docs/eval/managed-sync-catchup.md b/docs/eval/managed-sync-catchup.mdindex 06a374347e..ea8032ad76 100644--- a/docs/eval/managed-sync-catchup.md+++ b/docs/eval/managed-sync-catchup.md@@ -134,7 +134,82 @@ reads `persistence_requests` and `op_checkpoints`.to `now()`, which is the transaction start, so this figure leaves outthe publication transaction itself (about 5 s at 57 ms). Time-boxedrows also report an extrapolation for the full backlog, labelled as- one.+ one. `steady_state` adds the rate between the 10% and 90% committed+ marks, from commit times in the trace (each committed group+ publication counts one commit per member, any process; each committed+ single publication of a sync process counts one, except in rows with a+ foreground writer, where the sync process's consumer also publishes+ `put_page` writes the trace cannot tell apart), and the time from+ the first record of the first sync process to the first commit.+ `steady_state.db` is the same from `persistence_requests.completed_at`,+ with the first commit measured from the row's start.+- **Transaction classification.** The critical path and publication+ tables split each process's records into transactions per+ connection, whichever process or connection runs them. A group+ publication is a transaction with the set-based completion+ (`WITH m AS (SELECT * FROM unnest(...)) ... UPDATE persistence_requests r+ SET state='committed'`), or with a member attribution+ (`set_config('gbrain.write_request',...)`) and an `INSERT INTO pages` /+ `UPDATE pages` (a lane group rolled back before its completion). A+ single publication has the ownership guard, the counter lock and the+ single completion. Admission, recovery record, claim, waiver (a+ checkpoint write under a page guard), and cursor transactions follow.+ The full rules are in `RULES` in `managed-sync-catchup-phases.ts` and+ in each row's JSON.+- **Feeder (`trace.feeder`).** The sync process runs the sync loop and+ its consumer in one process, so its records are split by marker.+ Markers are statements only the sync loop sends: cursor, waiver and+ admission transactions, `op_checkpoints` reads, request lookups by+ `request_id`, the admit-ahead foreground check, and write-wait reads.+ A gap between markers that ends at a write-wait read is idle+ (`awaitWrite`); every other gap is producing. Loose reads in producing+ gaps are freeze and waiver-screen reads. Reads inside a consumer+ preparation span (the k-th claim chain's end to the k-th publication's+ begin) are reported apart as `overlapping_preparation`, because the+ screen and the consumer's preparation run the same helpers. A freeze+ sends one origin read, one page snapshot and one writer check, so the+ freeze/screen split is an estimate on that basis. Waves here are+ counted across connections. Each bucket reports statements, waves and+ describes per entry, per group and per page.+- **Lanes (`trace.lanes`).** Per group publication: apply time (begin+ to the commit-turn poll), turn wait (the trailing run of+ `SELECT state FROM persistence_requests WHERE ... request_id=$3`+ polls), completion, statements per page before the turn, and describes+ per group. Also the time-weighted number of open group publications+ while at least one is open, with its distribution.+- **Describes (`trace.describes`).** Describe round trips per+ connection over the run, by process, and per single publication.+- **Foreground spans (`foreground_*.spans`).** Each `put_page` is matched to+ the writer's transactions: writes in start order take admissions in+ order; a write's publication is the latest unassigned single+ publication before its reply, and its claim and recovery record are+ the latest before that. Spans: pre-admission, admission,+ admission+claim, preparation (claim to publication begin, including+ the recovery record), recovery record, publication, and visible+ (publication end to the reply). p50/p95 per span.+- **Open-loop foreground (`foreground-open`).** `cli` while a second+ process submits one `put_page` every `--fg-interval` seconds+ (default 5) for the whole run, whether or not earlier writes finished.+ `foreground_open` reports the arrival rate, most writes in flight,+ p50/p95, failures by code (`write_pending` included), spans, and the+ catch-up rate during the row. The closed-loop `foreground` row is+ unchanged.+- **Settings (`settings`).** `--pool-size N` sets `GBRAIN_POOL_SIZE`+ for every gbrain process; unset, the product default of 10 applies.+ Each row records the effective pool size and its source,+ `GBRAIN_SYNC_LANES` and `GBRAIN_SYNC_BULK` when set, the pooler, the+ most lanes observed busy, and `default_settings` (true only when+ nothing was overridden).+- **Pooler (`--pooler pgbouncer`, report-only).** A transaction-mode+ PgBouncer (`edoburu/pgbouncer`, pinned by digest, PgBouncer 1.26.0,+ `default_pool_size=50`, recreated each run) runs on loopback between toxiproxy and+ Postgres, so the RTT stays between gbrain and the pooler. gbrain runs+ with `GBRAIN_PREPARE=false`. Stock PgBouncer refuses the+ `statement_timeout` and `idle_in_transaction_session_timeout` startup+ parameters gbrain sends, so the pooler ignores them (listed in the+ row's `settings.pooler_detail.ignore_startup_parameters`): those session timeouts do+ not reach the server. Setup still talks to Postgres directly.+ `--pooler-port` picks the listener (default 55434).## JSON schema (`gbrain.bench.managed-sync-catchup/v1`)diff --git a/scripts/bench/managed-sync-catchup-lib.ts b/scripts/bench/managed-sync-catchup-lib.tsindex 72dc584c00..294cbcf741 100644--- a/scripts/bench/managed-sync-catchup-lib.ts+++ b/scripts/bench/managed-sync-catchup-lib.ts@@ -26,14 +26,24 @@ function docker(args: string[], allowFail = false): string {return (r.stdout ?? '').trim();}-export interface Harness { adminUrl: string; proxyUrl: (db: string) => string; directUrl: (db: string) => string; setRtt: (ms: number) => Promise<void>; stop: () => void }+export interface Harness { adminUrl: string; proxyUrl: (db: string) => string; directUrl: (db: string) => string; setRtt: (ms: number) => Promise<void>; stop: () => void;+ /** The transaction-mode pooler between toxiproxy and Postgres, when one was asked for. */+ pooler: Record<string, unknown> | null }++/** PgBouncer for `--pooler pgbouncer`, pinned by digest (PgBouncer 1.26.0). */+export const PGBOUNCER_IMAGE = 'edoburu/pgbouncer@sha256:9c78945868a6a142c7fc40ccd843bbe5a606df163c7ffce4de70e0d628d696a2';+const PGBOUNCER_POOL = { POOL_MODE: 'transaction', DEFAULT_POOL_SIZE: '50', MAX_CLIENT_CONN: '2000', IGNORE_STARTUP_PARAMETERS: 'extra_float_digits,options,statement_timeout,idle_in_transaction_session_timeout' };/*** Starts (or reuses) `gbrain-bench-pg` (pgvector + pg_stat_statements) and* `gbrain-bench-toxiproxy` (host network, loopback listeners). With an* explicit admin URL only toxiproxy is started, in front of that server.+ * With `poolerPort`, a transaction-mode `gbrain-bench-pgbouncer` (host network,+ * loopback, recreated each run) sits between toxiproxy and Postgres, so the+ * RTT stays on the client side of the pooler. It ignores the session-timeout+ * startup parameters gbrain sends, which stock PgBouncer refuses.*/-export async function startHarness(opts: { pgPort: number; proxyPort: number; apiPort: number; adminUrl?: string; keep: boolean }): Promise<Harness> {+export async function startHarness(opts: { pgPort: number; proxyPort: number; apiPort: number; adminUrl?: string; keep: boolean; poolerPort?: number }): Promise<Harness> {const started: string[] = [];let upstreamHost = '127.0.0.1';let upstreamPort = opts.pgPort;@@ -56,6 +66,26 @@ export async function startHarness(opts: { pgPort: number; proxyPort: number; apdocker(['run', '-d', '--name', 'gbrain-bench-toxiproxy', '--network', 'host', 'ghcr.io/shopify/toxiproxy:2.12.0', '-host', '127.0.0.1', '-port', String(opts.apiPort)]);started.push('gbrain-bench-toxiproxy');}+ let pooler: Harness['pooler'] = null;+ if (opts.poolerPort) {+ const admin = new URL(adminUrl);+ docker(['rm', '-f', 'gbrain-bench-pgbouncer'], true);+ const env = { DB_HOST: upstreamHost, DB_PORT: String(upstreamPort), DB_USER: decodeURIComponent(admin.username), DB_PASSWORD: decodeURIComponent(admin.password),+ AUTH_TYPE: 'scram-sha-256', LISTEN_ADDR: '127.0.0.1', LISTEN_PORT: String(opts.poolerPort), ...PGBOUNCER_POOL };+ docker(['run', '-d', '--name', 'gbrain-bench-pgbouncer', '--network', 'host', ...Object.entries(env).flatMap(([k, v]) => ['-e', `${k}=${v}`]), PGBOUNCER_IMAGE]);+ started.push('gbrain-bench-pgbouncer');+ for (let i = 0; ; i++) {+ try {+ const viaPooler = new URL(adminUrl); viaPooler.hostname = '127.0.0.1'; viaPooler.port = String(opts.poolerPort);+ const probe = postgres(viaPooler.toString(), { max: 1, onnotice: () => {}, connect_timeout: 2, prepare: false });+ await probe`SELECT 1`; await probe.end();+ break;+ } catch (error) { if (i > 60) throw error; }+ await Bun.sleep(1000);+ }+ pooler = { kind: 'pgbouncer', image: PGBOUNCER_IMAGE, listen: `127.0.0.1:${opts.poolerPort}`, ...Object.fromEntries(Object.entries(PGBOUNCER_POOL).map(([k, v]) => [k.toLowerCase(), v])) };+ upstreamHost = '127.0.0.1'; upstreamPort = opts.poolerPort;+ }const api = `http://127.0.0.1:${opts.apiPort}`;for (let i = 0; ; i++) {try {@@ -72,7 +102,7 @@ export async function startHarness(opts: { pgPort: number; proxyPort: number; apconst withDb = (url: string, db: string) => { const u = new URL(url); u.pathname = `/${db}`; return u.toString(); };const proxied = new URL(adminUrl); proxied.hostname = '127.0.0.1'; proxied.port = String(opts.proxyPort);return {- adminUrl,+ adminUrl, pooler,directUrl: db => withDb(adminUrl!, db),proxyUrl: db => withDb(proxied.toString(), db),async setRtt(ms: number) {@@ -91,9 +121,9 @@ export async function startHarness(opts: { pgPort: number; proxyPort: number; ap};}-/** Measures the harness round trip: median of 20 `SELECT 1` through the proxy on one connection. */-export async function measureRtt(url: string): Promise<number> {- const sql = postgres(url, { max: 1, onnotice: () => {} });+/** Measures the harness round trip: median of 20 `SELECT 1` through the proxy on one connection (unprepared behind a transaction-mode pooler). */+export async function measureRtt(url: string, prepare = true): Promise<number> {+ const sql = postgres(url, { max: 1, onnotice: () => {}, prepare });try {await sql`SELECT 1`;const xs: number[] = [];diff --git a/scripts/bench/managed-sync-catchup-phases.ts b/scripts/bench/managed-sync-catchup-phases.tsindex 2e811c5c1e..0197c64851 100644--- a/scripts/bench/managed-sync-catchup-phases.ts+++ b/scripts/bench/managed-sync-catchup-phases.ts@@ -12,13 +12,18 @@ import { classify, family, flatSql, pct, round1, sum, type TraceRecord } from '.export const RULES = {wave: 'A wave is a maximal run of records on one (pid, conn) whose [t, t+ms] intervals overlap; a describe record is always its own wave and the record after it starts a new one. Statements are execute and simple records; describes and connects count only as round trips.',- transaction: 'Records between begin and commit/rollback on one (pid, conn). publication = has the lock_timeout 1s set_config and the counter lock (INSERT INTO persistence_counters(key)); group publication = also has >= 1 member attribution (SELECT set_config(\'gbrain.write_request\',...)); admission = INSERT INTO persistence_requests; claim = UPDATE persistence_requests [r] SET state=\'running\' (head claim and group follower claim are separate occurrences); cursor = INSERT/UPDATE/DELETE op_checkpoints.',+ transaction: 'Records between begin and commit/rollback on one (pid, conn), whichever process or connection runs them. group publication = the set-based completion (WITH m AS (SELECT * FROM unnest(...)) ... UPDATE persistence_requests r SET state=\'committed\'), or >= 1 member attribution (SELECT set_config(\'gbrain.write_request\',...)) with an INSERT INTO pages / UPDATE pages (a lane group rolled back before its completion); single publication = the ownership guard, the counter lock (INSERT INTO persistence_counters(key)) and the single completion (UPDATE persistence_requests SET state=$2,outcome=), or the lock_timeout 1s set_config with the counter lock (older branches); admission = INSERT INTO persistence_requests (also behind the single admission\'s WITH reserved AS (UPDATE persistence_counters ...)); recovery = UPDATE persistence_requests SET recovery= (the recovery record before a file is touched); claim = UPDATE persistence_requests [r] SET state=\'running\' (head claim and group follower claim are separate occurrences); waiver = op_checkpoints write with a page_write_guards lock (a no-op entry waived); cursor = INSERT/UPDATE/DELETE op_checkpoints.',freeze: 'Per admission: sync-process statements outside any phase transaction from the end of the first cursor save after max(previous admission end, last publication commit) up to the admission begin; waits and consumer background excluded. Wall excludes the cursor saves nested in the window.',prepare: 'Per publication: statements outside any phase transaction between the end of the last claim since the previous publication and the publication begin (waits and consumer background excluded).',wait: 'Per admission: WRITE_PROGRESS_SQL and SELECT * FROM persistence_requests WHERE id=$1::uuid / id=ANY($1::uuid[]) reads from the admission commit to the next cursor save (or admission). Its wall overlaps claim, prepare and publication.',commit_gap: 'Between consecutive committed group publications of one sync process (all publications when it published no group): wall, and every record the process sent in between. Single publications include foreground writes the sync process\'s consumer published.',member_chain: 'Members are split at their attribution statements (with its describe, if any): segment i runs from member i\'s attribution to member i+1\'s, so it holds member i\'s apply/effects tail and member i+1\'s authorize/snapshot/validate lead. The rotation leaves the steady per-member total unchanged. Steady = segments 2..n-1 of transactions with >= 3 members; segment 1 carries first-use describes, the last one runs into the counter lock and is part of the fixed cost.',counter_hold: 'From the counter row lock (SELECT * FROM persistence_counters ... FOR UPDATE, with its describe) to the commit, inclusive. INSERT INTO persistence_counters(key) ... ON CONFLICT DO NOTHING creates missing rows and locks no existing one, so it is outside the hold.',+ chain_wave: 'Feeder round-trip waves are counted across connections: one wave is a maximal run of the bucket\'s records whose [t, t+ms] intervals overlap on any connection of the process, so four freezes in flight at once are one wave and a chain of reads hopping connections is one wave per read.',+ feeder: 'Sync process only. Feeder markers are statements only the sync loop sends: cursor and waiver transactions, admission transactions, op_checkpoints reads, request lookups by request_id (SELECT * / count(*)), the admit-ahead foreground check, and write-wait reads (WRITE_PROGRESS_SQL, id=$1, the group state read id=ANY). A gap between consecutive markers that ends at a write-wait read is idle (awaitWrite); every other gap is producing. A single entry\'s wait (admission, then the cursor save, no state read) counts as producing. Loose statements in producing gaps that are not consumer work (consumer background, claim attempts, claim renewals, the group recovery check) are freeze and waiver-screen reads; those inside a consumer preparation span (k-th claim chain end to the k-th publication begin; a chain is a head claim and its follower claim) are reported apart as overlapping, because the screen and the consumer\'s preparation run the same helpers. Freeze vs screen: each freeze issues one origin read (pages ... source_path=ANY), one page snapshot and one writer check, so per origin read one snapshot and one writer check are freeze; every other read is screen (an estimate). Entries frozen = origin reads outside preparation spans.',+ lane: 'Per group publication transaction: the turn wait is the last run of lane-turn polls (SELECT state FROM persistence_requests WHERE ... request_id=$3, describes included) after which no member attribution or page write follows (member validation sends the same read earlier); apply = begin to the first poll of that run, turn wait = its first poll to the end of its last, completion = the rest to commit. A group with no predecessor polls nothing (apply = whole transaction). Lanes busy = open group publication transactions per process, time-weighted over the time at least one is open.',+ foreground_spans: 'Per put_page, from the foreground process\'s transactions: writes in start order take the admission transactions in order (the first unassigned one starting in the write\'s [t-ms, t] window); a write\'s publication is the latest unassigned single publication between its admission end and its reply, its claim the latest unassigned claim before that publication, its recovery record the latest recovery transaction between the two. pre-admission = start to the admission begin; admission = the admission transaction; admission+claim = admission begin to the claim end; preparation = claim end to the publication begin (includes the recovery record); recovery = the recovery-record transaction; publication = the single publication transaction; visible = publication end to the reply, or admission end to the reply for a write another process published or that was still pending at its reply. Concurrent writes (open loop) are matched the same way.',+ steady_rate: 'Commit times: the end of each committed group publication (one commit per member, any process) and each committed single publication of a sync process when the trace has no foreground writer (the sync process\'s consumer also publishes foreground put_pages, which the trace cannot tell apart; persistence_requests.completed_at is exact). Pages/min between the commit that reaches 10% of the committed pages and the one that reaches 90%; first commit is measured from the first record of the first sync process.',};const SIG = {@@ -26,11 +31,26 @@ const SIG = {counterLock: /^INSERT INTO persistence_counters\(key\)/,counterRowLock: /^SELECT \* FROM persistence_counters WHERE key=ANY\(.*FOR UPDATE$/,attribution: /^SELECT set_config\('gbrain\.write_request',/,- admission: /^INSERT INTO persistence_requests\b/,+ admission: /^(?:WITH reserved AS \(UPDATE persistence_counters .*?\) )?INSERT INTO persistence_requests\b/,claim: /^UPDATE persistence_requests (?:r )?SET state='running'/,claimAttempt: /^SELECT r\.\* FROM persistence_requests r LEFT JOIN persistence_worktrees w/,cursor: /^(?:INSERT INTO|UPDATE|DELETE FROM) op_checkpoints\b/,wait: /^SELECT (?:\*|state,error_code,error_message,completed_at,updated_at,blocked_reason,outcome) FROM persistence_requests WHERE id=(?:\$1::uuid|ANY\(\$1::uuid\[\]\))$/,+ groupCompletion: /^WITH m AS \( SELECT \* FROM unnest\(.*\bUPDATE persistence_requests r SET state='committed'/,+ singleCompletion: /\bUPDATE persistence_requests SET state=\$2,outcome=/,+ ownershipGuard: /^SELECT owner_host_id,owner_epoch,state FROM persistence_worktrees WHERE id=\$1::uuid FOR SHARE$/,+ pageWrite: /^(?:INSERT INTO pages\b|UPDATE pages\b)/,+ recovery: /^WITH recorded AS \(UPDATE persistence_requests (?:r )?SET recovery=/,+ guard: /\bpage_write_guards\b/,+ laneTurn: /^SELECT state FROM persistence_requests WHERE principal_kind=\$1 AND principal_id=\$2 AND request_id=\$3::uuid$/,+ headClaim: /^UPDATE persistence_requests SET state='running'/,+ checkpointRead: /^SELECT\b.*\bFROM op_checkpoints\b/,+ requestLookup: /^SELECT (?:\*|count\(\*\)::int AS n) FROM persistence_requests WHERE principal_kind=\$1 AND principal_id=\$2 AND request_id=(?:\$3::uuid|ANY\(\$3::uuid\[\]\))$/,+ foregroundCheck: /^SELECT id FROM persistence_requests WHERE worktree_id=\$1::uuid AND state IN \('queued','running','recovering'\) AND NOT\(COALESCE\(intent->>'kind',''\) LIKE 'managed_sync_%'\)/,+ consumerOnly: /^UPDATE persistence_requests r SET claim_expires_at=|^SELECT 1 FROM persistence_requests WHERE worktree_id=\$1::uuid AND NOT \(id=ANY/,+ origin: /^SELECT id,slug,source_path FROM pages WHERE source_id=\$1 AND source_path=ANY\(/,+ snapshot: /^WITH chosen AS \( SELECT p\.\* FROM pages p WHERE p\.slug=\$1/,+ writerCheck: /^SELECT lane,revoked_at,grant_ceiling FROM persistence_local_writers WHERE id=\$1::uuid$/,};const BEGIN = /^(?:begin|start transaction)\b/i;const END = /^(?:commit|end)\b|^rollback(?!\s+to\b)/i;@@ -71,17 +91,16 @@ export function cost(records: TraceRecord[]): Cost {return { statements: records.filter(isStatement).length, waves: waves(records).count, describes: records.filter(r => r.kind === 'describe').length };}-export type TxnType = 'publication' | 'admission' | 'claim' | 'claim-attempt' | 'cursor' | 'other';-export interface Txn { pid: number; label: string; records: TraceRecord[]; start: number; end: number; type: TxnType; committed: boolean; members: number }--function txnType(records: TraceRecord[]): TxnType {- const has = (re: RegExp) => records.some(r => re.test(flatSql(r.sql)));- if (has(SIG.lock1s) && has(SIG.counterLock)) return 'publication';- if (has(SIG.admission)) return 'admission';- if (has(SIG.claim)) return 'claim';- if (has(SIG.cursor)) return 'cursor';- if (has(SIG.claimAttempt)) return 'claim-attempt';- return 'other';+export type TxnType = 'publication' | 'admission' | 'recovery' | 'claim' | 'claim-attempt' | 'waiver' | 'cursor' | 'other';+export interface Txn { pid: number; label: string; records: TraceRecord[]; start: number; end: number; type: TxnType; committed: boolean; members: number; group: boolean }++function txnType(records: TraceRecord[], members: number): { type: TxnType; group: boolean } {+ const has = (re: RegExp) => records.some(r => isStatement(r) && re.test(flatSql(r.sql)));+ if (has(SIG.groupCompletion) || (members > 0 && has(SIG.pageWrite))) return { type: 'publication', group: true };+ if ((has(SIG.ownershipGuard) && has(SIG.counterLock) && has(SIG.singleCompletion)) || (has(SIG.lock1s) && has(SIG.counterLock))) return { type: 'publication', group: members > 0 };+ const type: TxnType = has(SIG.admission) ? 'admission' : has(SIG.recovery) ? 'recovery' : has(SIG.claim) ? 'claim'+ : has(SIG.cursor) ? (has(SIG.guard) ? 'waiver' : 'cursor') : has(SIG.claimAttempt) ? 'claim-attempt' : 'other';+ return { type, group: false };}/** Transactions per (pid, conn), and the records outside any transaction. */@@ -90,8 +109,8 @@ export function transactions(records: TraceRecord[]): { txns: Txn[]; loose: Tracconst loose: TraceRecord[] = [];const close = (rs: TraceRecord[], committed: boolean) => {const last = rs.at(-1)!;- txns.push({ pid: rs[0]!.pid, label: rs[0]!.label, records: rs, start: rs[0]!.t, end: end(last), type: txnType(rs), committed,- members: rs.filter(r => isStatement(r) && SIG.attribution.test(flatSql(r.sql))).length });+ const members = rs.filter(r => isStatement(r) && SIG.attribution.test(flatSql(r.sql))).length;+ txns.push({ pid: rs[0]!.pid, label: rs[0]!.label, records: rs, start: rs[0]!.t, end: end(last), ...txnType(rs, members), committed, members });};for (const rs of groupBy(records, r => `${r.pid}:${r.conn}`).values()) {rs.sort(byStart);@@ -134,20 +153,20 @@ function phaseRow(phase: string, occ: Occurrence[], pages: number | null, concur*/export function publishedPages(records: TraceRecord[]): number {const pubs = [...groupBy(records, r => r.pid).values()].flatMap(rs => transactions(rs).txns.filter(t => t.type === 'publication' && t.committed));- return sum(pubs.map(t => t.members)) || pubs.filter(t => family(t.label) !== 'foreground').length;+ return sum(pubs.filter(t => t.group).map(t => Math.max(1, t.members))) || pubs.filter(t => family(t.label) !== 'foreground').length;}/** Per-phase critical path of the sync processes (`cli-sync`, `reentry`); RULES describes each phase. */export function criticalPath(records: TraceRecord[], pages: number | null): Record<string, unknown> {- const occ: Record<string, Occurrence[]> = { 'publication (group)': [], 'publication (single)': [], freeze: [], admission: [], cursor: [], claim: [], prepare: [], wait: [], commit_gap: [], background: [] };+ const occ: Record<string, Occurrence[]> = { 'publication (group)': [], 'publication (single)': [], freeze: [], admission: [], cursor: [], waiver: [], recovery: [], claim: [], prepare: [], wait: [], commit_gap: [], background: [] };const sync = records.filter(r => SYNC_FAMILIES.has(family(r.label)));for (const rs of groupBy(sync, r => r.pid).values()) {rs.sort(byStart);const { txns, loose } = transactions(rs);const of = (type: TxnType) => txns.filter(t => t.type === type);const pubs = of('publication'), adms = of('admission'), claims = of('claim'), cursors = of('cursor');- const groups = pubs.filter(p => p.members > 0);- for (const [phase, list] of [['publication (group)', groups], ['publication (single)', pubs.filter(p => !p.members)], ['admission', adms], ['claim', claims], ['cursor', cursors]] as const) {+ const groups = pubs.filter(p => p.group);+ for (const [phase, list] of [['publication (group)', groups], ['publication (single)', pubs.filter(p => !p.group)], ['admission', adms], ['claim', claims], ['cursor', cursors], ['waiver', of('waiver')], ['recovery', of('recovery')]] as const) {occ[phase]!.push(...list.map(t => ({ wall: t.end - t.start, records: t.records })));}const waits = loose.filter(is(SIG.wait));@@ -210,15 +229,15 @@ function analyzeGroup(t: Txn): GroupTxn {});const stop = lockAt < 0 ? rs.length : lockAt;const segments = bounds.map((b, i) => cost(rs.slice(b, i + 1 < bounds.length ? bounds[i + 1] : stop)));- return { process: family(t.label), members: t.members, ...cost(rs), wall_ms: round1(t.end - t.start), committed: t.committed, hold, segments, prefix: cost(rs.slice(0, bounds[0] ?? 0)) };+ return { process: family(t.label), members: Math.max(1, t.members), ...cost(rs), wall_ms: round1(t.end - t.start), committed: t.committed, hold, segments, prefix: cost(rs.slice(0, bounds[0] ?? 0)) };}/** Group publication breakdown (all processes): fixed vs per-member cost, steady member chain, completion and counter hold. */export function publicationBreakdown(records: TraceRecord[]): Record<string, unknown> {const pubs = [...groupBy(records, r => r.pid).values()].flatMap(rs => transactions(rs).txns.filter(t => t.type === 'publication'));- const groups = pubs.filter(t => t.members > 0).map(analyzeGroup);+ const groups = pubs.filter(t => t.group).map(analyzeGroup);const ok = groups.filter(g => g.committed);- const singles = pubs.filter(t => t.members === 0 && t.committed).map(t => ({ ...cost(t.records), wall: t.end - t.start }));+ const singles = pubs.filter(t => !t.group && t.committed).map(t => ({ ...cost(t.records), wall: t.end - t.start }));const xs = ok.map(g => g.members);const steady = ok.filter(g => g.members >= 3).flatMap(g => g.segments.slice(1, -1));const first = ok.filter(g => g.members >= 2).map(g => g.segments[0]!);@@ -251,6 +270,231 @@ export function publicationBreakdown(records: TraceRecord[]): Record<string, unk};}+/** Waves across connections (RULES.chain_wave) and the summed span of their merged intervals. */+export function chainWaves(records: TraceRecord[]): { count: number; spanMs: number } {+ const rs = [...records].sort(byStart);+ let count = 0, spanMs = 0, start = 0, stop = -Infinity;+ for (const r of rs) {+ if (r.t >= stop - WAVE_EPS_MS) { if (count) spanMs += stop - start; count++; start = r.t; stop = end(r); } else stop = Math.max(stop, end(r));+ }+ if (count) spanMs += stop - start;+ return { count, spanMs };+}++interface Span { start: number; end: number }+const within = (t: number, spans: Span[]) => spans.some(s => t >= s.start && t < s.end);++/** Consumer preparation spans of one process: the k-th claim chain (head claim + follower claim) ends, the k-th publication begins. */+function preparationSpans(txns: Txn[]): Span[] {+ const chains: Array<{ end: number; follower: boolean }> = [];+ for (const t of txns.filter(x => x.type === 'claim')) {+ const head = t.records.some(r => isStatement(r) && SIG.headClaim.test(flatSql(r.sql)));+ const open = chains.at(-1);+ if (!head && open && !open.follower) { open.end = t.end; open.follower = true; } else chains.push({ end: t.end, follower: !head });+ }+ const spans: Span[] = [];+ let k = 0;+ for (const p of txns.filter(x => x.type === 'publication')) {+ while (k < chains.length && chains[k]!.end > p.start) k++;+ if (k >= chains.length) break;+ spans.push({ start: chains[k]!.end, end: p.start });+ k++;+ }+ return spans;+}++interface Bucket { statements: number; waves: number; describes: number; ms: number | null }+function bucket(records: TraceRecord[], ms: number | undefined): Bucket {+ return { statements: records.filter(isStatement).length, waves: chainWaves(records).count, describes: records.filter(r => r.kind === 'describe').length, ms: ms === undefined ? null : round1(ms) };+}+const per = (b: Bucket, n: number | null) => n ? { statements: round1(b.statements / n), waves: round1(b.waves / n), ms: b.ms === null ? null : round1(b.ms / n) } : null;++/** Feeder (sync loop) breakdown of the sync processes: idle vs producing time and per-bucket cost per entry, group and page (RULES.feeder). */+export function feederBreakdown(records: TraceRecord[], pages: number | null): Record<string, unknown> {+ const sync = records.filter(r => SYNC_FAMILIES.has(family(r.label)));+ const acc: Record<string, TraceRecord[]> = { freeze: [], waiver_screen: [], waiver: [], cursor: [], admission: [], wait: [], overlapping_preparation: [] };+ const ms: Record<string, number> = { idle: 0, producing_gaps: 0, wall: 0, waiver: 0, cursor: 0, admission: 0, wait: 0 };+ let groups = 0, entries = 0;+ for (const rs of groupBy(sync, r => r.pid).values()) {+ rs.sort(byStart);+ const { txns, loose } = transactions(rs);+ ms.wall! += end(rs.reduce((a, b) => end(a) > end(b) ? a : b)) - rs[0]!.t;+ const prep = preparationSpans(txns);+ type Marker = { start: number; end: number; kind: string; records: TraceRecord[] };+ const markers: Marker[] = [];+ for (const t of txns) {+ if (t.type === 'cursor' || t.type === 'waiver' || t.type === 'admission') markers.push({ start: t.start, end: t.end, kind: t.type, records: t.records });+ if (t.type === 'admission') groups++;+ }+ const candidates: TraceRecord[] = [];+ for (const r of loose) {+ const s = flatSql(r.sql);+ const kind = SIG.wait.test(s) ? 'wait' : SIG.checkpointRead.test(s) ? 'cursor' : SIG.requestLookup.test(s) || SIG.foregroundCheck.test(s) ? 'admission' : null;+ if (kind) markers.push({ start: r.t, end: end(r), kind, records: [r] });+ else if (r.kind !== 'connect' && classify(r.sql) !== 'consumer-background' && !SIG.consumerOnly.test(s)) candidates.push(r);+ }+ for (const t of txns) if (t.type === 'other' && !t.records.some(r => classify(r.sql) === 'consumer-background')) candidates.push(...t.records);+ markers.sort((a, b) => a.start - b.start);+ const producing: Span[] = [];+ for (const [i, m] of markers.entries()) {+ acc[m.kind]!.push(...m.records);+ ms[m.kind]! += m.end - m.start;+ const next = markers[i + 1];+ if (!next || next.start <= m.end) continue;+ if (next.kind === 'wait') ms.idle! += next.start - m.end;+ else { ms.producing_gaps! += next.start - m.end; producing.push({ start: m.end, end: next.start }); }+ }+ const reads = candidates.filter(r => within(r.t, producing));+ const own = reads.filter(r => !within(r.t, prep));+ acc.overlapping_preparation!.push(...reads.filter(r => within(r.t, prep)));+ const origins = own.filter(r => isStatement(r) && SIG.origin.test(flatSql(r.sql))).length;+ entries += origins;+ let snapshots = origins, writers = origins;+ for (const r of own.sort(byStart)) {+ const s = flatSql(r.sql);+ const freeze = SIG.origin.test(s) || (SIG.snapshot.test(s) && (r.kind === 'describe' || snapshots-- > 0)) || (SIG.writerCheck.test(s) && (r.kind === 'describe' || writers-- > 0));+ acc[freeze ? 'freeze' : 'waiver_screen']!.push(r);+ }+ }+ const b = Object.fromEntries(Object.entries(acc).map(([k, rs]) => [k, bucket(rs, ms[k])])) as Record<string, Bucket>;+ const top = groupBy([...acc.freeze!, ...acc.waiver_screen!].filter(isStatement), r => flatSql(r.sql).slice(0, 120));+ const producing = ms.wall! - ms.idle!;+ return {+ processes: new Set(sync.map(r => r.pid)).size, groups_admitted: groups, entries_frozen_est: entries, pages,+ time_ms: { wall: round1(ms.wall!), idle_await_write: round1(ms.idle!), producing: round1(producing), producing_gaps: round1(ms.producing_gaps!),+ cursor: round1(ms.cursor!), admission: round1(ms.admission!), waiver: round1(ms.waiver!), wait_reads: round1(ms.wait!),+ idle_share_pct: ms.wall ? round1(100 * ms.idle! / ms.wall!) : null },+ buckets: Object.fromEntries(Object.entries(b).map(([k, v]) => [k, { ...v, per_entry: per(v, entries), per_group: per(v, groups), per_page: per(v, pages) }])),+ top_freeze_screen_statements: [...top.entries()].map(([sql, rs]) => ({ sql, count: rs.length, per_entry: entries ? round1(rs.length / entries) : null }))+ .sort((x, y) => y.count - x.count).slice(0, 15),+ rules: { feeder: RULES.feeder, chain_wave: RULES.chain_wave },+ };+}++/** Lane group apply vs commit-turn wait per group publication transaction, and how many lanes are busy at once (RULES.lane). */+export function laneApply(records: TraceRecord[]): Record<string, unknown> {+ const rows: Array<{ members: number; apply: number; turn: number | null; polls: number; completion: number; statements_per_page: number; describes: number; committed: boolean }> = [];+ const dist = new Map<number, number>();+ let busyMs = 0, weighted = 0, maxBusy = 0;+ for (const rs of groupBy(records, r => r.pid).values()) {+ const groups = transactions(rs).txns.filter(t => t.type === 'publication' && t.group);+ for (const t of groups) {+ const recs = t.records;+ const turn = (r: TraceRecord) => SIG.laneTurn.test(flatSql(r.sql));+ let last = recs.findLastIndex(turn);+ if (recs.slice(last + 1).some(r => isStatement(r) && (SIG.attribution.test(flatSql(r.sql)) || SIG.pageWrite.test(flatSql(r.sql))))) last = -1;+ let at = last;+ while (at > 0 && turn(recs[at - 1]!)) at--;+ const applyEnd = at >= 0 ? recs[at]!.t : t.end;+ const members = Math.max(1, t.members);+ rows.push({ members, apply: applyEnd - t.start, turn: at >= 0 ? end(recs[last]!) - recs[at]!.t : null, polls: at >= 0 ? recs.slice(at, last + 1).filter(isStatement).length : 0,+ completion: at >= 0 ? t.end - end(recs[last]!) : 0, statements_per_page: (at >= 0 ? recs.slice(0, at) : recs).filter(isStatement).length / members,+ describes: recs.filter(r => r.kind === 'describe').length, committed: t.committed });+ }+ const events = groups.flatMap(t => [{ t: t.start, d: 1 }, { t: t.end, d: -1 }]).sort((a, b) => a.t - b.t || a.d - b.d);+ let open = 0, prev = 0;+ for (const e of events) {+ if (open > 0) { const dt = e.t - prev; busyMs += dt; weighted += open * dt; dist.set(open, (dist.get(open) ?? 0) + dt); }+ open += e.d; prev = e.t; maxBusy = Math.max(maxBusy, open);+ }+ }+ const p = (xs: number[]) => ({ p50: pct(xs, 50), p95: pct(xs, 95) });+ const turns = rows.flatMap(r => r.turn === null ? [] : [r.turn]);+ return {+ group_txns: rows.length, committed: rows.filter(r => r.committed).length, with_turn_wait: turns.length,+ apply_ms: p(rows.map(r => r.apply)), turn_wait_ms: { ...p(turns), total: round1(sum(turns)) }, turn_polls_p50: pct(rows.filter(r => r.turn !== null).map(r => r.polls), 50),+ completion_ms: p(rows.map(r => r.completion)), apply_statements_per_page: p(rows.map(r => r.statements_per_page)),+ describes_per_group: { ...p(rows.map(r => r.describes)), mean: mean(rows.map(r => r.describes)) },+ lanes_busy: { mean: busyMs ? Math.round(100 * weighted / busyMs) / 100 : null, max: maxBusy, busy_ms: round1(busyMs),+ distribution_pct: Object.fromEntries([...dist.entries()].sort((a, b) => a[0] - b[0]).map(([k, v]) => [k, round1(100 * v / busyMs)])) },+ rules: { lane: RULES.lane },+ };+}++/** Describe round trips per connection over the run, and per single (put_page-sized) publication transaction, by process family. */+export function describeRoundTrips(records: TraceRecord[]): Record<string, unknown> {+ const conns = [...groupBy(records, r => `${r.pid}:${r.conn}`).values()].map(rs => ({ family: family(rs[0]!.label), describes: rs.filter(r => r.kind === 'describe').length }));+ const singles = [...groupBy(records, r => r.pid).values()].flatMap(rs => transactions(rs).txns.filter(t => t.type === 'publication' && !t.group));+ const byFamily = (xs: Array<{ family: string; describes: number }>) => Object.fromEntries([...groupBy(xs, x => x.family).entries()].map(([f, list]) => [f, {+ n: list.length, describes: sum(list.map(x => x.describes)), mean: mean(list.map(x => x.describes)), p50: pct(list.map(x => x.describes), 50), max: pct(list.map(x => x.describes), 100) }]));+ return { connections: conns.length, describes: sum(conns.map(c => c.describes)), per_connection: { p50: pct(conns.map(c => c.describes), 50), p95: pct(conns.map(c => c.describes), 95), max: pct(conns.map(c => c.describes), 100) },+ per_connection_by_process: byFamily(conns),+ per_single_publication_by_process: byFamily(singles.map(t => ({ family: family(t.label), describes: t.records.filter(r => r.kind === 'describe').length }))) };+}++/** Per-put_page span timeline from the foreground process's records (RULES.foreground_spans); p50/p95 per span. */+export function foregroundSpans(records: TraceRecord[], writes: Array<{ t: number; ms: number }>): Record<string, unknown> {+ const fg = records.filter(r => family(r.label) === 'foreground');+ const txns = [...groupBy(fg, r => r.pid).values()].flatMap(rs => transactions(rs).txns).sort((x, y) => x.start - y.start);+ const of = (type: TxnType) => txns.filter(t => t.type === type && !t.group);+ const admissions = of('admission'), claims = of('claim'), recoveries = of('recovery'), pubs = of('publication');+ const used = new Set<Txn>();+ const latest = (list: Txn[], from: number, to: number) => list.filter(t => !used.has(t) && t.start >= from && t.end <= to).at(-1);+ const ordered = writes.map(w => ({ from: w.t - w.ms, to: w.t })).sort((x, y) => x.from - y.from);+ let overlapping = 0;+ for (let i = 1; i < ordered.length; i++) if (ordered[i - 1]!.to > ordered[i]!.from) overlapping++;+ const spans: Record<string, number[]> = { pre_admission: [], admission: [], admission_claim: [], preparation: [], recovery: [], publication: [], visible: [], total: [] };+ const describes: number[] = [];+ let here = 0, elsewhere = 0, unmatched = 0, k = 0;+ const matched = ordered.map(w => {+ while (k < admissions.length && admissions[k]!.start < w.from) k++;+ const adm = k < admissions.length && admissions[k]!.start < w.to ? admissions[k++]! : null;+ if (adm) used.add(adm);+ return { w, adm };+ });+ for (const { w, adm } of [...matched].sort((x, y) => x.w.to - y.w.to)) {+ if (!adm) { unmatched++; continue; }+ spans.pre_admission!.push(adm.start - w.from);+ spans.admission!.push(adm.end - adm.start);+ spans.total!.push(w.to - w.from);+ const pub = latest(pubs, adm.end, w.to);+ const claim = pub ? latest(claims, adm.end, pub.start) : undefined;+ if (!pub || !claim) { elsewhere++; spans.visible!.push(w.to - adm.end); continue; }+ here++;+ used.add(pub); used.add(claim);+ const rec = latest(recoveries, claim.end, pub.start);+ if (rec) { used.add(rec); spans.recovery!.push(rec.end - rec.start); }+ spans.admission_claim!.push(claim.end - adm.start);+ spans.preparation!.push(pub.start - claim.end);+ spans.publication!.push(pub.end - pub.start);+ spans.visible!.push(w.to - pub.end);+ describes.push(pub.records.filter(r => r.kind === 'describe').length);+ }+ return { writes: writes.length, overlapping, unmatched, published_here: here, published_elsewhere_or_pending: elsewhere,+ publication_describes: { p50: pct(describes, 50), p95: pct(describes, 95), mean: mean(describes) },+ spans_ms: Object.fromEntries(Object.entries(spans).map(([key, xs]) => [key, { n: xs.length, p50: pct(xs, 50), p95: pct(xs, 95) }])),+ rules: { foreground_spans: RULES.foreground_spans } };+}++/** Commit times of published pages in a trace (RULES.steady_rate), sorted. */+export function commitTimes(records: TraceRecord[]): number[] {+ const out: number[] = [];+ const foreground = records.some(r => family(r.label) === 'foreground');+ for (const rs of groupBy(records, r => r.pid).values()) for (const t of transactions(rs).txns) {+ if (t.type !== 'publication' || !t.committed) continue;+ if (t.group) for (let i = 0; i < Math.max(1, t.members); i++) out.push(t.end);+ else if (!foreground && SYNC_FAMILIES.has(family(t.label))) out.push(t.end);+ }+ return out.sort((a, b) => a - b);+}++/** Steady-state pages/min between the 10% and 90% committed marks, and the time from `start` to the first commit. */+export function steadyRate(times: number[], start: number | null): Record<string, number | null> {+ const n = times.length;+ const first = start === null || !n ? null : round1(times[0]! - start);+ if (n < 2) return { committed: n, pages_per_min_10_90: null, window_s: null, first_commit_ms: first };+ const i10 = Math.max(0, Math.ceil(0.1 * n) - 1), i90 = Math.max(0, Math.ceil(0.9 * n) - 1);+ const dt = times[i90]! - times[i10]!;+ return { committed: n, pages_per_min_10_90: dt > 0 ? round1((i90 - i10) / (dt / 60_000)) : null, window_s: round1(dt / 1000), first_commit_ms: first };+}++/** First record of the first sync process: the start the steady-state rate's first commit is measured from. */+export function syncStart(records: TraceRecord[]): number | null {+ let t: number | null = null;+ for (const r of records) if (SYNC_FAMILIES.has(family(r.label)) && (t === null || r.t < t)) t = r.t;+ return t;+}+/*** Per put_page: the foreground process's admission, claim and single* publication transactions inside the write's window, and every record it sent@@ -261,7 +505,7 @@ export function publicationBreakdown(records: TraceRecord[]): Record<string, unkexport function foregroundRoundTrips(records: TraceRecord[], writes: Array<{ t: number; ms: number }>): Record<string, unknown> {const fg = records.filter(r => family(r.label) === 'foreground').sort(byStart);const txns = [...groupBy(fg, r => r.pid).values()].flatMap(rs => transactions(rs).txns)- .filter(t => t.type === 'admission' || t.type === 'claim' || (t.type === 'publication' && t.members === 0));+ .filter(t => t.type === 'admission' || t.type === 'claim' || (t.type === 'publication' && !t.group));const per = writes.map(w => {const from = w.t - w.ms;const own = txns.filter(t => t.start >= from && t.start < w.t);@@ -308,3 +552,40 @@ export function renderAnalysis(cp: Record<string, unknown>, pub: Record<string,]));return out.join('\n');}++/** Markdown tables for the Phase 0 fields: feeder, lanes, describes, steady-state rate and foreground spans. */+export function renderPhase0(fields: { feeder?: Record<string, unknown>; lanes?: Record<string, unknown>; describes?: Record<string, unknown>; steady?: Record<string, unknown>; spans?: Record<string, Record<string, unknown>> }): string {+ const out: string[] = [];+ const f = fields.feeder;+ if (f) {+ const time = f.time_ms as Record<string, number | null>;+ const buckets = f.buckets as Record<string, Bucket & { per_entry: Record<string, number | null> | null; per_group: Record<string, number | null> | null; per_page: Record<string, number | null> | null }>;+ const w = (x: Record<string, number | null> | null) => x ? `${cell(x.statements)} / ${cell(x.waves)}` : '—';+ out.push(`\nFeeder (sync loop): ${cell(f.groups_admitted)} groups, ~${cell(f.entries_frozen_est)} entries frozen, ${cell(f.pages)} pages; wall ${cell(time.wall)} ms, idle in awaitWrite ${cell(time.idle_await_write)} ms (${cell(time.idle_share_pct)}%), producing ${cell(time.producing)} ms`,+ table(['bucket', 'stmts', 'waves', 'describes', 'ms', 'per entry (stmts / waves)', 'per group', 'per page'],+ Object.entries(buckets).map(([k, b]) => [k, b.statements, b.waves, b.describes, b.ms, w(b.per_entry), w(b.per_group), w(b.per_page)])));+ }+ const l = fields.lanes;+ if (l && l.group_txns) {+ const q = (x: unknown) => { const v = x as Record<string, number | null>; return `${cell(v.p50)} / ${cell(v.p95)}`; };+ const busy = l.lanes_busy as Record<string, unknown>;+ out.push(`\nLane group transactions (${cell(l.group_txns)}, ${cell(l.with_turn_wait)} waited for their turn; lanes busy mean ${cell(busy.mean)}, max ${cell(busy.max)}, distribution % ${JSON.stringify(busy.distribution_pct)})`,+ table(['measure', 'p50 / p95'], [['apply ms', q(l.apply_ms)], ['turn wait ms', `${q(l.turn_wait_ms)} (total ${cell((l.turn_wait_ms as Record<string, number>).total)})`],+ ['completion ms', q(l.completion_ms)], ['apply statements per page', q(l.apply_statements_per_page)], ['describes per group', q(l.describes_per_group)]]));+ }+ const d = fields.describes;+ if (d) {+ const pc = d.per_connection as Record<string, number | null>;+ const sp = d.per_single_publication_by_process as Record<string, Record<string, number | null>>;+ out.push(`\nDescribe round trips: ${cell(d.describes)} over ${cell(d.connections)} connections (per connection p50 ${cell(pc.p50)}, p95 ${cell(pc.p95)}, max ${cell(pc.max)}); per single publication: ${Object.entries(sp).map(([k, v]) => `${k} mean ${cell(v.mean)} (n ${cell(v.n)})`).join(', ') || '—'}`);+ }+ const st = fields.steady;+ if (st) out.push(`Steady state: ${cell(st.pages_per_min_10_90)} pages/min between the 10% and 90% commits (${cell(st.window_s)} s, ${cell(st.committed)} commits); first commit ${cell(st.first_commit_ms)} ms after the sync process started.`);+ for (const [tag, sp] of Object.entries(fields.spans ?? {})) {+ const spans = sp.spans_ms as Record<string, { n: number; p50: number | null; p95: number | null }>;+ const pd = sp.publication_describes as Record<string, number | null>;+ out.push(`\nForeground ${tag} spans (${cell(sp.writes)} writes, ${cell(sp.published_here)} published by the writer, ${cell(sp.published_elsewhere_or_pending)} elsewhere or pending, ${cell(sp.overlapping)} overlapping; describes per publication p50 ${cell(pd.p50)})`,+ table(['span', 'n', 'p50 ms', 'p95 ms'], Object.entries(spans).map(([k, v]) => [k, v.n, v.p50, v.p95])));+ }+ return out.join('\n');+}diff --git a/scripts/bench/managed-sync-catchup.ts b/scripts/bench/managed-sync-catchup.tsindex f868daf86c..2eeb9d2f19 100644--- a/scripts/bench/managed-sync-catchup.ts+++ b/scripts/bench/managed-sync-catchup.ts@@ -4,14 +4,16 @@* schema: docs/eval/managed-sync-catchup.md.** bun scripts/bench/managed-sync-catchup.ts [--files 500] [--deletes 34] [--history 0]- * [--rtt 57,0] [--rows cli,reentry,unmanaged,serve,effects,foreground,all,newcomer]+ * [--rtt 57,0] [--rows cli,reentry,unmanaged,serve,effects,foreground,foreground-open,all,newcomer]* [--max-minutes 20] [--stall-iterations 8] [--pad-words 0] [--receipt-history 0] [--seed 1] [--label <name>] [--out <file.json>]- * [--database-url <admin url>] [--pg-port 55432] [--proxy-port 55433] [--api-port 58474] [--keep]+ * [--fg-interval 5] [--pool-size N] [--pooler pgbouncer]+ * [--database-url <admin url>] [--pg-port 55432] [--proxy-port 55433] [--api-port 58474] [--pooler-port 55434] [--keep]* bun scripts/bench/managed-sync-catchup.ts --analyze <sql-trace.jsonl> [--out <file.json>]*- * `--analyze` re-runs the critical-path, group publication and counter-hold- * analysis (managed-sync-catchup-phases.ts) on a kept trace, without Docker;- * `foreground-{idle,busy}.json` beside the trace add per-put_page round trips.+ * `--analyze` re-runs the critical-path, group publication, counter-hold,+ * feeder, lane, describe and steady-state analysis (managed-sync-catchup-phases.ts)+ * on a kept trace, without Docker; `foreground-{idle,busy,open}.json` beside the+ * trace add per-put_page round trips and span timelines.** Starts (or reuses) a pgvector Postgres with pg_stat_statements in Docker and* a toxiproxy in front of it with `--rtt` milliseconds of round trip split@@ -31,6 +33,9 @@* plus time to retrieval-ready* foreground `cli` while a second process submits put_page every second (p95, lock_timeout count),* after an idle foreground baseline+ * foreground-open+ * `cli` while a second process submits one put_page every --fg-interval seconds whether or+ * not earlier ones finished (open loop: arrival rate, p50/p95, failures by code)* all `gbrain sync --all --no-pull --no-embed --json` re-run until synced, two sources* newcomer cold start to first progress line, and a 5-page managed source to a search hit*@@ -38,8 +43,12 @@* each database round trip is attributed to its process; pg_stat_statements* gives the server-side totals; pg_locks/pg_stat_activity are sampled every* 100 ms for lock waits and their holders. Rows stop at --max-minutes and- * report a labelled extrapolation. Works against any branch: it only drives- * the CLI, performSync and submitPageMutation.+ * report a labelled extrapolation. `--pool-size N` sets GBRAIN_POOL_SIZE for+ * every gbrain process (unset: the product default of 10); `--pooler pgbouncer`+ * puts a transaction-mode PgBouncer between toxiproxy and Postgres and runs+ * gbrain with GBRAIN_PREPARE=false (report-only). Each row records its pool,+ * lane and pooler settings. Works against any branch: it only drives the CLI,+ * performSync and submitPageMutation.*/import { appendFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';@@ -53,7 +62,8 @@ import {BENCH_SQL, classify, family, flatSql, isTxnControl, groupStatements, measureRtt, pct, readEffects, readPgStatStatements, readTrace, round1, startEffectsSampler, startEmbeddingStub,startHarness, startLockSampler, sum, normalizeSql, type Harness, type LockSample, type TraceRecord,} from './managed-sync-catchup-lib.ts';-import { criticalPath, foregroundRoundTrips, publicationBreakdown, publishedPages, renderAnalysis } from './managed-sync-catchup-phases.ts';+import { commitTimes, criticalPath, describeRoundTrips, feederBreakdown, foregroundRoundTrips, foregroundSpans, laneApply, publicationBreakdown, publishedPages, renderAnalysis,+ renderPhase0, steadyRate, syncStart } from './managed-sync-catchup-phases.ts';const REPO = resolve(import.meta.dir, '../..');const CLI = join(REPO, 'src/cli.ts');@@ -70,16 +80,27 @@ if (analyze) analyzeTrace(resolve(analyze), flag('out', ''));function analyzeTrace(file: string, out: string): never {if (!existsSync(file)) { console.error(`trace not found: ${file}`); process.exit(2); }const records = readTrace(file, r => r.label !== 'setup');- const cp = criticalPath(records, publishedPages(records) || null);+ const pages = publishedPages(records) || null;+ const cp = criticalPath(records, pages);const pub = publicationBreakdown(records);+ const phase0 = { feeder: feederBreakdown(records, pages), lanes: laneApply(records), describes: describeRoundTrips(records), steady: steadyRate(commitTimes(records), syncStart(records)) };const foreground: Record<string, unknown> = {};- for (const tag of ['idle', 'busy']) {+ const spans: Record<string, Record<string, unknown>> = {};+ for (const tag of ['idle', 'busy', 'open']) {const results = join(dirname(file), `foreground-${tag}.json`);- if (existsSync(results)) foreground[tag] = foregroundRoundTrips(records, JSON.parse(readFileSync(results, 'utf8')));+ if (!existsSync(results)) continue;+ const writes = JSON.parse(readFileSync(results, 'utf8'));+ foreground[tag] = foregroundRoundTrips(records, writes);+ spans[tag] = foregroundSpans(records, writes);}console.log(renderAnalysis(cp, pub));+ console.log(renderPhase0({ ...phase0, spans }));for (const [tag, rt] of Object.entries(foreground)) console.log(`\nForeground ${tag} per put_page: ${JSON.stringify(rt)}`);- if (out) { mkdirSync(dirname(resolve(out)), { recursive: true }); writeFileSync(resolve(out), JSON.stringify({ trace: file, critical_path: cp, publication: pub, foreground }, null, 2) + '\n'); }+ if (out) {+ mkdirSync(dirname(resolve(out)), { recursive: true });+ writeFileSync(resolve(out), JSON.stringify({ trace: file, critical_path: cp, publication: pub, feeder: phase0.feeder, lanes: phase0.lanes, describes: phase0.describes,+ steady_state: phase0.steady, foreground, foreground_spans: spans }, null, 2) + '\n');+ }process.exit(0);}@@ -96,6 +117,22 @@ const STALL_ITERATIONS = Number(flag('stall-iterations', '8'));const LABEL = flag('label', gitDescribe());const OUT = resolve(flag('out', join(REPO, '.context', 'bench', `managed-sync-catchup-${LABEL.replace(/[^\w.-]/g, '_')}-${Date.now()}.json`)));const KEEP = process.argv.includes('--keep');+const FG_INTERVAL_S = Number(flag('fg-interval', '5'));+const POOL_SIZE = flag('pool-size', '');+const POOLER = flag('pooler', '');+if (POOLER && POOLER !== 'pgbouncer') { console.error(`--pooler takes pgbouncer; got ${POOLER}`); process.exit(2); }+if (POOL_SIZE && !(Number.isInteger(Number(POOL_SIZE)) && Number(POOL_SIZE) > 0)) { console.error(`--pool-size takes a whole number above 0; got ${POOL_SIZE}`); process.exit(2); }+if (!(FG_INTERVAL_S > 0)) { console.error(`--fg-interval takes seconds above 0; got ${FG_INTERVAL_S}`); process.exit(2); }+/** Pool, lane and pooler settings every measured gbrain process runs with, recorded on each row. */+const SETTINGS = {+ pool_size: Number(POOL_SIZE || process.env.GBRAIN_POOL_SIZE || 10),+ pool_size_source: POOL_SIZE ? '--pool-size' : process.env.GBRAIN_POOL_SIZE ? 'GBRAIN_POOL_SIZE' : 'product default',+ sync_lanes_env: process.env.GBRAIN_SYNC_LANES ?? null,+ sync_bulk_env: process.env.GBRAIN_SYNC_BULK ?? null,+ pooler: POOLER || null,+ prepare_env: POOLER ? 'false' : process.env.GBRAIN_PREPARE ?? null,+};+const DEFAULT_SETTINGS = !POOL_SIZE && !process.env.GBRAIN_POOL_SIZE && SETTINGS.sync_lanes_env === null && SETTINGS.sync_bulk_env === null && !POOLER && SETTINGS.prepare_env === null;const SOURCE = 'bench';const SOURCE_B = 'bench-b';const work = mkdtempSync(join(tmpdir(), 'gbrain-catchup-'));@@ -118,7 +155,8 @@ const log = (msg: string) => console.error(`[catchup ${new Date().toISOString().function childEnv(home: string, extra: Record<string, string | undefined> = {}): Record<string, string | undefined> {const env: Record<string, string | undefined> = { ...process.env };for (const key of Object.keys(env)) if (/_API_KEY$|_API_TOKEN$|^DATABASE_URL$|^GBRAIN_DATABASE_URL$|^OPENAI_BASE_URL$/.test(key)) delete env[key];- return { ...env, GBRAIN_HOME: home, GBRAIN_NO_BANNER: '1', GBRAIN_BACKUP_CHECK: '0', GBRAIN_SKILLS_DIR: join(home, 'skills'), NO_COLOR: '1', ...extra };+ return { ...env, GBRAIN_HOME: home, GBRAIN_NO_BANNER: '1', GBRAIN_BACKUP_CHECK: '0', GBRAIN_SKILLS_DIR: join(home, 'skills'), NO_COLOR: '1',+ ...(POOL_SIZE ? { GBRAIN_POOL_SIZE: POOL_SIZE } : {}), ...(POOLER ? { GBRAIN_PREPARE: 'false' } : {}), ...extra };}interface CliRun { killed: boolean; code: number; stdout: string; stderr: string; wallMs: number; firstStderrMs: number | null; firstProgressMs: number | null; json: Record<string, unknown> | null }@@ -345,24 +383,37 @@ async function runWorker(kind: string): Promise<never> {if (result.status !== 'partial') break;await Bun.sleep(250);}- } else if (kind === 'foreground') {+ } else if (kind === 'foreground' || kind === 'foreground-open') {const { submitPageMutation } = await import('../../src/core/persistence/page-mutations.ts');const stopFile = process.env.BENCH_STOP!;- const results: Array<{ t: number; ms: number; ok: boolean; code?: string; state?: string }> = [];+ const results: ForegroundWrite[] = [];const logger = { info() {}, warn() {}, error() {} };- for (let i = 0; !existsSync(stopFile); i++) {+ const open = kind === 'foreground-open';+ const submit = async (i: number): Promise<void> => {const t = performance.now();+ const start = Date.now();+ const slug = `notes/bench-${open ? 'open' : 'foreground'}-${process.pid}-${i}`;try {const out = await submitPageMutation({ engine, config, remote: false, dryRun: false, sourceId, logger } as unknown as Parameters<typeof submitPageMutation>[0],- { operation: 'put_page', params: { slug: `notes/bench-foreground-${process.pid}-${i}`, content: `---\ntitle: Foreground ${i}\n---\nForeground write ${i} during catch-up.\n` }, waitMs: 30_000 });+ { operation: 'put_page', params: { slug, content: `---\ntitle: Foreground ${i}\n---\nForeground write ${i} during catch-up.\n` }, waitMs: 30_000 });const state = String((out as { state?: string; status?: string }).state ?? (out as { status?: string }).status ?? '');- results.push({ t: Date.now(), ms: round1(performance.now() - t), ok: !['failed', 'conflict', 'cancelled'].includes(state), state });+ results.push({ start, t: Date.now(), ms: round1(performance.now() - t), ok: !['failed', 'conflict', 'cancelled'].includes(state), state });} catch (error) {const e = error as { code?: string; message?: string };- results.push({ t: Date.now(), ms: round1(performance.now() - t), ok: false, code: e.code ?? (/lock timeout/i.test(e.message ?? '') ? '55P03' : 'error'), state: (e.message ?? '').slice(0, 200) });+ results.push({ start, t: Date.now(), ms: round1(performance.now() - t), ok: false, code: e.code ?? (/lock timeout/i.test(e.message ?? '') ? '55P03' : 'error'), state: (e.message ?? '').slice(0, 200) });}- await Bun.sleep(Math.max(0, 1000 - (performance.now() - t)));+ };+ const intervalMs = open ? Number(process.env.BENCH_INTERVAL_MS) : 1000;+ const inflight = new Set<Promise<void>>();+ const began = performance.now();+ for (let i = 0; !existsSync(stopFile); i++) {+ const t = performance.now();+ if (!open) { await submit(i); await Bun.sleep(Math.max(0, 1000 - (performance.now() - t))); continue; }+ const write: Promise<void> = submit(i).finally(() => inflight.delete(write));+ inflight.add(write);+ while (!existsSync(stopFile) && performance.now() < began + (i + 1) * intervalMs) await Bun.sleep(Math.min(250, Math.max(1, began + (i + 1) * intervalMs - performance.now())));}+ await Promise.all(inflight);writeFileSync(process.env.BENCH_RESULTS!, JSON.stringify(results));}await disposePersistenceConsumer(engine);@@ -370,11 +421,14 @@ async function runWorker(kind: string): Promise<never> {process.exit(0);}-async function foregroundWriter(row: RowContext, tag: string): Promise<{ stop: () => Promise<Array<{ t: number; ms: number; ok: boolean; code?: string; state?: string }>> }> {+interface ForegroundWrite { start?: number; t: number; ms: number; ok: boolean; code?: string; state?: string }++async function foregroundWriter(row: RowContext, tag: string, kind: 'foreground' | 'foreground-open' = 'foreground'): Promise<{ stop: () => Promise<ForegroundWrite[]> }> {const stopFile = join(row.home, `foreground-${tag}.stop`);const results = join(row.home, `foreground-${tag}.json`);- const child = Bun.spawn([process.execPath, import.meta.path, '--worker', 'foreground'], { cwd: row.home, stdin: 'ignore', stdout: 'pipe', stderr: 'pipe',- env: childEnv(row.home, { GBRAIN_SQL_TRACE: row.trace, GBRAIN_SQL_TRACE_LABEL: 'foreground', BENCH_SOURCE: SOURCE, BENCH_STOP: stopFile, BENCH_RESULTS: results }) });+ const child = Bun.spawn([process.execPath, import.meta.path, '--worker', kind], { cwd: row.home, stdin: 'ignore', stdout: 'pipe', stderr: 'pipe',+ env: childEnv(row.home, { GBRAIN_SQL_TRACE: row.trace, GBRAIN_SQL_TRACE_LABEL: 'foreground', BENCH_SOURCE: SOURCE, BENCH_STOP: stopFile, BENCH_RESULTS: results,+ BENCH_INTERVAL_MS: String(FG_INTERVAL_S * 1000) }) });return {async stop() {writeFileSync(stopFile, '');@@ -385,6 +439,15 @@ async function foregroundWriter(row: RowContext, tag: string): Promise<{ stop: (};}+/** Latency, failures by code and per-put_page round trips and spans of one foreground writer's results. */+function summarizeWrites(rs: ForegroundWrite[], fgRecords: TraceRecord[]): Record<string, unknown> {+ const code = (r: ForegroundWrite) => r.code ?? r.state ?? '?';+ return { writes: rs.length, round_trips: foregroundRoundTrips(fgRecords, rs), spans: foregroundSpans(fgRecords, rs), p50_ms: pct(rs.map(r => r.ms), 50), p95_ms: pct(rs.map(r => r.ms), 95),+ failures: rs.filter(r => !r.ok).length,+ lock_timeouts: rs.filter(r => r.code === '55P03' || /lock_timeout|lock timeout/i.test(r.state ?? '')).length,+ failure_codes: Object.fromEntries([...new Set(rs.filter(r => !r.ok).map(code))].map(c => [c, rs.filter(r => !r.ok && code(r) === c).length])) };+}+function startServe(row: RowContext, env: Record<string, string> = {}): { stop: () => Promise<string> } {const port = 20000 + Math.floor(Math.random() * 20000);const child = Bun.spawn([process.execPath, CLI, 'serve', '--http', '--bind', '127.0.0.1', '--port', String(port)], { cwd: row.home, stdin: 'ignore', stdout: 'pipe', stderr: 'pipe',@@ -392,6 +455,14 @@ function startServe(row: RowContext, env: Record<string, string> = {}): { stop:return { async stop() { child.kill('SIGTERM'); const t = setTimeout(() => child.kill('SIGKILL'), 15_000); const err = await new Response(child.stderr).text(); await child.exited; clearTimeout(t); return err.slice(-2000); } };}+/** Most writes of one writer in flight at once. */+function maxInFlight(rs: ForegroundWrite[]): number {+ const events = rs.flatMap(r => [{ t: r.t - r.ms, d: 1 }, { t: r.t, d: -1 }]).sort((a, b) => a.t - b.t || a.d - b.d);+ let open = 0, max = 0;+ for (const e of events) { open += e.d; max = Math.max(max, open); }+ return max;+}+/** Statements a CLI process issues before its first admission, and what fraction of a process's statements that is. */function processBreakdown(records: TraceRecord[]): Record<string, unknown> {const byPid = new Map<number, TraceRecord[]>();@@ -457,8 +528,10 @@ async function collect(row: RowContext, driven: Driven, locks: LockSample[], meaconst publications = byFamily(/^UPDATE persistence_requests SET state=\$2,outcome=/);const releases = byFamily(/^UPDATE persistence_requests SET state='queued',execution_token=NULL/);const traced = records.filter(r => (r.kind === 'execute' || r.kind === 'simple') && !isTxnControl(r.sql)).length;+ const lanes = laneApply(records);return {row: row.name, rtt_target_ms: row.rtt, managed: row.managed, backlog_entries: row.backlog, home: row.home, database: row.db,+ settings: { ...SETTINGS, default_settings: DEFAULT_SETTINGS, pooler_detail: harness.pooler, lanes_busy_max_observed: (lanes.lanes_busy as { max: number }).max },done: driven.done, timed_out: driven.timedOut, error: driven.error ?? null,wall_s: round1(driven.wallMs / 1000),entries_committed: committed.length,@@ -466,6 +539,8 @@ async function collect(row: RowContext, driven: Driven, locks: LockSample[], meaentries_waived: null,pages_per_min: minutes > 0 ? round1(pages / minutes) : null,extrapolated_full_backlog_h: !driven.done && pages > 0 ? round1((row.backlog / (pages / minutes)) / 60) : null,+ steady_state: { ...steadyRate(commitTimes(records), syncStart(records)), source: 'trace',+ db: { ...steadyRate(completions, measureStart.getTime()), source: 'persistence_requests.completed_at; first commit from the row start' } },per_page_wall_ms: { p50: pct(gaps, 50), p90: pct(gaps, 90), import_p50: pct(gapOf('managed_sync_import'), 50), delete_p50: pct(gapOf('managed_sync_delete'), 50) },admission_to_commit_ms: { p50: pct(committed.map(r => r.completed! - r.created), 50), p90: pct(committed.map(r => r.completed! - r.created), 90), p99: pct(committed.map(r => r.completed! - r.created), 99) },requests_by_state: Object.fromEntries([...new Set(stats.reqs.map(r => `${r.kind ?? r.operation}:${r.state}`))].map(k => [k, stats.reqs.filter(r => `${r.kind ?? r.operation}:${r.state}` === k).length])),@@ -496,6 +571,9 @@ async function collect(row: RowContext, driven: Driven, locks: LockSample[], meare_entry: processBreakdown(records),critical_path: criticalPath(records, pages || null),publication: publicationBreakdown(records),+ feeder: feederBreakdown(records, pages || null),+ lanes,+ describes: describeRoundTrips(records),pg_stat_statements_calls_ex_txn: pss.calls_ex_txn, traced_executions_ex_txn: traced,reconciliation_pct: pss.available && pss.calls_ex_txn ? round1(100 * (traced - pss.calls_ex_txn) / pss.calls_ex_txn) : null,},@@ -532,7 +610,7 @@ async function measure(row: RowContext, drive: () => Promise<Driven>, extra: ()await harness.setRtt(row.rtt);const sizeBefore = await admin(async sql => Number((await sql.unsafe(BENCH_SQL + ' SELECT pg_database_size(current_database())::float8 AS b'))[0]!.b), row.db);await admin(sql => sql.unsafe(BENCH_SQL + ' SELECT pg_stat_statements_reset(0, (SELECT oid FROM pg_database WHERE datname=$1), 0)', [row.db]).catch(() => undefined));- const measuredRtt = await measureRtt(row.proxyUrl);+ const measuredRtt = await measureRtt(row.proxyUrl, !POOLER);const sampler = startLockSampler(harness.adminUrl, row.db);const effectsSampler = startEffectsSampler(row.directUrl);const start = new Date();@@ -545,11 +623,19 @@ async function measure(row: RowContext, drive: () => Promise<Driven>, extra: ()final_backlog: Number((await sql.unsafe(`${BENCH_SQL} SELECT count(*) FILTER (WHERE state IN ('queued','running'))::int AS n FROM persistence_effects`))[0]!.n) }), row.db);const result = await collect(row, driven, locks, start, { rtt_measured_ms: measuredRtt, ...more, effects,effects_backlog: { samples: backlog.length, sample_every_ms: 2000, max: pct(backlog, 100), p50: pct(backlog, 50), final: effects.final_backlog } });- const trace = result.trace as { critical_path: Record<string, unknown>; publication: Record<string, unknown> };- console.error(renderAnalysis(trace.critical_path, trace.publication));- for (const key of ['foreground_idle', 'foreground_during_catchup']) {- const fg = result[key] as { round_trips?: unknown } | undefined;+ const trace = result.trace as Record<string, Record<string, unknown>>;+ console.error(renderAnalysis(trace.critical_path!, trace.publication!));+ const spans: Record<string, Record<string, unknown>> = {};+ for (const key of ['foreground_idle', 'foreground_during_catchup', 'foreground_open']) {+ const fg = result[key] as { round_trips?: unknown; spans?: Record<string, unknown> } | undefined;if (fg?.round_trips) console.error(`${key} per put_page: ${JSON.stringify(fg.round_trips)}`);+ if (fg?.spans) spans[key] = fg.spans;+ }+ console.error(renderPhase0({ feeder: trace.feeder, lanes: trace.lanes, describes: trace.describes, steady: result.steady_state as Record<string, unknown>, spans }));+ const open = result.foreground_open as Record<string, unknown> | undefined;+ if (open) {+ Object.assign(open, { catchup_pages_per_min: result.pages_per_min, catchup_steady_pages_per_min: (result.steady_state as Record<string, unknown>).pages_per_min_10_90 });+ console.error(`foreground_open: ${open.submitted} submitted at ${open.arrival_per_min}/min, p50 ${open.p50_ms} ms, p95 ${open.p95_ms} ms, failures ${JSON.stringify(open.failure_codes)}, catch-up ${open.catchup_pages_per_min} pages/min`);}console.error(`effects: ${JSON.stringify(effects)}; backlog ${JSON.stringify(result.effects_backlog)}`);const committed = result.entries_committed as number;@@ -627,10 +713,19 @@ async function runRow(name: string, rtt: number): Promise<Record<string, unknownreturn measure(row, async () => { busy = await foregroundWriter(row, 'busy'); return driveCli(row, syncArgs); }, async () => {const busyResults = await busy!.stop();const fgRecords = readTrace(row.trace, r => family(r.label) === 'foreground');- const summarize = (rs: typeof idleResults) => ({ writes: rs.length, round_trips: foregroundRoundTrips(fgRecords, rs), p50_ms: pct(rs.map(r => r.ms), 50), p95_ms: pct(rs.map(r => r.ms), 95), failures: rs.filter(r => !r.ok).length,- lock_timeouts: rs.filter(r => r.code === '55P03' || /lock_timeout|lock timeout/i.test(r.state ?? '')).length,- failure_codes: Object.fromEntries([...new Set(rs.filter(r => !r.ok).map(r => r.code ?? r.state ?? '?'))].map(c => [c, rs.filter(r => !r.ok && (r.code ?? r.state ?? '?') === c).length])) });- return { foreground_idle: summarize(idleResults), foreground_during_catchup: summarize(busyResults) };+ return { foreground_idle: summarizeWrites(idleResults, fgRecords), foreground_during_catchup: summarizeWrites(busyResults, fgRecords) };+ });+ }+ if (name === 'foreground-open') {+ const row = await setupRow(name, rtt, { managed: true, sources: 1, files: FILES, deletes: DELETES });+ let open: Awaited<ReturnType<typeof foregroundWriter>> | undefined;+ return measure(row, async () => { open = await foregroundWriter(row, 'open', 'foreground-open'); return driveCli(row, syncArgs); }, async () => {+ const results = await open!.stop();+ const fgRecords = readTrace(row.trace, r => family(r.label) === 'foreground');+ const starts = results.flatMap(r => r.start === undefined ? [] : [r.start]).sort((a, b) => a - b);+ const spanMin = starts.length > 1 ? (starts.at(-1)! - starts[0]!) / 60_000 : 0;+ return { foreground_open: { interval_s: FG_INTERVAL_S, submitted: results.length, arrival_per_min: spanMin > 0 ? round1((starts.length - 1) / spanMin) : null,+ max_in_flight: maxInFlight(results), ...summarizeWrites(results, fgRecords) } };});}if (name === 'all') {@@ -662,10 +757,12 @@ async function newcomer(rtt: number): Promise<Record<string, unknown>> {}harness = await startHarness({ pgPort: Number(flag('pg-port', '55432')), proxyPort: Number(flag('proxy-port', '55433')), apiPort: Number(flag('api-port', '58474')),- adminUrl: process.argv.includes('--database-url') ? flag('database-url', '') : undefined, keep: KEEP });+ adminUrl: process.argv.includes('--database-url') ? flag('database-url', '') : undefined, keep: KEEP, poolerPort: POOLER ? Number(flag('pooler-port', '55434')) : undefined });const report: Record<string, unknown> = {schema: 'gbrain.bench.managed-sync-catchup/v1', label: LABEL, commit: gitDescribe(), started_at: new Date().toISOString(),- params: { files: FILES, deletes: DELETES, history: HISTORY, receipt_history: RECEIPT_HISTORY, pad_words: PAD_WORDS, seed: SEED, rtt_ms: RTTS, rows: ROWS, max_minutes: MAX_MS / 60_000 },+ params: { files: FILES, deletes: DELETES, history: HISTORY, receipt_history: RECEIPT_HISTORY, pad_words: PAD_WORDS, seed: SEED, rtt_ms: RTTS, rows: ROWS, max_minutes: MAX_MS / 60_000,+ fg_interval_s: FG_INTERVAL_S, pool_size: POOL_SIZE ? Number(POOL_SIZE) : null, pooler: POOLER || null },+ settings: { ...SETTINGS, default_settings: DEFAULT_SETTINGS }, pooler: harness.pooler,host: { cpus: navigator.hardwareConcurrency, platform: process.platform, bun: Bun.version },rerun: `bun scripts/bench/managed-sync-catchup.ts ${process.argv.slice(2).join(' ')}`,rows: [] as Array<Record<string, unknown>>,diff --git a/test/bench-managed-sync-catchup.test.ts b/test/bench-managed-sync-catchup.test.tsnew file mode 100644index 0000000000..cf18477ec2--- /dev/null+++ b/test/bench-managed-sync-catchup.test.ts@@ -0,0 +1,130 @@+/**+ * Pure trace analysis of scripts/bench/managed-sync-catchup-phases.ts on+ * synthetic SQL-trace records: transaction classification (lane group+ * publications, rolled-back groups, singles, waivers, recovery records), lane+ * turn waits and busy lanes, the feeder's idle vs producing split, foreground+ * spans and the steady-state rate. The bench itself never runs here.+ */+import { describe, expect, test } from 'bun:test';+import type { TraceRecord } from '../scripts/bench/managed-sync-catchup-lib.ts';+import {+ chainWaves, commitTimes, criticalPath, feederBreakdown, foregroundSpans, laneApply, publicationBreakdown, publishedPages, steadyRate, transactions,+} from '../scripts/bench/managed-sync-catchup-phases.ts';++const RTT = 60;+const DECLARE = "SELECT set_config('gbrain.persistence_protocol','2',true),set_config('synchronous_commit','on',true),\n set_config('lock_timeout',$1,true),set_config('statement_timeout',$2,true),(SELECT singleton FROM persistence_brain WHERE singleton=1 FOR SHARE) AS brain";+const GUARD = 'SELECT owner_host_id,owner_epoch,state FROM persistence_worktrees WHERE id=$1::uuid FOR SHARE';+const ATTRIBUTE = "SELECT set_config('gbrain.write_request',$1,true),set_config('gbrain.write_principal_kind',$2,true),set_config('gbrain.write_principal_id',$3,true)";+const INSERT_PAGE = 'INSERT INTO pages (source_id, slug, type, page_kind, title) VALUES ($1,$2,$3,$4,$5)';+const SAVE_CURSOR = 'INSERT INTO op_checkpoints(op,fingerprint,completed_keys) VALUES($1,$2,$3::text::jsonb) ON CONFLICT(op,fingerprint) DO UPDATE SET completed_keys=EXCLUDED.completed_keys';+const TURN = 'SELECT state FROM persistence_requests WHERE principal_kind=$1 AND principal_id=$2 AND request_id=$3::uuid';+const ENSURE = 'INSERT INTO persistence_counters(key) SELECT k FROM unnest($1::text[]) WITH ORDINALITY AS u(k,n) ORDER BY n ON CONFLICT DO NOTHING';+const LOCK = 'SELECT * FROM persistence_counters WHERE key=ANY($1::text[]) ORDER BY key COLLATE "C" FOR UPDATE';+const GROUP_DONE = "WITH m AS (\n SELECT * FROM unnest($1::uuid[],$2::uuid[],$3::text[],$4::bigint[],$5::text[]) AS m(id,token,outcome,need,principal_key)\n ), done AS (\n UPDATE persistence_requests r SET state='committed',outcome=m.outcome::jsonb FROM m WHERE r.id=m.id RETURNING r.*\n ) SELECT * FROM done";+const SINGLE_DONE = 'WITH effects AS (SELECT 1 AS bytes), done AS (UPDATE persistence_requests SET state=$2,outcome=$3::text::jsonb WHERE id=$1::uuid RETURNING *) SELECT * FROM done';++/** One sequential statement chain on one connection, one RTT per statement. */+function chain(start: number, conn: number, sqls: string[], opts: { pid?: number; label?: string; ms?: number } = {}): TraceRecord[] {+ const ms = opts.ms ?? RTT;+ return sqls.map((sql, i) => ({ t: start + i * ms, ms, pid: opts.pid ?? 1, label: opts.label ?? 'cli-sync', pool: 'module', conn, backend: conn, kind: /^(begin|commit|rollback)$/.test(sql) ? 'simple' : 'execute', sql }));+}+const memberSql = [ATTRIBUTE, INSERT_PAGE, SAVE_CURSOR];+function groupTxn(start: number, conn: number, members: number, opts: { turnPolls?: number; complete?: boolean } = {}): TraceRecord[] {+ const body = [DECLARE, GUARD, ...Array.from({ length: members }, () => memberSql).flat(), ...Array.from({ length: opts.turnPolls ?? 0 }, () => TURN)];+ return chain(start, conn, ['begin', ...body, ...(opts.complete === false ? ['rollback'] : [ENSURE, LOCK, GROUP_DONE, 'commit'])]);+}++describe('transaction classification', () => {+ test('a lane group publication is a group publication, not a cursor save', () => {+ const records = groupTxn(0, 1, 4, { turnPolls: 2 });+ const [txn] = transactions(records).txns;+ expect(txn).toMatchObject({ type: 'publication', group: true, members: 4, committed: true });+ const cp = criticalPath(records, 4);+ const phase = (name: string) => (cp.phases as Array<{ phase: string; occurrences: number }>).find(p => p.phase === name)!.occurrences;+ expect(phase('publication (group)')).toBe(1);+ expect(phase('cursor')).toBe(0);+ expect(publishedPages(records)).toBe(4);+ expect((publicationBreakdown(records) as { committed: number }).committed).toBe(1);+ });++ test('a lane group rolled back before its completion is still a group publication', () => {+ const [txn] = transactions(groupTxn(0, 1, 2, { complete: false })).txns;+ expect(txn).toMatchObject({ type: 'publication', group: true, committed: false });+ });++ test('a group run by another process and connection classifies the same way', () => {+ const [txn] = transactions(groupTxn(0, 7, 3).map(r => ({ ...r, pid: 9, label: 'serve' }))).txns;+ expect(txn).toMatchObject({ type: 'publication', group: true, members: 3 });+ });++ test('single publication, waiver and recovery transactions', () => {+ const single = chain(0, 1, ['begin', DECLARE, GUARD, ENSURE, LOCK, INSERT_PAGE, SINGLE_DONE, 'commit']);+ const waiver = chain(1000, 2, ['begin', 'INSERT INTO page_write_guards(source_incarnation,slug) VALUES ($1::uuid,$2) ON CONFLICT DO NOTHING',+ 'UPDATE op_checkpoints SET completed_keys=$4::text::jsonb,updated_at=now() WHERE op=$1 AND fingerprint=$2 AND completed_keys=$3::text::jsonb', 'commit']);+ const recovery = chain(2000, 3, ['begin', DECLARE, 'WITH recorded AS (UPDATE persistence_requests SET recovery=$3::text::jsonb,recovery_bytes=$4 WHERE id=$1::uuid RETURNING id) SELECT * FROM recorded', 'commit']);+ expect(transactions([...single, ...waiver, ...recovery]).txns.map(t => [t.type, t.group])).toEqual([['publication', false], ['waiver', false], ['recovery', false]]);+ });+});++describe('lanes', () => {+ test('turn wait is the last poll run before completion; busy lanes are time-weighted', () => {+ const records = [...groupTxn(0, 1, 2), ...groupTxn(0, 2, 2, { turnPolls: 3 })];+ const lanes = laneApply(records) as { group_txns: number; with_turn_wait: number; turn_wait_ms: { total: number }; lanes_busy: { mean: number; max: number; distribution_pct: Record<string, number> } };+ expect(lanes.group_txns).toBe(2);+ expect(lanes.with_turn_wait).toBe(1);+ expect(lanes.turn_wait_ms.total).toBe(3 * RTT);+ expect(lanes.lanes_busy.max).toBe(2);+ expect(lanes.lanes_busy.distribution_pct['2']).toBeGreaterThan(50);+ expect(lanes.lanes_busy.mean).toBeGreaterThan(1.5);+ });++ test('member validation sends the turn read too, but only the trailing run counts', () => {+ const records = chain(0, 1, ['begin', DECLARE, ATTRIBUTE, TURN, INSERT_PAGE, ATTRIBUTE, INSERT_PAGE, ENSURE, LOCK, GROUP_DONE, 'commit']);+ expect((laneApply(records) as { with_turn_wait: number }).with_turn_wait).toBe(0);+ });+});++describe('feeder', () => {+ test('the gap before a write-wait read is idle, gaps before cursor saves are producing', () => {+ const records = [+ ...chain(-100, 1, ['SELECT completed_keys FROM op_checkpoints WHERE op=$1 AND fingerprint=$2']),+ ...chain(0, 1, ['SELECT id,slug,source_path FROM pages WHERE source_id=$1 AND source_path=ANY($2::text[])', 'WITH chosen AS ( SELECT p.* FROM pages p WHERE p.slug=$1 AND p.source_id=$2 )',+ 'SELECT lane,revoked_at,grant_ceiling FROM persistence_local_writers WHERE id=$1::uuid']),+ ...chain(200, 1, ['begin', 'UPDATE op_checkpoints SET completed_keys=$4::text::jsonb,updated_at=now() WHERE op=$1 AND fingerprint=$2 AND completed_keys=$3::text::jsonb', 'commit']),+ ...chain(5000, 1, ['SELECT * FROM persistence_requests WHERE id=ANY($1::uuid[])']),+ ];+ const feeder = feederBreakdown(records, 1) as { entries_frozen_est: number; time_ms: Record<string, number>; buckets: Record<string, { statements: number }> };+ expect(feeder.entries_frozen_est).toBe(1);+ expect(feeder.time_ms.idle_await_write).toBe(5000 - 380);+ expect(feeder.buckets.freeze!.statements).toBe(3);+ expect(feeder.buckets.cursor!.statements).toBe(4);+ });+});++describe('foreground spans', () => {+ test('a write published by the writer gets every span', () => {+ const records = [+ ...chain(100, 1, ['begin', 'INSERT INTO persistence_requests (principal_kind) VALUES ($1)', 'commit']),+ ...chain(500, 2, ['begin', "UPDATE persistence_requests SET state='running', execution_token=$2::uuid WHERE id=$1", 'commit']),+ ...chain(900, 3, ['begin', DECLARE, GUARD, ENSURE, LOCK, INSERT_PAGE, SINGLE_DONE, 'commit']),+ ].map(r => ({ ...r, label: 'foreground' }));+ const spans = foregroundSpans(records, [{ t: 1500, ms: 1500 }]) as { published_here: number; spans_ms: Record<string, { p50: number | null }> };+ expect(spans.published_here).toBe(1);+ expect(spans.spans_ms.pre_admission!.p50).toBe(100);+ expect(spans.spans_ms.preparation!.p50).toBe(900 - 680);+ expect(spans.spans_ms.publication!.p50).toBe(8 * RTT);+ expect(spans.spans_ms.visible!.p50).toBe(1500 - 1380);+ });+});++describe('rates and waves', () => {+ test('steady-state pages/min between the 10% and 90% commits', () => {+ const times = Array.from({ length: 11 }, (_, i) => 1000 + i * 6000);+ expect(steadyRate(times, 0)).toEqual({ committed: 11, pages_per_min_10_90: 10, window_s: 48, first_commit_ms: 1000 });+ expect(commitTimes(groupTxn(0, 1, 3))).toHaveLength(3);+ });++ test('overlapping records on different connections are one wave', () => {+ expect(chainWaves([...chain(0, 1, ['a']), ...chain(10, 2, ['b']), ...chain(200, 3, ['c'])]).count).toBe(2);+ });+});