Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(persistence): record each write claim's phase and add the persistence_write_stall doctor check (#6176)

garrytan97cd8e4988e4
diff --git a/docs/ENGINES.md b/docs/ENGINES.md
index 2f1d87585e..a41f13b156 100644
--- a/docs/ENGINES.md
+++ b/docs/ENGINES.md
@@ -664,6 +664,21 @@ never holds a direct or session-pooler connection, so a
`GBRAIN_DIRECT_DATABASE_URL` that points at a session pooler is not pinned by
idle `gbrain serve` processes.
+<a id="persistence-claim-phase"></a>**Claim phases and `persistence.max_claim_ms`.** Each claim renewal
+(every 10 seconds) also records which phase the claimed write is in
+(`preparing` or `publishing`), when the claim started and when that phase
+started, in the request's `claim_phase` column, keyed to the claim's execution
+token. `gbrain sources writer status --json` shows it on every running blocker as
+`claim` (`phase`, `claim_age_ms`, `phase_age_ms`, `resumes_on_its_own`, `why`);
+a running request whose claim lapsed is reported as `publication_transaction`
+and one whose files were being published as `file_publication`. Doctor's
+`persistence_write_stall` warns when a claim is older than
+`persistence.max_claim_ms` (milliseconds; default 600000, 10 minutes, about 40
+times the 15-second bulk transaction budget; valid 60000 to 86400000; `gbrain
+config set persistence.max_claim_ms 900000` raises it, and `config set` refuses
+anything else with `invalid_params`). See
+[troubleshooting](guides/troubleshooting.md#persistence-write-stall).
+
## JSONB writes: never double-encode
Writing a JS value into a `jsonb` column has exactly two correct forms. Get this
diff --git a/docs/architecture/key-files/commands-2.md b/docs/architecture/key-files/commands-2.md
index c77071dbfe..db70cfdd7a 100644
--- a/docs/architecture/key-files/commands-2.md
+++ b/docs/architecture/key-files/commands-2.md
@@ -9,7 +9,7 @@ Doctor's embedding-dimension warning treats existing chunks as existing data eve
- `src/commands/doctor/checks/behavior-changes.ts` — `behavior_changes` (META, after `chat_fallback_chain`): the `behavior_changes` disclosure read again (`src/core/behavior-change-notice.ts`): every change newer than the brain's baseline, labeled by release, whether or not the notice was shown; always `ok`; reads the baseline and markers without recording either, and reports which channels were shown.
- `src/commands/doctor/checks/ranking-extraction.ts` — informational BRAIN check `extraction_date_grounding`, registered after `timeline_history`: fact extraction, synthesis, atoms and takes grounded by default, all off when the setting is false, and whether the chronicle prompt is opted in. Pinned by `test/doctor-ranking-extraction.test.ts` and the doctor registry/JSON goldens.
- `src/commands/doctor/checks/vector-plan.ts` — `vector_plan` (#5824, OPS, wave check with operator resolution). Postgres only: EXPLAINs (no ANALYZE) the statement `searchVector` emits for the active embedding column with a zero vector through `PostgresEngine.explainVectorSearch` (same builder, scoped read transaction and scan settings) and warns when an HNSW-indexed column's plan does not use its HNSW index, naming the observed scans, whether the index exists and is valid (`pg_index.indisvalid`, with the create/reindex command), the 8 s candidate-budget risk and the legacy guard as rollback. Skipped on PGLite, on columns wider than the HNSW cap, and below 10,000 embedded chunks (`pg_class.reltuples` x `pg_stats.null_frac`, a bounded count when never analyzed). A configured legacy guard warns "active after restarting the owning service". Details carry a sampled stale-text fraction and point to `gbrain embed --stale` above 5%. Tested in `test/e2e/vector-plan-real-column-postgres.test.ts` (empty, small, ok, unused valid index, INVALID index, guard via env and config).
-- `src/commands/doctor/checks/persistence-requests.ts` — two wave checks (OPS, registered in `wave-checks.ts`). `persistence_request_indexes` (#5762) reports each managed sync request index missing, INVALID or still building (with progress) and names `gbrain repair request-indexes --apply`. `persistence_request_growth` reports the request-table row count (a `reltuples` estimate on Postgres), each scope's admission rate over the last 7 days (the newest 10,000 admissions per scope, one bounded index read), lifetime IDs against `persistence.limits.*` and the projected exhaustion date within ten years; it warns under 90 days with the `oneYearCapacity` `gbrain config set` value and the doctor re-check. Tests: `test/persistence-request-indexes.test.ts`, `test/e2e/persistence-request-indexes-postgres.test.ts`.
+- `src/commands/doctor/checks/persistence-requests.ts` — three wave checks (OPS, registered in `wave-checks.ts`). `persistence_request_indexes` (#5762) reports each managed sync request index missing, INVALID or still building (with progress) and names `gbrain repair request-indexes --apply`. `persistence_request_growth` reports the request-table row count (a `reltuples` estimate on Postgres), each scope's admission rate over the last 7 days (the newest 10,000 admissions per scope, one bounded index read), lifetime IDs against `persistence.limits.*` and the projected exhaustion date within ten years; it warns under 90 days with the `oneYearCapacity` `gbrain config set` value and the doctor re-check. `persistence_write_stall` (#6176, host-only) reads running requests and warns when one has held its claim longer than `persistence.max_claim_ms` (`claim-phase.ts`; an owner that predates phase recording falls back to the request's age on the database clock), naming the stuck phase, the root, the claim age, the queued writes behind it and whether the request resumes on its own, with `gbrain sources writer status --source <id> --json` as the fix. Tests: `test/persistence-request-indexes.test.ts`, `test/e2e/persistence-request-indexes-postgres.test.ts`, `test/persistence-write-stall.test.ts`.
- `src/commands/doctor/checks/{persistence-capacity,parked-effects}.ts` — `persistence_capacity` (OPS) warns when a principal or the brain reaches 80% of permanent request IDs or receipt bytes (via `capacityDiagnostics`) and prints one `gbrain config set <key> <value>` per brain-wide key, using the largest value any scope needs for about one more year; transient caps never warn. `parked_effects` (BRAIN) reads the partial parked-effect index, counts exactly, samples 20, and names each parked page with its `retry-effects ... --dry-run` command. Both report `exact`/`inspected`/`truncated` details; an unreadable state is warn, never clean. Tests: `test/persistence-capacity.test.ts`, `test/persistence-effect-parking.test.ts`.
- `src/commands/doctor/checks/unbound-source.ts` — `unbound_source` (#5254) counts live pages with `pages.database_only_reason='unbound_source'` per source. While the source is unbound the count is ok and the message carries the filled `sources writer status`/`writer claim` bind command (database-only is the chosen mode); once the source has a binding it warns, because binding never materializes those pages into canonical files. Unreadable state warns. Registered on the `persistence_capacity` line in `doctor.ts`. Test: `test/e2e/unbound-source-postgres.test.ts`.
- `src/commands/doctor/checks/revision-backfill.ts` — `revision_backfill` (#5216, META, registered before `search_mode`): reads `readRevisionBackfillStatus` (column state, pages still without `knowledge_revision`, failed rows still pending with their page). ok when the column is NOT NULL; warn with the pending count and `gbrain apply-migrations --force-schema` as `fix` while any row is resumable (or only the NOT NULL step remains); failed rows are listed by page id, `source:slug`, attempt and error, and when only rows with spent attempts remain the `fix` is the read-only `gbrain repair orphan-children` preview. Tests: `test/doctor-revision-backfill.test.ts`.
diff --git a/docs/architecture/key-files/core-persistence.md b/docs/architecture/key-files/core-persistence.md
index d82622755a..ffadd5611a 100644
--- a/docs/architecture/key-files/core-persistence.md
+++ b/docs/architecture/key-files/core-persistence.md
@@ -28,7 +28,8 @@ Connector ingestion, item holds and checkpoint validation continue in [Core Pers
- `src/core/persistence/admission-retry.ts` — bounded retries for database-confirmed admission transaction aborts. Each retry reuses the UUID and normalized intent, rechecks guarded authority and reserves quota only on commitment. Standalone journal admission uses 100ms lock waits within the five-second retry budget to retain queue position behind short counter transactions; backoff occurs after rollback releases the connection so counter contention leaves pool capacity for reads. Ambiguous connection/commit errors are never classified as confirmed rollback. Real counter-lock, sustained-queue progress, read-capacity and after-insert rollback tests live in `test/persistence-journal.test.ts`. Withdrawal retries wrap its whole source-exclusive transaction with its existing lock policy; `admitWriteInTransaction` never backs off inside an existing unit of work. `test/persistence-withdrawal-retry.test.ts` verifies guard release, complete rollback and bounded contention.
-- `src/core/persistence/consumer.ts` — resident canonical-write consumer with retained wake-ups, root-scoped retry backoff and locked-row-skipping expired-claim sweeps. A full tick fans out to every worker; when idle, each tick instead runs one work probe (a single statement mirroring the claim, recovery, expired-claim, effect, projection and topology predicates, excluding rows those workers would skip, including topology recoveries that failed to finish within the last 30 s) and the poll interval doubles from 250 ms to a 5 s cap (`idleMaxMs`), resetting on work. `wake()` runs a full tick immediately; `waitForWrite` calls it after a same-process admission commits, so cross-process writes wait at most 5 s plus one probe and no LISTEN is used. #5984: `awaitWrite` (`waitForWrite` is its row-only form) receives a request this consumer publishes through the `onSettled` handoff with no request read, and skips polls while `holds(id)` says the consumer has it claimed; otherwise it polls the narrow `WRITE_PROGRESS_SQL` (first poll after min(200 ms, half the wait), then 50 ms backing off to 250 ms) and reads the full row once when terminal. Its own cancelled reads are not failures; a database read failure ends the wait as a classified `read_failed` (auth/permission failures at once), and a pending head with an intervention `blocked_reason` ends as `blocked`. A probe failure is reported once and the next tick runs the full fan-out. On Postgres pools of three or more with no connection checked out, idle probes share one reserved connection from the ordinary pool, never the direct/session route (acquired and queried under the phase deadline; a timed-out lane returns to the pool once its query settles) so the rest of the pool drains through the 20 s `idle_timeout` (postgres.js reuses idle connections first-in-first-out); root refresh and receipt compaction run every 5 minutes while idle. Root refresh, recovery scan, sweep and capacity-marking SQL use cooperative five-second cancellation; failure never admits work under stale confinement. Cold direct initialization and queued transactions remain observed and awaited through shutdown. Recognized cancellation owned by the consumer's stop reason is not reported as a storage failure; deadline-first cancellation and unrelated storage errors remain visible. The rate-limited stderr line names the phase, the SQLSTATE or write-error code, a redacted one-line message of at most 200 characters, connection-wait evidence (`first_conn_ms`, or `checkout=not_observed conn_wait_ms`, attributed to the phase through AsyncLocalStorage over the engine's `onCheckout` seam) plus `loop_lag_ms`, a fix command and its docs anchor (`docs/ENGINES.md#persistence-consumer-log`); the trusted status `phase` carries the same fields. Ordinary put-page/remember preparation has a cooperative 30-second deadline; abort-ignoring work remains tracked, and late preparation cannot publish. Publication and shutdown retain the token/native-lock/recovery barriers. Trusted status exposes sampled process-local phases and attempts, not durable progress. A tick woken by a completed publication or a local admission claims the next write at once and runs root refresh plus recovery, expiry and topology scans at most once per poll interval; explicit, timer and idle-probe ticks always scan. Effects drain in batches of 20 without waiting for the next tick while full batches keep arriving; within a batch, git effects wait for their asynchronous durability probe (one per worktree root) after the other effects, and a single-file git effect in a repository without the durability hook acquires the worktree lock only to prove its root and records its outcome after releasing it. Each projection-worker invocation (`runResidentProjectionInvocation`, #5401) rebuilds up to 100 pages and starts no new page once 250 ms have passed since it began; when `hasClaimableWrite` (the `CLAIMABLE_WRITE_SQL` predicate `claimNextWrite` claims with, in `journal.ts`) finds a claimable write at its start it takes 2 pages, and its selector skips failed rows for 30 s through the same `PROJECTION_RETRY_READY_SQL` fragment as the idle probe (measured PGLite rebuild cost on a 1,000-page fixture: mean ~9.5 ms, p99 ~18 ms per page). On PGLite the first full tick releases claims last written before this process started (`releaseAbandonedClaims` in `effect-journal.ts`: running effects and unpublished requests without a recovery record), since the datastore admits one process and those owners have exited; Postgres keeps lease expiry (requests 30 s, effects 2 minutes). On PGLite, which has no autovacuum, the maintenance worker also runs `vacuumPersistenceQueues` (VACUUM ANALYZE of the queue tables) every minute or after 50 + 20% of the request table's rows in publications. Tests: `persistence-consumer-scheduling.test.ts`, `persistence-consumer-idle.test.ts`, `persistence-consumer-log.test.ts`, `projection-drain.test.ts` (injected clock and per-page cost), `persistence-root-refresh.test.ts`, `test/e2e/persistence-phase-liveness.test.ts`, `test/e2e/persistence-idle-pool.test.ts`. With `requestsOnly` (engine graduation's drain) the effect, projection, topology and maintenance workers never start; claim, recovery, expired-claim and publication run as usual and `stop()` remains the barrier. Both the single route and the grouped/lane route (`executeClaimedGroup` in `group-publish.ts`) prepare under a claim lease (`claim-lease.ts`: a renewal every `renewalIntervalMs`, default 10 s, each bounded by `phaseMs`); the claim is lost the first time a renewal says it is gone, throws or overruns, and `whileHeld` stops waiting on the preparation at that moment (the single route also aborts it). The claims still ours are released unpublished with `claim_lost` (token-fenced, so a consumer that took one over keeps it); the abandoned preparation is never published and keeps its root or lane slot until it settles, while the consumer slot frees at once. Renewals are never awaited on the way out: `stop()` drains abandoned preparations and in-flight renewals before engine close. Tests: `test/persistence-claim-lease.test.ts`, `test/persistence-consumer-scheduling.test.ts`, `test/e2e/persistence-consumer-claim-loss.test.ts`.
+- `src/core/persistence/consumer.ts` — resident canonical-write consumer with retained wake-ups, root-scoped retry backoff and locked-row-skipping expired-claim sweeps. A full tick fans out to every worker; when idle, each tick instead runs one work probe (a single statement mirroring the claim, recovery, expired-claim, effect, projection and topology predicates, excluding rows those workers would skip, including topology recoveries that failed to finish within the last 30 s) and the poll interval doubles from 250 ms to a 5 s cap (`idleMaxMs`), resetting on work. `wake()` runs a full tick immediately; `waitForWrite` calls it after a same-process admission commits, so cross-process writes wait at most 5 s plus one probe and no LISTEN is used. #5984: `awaitWrite` (`waitForWrite` is its row-only form) receives a request this consumer publishes through the `onSettled` handoff with no request read, and skips polls while `holds(id)` says the consumer has it claimed; otherwise it polls the narrow `WRITE_PROGRESS_SQL` (first poll after min(200 ms, half the wait), then 50 ms backing off to 250 ms) and reads the full row once when terminal. Its own cancelled reads are not failures; a database read failure ends the wait as a classified `read_failed` (auth/permission failures at once), and a pending head with an intervention `blocked_reason` ends as `blocked`. A probe failure is reported once and the next tick runs the full fan-out. On Postgres pools of three or more with no connection checked out, idle probes share one reserved connection from the ordinary pool, never the direct/session route (acquired and queried under the phase deadline; a timed-out lane returns to the pool once its query settles) so the rest of the pool drains through the 20 s `idle_timeout` (postgres.js reuses idle connections first-in-first-out); root refresh and receipt compaction run every 5 minutes while idle. Root refresh, recovery scan, sweep and capacity-marking SQL use cooperative five-second cancellation; failure never admits work under stale confinement. Cold direct initialization and queued transactions remain observed and awaited through shutdown. Recognized cancellation owned by the consumer's stop reason is not reported as a storage failure; deadline-first cancellation and unrelated storage errors remain visible. The rate-limited stderr line names the phase, the SQLSTATE or write-error code, a redacted one-line message of at most 200 characters, connection-wait evidence (`first_conn_ms`, or `checkout=not_observed conn_wait_ms`, attributed to the phase through AsyncLocalStorage over the engine's `onCheckout` seam) plus `loop_lag_ms`, a fix command and its docs anchor (`docs/ENGINES.md#persistence-consumer-log`); the trusted status `phase` carries the same fields. Ordinary put-page/remember preparation has a cooperative 30-second deadline; abort-ignoring work remains tracked, and late preparation cannot publish. Publication and shutdown retain the token/native-lock/recovery barriers. Trusted status exposes sampled process-local phases and attempts, not durable progress. A tick woken by a completed publication or a local admission claims the next write at once and runs root refresh plus recovery, expiry and topology scans at most once per poll interval; explicit, timer and idle-probe ticks always scan. Effects drain in batches of 20 without waiting for the next tick while full batches keep arriving; within a batch, git effects wait for their asynchronous durability probe (one per worktree root) after the other effects, and a single-file git effect in a repository without the durability hook acquires the worktree lock only to prove its root and records its outcome after releasing it. Each projection-worker invocation (`runResidentProjectionInvocation`, #5401) rebuilds up to 100 pages and starts no new page once 250 ms have passed since it began; when `hasClaimableWrite` (the `CLAIMABLE_WRITE_SQL` predicate `claimNextWrite` claims with, in `journal.ts`) finds a claimable write at its start it takes 2 pages, and its selector skips failed rows for 30 s through the same `PROJECTION_RETRY_READY_SQL` fragment as the idle probe (measured PGLite rebuild cost on a 1,000-page fixture: mean ~9.5 ms, p99 ~18 ms per page). On PGLite the first full tick releases claims last written before this process started (`releaseAbandonedClaims` in `effect-journal.ts`: running effects and unpublished requests without a recovery record), since the datastore admits one process and those owners have exited; Postgres keeps lease expiry (requests 30 s, effects 2 minutes). On PGLite, which has no autovacuum, the maintenance worker also runs `vacuumPersistenceQueues` (VACUUM ANALYZE of the queue tables) every minute or after 50 + 20% of the request table's rows in publications. Tests: `persistence-consumer-scheduling.test.ts`, `persistence-consumer-idle.test.ts`, `persistence-consumer-log.test.ts`, `projection-drain.test.ts` (injected clock and per-page cost), `persistence-root-refresh.test.ts`, `test/e2e/persistence-phase-liveness.test.ts`, `test/e2e/persistence-idle-pool.test.ts`. With `requestsOnly` (engine graduation's drain) the effect, projection, topology and maintenance workers never start; claim, recovery, expired-claim and publication run as usual and `stop()` remains the barrier. Both the single route and the grouped/lane route (`executeClaimedGroup` in `group-publish.ts`) prepare under a claim lease (`claim-lease.ts`: a renewal every `renewalIntervalMs`, default 10 s, each bounded by `phaseMs`); the claim is lost the first time a renewal says it is gone, throws or overruns, and `whileHeld` stops waiting on the preparation at that moment (the single route also aborts it). The claims still ours are released unpublished with `claim_lost` (token-fenced, so a consumer that took one over keeps it); the abandoned preparation is never published and keeps its root or lane slot until it settles, while the consumer slot frees at once. Renewals are never awaited on the way out: `stop()` drains abandoned preparations and in-flight renewals before engine close. Tests: `test/persistence-claim-lease.test.ts`, `test/persistence-consumer-scheduling.test.ts`, `test/e2e/persistence-consumer-claim-loss.test.ts`. #6176: every renewal of a single or group claim also stores `claim-phase.ts`'s stamp in the request's `claim_phase` column (v216: phase `preparing` or `publishing`, claim start, phase start and the execution token; group members get their own token), so writer status (`diagnostics.ts`, `claim` on each running blocker, never the token) and doctor `persistence_write_stall` can name a stuck phase without an extra statement per write. Tests: `test/persistence-write-stall.test.ts`.
+- `src/core/persistence/claim-phase.ts` — #6176: the phase a running write request's claim is in. `startClaimPhase`/`enterClaimPhase` keep a per-claim clock in the consumer (single and group routes); `claimPhaseStamp` is the jsonb each claim renewal stores in `persistence_requests.claim_phase` (v216), keyed to the execution token so a later claim never reads an earlier claim's ages. `claimStateOf` reads a row back as `preparing`/`publishing` (live renewal), `publication_transaction` (claim lapsed while running, read on the database clock: a transaction holds the row or the owner is gone; requeued once it ends), `file_publication` (`publication_started`; recovery finishes it) or `unrecorded`, with claim and phase ages, `resumes_on_its_own` and a `why`. `persistence.max_claim_ms` (default 600000, 60000 to 86400000; `validateMaxClaimConfigValue` is `config set`'s `invalid_params` refusal) is doctor `persistence_write_stall`'s threshold. Tests: `test/persistence-write-stall.test.ts`.
- `src/core/persistence/health.ts` — pure advisory age/reason/action policy shared by receipts and trusted diagnostics. The nested public contract is optional, validated and explicitly allowlisted; thresholds are 30/120 seconds and polls 1/5/30 seconds. The journal batches at most 100 authorized receipts into one projected root query with a 500ms caller budget, retaining one in-flight query per engine until settlement. Database-only pending lookups use a partial source-incarnation/sequence index shared by both engines. Synchronous service reads coalesce only for the same request ID, retain at most four unresolved reads per engine until settlement, and permit cancellation only by the read's initiating waiter or shutdown. No health observation changes authority or durable state. Real authenticated legacy/OAuth recovery and the synthetic three-client import live in `test/e2e/persistence-http-liveness.test.ts`.
diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.md
index 4643e946af..ae7de005ab 100644
--- a/docs/guides/error-codes.md
+++ b/docs/guides/error-codes.md
@@ -1726,6 +1726,16 @@ More: [docs/guides/google-connect.md#troubleshooting](../../docs/guides/google-c
|---|---|---|---|---|---|---|
| This caller is not authorized for the operation. | Only the operator of the brain host can change what blocks this. | Only the brain host's operator can resolve this. Tell the user the message and run `gbrain doctor --json` on the brain host. | host_admin | `gbrain doctor --json` | 1 | no |
+### persistence_write_stall
+
+<a id="persistence_write_stall"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| A managed write request has held its claim longer than persistence.max_claim_ms, so later writes on its root wait behind it. | The owner renews a claim for as long as its work is unsettled, so a preparation or publication that hangs never lets the lease lapse; doctor names the stuck phase, the root, the claim's age and whether the same request resumes on its own. | Inspect the request with the command in fix, then restart the gbrain serve that owns the root; attach that status output when reporting the hang. Run: gbrain sources writer status --source '{source_id}' --json | agent | `gbrain doctor --json` | 1 | no |
+
+More: [docs/guides/troubleshooting.md#persistence-write-stall](../../docs/guides/troubleshooting.md#persistence-write-stall)
+
### pglite_busy
<a id="pglite_busy"></a>
diff --git a/docs/guides/troubleshooting.md b/docs/guides/troubleshooting.md
index 337aae2d80..10e94be282 100644
--- a/docs/guides/troubleshooting.md
+++ b/docs/guides/troubleshooting.md
@@ -77,6 +77,8 @@
**`gbrain doctor` warns `slug_collisions`, or sync prints slug collisions?** Two or more files in a source map to the same page slug (for example `notes/Foo Bar.md` and `notes/foo-bar.md`), and only one is indexed. Rename all but one file in each group, commit, then sync.
+<a id="persistence-write-stall"></a>**A managed write stays `running` for minutes and later writes on the same root stay `queued`, or doctor warns `persistence_write_stall`?** The owner keeps renewing a claim for as long as its work is unsettled, so a preparation or publication that hangs never lets the lease lapse. Doctor warns once a claim is older than `persistence.max_claim_ms` (milliseconds, default 600000 = 10 minutes, range 60000 to 86400000; for example `gbrain config set persistence.max_claim_ms 900000`) and names the request, its root, how long it has held the claim, how many writes wait behind it and the phase it is stuck in: `preparing` or `publishing` (the owner is still renewing, so nothing moves until that work settles or the owner restarts), `publication_transaction` (the claim lapsed while running and nothing was published; it is requeued once that transaction ends or the owner process exits), `file_publication` (files were being published; the recovery path restores or finishes them when the owner scans its roots again) or `unrecorded` (an owner that predates phase recording). Run `gbrain sources writer status --source <id> --json` (read-only; each running blocker carries `claim.phase`, `claim.claim_age_ms` and `claim.resumes_on_its_own`), then restart the `gbrain serve` that owns the root. The trigger of the hang is not known yet; attach that status output when reporting it. See the [consumer log](../ENGINES.md#persistence-consumer-log).
+
<a id="write-capacity"></a>**Managed writes refused with `queue_capacity`, or doctor warns `persistence_capacity`?** A per-principal or per-brain write-journal limit (`persistence.limits.*`) is full (`queue_capacity`), or doctor sees lifetime request IDs or receipt bytes at 80% or more (`persistence_capacity`). For the cumulative limits (lifetime request IDs and receipt bytes), the warning and the refusal print a `gbrain config set persistence.limits.<limit> <value>` sized for about one more year; run it on the brain host, then retry with the same request ID. For outstanding-request or queued-byte limits, let outstanding writes finish and check `gbrain sources writer status`. Receipt compaction age is `persistence.receipt_retention_days` (default 30). Limits and defaults: [bounded admission and retention](concurrent-writes.md#bounded-admission-and-retention).
<a id="dream-paid-loop"></a>**Dream keeps skipping one transcript, or doctor warns `dream_paid_loop`?** A dream key died `dream.breaker.max_dead_submissions` times (default 3) in 24 hours and is refused so it stops billing you. Fix the cause, then `gbrain dream reset-key --list` and `gbrain dream reset-key '<key>'`. See [the paid-loop breaker](../operations/spend-controls.md#dream-paid-loop-breaker-dreambreakermax_dead_submissions).
diff --git a/src/commands/config.ts b/src/commands/config.ts
index dc61c9b86c..baebd7cdbe 100644
--- a/src/commands/config.ts
+++ b/src/commands/config.ts
@@ -386,6 +386,11 @@ async function setConfigWithDecideHooks(engine: BrainEngine, key: string, value:
const err = validateFenceConfigValue(key, value);
if (err) { console.error(`[config] ${err}`); process.exit(1); }
}
+ if (key === 'persistence.max_claim_ms') {
+ const { validateMaxClaimConfigValue } = await import('../core/persistence/claim-phase.ts');
+ const err = validateMaxClaimConfigValue(key, value);
+ if (err) { console.error(`[config] ${err}`); process.exit(1); }
+ }
if (key.startsWith('facts.drain_')) {
const { validateFactsDrainConfigValue } = await import('../core/facts/drain-config.ts');
const err = validateFactsDrainConfigValue(key, value);
diff --git a/src/commands/doctor/checks/graph-health.ts b/src/commands/doctor/checks/graph-health.ts
index 89d34080d2..ed3f5f85e4 100644
--- a/src/commands/doctor/checks/graph-health.ts
+++ b/src/commands/doctor/checks/graph-health.ts
@@ -285,6 +285,7 @@ export const timelineHistoryEntry: DoctorEntry = {
'connector_checkpoints',
'persistence_request_indexes',
'persistence_request_growth',
+ 'persistence_write_stall',
'connector_held_items',
'git_held_files',
'frontmatter_hook',
diff --git a/src/commands/doctor/checks/persistence-requests.ts b/src/commands/doctor/checks/persistence-requests.ts
index 084d20d6bf..b25f856200 100644
--- a/src/commands/doctor/checks/persistence-requests.ts
+++ b/src/commands/doctor/checks/persistence-requests.ts
@@ -2,6 +2,8 @@ import type { BrainEngine } from '../../../core/engine.ts';
import type { Check } from '../../doctor.ts';
import { readRequestIndexStates, REQUEST_INDEXES_REPAIR_COMMAND } from '../../../core/persistence/checkpoint-validation.ts';
import { oneYearCapacity, readJournalLimits, journalLimitKey } from '../../../core/persistence/limits.ts';
+import { claimStateOf, MAX_CLAIM_CONFIG_KEY, readMaxClaimMs } from '../../../core/persistence/claim-phase.ts';
+import { agentFix, checkError } from '../check-fix.ts';
const WINDOW_DAYS = 7;
const SAMPLE = 10_000;
@@ -95,3 +97,50 @@ export async function requestGrowthCheck(engine: BrainEngine): Promise<Check> {
details: { health: 'unknown', docs } };
}
}
+
+/**
+ * #6176: a write request that has held its claim longer than
+ * `persistence.max_claim_ms` (default 10 minutes). The queue checks only see
+ * Minion jobs, so a persistence request whose preparation or publication hangs
+ * while its owner keeps renewing the claim was invisible: every later write on
+ * its root waits behind it. Names the stuck phase (claim-phase.ts), the root,
+ * the claim's age, how many writes wait behind it and whether the same request
+ * resumes on its own, with the read-only writer status as the next step.
+ */
+export async function writeStallCheck(engine: BrainEngine): Promise<Check> {
+ const docs = 'docs/guides/troubleshooting.md#persistence-write-stall';
+ try {
+ const maxClaimMs = await readMaxClaimMs(engine);
+ const rows = await engine.executeRaw<{ request_id: string; source_id: string; worktree_id: string | null; operation: string; state: string; claim_phase: unknown;
+ execution_token: string | null; claim_lapsed: boolean | null; publication_started: boolean; request_age_ms: string; waiting: number }>(
+ `SELECT r.request_id::text,r.source_id,r.worktree_id::text,r.operation,r.state,r.claim_phase,r.execution_token::text,r.claim_expires_at<now() AS claim_lapsed,
+ r.publication_started,(EXTRACT(EPOCH FROM (now()-r.created_at))*1000)::bigint::text AS request_age_ms,
+ (SELECT count(*)::int FROM persistence_requests q WHERE q.worktree_id=r.worktree_id AND q.state='queued' AND q.sequence>r.sequence) AS waiting
+ FROM persistence_requests r WHERE r.state='running' ORDER BY r.sequence LIMIT 100`);
+ const now = Date.now();
+ const stalls = rows.flatMap(row => {
+ const claim = claimStateOf(row, now);
+ if (!claim) return [];
+ // An owner that predates phase recording never stamps its claims; the request's own age bounds the claim's.
+ const held = claim.claim_age_ms ?? (row.claim_phase == null ? Math.max(0, Number(row.request_age_ms)) : null);
+ if (held === null || !(held >= maxClaimMs)) return [];
+ return [{ request_id: row.request_id, source_id: row.source_id, root: row.worktree_id, operation: row.operation, phase: claim.phase,
+ claim_age_ms: held, phase_age_ms: claim.phase_age_ms, waiting_behind: row.waiting, resumes_on_its_own: claim.resumes_on_its_own, why: claim.why }];
+ });
+ const details = { max_claim_ms: maxClaimMs, config_key: MAX_CLAIM_CONFIG_KEY, count: stalls.length, stalls, docs };
+ if (!stalls.length) return { name: 'persistence_write_stall', status: 'ok', details,
+ message: `No write request has held its claim longer than ${MAX_CLAIM_CONFIG_KEY} (${maxClaimMs} ms).` };
+ const first = stalls[0]!;
+ const minutes = (ms: number) => `${Math.round(ms / 60_000)} min`;
+ return { name: 'persistence_write_stall', status: 'warn', details,
+ message: `${stalls.length} write request(s) have held their claim longer than ${MAX_CLAIM_CONFIG_KEY} (${maxClaimMs} ms). `
+ + stalls.slice(0, 3).map(stall => `Request ${stall.request_id} (${stall.operation}) on source ${stall.source_id}, root ${stall.root ?? 'database-only'}, `
+ + `is stuck in phase ${stall.phase} after ${minutes(stall.claim_age_ms)}; ${stall.waiting_behind} queued write(s) wait behind it. ${stall.why}`).join(' ')
+ + ` Next: inspect it with gbrain sources writer status --source ${first.source_id} --json, then restart the gbrain serve that owns the root`
+ + `${first.resumes_on_its_own ? ' if it is still stuck after its transaction ends' : ''}. The root trigger of a hang is not known yet; attach that status output when reporting it.`,
+ fix: agentFix(['gbrain', 'sources', 'writer', 'status', '--source', first.source_id, '--json'],
+ 'Read-only: shows the owner, the stuck request\'s claim phase and every write waiting behind it on that root.', 'persistence_write_stall', { docs }) };
+ } catch (error) {
+ return checkError('persistence_write_stall', 'inspect running write requests', error, { details: { health: 'unknown', docs } });
+ }
+}
diff --git a/src/commands/doctor/wave-checks.ts b/src/commands/doctor/wave-checks.ts
index 15e0c6d401..6d35105bac 100644
--- a/src/commands/doctor/wave-checks.ts
+++ b/src/commands/doctor/wave-checks.ts
@@ -93,6 +93,14 @@ export const WAVE_CHECKS: readonly WaveCheckSpec[] = [
instruction: 'Raise the named limit with the `gbrain config set persistence.limits.<limit> <value>` command doctor prints, on the brain host (docs/guides/repair.md#request-growth).',
run: async engine => (await import('./checks/persistence-requests.ts')).requestGrowthCheck(engine),
},
+ {
+ id: 'persistence_write_stall', resolution: 'operator', registration: 'wave',
+ count: d => Number(d.count ?? 0),
+ hostOnly: 'Request ids, roots and the owning process are brain-host persistence state outside any source scope.',
+ impact: 'A write request has held its claim past persistence.max_claim_ms, so later writes on its root wait behind it',
+ instruction: 'Inspect it with `gbrain sources writer status --source <id> --json`, then restart the `gbrain serve` that owns the root (docs/guides/troubleshooting.md#persistence-write-stall).',
+ run: async engine => (await import('./checks/persistence-requests.ts')).writeStallCheck(engine),
+ },
{
id: 'connector_held_items', resolution: 'operator', registration: 'wave',
count: d => Number(d.held ?? 0),
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 449dee9b44..165a9f3d65 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -257,6 +257,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }
{ since: '0.60.97.0', text: 'Google Calendar sync writes only events between `historyDays` back and 60 days ahead; `gbrain sync --full` removes pages for in-window events the calendar no longer lists (more than 200 is refused and reported partial).' },
{ since: '0.60.98.0', text: 'Managed sync now holds a file whose facts or takes fence cannot be imported (code `invalid_fence`; `gbrain sources status <id>` names the fence, section and rows) instead of blocking the whole source, and a source such a fence blocked before recovers on its next sync. Coordinated writes refuse such a fence with `invalid_fence` (wire `error` stays `invalid_params`, or `take_row_collision`). `gbrain config set sync.holds fail` keeps fail-closed blocking.' },
{ since: '0.60.99.0', text: 'Fixable facts and takes fences are now rewritten instead of held or refused: managed sync, put_page and the fact and take writers normalize a fence whose meaning is unambiguous (a missing end marker after the table, two-dash takes markers, zero or duplicate row numbers, header aliases, invented kinds and enum synonyms, assistant holders, percent confidences) without changing a claim or an existing row number, and managed sync commits the rewritten file. Results report `fences_normalized`; `gbrain sync --dry-run` lists `would_normalize`. `gbrain config set fences.normalize false` turns it off (such fences are then held or refused).' },
+ { since: '0.0.0-wave11', text: 'Doctor\'s new `persistence_write_stall` check warns when a managed write has held its claim longer than `persistence.max_claim_ms` (default 10 minutes) and names the stuck phase; `gbrain sources writer status --json` shows each running request\'s `claim` phase.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/config.ts b/src/core/config.ts
index df76fc1870..69d447dfd7 100644
--- a/src/core/config.ts
+++ b/src/core/config.ts
@@ -1698,7 +1698,7 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = [
'persistence.limits.principal_lifetime_ids', 'persistence.limits.brain_lifetime_ids',
'persistence.limits.principal_terminal_bytes', 'persistence.limits.brain_terminal_bytes',
'persistence.limits.brain_recovery_bytes', 'persistence.limits.worktree_recovery_bytes',
- 'persistence.receipt_retention_days', 'persistence.unbound_write', // #5254: persistence/unbound-source.ts
+ 'persistence.receipt_retention_days', 'persistence.unbound_write', 'persistence.max_claim_ms', // #5254: persistence/unbound-source.ts; #6176: persistence/claim-phase.ts
// shared-skills migration inventory bounds (src/core/shared-skills/inventory-limits.ts)
'shared_skills.inventory.max_files', 'shared_skills.inventory.max_total_bytes', 'shared_skills.inventory.max_file_bytes', 'shared_skills.inventory.max_entries',
'persistence.write_wait_ms', // #5232: file plane, persistence/write-wait.ts
diff --git a/src/core/doctor-categories.ts b/src/core/doctor-categories.ts
index ab833507bb..879bf86957 100644
--- a/src/core/doctor-categories.ts
+++ b/src/core/doctor-categories.ts
@@ -241,6 +241,7 @@ export const OPS_CHECK_NAMES: ReadonlySet<string> = new Set([
'publication_refusals',
'persistence_request_growth',
'persistence_request_indexes',
+ 'persistence_write_stall',
'stale_embedding_effects',
'vector_plan',
'writer_version',
diff --git a/src/core/error-registry.ts b/src/core/error-registry.ts
index c035264c34..aaddcec0fd 100644
--- a/src/core/error-registry.ts
+++ b/src/core/error-registry.ts
@@ -247,6 +247,7 @@ export const CODES = {
payload_too_large: { class: 'caller', summary: "The payload exceeds the configured size cap." },
pending_writes: { class: 'retryable', summary: "A pending source write prevents verified completion." },
permission_denied: { class: 'host_only', summary: "This caller is not authorized for the operation." },
+ persistence_write_stall: { class: 'host_only', summary: "A managed write request has held its claim longer than persistence.max_claim_ms, so later writes on its root wait behind it.", why: "The owner renews a claim for as long as its work is unsettled, so a preparation or publication that hangs never lets the lease lapse; doctor names the stuck phase, the root, the claim's age and whether the same request resumes on its own.", docs: 'docs/guides/troubleshooting.md#persistence-write-stall', suggestion: 'Inspect the request with the command in fix, then restart the gbrain serve that owns the root; attach that status output when reporting the hang.', fix: { argv: ['gbrain', 'sources', 'writer', 'status', '--source', '{source_id}', '--json'], consent: [], actor: 'agent', why: "Shows the owner, the stuck request's claim phase and the writes waiting behind it, read-only.", requires_exclusive: false } },
pglite_busy: { class: 'retryable', summary: "Another gbrain process holds this PGLite brain's single-writer lock.", reasons: ['timeout', 'live_serve'], suggestion: 'Wait for the current command or server to close, then retry. Do not remove a live lock.' },
plan_output_failed: { class: 'server', summary: "Writing the plan output failed." },
plan_stale: { class: 'caller', summary: "The saved plan has no valid repository identity." },
diff --git a/src/core/persistence/claim-phase.ts b/src/core/persistence/claim-phase.ts
new file mode 100644
index 0000000000..76edfea5e6
--- /dev/null
+++ b/src/core/persistence/claim-phase.ts
@@ -0,0 +1,103 @@
+/**
+ * #6176: which phase a running write request's claim is in, and how long it
+ * has been there, so a stall names its phase instead of `cause_unknown`.
+ *
+ * The consumer keeps a `ClaimPhaseClock` per claim and every claim renewal
+ * (claim-lease.ts cadence, 10 s) stores `claimPhaseStamp` in the request's
+ * `claim_phase` column (v216): the phase, the claim start, the phase start and
+ * the execution token, so a later claim of the same request never reads an
+ * earlier claim's ages. Recording rides the renewal: no extra statement per write.
+ *
+ * `claimStateOf` reads a request row back. A claim whose renewal cannot reach
+ * its row (it lapsed while still `running`) is inside a transaction that holds
+ * the row, or its owner is gone; `publication_started` means files were being
+ * published and the recovery path finishes the request.
+ */
+import type { BrainEngine } from '../engine.ts';
+
+export type ClaimPhaseName = 'preparing' | 'publishing';
+export interface ClaimPhaseClock { phase: ClaimPhaseName; claimedAt: number; since: number }
+
+export function startClaimPhase(now = Date.now()): ClaimPhaseClock {
+ return { phase: 'preparing', claimedAt: now, since: now };
+}
+export function enterClaimPhase(clock: ClaimPhaseClock, phase: ClaimPhaseName, now = Date.now()): void {
+ if (clock.phase === phase) return;
+ clock.phase = phase;
+ clock.since = now;
+}
+/** The `claim_phase` jsonb a renewal stores for the claim holding `token`. */
+export function claimPhaseStamp(clock: ClaimPhaseClock, token: string | null): string {
+ return JSON.stringify({ phase: clock.phase, claimed_at: new Date(clock.claimedAt).toISOString(), since: new Date(clock.since).toISOString(), token });
+}
+
+/** `persistence.max_claim_ms`: how long a write may hold its claim before doctor reports it as stalled. */
+export const MAX_CLAIM_CONFIG_KEY = 'persistence.max_claim_ms';
+export const MAX_CLAIM_DEFAULT_MS = 600_000;
+const MAX_CLAIM_MIN_MS = 60_000;
+const MAX_CLAIM_MAX_MS = 86_400_000;
+
+export function parseMaxClaimMs(raw: string | null | undefined): number | null {
+ const text = raw?.trim() ?? '';
+ if (!/^\d+$/.test(text)) return null;
+ const n = Number(text);
+ return n >= MAX_CLAIM_MIN_MS && n <= MAX_CLAIM_MAX_MS ? n : null;
+}
+/** `config set` validation; the refusal text, or null when the value is valid (or the key is another one). */
+export function validateMaxClaimConfigValue(key: string, value: string): string | null {
+ if (key !== MAX_CLAIM_CONFIG_KEY || parseMaxClaimMs(value) !== null) return null;
+ return `invalid_params: ${MAX_CLAIM_CONFIG_KEY} must be a whole number of milliseconds from ${MAX_CLAIM_MIN_MS} to ${MAX_CLAIM_MAX_MS} `
+ + `(default ${MAX_CLAIM_DEFAULT_MS}, 10 minutes; for example gbrain config set ${MAX_CLAIM_CONFIG_KEY} 900000) (got '${value}'). Nothing was written.`;
+}
+export async function readMaxClaimMs(engine: Pick<BrainEngine, 'getConfig'>): Promise<number> {
+ return parseMaxClaimMs(await engine.getConfig(MAX_CLAIM_CONFIG_KEY).catch(() => null)) ?? MAX_CLAIM_DEFAULT_MS;
+}
+
+/**
+ * Where a running claim is: `preparing` or `publishing` (recorded by a live
+ * renewal), `publication_transaction` (the claim lapsed while running and
+ * nothing was published yet), `file_publication` (files were being published)
+ * or `unrecorded` (no stamp of this claim yet, or an owner that predates v216).
+ */
+export type ClaimStatePhase = ClaimPhaseName | 'publication_transaction' | 'file_publication' | 'unrecorded';
+export interface ClaimState {
+ phase: ClaimStatePhase;
+ claim_age_ms: number | null;
+ phase_age_ms: number | null;
+ /** Whether the same request continues without anyone acting (after its lease lapses or its transaction ends). */
+ resumes_on_its_own: boolean;
+ why: string;
+}
+export interface ClaimRow {
+ state: string;
+ claim_phase?: unknown;
+ execution_token?: string | null;
+ /** `claim_expires_at < now()`, read on the database clock. */
+ claim_lapsed?: boolean | null;
+ publication_started?: boolean | null;
+}
+
+const age = (at: unknown, now: number): number | null => {
+ const ms = typeof at === 'string' || at instanceof Date ? new Date(at).getTime() : NaN;
+ return Number.isFinite(ms) ? Math.max(0, Math.floor(now - ms)) : null;
+};
+
+export function claimStateOf(row: ClaimRow, now = Date.now()): ClaimState | null {
+ if (row.state !== 'running') return null;
+ const raw = typeof row.claim_phase === 'string' ? safeJson(row.claim_phase) : row.claim_phase;
+ const stamp = raw && typeof raw === 'object' ? raw as Record<string, unknown> : null;
+ const own = !!stamp && !!row.execution_token && stamp.token === row.execution_token;
+ const claimAge = own ? age(stamp!.claimed_at, now) : null;
+ if (row.publication_started) return { phase: 'file_publication', claim_age_ms: claimAge, phase_age_ms: null, resumes_on_its_own: false,
+ why: 'Its files were being published; the publication recovery path restores or finishes them when the owning process scans its roots again (after a restart if it hung).' };
+ if (row.claim_lapsed) return { phase: 'publication_transaction', claim_age_ms: claimAge, phase_age_ms: null, resumes_on_its_own: true,
+ why: 'Its claim lapsed while it was still running and nothing was published: a transaction holds the request row (renewals cannot reach it) or its owner is gone. It is requeued once that transaction ends or the owner process exits.' };
+ if (!own) return { phase: 'unrecorded', claim_age_ms: null, phase_age_ms: null, resumes_on_its_own: false,
+ why: 'The owner has not recorded this claim\'s phase (a claim younger than one renewal, or an owner that predates phase recording).' };
+ const phase = stamp!.phase === 'publishing' ? 'publishing' : 'preparing';
+ return { phase, claim_age_ms: claimAge, phase_age_ms: age(stamp!.since, now), resumes_on_its_own: false,
+ why: `Its owner is still renewing the claim while it is ${phase === 'preparing' ? 'preparing the write' : 'publishing the write'}, so the lease never lapses and nothing else on its root runs until that work settles or the owner restarts.` };
+}
+function safeJson(text: string): unknown {
+ try { return JSON.parse(text); } catch { return null; }
+}
diff --git a/src/core/persistence/consumer.ts b/src/core/persistence/consumer.ts
index 193b88df4e..f123134266 100644
--- a/src/core/persistence/consumer.ts
+++ b/src/core/persistence/consumer.ts
@@ -5,6 +5,7 @@ import { finishUnpublishedFailure, publishMutation, recoverPublication, type Pre
import { localHostId } from './identity.ts';
import { executeClaimedGroup, PAGE_BATCH_GROUP_MAX } from './group-publish.ts';
import { CLAIM_LOST, DEFAULT_CLAIM_LEASE_TIMING, endLostLease, startClaimLease, type ClaimLeaseTiming } from './claim-lease.ts';
+import { claimPhaseStamp, enterClaimPhase, startClaimPhase } from './claim-phase.ts';
import { isTerminal, type WriteRequest } from './model.ts';
import { refreshManagedFilesystemRoots } from './filesystem-guard.ts';
import { PROJECTION_RETRY_READY_SQL, rebuildPendingPageProjections } from '../page-state/projections.ts';
@@ -531,9 +532,10 @@ export class PersistenceConsumer {
abort.abort({ code: 'preparation_deadline' });
this.log('preparation', 'deadline_exceeded');
}, budget) : undefined;
+ const clock = startClaimPhase();
const lease = startClaimLease(
signal => renewWriteClaim({ executeRaw: this.engine.executeRawDirect.bind(this.engine) }, row.id, row.execution_token!, 30_000,
- this.engine.kind === 'postgres' ? signal : undefined),
+ this.engine.kind === 'postgres' ? signal : undefined, claimPhaseStamp(clock, row.execution_token)),
this.leaseTiming(), () => abort.abort({ code: 'claim_lost' }));
const releaseReason = () => !lease.held ? 'claim_lost' : observation.deadline_exceeded ? 'preparation_deadline' : 'consumer_stopping';
try {
@@ -556,6 +558,7 @@ export class PersistenceConsumer {
}
this.preparing.delete(row.id);
preparationActive = false;
+ enterClaimPhase(clock, 'publishing');
await faultPoint('consumer:prepared', { requestId: row.request_id, sourceId: row.source_id, operation: row.operation });
const done = await publishMutation(this.engine, row, prepared, this.hostId);
if (done.state === 'failed') this.log('publication', done.error_code ?? 'storage_error', done.error_message ?? undefined);
diff --git a/src/core/persistence/diagnostics.ts b/src/core/persistence/diagnostics.ts
index 3af427a869..493181f8f9 100644
--- a/src/core/persistence/diagnostics.ts
+++ b/src/core/persistence/diagnostics.ts
@@ -4,6 +4,7 @@ import type { JournalLimits } from './model.ts';
import { publicationConcurrency } from './pool-capacity.ts';
import { WRITER_INSPECTION_HINT } from './admin-intent.ts';
import { writeHealth } from './health.ts';
+import { claimStateOf, type ClaimRow } from './claim-phase.ts';
import type { WriteRequestState } from './types.ts';
import { DATABASE_REFUSAL_HINT, DATABASE_TRIGGER_HINT } from './connector-errors.ts';
@@ -62,8 +63,9 @@ export async function readWriterDiagnostics(engine: BrainEngine) {
FROM persistence_worktrees w LEFT JOIN persistence_requests r ON r.worktree_id=w.id
GROUP BY w.id ORDER BY w.id`);
const counters = await engine.executeRaw<Counter>(`SELECT key,outstanding_count::text,intent_bytes::text,lifetime_ids::text,terminal_bytes::text,recovery_bytes::text FROM persistence_counters ORDER BY key`);
- const blockers = await engine.executeRaw<{ request_id: string; worktree_id: string | null; state: WriteRequestState; created_at: Date | string; blocked_reason: string | null; error_code: string | null }>(
- `SELECT request_id,worktree_id,state,blocked_reason,error_code,created_at
+ const blockers = await engine.executeRaw<{ request_id: string; worktree_id: string | null; state: WriteRequestState; created_at: Date | string; blocked_reason: string | null; error_code: string | null }
+ & Omit<ClaimRow, 'state'>>(
+ `SELECT request_id,worktree_id,state,blocked_reason,error_code,created_at,claim_phase,execution_token,claim_expires_at<now() AS claim_lapsed,publication_started
FROM persistence_requests WHERE state IN ('queued','running','recovering') OR blocked_reason IS NOT NULL ORDER BY sequence LIMIT 100`);
const queue = await engine.executeRaw(`SELECT state,COUNT(*)::integer AS count,COALESCE(SUM(intent_bytes),0)::text AS intent_bytes,
MIN(created_at) AS oldest_request_at,
@@ -87,10 +89,12 @@ export async function readWriterDiagnostics(engine: BrainEngine) {
return { ...brain, sampled_at: new Date().toISOString(), publication_concurrency: publicationConcurrency(engine),
local_process_ingress, worktrees, counters, queue, effects, limits, capacity: capacityDiagnostics(counters, limits),
recent_failures: failures.map(row => ({ ...row, next_action: row.error_detail?.origin === 'database_guard' ? DATABASE_REFUSAL_HINT : DATABASE_TRIGGER_HINT })),
- blockers: blockers.map(row => {
+ blockers: blockers.map(({ claim_phase: _phase, execution_token: _token, claim_lapsed: _lapsed, publication_started: _started, ...row }) => {
const health = writeHealth(row);
const advice = writerNextAction(row.blocked_reason ?? row.error_code);
- return { ...row, ...health, next_action: health.diagnostic?.next_action === 'inspect_owner' && advice !== WRITER_INSPECTION_HINT
+ // #6176: a running request names the phase its claim is in and how long it has held it.
+ const claim = claimStateOf({ state: row.state, claim_phase: _phase, execution_token: _token, claim_lapsed: _lapsed, publication_started: _started });
+ return { ...row, ...health, ...(claim ? { claim } : {}), next_action: health.diagnostic?.next_action === 'inspect_owner' && advice !== WRITER_INSPECTION_HINT
? `${WRITER_INSPECTION_HINT} ${advice}` : advice };
}) };
}
diff --git a/src/core/persistence/group-publish.ts b/src/core/persistence/group-publish.ts
index c11338f559..4571ff4b88 100644
--- a/src/core/persistence/group-publish.ts
+++ b/src/core/persistence/group-publish.ts
@@ -37,6 +37,7 @@ import { clearResolvedRecoveries, completeWrite, ENSURE_COUNTERS_SQL, getWriteRe
publicationGroupKey, reclaimReleasedWrite, releaseUnpublishedClaim, renewGroupClaims } from './journal.ts';
import { principalKey, requestPrincipal, type FileRecoveryRecord, type WriteRequest } from './model.ts';
import { CLAIM_LOST, DEFAULT_CLAIM_LEASE_TIMING, endLostLease, startClaimLease, type ClaimLeaseTiming } from './claim-lease.ts';
+import { claimPhaseStamp, enterClaimPhase, startClaimPhase } from './claim-phase.ts';
import { setMemberAttribution, withCoordinatedWrite } from './context.ts';
import { requestAttribution } from './attribution.ts';
import { tryAcquirePublicationCapacity } from './pool-capacity.ts';
@@ -336,7 +337,8 @@ export interface GroupExecution {
* any member settled.
*/
export async function executeClaimedGroup(engine: BrainEngine, rows: WriteRequest[], run: GroupExecution): Promise<boolean> {
- const lease = startClaimLease(async signal => (await renewGroupClaims(engine, rows, 30_000, signal)).size === rows.length,
+ const clock = startClaimPhase();
+ const lease = startClaimLease(async signal => (await renewGroupClaims(engine, rows, 30_000, signal, claimPhaseStamp(clock, null))).size === rows.length,
run.lease ?? DEFAULT_CLAIM_LEASE_TIMING);
if (run.lane) laneClaimed(run.lane, rows);
try {
@@ -356,6 +358,7 @@ export async function executeClaimedGroup(engine: BrainEngine, rows: WriteReques
for (const row of rows) await releaseUnpublishedClaim(engine, row, 'claim_lost');
return false;
}
+ enterClaimPhase(clock, 'publishing');
// A put_pages batch is independent page writes: one page's failure never cancels its siblings.
const independent = publicationGroupKey(rows[0]!)?.startsWith('batch:') === true;
let requeued = new Set<string>();
diff --git a/src/core/persistence/journal.ts b/src/core/persistence/journal.ts
index 39d235fce3..9a918610f7 100644
--- a/src/core/persistence/journal.ts
+++ b/src/core/persistence/journal.ts
@@ -318,10 +318,11 @@ export async function claimGroupFollowers(engine: BrainEngine, head: WriteReques
}
/** Renews every claim of a group in one statement; returns the ids still held. */
-export async function renewGroupClaims(engine: SqlEngine, rows: WriteRequest[], leaseMs = 30_000, signal?: AbortSignal): Promise<Set<string>> {
- const held = await engine.executeRaw<{ id: string }>(`UPDATE persistence_requests r SET claim_expires_at=now()+($3::double precision*interval '1 millisecond'),updated_at=now()
+export async function renewGroupClaims(engine: SqlEngine, rows: WriteRequest[], leaseMs = 30_000, signal?: AbortSignal, phase: string | null = null): Promise<Set<string>> {
+ const held = await engine.executeRaw<{ id: string }>(`UPDATE persistence_requests r SET claim_expires_at=now()+($3::double precision*interval '1 millisecond'),updated_at=now(),
+ claim_phase=COALESCE(jsonb_set($4::text::jsonb,'{token}',to_jsonb(t.token::text)),r.claim_phase)
FROM unnest($1::uuid[],$2::uuid[]) AS t(id,token) WHERE r.id=t.id AND r.execution_token=t.token AND r.state='running' AND ${PERSISTENCE_PROTOCOL_PREDICATE} RETURNING r.id`,
- [rows.map(row => row.id), rows.map(row => row.execution_token), leaseMs], { signal });
+ [rows.map(row => row.id), rows.map(row => row.execution_token), leaseMs, phase], { signal });
return new Set(held.map(row => row.id));
}
@@ -445,10 +446,11 @@ export async function claimNextLaneHead(engine: BrainEngine, hostId: string, wor
return claimed;
});
}
-export async function renewWriteClaim(engine: SqlEngine, id: string, token: string, leaseMs = 30_000, signal?: AbortSignal): Promise<boolean> {
+/** `phase` (claim-phase.ts `claimPhaseStamp`, #6176) records the claim's current phase with the renewal. */
+export async function renewWriteClaim(engine: SqlEngine, id: string, token: string, leaseMs = 30_000, signal?: AbortSignal, phase: string | null = null): Promise<boolean> {
const rows = await engine.executeRaw(`UPDATE persistence_requests SET
- claim_expires_at=now()+($3::double precision*interval '1 millisecond'),updated_at=now()
- WHERE id=$1::uuid AND execution_token=$2::uuid AND state='running' AND ${PERSISTENCE_PROTOCOL_PREDICATE} RETURNING id`, [id, token, leaseMs], { signal });
+ claim_expires_at=now()+($3::double precision*interval '1 millisecond'),updated_at=now(),claim_phase=COALESCE($4::text::jsonb,claim_phase)
+ WHERE id=$1::uuid AND execution_token=$2::uuid AND state='running' AND ${PERSISTENCE_PROTOCOL_PREDICATE} RETURNING id`, [id, token, leaseMs, phase], { signal });
return rows.length === 1;
}
export async function releaseUnpublishedClaim(engine: SqlEngine, row: WriteRequest, reason: string): Promise<void> {
diff --git a/src/core/schema-migrations/registry.generated.ts b/src/core/schema-migrations/registry.generated.ts
index 7177831439..763315cc1e 100644
--- a/src/core/schema-migrations/registry.generated.ts
+++ b/src/core/schema-migrations/registry.generated.ts
@@ -216,6 +216,7 @@ import { v212 } from './v212-decide-review-proposals.ts';
import { v213 } from './v213-core-edit-notices.ts';
import { v214 } from './v214-wanted-links.ts';
import { v215 } from './v215-facts-attributed-to.ts';
+import { v216 } from './v216-persistence-request-claim-phase.ts';
// Array order is historical (see HISTORICAL_ARRAY_ORDER in the generator); the
// runner sorts by version before applying.
@@ -430,4 +431,5 @@ export const MIGRATIONS: Migration[] = [
v213,
v214,
v215,
+ v216,
];
diff --git a/src/core/schema-migrations/v216-persistence-request-claim-phase.ts b/src/core/schema-migrations/v216-persistence-request-claim-phase.ts
new file mode 100644
index 0000000000..375424ccb9
--- /dev/null
+++ b/src/core/schema-migrations/v216-persistence-request-claim-phase.ts
@@ -0,0 +1,19 @@
+import type { Migration } from './types.ts';
+
+// Applied by src/core/migrate.ts on the next initSchema(); see docs/ENGINES.md
+// ("Canonical schema sources") for when schema.sql or a TS fragment also changes.
+//
+// #6176: a running write request records which phase its claim is in
+// (persistence/claim-phase.ts): the consumer's claim renewal stamps the phase,
+// the claim start and the phase start, keyed to the execution token, so
+// `gbrain sources writer status` and the `persistence_write_stall` doctor check
+// can name a stuck phase and its age. Column-only and nullable, no backfill;
+// like v178 and v198 it is migration-created on PGLite and no index references it.
+export const v216: Migration = {
+ version: 216,
+ name: 'persistence_request_claim_phase',
+ idempotent: true,
+ sql: `
+ ALTER TABLE persistence_requests ADD COLUMN IF NOT EXISTS claim_phase jsonb;
+ `,
+};
diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-default.json b/test/fixtures/goldens/catalog/pglite-engine-init-default.json
index 4851a49f6d..019c6e1b02 100644
--- a/test/fixtures/goldens/catalog/pglite-engine-init-default.json
+++ b/test/fixtures/goldens/catalog/pglite-engine-init-default.json
@@ -2556,7 +2556,8 @@
"36 consumer_version text/text NULL",
"37 consumer_host_id uuid/uuid NULL",
"38 published_at timestamp with time zone/timestamptz NULL",
- "39 error_detail jsonb/jsonb NULL"
+ "39 error_detail jsonb/jsonb NULL",
+ "40 claim_phase jsonb/jsonb NULL"
],
"flags": "relkind=r rls=false force_rls=false"
},
diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json b/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json
index fcc9ff0f3e..5b3bc97250 100644
--- a/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json
+++ b/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json
@@ -2556,7 +2556,8 @@
"36 consumer_version text/text NULL",
"37 consumer_host_id uuid/uuid NULL",
"38 published_at timestamp with time zone/timestamptz NULL",
- "39 error_detail jsonb/jsonb NULL"
+ "39 error_detail jsonb/jsonb NULL",
+ "40 claim_phase jsonb/jsonb NULL"
],
"flags": "relkind=r rls=false force_rls=false"
},
diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json b/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json
index e6ec97798a..566507a1bf 100644
--- a/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json
+++ b/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json
@@ -2552,7 +2552,8 @@
"36 consumer_version text/text NULL",
"37 consumer_host_id uuid/uuid NULL",
"38 published_at timestamp with time zone/timestamptz NULL",
- "39 error_detail jsonb/jsonb NULL"
+ "39 error_detail jsonb/jsonb NULL",
+ "40 claim_phase jsonb/jsonb NULL"
],
"flags": "relkind=r rls=false force_rls=false"
},
diff --git a/test/fixtures/goldens/doctor/json-pglite-degraded.json b/test/fixtures/goldens/doctor/json-pglite-degraded.json
index 90fbd29064..39fe9b5ab9 100644
--- a/test/fixtures/goldens/doctor/json-pglite-degraded.json
+++ b/test/fixtures/goldens/doctor/json-pglite-degraded.json
@@ -731,6 +731,19 @@
"name": "persistence_request_growth",
"status": "ok"
},
+ {
+ "category": "ops",
+ "details": {
+ "config_key": "persistence.max_claim_ms",
+ "count": 0,
+ "docs": "docs/guides/troubleshooting.md#persistence-write-stall",
+ "max_claim_ms": "<volatile>",
+ "stalls": []
+ },
+ "message": "No write request has held its claim longer than persistence.max_claim_ms (600000 ms).",
+ "name": "persistence_write_stall",
+ "status": "ok"
+ },
{
"category": "brain",
"details": {
diff --git a/test/fixtures/goldens/doctor/json-pglite-fresh.json b/test/fixtures/goldens/doctor/json-pglite-fresh.json
index 25392ee55a..818cd8232f 100644
--- a/test/fixtures/goldens/doctor/json-pglite-fresh.json
+++ b/test/fixtures/goldens/doctor/json-pglite-fresh.json
@@ -819,6 +819,19 @@
"name": "persistence_request_growth",
"status": "ok"
},
+ {
+ "category": "ops",
+ "details": {
+ "config_key": "persistence.max_claim_ms",
+ "count": 0,
+ "docs": "docs/guides/troubleshooting.md#persistence-write-stall",
+ "max_claim_ms": "<volatile>",
+ "stalls": []
+ },
+ "message": "No write request has held its claim longer than persistence.max_claim_ms (600000 ms).",
+ "name": "persistence_write_stall",
+ "status": "ok"
+ },
{
"category": "brain",
"details": {
diff --git a/test/fixtures/goldens/doctor/registry-build-checks.json b/test/fixtures/goldens/doctor/registry-build-checks.json
index e3dc166564..be21187396 100644
--- a/test/fixtures/goldens/doctor/registry-build-checks.json
+++ b/test/fixtures/goldens/doctor/registry-build-checks.json
@@ -389,6 +389,10 @@
"category": "ops",
"name": "persistence_request_growth"
},
+ {
+ "category": "ops",
+ "name": "persistence_write_stall"
+ },
{
"category": "brain",
"name": "connector_held_items"
diff --git a/test/fixtures/goldens/migrations/records.json b/test/fixtures/goldens/migrations/records.json
index f0978e676d..21cb2746b7 100644
--- a/test/fixtures/goldens/migrations/records.json
+++ b/test/fixtures/goldens/migrations/records.json
@@ -1,6 +1,6 @@
{
"golden": {
- "count": 210,
+ "count": 211,
"gaps": [
17,
18,
@@ -35,7 +35,7 @@
"sqlQueryForEngine": "71fb1ccec1b22cdc1662876dbd8c17ed81e9ab83485c6965cdf5caa4fc4a4ab5",
"verifyProjectionStatistics": "59d9ccfea1c53384d8607874a51209a9c2dfd51b2b85a2cb6269fa4120faf1f3"
},
- "latest": 215,
+ "latest": 216,
"records": [
{
"handler": {
@@ -3191,6 +3191,19 @@
"transaction": "absent",
"verify": "absent",
"version": 215
+ },
+ {
+ "handler": "absent",
+ "idempotent": true,
+ "name": "persistence_request_claim_phase",
+ "sql": {
+ "length": 84,
+ "sha256": "830bd460b2c241fe7d09818ad43f630956bc53a9f3e2d66bca5d62750c6d55dd"
+ },
+ "sqlFor": "absent",
+ "transaction": "absent",
+ "verify": "absent",
+ "version": 216
}
],
"versions": [
@@ -3403,7 +3416,8 @@
212,
213,
214,
- 215
+ 215,
+ 216
]
},
"normalizer": "migrations-record-v1"
diff --git a/test/persistence-write-stall.test.ts b/test/persistence-write-stall.test.ts
new file mode 100644
index 0000000000..772a1b3b4b
--- /dev/null
+++ b/test/persistence-write-stall.test.ts
@@ -0,0 +1,128 @@
+/**
+ * #6176: a write whose publication hangs keeps its claim alive (the owner keeps renewing it), so every later
+ * write on its root waits behind it and nothing reported it. The claim renewal now records the claim's phase
+ * (claim-phase.ts), `gbrain sources writer status` names it, and doctor's `persistence_write_stall` warns once
+ * a claim is older than `persistence.max_claim_ms`. PGLite always; Postgres when DATABASE_URL is set.
+ */
+import { afterAll, describe, expect, setSystemTime, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { PersistenceConsumer } from '../src/core/persistence/consumer.ts';
+import { admitWrite, getWriteRequestById } from '../src/core/persistence/journal.ts';
+import { installFaultHook } from '../src/core/persistence/fault-points.ts';
+import { readWriterDiagnostics } from '../src/core/persistence/diagnostics.ts';
+import { claimStateOf, validateMaxClaimConfigValue } from '../src/core/persistence/claim-phase.ts';
+import { writeStallCheck } from '../src/commands/doctor/checks/persistence-requests.ts';
+import { admission, fixtures, initializeFixtures, prepared, selectFixtureHost, type HarnessConfig } from '../scripts/persistence/harness.ts';
+import { withEnv } from './helpers/with-env.ts';
+import { waitFor } from './helpers/wait-for.ts';
+
+const homes: string[] = [];
+afterAll(() => { installFaultHook(undefined); setSystemTime(); for (const home of homes) rmSync(home, { recursive: true, force: true }); });
+
+test('claim state names the phase from the stamp of the current claim only', () => {
+ const now = Date.parse('2026-10-06T12:00:00Z');
+ const stamp = { phase: 'publishing', claimed_at: '2026-10-06T11:45:00Z', since: '2026-10-06T11:50:00Z', token: 't1' };
+ expect(claimStateOf({ state: 'running', claim_phase: stamp, execution_token: 't1' }, now))
+ .toMatchObject({ phase: 'publishing', claim_age_ms: 15 * 60_000, phase_age_ms: 10 * 60_000, resumes_on_its_own: false });
+ expect(claimStateOf({ state: 'running', claim_phase: JSON.stringify(stamp), execution_token: 't2' }, now)).toMatchObject({ phase: 'unrecorded', claim_age_ms: null });
+ expect(claimStateOf({ state: 'running', claim_phase: stamp, execution_token: 't1', claim_lapsed: true }, now)).toMatchObject({ phase: 'publication_transaction', resumes_on_its_own: true });
+ expect(claimStateOf({ state: 'running', claim_phase: stamp, execution_token: 't1', publication_started: true }, now)).toMatchObject({ phase: 'file_publication' });
+ expect(claimStateOf({ state: 'queued', claim_phase: stamp, execution_token: 't1' }, now)).toBeNull();
+});
+
+test('persistence.max_claim_ms is validated with a coded refusal', () => {
+ expect(validateMaxClaimConfigValue('persistence.max_claim_ms', '900000')).toBeNull();
+ for (const bad of ['5000', 'ten', '1.5', '999999999999']) expect(validateMaxClaimConfigValue('persistence.max_claim_ms', bad)).toStartWith('invalid_params:');
+ expect(validateMaxClaimConfigValue('persistence.write_wait_ms', 'anything')).toBeNull();
+});
+
+async function scenario(engine: BrainEngine, config: HarnessConfig) {
+ const sources = await fixtures(engine, config);
+ const stuck = await admitWrite(engine, admission(config, sources[0]!, 'stall/stuck', 'stuck body'));
+ const behind = await admitWrite(engine, admission(config, sources[0]!, 'stall/behind', 'behind body'));
+ const hang = Promise.withResolvers<void>();
+ installFaultHook(async (point, detail) => { if (point === 'consumer:prepared' && detail.requestId === stuck.request_id) await hang.promise; });
+ const errors: unknown[] = [];
+ const consumer = new PersistenceConsumer(engine, { engine: engine.kind }, async (_engine, row) => prepared(row, sources),
+ { hostId: config.hostId, concurrency: 1, pollMs: 20, renewalIntervalMs: 20, phaseMs: 2_000, onError: error => errors.push(error) });
+ try {
+ consumer.start();
+ await waitFor(async () => (await engine.executeRaw<{ p: string | null }>("SELECT claim_phase->>'phase' AS p FROM persistence_requests WHERE id=$1::uuid", [stuck.id]))[0]?.p === 'publishing',
+ { timeoutMs: 15_000, label: 'the renewal records the publishing phase' });
+ const status = await readWriterDiagnostics(engine);
+ const blocker = status.blockers.find(row => row.request_id === stuck.request_id) as Record<string, unknown> | undefined;
+ expect(blocker?.claim).toMatchObject({ phase: 'publishing', resumes_on_its_own: false });
+ expect(blocker).not.toHaveProperty('execution_token');
+ expect(blocker).not.toHaveProperty('claim_phase');
+ expect((await writeStallCheck(engine)).status).toBe('ok');
+ // PGLite's now() follows the shifted clock too, so the check runs after a renewal under it (the claim stays live).
+ const live = async () => (await engine.executeRaw<{ live: boolean }>('SELECT claim_expires_at>now() AS live FROM persistence_requests WHERE id=$1::uuid', [stuck.id]))[0]?.live === true;
+ setSystemTime(new Date(Date.now() + 11 * 60_000));
+ let check;
+ try { await waitFor(live, { timeoutMs: 10_000, label: 'a renewal under the shifted clock' }); check = await writeStallCheck(engine); } finally { setSystemTime(); }
+ expect(check.status).toBe('warn');
+ expect(check.details).toMatchObject({ count: 1, max_claim_ms: 600_000,
+ stalls: [{ request_id: stuck.request_id, source_id: sources[0]!.id, root: stuck.worktree_id, phase: 'publishing', waiting_behind: 1, resumes_on_its_own: false }] });
+ expect((check.fix as { argv: string[] }).argv).toEqual(['gbrain', 'sources', 'writer', 'status', '--source', sources[0]!.id, '--json']);
+ expect(check.message).toContain('phase publishing');
+ await engine.setConfig('persistence.max_claim_ms', '86400000');
+ setSystemTime(new Date(Date.now() + 11 * 60_000));
+ try { await waitFor(live, { timeoutMs: 10_000, label: 'a renewal under the shifted clock' }); expect((await writeStallCheck(engine)).status).toBe('ok'); } finally { setSystemTime(); await engine.executeRaw("DELETE FROM config WHERE key='persistence.max_claim_ms'"); }
+ hang.resolve();
+ await waitFor(async () => (await getWriteRequestById(engine, behind.id))?.state === 'committed', { timeoutMs: 15_000, label: 'the write behind it commits' });
+ expect((await getWriteRequestById(engine, stuck.id))?.state).toBe('committed');
+ expect((await writeStallCheck(engine)).status).toBe('ok');
+ } finally {
+ hang.resolve();
+ installFaultHook(undefined);
+ await consumer.stop();
+ }
+ // An owner that predates phase recording never stamps its claim: the request's own age stands in for the claim's.
+ const legacy = await admitWrite(engine, admission(config, sources[1]!, 'stall/legacy', 'legacy body'));
+ await engine.executeRaw(`UPDATE persistence_requests SET state='running',execution_token=$2::uuid,claim_expires_at=now()+interval '30 seconds',
+ created_at=now()-interval '31 minutes' WHERE id=$1::uuid`, [legacy.id, randomUUID()]);
+ const old = await writeStallCheck(engine);
+ expect(old.status).toBe('warn');
+ expect(old.details).toMatchObject({ stalls: [{ request_id: legacy.request_id, phase: 'unrecorded' }] });
+ expect(errors).toEqual([]);
+}
+
+function harness(kind: 'pglite' | 'postgres'): HarnessConfig {
+ const root = mkdtempSync(join(tmpdir(), `gbrain-write-stall-${kind}-`)); homes.push(root);
+ return { kind, root, dataDir: join(root, 'data'), hostId: randomUUID(), seed: 6176, schedules: 0, operations: 0,
+ sourceIds: ['write-stall', 'write-stall-other'], principalIds: [randomUUID()] };
+}
+
+test('PGLite: a hung publication is named by writer status and doctor persistence_write_stall', async () => {
+ const config = harness('pglite');
+ await withEnv({ GBRAIN_HOME: config.root, GBRAIN_PERSISTENCE_FIXTURE_HOME: config.root }, async () => {
+ const engine = new PGLiteEngine();
+ await engine.connect({});
+ try {
+ await engine.initSchema();
+ selectFixtureHost(config.hostId);
+ await initializeFixtures(engine, config);
+ await scenario(engine, config);
+ } finally { await engine.disconnect(); }
+ });
+}, 120_000);
+
+describe.skipIf(!process.env.DATABASE_URL)('Postgres', () => {
+ test('a hung publication is named by writer status and doctor persistence_write_stall', async () => {
+ const config = harness('postgres');
+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!, 'instance', 6);
+ try {
+ await withEnv({ GBRAIN_HOME: config.root, GBRAIN_PERSISTENCE_FIXTURE_HOME: config.root }, async () => {
+ selectFixtureHost(config.hostId);
+ await initializeFixtures(pg.engine, config);
+ await scenario(pg.engine, config);
+ });
+ } finally { await pg.close(); }
+ }, 120_000);
+});