Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

#6650: a killed process's heartbeat and claims no longer stall managed sync

garrytan3b6a6317c6fb
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 82878081e2..49c1a40fd5 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.219.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.
+
+### Itemized changes
+
+- **Heartbeat rows** (`src/core/persistence/consumer-heartbeat.ts`, migration v243): each `persistence_consumers` row records its process's kernel boot id and start time (`/proc/<pid>/stat` field 22). `consumerProvablyDead` is true only for an owner under this boot and pid namespace whose pid is gone or reused. A process whose `/proc` numbers another pid namespace's processes records no start time and proves nothing. The owner probe behind serve-delegated sync and the waiter election (`consumer-election.ts` `electOwner`) skip such a row at once. A row from another host or container, or from an older gbrain without the new columns, keeps the time-only rule.
+- **Claims of a dead owner** (`src/core/persistence/consumer.ts`, `claim-phase.ts`): the claim stamp records the same boot id and start time. Every 5 s (Postgres), including while the consumer is idle, it looks up the distinct owners of running claims on its own roots. The expired-claim reclaim takes a claim at once when its stamp of the current token names an owner proven dead, instead of when its lease (up to the publication ceiling plus about 65 s) runs out. A claim re-taken by a live owner since the scan carries a new stamp and is never touched. The same guards as for an expired claim apply: no recovery record and no publication started. An owner that is alive, however slow, or on another host or container keeps its full lease. The idle scan runs on the idle probe's reserved connection, so an idle pool still drains.
+- **Convergence harness** (`test/sync-convergence.serial.test.ts`, `bun run test:convergence`, quarantined): kills the resident serve and a sync client at seeded fault points behind a transaction-mode PgBouncer and checks that a plain sync converges. Named checks cover delegation after a client kill and a stall bound of 70 s (consumer liveness window plus one renewal plus 30 s). See `scripts/persistence/README.md`.
+
## [0.60.218.0] - 2026-10-14
**Fencing legacy facts no longer leaks, loops or blocks.** When a legacy fact is adopted into a fence row that an earlier, interrupted run left behind, the row is now rebuilt from the stored fact, so the fact's own kind, dates, confidence, visibility and speaker attribution are kept. Before, a leftover row with a different visibility made the adoption refuse every time, and one with the same visibility overwrote the fact's metadata. A managed adoption that gbrain refused as a planning defect is no longer resubmitted every cycle, so the writer stops collecting one identical failed request per page per cycle. And one fact that can't be fenced now holds up only its own page: the phantom-redirect pass runs for the rest of the source.
diff --git a/docs/architecture/key-files/persistence-stalls.md b/docs/architecture/key-files/persistence-stalls.md
index 8a29de5faf..dac066f0ec 100644
--- a/docs/architecture/key-files/persistence-stalls.md
+++ b/docs/architecture/key-files/persistence-stalls.md
@@ -19,15 +19,15 @@ owner (`owner_wedged_here`), movement surfaces (`data_moving`, doctor
`host_identity_mismatch` check; its codes are registered in
`src/core/error-registry.ts` and pinned by `test/error-registry-6317-contract.test.ts`.
-- `src/core/persistence/claim-phase.ts` — #6176 / #6278: the phase and step a running write request's claim is in. `startClaimPhase`/`enterClaimPhase` keep a per-claim `ClaimPhaseClock` in the consumer (single and group routes); `claimPhaseStamp` is the jsonb every claim, renewal and group dispatch mark stores in `persistence_requests.claim_phase` (v217): phase `preparing` or `publishing`, claim start, phase start, the execution token (so a later claim never reads an earlier claim's ages), the `step` in flight and when it began, `waiting_on` and the owning process (`owner`: command kind, pid, gbrain build). Preparers (`sync-prepare.ts`, `page-prepare.ts`, `prepared-maintenance.ts`, link resolution) call `enterClaimStep(clock, step, signal, waitingOn)` at each await boundary: it names the step, records what the await waits on (`git`, `fs`, `db`, `pool`, else `unknown`: set only where observed, never inferred) and throws the preparation's abort reason, so cancellation reaches a preparer between its queries even though the queries take no signal. `claimStateOf` reads a row back from the current claim's stamp only: `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, `step`, `step_age_ms`, `waiting_on`, `owner`, `resumes_on_its_own` and a `why`. `claimStall` is the `preparation_overdue` verdict (`claim.stall`) for a preparing claim past its budget. `EXPIRED_PREPARING_CHARGE_SQL` is the one rule an expired-claim reclaim charges a preparation attempt by: only a claim stamped `preparing` under the token being reclaimed. `persistence.max_claim_ms` (default 600000, 60000 to 86400000; `validateMaxClaimConfigValue` is `config set`'s `invalid_params` refusal) is doctor `persistence_write_stall`'s threshold. Consumer and group-publish store the stamp on every renewal, so writer status (`diagnostics.ts`, `claim` on each running blocker, never the token) and doctor name a stuck phase and step without an extra statement per write. Tests: `test/persistence-write-stall.test.ts`, `test/persistence-claim-step.test.ts`.
+- `src/core/persistence/claim-phase.ts` — #6176 / #6278: the phase and step a running write request's claim is in. `startClaimPhase`/`enterClaimPhase` keep a per-claim `ClaimPhaseClock` in the consumer (single and group routes); `claimPhaseStamp` is the jsonb every claim, renewal and group dispatch mark stores in `persistence_requests.claim_phase` (v217): phase `preparing` or `publishing`, claim start, phase start, the execution token (so a later claim never reads an earlier claim's ages), the `step` in flight and when it began, `waiting_on` and the owning process (`owner`: command kind, pid, gbrain build; #6650 boot id, start). Preparers (`sync-prepare.ts`, `page-prepare.ts`, `prepared-maintenance.ts`, link resolution) call `enterClaimStep(clock, step, signal, waitingOn)` at each await boundary: it names the step, records what the await waits on (`git`, `fs`, `db`, `pool`, else `unknown`: set only where observed, never inferred) and throws the preparation's abort reason, so cancellation reaches a preparer between its queries even though the queries take no signal. `claimStateOf` reads a row back from the current claim's stamp only: `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, `step`, `step_age_ms`, `waiting_on`, `owner`, `resumes_on_its_own` and a `why`. `claimStall` is the `preparation_overdue` verdict (`claim.stall`) for a preparing claim past its budget. `EXPIRED_PREPARING_CHARGE_SQL` is the one rule an expired-claim reclaim charges a preparation attempt by: only a claim stamped `preparing` under the token being reclaimed. `persistence.max_claim_ms` (default 600000, 60000 to 86400000; `validateMaxClaimConfigValue` is `config set`'s `invalid_params` refusal) is doctor `persistence_write_stall`'s threshold. Consumer and group-publish store the stamp on every renewal, so writer status (`diagnostics.ts`, `claim` on each running blocker, never the token) and doctor name a stuck phase and step without an extra statement per write. Tests: `test/persistence-write-stall.test.ts`, `test/persistence-claim-step.test.ts`.
- `src/core/persistence/preparation-budget.ts` + `src/commands/config/preparation-keys.ts` — #6278: how long a claimed write may prepare and how many cut-offs it survives. `preparationKind` sorts a request into `foreground` (`remember`, and `put_page`/`edit_page` with no internal intent: the consumer's 30 s `preparationMs`), `sync` (`managed_sync_*` kinds: `persistence.sync_preparation_ms`, default 120000) or `maintenance` (every other kind: `persistence.maintenance_preparation_ms`, default 120000). `persistence.preparation_ceiling_ms` (default 600000, 60000 to 3600000, floored at the larger budget plus 30 s) is the hard ceiling for a preparation that ignores cancellation and `persistence.max_preparation_attempts` (default 2, 1 to 10) the cut-offs before a request finishes `preparation_stalled`; a missing or out-of-range value keeps its default (`resolvePreparationPolicy`). The four keys ride the write-switch snapshot (`switches.ts`, one statement, 5 s TTL) together with the `preparation_deadlines` kill switch, so a claim never reads config on its own. `startPreparation` runs a preparer under its budget and the budget wins the race even when the preparer ignores its signal (the signal aborts with `{ code: 'preparation_deadline' }`; a result that lands after the budget on the clock still reads as a deadline; the late result is the caller's to drop); `racePreparation` is its outcome-only form for the sync's out-of-consumer preparations (`sync-waivers.ts`). `validatePreparationConfigValue` is `config set`'s structured refusal (each key's range, and the ceiling rule across the sibling keys; usage error exit 2, nothing written), wired in by `refuseInvalidPreparationValue`. `persistence.max_claim_ms` keeps its doctor meaning. Tests: `test/persistence-preparation-budget.test.ts`.
- `src/core/persistence/bounded-reads.ts` — #6278 (plan item 1.4): a preparation read that can wait on a relation lock ends at the budget on the server. Phase 0 (`docs/eval/managed-sync-stall-repro.md`) showed that through a transaction-mode pooler gbrain's `statement_timeout` startup parameter is dropped, so a preparation read outside the publication transaction had no server-side bound; an `ACCESS EXCLUSIVE` lock on `pages` held elsewhere pinned the member's origin check and its connection until the lock lifted, and with the budget alone the released member's statement kept running as a zombie that blocked its root until the ceiling. `boundedReads(engine, clock)` is the engine view every preparer reads through (`prepareManagedSyncMutation` and its helpers, `preparePageMutation`, `prepareFactFenceAdoption`, the sync's out-of-consumer preparations): each unmemoized raw statement runs with `executeRaw`'s `timeoutMs` set to the clock's remaining budget (`ClaimPhaseClock.deadlineAt`, set by `startClaimPhase(now, signal, budgetMs)`) and the clock's signal, which ends only the wait for a free connection. On Postgres `timeoutMs` runs the statement on a reserved connection as `BEGIN; SET LOCAL statement_timeout; <statement>; COMMIT` in one pipelined round trip, so the bound holds through the pooler and `SET LOCAL` ends with it; inside a transaction and on PGLite the option is ignored. A statement the server ends (57014, or a 55P03 raised by a shorter session `lock_timeout`) surfaces as the member's own `preparation_deadline` (`PreparationDeadlineError`, or the signal's reason once it aborted), which `preparationAbortReason` classifies as the deadline: the consumer and the group route handle it as the deadline even inside the budget (charged release, `preparation_stalled` at the limit, the group cut like the timer), never as a `storage_error` receipt or an uncharged release. The memo rule holds: `preparationReads` answers a bounded read once with the member's bound and signal dropped. Engine helpers that bypass `executeRaw` (`readPageSnapshot`, the import pipeline) stay under the consumer's race and the ceiling. Tests: `test/persistence-bounded-reads.test.ts`, `test/e2e/persistence-preparation-lock-wait-postgres.test.ts` (a real lock held in another session), the server-ended cases in `test/persistence-consumer-scheduling.test.ts` and `test/e2e/persistence-group-deadline-postgres.test.ts`. GBRA-75 wave 9: `withBoundedReadSession` gives a waiver screen (`unchangedSyncImport`) one reserved ordinary-pool connection (a long-hold permit; none left, or PGLite, runs the screen as before) on which its bounded reads share one transaction: `BEGIN; SET LOCAL statement_timeout` once, `COMMIT` when the screen settles. The bound stays per statement on the server: it is set again in the read's pipeline once the bound in force differs from the read's own by more than `BOUNDED_SESSION_SLACK_MS` (25 ms). A waiver run (`waiveRun` in `sync-run.ts`) opens one session for all its screens, and a screen inside it joins it. Session reads are named prepared statements (`ReservedConnection.executeRaw` `prepare`, ANDed with the connection option as `runUnsafe` does). A failed read rolls back and the reads it aborted (25P02) run again in a new transaction; a read after the screen settled takes the per-read path. Test: `test/persistence-bounded-read-session.test.ts` (real lock wait and no remaining statement on Postgres).
- `src/core/persistence/owner-refusal.ts` — #6278: the `owner_unavailable` reasons matrix. `checkOwner(binding, incarnation, hostId)` names the first failing condition in a fixed order (`binding_missing`, `incarnation_changed`, `host_mismatch`, `transfer_in_progress` for a `draining` worktree, `clone_in_progress` for `recovering`, `local_path_missing`, `coordination_path_missing`) or returns the usable `ActiveOwnerBinding`; `ownerRefusal` gives each reason its message, `why`, actor, fix (always the read-only `gbrain sources writer status --source <id> --json`, with the same verify; `actor: provider` so the two in-progress reasons render `next: wait` with a 30 s delay, `host_admin` for the rest) and `retryable` (`host_mismatch` false at the site, carried by `OperationError.retryable`); `ownerUnavailableError` is the thrown form. `host_mismatch` prints both host ids' first 8 characters and, when `remote` is false, the `host.json` path this process read; nothing here claims or transfers ownership. Used by `maintenancePreflight`, `loadFenceSource` and `managedRepairRoot`; the registry's `owner_unavailable.reasons` and the `FENCE_REASONS` owner entries carry the same vocabulary. Tests: `test/owner-refusal.test.ts` (matrix, every preflight condition on a claimed worktree, the HTTP envelope without a local path), `test/fence-repair-reasons.test.ts`.
- `src/core/persistence/repair-busy.ts` — #6278: the busy set a repair must not write while a managed sync runs. `loadRepairBusySet(engine, sourceId, incarnation)` returns the paths and slugs named by queued, running and recovering requests and terminal rows with an open recovery (both rename endpoints included) plus, for every unfinished `managed-sync` cursor of the incarnation, the entries of its frozen `managed-sync-manifest` from the cursor's index on (a path with a `sync-hold` record is left out: the sync retries a held file only when its bytes change); it never throws and fails closed (`unknown` set, so `repairBusy` answers true for everything) when a query fails or a cursor's manifest is missing. `repairBusyMessage` is the hold text, `repairBusyError` the `sync_in_progress` refusal (`reason` `candidate_in_flight` or `busy_set_unreadable`) `submitManagedFileRepair` raises at admission. Tests: `test/repair-busy.test.ts`, `test/repair-fences.test.ts`, `test/repair-fences-during-catchup.test.ts` (Postgres: `test/e2e/repair-fences-during-catchup-postgres.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. 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). 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/persistence-consumer-scheduling.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/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 lapsed over 60 s in the same CTE, and a failed write is logged once and never stops the consumer. `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. Live is 30 s, lapsed 60 s. 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 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/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.
diff --git a/scripts/persistence/README.md b/scripts/persistence/README.md
index f8ac0ab486..953176bdfc 100644
--- a/scripts/persistence/README.md
+++ b/scripts/persistence/README.md
@@ -559,8 +559,8 @@ class; elapsed times and the longest stall each sync printed are
`[convergence]` lines.
It skips unless `GBRAIN_TEST_CONVERGENCE=1`, no CI lane sets that, and a run
-takes about half an hour at 50 ms. Run it against the E2E Postgres plus a
-PgBouncer in front of it:
+takes about 18 minutes at 50 ms (under 2 at 0 ms). Run it against the E2E
+Postgres plus a PgBouncer in front of it:
```bash
docker network create gbtest
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 35359a9b8e..556e862024 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -550,6 +550,9 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }
{ since: '0.60.218.0', text: 'Fencing a legacy fact into a fence row a partial earlier run left behind now rebuilds that row from the stored fact: the published row carries the fact\'s own visibility, kind, validity, confidence and speaker attribution instead of the leftover cell\'s, a leftover private row is never reused for a world fact (the world fact gets its own row), and a newly fenced fact keeps its `attributed_to`. Before, a leftover row with a different visibility made the adoption refuse every time, a leftover row with the same visibility overwrote the fact\'s kind, dates and confidence, and every adoption cleared the fact\'s speaker attribution.' },
{ since: '0.60.218.0', text: 'A managed fact-fence adoption refused as a planning defect (`fence_unrenderable`) is no longer resubmitted every cycle: for a day after the refusal the page is reported as unadoptable (`prior_refusal`), then it gets one more try, or right away once the adoption planner changes. The writer stops collecting one identical failed request per page per cycle.' },
{ since: '0.60.218.0', text: 'The `extract_facts` phantom-redirect pass no longer waits for the whole source to have no unfenced legacy fact rows: it holds only the top-level pages that own such rows or are the provenance page of an ontology observation (`phantoms_held_legacy_rows` in the cycle report), and redirects the rest.' },
+ // #6650 L0 (convergence harness fixes). `since` is a placeholder equal to the branch's VERSION until the merge-slot stamp.
+ { since: '0.60.218.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.218.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.' },
];
/** 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 bccbb7c59e..79158c4b84 100644
--- a/src/core/persistence/claim-phase.ts
+++ b/src/core/persistence/claim-phase.ts
@@ -40,7 +40,7 @@
*/
import type { BrainEngine } from '../engine.ts';
import { VERSION } from '../../version.ts';
-import { consumerIdentity, sameProcess } from './consumer-heartbeat.ts';
+import { consumerIdentity, consumerProvablyDead, sameProcess } from './consumer-heartbeat.ts';
export type ClaimPhaseName = 'preparing' | 'publishing';
/** #6405: `publication` is the publish phase's own wait (a stamp in `publishing` no longer reads `unknown`); #6288 `publication_deadline` is a publish past `persistence.publication_ceiling_ms`. */
@@ -75,7 +75,7 @@ export interface ClaimPhaseClock {
* The process that holds a claim, as the stamp records it. #6317: `nonce` (random per process) and `pid_ns` (the pid
* namespace where readable) tell a reused pid or another container's pid from this process; an older owner stamps neither.
*/
-export interface ClaimOwner { kind: string; pid: number; version: string; nonce?: string; pid_ns?: string | null }
+export interface ClaimOwner { kind: string; pid: number; version: string; nonce?: string; pid_ns?: string | null; boot_id?: string | null; start?: string | null }
/** #6317: the step / waiting_on / last_sql triple of a claim, as stamped and as read back. */
export interface ClaimLastSql { label: string; age_ms: number | null }
@@ -137,13 +137,25 @@ export function claimOwnerKind(): string {
/** The owning process for the stamp: the gbrain command this process runs (`cli` when none is recognisable), its pid, nonce, pid namespace and build. */
export function claimOwner(): ClaimOwner {
if (ownerOverride) return ownerOverride;
- const { pid, nonce, pid_ns } = consumerIdentity();
- return { kind: claimOwnerKind(), pid, version: VERSION, nonce, pid_ns };
+ const { pid, nonce, pid_ns, boot_id, start } = consumerIdentity();
+ return { kind: claimOwnerKind(), pid, version: VERSION, nonce, pid_ns, boot_id, start };
}
/** Whether a stamped owner is this process: the pid and, when the stamp carries one, the nonce (#6317: `owner_pid === process.pid` alone is not enough). */
export function claimOwnerIsThisProcess(owner: Pick<ClaimOwner, 'pid' | 'nonce'> | null | undefined): boolean {
return sameProcess(owner);
}
+/**
+ * #6650: whether the claim stamped `raw` (a `claim_phase` value) was held by a process this one can prove dead
+ * (`consumerProvablyDead`: same boot and pid namespace, its pid gone or reused). A stamp without the markers, from
+ * an older owner, another host or container, is never provably dead.
+ */
+export function claimOwnerProvablyDead(raw: unknown): boolean {
+ const stamp = (typeof raw === 'string' ? safeJson(raw) : raw) as { owner?: Record<string, unknown> } | null;
+ const owner = stamp?.owner;
+ if (!owner || typeof owner.pid !== 'number') return false;
+ const text = (key: string) => typeof owner[key] === 'string' ? owner[key] as string : null;
+ return consumerProvablyDead({ pid: owner.pid, nonce: text('nonce'), pid_ns: text('pid_ns'), boot_id: text('boot_id'), start: text('start') });
+}
/** Test seam. */
export function setClaimOwnerForTest(owner: ClaimOwner | undefined): void { ownerOverride = owner; }
diff --git a/src/core/persistence/consumer-election.ts b/src/core/persistence/consumer-election.ts
index 17d92c8efa..3d77b64d9e 100644
--- a/src/core/persistence/consumer-election.ts
+++ b/src/core/persistence/consumer-election.ts
@@ -43,7 +43,7 @@ import type { BrainEngine } from '../engine.ts';
import type { GBrainConfig } from '../config.ts';
import { LANE_BUSY, type ConsumerStatus, type PersistenceConsumer, type PersistenceConsumerLike } from './consumer.ts';
import {
- CONSUMER_LAPSED_MS, CONSUMER_LIVE_MS, consumerIdentity, consumerWedged, listHostConsumers, RESIDENT_CONSUMER_KINDS, startConsumerHeartbeat,
+ CONSUMER_LAPSED_MS, CONSUMER_LIVE_MS, consumerIdentity, consumerRowProvablyDead, consumerWedged, listHostConsumers, RESIDENT_CONSUMER_KINDS, startConsumerHeartbeat,
type ConsumerHeartbeat, type ConsumerPool, type ConsumerProcessIdentity, type ListedConsumer,
} from './consumer-heartbeat.ts';
import { DEFAULT_PREPARATION_POLICY } from './preparation-budget.ts';
@@ -73,12 +73,13 @@ export interface ElectedOwner { kind: string; pid: number; nonce: string; pid_ns
/**
* The owner to defer to among `rows`, or null: a resident-kind row that is not this process, in mode `full` or `promoted`,
* not wedged and live (renewed within `CONSUMER_LIVE_MS`); the current owner is kept while it is merely stale (under
- * `CONSUMER_LAPSED_MS`), so one slow renewal does not promote every waiter on the host.
+ * `CONSUMER_LAPSED_MS`), so one slow renewal does not promote every waiter on the host. #6650: a row whose process this
+ * one can prove dead (`consumerRowProvablyDead`) is never elected or kept, however recently it renewed.
*/
export function electOwner(rows: readonly ListedConsumer[], current: Pick<ListedConsumer, 'pid' | 'nonce'> | null, ceilingMs: number,
self: ConsumerProcessIdentity = consumerIdentity()): ListedConsumer | null {
const eligible = rows.filter(row => !(row.pid === self.pid && row.nonce === self.nonce) && RESIDENT_CONSUMER_KINDS.includes(row.kind)
- && (row.mode === 'full' || row.mode === 'promoted') && !consumerWedged(row, ceilingMs));
+ && (row.mode === 'full' || row.mode === 'promoted') && !consumerWedged(row, ceilingMs) && !consumerRowProvablyDead(row, self));
const kept = current ? eligible.find(row => row.pid === current.pid && row.nonce === current.nonce && row.renewed_age_ms < CONSUMER_LAPSED_MS) : undefined;
if (kept) return kept;
return eligible.find(row => row.renewed_age_ms < CONSUMER_LIVE_MS) ?? null;
diff --git a/src/core/persistence/consumer-heartbeat.ts b/src/core/persistence/consumer-heartbeat.ts
index e0801248ed..41f8dcb95f 100644
--- a/src/core/persistence/consumer-heartbeat.ts
+++ b/src/core/persistence/consumer-heartbeat.ts
@@ -30,6 +30,7 @@
import { randomBytes } from 'node:crypto';
import { readlinkSync } from 'node:fs';
import type { BrainEngine } from '../engine.ts';
+import { isProcessAlive, processStartTime, readBootId } from '../pglite-lock.ts';
import { VERSION } from '../../version.ts';
import { localHostIdentity } from './identity.ts';
import type { SqlEngine } from './model.ts';
@@ -48,8 +49,13 @@ export const CONSUMER_RENEWAL_MS = 10_000;
export const CONSUMER_DEADLINE_MS = 5_000;
export type ConsumerRowMode = 'probing' | 'full' | 'waiter_only' | 'promoted';
-/** Process identity: `{ pid, nonce, pid_ns }`; `kind` names the gbrain command. */
-export interface ConsumerProcessIdentity { pid: number; nonce: string; pid_ns: string | null }
+/**
+ * Process identity: `{ pid, nonce, pid_ns }`; `kind` names the gbrain command. #6650: `boot_id` (the kernel's
+ * boot id) and `start` (the process's kernel start time, `/proc/<pid>/stat` field 22) let another process on the
+ * same machine prove this one is dead; null where /proc is unreadable, and `start` is null where /proc does not number
+ * processes as this pid namespace does.
+ */
+export interface ConsumerProcessIdentity { pid: number; nonce: string; pid_ns: string | null; boot_id?: string | null; start?: string | null }
/** The pool numbers a heartbeat row carries; `inflight_oldest_ms` and `completed` (#6383) are absent from rows an older owner wrote. */
export interface ConsumerPool { checked_out: number; max: number; waiters: number; inflight_oldest_ms?: number; completed?: number }
export interface ConsumerRow {
@@ -68,6 +74,9 @@ export interface ConsumerRow {
persistence_home: string;
minted_under: Record<string, unknown> | null;
version: string;
+ /** #6650 (migration v243): the owner's boot id and process start time; null on rows an older consumer wrote. */
+ boot_id?: string | null;
+ process_start?: string | null;
}
/** A row as `listHostConsumers` returns it: the row plus its liveness, read on the database clock. */
export interface ListedConsumer extends ConsumerRow {
@@ -86,7 +95,11 @@ export function consumerIdentity(): ConsumerProcessIdentity {
if (identity) return identity;
let pidNs: string | null = null;
try { pidNs = readlinkSync('/proc/self/ns/pid'); } catch { pidNs = null; }
- identity = { pid: process.pid, nonce: randomBytes(8).toString('hex'), pid_ns: pidNs };
+ // #6650: a start time is recorded only when /proc numbers processes as this pid namespace does (a nested namespace
+ // that inherited its parent's procfs would read another process's stat), so a stamp never carries a wrong one.
+ let aligned = false;
+ try { aligned = readlinkSync('/proc/self') === String(process.pid); } catch { aligned = false; }
+ identity = { pid: process.pid, nonce: randomBytes(8).toString('hex'), pid_ns: pidNs, boot_id: readBootId(), start: aligned ? processStartTime(process.pid) : null };
return identity;
}
/** Test seam: a fresh identity, so one test process can play several consumers. */
@@ -95,6 +108,26 @@ export function resetConsumerIdentityForTest(next?: Partial<ConsumerProcessIdent
identity = { ...consumerIdentity(), ...next };
return identity;
}
+/**
+ * #6650: whether `owner` (a claim stamp's or a heartbeat row's identity) is provably a dead process: it ran under
+ * this machine's boot and pid namespace, it recorded its start time, it is not this process, and its pid is now
+ * either gone or held by a process that started at another time (a reused pid). Anything this process cannot
+ * check from here (another host or container, an older owner without the markers, a /proc this process cannot
+ * read or that numbers another pid namespace's processes) is not provably dead, so the caller keeps its time-based
+ * rule for it.
+ */
+export function consumerProvablyDead(owner: { pid: number; nonce?: string | null; pid_ns?: string | null; boot_id?: string | null; start?: string | null } | null | undefined,
+ self: ConsumerProcessIdentity = consumerIdentity()): boolean {
+ if (!owner || !owner.boot_id || !owner.pid_ns || !owner.start || !self.boot_id || !self.pid_ns || !self.start) return false;
+ if (owner.boot_id !== self.boot_id || owner.pid_ns !== self.pid_ns || sameProcess(owner, self)) return false;
+ if (!isProcessAlive(owner.pid)) return true;
+ const start = processStartTime(owner.pid);
+ return start !== null && start !== owner.start;
+}
+/** #6650: `consumerProvablyDead` for a heartbeat row, whose start time is stored as `process_start`. */
+export function consumerRowProvablyDead(row: Pick<ConsumerRow, 'pid' | 'nonce' | 'pid_ns' | 'boot_id' | 'process_start'>, self: ConsumerProcessIdentity = consumerIdentity()): boolean {
+ return consumerProvablyDead({ pid: row.pid, nonce: row.nonce, pid_ns: row.pid_ns, boot_id: row.boot_id, start: row.process_start }, self);
+}
/** Whether `owner` (a claim stamp's or a row's identity) is this process: the pid and, when both sides carry one, the nonce. */
export function sameProcess(owner: { pid?: number | null; nonce?: string | null } | null | undefined, self: ConsumerProcessIdentity = consumerIdentity()): boolean {
if (!owner || owner.pid !== self.pid) return false;
@@ -102,7 +135,7 @@ export function sameProcess(owner: { pid?: number | null; nonce?: string | null
}
const ROW_COLUMNS = `host_id::text AS host_id,pid,nonce,pid_ns,kind,mode,started_at::text AS started_at,renewed_at::text AS renewed_at,restart_required,root_barrier_age_ms,pool,
- host_json_path,persistence_home,minted_under,version,(EXTRACT(EPOCH FROM (now()-renewed_at))*1000)::bigint::text AS renewed_age_ms,
+ host_json_path,persistence_home,minted_under,version,boot_id,process_start,(EXTRACT(EPOCH FROM (now()-renewed_at))*1000)::bigint::text AS renewed_age_ms,
(EXTRACT(EPOCH FROM (now()-started_at))*1000)::bigint::text AS age_ms`;
type RawRow = Omit<ConsumerRow, 'pool' | 'minted_under'> & { pool: unknown; minted_under: unknown; renewed_age_ms: string; age_ms: string };
@@ -135,7 +168,12 @@ export function consumerWedged(row: Pick<ConsumerRow, 'restart_required' | 'root
/**
* The first live, full, resident-kind consumer of `hostId` that is not `self`
* and is not wedged (B1a), or null. Liveness is judged on the database clock
- * (renewed within `CONSUMER_LIVE_MS`), so two hosts' clocks never enter it.
+ * (renewed within `CONSUMER_LIVE_MS`), so two hosts' clocks never enter it;
+ * #6650: a row this process can prove dead (`consumerProvablyDead`: same boot
+ * and pid namespace, pid gone or reused) is skipped at once instead of reading
+ * live for the rest of its window, so a killed client's leftover row never
+ * outranks the serve started after it. The order stays oldest first, the
+ * order `consumer-election.ts` defers in.
* PGLite admits one process: always null there. A read the database cannot
* answer rejects; the caller decides whether that means "no owner".
*/
@@ -147,7 +185,8 @@ export async function probeLiveFullConsumer(engine: SqlEngine & Partial<Pick<Bra
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 });
const ceiling = opts.ceilingMs ?? 600_000;
- const live = rows.map(row => listed(row, self)).find(row => !consumerWedged(row, ceiling));
+ const live = rows.map(row => listed(row, self))
+ .find(row => !consumerWedged(row, ceiling) && !consumerRowProvablyDead(row, self));
return live ?? null;
}
@@ -176,8 +215,8 @@ export interface ConsumerHeartbeat {
type DirectEngine = SqlEngine & Partial<Pick<BrainEngine, 'kind' | 'executeRawDirect'>>;
const RENEW_SQL = `WITH purged AS (
DELETE FROM persistence_consumers WHERE host_id=$1::uuid AND renewed_at < now() - ($14::integer * interval '1 millisecond') AND NOT (pid=$2::integer AND nonce=$3))
- INSERT INTO persistence_consumers(host_id,pid,nonce,pid_ns,kind,mode,restart_required,root_barrier_age_ms,pool,host_json_path,persistence_home,minted_under,version)
- VALUES($1::uuid,$2::integer,$3,$4,$5,$6,$7::boolean,$8::integer,$9::text::jsonb,$10,$11,$12::text::jsonb,$13)
+ INSERT INTO persistence_consumers(host_id,pid,nonce,pid_ns,kind,mode,restart_required,root_barrier_age_ms,pool,host_json_path,persistence_home,minted_under,version,boot_id,process_start)
+ VALUES($1::uuid,$2::integer,$3,$4,$5,$6,$7::boolean,$8::integer,$9::text::jsonb,$10,$11,$12::text::jsonb,$13,$15,$16)
ON CONFLICT (host_id,pid,nonce) DO UPDATE SET renewed_at=now(),mode=EXCLUDED.mode,restart_required=EXCLUDED.restart_required,
root_barrier_age_ms=EXCLUDED.root_barrier_age_ms,pool=EXCLUDED.pool,version=EXCLUDED.version`;
@@ -219,7 +258,7 @@ export function startConsumerHeartbeat(engine: DirectEngine, hostId: string, opt
const mode = typeof opts.mode === 'function' ? opts.mode() : opts.mode;
await bounded(execute(RENEW_SQL, [hostId, self.pid, self.nonce, self.pid_ns, opts.kind, mode, status.restart_required, status.root_barrier_age_ms,
status.pool ? JSON.stringify(status.pool) : null, paths.host_json_path, paths.persistence_home,
- paths.minted_under ? JSON.stringify(paths.minted_under) : null, VERSION, CONSUMER_PURGE_MS], cancel.signal), cancel, deadlineMs);
+ paths.minted_under ? JSON.stringify(paths.minted_under) : null, VERSION, CONSUMER_PURGE_MS, self.boot_id ?? null, self.start ?? null], cancel.signal), cancel, deadlineMs);
streak = 0;
} catch (error) {
if (!stopped) report(error);
diff --git a/src/core/persistence/consumer.ts b/src/core/persistence/consumer.ts
index f191ae3e03..cc92d640ea 100644
--- a/src/core/persistence/consumer.ts
+++ b/src/core/persistence/consumer.ts
@@ -6,7 +6,7 @@ import { localHostId } from './identity.ts';
import { executeClaimedGroup, PAGE_BATCH_GROUP_MAX, publishSingleWrite, singleWrite } from './group-publish.ts';
import { preparationConfigView } from './config-snapshot.ts';
import { CLAIM_LOST, DEFAULT_CLAIM_LEASE_TIMING, endLostLease, holdClaimForPublication, startClaimLease, type ClaimLeaseTiming } from './claim-lease.ts';
-import { claimPhaseStamp, claimStateOf, claimTripleText, EXPIRED_PREPARING_CHARGE_SQL, enterClaimPhase, startClaimPhase, type ClaimPhaseClock, type WaitingOn } from './claim-phase.ts';
+import { claimOwnerProvablyDead, claimPhaseStamp, claimStateOf, claimTripleText, EXPIRED_PREPARING_CHARGE_SQL, enterClaimPhase, startClaimPhase, type ClaimPhaseClock, type WaitingOn } from './claim-phase.ts';
import { DEFAULT_PREPARATION_POLICY, preparationBudgetMs, preparationKind, startPreparation, type PreparationPolicy } from './preparation-budget.ts';
import { isTerminal, type WriteRequest } from './model.ts';
import { ownerExceptionLogText } from './publication-failure.ts';
@@ -50,6 +50,8 @@ export const DEFAULT_ZOMBIE_CAP = 1;
/** An effects drain running this long names itself on stderr (serve), then again at this cadence. */
const DRAIN_NOTICE_AFTER_MS = 5_000;
const DRAIN_NOTICE_EVERY_MS = 10_000;
+/** #6650: how often a consumer looks for claims held by an owner it can prove dead. */
+export const DEAD_OWNER_SCAN_MS = 5_000;
const yieldToEventLoop = () => new Promise<void>(resolve => setImmediate(resolve));
/** When this process started; on PGLite no claim written earlier can belong to a live owner. */
const PROCESS_STARTED_AT = new Date(performance.timeOrigin);
@@ -187,6 +189,9 @@ export class PersistenceConsumer implements PersistenceConsumerLike {
/** Requests this consumer claimed ahead of a queued sync row of their root. */
private passedSync = new Set<string>();
private rootRetryAfter = new Map<string, number>();
+ private deadOwnerScanAt = 0;
+ /** #6650: the dead owners (`deadOwnerClaims`) an idle tick found, handed to that tick's expired-claim reclaim. */
+ private deadOwnersSeen: string[] | null = null;
private projectionWorker: Promise<unknown> | undefined;
private effectsWorker: Promise<void> | undefined;
private draining: { since: number; settled: number; ran: number; noticedAt: number } | undefined;
@@ -476,7 +481,9 @@ export class PersistenceConsumer implements PersistenceConsumerLike {
return;
}
if (this.stopping) return;
- if (!work) {
+ // #6650: the idle probe sees only lapsed claims; a live-leased claim of a dead owner is looked for here, on its own cadence.
+ if (!work) this.deadOwnersSeen = await this.phase('dead_owner_claims', signal => this.deadOwnerClaims(signal, true));
+ if (!work && !this.deadOwnersSeen?.length) {
this.nextDelayMs = this.backoff();
if (!this.maintenanceWorker && Date.now() >= this.nextMaintenance) {
this.nextMaintenance = Date.now() + 300_000;
@@ -559,15 +566,21 @@ export class PersistenceConsumer implements PersistenceConsumerLike {
this.report(error);
}
}
+ // #6650: a claim whose stamped owner this process can prove dead is reclaimed now, not when its lease
+ // (up to `publicationLeaseMs`) runs out; the statement below takes it with the same guards as an expired one.
+ const deadOwners = this.deadOwnersSeen?.length ? this.deadOwnersSeen : await this.phase('dead_owner_claims', signal => this.deadOwnerClaims(signal));
+ this.deadOwnersSeen = null;
// #6278: a claim that expired while its owner was preparing (the kill case) counts one preparation attempt.
await this.phase('expired_claims', signal => this.statements.executeRaw(`WITH expired AS (
SELECT r.id FROM persistence_requests r WHERE r.state='running' AND r.recovery IS NULL
- AND r.publication_started=false AND r.claim_expires_at<now() AND ${PERSISTENCE_PROTOCOL_PREDICATE}
+ AND r.publication_started=false AND ${PERSISTENCE_PROTOCOL_PREDICATE}
+ AND (r.claim_expires_at<now() OR r.claim_phase->>'token'=r.execution_token::text
+ AND concat_ws(':',r.claim_phase->'owner'->>'pid',r.claim_phase->'owner'->>'nonce',r.claim_phase->'owner'->>'start')=ANY($3::text[]))
AND (r.worktree_id IS NULL OR EXISTS (SELECT 1 FROM persistence_worktrees w WHERE w.id=r.worktree_id AND w.owner_host_id=$1::uuid))
ORDER BY r.sequence LIMIT 100 FOR UPDATE OF r SKIP LOCKED)
UPDATE persistence_requests r SET state='queued',execution_token=NULL,claim_expires_at=NULL,
preparation_attempts=r.preparation_attempts+CASE WHEN $2::boolean THEN ${EXPIRED_PREPARING_CHARGE_SQL('r')} ELSE 0 END
- FROM expired WHERE r.id=expired.id`, [this.hostId, this.policy.deadlines], { signal }));
+ FROM expired WHERE r.id=expired.id`, [this.hostId, this.policy.deadlines, deadOwners], { signal }));
}
if (publicationConcurrency(this.engine) === 0) {
await this.phase('capacity', signal => this.statements.executeRaw(`UPDATE persistence_requests SET blocked_reason='writer_pool_capacity'
@@ -603,6 +616,30 @@ export class PersistenceConsumer implements PersistenceConsumerLike {
}
await this.claimLanes();
}
+ /**
+ * #6650: the owners (`pid:nonce:start`) of unexpired running claims on this host's roots that this process can prove dead
+ * (`claimOwnerProvablyDead`: same boot and pid namespace, pid gone or reused). The reclaim takes a claim only while
+ * its stamp of the current token still names such an owner, so a claim re-taken since this scan (a new token and
+ * stamp) is never touched. Only claims the expired-claim reclaim may take at all qualify: no recovery record and no
+ * publication started, so the dead owner's publication transaction either committed (the row is no longer
+ * `running`) or rolled back with its connection. A live owner, however slow, and an owner on another host or
+ * container keep their full lease. Postgres only, at most every `DEAD_OWNER_SCAN_MS`: PGLite admits one process
+ * and releases abandoned claims at start. An `idle` scan runs where the idle probe does (its reserved lane), so an
+ * idle pool still drains.
+ */
+ private async deadOwnerClaims(signal?: AbortSignal, idle = false): Promise<string[]> {
+ if (this.engine.kind !== 'postgres' || Date.now() - this.deadOwnerScanAt < DEAD_OWNER_SCAN_MS) return [];
+ this.deadOwnerScanAt = Date.now();
+ const lane = idle && !this.laneInUse && consumerConnectionRoute(this.engine).lane !== 'direct' ? await this.acquireIdleLane(signal) : undefined;
+ const owners = await this.probeQuery<{ key: string; owner: string }>(lane, `SELECT DISTINCT
+ concat_ws(':',r.claim_phase->'owner'->>'pid',r.claim_phase->'owner'->>'nonce',r.claim_phase->'owner'->>'start') AS key,(r.claim_phase->'owner')::text AS owner
+ FROM persistence_requests r
+ WHERE r.state='running' AND r.recovery IS NULL AND r.publication_started=false AND r.claim_expires_at>=now()
+ AND r.claim_phase->>'token'=r.execution_token::text AND r.claim_phase->'owner'->>'boot_id' IS NOT NULL
+ AND (r.worktree_id IS NULL OR EXISTS (SELECT 1 FROM persistence_worktrees w WHERE w.id=r.worktree_id AND w.owner_host_id=$1::uuid))
+ LIMIT 100`, [this.hostId], signal);
+ return owners.filter(row => claimOwnerProvablyDead({ owner: JSON.parse(row.owner) })).map(row => row.key);
+ }
/** #5984 lanes: claims the next group heads of every open lane run in this process, up to its effective lane count. */
private async claimLanes(): Promise<void> {
for (const { worktreeId, run, capacity } of laneRoots()) {
diff --git a/src/core/persistence/schema.ts b/src/core/persistence/schema.ts
index 2cf1dca62f..0aacb5d148 100644
--- a/src/core/persistence/schema.ts
+++ b/src/core/persistence/schema.ts
@@ -90,6 +90,8 @@ export const PERSISTENCE_CONSUMERS_TABLE_SQL = `CREATE TABLE IF NOT EXISTS persi
persistence_home text NOT NULL,
minted_under jsonb,
version text NOT NULL,
+ boot_id text,
+ process_start text,
PRIMARY KEY(host_id,pid,nonce)
)`;
/** Indexes the Postgres blob omits because a migration builds them CONCURRENTLY. */
diff --git a/src/core/pglite-schema.generated.ts b/src/core/pglite-schema.generated.ts
index a97d414068..4a0fe95b8d 100644
--- a/src/core/pglite-schema.generated.ts
+++ b/src/core/pglite-schema.generated.ts
@@ -1367,6 +1367,8 @@ CREATE TABLE IF NOT EXISTS persistence_consumers (
persistence_home text NOT NULL,
minted_under jsonb,
version text NOT NULL,
+ boot_id text,
+ process_start text,
PRIMARY KEY(host_id,pid,nonce)
);
diff --git a/src/core/schema-embedded.generated.ts b/src/core/schema-embedded.generated.ts
index cdbb16a1fd..03157f03b1 100644
--- a/src/core/schema-embedded.generated.ts
+++ b/src/core/schema-embedded.generated.ts
@@ -2075,6 +2075,8 @@ CREATE TABLE IF NOT EXISTS persistence_consumers (
persistence_home text NOT NULL,
minted_under jsonb,
version text NOT NULL,
+ boot_id text,
+ process_start text,
PRIMARY KEY(host_id,pid,nonce)
);
diff --git a/src/core/schema-migrations/latest.generated.ts b/src/core/schema-migrations/latest.generated.ts
index 115c3b3e46..a73fbd1589 100644
--- a/src/core/schema-migrations/latest.generated.ts
+++ b/src/core/schema-migrations/latest.generated.ts
@@ -4,4 +4,4 @@
// The highest schema migration version (migrate.ts LATEST_VERSION), importable without
// loading the migrations themselves.
-export const LATEST_SCHEMA_VERSION = 242;
+export const LATEST_SCHEMA_VERSION = 243;
diff --git a/src/core/schema-migrations/registry.generated.ts b/src/core/schema-migrations/registry.generated.ts
index 5d10baa3ff..129cf41721 100644
--- a/src/core/schema-migrations/registry.generated.ts
+++ b/src/core/schema-migrations/registry.generated.ts
@@ -243,6 +243,7 @@ import { v239 } from './v239-extract-rollup-halt-reasons.ts';
import { v240 } from './v240-pages-name-lookup-indexes.ts';
import { v241 } from './v241-persistence-request-slug-intent-index.ts';
import { v242 } from './v242-extract-atoms-partial-input.ts';
+import { v243 } from './v243-persistence-consumer-process-start.ts';
// Array order is historical (see HISTORICAL_ARRAY_ORDER in the generator); the
// runner sorts by version before applying.
@@ -484,4 +485,5 @@ export const MIGRATIONS: Migration[] = [
v240,
v241,
v242,
+ v243,
];
diff --git a/src/core/schema-migrations/v243-persistence-consumer-process-start.ts b/src/core/schema-migrations/v243-persistence-consumer-process-start.ts
new file mode 100644
index 0000000000..489da90174
--- /dev/null
+++ b/src/core/schema-migrations/v243-persistence-consumer-process-start.ts
@@ -0,0 +1,21 @@
+import type { Migration } from './types.ts';
+
+// Applied by src/core/migrate.ts on the next initSchema(); the fresh-install
+// copy of the table (persistence/schema.ts PERSISTENCE_CONSUMERS_TABLE_SQL,
+// generated into src/schema.sql) carries the same columns.
+export const v243: Migration = {
+ version: 243,
+ name: 'persistence_consumer_process_start',
+ // #6650: a consumer heartbeat row records its process's kernel boot id and
+ // start time (`/proc/<pid>/stat` field 22), so a process on the same host can
+ // prove the row's owner is dead (its pid is gone, or now belongs to a process
+ // that started later) instead of trusting the row for the 30 s liveness
+ // window (consumer-heartbeat.ts `consumerProvablyDead`). NULL on rows an
+ // older consumer writes; those keep the time-only rule. DDL only: two
+ // metadata-only ADD COLUMNs, nothing to backfill.
+ idempotent: true,
+ sql: `
+ ALTER TABLE persistence_consumers ADD COLUMN IF NOT EXISTS boot_id text;
+ ALTER TABLE persistence_consumers ADD COLUMN IF NOT EXISTS process_start text;
+ `,
+};
diff --git a/src/schema.sql b/src/schema.sql
index daa15be985..6afd1c311e 100644
--- a/src/schema.sql
+++ b/src/schema.sql
@@ -2071,6 +2071,8 @@ CREATE TABLE IF NOT EXISTS persistence_consumers (
persistence_home text NOT NULL,
minted_under jsonb,
version text NOT NULL,
+ boot_id text,
+ process_start text,
PRIMARY KEY(host_id,pid,nonce)
);
diff --git a/test/consumer-provably-dead-6650.test.ts b/test/consumer-provably-dead-6650.test.ts
new file mode 100644
index 0000000000..0e201a236a
--- /dev/null
+++ b/test/consumer-provably-dead-6650.test.ts
@@ -0,0 +1,124 @@
+/**
+ * #6650: a heartbeat row or claim stamp names a process this one can prove
+ * dead (same boot and pid namespace, pid gone or reused), so a killed sync
+ * client's row never outranks the serve started after it and its claims are
+ * reclaimable at once. Anything not provable from here (another boot or pid
+ * namespace, an owner without the markers, a live process with its recorded
+ * start time) keeps the time-based rule.
+ *
+ * The probe runs against a stub engine that answers the probe's query with the
+ * rows the database would hold; the SQL time filter is not what is under test.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { spawn, type ChildProcess } from 'node:child_process';
+import { consumerIdentity, consumerProvablyDead, probeLiveFullConsumer } from '../src/core/persistence/consumer-heartbeat.ts';
+import { claimOwnerProvablyDead } from '../src/core/persistence/claim-phase.ts';
+import { processStartTime, readBootId } from '../src/core/pglite-lock.ts';
+import { deadPid } from './helpers/dead-pid.ts';
+
+const linux = process.platform === 'linux' && readBootId() !== null;
+let live: ChildProcess;
+let liveStart: string;
+
+beforeAll(async () => {
+ if (!linux) return;
+ live = spawn('sleep', ['60'], { stdio: 'ignore' });
+ await new Promise(resolve => live.once('spawn', resolve));
+ liveStart = processStartTime(live.pid!)!;
+});
+afterAll(() => { live?.kill('SIGKILL'); });
+
+const self = () => consumerIdentity();
+const owner = (pid: number, over: Record<string, string | null> = {}) =>
+ ({ pid, nonce: `n-${pid}`, pid_ns: self().pid_ns, boot_id: self().boot_id ?? null, start: '1', ...over });
+
+function row(pid: number, kind: string, startedAt: string, over: Record<string, string | null> = {}) {
+ const o = owner(pid, over);
+ return { host_id: '00000000-0000-0000-0000-000000000001', pid, nonce: o.nonce, pid_ns: o.pid_ns, kind, mode: 'full', started_at: startedAt,
+ renewed_at: startedAt, restart_required: false, root_barrier_age_ms: null, pool: null, host_json_path: '/h', persistence_home: '/p',
+ minted_under: null, version: '0.0.0', boot_id: o.boot_id, process_start: o.start, renewed_age_ms: '1000', age_ms: '5000' };
+}
+const stub = (rows: unknown[]) => ({ kind: 'postgres' as const, executeRaw: async () => rows }) as never;
+
+describe.skipIf(!linux)('consumerProvablyDead', () => {
+ test('a reaped pid under this boot and pid namespace is dead', () => {
+ expect(consumerProvablyDead(owner(deadPid()))).toBe(true);
+ });
+ test('a live pid whose start time differs is a reused pid, so the recorded owner is dead', () => {
+ expect(consumerProvablyDead(owner(live.pid!, { start: '1' }))).toBe(true);
+ });
+ test('a live pid with its recorded start time is alive', () => {
+ expect(consumerProvablyDead(owner(live.pid!, { start: liveStart }))).toBe(false);
+ });
+ test('another boot, another pid namespace, or an owner without markers is never provably dead', () => {
+ const pid = deadPid();
+ expect(consumerProvablyDead(owner(pid, { boot_id: '00000000-0000-0000-0000-000000000000' }))).toBe(false);
+ expect(consumerProvablyDead(owner(pid, { pid_ns: 'pid:[1]' }))).toBe(false);
+ expect(consumerProvablyDead(owner(pid, { start: null }))).toBe(false);
+ expect(consumerProvablyDead({ pid, nonce: 'older-owner', pid_ns: self().pid_ns })).toBe(false);
+ });
+ test('a checker whose /proc numbers another pid namespace (no start time of its own) proves nothing', () => {
+ expect(consumerProvablyDead(owner(deadPid()), { ...self(), start: null })).toBe(false);
+ });
+ test('this process is never dead to itself', () => {
+ const me = self();
+ expect(consumerProvablyDead({ ...me, start: '1' })).toBe(false);
+ });
+});
+
+describe.skipIf(!linux)('probeLiveFullConsumer skips a row whose owner is provably dead (#6650 bug 1)', () => {
+ test("a killed sync client's fresh row does not outrank the serve started after it", async () => {
+ const found = await probeLiveFullConsumer(stub([
+ row(deadPid(), 'sync', '2026-10-13 10:00:00+00'),
+ row(live.pid!, 'serve', '2026-10-13 10:00:05+00', { start: liveStart }),
+ ]), '00000000-0000-0000-0000-000000000001');
+ expect({ kind: found?.kind, pid: found?.pid }).toEqual({ kind: 'serve', pid: live.pid });
+ });
+ test('only a dead row reads as no owner', async () => {
+ expect(await probeLiveFullConsumer(stub([row(deadPid(), 'serve', '2026-10-13 10:00:00+00')]), '00000000-0000-0000-0000-000000000001')).toBeNull();
+ });
+ test('a row from another boot keeps the time-only rule', async () => {
+ const pid = deadPid();
+ const found = await probeLiveFullConsumer(stub([row(pid, 'serve', '2026-10-13 10:00:00+00', { boot_id: '00000000-0000-0000-0000-000000000000' })]),
+ '00000000-0000-0000-0000-000000000001');
+ expect(found?.pid).toBe(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', () => {
+ const o = owner(deadPid());
+ expect(claimOwnerProvablyDead(stamp(o))).toBe(true);
+ expect(claimOwnerProvablyDead(JSON.parse(stamp(o)))).toBe(true);
+ });
+ test('a live owner, a foreign boot, an older stamp without markers, and no stamp are kept', () => {
+ expect(claimOwnerProvablyDead(stamp(owner(live.pid!, { start: liveStart })))).toBe(false);
+ expect(claimOwnerProvablyDead(stamp(owner(deadPid(), { boot_id: '00000000-0000-0000-0000-000000000000' })))).toBe(false);
+ expect(claimOwnerProvablyDead(stamp({ pid: deadPid(), nonce: 'n', pid_ns: self().pid_ns }))).toBe(false);
+ expect(claimOwnerProvablyDead(null)).toBe(false);
+ });
+ test('the stamp this process writes carries the markers', async () => {
+ const { claimOwner } = await import('../src/core/persistence/claim-phase.ts');
+ expect(claimOwner()).toMatchObject({ pid: process.pid, boot_id: readBootId(), start: processStartTime(process.pid) });
+ });
+});
+
+describe.skipIf(!linux)('electOwner never defers to a provably dead owner (#6650 bug 1)', () => {
+ const listed = (pid: number, over: Record<string, string | null> = {}) => {
+ const r = row(pid, 'serve', '2026-10-13 10:00:00+00', over);
+ return { ...r, pool: null, minted_under: null, renewed_age_ms: 1000, age_ms: 5000, liveness: 'live', self: false } as never;
+ };
+ test('a dead current owner is neither kept nor elected; the live one is', async () => {
+ const { electOwner } = await import('../src/core/persistence/consumer-election.ts');
+ const dead = deadPid();
+ const elected = electOwner([listed(dead), listed(live.pid!, { start: liveStart })], { pid: dead, nonce: `n-${dead}` }, 600_000);
+ expect((elected as { pid: number } | null)?.pid).toBe(live.pid);
+ });
+ test('a row from another boot is still kept on time alone', async () => {
+ const { electOwner } = await import('../src/core/persistence/consumer-election.ts');
+ const pid = deadPid();
+ const elected = electOwner([listed(pid, { boot_id: '00000000-0000-0000-0000-000000000000' })], { pid, nonce: `n-${pid}` }, 600_000);
+ expect((elected as { pid: number } | null)?.pid).toBe(pid);
+ });
+});
diff --git a/test/e2e/persistence-dead-owner-reclaim-6650.test.ts b/test/e2e/persistence-dead-owner-reclaim-6650.test.ts
new file mode 100644
index 0000000000..69e20d9e84
--- /dev/null
+++ b/test/e2e/persistence-dead-owner-reclaim-6650.test.ts
@@ -0,0 +1,191 @@
+/**
+ * #6650 defect 2 on Postgres: a running claim whose stamped owner this host
+ * can prove dead (same boot and pid namespace, its pid gone or reused) is
+ * reclaimed on the consumer's next scan instead of after its lease, which for
+ * a publishing group is `publicationLeaseMs` (365 s by default). A live owner,
+ * however long its lease, and an owner from another boot keep the claim.
+ * Bug 1's heartbeat probe is pinned on real rows here too.
+ *
+ * The claim is staged the way an owner leaves it when it is SIGKILLed inside
+ * its publication transaction (that transaction rolls back with its
+ * connection): `running`, its token, a lease minutes out, a `publishing` stamp
+ * of that token, no recovery record and no `publication_started`.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { spawn, type ChildProcess } from 'node:child_process';
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+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 { 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';
+import { assertSafeE2eDatabaseUrl, hasDatabase } from './helpers.ts';
+import { deadPid } from '../helpers/dead-pid.ts';
+import { withEnv } from '../helpers/with-env.ts';
+import { waitFor } from '../helpers/wait-for.ts';
+
+const DATABASE_URL = process.env.DATABASE_URL ?? '';
+const linux = process.platform === 'linux' && readBootId() !== null;
+const FOREIGN_BOOT = '00000000-0000-0000-0000-000000000000';
+let live: ChildProcess;
+let liveStart: string;
+
+beforeAll(async () => {
+ if (!linux) return;
+ live = spawn('sleep', ['120'], { stdio: 'ignore' });
+ await new Promise(resolve => live.once('spawn', resolve));
+ liveStart = processStartTime(live.pid!)!;
+});
+afterAll(() => { live?.kill('SIGKILL'); });
+
+async function withBrain(run: (ctx: { engine: PostgresEngine; config: HarnessConfig; sources: FixtureSource[] }) => Promise<void>) {
+ assertSafeE2eDatabaseUrl(DATABASE_URL);
+ const name = `gbrain_test_dead_owner_${randomUUID().replaceAll('-', '')}`;
+ const admin = postgres(DATABASE_URL, { max: 1, prepare: false, onnotice: () => {} });
+ await admin.unsafe(`CREATE DATABASE ${name}`);
+ const url = new URL(DATABASE_URL); url.pathname = `/${name}`;
+ const root = mkdtempSync(join(tmpdir(), 'gbrain-dead-owner-'));
+ const config: HarnessConfig = { kind: 'postgres', root, dataDir: join(root, 'unused'), hostId: randomUUID(),
+ seed: 6650, schedules: 0, operations: 0, sourceIds: ['dead-a', 'dead-b', 'dead-c'], principalIds: [randomUUID(), randomUUID(), randomUUID(), randomUUID()] };
+ const engine = new PostgresEngine();
+ try {
+ await withEnv({ GBRAIN_HOME: root, GBRAIN_PERSISTENCE_FIXTURE_HOME: root }, async () => {
+ await engine.connect({ database_url: url.toString(), poolSize: 6 });
+ await engine.initSchema();
+ selectFixtureHost(config.hostId);
+ await initializeFixtures(engine, config);
+ await run({ engine, config, sources: await fixtures(engine, config) });
+ });
+ } finally {
+ await engine.disconnect();
+ try { await admin.unsafe(`DROP DATABASE IF EXISTS ${name} WITH (FORCE)`); } finally { await admin.end(); }
+ rmSync(root, { recursive: true, force: true });
+ }
+}
+
+/** Stages `id` as claimed by `owner`, publishing, with a lease `leaseS` seconds out; returns the claim's token. */
+async function stageClaim(engine: PostgresEngine, id: string, owner: Record<string, unknown>, leaseS = 360): Promise<string> {
+ const token = randomUUID();
+ const now = new Date().toISOString();
+ const stamp = { phase: 'publishing', claimed_at: now, since: now, token, step: null, step_since: now, waiting_on: 'publication', last_sql: null,
+ owner: { kind: 'sync', version: '0.0.0', nonce: `n-${String(owner.pid)}`, pid_ns: consumerIdentity().pid_ns, boot_id: readBootId(), ...owner } };
+ await engine.executeRaw(`UPDATE persistence_requests SET state='running', execution_token=$2::uuid, claim_expires_at=now()+($3::integer*interval '1 second'),
+ claim_phase=$4::text::jsonb, updated_at=now() WHERE id=$1::uuid`, [id, token, leaseS, JSON.stringify(stamp)]);
+ return token;
+}
+
+function consumerFor(engine: PostgresEngine, config: HarnessConfig, sources: FixtureSource[]) {
+ return new PersistenceConsumer(engine, { engine: 'postgres' }, async (_engine, row) => prepared(row, sources),
+ { hostId: config.hostId, concurrency: 3, pollMs: 60_000, phaseMs: 5_000, onError: () => {} });
+}
+
+describe.skipIf(!hasDatabase() || !linux)('a claim held by a provably dead owner is reclaimed at once (#6650)', () => {
+ test('dead and reused-pid owners: reclaimed and committed long before the lease; a live owner keeps its claim', () => withBrain(async ({ engine, config, sources }) => {
+ const dead = await admitWrite(engine, admission(config, sources[0]!, 'dead-a/page', 'dead owner body'));
+ const reused = await admitWrite(engine, admission(config, sources[1]!, 'dead-b/page', 'reused pid body'));
+ const kept = await admitWrite(engine, admission(config, sources[2]!, 'dead-c/page', 'live owner body'));
+ await stageClaim(engine, dead.id, { pid: deadPid(), start: '1' });
+ await stageClaim(engine, reused.id, { pid: live.pid!, start: '1' });
+ const liveToken = await stageClaim(engine, kept.id, { pid: live.pid!, start: liveStart });
+ const consumer = consumerFor(engine, config, sources);
+ try {
+ await consumer.tick();
+ await waitFor(async () => (await getWriteRequestById(engine, dead.id))?.state === 'committed'
+ && (await getWriteRequestById(engine, reused.id))?.state === 'committed', { timeoutMs: 20_000, label: 'the dead and reused-pid owners\' claims commit' });
+ await consumer.tick();
+ const held = await getWriteRequestById(engine, kept.id);
+ expect({ state: held?.state, token: held?.execution_token }).toEqual({ state: 'running', token: liveToken });
+ } finally { await consumer.stop(); }
+ }), 90_000);
+
+ test('an already idle consumer finds a dead owner\'s live-leased claim on its own (no wake, no other work)', () => withBrain(async ({ engine, config, sources }) => {
+ const consumer = consumerFor(engine, config, sources);
+ try {
+ await consumer.tick();
+ const orphan = await admitWrite(engine, admission(config, sources[0]!, 'dead-a/idle', 'idle consumer body'));
+ await stageClaim(engine, orphan.id, { pid: deadPid(), start: '1' });
+ await Bun.sleep(DEAD_OWNER_SCAN_MS);
+ await consumer.tick();
+ await waitFor(async () => (await getWriteRequestById(engine, orphan.id))?.state === 'committed', { timeoutMs: 20_000, label: 'the idle consumer reclaims and commits it' });
+ } finally { await consumer.stop(); }
+ }), 90_000);
+
+ test('a dead owner behind more than a scan page of live claims is still found', () => withBrain(async ({ engine, config, sources }) => {
+ const liveOwner = { pid: live.pid!, start: liveStart };
+ for (let i = 0; i < 110; i++) await stageClaim(engine, (await admitWrite(engine, admission(config, sources[1]!, `dead-b/live-${i}`, `live ${i}`, i % 4))).id, liveOwner);
+ const orphan = await admitWrite(engine, admission(config, sources[0]!, 'dead-a/behind', 'behind the live prefix'));
+ await stageClaim(engine, orphan.id, { pid: deadPid(), start: '1' });
+ const consumer = consumerFor(engine, config, sources);
+ try {
+ await consumer.tick();
+ await waitFor(async () => (await getWriteRequestById(engine, orphan.id))?.state === 'committed', { timeoutMs: 20_000, label: 'the claim behind the live prefix commits' });
+ } finally { await consumer.stop(); }
+ }), 90_000);
+
+ test('a claim re-taken by a live owner between the scan and the reclaim keeps its new token and attempt count', () => withBrain(async ({ engine, config, sources }) => {
+ const req = await admitWrite(engine, admission(config, sources[0]!, 'dead-a/retaken', 'retaken body'));
+ await stageClaim(engine, req.id, { pid: deadPid(), start: '1' });
+ const consumer = consumerFor(engine, config, sources);
+ const seam = consumer as unknown as { deadOwnerClaims: (signal?: AbortSignal) => Promise<string[]> };
+ const scan = seam.deadOwnerClaims.bind(consumer);
+ let liveToken = '';
+ seam.deadOwnerClaims = async signal => {
+ const found = await scan(signal);
+ liveToken = await stageClaim(engine, req.id, { pid: live.pid!, start: liveStart });
+ return found;
+ };
+ try {
+ await consumer.tick();
+ const held = await getWriteRequestById(engine, req.id);
+ expect({ state: held?.state, token: held?.execution_token, attempts: held?.preparation_attempts }).toEqual({ state: 'running', token: liveToken, attempts: 0 });
+ } finally { await consumer.stop(); }
+ }), 90_000);
+
+ test('a dead owner\'s claim whose publication started is left to its lease and recovery, never reclaimed early', () => withBrain(async ({ engine, config, sources }) => {
+ const started = await admitWrite(engine, admission(config, sources[0]!, 'dead-a/started', 'publication started body'));
+ const token = await stageClaim(engine, started.id, { pid: deadPid(), start: '1' });
+ await engine.executeRaw('UPDATE persistence_requests SET publication_started=true WHERE id=$1::uuid', [started.id]);
+ const consumer = consumerFor(engine, config, sources);
+ try {
+ await consumer.tick();
+ await Bun.sleep(1_000);
+ const held = await getWriteRequestById(engine, started.id);
+ expect({ state: held?.state, token: held?.execution_token }).toEqual({ state: 'running', 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'));
+ const foreignToken = await stageClaim(engine, foreign.id, { pid: deadPid(), start: '1', boot_id: FOREIGN_BOOT });
+ const olderToken = await stageClaim(engine, older.id, { pid: deadPid(), boot_id: undefined, start: undefined });
+ const consumer = consumerFor(engine, config, sources);
+ try {
+ await consumer.tick();
+ await Bun.sleep(1_000);
+ expect([(await getWriteRequestById(engine, foreign.id))?.execution_token, (await getWriteRequestById(engine, older.id))?.execution_token])
+ .toEqual([foreignToken, olderToken]);
+ } finally { await consumer.stop(); }
+ }), 90_000);
+
+ test('the heartbeat probe skips a dead same-boot row and keeps a live one and a foreign-boot one (bug 1)', () => withBrain(async ({ engine }) => {
+ const host = randomUUID();
+ const self = consumerIdentity();
+ const seed = (pid: number, kind: string, ageS: number, boot: string | null, start: string | null) => engine.executeRaw(
+ `INSERT INTO persistence_consumers(host_id,pid,nonce,pid_ns,kind,mode,started_at,renewed_at,host_json_path,persistence_home,version,boot_id,process_start)
+ VALUES($1::uuid,$2,$3,$4,$5,'full',now()-($6::integer*interval '1 second'),now(),'/h','/p','0.0.0',$7,$8)`,
+ [host, pid, `n-${pid}-${kind}`, self.pid_ns, kind, ageS, boot, start]);
+ await seed(deadPid(), 'sync', 60, readBootId(), '1');
+ await seed(live.pid!, 'serve', 5, readBootId(), liveStart);
+ expect((await probeLiveFullConsumer(engine, host))?.kind).toBe('serve');
+ await engine.executeRaw('DELETE FROM persistence_consumers WHERE host_id=$1::uuid', [host]);
+ const foreignPid = deadPid();
+ await seed(foreignPid, 'serve', 60, FOREIGN_BOOT, '1');
+ expect((await probeLiveFullConsumer(engine, host))?.pid).toBe(foreignPid);
+ }), 90_000);
+});
diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-default.json b/test/fixtures/goldens/catalog/pglite-engine-init-default.json
index 206ea38690..f94b5a044f 100644
--- a/test/fixtures/goldens/catalog/pglite-engine-init-default.json
+++ b/test/fixtures/goldens/catalog/pglite-engine-init-default.json
@@ -2689,7 +2689,9 @@
"12 host_json_path text/text NOT NULL",
"13 persistence_home text/text NOT NULL",
"14 minted_under jsonb/jsonb NULL",
- "15 version text/text NOT NULL"
+ "15 version text/text NOT NULL",
+ "16 boot_id text/text NULL",
+ "17 process_start text/text 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 83b5c7544c..545b92cf9a 100644
--- a/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json
+++ b/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json
@@ -2689,7 +2689,9 @@
"12 host_json_path text/text NOT NULL",
"13 persistence_home text/text NOT NULL",
"14 minted_under jsonb/jsonb NULL",
- "15 version text/text NOT NULL"
+ "15 version text/text NOT NULL",
+ "16 boot_id text/text NULL",
+ "17 process_start text/text 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 b0cc907cf9..5a06338969 100644
--- a/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json
+++ b/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json
@@ -2685,7 +2685,9 @@
"12 host_json_path text/text NOT NULL",
"13 persistence_home text/text NOT NULL",
"14 minted_under jsonb/jsonb NULL",
- "15 version text/text NOT NULL"
+ "15 version text/text NOT NULL",
+ "16 boot_id text/text NULL",
+ "17 process_start text/text NULL"
],
"flags": "relkind=r rls=false force_rls=false"
},
diff --git a/test/fixtures/goldens/catalog/pglite-schema-blob-default.json b/test/fixtures/goldens/catalog/pglite-schema-blob-default.json
index c7ea240aa5..f492a7603e 100644
--- a/test/fixtures/goldens/catalog/pglite-schema-blob-default.json
+++ b/test/fixtures/goldens/catalog/pglite-schema-blob-default.json
@@ -1955,7 +1955,9 @@
"12 host_json_path text/text NOT NULL",
"13 persistence_home text/text NOT NULL",
"14 minted_under jsonb/jsonb NULL",
- "15 version text/text NOT NULL"
+ "15 version text/text NOT NULL",
+ "16 boot_id text/text NULL",
+ "17 process_start text/text NULL"
],
"flags": "relkind=r rls=false force_rls=false"
},
diff --git a/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.json b/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.json
index 4d86b21e99..384e9c888f 100644
--- a/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.json
+++ b/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.json
@@ -1955,7 +1955,9 @@
"12 host_json_path text/text NOT NULL",
"13 persistence_home text/text NOT NULL",
"14 minted_under jsonb/jsonb NULL",
- "15 version text/text NOT NULL"
+ "15 version text/text NOT NULL",
+ "16 boot_id text/text NULL",
+ "17 process_start text/text NULL"
],
"flags": "relkind=r rls=false force_rls=false"
},
diff --git a/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.json b/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.json
index ceb41a12f0..9e912dbff9 100644
--- a/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.json
+++ b/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.json
@@ -1954,7 +1954,9 @@
"12 host_json_path text/text NOT NULL",
"13 persistence_home text/text NOT NULL",
"14 minted_under jsonb/jsonb NULL",
- "15 version text/text NOT NULL"
+ "15 version text/text NOT NULL",
+ "16 boot_id text/text NULL",
+ "17 process_start text/text NULL"
],
"flags": "relkind=r rls=false force_rls=false"
},
diff --git a/test/fixtures/goldens/catalog/postgres-db-initschema.json b/test/fixtures/goldens/catalog/postgres-db-initschema.json
index 02e9e35d56..1ef7a9aedf 100644
--- a/test/fixtures/goldens/catalog/postgres-db-initschema.json
+++ b/test/fixtures/goldens/catalog/postgres-db-initschema.json
@@ -2024,7 +2024,9 @@
"12 host_json_path text/text NOT NULL",
"13 persistence_home text/text NOT NULL",
"14 minted_under jsonb/jsonb NULL",
- "15 version text/text NOT NULL"
+ "15 version text/text NOT NULL",
+ "16 boot_id text/text NULL",
+ "17 process_start text/text NULL"
],
"flags": "relkind=r rls=false force_rls=false"
},
diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-default.json b/test/fixtures/goldens/catalog/postgres-engine-init-default.json
index 547a9ac20e..14f901d232 100644
--- a/test/fixtures/goldens/catalog/postgres-engine-init-default.json
+++ b/test/fixtures/goldens/catalog/postgres-engine-init-default.json
@@ -2701,7 +2701,9 @@
"12 host_json_path text/text NOT NULL",
"13 persistence_home text/text NOT NULL",
"14 minted_under jsonb/jsonb NULL",
- "15 version text/text NOT NULL"
+ "15 version text/text NOT NULL",
+ "16 boot_id text/text NULL",
+ "17 process_start text/text NULL"
],
"flags": "relkind=r rls=true force_rls=false"
},
diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json b/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json
index 8c543fe2ba..94fc6a5348 100644
--- a/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json
+++ b/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json
@@ -2701,7 +2701,9 @@
"12 host_json_path text/text NOT NULL",
"13 persistence_home text/text NOT NULL",
"14 minted_under jsonb/jsonb NULL",
- "15 version text/text NOT NULL"
+ "15 version text/text NOT NULL",
+ "16 boot_id text/text NULL",
+ "17 process_start text/text NULL"
],
"flags": "relkind=r rls=true force_rls=false"
},
diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json b/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json
index 501a895dec..a9688cbe03 100644
--- a/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json
+++ b/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json
@@ -2697,7 +2697,9 @@
"12 host_json_path text/text NOT NULL",
"13 persistence_home text/text NOT NULL",
"14 minted_under jsonb/jsonb NULL",
- "15 version text/text NOT NULL"
+ "15 version text/text NOT NULL",
+ "16 boot_id text/text NULL",
+ "17 process_start text/text NULL"
],
"flags": "relkind=r rls=true force_rls=false"
},
diff --git a/test/fixtures/goldens/migrations/records.json b/test/fixtures/goldens/migrations/records.json
index 4b531812c4..ef3d235035 100644
--- a/test/fixtures/goldens/migrations/records.json
+++ b/test/fixtures/goldens/migrations/records.json
@@ -1,6 +1,6 @@
{
"golden": {
- "count": 237,
+ "count": 238,
"gaps": [
17,
18,
@@ -54,7 +54,7 @@
"sqlQueryForEngine": "71fb1ccec1b22cdc1662876dbd8c17ed81e9ab83485c6965cdf5caa4fc4a4ab5",
"verifyProjectionStatistics": "0d231b04ecfbc5a4109d6fca9567bf4e8c9e9db6c3fbbb35212e026579ed6f67"
},
- "latest": 242,
+ "latest": 243,
"records": [
{
"handler": {
@@ -2248,8 +2248,8 @@
"idempotent": true,
"name": "durable_concurrent_persistence",
"sql": {
- "length": 11749,
- "sha256": "66065b6bd5f2c11094ff00db6ebea8d19e45bf2e395ca3aac880edea9f20b0df"
+ "length": 11791,
+ "sha256": "34fa2dd7def982037e8c04ef6914fe16e0c87f8d73927d99e3dd13b221697d75"
},
"sqlFor": "absent",
"transaction": "absent",
@@ -3314,8 +3314,8 @@
"idempotent": true,
"name": "persistence_consumers",
"sql": {
- "length": 617,
- "sha256": "cd4f82da89b693d122d4591ebbbb692178f1d7b497349c2faa44fc165c1114d4"
+ "length": 659,
+ "sha256": "5213f749da68ef7437adfc85b947363357cec4959f153de5bbccbb6cd8826bf3"
},
"sqlFor": "absent",
"transaction": "absent",
@@ -3684,6 +3684,19 @@
"transaction": "absent",
"verify": "absent",
"version": 242
+ },
+ {
+ "handler": "absent",
+ "idempotent": true,
+ "name": "persistence_consumer_process_start",
+ "sql": {
+ "length": 163,
+ "sha256": "10a330a9e1287db4f47bf4f2a70456fa3fa62dbdca8dde2ff2b8f876333e6e6d"
+ },
+ "sqlFor": "absent",
+ "transaction": "absent",
+ "verify": "absent",
+ "version": 243
}
],
"versions": [
@@ -3923,7 +3936,8 @@
239,
240,
241,
- 242
+ 242,
+ 243
]
},
"normalizer": "migrations-record-v1"
diff --git a/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json b/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json
index 8723216ee8..57e79115c3 100644
--- a/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json
+++ b/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json
@@ -2689,7 +2689,9 @@
"12 host_json_path text/text NOT NULL",
"13 persistence_home text/text NOT NULL",
"14 minted_under jsonb/jsonb NULL",
- "15 version text/text NOT NULL"
+ "15 version text/text NOT NULL",
+ "16 boot_id text/text NULL",
+ "17 process_start text/text NULL"
],
"flags": "relkind=r rls=false force_rls=false"
},
diff --git a/test/persistence-claim-step.test.ts b/test/persistence-claim-step.test.ts
index 8f3619e710..4393576c1c 100644
--- a/test/persistence-claim-step.test.ts
+++ b/test/persistence-claim-step.test.ts
@@ -13,6 +13,7 @@
import { afterEach, describe, expect, test } from 'bun:test';
import { claimOwner, claimOwnerIsThisProcess, claimPhaseStamp, claimStall, claimStateOf, enterClaimPhase, enterClaimStep, setClaimOwnerForTest, startClaimPhase } from '../src/core/persistence/claim-phase.ts';
import { VERSION } from '../src/version.ts';
+import { processStartTime, readBootId } from '../src/core/pglite-lock.ts';
afterEach(() => setClaimOwnerForTest(undefined));
@@ -50,9 +51,10 @@ describe('claimPhaseStamp and claimStateOf', () => {
expect(JSON.parse(claimPhaseStamp(clock, 'tok-1'))).toEqual({ phase: 'preparing', claimed_at: '2026-10-08T03:00:00.000Z', since: '2026-10-08T03:00:00.000Z', token: 'tok-1',
step: 'origin_check', step_since: '2026-10-08T03:01:00.000Z', waiting_on: 'db', last_sql: null, owner: { kind: 'sync', pid: 4242, version: '0.60.200.0' } });
});
- test('the default owner is this process: the gbrain command (cli when none), pid, build and (#6317) its nonce and pid namespace', () => {
+ test('the default owner is this process: the gbrain command (cli when none), pid, build, (#6317) its nonce and pid namespace and (#6650) its boot id and start time', () => {
const owner = claimOwner();
- expect(owner).toEqual({ kind: expect.any(String), pid: process.pid, version: VERSION, nonce: expect.stringMatching(/^[0-9a-f]{16}$/), pid_ns: process.platform === 'linux' ? expect.stringMatching(/^pid:\[\d+\]$/) : null });
+ expect(owner).toEqual({ kind: expect.any(String), pid: process.pid, version: VERSION, nonce: expect.stringMatching(/^[0-9a-f]{16}$/), pid_ns: process.platform === 'linux' ? expect.stringMatching(/^pid:\[\d+\]$/) : null,
+ boot_id: readBootId(), start: processStartTime(process.pid) });
expect(claimOwner().nonce).toBe(owner.nonce);
expect(claimOwnerIsThisProcess(owner)).toBe(true);
expect(claimOwnerIsThisProcess({ pid: process.pid, nonce: 'another-process-reusing-the-pid' })).toBe(false);