Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(persistence): stamp group followers with their owner so a dead leader's queued members are reclaimed (#6650)

garrytan5138e84d42df
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 67a5d4c72f..43a7b3ace5 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,6 +10,16 @@ credits are retained; no result has been reassigned to another provider. Origina
identifiers and attribution are available in the pre-removal Git revision
`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).
+## [0.60.224.0] - 2026-10-14
+
+**When a gbrain process that was running a group of writes is killed, its queued group members are now reclaimed with the rest of its claims, within about 5 s, instead of after their 30 s claim lease (#6650 follow-up).** On Linux, a consumer on the same machine already took back the claims of a write owner it could prove dead. But the members of a group the owner had claimed and not yet started carried no record of their owner, so they waited out their lease and held up the rest of the catch-up behind them. Now each member records its owner when it is claimed. Members that the owner had started, and any member with a recovery record or a publication in progress, are handled exactly as before. In the convergence harness (seed 6650, 50 ms latency) the worst stall after the round-1 serve kill went from 30 s to 21 s.
+
+### Itemized changes
+
+- **Follower claims record their owner** (`src/core/persistence/journal.ts` `claimGroupFollowers`): a group follower's claim stamp holds its own token and the claiming process's identity (pid, nonce, pid namespace, boot id, start time), with no phase until its wave dispatches it. The dead-owner reclaim (`consumer.ts`) matches it by owner like any other claim. Because it has no `preparing` phase, the reclaim charges it no preparation attempt, as before.
+- **Readers of a follower stamp** (`claim-phase.ts` `claimStateOf`, `sync-drain.ts` `drainClaimOf`): a stamp with an owner and no phase reads as unrecorded for its phase and stall window, as an unstamped follower did, and now names its owner. Doctor ages it from when it was claimed, and `gbrain sources writer status` does not count its wait against the preparation budget it has not started.
+- **Owner probe** (`consumer-heartbeat.ts` `probeLiveFullConsumer`): the probe reads every live row of the host before it skips rows it can prove dead, so a live serve listed after eight dead rows is still found. Before, it read the first eight rows and could answer "no owner".
+
## [0.60.223.0] - 2026-10-14
**On Linux, a managed sync no longer stalls for six minutes after a gbrain process on the same machine is killed (#6650).** When a `gbrain sync` client was killed, its consumer heartbeat row still read as live for up to 30 s (and as the elected owner for up to 60 s). So the next sync didn't hand its catch-up to the running `gbrain serve`: it ran its own consumer next to the serve. When the write owner was killed mid-catch-up, the requests it had claimed stayed claimed until their publication lease ran out, about 365 s with the default ceiling. Now a process proves from `/proc` that a same-machine owner is dead (its pid is gone, or now belongs to a process that started later) and stops waiting for it. In the new convergence harness (seed 6650) the worst stall after an owner kill went from 356 s and 362 s to 0 s with no injected latency, and from 364 s to 30 s at 50 ms; the catch-up after a serve kill went from 385 s to 29 s. Where `/proc` is unavailable (macOS) the time-based rules are unchanged.
diff --git a/docs/architecture/key-files/persistence-stalls.md b/docs/architecture/key-files/persistence-stalls.md
index dac066f0ec..0ab437b353 100644
--- a/docs/architecture/key-files/persistence-stalls.md
+++ b/docs/architecture/key-files/persistence-stalls.md
@@ -27,12 +27,12 @@ owner (`owner_wedged_here`), movement surfaces (`data_moving`, doctor
- `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, + the 5 s #6650 dead-owner scan, 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. Every claimed write has a preparation budget (`preparation-budget.ts`): `execute` races the preparation against it (`startPreparation`), so the claim is released with `blocked_reason` `preparation_deadline` and one counted attempt at the budget even when the preparer ignores its signal, and a late result never publishes (the execution-token fence). A request already at `persistence.max_preparation_attempts` is finished `failed` with `preparation_stalled` at claim without preparing again, and the release that reaches the limit finishes it there (`coordinator.ts` `finishPreparationStalled`; a waiting `awaitWrite` caller gets the terminal receipt, foreground writes included); a preparer's rejection on the consumer's own abort (its reason, an `AbortError` or a cancelled statement, `preparationAbortReason`) is a release, never a receipt. The expired-claim sweep (Postgres, and PGLite's `releaseAbandonedClaims`) charges one attempt for a claim stamped `preparing` (a process killed mid-preparation); `claim_lost`, `consumer_stopping` and `group_member_waiting` never charge, and a commit resets the counter. The #5373 root barrier for an abandoned preparation ends at `persistence.preparation_ceiling_ms` measured from the claim: the root is freed, the counter is pinned at the limit (an overrun proves cancellation is ignored, so the next claim fails the request `preparation_stalled`) and the zombie stays in `status().outlived_ceiling`; at the per-process cap (`zombieCap`, default 1) the consumer claims nothing more and `status().restart_required` is true. `stop()` gives abandoned preparations `ABANDONED_STOP_GRACE_MS` (5 s) after aborting them instead of waiting forever. The fault point `consumer:preparing` sits inside the budget, `status()` reports `preparation_policy` and `abandoned_preparations`, and the stderr line carries `phase=preparation reason=deadline_exceeded | preparation_stalled | ceiling_exceeded`. With the `preparation_deadlines` switch off only `remember` and intent-less `put_page`/`edit_page` keep the 30 s budget, the old unbounded wait applies and no attempt is counted. 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 `claimableWriteSql` 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); a provably dead owner's claim goes in 5 s (#6650). 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 or the ceiling passes, while the consumer slot frees at once. Renewals are never awaited on the way out: `stop()` drains in-flight renewals and gives abandoned preparations their grace before engine close. Tests: `test/persistence-claim-lease.test.ts`, `test/e2e/persistence-consumer-claim-loss.test.ts`, `test/persistence-preparation-kill-accounting.test.ts`, `test/e2e/persistence-preparation-deadline.e2e.test.ts`. #6355: `onLane` lends its warm lane's transaction through a wrapper that notes a connection loss (`isConnectionLoss`); in `finally` a lost lane is released and `idleLaneRetryAt` set a minute out, whatever `run` returned or threw (admission turns the loss into `write_outcome_unknown` or succeeds on the pool, so the catch alone never saw it), because the dead reservation answers every later statement with "Connection is no longer owned" (`test/persistence-consumer-lane-loss.test.ts`).
- **`src/core/persistence/sync-group.ts`** + **`group-publish.ts`** — #5984 bulk publication for draining managed Postgres syncs. `sync-group.ts` resolves bulk settings (`--no-bulk` > `GBRAIN_SYNC_BULK` > `sync.bulk` > on; `sync.bulk_size` 16, `sync.bulk_max_txn_ms` 15 s; PGLite off), sizes the next group from the last group's admission-to-commit time per member, freezes followers (four at a time, stopping at a rename, company plan, overtaken entry or one the waiver would take) and admits a group in one transaction (`admitWriteGroupInTransaction`, which keeps one request row, ID and digest per page and replays priors). `sync-run.ts` keeps the head in `pending` and all members in the cursor's `group` (members carry `intent.group` = the head's request ID), waits for the last member and advances over the committed prefix; a terminal failure becomes the single pending entry, a still-pending member returns `writer_pending`. Any caller finishes an existing group; only a drain forms one. #6075: when another owner loop already admitted the group's head on the single path with the head's pre-group intent (the intent minus the `group`/`lane` keys `formGroup` adds, `groupedIntent`/`ungroupedIntent`), `groupStep` drops the group and the single path takes that request, and the never-admitted followers are frozen again; a different intent under the head's request ID still refuses `idempotency_conflict`. The single path's ENG-A7 admission guard compares the stored pending intent as well as its request ID, so a pass that read the head before a drain grouped it re-reads the cursor instead of admitting the stale intent, and an `idempotency_conflict` against a head the group admitted first re-reads the cursor too (`test/managed-sync-stale-group-head.test.ts`). The consumer claims a head's directly following queued members (`claimGroupFollowers`, never past an unfinished non-member) and `executeClaimedGroup` prepares four at a time, then `publishGroup` publishes them in one transaction: one worktree lock, ownership guard and coordinated write (each member set as the attributed actor with `setMemberAttribution`), per-member authorization, preimage read, sync validation (its source-wide part shared per transaction), apply (which reads the postimage the receipt and effects use), effects and receipt; `completeGroup` then reads every member's effect bytes, and pipelines the counter lock with one `UPDATE ... FROM unnest(...) RETURNING` that checks each member's claim and terminal reservation and releases the counters (a short `RETURNING` throws, so the single path reports each member's own code). Any failure rolls the group back; members then publish singly, later members are cancelled after a terminal failure or released after a requeue. Sync validation accepts a group member through the cursor's `group`. #6007: the pages of one `put_pages` batch (`intent.page_batch.id`; the group key is `journal.ts` `publicationGroupKey`) and the files of one managed import batch (`intent.import_batch`, key `import:`, grouped on PGLite too; `independentGroup` names both) also publish as groups of at most `PAGE_BATCH_GROUP_MAX` (8) pages, prepared all at once, files included: one transaction records every member's recovery record (`prepareRecoveries`) before any file is touched, the publication transaction marks the members `publication_started`, publishes each member's file before its apply and re-arms the batch's mention links once after every member completes (`reconcileFinishedBatch`), and one transaction clears the records after commit (`clearResolvedRecoveries`). A single foreground page write publishes here too, as a group of one (core-persistence-continued.md, `switches.ts` entry). Within that transaction the source's local path, the owner's host binding and config values are read once per group (source membership and the writer registration are already memoized per transaction by `transactionMemo`). On failure every file the group published is restored by `recoverPublication`, which requeues those claims; the fallback claims them back in order (`reclaimReleasedWrite`) and publishes the members singly, and a batch member's failure never cancels its siblings. Each member has its own preparation budget (#6278): `executeClaimedGroup` marks a wave durably (`markDispatched`) and starts each member's clock when the wave dispatches it, so a follower waiting behind four others is never charged; the lease renews the mutable set of members still held (`renewGroupClaims` stamps each member's own phase), so releasing one member never reads as a lost group lease. When member k's budget passes, nothing later is dispatched, the in-flight suffix is aborted, k is released `preparation_deadline` (charged; finished `preparation_stalled` when that reaches the limit) and the later members `group_member_waiting` (not charged), and the contiguous prepared prefix 0..k-1 publishes (singly when shorter than two; under lanes in the original group's key order). An independent `put_pages` batch group releases only k, `laneFallback` keeps the expired member's reason, and an abandoned member's preparation goes to the consumer with its clock, so the root waits for it until it settles or the ceiling. A member's signal reaches its preparer through its clock (`enterClaimStep`), never as a blanket statement signal: `preparationReads` and `groupReads` answer one read for every member (GBRA-75 wave 10: `preparationReads` answers `getConfig` from one `getAllConfig` per group; an import group's members also read their own `{ sourceId, includeDeleted: true }` snapshot from one batch and coalesce `findDuplicatePage` into one `findDuplicatePages` statement through `import-reads.ts`, and the group's preparation runs inside `withScreeningPaths`; publication's `validate`/`checkPaths` run after it, unmemoized) and skip their memo for a signalled statement, so a member that must give up on a shared read races its own signal against the shared promise (pinned by `test/persistence-preparation-memo-rule.test.ts`). A commit resets `preparation_attempts` (`completeGroup`). Tests: `test/managed-sync-bulk.test.ts`, `test/e2e/put-pages-group-postgres.test.ts`, `test/e2e/persistence-group-deadline-postgres.test.ts`.
- `src/core/persistence/identity.ts` — local writer and host identity. GBRA-75 wave 7: `localHostId` / `localHostIdentity` / `existingLocalHostId` share one cache of the validated `host.json`, keyed on the path (recomputed from `persistenceHome()` on every call, so a `GBRAIN_HOME` change misses) plus `statSync(bigint)` dev, ino, mtimeNs, ctimeNs and size. ENOENT is a miss (`existingLocalHostId` never mints); any other stat error reads uncached, so `writer_identity_invalid` still throws on every call; an invalid document is never cached; a file modified under 2 s ago is read but not cached (same-size rewrites inside one timestamp tick). `scripts/persistence/harness.ts` `selectFixtureHost` (rename over the path) stays correct. Tests: `test/persistence-host-identity-cache.test.ts`.
-- `src/core/persistence/consumer-heartbeat.ts` — #6317 (B1a, B3): the probe and heartbeat behind one full consumer per host. `consumerIdentity()` is this process's `{pid, nonce, pid_ns}` (a random per-process nonce and the pid-namespace inode from `/proc/self/ns/pid` where readable), so a reused pid after a container restart is a new row; every `owner_pid === process.pid` check compares the nonce too. `startConsumerHeartbeat(engine, row, opts)` renews this process's `persistence_consumers` row every 10 s on its own single-flight timer through `executeRawDirect` (independent of claim renewal: an idle `serve` holds no claim), carrying kind (`claimOwner().kind`), mode (`probing|full|waiter_only|promoted`), `restart_required`, the age of the oldest abandoned root barrier, the pool gauge `{checked_out, max, waiters}`, `host_json_path`, `persistence_home`, `minted_under` and the build; each renewal deletes rows not renewed for 90 s in the same CTE, and a failed write is logged once and never stops the consumer. #6650: rows carry `boot_id`, `process_start` (v243); the probe and `electOwner` skip rows `consumerRowProvablyDead` proves dead (Linux: same boot and pid ns, pid gone/reused). `probeLiveFullConsumer(engine, hostId, self)` is the database-only probe (never a socket: the persistence IPC socket exists only on PGLite): a row of a resident kind (`serve`, `sync`, `jobs`, `autopilot`, `mcp`), mode `full`, not this process, renewed within 30 s, not `restart_required` and not wedged (no root barrier older than `persistence.preparation_ceiling_ms`), on an `active` binding. `listHostConsumers(engine, hostId)` feeds `writer status --json` `host.consumers` and doctor. The consumer mode machine in `consumer.ts` (`probing` → `full` or `waiter_only` → `promoted` → back to `waiter_only` after three healthy owner ticks) consumes the probe on every tick; `startPersistenceConsumer` in `service.ts` stays synchronous and returns the waiter-only seam (`WaiterOnlyConsumer` behind `PersistenceConsumerLike`: `wake()` no-op, settlement listeners kept, `holds()` false, `status()` `waiter_only` with the owner pid) when the probe finds an owner and `persistence.single_consumer` is on. A `serve` always starts full; short-lived kinds (`put`, `import`, `dream`, `cycle`, `sources`, `cli`) keep their own consumer; PGLite is inert.
+- `src/core/persistence/consumer-heartbeat.ts` — #6317 (B1a, B3): the probe and heartbeat behind one full consumer per host. `consumerIdentity()` is this process's `{pid, nonce, pid_ns}` (a random per-process nonce, the `/proc/self/ns/pid` inode where readable), so a reused pid after a container restart is a new row; every `owner_pid === process.pid` check compares the nonce too. `startConsumerHeartbeat(engine, row, opts)` renews this process's `persistence_consumers` row every 10 s on its own single-flight timer through `executeRawDirect` (independent of claim renewal: an idle `serve` holds no claim), carrying kind (`claimOwner().kind`), mode (`probing|full|waiter_only|promoted`), `restart_required`, the age of the oldest abandoned root barrier, the pool gauge `{checked_out, max, waiters}`, `host_json_path`, `persistence_home`, `minted_under` and the build; each renewal deletes rows not renewed for 90 s in the same CTE, and a failed write is logged once and never stops the consumer. #6650: rows carry `boot_id`, `process_start` (v243); the probe and `electOwner` skip rows `consumerRowProvablyDead` proves dead (Linux: same boot and pid ns, pid gone/reused). `probeLiveFullConsumer(engine, hostId, self)` is the database-only probe (never a socket: the persistence IPC socket exists only on PGLite): a row of a resident kind (`serve`, `sync`, `jobs`, `autopilot`, `mcp`), mode `full`, not this process, renewed within 30 s, not `restart_required` and not wedged (no root barrier older than `persistence.preparation_ceiling_ms`), on an `active` binding. `listHostConsumers(engine, hostId)` feeds `writer status --json` `host.consumers` and doctor. The consumer mode machine in `consumer.ts` (`probing` → `full` or `waiter_only` → `promoted` → back to `waiter_only` after three healthy owner ticks) consumes the probe on every tick; `startPersistenceConsumer` in `service.ts` stays synchronous and returns the waiter-only seam (`WaiterOnlyConsumer` behind `PersistenceConsumerLike`: `wake()` no-op, settlement listeners kept, `holds()` false, `status()` `waiter_only` with the owner pid) when the probe finds an owner and `persistence.single_consumer` is on. A `serve` always starts full; short-lived kinds (`put`, `import`, `dream`, `cycle`, `sources`, `cli`) keep their own consumer; PGLite is inert.
- `src/core/schema-migrations/v222-persistence-consumers.ts` — #6317 (T-01): the `persistence_consumers` table, primary key `(host_id, pid, nonce)`, columns `pid_ns`, `kind`, `mode`, `started_at`, `renewed_at`, `restart_required`, `root_barrier_age_ms`, `pool` jsonb, `host_json_path`, `persistence_home`, `minted_under` jsonb, `version`; plus the partial index `persistence_requests (worktree_id, completed_at DESC) WHERE state = 'committed'` that the movement watermark reads (the baseline indexes cover pending, recovery and principal reads only). Both objects are also in `src/schema.sql` for fresh installs (PGLite and Postgres parity, goldens). The number is taken at the merge slot by `bun run release:restamp`.
- `src/commands/doctor/checks/persistence-consumers.ts` — #6317 (B3, T1c): doctor `two_consumers_on_host` (warn only when two live rows of resident kinds on this host have both been alive longer than 30 s; every other row, a `put` or a row younger than 30 s, is listed in `details`) and `consumers_without_heartbeat` (a `claim_phase.owner` pid on a running claim of this host with no heartbeat row: an older process that never defers; named with its kind and version from the stamp). Both carry a structured `agentFix` (`gbrain sources writer status --json`) and `doctorVerify`; with `persistence.single_consumer` off the overlap is reported as the configured behavior. Registered in `DOCTOR_CHECK_REGISTRY` before `searchModeEntry` and categorised `ops` in `src/core/doctor-categories.ts`.
- `src/commands/doctor/checks/managed-sync-movement.ts` + `src/core/persistence/sync-movement.ts` — #6317 (B4, I2): the movement reader and its doctor check. `readManagedSyncMovement` snapshots, per active managed source, the newest `completed_at` of committed `managed_sync_*` receipts in the current source incarnation (the watermark, one probe of the partial index `persistence_requests_sync_watermark`, v223, whose predicate repeats the read's kind test; a count would shrink under compaction), the head claim's `step_since`, the `managed-sync` cursor (`index/total`, `held`) and `sources.last_sync_at`/`last_commit`, and whether a drain or full consumer is live on the owner host. `data_moving` is false when an unfinished cursor has had neither a committed receipt nor a head step advance for longer than `persistence.preparation_ceiling_ms` while a consumer is live; with none live the state is `parked` (informational). `sources status --json` and `writer status --json` print `data_moving`, `not_moving_since` and `movement_state` beside `sync_running`, and `sources status` prints the exact `gbrain sources writer status --source <id> --json` beside `data_moving: false`; doctor `managed_sync_not_moving` (warn; counts against the score for `not_moving`, never for `parked`) uses the same rule with that command as its structured fix; `serve` prints one `[gbrain notice]` when a source flips. `/health` stays liveness-only.
- `src/commands/sources-writer-movement.ts` — #6317 (I2): `gbrain sources writer movement [<source>] [--wait <dur>] [--warn-only] [--json]`, the deploy gate `gbrain upgrade` and `post-upgrade` end by printing (bare, so it inherits the default window; neither runs it, because neither restarts the resident processes). Same source selection as `writer status` (`persistence-admin.ts`). It snapshots through `sync-movement.ts`, waits `max(300 s, preparation budget + 60 s)` (printed as the effective budget; `--wait <dur>` takes sync's duration syntax) and judges each source: `moved` (a new committed publication; a cursor advanced only by holds or a `last_sync_at` touched by an up-to-date check is not movement) and `current` exit 0; `held` exits 0 with a warning and the hold kind's route (`gbrain repair fences --source <id>`; `preparation_stalled` → writer status, then `gbrain sources retry-held <id>`); `within_allowance` (the head's step advanced inside the window) exits 0 with `retry_after_ms`; `not_moving` exits 1 with `managed_sync_not_moving` (`reason: movement_check`, `fix.argv` the writer-status command, `fix.verify` this command); `unknown` carries the read failure's own code with `fix.next: report`. `--warn-only` prints the same envelopes and exits 0. Flags are regenerated into `src/core/cli-flag-registry.generated.ts` with `bun run build:flag-registry`.
-- `src/core/persistence/journal.ts` — the request journal SQL: admission, claims, renewals, releases and completion. #6278: the claim statements stamp a `preparing` phase of their own token at claim time and return the previous claim's stamp with the row (`previous_claim_phase`), so a stalled receipt names the last recorded step; a group follower carries no stamp until its wave dispatches it (`markDispatched`), so a kill charges exactly the members that were preparing; `renewGroupClaims` stamps each member's own phase; `releaseUnpublishedClaim` charges one `preparation_attempts` only for `preparation_deadline` (`claim_lost`, `consumer_stopping` and `group_member_waiting` never do); `chargePreparationAttempt` charges a claim this owner still holds before it is finished `preparation_stalled`; `floorPreparationAttempts` pins the counter at the limit after a ceiling overrun; completing a request as committed resets the counter (`completeWrite`, `completeGroup`). An older owner ignores the counter and its renewals overwrite the stamp with the old shape (writer status shows each owner's version); every statement keeps `PERSISTENCE_PROTOCOL_PREDICATE`. Tests: `test/persistence-preparation-kill-accounting.test.ts`, `test/e2e/persistence-preparation-attempts-postgres.test.ts`.
+- `src/core/persistence/journal.ts` — the request journal SQL: admission, claims, renewals, releases and completion. #6278: the claim statements stamp a `preparing` phase of their own token at claim time and return the previous claim's stamp with the row (`previous_claim_phase`), so a stalled receipt names the last recorded step; a follower's stamp has only its token and owner (#6650) until its wave dispatches it (`markDispatched`), so a kill charges exactly the members that were preparing; `renewGroupClaims` stamps each member's own phase; `releaseUnpublishedClaim` charges one `preparation_attempts` only for `preparation_deadline` (`claim_lost`, `consumer_stopping` and `group_member_waiting` never do); `chargePreparationAttempt` charges a claim this owner still holds before it is finished `preparation_stalled`; `floorPreparationAttempts` pins the counter at the limit after a ceiling overrun; completing a request as committed resets the counter (`completeWrite`, `completeGroup`). An older owner ignores the counter and its renewals overwrite the stamp with the old shape (writer status shows each owner's version); every statement keeps `PERSISTENCE_PROTOCOL_PREDICATE`. Tests: `test/persistence-preparation-kill-accounting.test.ts`, `test/e2e/persistence-preparation-attempts-postgres.test.ts`.
- `src/core/persistence/diagnostics.ts` — trusted administrator counts for owners/epochs, queued bytes/age, outbox recovery, configured quota usage and actionable capacity warnings; bigint values are transport-safe strings and diagnostics exclude intent, credentials and private paths. Writer status's blockers also carry each request's `operation`, `intent_kind` and `preparation_attempts`; a running blocker's `claim` adds the preparation `step`, `step_age_ms`, `waiting_on`, the owner process (kind, pid, gbrain build, from the live claim's stamp), `budget_ms` and, past the budget, `stall: { reason: 'preparation_overdue', step, step_age_ms, waiting_on, budget_ms }` (`claimStall`; `WRITE_HEALTH_REASONS`, the wire enum, is unchanged). `WRITER_NEXT_ACTIONS` has entries for `preparation_deadline` (keep the request id: the owner will claim it again) and `preparation_stalled` (do not resubmit under the same id; retry-held after the fix), and the result carries `preparation_policy` (the budgets, ceiling, attempt limit and switch in effect). Doctor `persistence_write_stall` prints the same fields. Tests: `test/persistence-writer-status-stall.test.ts`.
- `src/core/schema-migrations/v220-persistence-request-preparation-attempts.ts` — #6278: `persistence_requests.preparation_attempts integer NOT NULL DEFAULT 0 CHECK (preparation_attempts >= 0)`, the count of cut-offs of a request's preparation. Existing rows start at 0; a commit resets it. It is a migration-created column (also in the `persistence_requests` CREATE TABLE of `src/schema.sql`, with no index) so a fresh install and an upgraded brain keep the same column order. Tests: `test/persistence-preparation-attempts-migration.test.ts`, `test/e2e/persistence-preparation-attempts-postgres.test.ts`.
- `src/core/persistence/pre-activation-release.ts` — #6122: `preActivationClaims` lists the source bindings of a never-activated brain with their roots; `releasePreActivationClaims` (called by `deactivatePersistence` on a disabled brain once `deactivationBlockers` is empty) takes the local worktree locks with `identity: 'reservation'` (#5914: it publishes nothing, so a recreated directory whose reservation names the worktree and whose stamp carries the same token releases; a token mismatch refuses), then in one transaction checks the admin state, the admin lock and that the brain is still disabled, re-runs the blockers, retires the claimed worktrees, deletes the source and host bindings and records a committed `writer_deactivate` change with `outcome.pre_activation: true`, so `cleanupRetiredManagedMarkers` clears this host's claim markers. It ensures the CLI writer registration first (a never-activated brain may have none). `sync-authority.ts` `resolveSyncPersistenceMode` refuses such a claimed source with an agent-first `writer_coordinator_required`: both choices in the suggestion, `fix` the state-bound release (`consent: ['destructive']`, so `ask_user`, with the dry run as `preview_argv`). In `deactivation.ts`: on a brain whose managed persistence was never activated, `--dry-run` reports the real `source_bindings` and each claim as `pre_activation_claims` (and `apply_command` when clean), and the state-bound run releases them through `pre-activation-release.ts`; with no claims a rerun still only cleans retired markers. Tests: `test/persistence-preactivation-claim.test.ts`. In `unbound-source.ts`: on a brain whose managed persistence is not activated, the hint offers editing the page's file plus `gbrain sync --source <id>` (and `persistence.unbound_write=database_only` where it applies) instead of the claim, and says a claim alone would block classic sync until activation or `gbrain sources writer deactivate`.
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index facb321968..4260d7ac01 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -561,6 +561,8 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }
// #6650 L0 (convergence harness fixes). `since` is a placeholder equal to the branch's VERSION until the merge-slot stamp.
{ since: '0.60.223.0', text: 'On Linux, a `gbrain sync` started after another gbrain process on the same machine was killed no longer treats the dead process\'s heartbeat as a live write owner. Before, it refused to hand its catch-up to the running `gbrain serve` for up to 30 s and ran its own consumer next to it; now it hands the catch-up to the serve (or runs its own consumer when no serve is running). A waiter-only consumer deferring to the dead process promotes on its next check instead of after 60 s. A heartbeat row from another host or container, or from an older gbrain, keeps the time-only rule, as does every row where `/proc` is unavailable.' },
{ since: '0.60.223.0', text: 'On Linux, when the process holding write claims on this host is killed, another consumer on the same machine now reclaims those claims within about 5 s instead of waiting out their lease (up to `persistence.publication_ceiling_ms` plus about 65 s, so about 365 s by default). Only claims with no recovery record and no publication started are taken, the same guard an expired claim has. An owner that is alive, however slow, or on another host or container keeps its full lease.' },
+ // #6650 follow-up (group follower stamps). `since` is a placeholder equal to the branch's VERSION until the merge-slot stamp.
+ { since: '0.60.223.0', text: 'On Linux, when a gbrain process holding a group of writes is killed, the group members it had claimed but not started are now reclaimed with its other claims within about 5 s, instead of after their 30 s claim lease. Members it had started, and any member with a recovery record or a publication in progress, are handled as before. A host with a dead owner row ahead of more than eight others now still finds the live `gbrain serve` to hand a sync to.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/persistence/claim-phase.ts b/src/core/persistence/claim-phase.ts
index 79158c4b84..860f181226 100644
--- a/src/core/persistence/claim-phase.ts
+++ b/src/core/persistence/claim-phase.ts
@@ -261,8 +261,9 @@ export function claimStateOf(row: ClaimRow, now = Date.now()): ClaimState | null
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, ...detail, 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, ...detail, 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).' };
+ // #6650: an undispatched group follower's stamp names its token and owner but no phase yet.
+ if (!own || (stamp!.phase !== 'preparing' && stamp!.phase !== 'publishing')) return { phase: 'unrecorded', claim_age_ms: claimAge, phase_age_ms: null, ...detail, resumes_on_its_own: false,
+ why: 'The owner has not recorded this claim\'s phase (a claim younger than one renewal, a group member its owner has not started yet, 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), ...detail, resumes_on_its_own: false,
why: `Its owner is still renewing the claim while it is ${phase === 'preparing' ? 'preparing the write' : 'publishing the write'}${step ? ` (step ${step}, waiting on ${detail.waiting_on})` : ''}, so the lease never lapses and nothing else on its root runs until that work settles or the owner restarts.` };
diff --git a/src/core/persistence/consumer-heartbeat.ts b/src/core/persistence/consumer-heartbeat.ts
index 41f8dcb95f..eaaf47b33e 100644
--- a/src/core/persistence/consumer-heartbeat.ts
+++ b/src/core/persistence/consumer-heartbeat.ts
@@ -183,7 +183,7 @@ export async function probeLiveFullConsumer(engine: SqlEngine & Partial<Pick<Bra
const rows = await engine.executeRaw<RawRow>(`SELECT ${ROW_COLUMNS} FROM persistence_consumers
WHERE host_id=$1::uuid AND mode IN ('full','promoted') AND kind=ANY($2::text[]) AND NOT (pid=$3::integer AND nonce=$4)
AND renewed_at > now() - ($5::integer * interval '1 millisecond') AND NOT restart_required
- ORDER BY started_at,pid LIMIT 8`, [hostId, [...RESIDENT_CONSUMER_KINDS], self.pid, self.nonce, CONSUMER_LIVE_MS], { signal: opts.signal });
+ ORDER BY started_at,pid`, [hostId, [...RESIDENT_CONSUMER_KINDS], self.pid, self.nonce, CONSUMER_LIVE_MS], { signal: opts.signal });
const ceiling = opts.ceilingMs ?? 600_000;
const live = rows.map(row => listed(row, self))
.find(row => !consumerWedged(row, ceiling) && !consumerRowProvablyDead(row, self));
diff --git a/src/core/persistence/diagnostics.ts b/src/core/persistence/diagnostics.ts
index 2efaa4f9d8..6b3778f40a 100644
--- a/src/core/persistence/diagnostics.ts
+++ b/src/core/persistence/diagnostics.ts
@@ -58,7 +58,7 @@ export function claimNextAction(claim: ClaimState, stall: ClaimStall | null, pol
return { code: 'claim_lapsed', retry_after_ms: null, why: `The claim lapsed while running; the request is requeued once the transaction holding its row ends or the owner exits, and the next consumer claims it.`,
fix: renderAction({ argv: status, consent: [], actor: 'agent', requires_exclusive: false, why: 'Read-only: rerun to see the request requeued or claimed again.', verify: { argv: status } }, ctx) };
}
- const age = claim.phase_age_ms ?? claim.claim_age_ms ?? 0;
+ const age = claim.phase === 'unrecorded' ? 0 : claim.phase_age_ms ?? claim.claim_age_ms ?? 0;
const pastCeiling = claim.phase === 'preparing' && age >= policy.ceilingMs;
const wedged = owner.row?.restart_required === true || (owner.row?.root_barrier_age_ms ?? -1) > policy.ceilingMs;
if (pastCeiling || wedged) {
@@ -70,7 +70,7 @@ export function claimNextAction(claim: ClaimState, stall: ClaimStall | null, pol
const budgetLeft = stall ? Math.max(0, policy.ceilingMs - age) : policy.budgetMs === null ? null : Math.max(0, policy.budgetMs - age);
return { code: 'claim_running', retry_after_ms: budgetLeft,
why: stall ? `${who} is past the ${Math.round(stall.budget_ms / 1000)}s preparation budget${where}; its own budget cuts the preparation off and frees the root by the ${Math.round(policy.ceilingMs / 1000)}s ceiling (${Math.round((budgetLeft ?? 0) / 1000)}s left). Nothing to do yet.`
- : `${who} is ${claim.phase === 'publishing' ? 'publishing' : 'preparing'} this write${where}${owner.live === false ? '; its heartbeat row is not live' : ''}. Nothing to do yet.`,
+ : `${who} ${claim.phase === 'unrecorded' ? 'holds this write and has not recorded starting it (a group member waits for the members before it)' : `is ${claim.phase === 'publishing' ? 'publishing' : 'preparing'} this write`}${where}${owner.live === false ? '; its heartbeat row is not live' : ''}. Nothing to do yet.`,
fix: renderAction({ argv: status, consent: [], actor: 'agent', requires_exclusive: false, why: 'Read-only: rerun after retry_after_ms to see the step advance or the claim settle.', verify: { argv: status } }, ctx) };
}
/**
diff --git a/src/core/persistence/journal.ts b/src/core/persistence/journal.ts
index 120d40c67e..2e73b801dd 100644
--- a/src/core/persistence/journal.ts
+++ b/src/core/persistence/journal.ts
@@ -14,7 +14,7 @@ import { pipelined } from '../page-state/transactions.ts';
import { writeHealth, type WriteHealthFacts } from './health.ts';
import { writerStamp } from './writer-versions.ts';
import { intentCarriesContent, intentCarriesPurgedContent, PURGE_PRESENCE_COLUMNS } from './purged-intent.ts';
-import { claimPhaseStamp, startClaimPhase } from './claim-phase.ts';
+import { claimOwner, claimPhaseStamp, startClaimPhase } from './claim-phase.ts';
import { consumerIdentity } from './consumer-heartbeat.ts';
import { publicFailureDetail } from './publication-failure.ts';
import { catalogueError } from '../error-catalogue.ts';
@@ -368,10 +368,13 @@ export async function claimGroupFollowers(engine: BrainEngine, head: WriteReques
}
if (!members.length) return [];
const tokens = members.map(() => randomUUID());
- // #6278: a follower carries no stamp of its claim until its wave dispatches it (`markDispatched`), so an undispatched follower is never charged.
+ // #6278: a follower carries no phase until its wave dispatches it (`markDispatched`), so an undispatched follower is never
+ // charged. #6650: it does carry its token, owner and claim time, so a consumer that proves the owner dead reclaims it with
+ // the head, and writer status and doctor age the claim from when it was taken.
return tx.executeRaw<WriteRequest>(`UPDATE persistence_requests r SET state='running',execution_token=t.token,
- claim_expires_at=now()+($3::double precision*interval '1 millisecond'),updated_at=now(),blocked_reason=NULL,claim_phase=NULL
- FROM unnest($1::uuid[],$2::uuid[]) AS t(id,token) WHERE r.id=t.id AND r.state='queued' RETURNING r.*`, [members, tokens, leaseMs])
+ claim_expires_at=now()+($3::double precision*interval '1 millisecond'),updated_at=now(),blocked_reason=NULL,
+ claim_phase=jsonb_build_object('token',t.token::text,'owner',$4::text::jsonb,'claimed_at',to_jsonb(now()))
+ FROM unnest($1::uuid[],$2::uuid[]) AS t(id,token) WHERE r.id=t.id AND r.state='queued' RETURNING r.*`, [members, tokens, leaseMs, JSON.stringify(claimOwner())])
.then(rows => rows.sort((a, b) => Number(BigInt(a.sequence) - BigInt(b.sequence))).map(row => ({ ...row, previous_claim_phase: previous.get(row.id) })));
});
}
diff --git a/src/core/persistence/sync-drain.ts b/src/core/persistence/sync-drain.ts
index 5f4e531ac3..c584a5f720 100644
--- a/src/core/persistence/sync-drain.ts
+++ b/src/core/persistence/sync-drain.ts
@@ -593,7 +593,8 @@ export function drainClaimOf(row: { head_state: string | null; head_claim_phase:
const own = !!stamp && !!row.head_token && stamp.token === row.head_token;
const age = (at: unknown) => { const ms = typeof at === 'string' ? Date.parse(at) : NaN; return Number.isFinite(ms) ? Math.max(0, now - ms) : null; };
const budget = String(row.head_kind ?? '').startsWith('managed_sync_') ? budgets.syncMs : budgets.maintenanceMs;
- const phase = own ? stamp!.phase === 'publishing' ? 'publishing' : 'preparing' : null;
+ // #6650: an undispatched group follower's stamp names its owner but no phase; it reads as unstamped, never as preparing.
+ const phase = own && (stamp!.phase === 'publishing' || stamp!.phase === 'preparing') ? stamp!.phase : null;
const waiting = own ? stamp!.waiting_on : null;
const owner = own && stamp!.owner && typeof stamp!.owner === 'object' ? stamp!.owner as Record<string, unknown> : null;
return { phase, step: own && typeof stamp!.step === 'string' ? stamp!.step : null,
diff --git a/test/consumer-provably-dead-6650.test.ts b/test/consumer-provably-dead-6650.test.ts
index 0e201a236a..194947e749 100644
--- a/test/consumer-provably-dead-6650.test.ts
+++ b/test/consumer-provably-dead-6650.test.ts
@@ -85,6 +85,18 @@ describe.skipIf(!linux)('probeLiveFullConsumer skips a row whose owner is provab
});
});
+describe.skipIf(!linux)('the probe skips dead rows before it bounds the rows it reads (#6650)', () => {
+ test('a live serve behind more than eight dead rows is still the owner', async () => {
+ const dead = Array.from({ length: 9 }, (_, i) => row(deadPid(), 'sync', `2026-10-13 10:00:0${i}+00`));
+ const rows = [...dead, row(live.pid!, 'serve', '2026-10-13 10:00:30+00', { start: liveStart })];
+ const limited = { kind: 'postgres' as const, executeRaw: async (sql: string) => {
+ const limit = /LIMIT (\d+)/.exec(sql);
+ return limit ? rows.slice(0, Number(limit[1])) : rows;
+ } } as never;
+ expect((await probeLiveFullConsumer(limited, '00000000-0000-0000-0000-000000000001'))?.pid).toBe(live.pid);
+ });
+});
+
describe.skipIf(!linux)('claimOwnerProvablyDead reads a claim stamp (#6650 defect 2)', () => {
const stamp = (o: Record<string, unknown>) => JSON.stringify({ phase: 'publishing', token: 't', owner: { kind: 'sync', version: '0.0.0', ...o } });
test('a stamp naming a dead owner, as text or jsonb', () => {
diff --git a/test/e2e/persistence-dead-owner-reclaim-6650.test.ts b/test/e2e/persistence-dead-owner-reclaim-6650.test.ts
index 69e20d9e84..f047277e66 100644
--- a/test/e2e/persistence-dead-owner-reclaim-6650.test.ts
+++ b/test/e2e/persistence-dead-owner-reclaim-6650.test.ts
@@ -20,7 +20,9 @@ import { join } from 'node:path';
import postgres from '#postgres';
import { PostgresEngine } from '../../src/core/postgres-engine.ts';
import { DEAD_OWNER_SCAN_MS, PersistenceConsumer } from '../../src/core/persistence/consumer.ts';
-import { admitWrite, getWriteRequestById } from '../../src/core/persistence/journal.ts';
+import { admitWrite, claimGroupFollowers, getWriteRequestById } from '../../src/core/persistence/journal.ts';
+import { setClaimOwnerForTest } from '../../src/core/persistence/claim-phase.ts';
+import type { WriteRequest } from '../../src/core/persistence/model.ts';
import { consumerIdentity, probeLiveFullConsumer } from '../../src/core/persistence/consumer-heartbeat.ts';
import { processStartTime, readBootId } from '../../src/core/pglite-lock.ts';
import { admission, fixtures, initializeFixtures, prepared, selectFixtureHost, type FixtureSource, type HarnessConfig } from '../../scripts/persistence/harness.ts';
@@ -79,8 +81,15 @@ async function stageClaim(engine: PostgresEngine, id: string, owner: Record<stri
return token;
}
+/** Request id -> how many times its mutation was applied (in any transaction, committed or not). */
+const applied = new Map<string, number>();
function consumerFor(engine: PostgresEngine, config: HarnessConfig, sources: FixtureSource[]) {
- return new PersistenceConsumer(engine, { engine: 'postgres' }, async (_engine, row) => prepared(row, sources),
+ return new PersistenceConsumer(engine, { engine: 'postgres' }, async (_engine, row) => {
+ const mutation = prepared(row, sources);
+ const apply = mutation.apply;
+ mutation.apply = (tx, snapshot) => { applied.set(row.id, (applied.get(row.id) ?? 0) + 1); return apply(tx, snapshot); };
+ return mutation;
+ },
{ hostId: config.hostId, concurrency: 3, pollMs: 60_000, phaseMs: 5_000, onError: () => {} });
}
@@ -159,6 +168,50 @@ describe.skipIf(!hasDatabase() || !linux)('a claim held by a provably dead owner
} finally { await consumer.stop(); }
}), 90_000);
+ /** A page batch of `size` whose head `owner` claimed and whose followers it claimed but never dispatched (no phase stamp). */
+ async function stageGroup(engine: PostgresEngine, config: HarnessConfig, source: FixtureSource, prefix: string, owner: { pid: number; start: string }, size = 4) {
+ const batch = randomUUID();
+ const rows: WriteRequest[] = [];
+ for (let i = 0; i < size; i++) rows.push(await admitWrite(engine, admission(config, source, `${prefix}-${i}`, `${prefix} body ${i}`, 0,
+ { intent: { content: `${prefix} body ${i}`, page_batch: { id: batch, index: i, size } }, callerIntent: { content: `${prefix} body ${i}` } })));
+ await stageClaim(engine, rows[0]!.id, owner, 30);
+ const head = (await getWriteRequestById(engine, rows[0]!.id))!;
+ setClaimOwnerForTest({ kind: 'sync', version: '0.0.0', nonce: `n-${owner.pid}`, pid_ns: consumerIdentity().pid_ns, boot_id: readBootId(), ...owner });
+ try { expect((await claimGroupFollowers(engine, head, `batch:${batch}`, 10)).length).toBe(size - 1); } finally { setClaimOwnerForTest(undefined); }
+ return rows;
+ }
+
+ test('a killed leader\'s undispatched followers are reclaimed with it in under 10 s and each publishes once', () => withBrain(async ({ engine, config, sources }) => {
+ const rows = await stageGroup(engine, config, sources[0]!, 'dead-a/group', { pid: deadPid(), start: '1' });
+ const followers = await Promise.all(rows.slice(1).map(row => getWriteRequestById(engine, row.id)));
+ expect(followers.map(row => [row?.state, (row?.claim_phase as { phase?: string } | null)?.phase ?? null])).toEqual(followers.map(() => ['running', null]));
+ const consumer = consumerFor(engine, config, sources);
+ const started = Date.now();
+ try {
+ await consumer.tick();
+ await waitFor(async () => (await Promise.all(rows.map(row => getWriteRequestById(engine, row.id)))).every(row => row?.state === 'committed'),
+ { timeoutMs: 10_000, label: 'the leader and every follower commit' });
+ expect(Date.now() - started).toBeLessThan(10_000);
+ expect(rows.map(row => applied.get(row.id) ?? 0)).toEqual(rows.map(() => 1));
+ const ids = rows.map(row => row.id);
+ expect(await engine.executeRaw(`SELECT e.request_id,e.kind FROM persistence_effects e WHERE e.request_id=ANY($1::uuid[]) GROUP BY e.request_id,e.kind HAVING count(*)>1`, [ids])).toEqual([]);
+ const [pages] = await engine.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM pages WHERE slug LIKE 'dead-a/group-%' AND deleted_at IS NULL`);
+ expect(Number(pages!.n)).toBe(rows.length);
+ } finally { await consumer.stop(); }
+ }), 90_000);
+
+ test('a live, slow leader\'s undispatched followers keep their claims', () => withBrain(async ({ engine, config, sources }) => {
+ const rows = await stageGroup(engine, config, sources[0]!, 'dead-a/slow', { pid: live.pid!, start: liveStart });
+ const before = await Promise.all(rows.map(row => getWriteRequestById(engine, row.id)));
+ const consumer = consumerFor(engine, config, sources);
+ try {
+ await consumer.tick();
+ await Bun.sleep(1_000);
+ const after = await Promise.all(rows.map(row => getWriteRequestById(engine, row.id)));
+ expect(after.map(row => [row?.state, row?.execution_token])).toEqual(before.map(row => ['running', row?.execution_token]));
+ } finally { await consumer.stop(); }
+ }), 90_000);
+
test('an owner from another boot, and an older stamp without the markers, wait for their lease', () => withBrain(async ({ engine, config, sources }) => {
const foreign = await admitWrite(engine, admission(config, sources[0]!, 'dead-a/foreign', 'foreign boot body'));
const older = await admitWrite(engine, admission(config, sources[1]!, 'dead-b/older', 'older owner body'));
diff --git a/test/e2e/persistence-group-deadline-postgres.test.ts b/test/e2e/persistence-group-deadline-postgres.test.ts
index 8bc0ceab47..aaa4837f91 100644
--- a/test/e2e/persistence-group-deadline-postgres.test.ts
+++ b/test/e2e/persistence-group-deadline-postgres.test.ts
@@ -227,7 +227,8 @@ describe.skipIf(!hasDatabase())('grouped preparation deadlines (Postgres, #6278)
const rows = await admitGroup(engine, config, sources[0]!, 'kill', 6, 'ordered');
const release = Promise.withResolvers<void>();
const attempts = new Map<string, number>();
- // Every dispatched member hangs: wave one (members 0-3) is marked preparing, members 4 and 5 are claimed but never dispatched.
+ // Every dispatched member hangs: wave one (members 0-3) is marked preparing, members 4 and 5 are claimed but never dispatched
+ // (#6650: they carry their own token and owner with no phase, so the sweep does not charge them).
const owner = new PersistenceConsumer(engine, { engine: 'postgres' }, hangingPreparer(sources, new Set(rows.map(row => row.id)), release.promise, attempts),
{ hostId: config.hostId, concurrency: 1, pollMs: 60_000, renewalIntervalMs: 60_000, phaseMs: 2_000, preparationMs: 60_000,
preparationBudgets: { maxAttempts: 5, ceilingMs: 120_000 }, onError: () => {} });
@@ -238,7 +239,7 @@ describe.skipIf(!hasDatabase())('grouped preparation deadlines (Postgres, #6278)
await waitFor(() => [0, 1, 2, 3].every(i => attempts.get(rows[i]!.id) === 1), { timeoutMs: 15_000, label: 'the first wave is dispatched' });
const stamps = await engine.executeRaw<{ slug: string; phase: string | null; own: boolean }>(`SELECT slug,claim_phase->>'phase' AS phase,
claim_phase->>'token'=execution_token::text AS own FROM persistence_requests WHERE id=ANY($1::uuid[]) ORDER BY sequence`, [rows.map(row => row.id)]);
- expect(stamps.map(s => [s.phase, s.own])).toEqual([['preparing', true], ['preparing', true], ['preparing', true], ['preparing', true], [null, null], [null, null]]);
+ expect(stamps.map(s => [s.phase, s.own])).toEqual([['preparing', true], ['preparing', true], ['preparing', true], ['preparing', true], [null, true], [null, true]]);
// The owner dies (its renewals never run again); the leases lapse and another consumer's sweep reclaims them.
await engine.executeRaw(`UPDATE persistence_requests SET claim_expires_at=now()-interval '1 second' WHERE id=ANY($1::uuid[])`, [rows.map(row => row.id)]);
(sweeper as unknown as { rootRetryAfter: Map<string, number> }).rootRetryAfter.set(rows[0]!.worktree_id!, Date.now() + 60_000);
diff --git a/test/persistence-claim-step.test.ts b/test/persistence-claim-step.test.ts
index 4393576c1c..449e64f2d1 100644
--- a/test/persistence-claim-step.test.ts
+++ b/test/persistence-claim-step.test.ts
@@ -72,6 +72,14 @@ describe('claimPhaseStamp and claimStateOf', () => {
// Another claim's stamp: nothing of it is attributed to the current token.
expect(claimStateOf({ state: 'running', claim_phase: stamp, execution_token: 't2' }, now)).toMatchObject({ phase: 'unrecorded', step: null, step_age_ms: null, waiting_on: 'unknown', owner: null });
});
+ test('#6650: an undispatched group follower\'s stamp (token and owner, no phase) reads as unrecorded with its owner, never as preparing', () => {
+ const owner = { kind: 'sync', pid: 7, version: '0.60.200.0' };
+ const now = Date.parse('2026-10-08T03:12:00Z');
+ const state = claimStateOf({ state: 'running', claim_phase: { token: 't1', owner, claimed_at: '2026-10-08T03:00:00.123456+00:00' }, execution_token: 't1' }, now);
+ expect(state).toMatchObject({ phase: 'unrecorded', claim_age_ms: 12 * 60_000 - 123, phase_age_ms: null, step: null, owner });
+ expect(state?.why).toContain('a group member its owner has not started yet');
+ expect(claimStall(state, 0)).toBeNull();
+ });
test('an older owner\'s stamp (no step fields) reads as step null and waiting_on unknown, never inferred', () => {
const now = Date.parse('2026-10-08T03:12:00Z');
const old = { phase: 'preparing', claimed_at: '2026-10-08T03:00:00Z', since: '2026-10-08T03:00:00Z', token: 't1' };
diff --git a/test/persistence-write-stall.test.ts b/test/persistence-write-stall.test.ts
index 5fb42515f8..41d55060ed 100644
--- a/test/persistence-write-stall.test.ts
+++ b/test/persistence-write-stall.test.ts
@@ -91,9 +91,17 @@ async function scenario(engine: BrainEngine, config: HarnessConfig) {
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()]);
+ // #6650: an undispatched group follower's stamp (token, owner and claim time, no phase) is aged from its claim time.
+ const follower = await admitWrite(engine, admission(config, sources[0]!, 'stall/follower', 'follower body'));
+ const followerToken = randomUUID();
+ await engine.executeRaw(`UPDATE persistence_requests SET state='running',execution_token=$2::uuid,claim_expires_at=now()+interval '30 seconds',
+ claim_phase=jsonb_build_object('token',$2::text,'owner',jsonb_build_object('kind','sync','pid',4242,'version','v'),'claimed_at',to_jsonb(now()-interval '31 minutes'))
+ WHERE id=$1::uuid`, [follower.id, followerToken]);
const old = await writeStallCheck(engine);
expect(old.status).toBe('warn');
- expect(old.details).toMatchObject({ stalls: [{ request_id: legacy.request_id, phase: 'unrecorded' }] });
+ expect((old.details as { stalls: Array<{ request_id: string }> }).stalls.map(s => s.request_id).sort()).toEqual([legacy.request_id, follower.request_id].sort());
+ expect(old.details).toMatchObject({ stalls: expect.arrayContaining([expect.objectContaining({ request_id: legacy.request_id, phase: 'unrecorded' }),
+ expect.objectContaining({ request_id: follower.request_id, phase: 'unrecorded', stall: null, owner: { kind: 'sync', pid: 4242, version: 'v' } })]) });
expect(errors).toEqual([]);
}
diff --git a/test/sync-drain-claims.test.ts b/test/sync-drain-claims.test.ts
index 462e1a79eb..676545d501 100644
--- a/test/sync-drain-claims.test.ts
+++ b/test/sync-drain-claims.test.ts
@@ -212,6 +212,10 @@ describe('drainClaimOf', () => {
// The ceiling caps the allowance.
expect(drainClaimOf({ head_state: 'running', head_claim_phase: stamp(), head_token: 't', head_lapsed: false, head_kind: 'managed_sync_import' }, { ...budgets, ceilingMs: 60_000 }, now)!.allowance_ms).toBe(60_000 + STALL_GRACE_MS);
});
+ test('#6650: an undispatched group follower\'s stamp (owner, no phase) is unstamped for the stall window and still names its owner', () => {
+ expect(drainClaimOf({ head_state: 'running', head_claim_phase: { token: 't', owner: { kind: 'sync', pid: 9, version: 'v', nonce: 'n9' } }, head_token: 't', head_lapsed: false, head_kind: 'managed_sync_import' }, budgets, now))
+ .toMatchObject({ phase: null, step: null, owner_pid: 9, owner_nonce: 'n9' });
+ });
test('an older owner\'s stamp, a stamp of another claim, or no stamp read as null/unknown, never inferred; a lapsed lease is reported', () => {
expect(drainClaimOf({ head_state: 'running', head_claim_phase: stamp({ token: 'other' }), head_token: 't', head_lapsed: false, head_kind: null }, budgets, now))
diff --git a/test/writer-status-owner-backends.test.ts b/test/writer-status-owner-backends.test.ts
index 688ae0fe53..9516a33ab8 100644
--- a/test/writer-status-owner-backends.test.ts
+++ b/test/writer-status-owner-backends.test.ts
@@ -137,6 +137,11 @@ describe('writer status running claims', () => {
const running = claimNextAction(young, null, { budgetMs: 120_000, ceilingMs: 600_000 }, 's', { row: null, live: null });
expect(running).toMatchObject({ code: 'claim_running', fix: { next: 'run' } });
expect(running.retry_after_ms).toBeGreaterThan(100_000);
+ // #6650: an undispatched follower that has waited longer than its budget has spent none of it.
+ const follower = claimStateOf({ state: 'running', claim_phase: { token: 't', owner: claimOwner(), claimed_at: new Date(Date.now() - 180_000).toISOString() }, execution_token: 't' })!;
+ const waiting = claimNextAction(follower, null, { budgetMs: 120_000, ceilingMs: 600_000 }, 's', { row: null, live: null });
+ expect(waiting).toMatchObject({ code: 'claim_running', retry_after_ms: 120_000, fix: { next: 'run' } });
+ expect(waiting.why).toContain('has not recorded starting it');
const lapsed = claimStateOf({ state: 'running', claim_phase: null, execution_token: 't', claim_lapsed: true })!;
expect(claimNextAction(lapsed, null, { budgetMs: null, ceilingMs: 600_000 }, null, { row: null, live: null })).toMatchObject({ code: 'claim_lapsed', retry_after_ms: null, fix: { next: 'run', argv: ['gbrain', 'sources', 'writer', 'status', '--json'] } });
});