Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
bench: managed-sync catch-up harness and master baseline (#5984)
garrytan36cfd0472d59
diff --git a/docs/eval/managed-sync-catchup.md b/docs/eval/managed-sync-catchup.mdnew file mode 100644index 0000000000..f6477971d9--- /dev/null+++ b/docs/eval/managed-sync-catchup.md@@ -0,0 +1,439 @@+# Managed-sync catch-up bench (#5984)++On master, catching up a git source on managed Postgres is bound by+database round trips. Each committed page costs about 190 to 260+sequential round trips. At 57 ms RTT that is 3.4 pages/min with the+reporter's CLI loop and 4.2 pages/min when one process re-enters+`performSync`. The issue-sized 10k backlog projects to about 49 h,+close to the reporter's 52 h. The plan's budget for 150 pages/min is+about 7 round trips per page, and the publication transaction alone+takes 77 to 83. By the CEO-A1 decision rule, the measured numbers+call for multi-page (bulk) publication after the round-trip diet;+pipelined admission alone cannot reach the target.++This page is the research and decision record for the #5984 plan+(CEO-A1, A2, A3, A4, A6, A17, A19, A25, A26, A27, A29; ENG-A5, A9,+A11, A14, A15, A18; DX-A12, A13). The bench is opt-in and never runs+in CI.++## Rerun++Needs Docker on Linux (toxiproxy runs with host networking and every+listener binds 127.0.0.1) and Bun 1.4+. Make no provider calls: the+effects row uses a loopback stub for `/v1/embeddings`.++```bash+# 500-file rows at 57 ms and ~0 ms (the baseline table below)+bun scripts/bench/managed-sync-catchup.ts --files 500 --deletes 34 --rtt 57,0 \+ --rows cli,reentry,unmanaged,serve,effects,foreground,all,newcomer --max-minutes 15 --label <branch>++# issue-sized row: 10k files, 300-word pages, 300 pages of existing receipt history+bun scripts/bench/managed-sync-catchup.ts --files 10000 --deletes 34 --receipt-history 300 --pad-words 300 \+ --rtt 57,0 --rows cli --max-minutes 15 --label <branch>-10k+```++Rows run in sequence by default. Rows at 57 ms are latency-bound and+use almost no CPU, so they can run in parallel as separate+invocations, each with its own `--proxy-port` and `--keep` (one+toxiproxy proxy per port). Rows at ~0 ms are CPU-bound; run them+alone. The baseline used one invocation per 57 ms row in parallel,+then the ~0 ms rows in one sequential invocation.++Flags: `--files`, `--deletes` (already soft-deleted pages whose files+the backlog commit removes), `--history` (classic-mode pages present+before the backlog), `--receipt-history` (pages synced in managed mode+before the backlog, so the journal holds receipts), `--pad-words`+(page size), `--rtt` (comma-separated round-trip targets in ms, split+evenly across the two directions), `--rows`, `--max-minutes` (per-row+time box), `--stall-iterations` (consecutive CLI runs with no new+commit before a row stops, default 8), `--seed`, `--label`, `--out`,+`--database-url <admin url>` (use an existing server instead of the+Docker one; it needs `pg_stat_statements` preloaded for the server+totals), `--pg-port`, `--proxy-port`, `--api-port`, `--keep`.++The command works against any branch: it drives the real CLI+(`gbrain sync`, `gbrain sources writer claim/activate`,+`gbrain serve --http`), `performSync` and `submitPageMutation`, and it+reads `persistence_requests` and `op_checkpoints`.++## Method++- **Server and latency.** `pgvector/pgvector:pg16` with+ `shared_preload_libraries=pg_stat_statements`, behind+ `ghcr.io/shopify/toxiproxy:2.12.0` latency toxics (half the RTT+ upstream, half downstream). Each row records the measured proxy RTT,+ the median of 20 `SELECT 1` (59.4 to 60.2 ms for the 57 ms rows,+ 0.3 to 0.5 ms for the ~0 ms rows).+- **Fresh brain per row.** Each row clones a database from a template+ that this checkout's `initSchema` built, with a temporary+ `GBRAIN_HOME`. In classic mode the bench adds source `bench` from a+ git repository and syncs it, then soft-deletes the `--deletes` pages.+ It claims and activates through the real `sources writer` CLI (same+ host, so the CLI host is the owner host, ENG-A9) and optionally syncs+ `--receipt-history` pages in managed mode. Then it commits the+ backlog: `--files` new pages, plus deletions of the soft-deleted+ files. The manifest therefore holds 34 already-soft-deleted deletes+ (published first) and N imports, as in the issue. Setup talks to+ Postgres directly; only the measured run goes through the proxy.+- **Drivers.** `cli` re-runs+ `gbrain sync --source bench --no-pull --no-embed --json` until it+ reports `synced`, exactly like the reporter's workaround, and keeps+ looping after a failed run. `reentry` keeps one process calling+ `performSync` with a 250 ms pause, like the PGLite delegate.+ `unmanaged` runs one classic sync of the same corpus. `serve` is+ `cli` with a resident `gbrain serve --http`. `effects` is `cli`+ without `--no-embed`, with a resident serve, against a loopback+ embeddings stub (200 ms per call, 4 concurrent, 429 beyond).+ `foreground` is `cli` with a second process submitting `put_page`+ once a second, after a 60 s idle foreground baseline. `all` runs+ `gbrain sync --all` over two sources. `newcomer` measures a cold+ `--progress-json` sync of a 5-page backlog to a search hit.+- **Trace (ENG-A15, CEO-A19).** Every gbrain process runs with+ `GBRAIN_SQL_TRACE=<file>` and a per-process+ `GBRAIN_SQL_TRACE_LABEL`. The hook (`src/core/sql-trace.ts`) wraps+ the postgres.js socket of all four pools, so `executeRaw`,+ `tx.unsafe`, the engine-sql adapter and the direct pool are covered.+ It writes one record per database round trip:+ - Sync/Query: one record per Sync or simple Query sent, closed by its+ ReadyForQuery reply.+ - Describe: one record for the describe Flush that an unprepared+ statement with parameters pays before it executes.+ - Connect: one record per new connection, covering TCP plus the+ startup handshake.++ Records carry statement text, never parameter values. When the+ variable is unset, the hook returns the pool options unchanged.+- **Reconciliation.** The bench resets `pg_stat_statements` for the+ row's database. It excludes its own monitoring statements (tagged+ `/* gbrain-bench */`) and transaction control, which+ `pg_stat_statements` does not count reliably. Traced executions then+ match the server totals within 0.0 to 2.1% on every row.+- **Locks (CEO-A4).** Every 100 ms, a separate admin connection samples+ `pg_stat_activity` joined to `pg_blocking_pids()` for the row's+ database. `application_name` (`gbrain:<label>:<pid>:<pool>`) names+ the process holding the lock.+- **Throughput.** Pages/min counts committed `managed_sync_import` and+ `managed_sync_delete` requests over the driver's wall time. Per-page+ wall time is the gap between consecutive commits.+ Admission→commit is `completed_at - created_at`. Both columns default+ to `now()`, which is the transaction start, so this figure leaves out+ the publication transaction itself (about 5 s at 57 ms). Time-boxed+ rows also report an extrapolation for the full backlog, labelled as+ one.++## JSON schema (`gbrain.bench.managed-sync-catchup/v1`)++Top level: `schema`, `label`, `commit`, `started_at`, `finished_at`,+`params` (every flag), `host`, `rerun`, `rows[]`. Each throughput row+has:++| Field | Meaning |+|---|---|+| `row`, `rtt_target_ms`, `rtt_measured_ms`, `managed`, `backlog_entries`, `home`, `database` | Identity. |+| `done`, `timed_out`, `error`, `wall_s` | Outcome. A row that hits `--max-minutes` has `timed_out: true`. |+| `entries_committed`, `entries_noop`, `entries_waived` | Committed sync entries; `noop` = `outcome.noop`; `waived` is null until the waiver lands (Lane C should fill it from the run's counts). |+| `pages_per_min`, `extrapolated_full_backlog_h` | Throughput; the extrapolation is set only when the row did not finish. |+| `per_page_wall_ms` `{p50,p90,import_p50,delete_p50}` | Gaps between consecutive commits. |+| `admission_to_commit_ms` `{p50,p90,p99}` | From `persistence_requests` timestamps (see Method). |+| `requests_by_state` | `<kind>:<state>` counts admitted during the run. |+| `cli` | `invocations`, `wall_ms_p50/p90`, `pages_per_invocation`, `writer_pending_exits`, `first_stderr_ms_p50`, `e1_first_progress_ms`, `failed_runs` (failure code → count), `statuses`. |+| `trace.round_trips`, `round_trips_per_page`, `describe_round_trips`, `connections_opened`, `connect_ms_p50`, `db_ms_per_page` | All traced round trips, every process. |+| `trace.by_process` | Round trips, per page, ms and process count per process family (`cli-sync`, `reentry`, `serve`, `foreground`). |+| `trace.round_trips_by_class`, `trace.sync_process_by_class` | Per-page round trips by class, and the sync process's statement share by class (`consumer-background`, `wait-poll`, `txn-control`, `guards+counters`, `cursor`, `journal`, `page-data`, `connection-setup`, `other-control`; see `classify()` in the lib). |+| `trace.top_statements[]` | Normalized statement, count, total ms, per page, by process (describe round trips listed separately). |+| `trace.re_entry` | Per process: statements before the first admission, and ms from the first statement to the first admission. |+| `trace.errors` | `<process>:<SQLSTATE>` counts. |+| `trace.reconciliation_pct`, `pg_stat_statements_calls_ex_txn`, `traced_executions_ex_txn`, `pg_stat_statements` | ENG-A15 reconciliation and the server's top statements. |+| `guard_wait` | `page_write_guards ... FOR UPDATE` statement count, total, per page, p50, max. |+| `claims` | Claims, publications and unpublished releases (`writer_busy`) by process (CEO-A3 claim races). |+| `lock_waits` | Lock-wait samples (100 ms each), grouped by waiting statement, holder process and holder statement. |+| `db_size_bytes`, `db_growth_bytes_per_page`, `persistence_counters`, `capacity_headroom` | CEO-A25 growth and journal headroom vs the default limits, including the full backlog's projected reservation. |+| `cli_is_owner_host` | ENG-A9. |+| `foreground_idle`, `foreground_during_catchup` | `foreground` row: writes, p50/p95 ms, failures, lock_timeouts, failure codes (ENG-A5). |+| `effects_backlog_at_cli_exit`, `readiness`, `retrieval_ready`, `retrieval_ready_after_sync_s`, `embedding_stub` | `effects` row (CEO-A17, ENG-A18). Ready = no unembedded chunks for the source, no queued or running effects, no pending minion jobs, and no page with stale link extraction. |+| `e1_cold_start_to_first_progress_ms`, `e1_cold_start_to_first_stderr_ms`, `e1_wall_ms`, `newcomer_sync_runs`, `newcomer_to_search_hit_s`, `search_hit` | `newcomer` row (DX-A12). |++## Baseline (master `f4739fff`, v0.60.39.0, 2026-10-04)++Host: 4-vCPU Linux cloud machine, local Docker. 500-file rows have a+534-entry manifest (34 no-op deletes first, then 500 imports). Rows at+57 ms are time-boxed at 15 min and extrapolated; rows at ~0 ms ran to+completion. Raw JSON is not committed; rerun with the commands above.++| Row | RTT | Pages/min | Per-page p50 (import / delete) | Admission→commit p50 / p90 | Round trips per page | Notes |+|---|---|---|---|---|---|---|+| `cli` (reporter loop) | 57 | **3.4** | 15.5 s | 4.4 / 5.4 s | 487 | 52 runs, 1 page per run, every run exits `writer_pending`; full backlog ≈ 2.6 h |+| `reentry` (one process) | 57 | **4.2** | 11.7 s | 4.3 / 4.8 s | 682 | 73 passes, all `writer_pending`; full backlog ≈ 2.1 h |+| `unmanaged` | 57 | **50.9** | — | — | 77 | finished: 500 pages in 9.8 min |+| `serve` (resident serve) | 57 | 3.5 | 15.5 s | 4.4 / 5.4 s | 519 | serve claimed 4 of 52 pages |+| `effects` (stub embeddings + serve) | 57 | 3.3 | 16.5 s | 4.4 / 5.2 s | 561 | not retrieval-ready: links stay stale until the checkpoint |+| `foreground` | 57 | 2.3 | 23.7 s (27.0 / 23.6 s) | 14.6 / 15.8 s | 2137 | 15 of 73 runs failed `storage_error` (admission contention) |+| `all` (2 sources) | 57 | **0** | — | — | — | 89 runs over 15 min: 61 claims, 0 publications |+| `cli` 10k (300 words, 300 receipts) | 57 | 3.4 | 15.6 s | 4.4 / 5.4 s | 488 | **full backlog ≈ 49.3 h** |+| `cli` | ~0 | 350 | 131 ms (131 / 290 ms) | 38 / 46 ms | 387 | one run |+| `reentry` | ~0 | 345 | 131 ms | 38 / 47 ms | 387 | |+| `unmanaged` | ~0 | 4,711 | — | — | 77 | 6.4 s for 500 pages |+| `serve` | ~0 | 350 | 131 ms | 38 / 46 ms | 387 | serve claimed 0 of 534 |+| `effects` | ~0 | 349 | 131 ms | 38 / 45 ms | 472 | retrieval-ready when the sync ended |+| `foreground` | ~0 | 328 | 132 ms | 37 / 49 ms | 482 | foreground p95 254 → 244 ms |+| `all` (2 sources) | ~0 | 545 | 90 ms | 86 / 94 ms | 368 | |+| `cli` 10k | ~0 | 440 | 132 ms | 39 / 44 ms | 306 | 8,795 committed in a 20 min run, steady at 384 to 455 per minute; full backlog ≈ 23 min. The trace has no checkpoint or link-extraction phase, so it reads lower than the 500-file row. |++Readings from the table and the traces:++- **Network-bound (CEO-A26).** The same code runs 100x faster near+ the database (350 vs 3.4 pages/min). Until the fix ships, the+ workaround is to run the catch-up from a host near the database, or+ to loop `gbrain sync --source <id> --no-pull` until `synced`.+- **Drain loop (CEO-A2).** Re-entering in one process is 4.2 vs 3.4+ pages/min. That gain is the removed CLI start: 110 round trips and+ 6.9 s from first statement to first admission per run, including 8+ connection handshakes of ~187 ms each. The drain loop is UX plus a+ ~25% gain, not the throughput lever.+- **Unmanaged (CEO-A6, CEO-A27).** Unmanaged sync is 15x managed at+ 57 ms (50.9 vs 3.4) and 13x at ~0 ms. That crosses CEO-A27's 10x+ trigger, so the decision record below compares a worktree fence+ plus bulk import and reconcile.+- **No-op deletes.** At ~0 ms a no-op delete costs 2.2x an import+ (290 vs 131 ms). At 57 ms they cost about the same (23.6 vs 27.0 s+ in the foreground row). They are 34 of 10,034 entries at issue+ scale, so the waiver matters for correctness of the counts and for+ small backlogs, not for the 10k throughput.+- **Growth and headroom (CEO-A25).** Database growth is about 13 to+ 21 KB per committed page (47 KB with embeddings); the 10k slice was too short to measure+ through autovacuum. Each request reserves 16,384 terminal bytes. A+ full 10,034-entry backlog reserves about 164 MB, about 10% of the+ default 1.5 GiB per-principal terminal budget and 4% of the+ per-principal lifetime IDs. Capacity is not a constraint.+- **Effects (CEO-A17, ENG-A18).** With a resident serve, embeddings+ keep pace with sync: 2 unembedded chunks when the last CLI run exited, 0 shortly after. Link+ extraction runs only after the checkpoint (`withLinks`), so a+ catch-up stays not retrieval-ready for links until the whole manifest+ commits. Without a resident consumer, the CLI leaves effects queued+ when it exits (a 20-file smoke run left 7 effects and 24 unembedded+ chunks pending for 10 min). This is the CEO-A3 effects backlog that+ the result must report with its drain command.+- **Newcomer and E1 (DX-A12).** Master prints no progress line before+ exiting. At 57 ms the first stderr line, the watchdog notice, arrives+ after 300 ms; the first run takes 21.6 s. The 5-page newcomer path+ needs 6 sync runs and 146 s to a search hit (3.9 s and 1 run at+ ~0 ms).++## CEO-A1: round-trip budget (baseline)++Budget: 150 pages/min is 400 ms per committed page. At 57 ms RTT+(59.6 ms measured) that allows **about 7 sequential round trips** per+page, end to end.++Measured sequential round trips per committed page, two ways:++1. **Wall time over RTT.** (per-page p50 at 57 ms − per-page p50 at+ ~0 ms) / RTT:+ - CLI loop: (15,529 − 131) / 59.6 = **258**.+ - Re-entry: (11,675 − 131) / 60.1 = **192**.+2. **Phase timing in the re-entry trace** (p50 over 65 pages):+ - admission → claim: 1.09 s = 18 RTT (the consumer's next tick and+ claim).+ - claim → `completeWrite`: 6.33 s = 105 RTT. This contains the+ publication transaction: 5.06 s, 77 to 83 round trips, 34 of them+ describes.+ - `completeWrite` → next admission: 4.13 s = 69 RTT (wait detection,+ cursor save, `writer_pending` return, re-entry prologue, freeze,+ screen, admission).+ - Total ≈ 192 RTT, matching the first method.++The baseline is 192 to 258 round trips per page, 27 to 37x the budget.+The publication transaction alone is 11x the budget. Even with every+describe round trip removed (about 43 left) and the counter and guard+locks set-based (ENG-A13: 12 counter and 9 guard statements become 4),+one page's publication stays well above 7 round trips. Pipelined+admission (2.2) is capped at one page per publication time, so at 57 ms+it cannot pass roughly 25 to 40 pages/min. Unless the post-diet+measurement shows publication at 400 ms or less per page (CEO-A9), the+rule selects 2.3 multi-page publication with set-based apply. The rule+re-runs on the post-Phase-1 and post-2.1 rows below.++## Top statements by round trips per committed page++`cli` at 57 ms, all processes, describe round trips included, per+committed page (487.5 total; 40% are describes):++| RT/page | of which describe | Statement |+|---|---|---|+| 59.8 | 29.9 | `SELECT * FROM persistence_requests WHERE id=$1::uuid` (waitForWrite poll, 50 ms) |+| 20.0 | 10.0 | `SELECT c.* FROM persistence_topology_changes c JOIN persistence_worktrees ...` (consumer topology recovery) |+| 17.3 | 0 | `SELECT set_config('gbrain.persistence_protocol','2',true)` |+| 16.0 | 8.0 | `INSERT INTO persistence_counters(key) VALUES ($1) ON CONFLICT DO NOTHING` |+| 16.0 | 8.0 | `SELECT * FROM persistence_counters WHERE key=$1 FOR UPDATE` |+| 15.0 / 15.0 | 0 | `begin` / `commit` |+| 12.0 | 6.0 | `SELECT r.* FROM persistence_requests r LEFT JOIN persistence_worktrees w ... state='queued'` (claim attempts) |+| 12.0 | 6.0 | `SELECT lane,revoked_at,grant_ceiling FROM persistence_local_writers WHERE id=$1::uuid` |+| 10.0 each | 5.0 | source/worktree binding join; `DISTINCT ON (local_path)` root scan; `EXISTS` claimable probe; recovery scan; projection-job scan; `WITH expired AS` claim expiry; worktree-refresh scan; two effects scans |+| 9.4 | 4.7 | `WITH chosen AS (SELECT p.* FROM pages p ...)` page snapshot |+| 8.0 | 4.0 | `SELECT completed_keys FROM op_checkpoints ...` cursor read |+| 8.0 + 8.0 | 0 | connection handshakes + postgres.js array-type probe (new process, 8 connections) |++Inside the publication transaction (re-entry at 57 ms, p50 77 round+trips per page, 34 describes, holding `persistence_counters` FOR+UPDATE for its whole 5 s):++- `persistence_counters`: 6 `INSERT ... ON CONFLICT` and 6 `SELECT ...+ FOR UPDATE`, 24 round trips with describes.+- Page lock trio, 2.9 times each: `INSERT INTO page_write_guards`,+ `SELECT ... page_write_guards ... FOR UPDATE` and `SELECT id FROM+ pages ... FOR UPDATE`, 17 round trips.+- 2.9 `sources FOR SHARE`, 2.5 + 1.9 page snapshots, 2.0 binding joins,+ 2.0 `persistence_requests FOR UPDATE`, 2.0 + 3.5 `set_config`.+- One each of: the worktree, source, local-writer and brain+ `FOR SHARE` checks, the cursor check, the `source_path` read, the+ effects-bytes sum and `completeWrite`.++Re-entry prologue per `performSync` pass (ENG-A11): 58 round trips+(about 30 statements plus describes) and 1.9 s before the cursor read.+These are the brain and source mode probes, company-brain profile,+local-writer registration, binding and refresh checks and authority.+Hoisting them across passes saves them on every pass.++### The describe round trip++postgres.js sends every `sql.unsafe(text, params)` unprepared (its+`unsafe` default is `prepare: false`). An unprepared statement with+parameters is sent as Parse/Describe/Flush, waits for the parameter+types, then sends Bind/Execute/Sync. That is two round trips per+statement. `executeRaw`, `tx.unsafe` and the persistence layer all use+this path, so 40% of all round trips at 57 ms are describes+(10,277 of 25,340 in the `cli` row; 85,069 of 206,455 at ~0 ms).+Passing `prepare: true` where the connection allows it (not on a+transaction-mode PgBouncer), or sending explicit parameter types, would+roughly halve the round trips of every managed write. This lever is not+in the plan. It belongs in the 2.1 diet, and it also speeds up+foreground writes.++## CEO-A4: lock waits and the guard holder++The issue's 2.3 s `page_write_guards ... FOR UPDATE` wait did not+reproduce on a single host. Every guard statement took one round trip+(p50 59.7 ms, max 92 ms at 57 ms; max 3.8 ms at ~0 ms), with or+without a resident serve. The guard's cost is its count (about 9+guard-trio statements per page across screen, admission and+publication), not a wait. The reporter's 2.3 s is most likely the same+publication-lock queueing shown below, measured on a busier+deployment. That inference is not proven.++The lock waits that were sampled (100 ms samples):++- **Lease renewal behind its own publication (~0.75 s per page).**+ `cli` had 393 samples, `reentry` 476, `serve` 391 and 10k 400.+ 92 to 99% of them are the consumer's claim-lease renewal+ (`UPDATE persistence_requests SET claim_expires_at=...`). It waits+ on the row lock that the same process's publication transaction+ holds on that request (holder states `idle in transaction` and+ `active`, statements `persistence_counters ... FOR UPDATE`, counter+ `INSERT`, `set_config`, timeline writes). The cost is self-contention+ and one blocked connection, not a cross-process holder.+- **Brain-wide `persistence_counters` lock (the real contention).** The+ publication transaction locks the brain counter row first and holds+ it for 77 round trips (5 s at 57 ms). Any other admission or+ publication with the default 1 s `lock_timeout` then fails `55P03`:+ - `foreground`: 30 `55P03` and 15 `57014` in the catch-up process,+ and 15 of 73 catch-up runs ended `storage_error` ("admission is+ temporarily blocked by database contention"). The foreground writer+ took 3 `55P03` that it retried internally.+ - `all`: two worktrees publish in parallel. One publication times out+ on the counter lock and releases its claim. The other publication+ is still running when the CLI's 5 s wait expires and the process+ exits. The next process re-claims after the lease lapses. The+ result is a livelock: 89 runs, 61 claims, **0 publications** in+ 15 min.++This is ENG-A5's constraint, measured: no publication path can hold+the counter row across a multi-round-trip transaction at 57 ms. ENG-A13+(lock the counter last, set-based) and the group publish budget (ENG-A5)+are required for `--all` (CEO-A8) and for foreground fairness, not+optional.++## CEO-A3 / CEO-A29: the CLI's in-process consumer++- **Background share.** The consumer's background work (effects+ scans, projection jobs, topology recovery, root refresh, recovery and+ expiry scans, idle probes, receipt maintenance) is 22.1% of the+ sync process's statements at 57 ms (`cli`: 64 of 290 statements per+ page) and 33.5% in `reentry`. It is only 8.7% at ~0 ms, because the+ background loop runs on a timer, so its share grows with wall time+ per page. Waits add 10 to 11% (`wait-poll`) at 57 ms.+- **Not the lock holder.** The background work is not the sampled+ lock holder (see CEO-A4).+- **Gate.** CEO-A29's gate is ">= 20% of per-page statements or the+ guard-lock holder", and the 57 ms rows pass its first arm (22.1% CLI+ loop, 33.5% re-entry). At ~0 ms it fails (8.7%). Because these+ statements run concurrently with the critical path, removing them+ saves server load and pool connections more than sequential time.+ Phase 1 should re-measure their effect on pages/min before building+ publication-only mode.+- **Claim races (CEO-A3).** No row released a claim as `writer_busy`.+ An idle resident `serve` backs off and claimed only 4 of 52 pages at+ 57 ms (0 of 534 at ~0 ms). An active second consumer (the+ `foreground` writer process) claimed 68 of 73 catch-up requests at+ 57 ms, and the CLI's waiter still resolved by polling. Races cost+ nothing measurable, so no claim preference is needed (the 10% rule).+- **ENG-A9.** `cli_is_owner_host` is `true` in every managed row. The+ bench claims from the same `GBRAIN_HOME`, so the CLI host is the+ worktree owner host.++## Foreground writes during catch-up (ENG-A5, CEO-A23)++| RTT | Idle p50 / p95 | During catch-up p50 / p95 | Foreground failures | Catch-up failures |+|---|---|---|---|---|+| 57 ms | 19.1 / 19.7 s | 23.6 / 29.6 s | 0 (3 `55P03` retried) | 15 of 73 runs `storage_error`; 30 `55P03` and 15 `57014` |+| ~0 ms | 245 / 254 ms | 127 / 244 ms | 0 | 0 |++At 57 ms, a single `put_page` costs about 19 s even with no catch-up+running. Catch-up raises its p95 by about 10 s, against the release+constraint of ≤ 1 s. The catch-up itself loses runs to admission+contention.++## Decision-rule inputs (CEO-A1, CEO-A9, CEO-A27)++Round trips per committed page at 57 ms. Measured values are labelled+measured; everything else is an estimate from the traces above, to be+replaced by measured rows as each phase lands.++| Mechanism | RT per page | Pages/min at 57 ms | Basis |+|---|---|---|---|+| Today, CLI loop | 258 | 3.4 | measured |+| Today, one process (drain loop, Phase 1.1) | 192 | 4.2 | measured (`reentry`) |+| + no describe round trips (prepared or typed `executeRaw`) | ~115 | ~8 | estimate: 40% of round trips are describes |+| + 2.1 diet (set-based counters and guards, hoisted re-entry context, narrow waits) | ~70 to 90 | ~11 to 14 | estimate |+| 2.2 pipelined admission, K=25, one page per publication | ≥ 40 (publication only) | ≤ 25 | estimate: pipelining hides admission, not publication |+| 2.3 bulk publication, B=25, set-based apply | ~5 to 8 (≈ 80/B fixed + 2 to 4 per page) | ~125 to 200 | estimate; needs set-based apply and the ENG-A5 counter order |+| Worktree fence + bulk import + reconcile (CEO-A27 alternative) | ~20 sequential (77 traced, concurrent) | 50.9 | measured as unmanaged sync; leaves the journal, receipts and per-page effects to a reconcile pass |+| plpgsql publication function | — | — | rejected (CEO-A27): duplicates TypeScript publication logic and costs engine parity |++Recommendation for Phase 2, read from the rule: build 2.1, including+the describe fix and the counter-lock order. Then measure, and expect+the rule to select 2.3. Skip 2.2 unless post-2.1 publication is+400 ms or less per page.++## Post-Phase-1 rows (placeholder)++Root thread: rerun the two commands above on the integrated branch and+fill this table. It covers the drain loop, waivers, narrow waits and+the waived counts in `entries_waived`.++| Row | RTT | Pages/min | Per-page p50 | RT per page | Notes |+|---|---|---|---|---|---|+| `cli` | 57 | _TBD_ | | | |+| `reentry` | 57 | _TBD_ | | | |+| `foreground` | 57 | _TBD_ | | | p95 delta, `55P03` count |+| `all` | 57 | _TBD_ | | | must be > 0 |+| `cli` 10k | 57 | _TBD_ | | | ship-gate row |+| `cli` | ~0 | _TBD_ | | | |++## Post-diet (2.1) and Phase 2 rows (placeholder)++| Row | RTT | Pages/min | Per-page p50 | RT per page | Mechanism selected |+|---|---|---|---|---|---|+| `cli` | 57 | _TBD_ | | | |+| `cli` 10k | 57 | _TBD_ | | | |+| `foreground` | 57 | _TBD_ | | | |+| `effects` | 57 | _TBD_ | | | retrieval-ready time |diff --git a/scripts/bench/managed-sync-catchup-lib.ts b/scripts/bench/managed-sync-catchup-lib.tsnew file mode 100644index 0000000000..955fb3f4e7--- /dev/null+++ b/scripts/bench/managed-sync-catchup-lib.ts@@ -0,0 +1,251 @@+/**+ * Helpers for scripts/bench/managed-sync-catchup.ts: the Docker Postgres+ * (pg_stat_statements) and toxiproxy latency harness, the stub OpenAI+ * embeddings server, the pg_locks sampler and the SQL-trace analysis.+ * Every helper binds loopback only.+ */+import { readFileSync, existsSync } from 'node:fs';+import { createServer, type Server } from 'node:http';+import { spawnSync } from 'node:child_process';+import postgres from '#postgres';++export type Sql = ReturnType<typeof postgres>;+/** Prefix on every statement the bench itself sends to a measured database, so pg_stat_statements totals exclude it. */+export const BENCH_SQL = '/* gbrain-bench */';+export const round1 = (n: number) => Math.round(n * 10) / 10;+export function pct(xs: number[], p: number): number | null {+ if (!xs.length) return null;+ const s = [...xs].sort((a, b) => a - b);+ return round1(s[Math.min(s.length - 1, Math.floor((p / 100) * s.length))]!);+}+export const sum = (xs: number[]) => xs.reduce((a, b) => a + b, 0);++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();+}++export interface Harness { adminUrl: string; proxyUrl: (db: string) => string; directUrl: (db: string) => string; setRtt: (ms: number) => Promise<void>; stop: () => void }++/**+ * 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.+ */+export async function startHarness(opts: { pgPort: number; proxyPort: number; apiPort: number; adminUrl?: string; keep: boolean }): Promise<Harness> {+ const started: string[] = [];+ let upstreamHost = '127.0.0.1';+ let upstreamPort = opts.pgPort;+ let adminUrl = opts.adminUrl;+ if (!adminUrl) {+ if (!docker(['ps', '-q', '-f', 'name=^gbrain-bench-pg$'])) {+ docker(['rm', '-f', 'gbrain-bench-pg'], true);+ docker(['run', '-d', '--name', 'gbrain-bench-pg', '-p', `127.0.0.1:${opts.pgPort}:5432`, '-e', 'POSTGRES_PASSWORD=postgres',+ '--shm-size=1g', 'pgvector/pgvector:pg16', '-c', 'shared_preload_libraries=pg_stat_statements', '-c', 'max_connections=400',+ '-c', 'pg_stat_statements.max=10000', '-c', 'fsync=on']);+ started.push('gbrain-bench-pg');+ }+ adminUrl = `postgresql://postgres:[email protected]:${opts.pgPort}/postgres`;+ } else {+ const u = new URL(adminUrl.replace(/^postgres(ql)?:/, 'http:'));+ upstreamHost = u.hostname; upstreamPort = Number(u.port || 5432);+ }+ if (!docker(['ps', '-q', '-f', 'name=^gbrain-bench-toxiproxy$'])) {+ docker(['rm', '-f', 'gbrain-bench-toxiproxy'], true);+ docker(['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');+ }+ const api = `http://127.0.0.1:${opts.apiPort}`;+ for (let i = 0; ; i++) {+ try {+ const probe = postgres(adminUrl, { max: 1, onnotice: () => {}, connect_timeout: 2 });+ await probe`SELECT 1`; await probe.end();+ if ((await fetch(`${api}/version`)).ok) break;+ } catch (error) { if (i > 60) throw error; }+ await Bun.sleep(1000);+ }+ const proxy = `pg-${opts.proxyPort}`;+ await fetch(`${api}/proxies/${proxy}`, { method: 'DELETE' });+ const created = await fetch(`${api}/proxies`, { method: 'POST', body: JSON.stringify({ name: proxy, listen: `127.0.0.1:${opts.proxyPort}`, upstream: `${upstreamHost}:${upstreamPort}`, enabled: true }) });+ if (!created.ok) throw new Error(`toxiproxy proxy create failed: ${await created.text()}`);+ const 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,+ directUrl: db => withDb(adminUrl!, db),+ proxyUrl: db => withDb(proxied.toString(), db),+ async setRtt(ms: number) {+ for (const stream of ['upstream', 'downstream']) {+ await fetch(`${api}/proxies/${proxy}/toxics/lat_${stream}`, { method: 'DELETE' });+ if (ms <= 0) continue;+ const r = await fetch(`${api}/proxies/${proxy}/toxics`, { method: 'POST', body: JSON.stringify({ name: `lat_${stream}`, type: 'latency', stream,+ toxicity: 1, attributes: { latency: Math.round(ms / 2), jitter: 0 } }) });+ if (!r.ok) throw new Error(`toxiproxy toxic failed: ${await r.text()}`);+ }+ },+ stop() {+ void fetch(`${api}/proxies/${proxy}`, { method: 'DELETE' }).catch(() => undefined);+ if (!opts.keep) for (const name of started) docker(['rm', '-f', name], true);+ },+ };+}++/** 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: () => {} });+ try {+ await sql`SELECT 1`;+ const xs: number[] = [];+ for (let i = 0; i < 20; i++) { const t = performance.now(); await sql.unsafe(`${BENCH_SQL} SELECT 1`).simple(); xs.push(performance.now() - t); }+ return pct(xs, 50)!;+ } finally { await sql.end(); }+}++/** A loopback OpenAI `/v1/embeddings` stub: fixed latency, a concurrency cap answered with 429 + retry-after, deterministic vectors. */+export function startEmbeddingStub(opts: { latencyMs: number; maxConcurrent: number; dims: number }): Promise<{ url: string; stats: { calls: number; inputs: number; limited: number }; close: () => void }> {+ const stats = { calls: 0, inputs: 0, limited: 0 };+ let active = 0;+ const server: Server = createServer((req, res) => {+ let body = '';+ req.on('data', c => { body += c; });+ req.on('end', async () => {+ if (!req.url?.endsWith('/embeddings')) { res.writeHead(404).end(); return; }+ if (active >= opts.maxConcurrent) {+ stats.limited++;+ res.writeHead(429, { 'content-type': 'application/json', 'retry-after-ms': '500', 'retry-after': '1' })+ .end(JSON.stringify({ error: { message: 'Rate limit reached (bench stub)', type: 'rate_limit_error', code: 'rate_limit_exceeded' } }));+ return;+ }+ active++;+ try {+ const parsed = JSON.parse(body || '{}') as { input?: string | string[]; dimensions?: number; model?: string };+ const inputs = Array.isArray(parsed.input) ? parsed.input : [parsed.input ?? ''];+ const dims = parsed.dimensions ?? opts.dims;+ stats.calls++; stats.inputs += inputs.length;+ await Bun.sleep(opts.latencyMs);+ const data = inputs.map((text, index) => {+ const v = new Array<number>(dims).fill(0);+ for (let i = 0; i < String(text).length; i++) v[(String(text).charCodeAt(i) * 31 + i) % dims] += 1;+ const norm = Math.sqrt(v.reduce((a, b) => a + b * b, 0)) || 1;+ return { object: 'embedding', index, embedding: v.map(x => x / norm) };+ });+ res.writeHead(200, { 'content-type': 'application/json' }).end(JSON.stringify({ object: 'list', data, model: parsed.model ?? 'stub',+ usage: { prompt_tokens: inputs.length * 50, total_tokens: inputs.length * 50 } }));+ } finally { active--; }+ });+ });+ return new Promise(resolve => server.listen(0, '127.0.0.1', () => {+ const port = (server.address() as { port: number }).port;+ resolve({ url: `http://127.0.0.1:${port}/v1`, stats, close: () => server.close() });+ }));+}++export interface LockSample { t: number; waiting_app: string; waiting_query: string; wait_ms: number; blocker_app: string; blocker_state: string; blocker_query: string; blocker_xact_ms: number }++/** Samples lock waits in `db` every `everyMs` from an admin connection (not proxied, not traced). */+export function startLockSampler(adminUrl: string, db: string, everyMs = 100): { stop: () => Promise<LockSample[]> } {+ const sql = postgres(adminUrl, { max: 1, onnotice: () => {} });+ const samples: LockSample[] = [];+ let running = true;+ const loop = (async () => {+ while (running) {+ try {+ const rows = await sql.unsafe(`${BENCH_SQL} SELECT w.application_name AS waiting_app, left(w.query, 400) AS waiting_query,+ (extract(epoch FROM clock_timestamp() - w.query_start) * 1000)::float8 AS wait_ms,+ coalesce(b.application_name,'') AS blocker_app, coalesce(b.state,'') AS blocker_state, left(coalesce(b.query,''), 400) AS blocker_query,+ coalesce((extract(epoch FROM clock_timestamp() - b.xact_start) * 1000)::float8, 0) AS blocker_xact_ms+ FROM pg_stat_activity w CROSS JOIN LATERAL unnest(pg_blocking_pids(w.pid)) AS bp(pid)+ LEFT JOIN pg_stat_activity b ON b.pid = bp.pid+ WHERE w.datname = $1 AND w.wait_event_type = 'Lock'`, [db]);+ const t = Date.now();+ for (const r of rows) samples.push({ t, ...(r as unknown as Omit<LockSample, 't'>) });+ } catch { /* sampling is best effort */ }+ await Bun.sleep(everyMs);+ }+ })();+ return { async stop() { running = false; await loop; await sql.end(); return samples; } };+}++export interface TraceRecord { t: number; ms: number; pid: number; label: string; pool: string; conn: number; backend: number; kind: string; sql: string; err?: string }++/** Reads a trace, interning statement text so a multi-million-record trace keeps one copy of each statement. */+export function readTrace(file: string, keep: (r: TraceRecord) => boolean = () => true): TraceRecord[] {+ if (!existsSync(file)) return [];+ const interned = new Map<string, string>();+ const out: TraceRecord[] = [];+ const text = readFileSync(file, 'utf8');+ for (let at = 0; at < text.length;) {+ const end = text.indexOf('\n', at);+ const line = text.slice(at, end < 0 ? text.length : end);+ at = end < 0 ? text.length : end + 1;+ if (!line) continue;+ const r = JSON.parse(line) as TraceRecord;+ if (!keep(r)) continue;+ const sql = interned.get(r.sql);+ if (sql === undefined) interned.set(r.sql, r.sql); else r.sql = sql;+ out.push(r);+ }+ return out;+}++const memo = <T>(fn: (s: string) => T): ((s: string) => T) => {+ const cache = new Map<string, T>();+ return s => { let v = cache.get(s); if (v === undefined) { v = fn(s); cache.set(s, v); } return v; };+};++/** Normalizes a statement for grouping: whitespace collapsed, literals and IN-lists folded, cut to 160 chars. */+export const normalizeSql = memo((sql: string): string => {+ return sql.replace(/\s+/g, ' ').replace(/'(?:[^']|'')*'/g, "'?'").replace(/\b\d+\b/g, 'N').replace(/\$\d+/g, '$n').trim().slice(0, 160);+});+/** Whitespace-collapsed statement text, memoized. */+export const flatSql = memo((sql: string) => sql.replace(/\s+/g, ' ').trim());++/** Process family from a trace label: `cli-sync`, `serve`, `reentry`, `foreground`, ... */+export const family = memo((label: string) => label.replace(/[:#].*$/, ''));++export interface StatementGroup { sql: string; count: number; total_ms: number; per_page: number; by_process: Record<string, number> }+export function groupStatements(records: TraceRecord[], pages: number, top = 40): StatementGroup[] {+ const groups = new Map<string, StatementGroup>();+ for (const r of records) {+ const key = r.kind === 'describe' ? `[describe] ${normalizeSql(r.sql)}` : normalizeSql(r.sql);+ const g = groups.get(key) ?? { sql: key, count: 0, total_ms: 0, per_page: 0, by_process: {} };+ g.count++; g.total_ms += r.ms; g.by_process[family(r.label)] = (g.by_process[family(r.label)] ?? 0) + 1;+ groups.set(key, g);+ }+ return [...groups.values()].map(g => ({ ...g, total_ms: round1(g.total_ms), per_page: pages ? round1(g.count / pages) : 0 }))+ .sort((a, b) => b.count - a.count).slice(0, top);+}++const TXN_CONTROL = /^(begin|commit|rollback|savepoint|release|start transaction|end)\b/i;+/** pg_stat_statements for one database, without the bench's own statements; `calls_ex_txn` drops transaction control, which pg_stat_statements does not count reliably. */+export async function readPgStatStatements(sql: Sql, db: string): Promise<{ available: boolean; calls: number; calls_ex_txn: number; total_ms: number; top: Array<{ query: string; calls: number; total_ms: number }> }> {+ try {+ const rows = (await sql.unsafe(`${BENCH_SQL} SELECT left(regexp_replace(s.query, '\\s+', ' ', 'g'), 200) AS query, s.calls::float8 AS calls, s.total_exec_time::float8 AS total_ms+ FROM pg_stat_statements s JOIN pg_database d ON d.oid = s.dbid WHERE d.datname = $1 ORDER BY s.calls DESC`, [db]) as unknown as Array<{ query: string; calls: number; total_ms: number }>)+ .filter(r => !r.query.startsWith(BENCH_SQL));+ return { available: true, calls: sum(rows.map(r => Number(r.calls))), calls_ex_txn: sum(rows.filter(r => !TXN_CONTROL.test(r.query.trim())).map(r => Number(r.calls))),+ total_ms: round1(sum(rows.map(r => Number(r.total_ms)))),+ top: rows.slice(0, 25).map(r => ({ query: r.query, calls: Number(r.calls), total_ms: round1(Number(r.total_ms)) })) };+ } catch { return { available: false, calls: 0, calls_ex_txn: 0, total_ms: 0, top: [] }; }+}+export const isTxnControl = memo((sql: string) => TXN_CONTROL.test(sql.trim()));++/**+ * Which part of the system issued a statement, from its text. `consumer-background`+ * is the in-process PersistenceConsumer's work that a publication-only consumer would+ * skip (effects drain, projection, topology recovery, root refresh, recovery and+ * expiry scans, idle probes, receipt maintenance); `wait-poll` is waitForWrite.+ */+export const classify = memo((sql: string): string => {+ const s = flatSql(sql);+ if (/^SELECT \* FROM persistence_requests WHERE id=\$1::uuid$/.test(s)) return 'wait-poll';+ if (/persistence_effects e (LEFT )?JOIN persistence_worktrees|page_projection_jobs|persistence_topology_changes c JOIN|DISTINCT ON \(local_path\)|shared_skill_packs|persistence_worktree_refreshes f JOIN|r\.recovery IS NOT NULL AND NOT\(r\.worktree_id|^WITH expired AS|writer_pool_capacity|^SELECT \( EXISTS|^SELECT EXISTS \(SELECT 1 FROM persistence_requests r LEFT JOIN|NOT compacted|brain_id,enabled,to_jsonb\(persistence_brain\)/.test(s)) return 'consumer-background';+ if (/^(begin|commit|rollback|savepoint|release)/i.test(s) || /^SELECT set_config\('(gbrain\.persistence_protocol|synchronous_commit)'/.test(s)) return 'txn-control';+ if (/page_write_guards|persistence_counters|FROM pages WHERE source_id=\$1 AND slug=\$2 FOR UPDATE/.test(s)) return 'guards+counters';+ if (/op_checkpoints/.test(s)) return 'cursor';+ if (/persistence_requests/.test(s)) return 'journal';+ if (/^<connect>$/.test(s) || /pg_catalog\.pg_type/.test(s)) return 'connection-setup';+ if (/\b(pages|content_chunks|page_versions|links|timeline_entries|tags|raw_data|facts|takes|slug_aliases|page_aliases)\b/.test(s)) return 'page-data';+ return 'other-control';+});diff --git a/scripts/bench/managed-sync-catchup.ts b/scripts/bench/managed-sync-catchup.tsnew file mode 100644index 0000000000..20b909dc7d--- /dev/null+++ b/scripts/bench/managed-sync-catchup.ts@@ -0,0 +1,651 @@+#!/usr/bin/env bun+/**+ * #5984 managed-sync catch-up bench. Opt-in, never run in CI. Record and+ * 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]+ * [--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]+ *+ * 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+ * across both directions (every helper binds 127.0.0.1). Per row and RTT it+ * clones a fresh database from a template initialized by this checkout, builds+ * a git source in classic mode (history pages plus `--deletes` pages that are+ * imported, then soft-deleted), commits the backlog (`--files` new pages and+ * the deletion of the soft-deleted files), activates managed persistence+ * through the real `gbrain sources writer claim/activate` CLI, and points the+ * brain at the proxy. Then it drives the catch-up:+ *+ * cli the reporter's workaround: `gbrain sync --source <id> --no-pull --no-embed --json` re-run until synced+ * reentry one long-lived process re-entering performSync until synced (250 ms pause, like the PGLite delegate)+ * unmanaged classic sync of the same corpus (no activation), one CLI run+ * serve `cli` with a resident `gbrain serve --http` on the same brain+ * effects `cli` without --no-embed against a loopback stub /v1/embeddings (200 ms, 4 concurrent, 429 beyond),+ * 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+ * 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+ *+ * Every gbrain process runs with GBRAIN_SQL_TRACE (src/core/sql-trace.ts), so+ * 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.+ */+import { appendFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { dirname, join, resolve } from 'node:path';+import { execFileSync } from 'node:child_process';+import { randomBytes } from 'node:crypto';+import postgres from '#postgres';+import { generateScaleFixture } from '../scale/fixture.ts';+import { DEFAULT_JOURNAL_LIMITS } from '../../src/core/persistence/model.ts';+import {+ BENCH_SQL, classify, family, flatSql, isTxnControl, groupStatements, measureRtt, pct, readPgStatStatements, readTrace, round1, startEmbeddingStub, startHarness, startLockSampler, sum,+ normalizeSql, type Harness, type LockSample, type TraceRecord,+} from './managed-sync-catchup-lib.ts';++const REPO = resolve(import.meta.dir, '../..');+const CLI = join(REPO, 'src/cli.ts');+function flag(name: string, fallback: string): string {+ const i = process.argv.indexOf(`--${name}`);+ return i >= 0 && process.argv[i + 1] ? process.argv[i + 1]! : fallback;+}+const worker = flag('worker', '');+if (worker) await runWorker(worker);++const FILES = Number(flag('files', '500'));+const DELETES = Number(flag('deletes', '34'));+const HISTORY = Number(flag('history', '0'));+const RECEIPT_HISTORY = Number(flag('receipt-history', '0'));+const PAD_WORDS = Number(flag('pad-words', '0'));+const SEED = Number(flag('seed', '1'));+const RTTS = flag('rtt', '57,0').split(',').map(Number);+const ROWS = flag('rows', 'cli,reentry,unmanaged,serve,effects,foreground,all,newcomer').split(',');+const MAX_MS = Number(flag('max-minutes', '20')) * 60_000;+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 SOURCE = 'bench';+const SOURCE_B = 'bench-b';+const work = mkdtempSync(join(tmpdir(), 'gbrain-catchup-'));++function gitDescribe(): string {+ try { return execFileSync('git', ['-C', REPO, 'rev-parse', '--abbrev-ref', 'HEAD'], { encoding: 'utf8' }).trim() + '@' + execFileSync('git', ['-C', REPO, 'rev-parse', '--short', 'HEAD'], { encoding: 'utf8' }).trim(); }+ catch { return 'unknown'; }+}+function git(root: string, ...args: string[]): string {+ return execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();+}+function commitAll(root: string, message: string): string {+ git(root, 'add', '-A');+ git(root, '-c', 'user.name=Bench Example', '-c', '[email protected]', 'commit', '-qm', message);+ return git(root, 'rev-parse', 'HEAD');+}+const log = (msg: string) => console.error(`[catchup ${new Date().toISOString().slice(11, 19)}] ${msg}`);++/** Child environment: hermetic home, no ambient database URL or provider keys. */+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 };+}++interface CliRun { killed: boolean; code: number; stdout: string; stderr: string; wallMs: number; firstStderrMs: number | null; firstProgressMs: number | null; json: Record<string, unknown> | null }+async function runCli(home: string, args: string[], env: Record<string, string | undefined> = {}, timeoutMs = 30 * 60_000): Promise<CliRun> {+ const started = performance.now();+ const child = Bun.spawn([process.execPath, CLI, ...args], { cwd: home, env: childEnv(home, env), stdin: 'ignore', stdout: 'pipe', stderr: 'pipe' });+ let killed = false;+ const timer = setTimeout(() => { killed = true; child.kill('SIGTERM'); setTimeout(() => child.kill('SIGKILL'), 30_000).unref(); }, timeoutMs);+ let firstStderrMs: number | null = null;+ let firstProgressMs: number | null = null;+ let stderr = '';+ const errReader = (async () => {+ const decoder = new TextDecoder();+ for await (const chunk of child.stderr as ReadableStream<Uint8Array>) {+ const at = performance.now() - started;+ if (firstStderrMs === null) firstStderrMs = at;+ stderr += decoder.decode(chunk);+ if (firstProgressMs === null && stderr.split('\n').some(l => /^\{.*"(event|phase)"/.test(l) || /\b\d+\/\d+\b.*(pages?|files?|entries)/i.test(l))) firstProgressMs = at;+ }+ })();+ const [stdout, code] = await Promise.all([new Response(child.stdout).text(), child.exited, errReader]);+ clearTimeout(timer);+ const lastJson = stdout.trim().split('\n').reverse().find(l => l.startsWith('{'));+ let json: Record<string, unknown> | null = null;+ try { json = JSON.parse(stdout); } catch { try { json = lastJson ? JSON.parse(lastJson) : null; } catch { json = null; } }+ return { killed, code, stdout, stderr, wallMs: performance.now() - started, firstStderrMs, firstProgressMs, json };+}+async function mustCli(home: string, args: string[], env: Record<string, string | undefined> = {}): Promise<CliRun> {+ const r = await runCli(home, args, env);+ if (r.code !== 0) throw new Error(`gbrain ${args.join(' ')} exited ${r.code}\nstdout: ${r.stdout.slice(-1500)}\nstderr: ${r.stderr.slice(-1500)}`);+ return r;+}++const fixture = generateScaleFixture({ pages: Math.max(20, 2 * (FILES + DELETES + HISTORY + RECEIPT_HISTORY) + 4), seed: SEED });+const padding = (i: number) => PAD_WORDS > 0+ ? '\n\n' + Array.from({ length: Math.ceil(PAD_WORDS / 24) }, (_, p) => `Paragraph ${p} of bench page ${i} carries ordinary note prose about meetings, plans, follow-ups and decisions that a real brain keeps.`).join('\n\n') + '\n'+ : '';+function writeFiles(root: string, files: Array<{ path: string; content: string }>): void {+ for (const p of files) { mkdirSync(dirname(join(root, p.path)), { recursive: true }); writeFileSync(join(root, p.path), p.content); }+}+function pagesFor(sourceIndex: number): Array<{ path: string; content: string }> {+ const sourceId = sourceIndex === 0 ? 'default' : 'scale-b';+ return fixture.pages.filter(p => p.sourceId === sourceId).map((p, i) => ({ path: `${p.slug}.md`, content: p.content + padding(i) }));+}++interface RowContext { name: string; rtt: number; db: string; home: string; roots: Record<string, string>; managed: boolean; trace: string; proxyUrl: string; directUrl: string; backlog: number }++let harness: Harness;+let template = '';+const created: string[] = [];++async function admin<T>(fn: (sql: ReturnType<typeof postgres>) => Promise<T>, db = 'postgres'): Promise<T> {+ const sql = postgres(harness.directUrl(db), { max: 1, onnotice: () => {} });+ try { return await fn(sql); } finally { await sql.end(); }+}++async function buildTemplate(): Promise<void> {+ template = `gbrain_bench_tmpl_${randomBytes(4).toString('hex')}`;+ await admin(sql => sql.unsafe(`CREATE DATABASE ${template}`));+ created.push(template);+ await admin(sql => sql.unsafe('CREATE EXTENSION IF NOT EXISTS pg_stat_statements'));+ const home = mkdtempSync(join(work, 'tmpl-'));+ writeConfig(home, harness.directUrl(template));+ const started = performance.now();+ process.env.GBRAIN_HOME = home;+ const { PostgresEngine } = await import('../../src/core/postgres-engine.ts');+ const engine = new PostgresEngine();+ await engine.connect({ database_url: harness.directUrl(template), poolSize: 2 });+ await engine.initSchema();+ await engine.disconnect();+ log(`template ${template} initialized in ${round1((performance.now() - started) / 1000)} s`);+}++function writeConfig(home: string, url: string, embeddings = false): void {+ mkdirSync(join(home, '.gbrain'), { recursive: true });+ mkdirSync(join(home, 'skills'), { recursive: true });+ if (!existsSync(join(home, 'skills', 'RESOLVER.md'))) writeFileSync(join(home, 'skills', 'RESOLVER.md'), '# Bench fixture skills\n');+ writeFileSync(join(home, '.gbrain', 'config.json'), JSON.stringify({ engine: 'postgres', database_url: url, self_upgrade: { mode: 'off' },+ ...(embeddings ? { embedding_model: 'openai:text-embedding-3-small', embedding_dimensions: 1024 } : { embedding_disabled: true }) }, null, 2) + '\n');+}++/** Fresh database, classic-mode history and soft-deleted pages, then the backlog commit; activation when managed. */+async function setupRow(name: string, rtt: number, opts: { managed: boolean; sources: number; files: number; deletes: number }): Promise<RowContext> {+ const db = `gbrain_bench_${name.replace(/\W/g, '_')}_${rtt}_${randomBytes(3).toString('hex')}`;+ await admin(sql => sql.unsafe(`CREATE DATABASE ${db} TEMPLATE ${template}`));+ created.push(db);+ const home = mkdtempSync(join(work, `${name}-${rtt}-`));+ writeConfig(home, harness.directUrl(db));+ const roots: Record<string, string> = {};+ const ids = opts.sources === 2 ? [SOURCE, SOURCE_B] : [SOURCE];+ const perSource = Math.ceil(opts.files / ids.length);+ const deletesPer = Math.ceil(opts.deletes / ids.length);+ const doomedBySource: Record<string, string[]> = {};+ const later: Record<string, { doomed: Array<{ path: string }>; backlog: Array<{ path: string; content: string }>; receipts: Array<{ path: string; content: string }> }> = {};+ for (const [s, id] of ids.entries()) {+ const root = join(home, `repo-${id}`);+ mkdirSync(root, { recursive: true });+ git(root, 'init', '-q');+ const pages = pagesFor(s);+ const history = pages.slice(0, HISTORY);+ const doomed = pages.slice(HISTORY, HISTORY + deletesPer);+ const backlog = pages.slice(HISTORY + deletesPer, HISTORY + deletesPer + perSource);+ const receipts = opts.managed ? pages.slice(HISTORY + deletesPer + perSource, HISTORY + deletesPer + perSource + RECEIPT_HISTORY) : [];+ writeFiles(root, [...history, ...doomed]);+ writeFileSync(join(root, 'README.md'), '# Bench source\n');+ commitAll(root, 'history');+ await mustCli(home, ['sources', 'add', id, '--path', root, '--no-federated']);+ await mustCli(home, ['sync', '--source', id, '--no-pull', '--no-embed', '--json'], { GBRAIN_SQL_TRACE_LABEL: 'setup' });+ doomedBySource[id] = doomed.map(p => p.path.replace(/\.md$/, ''));+ later[id] = { doomed, backlog, receipts };+ roots[id] = root;+ }+ await softDelete(home, harness.directUrl(db), doomedBySource);+ if (opts.managed) {+ for (const [id, root] of Object.entries(roots)) {+ const state = (await mustCli(home, ['sources', 'writer', 'status', '--json'])).json!.admin_state as string;+ await mustCli(home, ['sources', 'writer', 'claim', id, '--path', root, '--admin-intent', 'writer_claim', '--expected-state', state, '--json']);+ }+ const state = (await mustCli(home, ['sources', 'writer', 'status', '--json'])).json!.admin_state as string;+ const activated = await mustCli(home, ['sources', 'writer', 'activate', '--confirm-quiesced', '--admin-intent', 'writer_activate', '--expected-state', state, '--json']);+ if (activated.json?.enabled !== true) throw new Error(`activation did not enable managed persistence: ${activated.stdout}`);+ for (const [id, root] of Object.entries(roots)) {+ if (!later[id]!.receipts.length) continue;+ writeFiles(root, later[id]!.receipts);+ commitAll(root, 'receipt history');+ for (let i = 0; ; i++) {+ const r = await runCli(home, ['sync', '--source', id, '--no-pull', '--no-embed', '--json'], { GBRAIN_SQL_TRACE_LABEL: 'setup' });+ if (r.json?.sync_status !== 'partial') { if (r.code !== 0) throw new Error(`receipt-history sync failed: ${r.stdout.slice(-1500)}`); break; }+ if (i > 50) throw new Error('receipt-history sync did not converge');+ }+ }+ }+ for (const [id, root] of Object.entries(roots)) {+ for (const p of later[id]!.doomed) rmSync(join(root, p.path));+ writeFiles(root, later[id]!.backlog);+ commitAll(root, 'backlog');+ }+ writeConfig(home, harness.proxyUrl(db));+ return { name, rtt, db, home, roots, managed: opts.managed, trace: join(home, 'sql-trace.jsonl'), proxyUrl: harness.proxyUrl(db), directUrl: harness.directUrl(db),+ backlog: ids.length * (perSource + deletesPer) };+}++/** Soft-deletes the given pages in classic mode, before activation (the reporter's already-soft-deleted manifest deletes). */+async function softDelete(home: string, url: string, slugs: Record<string, string[]>): Promise<void> {+ process.env.GBRAIN_HOME = home;+ const { PostgresEngine } = await import('../../src/core/postgres-engine.ts');+ const engine = new PostgresEngine();+ await engine.connect({ database_url: url, poolSize: 2 });+ try {+ for (const [sourceId, list] of Object.entries(slugs)) for (const slug of list) {+ if (!(await engine.softDeletePage(slug, { sourceId }))) throw new Error(`soft delete of ${sourceId}/${slug} found no page`);+ }+ } finally { await engine.disconnect(); }+}++interface Driven { failures?: string[]; iterations: Array<{ wallMs: number; code: number; status: string | null; reason: string | null; firstStderrMs: number | null; firstProgressMs: number | null }>; done: boolean; timedOut: boolean; wallMs: number; error?: string; passes?: unknown[] }++/** Re-runs the CLI until the source reports synced, a failure stops it, or the time box ends. */+async function driveCli(row: RowContext, args: string[], extraEnv: Record<string, string> = {}): Promise<Driven> {+ const started = performance.now();+ const iterations: Driven['iterations'] = [];+ const failures: string[] = [];+ let stalled = 0;+ let before = await committedCount(row);+ while (performance.now() - started < MAX_MS) {+ const r = await runCli(row.home, args, { GBRAIN_SQL_TRACE: row.trace, GBRAIN_SQL_TRACE_LABEL: 'cli-sync', ...extraEnv }, Math.max(1000, MAX_MS - (performance.now() - started)));+ const found: Array<{ status: string; reason: string }> = [];+ const walk = (v: unknown): void => {+ if (Array.isArray(v)) { v.forEach(walk); return; }+ if (!v || typeof v !== 'object') return;+ const o = v as Record<string, unknown>;+ const st = o.sync_status ?? (typeof o.status === 'string' && o.source_id ? o.status : undefined);+ if (typeof st === 'string') found.push({ status: st, reason: String(o.reason ?? '') });+ else Object.values(o).forEach(walk);+ };+ walk(r.json);+ const status = found.length ? found.map(x => x.status).join(',') : null;+ const reason = found.length ? found.map(x => x.reason).join(',') : null;+ iterations.push({ wallMs: round1(r.wallMs), code: r.code, status, reason, firstStderrMs: r.firstStderrMs === null ? null : round1(r.firstStderrMs), firstProgressMs: r.firstProgressMs === null ? null : round1(r.firstProgressMs) });+ if (iterations.length % 10 === 1) log(`${row.name}@${row.rtt}: iteration ${iterations.length} ${status}/${reason} ${round1(r.wallMs / 1000)} s`);+ const statuses = (status ?? '').split(',');+ if (status && statuses.every(s => ['synced', 'first_sync', 'up_to_date'].includes(s))) return { iterations, failures, done: true, timedOut: false, wallMs: performance.now() - started };+ if (r.code !== 0 && !r.killed && !statuses.includes('partial')) failures.push((r.stdout + r.stderr).match(/code=(\w+)|"(?:error|code)":"(\w+)"/)?.slice(1).find(Boolean) ?? `exit_${r.code}`);+ const after = await committedCount(row);+ stalled = after === before ? stalled + 1 : 0;+ before = after;+ if (stalled >= STALL_ITERATIONS) return { iterations, failures, done: false, timedOut: false, wallMs: performance.now() - started, error: `no progress in ${STALL_ITERATIONS} iterations: ${(r.stdout + r.stderr).slice(-800)}` };+ }+ return { iterations, failures, done: false, timedOut: true, wallMs: performance.now() - started };+}++async function committedCount(row: RowContext): Promise<number> {+ return admin(async sql => Number((await sql.unsafe(`${BENCH_SQL} SELECT count(*)::int AS n FROM persistence_requests WHERE state='committed' AND intent->>'kind' IN ('managed_sync_import','managed_sync_delete')`))[0]!.n), row.db);+}++async function driveReentry(row: RowContext): Promise<Driven> {+ const markers = join(row.home, 'reentry-passes.jsonl');+ const started = performance.now();+ const child = Bun.spawn([process.execPath, import.meta.path, '--worker', 'reentry'], { cwd: row.home, stdin: 'ignore', stdout: 'pipe', stderr: 'pipe',+ env: childEnv(row.home, { GBRAIN_SQL_TRACE: row.trace, GBRAIN_SQL_TRACE_LABEL: 'reentry', BENCH_SOURCE: SOURCE, BENCH_MARKERS: markers, BENCH_MAX_MS: String(MAX_MS) }) });+ const [stdout, stderr, code] = await Promise.all([new Response(child.stdout).text(), new Response(child.stderr).text(), child.exited]);+ const passes = existsSync(markers) ? readFileSync(markers, 'utf8').split('\n').filter(Boolean).map(l => JSON.parse(l)) : [];+ const last = passes.at(-1) as { status?: string } | undefined;+ const done = code === 0 && ['synced', 'first_sync', 'up_to_date'].includes(last?.status ?? '');+ return { iterations: [], passes, done, timedOut: code === 0 && !done, wallMs: performance.now() - started, ...(code !== 0 ? { error: `reentry worker exit ${code}: ${(stdout + stderr).slice(-1500)}` } : {}) };+}++async function runWorker(kind: string): Promise<never> {+ const { loadConfig, toEngineConfig } = await import('../../src/core/config.ts');+ const { createEngine } = await import('../../src/core/engine-factory.ts');+ const config = loadConfig()!;+ const engine = await createEngine(toEngineConfig(config));+ await engine.connect(toEngineConfig(config));+ const { disposePersistenceConsumer } = await import('../../src/core/persistence/service.ts');+ const sourceId = process.env.BENCH_SOURCE!;+ if (kind === 'reentry') {+ const { performSync } = await import('../../src/commands/sync/perform.ts');+ const deadline = performance.now() + Number(process.env.BENCH_MAX_MS);+ for (let pass = 0; performance.now() < deadline; pass++) {+ const t = performance.timeOrigin + performance.now();+ const result = await performSync(engine, { sourceId, noPull: true, noEmbed: true } as Parameters<typeof performSync>[1]);+ const end = performance.timeOrigin + performance.now();+ appendFileSync(process.env.BENCH_MARKERS!, JSON.stringify({ pass, t, end, status: result.status, reason: (result as { reason?: string }).reason ?? null, banked: (result as { bankedFiles?: number }).bankedFiles ?? null }) + '\n');+ if (result.status !== 'partial') break;+ await Bun.sleep(250);+ }+ } else if (kind === 'foreground') {+ 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 logger = { info() {}, warn() {}, error() {} };+ for (let i = 0; !existsSync(stopFile); i++) {+ const t = performance.now();+ 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 });+ 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 });+ } 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) });+ }+ await Bun.sleep(Math.max(0, 1000 - (performance.now() - t)));+ }+ writeFileSync(process.env.BENCH_RESULTS!, JSON.stringify(results));+ }+ await disposePersistenceConsumer(engine);+ await engine.disconnect();+ process.exit(0);+}++async function foregroundWriter(row: RowContext, tag: string): Promise<{ stop: () => Promise<Array<{ t: number; ms: number; ok: boolean; code?: string; state?: string }>> }> {+ 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 }) });+ return {+ async stop() {+ writeFileSync(stopFile, '');+ const [stderr] = await Promise.all([new Response(child.stderr).text(), child.exited]);+ if (!existsSync(results)) throw new Error(`foreground worker wrote no results: ${stderr.slice(-1500)}`);+ return JSON.parse(readFileSync(results, 'utf8'));+ },+ };+}++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',+ env: childEnv(row.home, { GBRAIN_SQL_TRACE: row.trace, GBRAIN_SQL_TRACE_LABEL: 'serve', ...env }) });+ 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); } };+}++/** 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[]>();+ for (const r of records) {+ if (family(r.label) !== 'cli-sync' && family(r.label) !== 'reentry') continue;+ const list = byPid.get(r.pid) ?? [];+ if (!list.length) byPid.set(r.pid, list);+ list.push(r);+ }+ const prologue: number[] = []; const prologueMs: number[] = []; const perProcess: number[] = [];+ for (const rs of byPid.values()) {+ rs.sort((a, b) => a.t - b.t);+ const first = rs.findIndex(r => /INSERT INTO persistence_requests/i.test(r.sql));+ perProcess.push(rs.length);+ if (first >= 0) { prologue.push(first); prologueMs.push(rs[first]!.t - rs[0]!.t); }+ }+ return { processes: byPid.size, statements_per_process_p50: pct(perProcess, 50), statements_before_first_admission_p50: pct(prologue, 50),+ ms_from_first_statement_to_first_admission_p50: pct(prologueMs, 50) };+}++async function collect(row: RowContext, driven: Driven, locks: LockSample[], measureStart: Date, extra: Record<string, unknown> = {}): Promise<Record<string, unknown>> {+ const records = readTrace(row.trace, r => r.label !== 'setup' && r.t >= measureStart.getTime());+ const stats = await admin(async sql => {+ const reqs = await sql.unsafe(`${BENCH_SQL} SELECT intent->>'kind' AS kind, state, (outcome->>'noop')::boolean AS noop,+ extract(epoch FROM created_at)*1000 AS created, extract(epoch FROM completed_at)*1000 AS completed, operation+ FROM persistence_requests WHERE created_at >= $1 ORDER BY sequence`, [measureStart]) as unknown as Array<{ kind: string | null; state: string; noop: boolean | null; created: number; completed: number | null; operation: string }>;+ const counters = await sql.unsafe(BENCH_SQL + ' SELECT key, outstanding_count::float8 AS outstanding, lifetime_ids::float8 AS lifetime_ids, intent_bytes::float8 AS intent_bytes, terminal_bytes::float8 AS terminal_bytes FROM persistence_counters ORDER BY key');+ const size = Number((await sql.unsafe(BENCH_SQL + ' SELECT pg_database_size(current_database())::float8 AS b'))[0]!.b);+ const pages = Number((await sql.unsafe(`${BENCH_SQL} SELECT count(*)::int AS n FROM pages WHERE source_id IN ('${SOURCE}','${SOURCE_B}') AND deleted_at IS NULL`))[0]!.n);+ return { reqs, counters, size, pages };+ }, row.db);+ const pss = await admin(sql => readPgStatStatements(sql, row.db));+ const syncReqs = stats.reqs.filter(r => r.kind === 'managed_sync_import' || r.kind === 'managed_sync_delete');+ const committed = syncReqs.filter(r => r.state === 'committed' && r.completed);+ const completions = committed.map(r => r.completed!).sort((a, b) => a - b);+ const gaps = completions.slice(1).map((c, i) => c - completions[i]!);+ const ordered = [...committed].sort((a, b) => a.completed! - b.completed!);+ const gapOf = (kind: string) => ordered.slice(1).flatMap((r, i) => r.kind === kind ? [r.completed! - ordered[i]!.completed!] : []);+ const pages = committed.length || (row.managed ? 0 : Math.max(0, stats.pages - HISTORY * Object.keys(row.roots).length));+ const minutes = driven.wallMs / 60_000;+ const guard = records.filter(r => /page_write_guards/i.test(r.sql) && /for update/i.test(r.sql));+ const syncProc = records.filter(r => ['cli-sync', 'reentry'].includes(family(r.label)) && r.kind !== 'describe');+ const byClass: Record<string, number> = {};+ for (const r of syncProc) byClass[classify(r.sql)] = (byClass[classify(r.sql)] ?? 0) + 1;+ const holder = new Map<string, { samples: number; waiting: string; blocker_app: string; blocker_query: string; blocker_state: string }>();+ for (const s of locks) {+ const key = `${normalizeSql(s.waiting_query)}|${family(s.blocker_app.replace(/^gbrain:/, ''))}|${normalizeSql(s.blocker_query)}`;+ const h = holder.get(key) ?? { samples: 0, waiting: normalizeSql(s.waiting_query), blocker_app: family(s.blocker_app.replace(/^gbrain:/, '')), blocker_query: normalizeSql(s.blocker_query), blocker_state: s.blocker_state };+ h.samples++; holder.set(key, h);+ }+ const byFamily = (re: RegExp) => {+ const matches = new Map<string, boolean>();+ const counts: Record<string, number> = {};+ for (const r of records) {+ if (r.kind === 'describe') continue;+ let hit = matches.get(r.sql);+ if (hit === undefined) { hit = re.test(flatSql(r.sql)); matches.set(r.sql, hit); }+ if (hit) counts[family(r.label)] = (counts[family(r.label)] ?? 0) + 1;+ }+ return counts;+ };+ const claims = byFamily(/^UPDATE persistence_requests SET state='running', ?execution_token/);+ const 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;+ return {+ row: row.name, rtt_target_ms: row.rtt, managed: row.managed, backlog_entries: row.backlog, home: row.home, database: row.db,+ done: driven.done, timed_out: driven.timedOut, error: driven.error ?? null,+ wall_s: round1(driven.wallMs / 1000),+ entries_committed: committed.length,+ entries_noop: committed.filter(r => r.noop).length,+ entries_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,+ 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])),+ cli: driven.iterations.length ? {+ invocations: driven.iterations.length, wall_ms_p50: pct(driven.iterations.map(i => i.wallMs), 50), wall_ms_p90: pct(driven.iterations.map(i => i.wallMs), 90),+ pages_per_invocation: round1(pages / driven.iterations.length),+ writer_pending_exits: driven.iterations.filter(i => i.reason === 'writer_pending').length,+ first_stderr_ms_p50: pct(driven.iterations.flatMap(i => i.firstStderrMs === null ? [] : [i.firstStderrMs]), 50),+ e1_first_progress_ms: driven.iterations[0]?.firstProgressMs ?? null,+ failed_runs: Object.fromEntries([...new Set(driven.failures ?? [])].map(k => [k, (driven.failures ?? []).filter(x => x === k).length])),+ statuses: Object.fromEntries([...new Set(driven.iterations.map(i => `${i.status}/${i.reason}`))].map(k => [k, driven.iterations.filter(i => `${i.status}/${i.reason}` === k).length])),+ } : null,+ reentry: driven.passes ? { passes: driven.passes.length, statuses: driven.passes.map(p => `${(p as { status: string }).status}/${(p as { reason: string }).reason}`).slice(-3) } : null,+ trace: {+ round_trips: records.length, round_trips_per_page: pages ? round1(records.length / pages) : null,+ describe_round_trips: records.filter(r => r.kind === 'describe').length,+ connections_opened: records.filter(r => r.kind === 'connect').length,+ connect_ms_p50: pct(records.filter(r => r.kind === 'connect').map(r => r.ms), 50),+ db_ms_per_page: pages ? round1(sum(records.map(r => r.ms)) / pages) : null,+ by_process: Object.fromEntries([...new Set(records.map(r => family(r.label)))].map(f => {+ const rs = records.filter(r => family(r.label) === f);+ return [f, { round_trips: rs.length, per_page: pages ? round1(rs.length / pages) : null, ms: round1(sum(rs.map(r => r.ms))), processes: new Set(rs.map(r => r.pid)).size }];+ })),+ round_trips_by_class: Object.fromEntries(Object.entries(records.reduce<Record<string, number>>((acc, r) => { acc[classify(r.sql)] = (acc[classify(r.sql)] ?? 0) + 1; return acc; }, {})).map(([k, n]) => [k, pages ? round1(n / pages) : null])),+ sync_process_by_class: Object.fromEntries(Object.entries(byClass).map(([k, v]) => [k, { round_trips: v, per_page: pages ? round1(v / pages) : null, share: round1(100 * v / Math.max(1, syncProc.length)) }])),+ errors: Object.fromEntries([...new Set(records.flatMap(r => r.err ? [`${family(r.label)}:${r.err}`] : []))].map(e => [e, records.filter(r => r.err && `${family(r.label)}:${r.err}` === e).length])),+ top_statements: groupStatements(records, pages, 40),+ re_entry: processBreakdown(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,+ },+ pg_stat_statements: pss,+ guard_wait: {+ statements: guard.length, total_ms: round1(sum(guard.map(r => r.ms))), per_page_ms: pages ? round1(sum(guard.map(r => r.ms)) / pages) : null,+ p50_ms: pct(guard.map(r => r.ms), 50), max_ms: pct(guard.map(r => r.ms), 100),+ },+ claims: { claims_by_process: claims, publications_by_process: publications, released_unpublished_by_process: releases },+ lock_waits: { samples: locks.length, sample_every_ms: 100, by_holder: [...holder.values()].sort((a, b) => b.samples - a.samples).slice(0, 12) },+ db_growth_bytes_per_page: null as number | null,+ db_size_bytes: stats.size,+ persistence_counters: stats.counters,+ capacity_headroom: capacityHeadroom(stats.counters as unknown as Array<{ key: string; lifetime_ids: number; terminal_bytes: number }>, row.backlog),+ ...extra,+ };+}++/** CEO-A25: lifetime IDs and terminal bytes used vs the default journal limits, and what the whole backlog would reserve at the observed bytes per request. */+function capacityHeadroom(counters: Array<{ key: string; lifetime_ids: number; terminal_bytes: number }>, backlog: number): Record<string, unknown> {+ const brain = counters.find(c => c.key === 'brain');+ const principal = counters.filter(c => c.key.startsWith('principal:')).sort((a, b) => b.terminal_bytes - a.terminal_bytes)[0];+ if (!brain || !principal || !brain.lifetime_ids) return { available: false };+ const perRequest = principal.terminal_bytes / Math.max(1, principal.lifetime_ids);+ const limits = DEFAULT_JOURNAL_LIMITS;+ return { terminal_bytes_per_request: Math.round(perRequest),+ brain_lifetime_ids_used_pct: round1(100 * brain.lifetime_ids / limits.brainLifetimeIds),+ principal_terminal_bytes_used_pct: round1(100 * principal.terminal_bytes / limits.principalTerminalBytes),+ full_backlog_principal_terminal_bytes_pct: round1(100 * (principal.terminal_bytes + perRequest * backlog) / limits.principalTerminalBytes),+ full_backlog_principal_lifetime_ids_pct: round1(100 * (principal.lifetime_ids + backlog) / limits.principalLifetimeIds) };+}++async function measure(row: RowContext, drive: () => Promise<Driven>, extra: () => Promise<Record<string, unknown>> = async () => ({})): Promise<Record<string, unknown>> {+ 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 sampler = startLockSampler(harness.adminUrl, row.db);+ const start = new Date();+ log(`${row.name}@${row.rtt}: measuring (proxy RTT ${measuredRtt} ms, backlog ${row.backlog})`);+ const driven = await drive();+ const more = await extra();+ const locks = await sampler.stop();+ const result = await collect(row, driven, locks, start, { rtt_measured_ms: measuredRtt, ...more });+ const committed = result.entries_committed as number;+ result.db_growth_bytes_per_page = committed ? Math.round(((result.db_size_bytes as number) - sizeBefore) / committed) : null;+ result.cli_is_owner_host = await ownerHost(row);+ log(`${row.name}@${row.rtt}: ${result.pages_per_min} pages/min, done=${result.done}, ${committed} committed, ${(result.trace as { round_trips_per_page: number }).round_trips_per_page} round trips/page`);+ return result;+}++/** ENG-A9: whether this home's host identity is the worktree owner host. */+async function ownerHost(row: RowContext): Promise<boolean | null> {+ const file = join(row.home, '.gbrain', 'persistence', 'host.json');+ const candidates = [file, join(row.home, 'persistence', 'host.json'), join(row.home, '.gbrain', 'host.json')];+ const found = candidates.find(existsSync);+ if (!found) return null;+ const hostId = (JSON.parse(readFileSync(found, 'utf8')) as { host_id?: string; id?: string }).host_id ?? (JSON.parse(readFileSync(found, 'utf8')) as { id?: string }).id;+ const owners = await admin(sql => sql.unsafe(BENCH_SQL + ' SELECT DISTINCT owner_host_id::text AS h FROM persistence_worktrees WHERE owner_host_id IS NOT NULL'), row.db) as unknown as Array<{ h: string }>;+ return owners.length ? owners.every(o => o.h === hostId) : null;+}++async function retrievalReadiness(row: RowContext, budgetMs: number): Promise<Record<string, unknown>> {+ const started = performance.now();+ let last: Record<string, number> = {};+ for (let first = true; first || performance.now() - started < budgetMs; first = false) {+ last = await admin(async sql => {+ const [c] = await sql.unsafe(`${BENCH_SQL} SELECT count(*) FILTER (WHERE cc.embedding IS NULL)::int AS unembedded, count(*)::int AS chunks+ FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE p.source_id = $1 AND p.deleted_at IS NULL`, [SOURCE]);+ const [e] = await sql.unsafe(`${BENCH_SQL} SELECT count(*) FILTER (WHERE e.state IN ('queued','running'))::int AS pending, count(*) FILTER (WHERE e.state = 'failed')::int AS failed+ FROM persistence_effects e JOIN persistence_requests r ON r.id = e.request_id WHERE r.source_id = $1`, [SOURCE]);+ const [j] = await sql.unsafe(`${BENCH_SQL} SELECT count(*) FILTER (WHERE status IN ('waiting','active','delayed'))::int AS jobs FROM minion_jobs`).catch(() => [{ jobs: -1 }]);+ const [l] = await sql.unsafe(`${BENCH_SQL} SELECT count(*)::int AS stale FROM pages WHERE source_id = $1 AND deleted_at IS NULL AND (links_extracted_at IS NULL OR links_extracted_at < updated_at)`, [SOURCE]);+ return { unembedded: c!.unembedded, chunks: c!.chunks, effects_pending: e!.pending, effects_failed: e!.failed, jobs_pending: j!.jobs, links_stale: l!.stale };+ }, row.db);+ if (last.unembedded === 0 && last.effects_pending === 0 && last.jobs_pending <= 0 && last.links_stale === 0) return { retrieval_ready: true, retrieval_ready_after_sync_s: round1((performance.now() - started) / 1000), readiness: last };+ if (budgetMs > 0) await Bun.sleep(2000);+ }+ return { retrieval_ready: false, retrieval_ready_after_sync_s: null, readiness: last };+}++async function runRow(name: string, rtt: number): Promise<Record<string, unknown>> {+ const syncArgs = ['sync', '--source', SOURCE, '--no-pull', '--no-embed', '--json'];+ if (name === 'cli') { const row = await setupRow(name, rtt, { managed: true, sources: 1, files: FILES, deletes: DELETES }); return measure(row, () => driveCli(row, syncArgs)); }+ if (name === 'reentry') { const row = await setupRow(name, rtt, { managed: true, sources: 1, files: FILES, deletes: DELETES }); return measure(row, () => driveReentry(row)); }+ if (name === 'unmanaged') { const row = await setupRow(name, rtt, { managed: false, sources: 1, files: FILES, deletes: DELETES }); return measure(row, () => driveCli(row, syncArgs)); }+ if (name === 'serve') {+ const row = await setupRow(name, rtt, { managed: true, sources: 1, files: FILES, deletes: DELETES });+ await harness.setRtt(rtt);+ const serve = startServe(row);+ await Bun.sleep(8000);+ return measure(row, () => driveCli(row, syncArgs), async () => ({ serve_stderr_tail: (await serve.stop()).slice(-400) }));+ }+ if (name === 'effects') {+ const stub = await startEmbeddingStub({ latencyMs: 200, maxConcurrent: 4, dims: 1024 });+ try {+ const row = await setupRow(name, rtt, { managed: true, sources: 1, files: FILES, deletes: DELETES });+ writeConfig(row.home, row.proxyUrl, true);+ const env = { OPENAI_API_KEY: 'bench-stub-key', OPENAI_BASE_URL: stub.url };+ await harness.setRtt(rtt);+ const serve = startServe(row, env);+ await Bun.sleep(8000);+ return await measure(row, () => driveCli(row, ['sync', '--source', SOURCE, '--no-pull', '--json'], env), async () => {+ const atExit = await retrievalReadiness(row, 0);+ const ready = await retrievalReadiness(row, MAX_MS);+ return { effects_backlog_at_cli_exit: atExit.readiness, ...ready, embedding_stub: { ...stub.stats }, serve_stderr_tail: (await serve.stop()).slice(-400) };+ });+ } finally { stub.close(); }+ }+ if (name === 'foreground') {+ const row = await setupRow(name, rtt, { managed: true, sources: 1, files: FILES, deletes: DELETES });+ await harness.setRtt(rtt);+ const idle = await foregroundWriter(row, 'idle');+ await Bun.sleep(60_000);+ const idleResults = await idle.stop();+ let busy: Awaited<ReturnType<typeof foregroundWriter>> | undefined;+ return measure(row, async () => { busy = await foregroundWriter(row, 'busy'); return driveCli(row, syncArgs); }, async () => {+ const busyResults = await busy!.stop();+ const summarize = (rs: typeof idleResults) => ({ writes: rs.length, 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) };+ });+ }+ if (name === 'all') {+ const row = await setupRow(name, rtt, { managed: true, sources: 2, files: FILES, deletes: DELETES });+ return measure(row, () => driveCli(row, ['sync', '--all', '--no-pull', '--no-embed', '--json']));+ }+ if (name === 'newcomer') return newcomer(rtt);+ throw new Error(`unknown row ${name}`);+}++/** DX-A12: cold CLI start to first progress line on a managed backlog, and a 5-page managed source to a search hit. */+async function newcomer(rtt: number): Promise<Record<string, unknown>> {+ const row = await setupRow('newcomer', rtt, { managed: true, sources: 1, files: 5, deletes: 0 });+ await harness.setRtt(rtt);+ const started = performance.now();+ const first = await runCli(row.home, ['--progress-json', '--progress-interval', '0', 'sync', '--source', SOURCE, '--no-pull', '--no-embed'], { GBRAIN_SQL_TRACE: row.trace, GBRAIN_SQL_TRACE_LABEL: 'cli-sync' });+ const firstProgressMs = first.firstProgressMs;+ let runs = 1;+ let status = first.stdout;+ for (; runs < 30 && !/synced|up to date|up_to_date|first_sync/i.test(status); runs++) {+ status = (await runCli(row.home, ['sync', '--source', SOURCE, '--no-pull', '--no-embed', '--json'])).stdout;+ }+ const token = pagesFor(0)[HISTORY]!.content.match(/Marker (\w+)\./)?.[1] ?? 'scaletok';+ const search = await runCli(row.home, ['search', token, '--json']);+ return { row: 'newcomer', rtt_target_ms: rtt, e1_cold_start_to_first_progress_ms: firstProgressMs === null ? null : round1(firstProgressMs),+ e1_cold_start_to_first_stderr_ms: first.firstStderrMs === null ? null : round1(first.firstStderrMs), e1_wall_ms: round1(first.wallMs),+ newcomer_sync_runs: runs, newcomer_to_search_hit_s: round1((performance.now() - started) / 1000), search_hit: search.stdout.includes(token) || search.stdout.includes('scale-0-'),+ first_stderr_sample: first.stderr.split('\n').slice(0, 3) };+}++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 });+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 },+ 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>>,+};+const save = () => { mkdirSync(dirname(OUT), { recursive: true }); writeFileSync(OUT, JSON.stringify(report, null, 2) + '\n'); };+try {+ await buildTemplate();+ for (const rtt of RTTS) for (const name of ROWS) {+ try { (report.rows as unknown[]).push(await runRow(name, rtt)); }+ catch (error) { log(`${name}@${rtt} failed: ${error instanceof Error ? error.stack : String(error)}`); (report.rows as unknown[]).push({ row: name, rtt_target_ms: rtt, error: String(error instanceof Error ? error.message : error).slice(0, 3000) }); }+ save();+ }+} finally {+ report.finished_at = new Date().toISOString();+ save();+ log(`report: ${OUT}`);+ if (!KEEP) {+ for (const datname of created) await admin(sql => sql.unsafe(`DROP DATABASE IF EXISTS ${datname} WITH (FORCE)`)).catch(() => undefined);+ rmSync(work, { recursive: true, force: true });+ }+ harness.stop();+}+process.exit(0);