Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

docs(eval): Phase 0 record for the transaction-pooler ClientRead wedge (#6317, #6278): mechanism reproduced on demand, two consumers are a multiplier; harness gains --scenario two-consumer and --chaos-kind partition

garrytan9cfb51a8d29e
diff --git a/docs/eval/managed-sync-two-consumer-repro.md b/docs/eval/managed-sync-two-consumer-repro.md
index 5a6ae77510..5c196d0ced 100644
--- a/docs/eval/managed-sync-two-consumer-repro.md
+++ b/docs/eval/managed-sync-two-consumer-repro.md
@@ -1,77 +1,306 @@
-# Managed sync: two-consumer `preparing` wedge, Phase 0 reproduction record (#6317)
-
-Phase 0 of the #6317 plan
-(`docs/plans/2026-10-08-001-fix-managed-sync-reliability-contract-6317-plan.md`, §2)
-asks for a two-process reproduction of the reporter's wedge: a bulk group
-claimed by the process that does not hold the lane run (a `gbrain serve` that
-booted first, the sync CLI started 60–90 s later), its head member sitting in
-`running` / `claim_phase.phase = preparing` past five minutes with nothing in
-flight at the database, the lease renewing every 10 s, and the same rows
-preparing in seconds from a scratch process. This page is the record of that
-reproduction. The deployment, hosts and paths use placeholders (the
-`AGENTS.md` privacy rule); the real names stay in thread GBRA-61.
-
-## Where to find it
-
-The content of this page is written by Phase 0 (plan task T-09, thread GBRA-61)
-from the captures it takes on its Ubicloud VM (`UBI_OWNER=gbra61`), not by the
-build lanes. Until it lands here:
-
-- the live evidence it starts from is in #6278 (the reporter's comments of
- 2026-10-08 15:15Z and 15:25Z: E1–E5 in the plan's §1);
-- the preregistered reading of the arms, which decides the default of
- `persistence.single_consumer` and what lane A fixes, is in the plan's §2;
-- the previous record, for the other stall class (a relation lock wait a
- transaction-mode pooler hides), is
- [`managed-sync-stall-repro.md`](managed-sync-stall-repro.md); its scripts
- (`scripts/bench/managed-sync-stall-repro.ts`,
- `scripts/bench/stall-repro-vm-setup.sh`) are the starting point for this
- one.
-
-## What this page records once Phase 0 lands
-
-Written in the order the plan lists them (§2, deliverables 1–4):
-
-1. **The timeline.** Fixture size, lane count, when `serve` booted, when the
- CLI started, when the group was claimed and by which pid, the claim stamps
- (`claim_phase.step`, `waiting_on`, owner kind, pid, build) read every 10 s
- with `gbrain sources writer status --json`, and `pg_stat_activity` at the
- same instants, on current master first and then on #6298's head.
-2. **The named await**, or the statement that it could not be named inside
- the three-hour box: the `enterClaimStep` stamp first, the
- `bun --inspect` `Debugger.paused` frames and `asyncStackTrace` where the
- second instrument was available.
-3. **Which arms wedged**: (i) `serve` plus the sync CLI on the reporter's
- timeline, (ii) one long-lived consumer only, (iii) arm (i) plus a `jobs`-kind
- process submitting adoption writes every 20 s; and which of the four
- candidates the code supports held: (a) pool self-deadlock in the claiming
- process, (b) a cross-process wait on state only the other process has,
- (c) a per-process resource exhausted in a long-lived owner, (d) a response
- lost between the pooler and the driver.
-4. **What #6298's containment did to it**: whether the budget cut the
- preparation at 120 s, whether the entry was held after two attempts, and
- how long the root stayed blocked per occurrence (the ceiling at the latest).
-
-The verdict's first line states the preregistered reading that applied: arm (i)
-wedges and arm (ii) does not (the second consumer is the cause class, B1 is a
-cause fix), both wedge (the cause is in the long-lived owner, B1 is policy), or
-neither wedges in the box (the trigger is unreproduced and the production
-capture from the plan's §6 step (4) is the evidence).
-
-## Mirror into gbrain-evals
-
-Every measured verdict for a shipped feature is mirrored into gbrain-evals
-(project rule). For #6317 the integrator's gbrain-evals PR carries:
-
-- this page, once Phase 0 has written it, with the same placeholders;
-- the per-arm timelines (`writer status --json` samples every 10 s) and the
- `pg_stat_activity` captures that back the verdict, as fixtures;
-- the preregistration (the plan's §2 reading) next to the outcome, so the
- default chosen for `persistence.single_consumer` is traceable to the arm
- that decided it;
-- the T1 two-process regression test's forced-probe result (fails on #6298's
- head, passes with the fix) and, if lane A named the await, the A1
- regression's before/after;
-- the containment numbers from deliverable 4 (time to cut-off, time the root
- stayed blocked, entries held) beside #6298's own measurements in
- `managed-sync-catchup.md`.
+# Managed-sync `preparing` wedge through a transaction-mode pooler: Phase 0 reproduction record (#6317, #6278)
+
+Phase 0 of the GBRA-61 plan for #6317 started from the reporter's two
+comments of 2026-10-08 15:15Z and 15:25Z on #6278: sixteen
+`managed_sync_import` members of one bulk group in `state='running'` /
+`claim_phase.phase='preparing'` for 25+ minutes on 0.60.110.0 while the
+lease renewed, `pg_stat_activity` showed no statement older than about 3 s,
+the same rows prepared in 2.6–3.4 s from a scratch process, and every wedge
+had two persistence consumers on the host (`gbrain serve --http` plus the
+one inside `gbrain sync`). The brief was to build that two-process shape on
+Ubicloud, name the await, test the candidate causes and record what this
+branch's preparation budget does to it. Halfway through, the reporter's
+17:09Z comment reframed the cause: the wedge reproduces with one process,
+`--no-lanes` and no serve; the differentiator is the pooler mode
+(Supavisor :6543 transaction mode wedges, the :5432 session URL drains),
+and the live signature is a backend `active` / `wait_event=ClientRead` for
+minutes on the consumer's `expired_claims` CTE with the consumer logging
+`phase=expired_claims reason=deadline_exceeded` and staying parked. This
+page records both halves: the mechanism first, then the two-consumer arms
+as what they turned out to be, a multiplier of pooled round trips, not the
+mechanism.
+
+The harness is the #6278 one extended, not a new script:
+`scripts/bench/managed-sync-stall-repro.ts` gained `--scenario two-consumer`
+(a seeding lane drain killed mid-run, a `gbrain serve --http` consumer, a
+`gbrain sync` consumer `--gap-seconds` later, CLI SIGTERM/restart on a
+cadence, a wedge rule with dumps on detection, `--direct-pool` for the
+dual-pool topology, `--inspect`) and `--chaos-kind partition` (iptables
+drops the client→pooler half of every gbrain connection, never closes it,
+and lifts it after `--chaos-for`). `scripts/bench/stall-debug-instrument.py`
+(debug only, applied on the VM, never committed) now also records every raw
+statement, transaction checkout and reserve between its send in JS and its
+settle (a statement that is in JS but not in `pg_stat_activity` is one that
+never reached the server or is waiting for a connection), the postgres.js
+pool queues per pool, the consumer's head-order / follower-claim /
+wave-dispatch marks, and a forced never-settling preparation
+(`--hang-after N`), which this page did not need in the end. Captures live
+under `.context/bench/*/` on the two VMs (`UBI_OWNER=gbra61`, destroyed
+after the runs) and were copied to `~/.capy/work/gbra61/phase0/` on the
+GBRA-61 machine; every number below comes from those captures.
+
+## Verdict
+
+- **The mechanism reproduces on demand, on 0.60.110 and on this branch, with
+ one process and no lanes.** Drop the client→pooler half of the sync's
+ connections (PgBouncer transaction mode, 57 ms RTT, `iptables … -j DROP`,
+ the socket stays open) and within one sample the process shows exactly
+ the reporter's live capture: a backend `active` / `wait_event=ClientRead`
+ on a statement whose extended-protocol exchange never completes
+ (0.60.110: `UPDATE timeline_entries …` of the publication transaction,
+ `query_age` 136 s, `xact_age` 146 s), the rest of the backends `idle` /
+ `ClientRead` with their last statement 135–147 s old, the consumer's own
+ `WITH expired AS (…) UPDATE …` round trip parked in JS for 135 s with
+ `status().phase = { name: 'expired_claims', deadline_exceeded: true }`
+ still current 134 s after it started (this branch) and
+ `[persistence] phase=expired_claims reason=deadline_exceeded` /
+ `phase=refresh_roots reason=deadline_exceeded` on stderr, the group's
+ lease renewal (`UPDATE persistence_requests r SET claim_expires_at=…`)
+ parked 127–130 s so the claims lapsed, the drain's `awaitWrite` poll
+ (`SELECT * FROM persistence_requests WHERE id=ANY($1)`) parked 109–177 s,
+ zero committed pages, the process at 3.6–4.9 % CPU. `statement_timeout`
+ cannot end a backend that is waiting for the client, and the 5 s phase
+ deadline fires `abort()` but nothing settles: the awaits sit on sockets,
+ not on the pool (every dump had the pool's `open` or `connecting` queues
+ non-empty while the statements were parked).
+- **The await that hangs is postgres.js's query promise in
+ `PostgresEngine.runUnsafe`** (`src/core/postgres-engine.ts:2733-2734`,
+ `pending = conn.unsafe(…); return await pending`), reached from the
+ consumer's `phase('expired_claims', …)` (`consumer.ts:468`, through
+ `phase()`'s `return await phaseScope.run(…)` at `consumer.ts:618`), from
+ `renewGroupClaims` (`journal.ts:352`), from the drain's progress poll
+ (`service.ts:249`, `getWriteRequestProgress`) and from every statement of
+ `publishGroup`'s transaction (`group-publish.ts:238`). Why `abort()`
+ cannot end it: `onAbort` calls `pending.cancel()`
+ (`postgres-engine.ts:2744`); the vendored driver's `cancelActive`
+ (`vendor/postgres/src/index.js:463`) opens a cancel connection, sends
+ CancelRequest and then re-sends it every 50 ms → 1 s for as long as the
+ query stays active, resolving only once the query settles; a backend in
+ `ClientRead` is not executing, so the cancel is a no-op and the loop runs
+ forever (the steady trickle of new cancel connections is the 5–20 % CPU
+ the reporter saw); and the `owner.discard()` that would destroy the socket
+ sits in `runUnsafe`'s `finally`, which runs only after the parked `await
+ pending` settles. GBRA-59's PR 1.5 (bounded client-side settle in
+ `runUnsafe`: cancel, then destroy the reserved connection after ~2 s; the
+ same for `executeRawDirect` renewals) is the fix for this seam and is not
+ duplicated here.
+- **The preparation budget does not cover this class, as expected.** On
+ this branch (532d1145, VERSION 0.60.112.0) the partition parked a
+ 16-member group at step `publish:transaction` for 166 s and the consumer's
+ tick in `expired_claims`; `status()` reported `abandoned_preparations: 0`,
+ `outlived_ceiling: []`, `preparation_attempts: 0`, `restart_required:
+ false`, no member was released `preparation_deadline` and nothing was
+ finished `preparation_stalled`, because `startPreparation` races only
+ `run.prepare`, and none of the parked awaits is inside a preparer. The
+ progress line did name the phase (`stalled 269s on publishing`). Only the
+ network recovering (the drop lifted after 240 s, TCP retransmitted the
+ lost segments) ended the wedge: the group committed within 41 s of the
+ lift (298 → 330), after which the pass exited `database_error … connect
+ ECONNREFUSED` on its next connection (the harness proxy under the burst of
+ retransmitted SYNs and queued cancel connections, which the drain did not
+ retry) on both builds; in the earlier manual run on 0.60.110 the drain
+ resumed on its own 45 s after the lift (89 → 91, next group running).
+- **Two consumers are a multiplier, not the mechanism.** 2 h 49 min of the
+ reporter's two-process shape on 0.60.110 (three arms: plain; adoption
+ load plus CLI restarts every 10 min; dual pool plus restarts every 15 min)
+ published 4,951 pages with no `preparing` claim older than 25 s and no
+ server-side statement older than 11.5 s; serve claimed 18 FIFO heads
+ beside the CLI's 456 lane and FIFO claims and published every one. The one
+ cross-process effect observed is bounded: a serve-held group's exclusive
+ worktree lock makes the CLI's lane transactions wait in `awaitLaneTurn`
+ (`idle in transaction`, up to 60 s) and roll back. A second consumer
+ simply doubles the pooled round trips a dropped exchange can park, and
+ with a group memo (`preparationReads`, `groupReads`) or a group
+ transaction, one parked round trip parks every member of the group, which
+ is how sixteen members show the same `preparing` age.
+- **Preregistered reading for `persistence.single_consumer`: ship it OFF.**
+ The single-process arm wedges (the reporter's 17:09Z capture; runs E2, F2
+ and F below), so refusing or delegating the second consumer does not
+ address the mechanism; it stays a default-off operational switch until the
+ bounded settle has shipped and the two-consumer shape has been measured
+ against it.
+
+## The mechanism: timeline and captures
+
+Topology for every mechanism run: 16-vCPU `standard-16`, pgvector/pg16 in
+Docker, PgBouncer 1.26 transaction mode (`statement_timeout` dropped at the
+pooler: `SHOW statement_timeout` = `0` via the pooler, `5min` direct),
+toxiproxy with 57 ms round trip in front of the pooler, `GBRAIN_PREPARE=false`,
+`GBRAIN_POOL_SIZE=10`, `GBRAIN_SYNC_LANES=1`, a 3,000-page backlog on a
+300-page history source, one non-TTY `timeout 3600 gbrain sync --source
+bench --no-pull --no-embed`, 10 s samples, `--stall-minutes 2`, SIGUSR2 dumps
+on the stall.
+
+### Run E2 (0.60.110, 1935c74a, manual partition; `E2-110/`)
+
+| time (UTC) | event | what the captures show |
+|---|---|---|
+| 17:49:51 | pass starts | single path, 7.2–8.2 pages/min (the reporter's 7–19/min bracket) |
+| 17:51:51–17:51:54 | toxiproxy `timeout` toxic, upstream, toxicity 1, 3 s | PgBouncer sees a truncated exchange and closes: `phase=expired_claims reason=storage_error write CONNECTION_CLOSED`, `phase=execution … CONNECT_TIMEOUT`; the pass recovers. A pooler that parses packets fails loud; the reporter's did not. |
+| 17:55:48 | `iptables -I OUTPUT -p tcp --sport 55466 --dport 55433 -j DROP` (one connection) | 17:56:35: one `SELECT EXISTS (… persistence_requests …)` (`hasClaimableWrite`, reserved connection) parked 44 s in JS; the tick's other probes kept completing (278 in the window on two other connections), so one dead connection parks one caller, not the process |
+| 18:02:34 | `iptables -I OUTPUT -p tcp --dport 55433 -j DROP` (every connection) | 18:04:51 stall rule (140 s without a commit); `stall-1.json`: backend 96 `active` / `ClientRead`, `DELETE FROM page_aliases …`, `query_age` 138 s, `xact_age` 142 s; nine backends `idle` / `ClientRead` 136–177 s; JS: `DELETE FROM page_aliases` parked 164 s in the publication transaction, the drain's `SELECT * FROM persistence_requests WHERE id=ANY($1)` parked 137 s, renewal parked, `claim_lapsed: true`, `since_update_ms` 144,490; consumer phase `refresh_roots` `deadline_exceeded`, then `storage_error aborted` / `read ECONNRESET` every tick; pool `connecting: 9`, `full: 1`, `open: 0`; process 4.1 % CPU; `pg_locks`: nothing waiting |
+| 18:05:45 | drop lifted | 18:06:04 `writer status --json` (the first one that could run): the running member `assessment: stalled, reason: cause_unknown, next_action: inspect_owner`, claim `publication_transaction` (lapsed), the reporter's wording; 18:06:29: committed 89 → 91, a new group of 16 running: the parked statements completed through TCP retransmission and the drain resumed on its own |
+
+### Run F2 (0.60.110, 1935c74a, `--chaos-kind partition --chaos-at 3 --chaos-for 240`; `F2-110/`)
+
+Pass start 18:14:38; drop 18:17:38–18:21:39; stall rule 18:19:53 (140 s);
+`stall-1.json` at 18:19:55: backend 98 `active` / `ClientRead` on `UPDATE
+timeline_entries t SET detail=r.next FROM jsonb_to_recordset(…)`,
+`query_age` 136,379 ms, `xact_age` 146,499 ms; backend 99 `idle` /
+`ClientRead` with `WITH expired AS (…)` 136,684 ms old; six more backends
+idle on `config` reads and `commit` 135–147 s old. SIGUSR2 dump at
+18:19:53: three members (`cffd8b36`, `5ee41838`, `8a61df03`) at step
+`publish:transaction` for 145,020 ms; `sql_inflight`: `UPDATE
+timeline_entries` (tx) 135,270 ms, `SELECT brain_id,enabled,… FROM
+persistence_brain` (reserved) 134,585 ms, the renewal `UPDATE
+persistence_requests r SET claim_expires_at=…` (reserved) 127,164 ms, the
+drain poll `SELECT * FROM persistence_requests WHERE id=ANY($1)` 114,534 ms;
+pool `max 10: open 0, busy 0, full 2, reserved 1`; consumer phase
+`refresh_roots` started 18:17:39, `deadline_exceeded: true`, attempt 689,
+still current 134 s later; stderr: 12 × `phase=refresh_roots
+reason=deadline_exceeded`, 11 × `reason=storage_error message="aborted"`;
+`claim_phase.phase = publishing` on all three rows with `claim_lapsed:
+true`, `since_update_ms` 138,641; the sampler's own `gbrain sources writer
+status --probe --json` hung through the same pooler and was killed at
+120 s (exit 143), so during the wedge the one command meant to explain it
+cannot run; 3.6 % CPU. After the lift the three members
+committed (30 → 33) and the pass exited `database_error … connect
+ECONNREFUSED` 48 s later (code 1, 470 s wall).
+
+### Run F (this branch 532d1145, same chaos; `F-head/`)
+
+Pass start 18:13:45 (groups of 16 publish in one transaction even with lanes
+off on this build: 266 pages in the first 2 min 45 s); drop
+18:16:46–18:20:46; stall rule 18:19:00. `stall-1.json` at 18:19:02: backend
+89 `idle in transaction` / `ClientRead` on `DELETE FROM page_aliases …`
+(`query_age` 136,464 ms, `xact_age` 139,548 ms); five idle backends with
+statements 136–141 s old. Dump at 18:19:00: 16 members at
+`publish:transaction` for 138,068 ms (steps `consumer:head_order@0 …
+group:prepared@1397 … publish:acquire_worktree@2425 →
+publish:transaction`); `sql_inflight`: `UPDATE pages SET chunker_version
+…` and `INSERT INTO content_chunks …` (tx) 134,923 ms, `WITH expired AS
+(…)` (reserved) 134,923 ms, `UPDATE persistence_requests r SET
+claim_expires_at` (reserved) 130,151 ms, `SELECT c.* FROM
+persistence_topology_changes` 134,925 ms, the drain poll 109,345 ms; pool
+`max 10: open 0, busy 2, full 2, reserved 3`; consumer `phase: {
+name: 'expired_claims', started_at: 18:16:46.036Z, deadline_exceeded: true,
+attempt: 1272 }`, `abandoned_preparations: 0`, `outlived_ceiling: []`,
+`preparation_attempts: 0`, `restart_required: false`; stderr: `phase=
+expired_claims reason=deadline_exceeded` once, then (one connection came
+back `read ECONNRESET`, logged as `phase=execution reason=storage_error`,
+which is what un-parked the tick here about 2.5 min in and did not happen
+to the reporter in 25 min)
+9 × `phase=switches reason=deadline_exceeded checkout=not_observed
+conn_wait_ms=5000` and 9 × `storage_error aborted`; progress line `[sync]
+298/3000 processed · stalled 269s on publishing`; the 16 rows
+`running`, stamp `preparing` (the publishing stamp never reached the
+server), `claim_lapsed: true`, `since_update_ms` 142,283. After the lift
+the group committed (298 → 330 by 18:21:27, 41 s) and the pass exited
+`GBRAIN_DB_ACCESS conn_refused` / `database_error connect ECONNREFUSED
+…:55433` at 18:21:35 (code 1, 470 s wall); no `preparation_deadline`, no
+`preparation_stalled`, no `preparation_abandoned`.
+
+### What the inspector gives
+
+With `--inspect` each process listens on 127.0.0.1:650N; `Runtime.evaluate`
+reads the pool queues and the instrument's maps live, `Debugger.enable` /
+`setAsyncStackTraceDepth` are accepted, but the protocol has no way to
+enumerate parked promises, and `Debugger.pause` only shows the current
+synchronous stack. The step marks plus the in-flight statement table are
+what name the await; the inspector adds nothing for this class.
+
+## Candidate table
+
+| candidate | verdict | evidence |
+|---|---|---|
+| (a) pool self-deadlock in the claiming process (every connection held by a holder that waits for another) | ruled out | Every dump during a wedge had `open` or `connecting` connections while statements were parked (E2: `connecting 9`; F: `open 0, busy 2, full 2, reserved 3` with nine SYN_SENT sockets); the parked waits are `await pending` on sockets, not reserve/checkout waits. The reporter's group renewals went through on the ordinary pool (`renewGroupClaims` uses `executeRaw`), which a pool deadlock would have blocked. |
+| (b) cross-process wait on the other process's state: lane sets, `windowPredecessorAllows` / `claimedHeadOrder`, `page_write_guards FOR UPDATE`, the native worktree lock | ruled out as the mechanism | A/B/C: 2 h 49 min of serve + CLI (serve-first, 75 s gap; with adoption writes; with CLI restarts; with the dual pool), 18 serve-claimed FIFO groups published beside the CLI's lanes, no `preparing` claim older than 25 s, no `pg_locks` waiter, the `claimedHeadOrder` marks always `go`. The worktree lock is `tryAcquireNativeLock` (`ownership.ts` `lockWorktree`, `waitMs 0`): a busy lock returns `busy` and the group releases its claims, never waits. Lane commit-order waits (`awaitLaneTurn`) are bounded at 60 s. No wedge occurred, so `lslocks` / `fdinfo` were never captured during one. |
+| (c) a shared memo or promise that never settles (`transactionMemo`, `sharedSyncValidation`, `groupReads`, `preparationReads`) | not the trigger; it is the fan-out | Nothing memoized hung on its own. Under the mechanism a memoized read or a shared group transaction parked on a dead socket parks every member at once, which is how the reporter's sixteen members show the same age (F: 16 members, one transaction, one parked `INSERT INTO content_chunks`). |
+| (d) a round trip through a transaction-mode pooler whose exchange never completes, plus awaits that cannot be cancelled once it does | **reproduced** | E2, F2, F above; the reporter's 17:09Z capture. The await is `runUnsafe`'s `await pending`; `cancelActive` loops; `discard()` is unreachable. |
+| two consumers on one host | multiplier, not mechanism | A/B/C published 4,951 pages with none; a second process only adds round trips that can park. |
+
+## Two-consumer arms (0.60.110, 1935c74a)
+
+15,000-page backlog on a 1,500-page history source, PgBouncer transaction
+mode, 57 ms, pool 10, `GBRAIN_SYNC_LANES=6` (effective 6), seed drain run
+7–8 min then SIGTERM (the reporter's watchdog kill), 40 s for its claims to
+lapse, `gbrain serve --http` boots alone and claims the dead run's FIFO head
+within one tick, `gbrain sync --source bench --no-pull --no-embed` 75 s
+later; 15 s samples with `writer status --probe --json` every other sample;
+wedge rule: a `preparing` stamp older than 5 min with nothing older than
+10 s in `pg_stat_activity`.
+
+| run | arm | two-consumer phase | pages | pages/min | max `preparing` stamp age | max active statement | max window with no commit | wedges |
+|---|---|---|---|---|---|---|---|---|
+| A (`two-A-110/`) | plain | 50 min | 432 → 3,215 | 55 | 25.5 s | 4.8 s | 100 s (the seed-kill → serve gap) | 0 |
+| B (`two-B-110/`) | adoption writes (60 legacy rows, 6 + 20 marker pages, `dream --phase extract_facts` every 120 s) + CLI SIGTERM/restart every 600 s (6 restarts) | 62 min | 73 → 1,153 | 17–23 | 16.3 s | 3.9 s | 67 s | 0 |
+| C (`two-C-110/`) | + `GBRAIN_DIRECT_DATABASE_URL` (dual pool: claims, followers and DDL on a 3-connection direct pool, as a Supabase deployment runs) + `--inspect`, restarts every 900 s (3) | 57 min | 93 → 1,181 | 19–24 | 16.8 s | 11.5 s | 115 s | 0 |
+
+What the two-process shape does show: serve claimed 18 FIFO group heads
+beside the CLI's 456 lane and FIFO claims in run A and published every one;
+while a serve-held group publishes under the exclusive worktree lock, the
+CLI's six lane transactions wait for their commit turn (`awaitLaneTurn`
+polling `SELECT state FROM persistence_requests …` `idle in transaction`,
+16 of 181 samples with four or more such transactions, worst 47 s) and roll
+back at 60 s, a slow cycle in the publishing phase; the dual pool changed
+nothing measurable. None of this parks a preparation.
+
+## What the budget does to the wedge (this branch)
+
+Nothing, by construction, and run F shows it: the budget wraps
+`run.prepare` (`startPreparation` in `executeClaimedGroup`), and the awaits
+that park under a dead exchange are the publication transaction's
+statements, the lease renewal, the consumer tick's `expired_claims` /
+`refresh_roots` / `switches` reads and the drain's progress poll. Wall
+clock in F: drop at 18:16:46, last commit 18:16:40, stall rule at 140 s,
+`deadline_exceeded` logged for the tick at +5 s and the tick still parked at
++134 s, no member cut at 120 s (`persistence.sync_preparation_ms`), no root
+block to measure against `persistence.preparation_ceiling_ms` (600 s)
+because no preparation was abandoned, no `preparation_stalled` after two
+attempts because no attempt was charged; the catch-up continued only when
+the network did (lift at +240 s, commit at +281 s), and the pass then died
+on `ECONNREFUSED` instead of retrying. The B6 stall line is the one thing
+that named the phase (`stalled 269s on publishing`); `writer status` could
+not run at all during the wedge (its own probe parks through the same
+pooler, killed at 120 s) and, once the network was back, called the member
+`stalled` / `cause_unknown`.
+
+## Recommended fix
+
+Settle every consumer-side round trip on the client, not the server: in
+`src/core/postgres-engine.ts` `runUnsafe` (2733–2748) race `await pending`
+against the signal and, once `pending.cancel()` has not settled it within a
+short grace, destroy the reserved socket (`owner.discard()` outside the
+`finally`, or a `Promise.race` that rejects and then discards), so the
+`phase()` deadline in `consumer.ts:598–618`, the renewal signal in
+`journal.ts:352` and the drain poll's signal in `service.ts:249` end their
+await with `CONNECTION_CLOSED` instead of parking; GBRA-59's PR 1.5 is this
+change and should land first. Then route the consumer's own round trips
+(claims, renewals, the tick's reads, the publication transaction) over the
+session-mode / direct URL when the dual pool is active
+(`postgres-engine.ts:608`, `connection-manager.ts` `isDualPoolActive`), and
+make `gbrain sources writer status` print the owner's current statement,
+its age and `wait_event` from `pg_stat_activity` for the owner's backends,
+so a `ClientRead` wedge is visible in one command; leave
+`persistence.single_consumer` off.
+
+## Rerun
+
+```bash
+# the mechanism, either build (RELEASE_COMMIT for 0.60.110; omit --cli-repo for this branch)
+UBI_OWNER=gbra61 scripts/ubicloud/ubi-runner.sh run -s standard-16 --setup scripts/bench/stall-repro-vm-setup.sh \
+ --env RELEASE_COMMIT=1935c74a9 -- 'python3 scripts/bench/stall-debug-instrument.py ../gbrain-release && \
+ bun scripts/bench/managed-sync-stall-repro.ts --cli-repo ../gbrain-release --scenario passes --lanes 1 --files 3000 --history 300 \
+ --legacy-facts 0 --marker-pages 0 --doomed-pages 0 --backlog-marker-pages 0 --adoption-interval 0 --rtt 57 --pool-size 10 \
+ --passes 1 --sample-seconds 10 --stall-minutes 2 --stall-kill-minutes 1000 --stall-signal SIGUSR2 \
+ --chaos-at 3 --chaos-kind partition --chaos-for 240 --out .context/bench/partition'
+
+# the two-consumer shape
+bun scripts/bench/managed-sync-stall-repro.ts --cli-repo ../gbrain-release --scenario two-consumer [--direct-pool] [--inspect] \
+ --files 15000 --history 1500 --rtt 57 --pool-size 10 --lanes 6 --seed-seconds 480 --seed-settle-seconds 40 \
+ --order serve-first --gap-seconds 75 --cli-restart-seconds 600 --max-minutes 60 --passes 6 --sample-seconds 15 \
+ --stall-minutes 5 --stall-kill-minutes 1000 --wedge-minutes 5 --wedge-hold-minutes 20 --stall-signal SIGUSR2 --out .context/bench/two
+```
+
+`git checkout -- src vendor && rm src/core/persistence/stall-debug.ts` undoes
+the instrument in a checkout.
diff --git a/scripts/bench/managed-sync-stall-repro.ts b/scripts/bench/managed-sync-stall-repro.ts
old mode 100755
new mode 100644
index ff3f7b7a6a..ee18d6ccdd
--- a/scripts/bench/managed-sync-stall-repro.ts
+++ b/scripts/bench/managed-sync-stall-repro.ts
@@ -8,7 +8,7 @@
* [--marker-pages 20] [--doomed-pages 12] [--drip-rows 20] [--backlog-marker-pages 20] [--rtt 57] [--pool-size 10] [--pooler pgbouncer|none]
* [--cli-repo <checkout>] [--max-minutes 90] [--passes 3] [--sample-seconds 30] [--adoption-interval 60]
* [--stall-minutes 5] [--stall-kill-minutes 15] [--stall-signal SIGUSR2] [--seed 1] [--label <name>] [--out <dir>] [--keep] [--inspect] [--inspect-port 6499]
- * [--chaos-at <minutes>] [--chaos-toxicity 0.3] [--chaos-kind timeout|reset|lock] [--chaos-stream downstream|upstream] [--chaos-for <seconds>]
+ * [--chaos-at <minutes>] [--chaos-toxicity 0.3] [--chaos-kind timeout|reset|lock|partition] [--chaos-stream downstream|upstream] [--chaos-for <seconds>]
* [--chaos-lock 'LOCK TABLE pages IN ACCESS EXCLUSIVE MODE']
* [--pg-port 55432] [--proxy-port 55433] [--api-port 58474] [--pooler-port 55434]
*
@@ -126,6 +126,37 @@ const CHAOS_GAP_MS = Number(flag('chaos-gap', '300')) * 1000;
const FENCE_REPAIR_AT_MS = Number(flag('fence-repair-at', '0')) * 60_000;
/** Phase 4.1: `--retry-held-after` runs `gbrain sources retry-held` plus the sync it prints once the passes end, and records what the held files did (`retry-held.json`). */
const RETRY_HELD_AFTER = process.argv.includes('--retry-held-after');
+/**
+ * #6317 (GBRA-61 Phase 0): `--scenario two-consumer` builds the reporter's two-process shape instead of the pass loop.
+ * A seeding drain (`gbrain sync`, bulk lanes `--lanes`) runs `--seed-seconds` and is killed with `--seed-kill` (the
+ * reporter's watchdog kill), leaving its lane groups queued; then `gbrain serve --http` and a fresh `gbrain sync` start
+ * `--gap-seconds` apart in `--order` (serve-first: serve boots, claims the FIFO head, the CLI arrives later, as in the
+ * reporter's timeline; cli-first: the reverse). `--cli-restart-seconds N` kills the CLI with SIGTERM every N s and
+ * restarts it 10 s later (the reporter's passes were restarted after each watchdog kill). A wedge is a `preparing`
+ * claim older than `--wedge-minutes` while nothing in pg_stat_activity is older than 10 s; on detection the sampler
+ * writes `wedge-<n>.json`, sends `--stall-signal` to every gbrain process it started and records each dump.
+ * `--seed-settle-seconds` lets the seed's claims lapse before the first consumer boots. `--serve-port` is the serve's HTTP port; `--wedge-hold-minutes` keeps a wedge alive that long before the scenario
+ * ends (0 = until --max-minutes).
+ */
+const SCENARIO = flag('scenario', 'passes');
+const LANES = flag('lanes', '6');
+const SEED_S = Number(flag('seed-seconds', '90'));
+const SEED_KILL = flag('seed-kill', 'SIGTERM');
+/** After the seed kill, time for its claims to lapse (30 s lease) before the first consumer boots, so that consumer sweeps and claims the dead run's groups alone, as serve did in the reporter's timeline. */
+const SEED_SETTLE_S = Number(flag('seed-settle-seconds', '40'));
+const ORDER = flag('order', 'serve-first');
+const GAP_S = Number(flag('gap-seconds', '75'));
+const CLI_RESTART_S = Number(flag('cli-restart-seconds', '0'));
+const SERVE_PORT = Number(flag('serve-port', '53131'));
+const WEDGE_MS = Number(flag('wedge-minutes', '5')) * 60_000;
+const WEDGE_HOLD_MS = Number(flag('wedge-hold-minutes', '0')) * 60_000;
+/** `--direct-pool`: every scenario process also gets GBRAIN_DIRECT_DATABASE_URL (the database without the pooler), so the engine runs its dual pool (claims, followers, renewals and DDL on a 3-connection direct pool) as a Supabase deployment does. */
+const DIRECT_POOL = process.argv.includes('--direct-pool');
+/** `--hang-after N` (debug instrument applied): the N-th managed_sync_import preparation of the scenario's `--hang-role` process (serve | cli-sync; default any) parks forever, the reporter's wedge on demand. */
+const HANG_AFTER = Number(flag('hang-after', '0'));
+const HANG_ROLE = flag('hang-role', '');
+if (!['passes', 'two-consumer'].includes(SCENARIO)) { console.error(`--scenario takes passes or two-consumer; got ${SCENARIO}`); process.exit(2); }
+if (!['serve-first', 'cli-first'].includes(ORDER)) { console.error(`--order takes serve-first or cli-first; got ${ORDER}`); process.exit(2); }
const LABEL = flag('label', `${gitDescribe(CLI_REPO)}-pool${POOL_SIZE}-${POOLER}`).replace(/[^\w.-]/g, '_');
const OUT = resolve(flag('out', join(REPO, '.context', 'bench', `stall-repro-${LABEL}-${Date.now()}`)));
if (POOLER !== 'pgbouncer' && POOLER !== 'none') { console.error(`--pooler takes pgbouncer or none; got ${POOLER}`); process.exit(2); }
@@ -349,7 +380,10 @@ const SAMPLE_SQL = {
};
interface SyncPass { pass: number; pid: number; inspect?: string; startedAt: number; endedAt?: number; code?: number; killedBy?: string; committedAtStart: number; committedAtEnd?: number; stallAt?: number; stallCaptured?: boolean }
-const state = { committed: 0, committedChangedAt: Date.now(), pass: null as SyncPass | null, samples: 0, stalls: [] as Array<Record<string, unknown>>, lastSample: null as Record<string, unknown> | null };
+interface Proc { label: string; kind: 'serve' | 'cli' | 'seed'; pid: number; startedAt: number; endedAt?: number; code?: number; killedBy?: string; exited: Promise<number>; stderrPath: string; child: ReturnType<typeof Bun.spawn> }
+const state = { committed: 0, committedChangedAt: Date.now(), pass: null as SyncPass | null, samples: 0, stalls: [] as Array<Record<string, unknown>>, lastSample: null as Record<string, unknown> | null,
+ procs: [] as Proc[], wedges: [] as Array<Record<string, unknown>>, wedgeSince: null as number | null, wedgeCaptured: false };
+const liveProcs = () => state.procs.filter(p => p.endedAt === undefined);
function append(file: string, record: Record<string, unknown>): void { appendFileSync(join(OUT, file), JSON.stringify(record) + '\n'); }
@@ -404,6 +438,7 @@ async function sampler(row: Row, stop: () => boolean): Promise<void> {
log(`sample ${n}: pass=${sample.pass} committed=${state.committed} stale=${Math.round(stale / 1000)}s running=${running.length}`
+ (running.length ? ` [${running.slice(0, 4).map(r => `${r.kind ?? r.operation}:${(r.claim_phase as { phase?: string } | null)?.phase ?? '?'}${r.blocked_reason ? '/' + r.blocked_reason : ''}`).join(', ')}]` : '')
+ ` activity=${Array.isArray(sample.activity) ? (sample.activity as unknown[]).length : '?'} locks=${Array.isArray(sample.locks) ? (sample.locks as unknown[]).length : '?'}`);
+ if (SCENARIO === 'two-consumer') await detectWedge(row, sample);
const pass = state.pass;
if (pass && !pass.endedAt && stale >= STALL_MS) {
if (!pass.stallAt) { pass.stallAt = Date.now() - stale; log(`STALL: no committed sync request for ${Math.round(stale / 1000)} s in pass ${pass.pass} (pid ${pass.pid})`); }
@@ -517,6 +552,22 @@ async function chaos(stop: () => boolean): Promise<void> {
if (CHAOS_AT_MS <= 0) return;
while (!stop() && !(state.pass && state.pass.pass === 1 && Date.now() - state.pass.startedAt >= CHAOS_AT_MS)) await Bun.sleep(1000);
if (stop()) return;
+ if (CHAOS_KIND === 'partition') {
+ // #6317: the client->pooler half of every gbrain connection is dropped (iptables, never closed): statements already sent park
+ // in JS while their backend waits in ClientRead for the rest of the exchange; new connections time out. The reporter's
+ // Supavisor wedge, deterministically and for every connection at once; lifted after --chaos-for.
+ const rule = ['OUTPUT', '-p', 'tcp', '--dport', flag('proxy-port', '55433'), '-j', 'DROP'];
+ execFileSync('sudo', ['iptables', '-I', ...rule], { stdio: 'inherit' });
+ append('chaos.jsonl', { t: Date.now(), at: new Date().toISOString(), action: 'partition', rule: rule.join(' '), pass: state.pass?.pass ?? null, committed: state.committed });
+ log(`CHAOS: partition: iptables -I ${rule.join(' ')}${CHAOS_FOR_MS > 0 ? ` for ${CHAOS_FOR_MS / 1000} s` : ''}`);
+ if (CHAOS_FOR_MS <= 0) return;
+ const until = Date.now() + CHAOS_FOR_MS;
+ while (!stop() && Date.now() < until) await Bun.sleep(1000);
+ execFileSync('sudo', ['iptables', '-D', ...rule], { stdio: 'inherit' });
+ append('chaos.jsonl', { t: Date.now(), at: new Date().toISOString(), action: 'partition_lifted', committed: state.committed });
+ log('CHAOS: partition lifted');
+ return;
+ }
if (CHAOS_KIND === 'lock') {
for (let episode = 1; episode <= Math.max(1, CHAOS_REPEAT) && !stop(); episode++) {
if (episode > 1) { const gapUntil = Date.now() + CHAOS_GAP_MS; while (!stop() && Date.now() < gapUntil) await Bun.sleep(1000); if (stop()) return; }
@@ -657,7 +708,7 @@ async function syncPass(row: Row, pass: number): Promise<SyncPass> {
const out = Bun.file(join(OUT, `pass-${pass}.stdout`)).writer();
const err = Bun.file(join(OUT, `pass-${pass}.stderr`)).writer();
const child = Bun.spawn(['timeout', '3600', process.execPath, ...(INSPECT ? [`--inspect=127.0.0.1:${INSPECT_PORT}`] : []), CLI, ...SYNC_ARGS], { cwd: row.home, stdin: 'ignore', stdout: 'pipe', stderr: 'pipe',
- env: childEnv(row.home, { GBRAIN_SQL_TRACE: row.trace, GBRAIN_SQL_TRACE_LABEL: 'cli-sync' }) });
+ env: childEnv(row.home, { GBRAIN_SQL_TRACE: row.trace, GBRAIN_SQL_TRACE_LABEL: 'cli-sync', GBRAIN_SYNC_LANES: LANES, ...(DIRECT_POOL ? { GBRAIN_DIRECT_DATABASE_URL: row.directUrl } : {}) }) });
// `timeout` is the parent; the gbrain process is its child. Find it for the kill and trace attribution.
await Bun.sleep(1500);
let gbrainPid = child.pid;
@@ -684,6 +735,155 @@ async function syncPass(row: Row, pass: number): Promise<SyncPass> {
return record;
}
+/** Oldest `preparing` claim (phase age from the stamp's `since`) and the oldest non-idle backend statement, both in ms. */
+function wedgeSignature(sample: Record<string, unknown>): { preparing_age_ms: number; preparing: number; oldest_active_query_ms: number; idle_in_tx_ms: number; running: number } {
+ const running = Array.isArray(sample.running) ? sample.running as Array<Record<string, unknown>> : [];
+ const now = Date.now();
+ let preparingAge = 0, preparing = 0;
+ for (const r of running) {
+ const phase = r.claim_phase as { phase?: string; since?: string; phase_since?: string } | null;
+ if (!phase || phase.phase !== 'preparing' || r.state !== 'running') continue;
+ preparing++;
+ const since = Date.parse(phase.phase_since ?? phase.since ?? '');
+ if (!Number.isNaN(since)) preparingAge = Math.max(preparingAge, now - since);
+ }
+ const activity = Array.isArray(sample.activity) ? sample.activity as Array<Record<string, unknown>> : [];
+ let oldestActive = 0, idleInTx = 0;
+ for (const a of activity) {
+ if (a.state === 'active') oldestActive = Math.max(oldestActive, Number(a.query_age_ms ?? 0));
+ if (String(a.state).startsWith('idle in transaction')) idleInTx = Math.max(idleInTx, Number(a.state_age_ms ?? 0));
+ }
+ return { preparing_age_ms: preparingAge, preparing, oldest_active_query_ms: oldestActive, idle_in_tx_ms: idleInTx, running: running.length };
+}
+
+/** Sends `signal` to every live gbrain process the scenario started and collects the `[stall-debug]` line each wrote. */
+async function dumpAll(signal: string): Promise<Array<Record<string, unknown>>> {
+ const procs = liveProcs();
+ for (const p of procs) { try { process.kill(p.pid, signal as NodeJS.Signals); } catch { /* gone */ } }
+ await Bun.sleep(2000);
+ const dumps: Array<Record<string, unknown>> = [];
+ for (const p of procs) {
+ const line = existsSync(p.stderrPath) ? readFileSync(p.stderrPath, 'utf8').split('\n').filter(l => l.startsWith('[stall-debug]')).at(-1) : undefined;
+ dumps.push({ label: p.label, pid: p.pid, dump: line ? safeJson(line.slice('[stall-debug] '.length)) : null });
+ }
+ return dumps;
+}
+
+/** #6317: the wedge rule (preparing > --wedge-minutes, nothing old at the server); one capture per episode, dumps on every sample while it lasts. */
+async function detectWedge(row: Row, sample: Record<string, unknown>): Promise<void> {
+ const sig = wedgeSignature(sample);
+ sample.wedge_signature = sig;
+ const wedged = sig.preparing_age_ms >= WEDGE_MS && sig.oldest_active_query_ms < 10_000;
+ if (!wedged) { if (state.wedgeSince) log(`wedge over: preparing_age=${Math.round(sig.preparing_age_ms / 1000)}s`); state.wedgeSince = null; state.wedgeCaptured = false; return; }
+ if (!state.wedgeSince) { state.wedgeSince = Date.now() - sig.preparing_age_ms; log(`WEDGE: ${sig.preparing} preparing claim(s), oldest ${Math.round(sig.preparing_age_ms / 1000)} s, oldest active statement ${sig.oldest_active_query_ms} ms, idle-in-tx ${sig.idle_in_tx_ms} ms; live procs ${liveProcs().map(p => `${p.label}:${p.pid}`).join(',')}`); }
+ const dumps = STALL_SIGNAL ? await dumpAll(STALL_SIGNAL) : [];
+ for (const d of dumps) { const dump = d.dump as { inflight?: Array<Record<string, unknown>>; sql_inflight?: unknown[]; pools?: unknown } | null; log(`stall-debug ${d.label}:${d.pid}: ${dump ? `inflight=${(dump.inflight ?? []).map(i => `${String(i.id).slice(0, 8)}@${i.step}/${Math.round(Number(i.step_age_ms) / 1000)}s`).join(' ')} sql_inflight=${(dump.sql_inflight ?? []).length} pools=${JSON.stringify(dump.pools ?? null).slice(0, 300)}` : 'no dump'}`); }
+ if (dumps.length) append('wedge-dumps.jsonl', { t: Date.now(), at: new Date().toISOString(), wedge: state.wedges.length, dumps });
+ if (state.wedgeCaptured) return;
+ state.wedgeCaptured = true;
+ const n = state.wedges.length + 1;
+ const via = row.poolerUrl ?? row.directUrl;
+ const pids = liveProcs().map(p => p.pid);
+ const capture: Record<string, unknown> = { ...sample, wedge_since: new Date(state.wedgeSince).toISOString(), procs: state.procs.map(({ child: _c, exited: _e, ...p }) => p), dumps,
+ running_detail: await admin(via, sql => sql.unsafe(`${BENCH_SQL} SELECT * FROM persistence_requests WHERE state IN ('running','recovering') ORDER BY sequence`), false).catch(e => String(e)),
+ queued_head: await admin(via, sql => sql.unsafe(`${BENCH_SQL} SELECT request_id, operation, intent->>'kind' AS kind, intent->>'group' AS grp, intent->>'lane' AS lane, intent->>'after' AS after, blocked_reason, created_at FROM persistence_requests WHERE state='queued' ORDER BY sequence LIMIT 20`), false).catch(e => String(e)),
+ cursor: await admin(via, sql => sql.unsafe(`${BENCH_SQL} SELECT fingerprint, completed_keys->0 AS cursor FROM op_checkpoints WHERE op='managed-sync'`), false).catch(e => String(e)),
+ pg_locks: await admin(harness.adminUrl, sql => sql.unsafe(`${BENCH_SQL} SELECT l.locktype, l.relation::regclass::text AS relation, l.mode, l.granted, l.pid, a.application_name, a.state FROM pg_locks l JOIN pg_stat_activity a ON a.pid=l.pid WHERE a.datname=$1 AND l.locktype IN ('relation','transactionid','tuple','advisory') ORDER BY l.pid`, [row.db])).catch(e => String(e)),
+ traces: Object.fromEntries(pids.map(pid => [pid, traceTail(row.trace, pid, 40)])),
+ os: { lslocks: sh('lslocks', '-n', '-o', 'PID,TYPE,MODE,PATH'), fds: Object.fromEntries(pids.map(pid => [pid, sh('sh', '-c', `ls -l /proc/${pid}/fd 2>/dev/null | grep -v socket | tail -n 30`)])),
+ ps: sh('ps', '-o', 'pid,ppid,stat,%cpu,etime,cmd', '-p', pids.join(',') || '0'), children: Object.fromEntries(pids.map(pid => [pid, sh('pgrep', '-P', String(pid))])) } };
+ writeFileSync(join(OUT, `wedge-${n}.json`), JSON.stringify(capture, null, 2) + '\n');
+ state.wedges.push({ n, wedge_since: capture.wedge_since, signature: sig, procs: capture.procs, dumps_summary: dumps.map(d => ({ label: d.label, pid: d.pid, inflight: ((d.dump as { inflight?: unknown[] } | null)?.inflight ?? []).length })) });
+ log(`wedge capture written: wedge-${n}.json`);
+}
+
+function sh(cmd: string, ...args: string[]): string {
+ try { return execFileSync(cmd, args, { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], timeout: 10_000 }).trim(); } catch (error) { return `(${cmd} failed: ${error instanceof Error ? error.message.split('\n')[0] : String(error)})`; }
+}
+
+/** One gbrain process of the scenario, output to `<label>.stdout` / `<label>.stderr`; the gbrain pid is the child itself (no `timeout` wrapper). */
+function spawnProc(row: Row, label: string, kind: Proc['kind'], args: string[], env: Record<string, string | undefined> = {}): Proc {
+ const out = Bun.file(join(OUT, `${label}.stdout`)).writer();
+ const err = Bun.file(join(OUT, `${label}.stderr`)).writer();
+ const child = Bun.spawn([process.execPath, ...(INSPECT && kind !== 'seed' ? [`--inspect=127.0.0.1:${INSPECT_PORT + state.procs.length}`] : []), CLI, ...args], { cwd: row.home, stdin: 'ignore', stdout: 'pipe', stderr: 'pipe',
+ env: childEnv(row.home, { GBRAIN_SQL_TRACE: row.trace, GBRAIN_SQL_TRACE_LABEL: label, GBRAIN_SYNC_LANES: LANES, ...(DIRECT_POOL ? { GBRAIN_DIRECT_DATABASE_URL: row.directUrl } : {}),
+ ...(HANG_AFTER > 0 && kind !== 'seed' ? { STALL_DEBUG_HANG_KIND: 'managed_sync_import', STALL_DEBUG_HANG_AFTER: String(HANG_AFTER), ...(HANG_ROLE ? { STALL_DEBUG_HANG_ROLE: HANG_ROLE } : {}) } : {}), ...env }) });
+ const pump = async (stream: ReadableStream<Uint8Array>, sink: { write(chunk: Uint8Array): unknown; flush(): unknown; end(): unknown }) => {
+ for await (const chunk of stream) { sink.write(chunk); await sink.flush(); }
+ await sink.end();
+ };
+ const proc: Proc = { label, kind, pid: child.pid, startedAt: Date.now(), stderrPath: join(OUT, `${label}.stderr`), child,
+ exited: Promise.all([child.exited, pump(child.stdout as ReadableStream<Uint8Array>, out), pump(child.stderr as ReadableStream<Uint8Array>, err)]).then(([code]) => { proc.endedAt = Date.now(); proc.code = code; return code; }) };
+ state.procs.push(proc);
+ log(`${label} started: pid ${child.pid} (${args.join(' ')})`);
+ append('procs.jsonl', { t: Date.now(), at: new Date().toISOString(), event: 'start', label, kind, pid: child.pid, args });
+ void proc.exited.then(code => { append('procs.jsonl', { t: Date.now(), at: new Date().toISOString(), event: 'exit', label, pid: child.pid, code, killed_by: proc.killedBy ?? null, wall_s: round1((proc.endedAt! - proc.startedAt) / 1000) });
+ log(`${label} exited: code=${code} ${proc.killedBy ?? ''} after ${round1((proc.endedAt! - proc.startedAt) / 1000)} s; stderr tail: ${readFileSync(proc.stderrPath, 'utf8').slice(-300).replace(/\n/g, ' | ')}`); });
+ return proc;
+}
+async function killProc(proc: Proc, signal: string, why: string): Promise<number> {
+ if (proc.endedAt !== undefined) return proc.code!;
+ proc.killedBy = `${signal}:${why}`;
+ log(`killing ${proc.label} (pid ${proc.pid}) with ${signal}: ${why}`);
+ try { process.kill(proc.pid, signal as NodeJS.Signals); } catch { /* gone */ }
+ const escalate = setTimeout(() => { try { process.kill(proc.pid, 'SIGKILL'); } catch { /* gone */ } }, 30_000);
+ const code = await proc.exited;
+ clearTimeout(escalate);
+ return code;
+}
+async function sleepUntil(until: number, stop: () => boolean): Promise<void> { while (!stop() && Date.now() < until) await Bun.sleep(500); }
+
+/** #6317: the reporter's two-consumer shape (see the `--scenario two-consumer` flags). */
+async function twoConsumerScenario(row: Row): Promise<void> {
+ const started = Date.now();
+ const stop = () => stopped || Date.now() - started >= MAX_MS;
+ const syncArgs = [...SYNC_ARGS];
+ // 1. seed: a lane drain that is killed mid-run, its admitted groups left queued (the reporter's killed passes).
+ const seed = spawnProc(row, 'seed-sync', 'seed', syncArgs);
+ state.pass = { pass: 0, pid: seed.pid, startedAt: seed.startedAt, committedAtStart: await committedCount(row) };
+ await Promise.race([seed.exited, sleepUntil(seed.startedAt + SEED_S * 1000, stop)]);
+ const seedCommitted = await committedCount(row);
+ if (seed.endedAt === undefined) await killProc(seed, SEED_KILL, `seed window of ${SEED_S} s over`);
+ state.pass = null;
+ const afterSeed = await admin(row.poolerUrl ?? row.directUrl, sql => sql.unsafe(`${BENCH_SQL} SELECT state, intent->>'lane' AS lane, count(*)::int AS n, min(sequence) AS first_seq FROM persistence_requests WHERE intent->>'kind' IN ('managed_sync_import','managed_sync_delete') GROUP BY 1,2 ORDER BY 1,2`), false).catch(e => [{ error: String(e) }]);
+ append('scenario.jsonl', { t: Date.now(), at: new Date().toISOString(), event: 'seeded', committed: seedCommitted, requests_by_state_and_lane: afterSeed });
+ log(`seeded: ${seedCommitted} committed; requests by state/lane: ${JSON.stringify(afterSeed).slice(0, 600)}`);
+ await sleepUntil(Date.now() + SEED_SETTLE_S * 1000, stop);
+ if (stop()) return;
+ // 2. the two consumers, --gap-seconds apart.
+ const startServe = () => spawnProc(row, `serve-${state.procs.filter(p => p.kind === 'serve').length + 1}`, 'serve', ['serve', '--http', '--port', String(SERVE_PORT), '--bind', '127.0.0.1'],
+ { GBRAIN_ADMIN_BOOTSTRAP_TOKEN: 'bench-admin-token-0123456789abcdefghijklmnopqrstuvwxyz' });
+ let passNo = 0;
+ const startCli = async () => { passNo++; const p = spawnProc(row, `cli-sync-${passNo}`, 'cli', syncArgs); state.pass = { pass: passNo, pid: p.pid, startedAt: p.startedAt, committedAtStart: await committedCount(row) }; state.committedChangedAt = Date.now(); return p; };
+ let serve: Proc | null = null, cli: Proc | null = null;
+ if (ORDER === 'serve-first') { serve = startServe(); await sleepUntil(Date.now() + GAP_S * 1000, stop); if (!stop()) cli = await startCli(); }
+ else { cli = await startCli(); await sleepUntil(Date.now() + GAP_S * 1000, stop); if (!stop()) serve = startServe(); }
+ // 3. keep the shape alive: restart the CLI on exit or on --cli-restart-seconds; end on synced, the wedge hold or --max-minutes.
+ let cliRestarts = 0;
+ while (!stop()) {
+ await Bun.sleep(1000);
+ if (serve && serve.endedAt !== undefined && Date.now() - serve.endedAt > 5000) { log(`serve exited on its own (code ${serve.code}); restarting it`); serve = startServe(); }
+ if (cli && cli.endedAt !== undefined) {
+ const status = readFileSync(join(OUT, `${cli.label}.stdout`), 'utf8').concat(readFileSync(cli.stderrPath, 'utf8'));
+ const synced = /Managed sync synced|"sync_status"\s*:\s*"synced"/.test(status);
+ const pass = state.pass as SyncPass | null;
+ if (pass && pass.pid === cli.pid) { pass.endedAt = cli.endedAt; pass.code = cli.code; pass.committedAtEnd = await committedCount(row); append('passes.jsonl', { ...pass, label: cli.label, killed_by: cli.killedBy ?? null }); state.pass = null; }
+ if (synced) { log('CLI reports synced; scenario ends'); append('scenario.jsonl', { t: Date.now(), at: new Date().toISOString(), event: 'synced', cli: cli.label }); break; }
+ if (cliRestarts >= PASSES) { log(`CLI exited ${cliRestarts + 1} times; no more restarts (--passes ${PASSES})`); cli = null; }
+ else { cliRestarts++; await sleepUntil(Date.now() + 10_000, stop); if (!stop()) cli = await startCli(); }
+ continue;
+ }
+ if (cli && CLI_RESTART_S > 0 && Date.now() - cli.startedAt >= CLI_RESTART_S * 1000) { await killProc(cli, 'SIGTERM', `--cli-restart-seconds ${CLI_RESTART_S}`); continue; }
+ if (WEDGE_HOLD_MS > 0 && state.wedgeSince && Date.now() - state.wedgeSince >= WEDGE_HOLD_MS) { log(`wedge held ${Math.round(WEDGE_HOLD_MS / 60_000)} min; scenario ends`); break; }
+ }
+ // 4. teardown: stop both, recording whether the stuck preparation settles when the other process dies.
+ if (cli && cli.endedAt === undefined) { await killProc(cli, 'SIGTERM', 'scenario end'); await Bun.sleep(15_000); const after = await sampleOnce(row, true); writeFileSync(join(OUT, 'after-cli-exit.json'), JSON.stringify({ ...after, wedge_signature: wedgeSignature(after), dumps: STALL_SIGNAL ? await dumpAll(STALL_SIGNAL) : [] }, null, 2) + '\n'); log(`after CLI exit: ${JSON.stringify(wedgeSignature(after))} committed=${after.committed}`); }
+ if (serve && serve.endedAt === undefined) await killProc(serve, 'SIGTERM', 'scenario end');
+ for (const p of liveProcs()) await killProc(p, 'SIGKILL', 'scenario end');
+ report.scenario = { kind: SCENARIO, direct_pool: DIRECT_POOL, hang_after: HANG_AFTER, hang_role: HANG_ROLE || null, lanes: LANES, seed_seconds: SEED_S, seed_kill: SEED_KILL, seed_settle_seconds: SEED_SETTLE_S, order: ORDER, gap_seconds: GAP_S, cli_restart_seconds: CLI_RESTART_S, serve_port: SERVE_PORT,
+ wedge_minutes: WEDGE_MS / 60_000, procs: state.procs.map(({ child: _c, exited: _e, ...p }) => p), wedges: state.wedges, cli_restarts: cliRestarts };
+}
+
function statusOf(pass: number): string | null {
const text = readFileSync(join(OUT, `pass-${pass}.stdout`), 'utf8') + readFileSync(join(OUT, `pass-${pass}.stderr`), 'utf8');
const m = text.match(/"sync_status"\s*:\s*"(\w+)"/) ?? text.match(/\b(synced|up to date|up_to_date|first_sync|partial|stopped)\b/i);
@@ -730,7 +930,8 @@ try {
const passes: SyncPass[] = [];
const passExtras = new Map<number, Record<string, unknown>>();
const started = Date.now();
- for (let pass = 1; pass <= PASSES && Date.now() - started < MAX_MS; pass++) {
+ if (SCENARIO === 'two-consumer') await twoConsumerScenario(row);
+ for (let pass = 1; SCENARIO === 'passes' && pass <= PASSES && Date.now() - started < MAX_MS; pass++) {
const result = await syncPass(row, pass);
passes.push(result);
const status = statusOf(pass);
@@ -761,7 +962,7 @@ try {
const doctorChecks = (doctorFences.json?.checks as Array<Record<string, unknown>> | undefined) ?? [];
const fenceCheck = doctorChecks.find(c => c.name === 'fence_integrity' || c.check === 'fence_integrity' || c.id === 'fence_integrity') ?? doctorChecks[0] ?? null;
const unrenderable = ((fenceCheck?.details ?? fenceCheck?.data ?? fenceCheck ?? {}) as Record<string, unknown>).unrenderable_legacy_facts as { total?: number; complete?: boolean; pages?: Array<{ slug: string; rows: Array<{ class: string; reason: string }> }> } | undefined;
- report.result = { committed_sync_requests: state.committed, chaos: chaosEvents, stall_debug_last: stallDebug.at(-1) ?? null, backlog_entries: backlogPages.length, states: final.states, stalls: state.stalls,
+ report.result = { committed_sync_requests: state.committed, chaos: chaosEvents, wedges: state.wedges, stall_debug_last: stallDebug.at(-1) ?? null, backlog_entries: backlogPages.length, states: final.states, stalls: state.stalls,
preparing_claims_observed: preparingClaimsObserved(),
doctor_fence_integrity: { exit: doctorFences.code, status: fenceCheck?.status ?? null, unrenderable_total: unrenderable?.total ?? null, unrenderable_complete: unrenderable?.complete ?? null,
unrenderable_by_class: Object.fromEntries([...(unrenderable?.pages ?? []).flatMap(p => p.rows).reduce((m, r) => m.set(`${r.class}/${r.reason}`, (m.get(`${r.class}/${r.reason}`) ?? 0) + 1), new Map<string, number>())]),
diff --git a/scripts/bench/stall-debug-instrument.py b/scripts/bench/stall-debug-instrument.py
index 2c43cb31b0..0ddc563aac 100644
--- a/scripts/bench/stall-debug-instrument.py
+++ b/scripts/bench/stall-debug-instrument.py
@@ -43,6 +43,47 @@ export function stallMark(id: string, step: string): void {
}
export function stallDone(id: string): void { inflight.delete(id); }
export function stallRegister(name: string, fn: () => unknown): void { install(); extras.set(name, fn); }
+/** #6317: every raw statement between its send in JS and its settle; one that is here but not in pg_stat_activity is waiting for a connection. */
+const sqlInflight = new Map<number, { sql: string; since: number; pool: string; reserved: boolean }>();
+let sqlSeq = 0;
+export function stallSql(sql: string, pool: string, reserved = false): () => void {
+ install();
+ const id = ++sqlSeq;
+ sqlInflight.set(id, { sql: sql.replace(/\\s+/g, ' ').slice(0, 160), since: Date.now(), pool, reserved });
+ return () => { sqlInflight.delete(id); };
+}
+/** #6317: postgres.js pool queues (vendor/postgres/src/index.js exposes `queues` and registers each pool here when instrumented). */
+export function stallPools(): unknown {
+ const pools = (globalThis as { __gbrainPools?: Array<{ options: { max: number; host?: string[]; port?: number[]; database?: string }; queues?: Record<string, { length: number }> }> }).__gbrainPools ?? [];
+ return pools.map((pool, i) => ({ i, max: pool.options?.max, database: pool.options?.database, port: pool.options?.port,
+ ...Object.fromEntries(Object.entries(pool.queues ?? {}).map(([name, queue]) => [name, queue.length])) }));
+}
+/**
+ * #6317 forced wedge (debug only): with STALL_DEBUG_HANG_KIND=<intent kind> (e.g. managed_sync_import), the preparation of
+ * the STALL_DEBUG_HANG_AFTER-th (default 40th) request of that kind in this process parks on a promise that never settles and
+ * ignores its signal: the reporter's never-settling await with nothing in flight at the database. STALL_DEBUG_HANG_ROLE limits
+ * it to processes whose GBRAIN_SQL_TRACE_LABEL starts with that prefix (e.g. serve, cli-sync). Hung ids appear in the dump.
+ */
+const hung: Array<{ id: string; since: number }> = [];
+let seenOfKind = 0;
+const hungIds = new Set<string>();
+export async function stallMaybeHang(id: string, kind: string | undefined, attempts = 0): Promise<void> {
+ const wanted = process.env.STALL_DEBUG_HANG_KIND;
+ if (!wanted || kind !== wanted) return;
+ const role = process.env.STALL_DEBUG_HANG_ROLE;
+ const mine = !role || (process.env.GBRAIN_SQL_TRACE_LABEL ?? '').startsWith(role);
+ if (mine) seenOfKind++;
+ // Sticky: the chosen request hangs again whenever this process prepares it, and (budget builds) any request already cut once
+ // hangs in every process, so a re-claim after a cut parks again the way the reporter's did.
+ if (!(mine && seenOfKind === Number(process.env.STALL_DEBUG_HANG_AFTER ?? '40')) && !hungIds.has(id) && !(attempts > 0)) return;
+ hungIds.add(id);
+ hung.push({ id, since: Date.now() });
+ process.stderr.write(`[stall-debug] HANG request ${id} (${kind}) parked forever in pid ${process.pid}\n`);
+ await new Promise<never>(() => {});
+}
+stallRegister('hung', () => { const now = Date.now(); return hung.map(h => ({ ...h, age_ms: now - h.since })); });
+stallRegister('sql_inflight', () => { const now = Date.now(); return [...sqlInflight.values()].map(s => ({ ...s, age_ms: now - s.since })); });
+stallRegister('pools', stallPools);
'''
def edit(path, fn):
@@ -69,10 +110,11 @@ if not os.path.exists(mod):
# 2. service.ts: wrap preparePersistedMutation; register the consumer status
def service(text):
if 'preparePersistedMutationInner' in text: return text
- text = ensure_import(text, "import { stallDone, stallMark, stallRegister } from './stall-debug.ts';")
+ text = ensure_import(text, "import { stallDone, stallMark, stallMaybeHang, stallRegister } from './stall-debug.ts';")
text = text.replace('export async function preparePersistedMutation(e: BrainEngine, row: WriteRequest, cfg: GBrainConfig, signal?: AbortSignal) {',
'export async function preparePersistedMutation(e: BrainEngine, row: WriteRequest, cfg: GBrainConfig, signal?: AbortSignal) {\n'
" stallMark(row.request_id, `dispatch:${row.operation}:${row.intent?.kind ?? ''}`);\n"
+ " stallMark(row.request_id, 'debug_hang_check'); await stallMaybeHang(row.request_id, row.intent?.kind as string | undefined, Number((row as { preparation_attempts?: number }).preparation_attempts ?? 0));\n"
' try { return await preparePersistedMutationInner(e, row, cfg, signal); } finally { stallDone(row.request_id); }\n'
'}\n'
'async function preparePersistedMutationInner(e: BrainEngine, row: WriteRequest, cfg: GBrainConfig, signal?: AbortSignal) {', 1)
@@ -123,4 +165,65 @@ def maintenance(text):
return '\n'.join(lines)
if os.path.exists(P('prepared-maintenance.ts')): report.append(f"prepared-maintenance.ts edited={edit(P('prepared-maintenance.ts'), maintenance)}")
+
+# 5. consumer.ts: the group claim path before executeClaimedGroup (#6317: head order, follower claim, group start)
+def consumer(text):
+ if "from './stall-debug.ts'" in text: return text
+ text = ensure_import(text, "import { stallMark, stallDone } from './stall-debug.ts';")
+ text = text.replace(" const order = await claimedHeadOrder(this.engine, row, lane !== null);",
+ " stallMark(row.request_id, 'consumer:head_order');\n const order = await claimedHeadOrder(this.engine, row, lane !== null);\n stallMark(row.request_id, `consumer:head_order_done:${order === 'wait' ? 'wait' : order ? 'cancel' : 'go'}`);", 1)
+ text = text.replace(" const followers = await claimGroupFollowers(this.engine, row, group,",
+ " stallMark(row.request_id, 'consumer:claim_followers');\n const followers = await claimGroupFollowers(this.engine, row, group,", 1)
+ text = text.replace(" return await executeClaimedGroup(this.engine, rows, {",
+ " stallMark(row.request_id, `consumer:group_start:${rows.length}:${lane ? 'lane' : 'fifo'}`);\n return await executeClaimedGroup(this.engine, rows, {", 1)
+ text = text.replace(" } finally { for (const member of rows) this.executing.delete(member.id); }\n }\n /** Mandatory barrier",
+ " } finally { for (const member of rows) { this.executing.delete(member.id); stallDone(member.request_id); } stallDone(row.request_id); }\n }\n /** Mandatory barrier", 1)
+ return text
+report.append(f"consumer.ts edited={edit(P('consumer.ts'), consumer)}")
+
+# 6. group-publish.ts: wave dispatch, lease outcome, publish entry (both the 0.60.110 and the budget shape)
+def group_publish(text):
+ if "from './stall-debug.ts'" in text: return text
+ text = ensure_import(text, "import { stallMark } from './stall-debug.ts';")
+ text = text.replace(" try { prepared[start + offset] = { ok: await run.prepare(row) }; }",
+ " stallMark(row.request_id, `group:dispatch:${start + offset}`);\n try { prepared[start + offset] = { ok: await run.prepare(row) }; stallMark(row.request_id, 'group:prepared'); }", 1)
+ text = text.replace(" return run.prepare(row, reads, undefined, clocks[i]);",
+ " stallMark(row.request_id, `group:dispatch:${i}`);\n return run.prepare(row, reads, undefined, clocks[i]).then(value => { stallMark(row.request_id, 'group:prepared'); return value; });", 1)
+ text = text.replace(" const preparing = (async () => {",
+ " for (const row of rows) stallMark(row.request_id, 'group:queued_in_group');\n const preparing = (async () => {", 1)
+ text = text.replace(" const lock = lane ? await acquireWorktreeShared(binding, engine)",
+ " for (const row of rows) stallMark(row.request_id, lane ? 'publish:acquire_worktree_shared' : 'publish:acquire_worktree');\n const lock = lane ? await acquireWorktreeShared(binding, engine)", 1)
+ text = text.replace(" if (lane) await awaitLaneBegin(lane, rows);\n const done = await transaction(",
+ " if (lane) { for (const row of rows) stallMark(row.request_id, 'publish:await_lane_begin'); await awaitLaneBegin(lane, rows); }\n for (const row of rows) stallMark(row.request_id, 'publish:transaction');\n const done = await transaction(", 1)
+ text = text.replace(" if (lane) await awaitLaneBegin(lane, rows);\n const done = await engine.transaction(",
+ " if (lane) { for (const row of rows) stallMark(row.request_id, 'publish:await_lane_begin'); await awaitLaneBegin(lane, rows); }\n for (const row of rows) stallMark(row.request_id, 'publish:transaction');\n const done = await engine.transaction(", 1)
+ return text
+report.append(f"group-publish.ts edited={edit(P('group-publish.ts'), group_publish)}")
+
+# 7. postgres-engine.ts: every raw statement and reserve while it is in flight in JS
+PE = os.path.join(repo, 'src', 'core', 'postgres-engine.ts')
+def postgres_engine(text):
+ if "persistence/stall-debug.ts" in text: return text
+ text = ensure_import(text, "import { stallSql } from './persistence/stall-debug.ts';")
+ text = text.replace(" reserved = signal && typeof conn.reserve === 'function' ? await reserveWithCancellation(opts => conn.reserve(opts), signal) : undefined;",
+ " const __reserveDone = signal && typeof conn.reserve === 'function' ? stallSql(`RESERVE for ${sql}`, 'raw', true) : null;\n try { reserved = signal && typeof conn.reserve === 'function' ? await reserveWithCancellation(opts => conn.reserve(opts), signal) : undefined; } finally { __reserveDone?.(); }", 1)
+ text = text.replace(" pending = conn.unsafe(sql, params as Parameters<typeof conn.unsafe>[1], driverOpts);\n return await pending as unknown as T[];",
+ " const __sqlDone = stallSql(sql, reserved ? 'raw:reserved' : this._pageTransaction ? 'tx' : 'raw', !!reserved);\n try {\n pending = conn.unsafe(sql, params as Parameters<typeof conn.unsafe>[1], driverOpts);\n return await pending as unknown as T[];\n } finally { __sqlDone(); }", 1)
+ text = text.replace(" reserved = await pool.reserve();\n } catch (e) {",
+ " const __reserveDone = stallSql('RESERVE withReservedConnection', 'reserved', true);\n try { reserved = await pool.reserve(); } finally { __reserveDone(); }\n } catch (e) {", 1)
+ text = text.replace(" return await withHeldPageKeys(this._pageTransaction ? this._heldPageKeys : null, held => conn.begin(async (handle) => {",
+ " const __beginDone = this._pageTransaction ? null : stallSql('BEGIN (transaction checkout)', 'tx', true);\n try { return await withHeldPageKeys(this._pageTransaction ? this._heldPageKeys : null, held => conn.begin(async (handle) => {\n __beginDone?.();", 1)
+ text = text.replace(" return fn(txEngine);\n }) as Promise<T>);\n } finally {\n if (!this._pageTransaction) this.checkoutGauge.release('tx');",
+ " return fn(txEngine);\n }) as Promise<T>); } finally { __beginDone?.(); }\n } finally {\n if (!this._pageTransaction) this.checkoutGauge.release('tx');", 1)
+ return text
+report.append(f"postgres-engine.ts edited={edit(PE, postgres_engine)}")
+
+# 8. vendor/postgres/src/index.js: expose the pool queues and register every pool (debug only)
+VP = os.path.join(repo, 'vendor', 'postgres', 'src', 'index.js')
+def vendor_pool(text):
+ if '__gbrainPools' in text: return text
+ return text.replace(" Object.assign(sql, {\n get parameters() { return options.parameters },",
+ " ;(globalThis.__gbrainPools ??= []).push(sql)\n Object.assign(sql, {\n queues,\n get parameters() { return options.parameters },", 1)
+report.append(f"vendor/postgres edited={edit(VP, vendor_pool)}")
+
print('\n'.join(report))