Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Merge remote-tracking branch 'origin/capy/large-pages-hardening' into capy/lph-bc
garrytancbdb881ccd38
diff --cc docs/architecture/key-files/persistence-stalls.mdindex 85c983cf17,de1c383bbe..242766d0cd--- a/docs/architecture/key-files/persistence-stalls.md+++ b/docs/architecture/key-files/persistence-stalls.md@@@ -20,9 -20,9 +20,9 @@@ owner (`owner_wedged_here`), movement s`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; #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/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`). These keys and `persistence.max_transient_retries` (transient-retry.ts) 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/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`. `transfer_in_progress` is `wait` until the drain's `prepared_at` is `TRANSFER_STALE_MINUTES` (30) old, then `ask_user` naming the accept and the exact `transfer cancel` argv (a drain with no `prepared_at` keeps the wait).- `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, + the 5 s #6650 dead-owner scan, mirroring the claim, recovery, expired-claim, effect, projection (inline rows windowed by `projection-window.ts`) 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. A statement the database ended with 57014 (statement timeout or cancel: `coordinator.ts` `writeInterruption`) is charged too, in `finishUnpublishedFailure` and in `publishMutation`'s recovery route, and at the limit ends the request `failed` with `write_interrupted` instead of a `database_contention` release; contention with other transactions (55P03, 40001, 40P01), a dropped connection or a restarting database is never charged (`test/persistence-write-interrupted.test.ts`). 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 (PGLite, 1,000 pages: ~9.5 ms mean, ~18 ms p99 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 or waived entry, or #6712 a slug or page id shared with a member in flight or held, `dependencyKeys`) 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 pending entry (settled by fault class; later members stay in the window, #6712), 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). #6712: each member keeps its own fate (sync groups keep claim 64, width four, ordered release, `syncGroup`): a failed preparation settles before the rest publish as a group; a sync member its lane group's transaction refused settles alone, the rest requeue (`settleCulprit`); other failures roll back and members publish singly. 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. 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). A `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`.diff --cc src/core/behavior-change-notice.tsindex 7ebe4e7b0e,2abbfd439d..f06993eebe--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@@ -902,7 -902,13 +902,15 @@@ export const BEHAVIOR_CHANGES: Readonly{ since: '0.60.299.0', text: 'Upgrading builds the index `pages_segmented_body_bytes_idx` (migration v260) over pages stored in segments: on Postgres online (`CREATE INDEX CONCURRENTLY`), on PGLite as a plain build that holds writes until it ends. With it, the default `persistence.limits.worktree_recovery_bytes` also leaves room for the largest page already stored in segments, deleted pages included (while the index is not yet valid, a page at the engine ceiling, so no limit read scans `pages`): turning `pages.segmented_storage` off or lowering `pages.max_bytes` no longer makes a delete, restore or withdrawal mirror of such a page fail with `request_too_large` (a withdrawn row stayed in its file). A value you set is kept, and a request it cannot hold is refused with `request_too_large` naming both recovery budgets and the bytes it needed.' },{ since: '0.60.299.0', text: 'Doctor `segmented_storage` no longer tells you to upgrade this host when the only writes holding segmented storage off are this host\'s own from before its upgrade and the upgraded gbrain has since made the same kind of write (the same import or sync type, resident kind or managed principal), after the last of them: it reports the hold as information with the time it clears. Another host, an older `serve` or worker still running on this host, or an older write this build has not matched (a cron job or `npx` run on this host) keeps the warning and the `gbrain upgrade` fix.' },{ since: '0.60.299.0', text: 'Managed sync of a Markdown file over 24 MiB whose origin another page records (a page renamed with its file) now imports it into that page, as for a smaller file, instead of failing it `revision_conflict` ("A different page already owns this file identity") and stopping the source\'s sync at it.' },- { since: '0.60.299.0', text: '`gbrain repair stuck-recovery` now resolves a page recovery whose file is over 24 MiB, which used to be listed as refused (`recovery_large_file_unsupported`) with no exit while it stopped every write on its source\'s worktree. The preview lists it with both fingerprints and the state of the staged copy of the prior file, backs up both versions, and writes a summary instead of a full diff (both hashes and sizes, the first byte where they differ, and a window of at most 1 KiB); `--apply --expect <hash> --keep prior|disk --yes` resolves it as it does a small file. Every read, hash and copy of the large file is done in pieces of at most a segment. When the staged copy of the prior file is missing or damaged, `--keep prior` refuses with `recovery_prior_stage_unavailable`, whose fix is the `--keep disk` apply, which keeps a damaged copy in the backup directory and removes it from the checkout.' }, { since: 'TBD', text: 'A managed write the database interrupts under load is now retried with backoff instead of failing at the second interruption. A statement the database ends with a statement timeout or cancel (SQLSTATE 57014) and, new, a publication the owner cancels past `persistence.publication_ceiling_ms` (until now released and published again without limit, or on Postgres sometimes failed `storage_error` at once) count against their own budget, `persistence.max_transient_retries` (default 5, 0 to 20), instead of `persistence.max_preparation_attempts`: each one schedules the request\'s next claim after 1 s, 2 s, 4 s, 8 s, then 15 s (stored on the request, so nothing is held while it waits; `gbrain sources writer status` names the waiting head `transient_backoff`), and the interruption after the last retry ends it `failed` with `write_interrupted` as before. Its receipt names the interruptions (`attempts`), the retry limit (`limit`, `limit_key`), the cause (`statement_cancel` or `publication_ceiling`) and the SQLSTATE. Preparations cut off at their deadline still count against `persistence.max_preparation_attempts` alone, and lock timeouts, serialization failures, deadlocks and lost connections are still never counted. `persistence.preparation_deadlines false` turns this counting and the backoff off with the deadlines. Upgrading adds two columns to `persistence_requests` (migration v261, no rewrite of existing rows).' },+ { since: '0.60.299.0', text: '`gbrain repair stuck-recovery` now resolves a page recovery whose file is over 24 MiB, which used to be listed as refused (`recovery_large_file_unsupported`) with no exit while it stopped every write on its source\'s worktree. The preview lists it with both fingerprints and the state of the staged copy of the prior file, backs up both versions, and writes a summary instead of a full diff (both hashes and sizes, the first byte where they differ, and a window of at most 1 KiB); `--apply --expect <hash> --keep prior|disk --yes` resolves it as it does a small file. Every read, hash and copy of the large file is done in pieces of at most a segment. When the staged copy of the prior file is missing or damaged, `--keep prior` refuses with `recovery_prior_stage_unavailable`, whose fix is the `--keep disk` apply, which keeps a damaged copy in the backup directory and removes it from the checkout.' },+ { since: 'TBD', text: 'New `gbrain repair segmented-mirror [--source <id>]` for brains that ran a gbrain older than v0.60.299.0 with `pages.segmented_storage` on: on those versions a withdrawal (`forget`, `forget_fact`, `purge_fact`) of a row in a page stored in segments struck it in the database but left the page\'s canonical file holding it (the mirror skipped the page with `page_body_segmented`). Upgrading does not rewrite those files. Run the preview on the source\'s owner host: it lists each file-backed segmented page whose file still holds a withdrawn or purged row and otherwise matches the database, with the file\'s SHA-256 and size and those of the page\'s canonical render (`gbrain export`\'s bytes), and prints a hash; a file that also differs from the database for another reason is listed held (`file_database_drift`) and never rewritten. `--apply --expect <hash> --yes` rewrites each listed file to that render through the withdrawal mirror (one receipted write request per page, `operation: repair_segmented_mirror`) and its Git effect commits it; a file or page that changed since the preview refuses the apply with `preview_changed`. Doctor does not scan for these files (that needs every segmented file read), so run the preview once if this brain ever ran such a version.' },+ // LPH (d): recovery records of unknown versions, and no version 2 mirror record while an older writer is seen.+ { since: 'TBD', text: 'A publication or withdrawal-mirror recovery record of a version this gbrain does not know (one a newer gbrain wrote) is now refused with `recovery_version_unsupported` before anything reads it: the record, its staged files and the canonical file are left exactly as they are, the effect keeps retrying instead of parking, and `gbrain sources writer status` and a stalled sync name it as a blocker whose fix is `gbrain upgrade` on the owner host. Before, recovery could read a newer record as an older one: a withdrawal-mirror recovery published the bytes the record embedded, removed its staging file and cleared the record, and a request recovery tried to rewrite the record\'s staging (the database refused it with an untyped `unsupported_mutation_protocol`). v0.60.290.0 and older still read a version 2 withdrawal-mirror record as version 1 and fail every attempt with an untyped `effect_unavailable` while the record holds every write and effect on the worktree; they never delete the record or its staging file, and an upgraded owner finishes it.' },+ { since: 'TBD', text: 'While a gbrain older than the segmented writer floor (v0.60.290.0 included) that doctor `segmented_storage` still warns about wrote to the brain in the last 7 days (another host, an older `serve` or worker still running on this host, or an older write this build has not matched; doctor names the host), a withdrawal (`forget`, `forget_fact`, `purge_fact`) on a page stored in segments still commits, but its withdrawal mirror no longer writes a version 2 recovery record, which that older gbrain cannot read and would wedge the worktree on. The mirror refuses `segmented_mirror_writer_gate` (its fix names the hosts to upgrade), retries, and parks after five attempts like any failed mirror, so writes on the worktree are not held; the page\'s canonical file keeps the withdrawn row and the withdrawal\'s Git effect waits meanwhile. Once the older writer is upgraded and out of the 7-day window, the parked mirror runs again by itself (checked at most once a minute), rewrites the file and the Git effect commits it. `gbrain sources writer retry-effects` retries it at any time. A hold left only by this host\'s own writes from before it upgraded, which the upgraded gbrain has since superseded with the same kind of write (doctor reports it as information), still keeps new pages inline but does not hold the mirror: an upgraded single-host brain mirrors withdrawals at once.' },+ // Large-pages hardening (f).+ { since: 'TBD', text: 'A withdrawal (`forget`, `forget_fact`, `purge_fact`) of a claim in a facts fence that crosses a forced segment cut, when that one fence holds more than 16,384 rows (or more than 8 MiB of rows to check), is still refused `withdrawal_capacity` (the bound is unchanged), but the refusal now says why: it carries reason `split_fence_rows`, names the page, the fence\'s row count and the limit, and its fix asks you to split that fence into fences of at most 16,384 rows and write the page again. It used to say discovery "could not prove a bounded complete target set" and told you not to split the source.' },++ // Large-pages hardening (b, c).++ { since: 'TBD', text: 'A managed write the database interrupts under load is now retried with backoff instead of failing at the second interruption. A statement the database ends with a statement timeout or cancel (SQLSTATE 57014) and, new, a publication the owner cancels past `persistence.publication_ceiling_ms` (until now released and published again without limit, or on Postgres sometimes failed `storage_error` at once) count against their own budget, `persistence.max_transient_retries` (default 5, 0 to 20), instead of `persistence.max_preparation_attempts`: each one schedules the request\'s next claim after 1 s, 2 s, 4 s, 8 s, then 15 s (stored on the request, so nothing is held while it waits; `gbrain sources writer status` names the waiting head `transient_backoff`), and the interruption after the last retry ends it `failed` with `write_interrupted` as before. Its receipt names the interruptions (`attempts`), the retry limit (`limit`, `limit_key`), the cause (`statement_cancel` or `publication_ceiling`) and the SQLSTATE. Preparations cut off at their deadline still count against `persistence.max_preparation_attempts` alone, and lock timeouts, serialization failures, deadlocks and lost connections are still never counted. `persistence.preparation_deadlines false` turns this counting and the backoff off with the deadlines. Upgrading adds two columns to `persistence_requests` (migration v261, no rewrite of existing rows).' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --cc src/core/persistence/head-blocker.tsindex 681d2af64a,f7a1a37d7e..19c663e7a5--- a/src/core/persistence/head-blocker.ts+++ b/src/core/persistence/head-blocker.ts@@@ -18,15 -20,15 +20,16 @@@ import { claimStateOf } from './claim-pimport { isTerminal, type RequestState } from './model.ts';import { sha256 } from './digest.ts';import { claimableWriteSql, EARLIER_HEAD, foregroundPrioritySql, SYNC_KIND } from './journal.ts';+import { BACKOFF_ELAPSED } from './transient-retry.ts';+ import { recoveryUpgradeFix, recoveryVersionKnown, type RecoveryTable } from './recovery-version.ts';export type HeadBlockerPredicate = 'worktree_owner' | 'refresh_fence' | 'effect_recovery' | 'withdrawal_mirror' | 'request_recovery'- | 'zombie_publication' | 'lease' | 'root_hold';+ | 'zombie_publication' | 'lease' | 'root_hold' | 'transient_backoff';export interface HeadBlocker {predicate: HeadBlockerPredicate;- /** The refresh id for a fence, the request ids of blocking requests, the effect ids of blocking effects, or the worktree id. */+ /** The refresh id for a fence, the request ids of blocking requests (the head itself for `transient_backoff`), the effect ids of blocking effects, or the worktree id. */ids: string[];- /** The fence state, the blocking request's state, the worktree state (`other_host` when another host owns it), or why an effect recovery cannot finish. */+ /** The fence state, the blocking request's state, the worktree state (`other_host` when another host owns it), why an effect recovery cannot finish, or when a backoff ends (ISO time). */state: string | null;/** The process behind the blocker when one is known: a refresh process (`live` from its lock) or a claim's stamped owner. */owner: { kind: string | null; pid: number | null; live: boolean | null; restart_required: boolean } | null;@@@ -43,12 -45,14 +46,14 @@@ interface RowRef { request_id: string;publication_started: boolean; recovery: boolean; principal_kind: string; principal_id: string }interface ProbeRow { id: string; worktree_id: string | null; owner_host_id: string | null; worktree_state: string | null; claimable: boolean;fence: { id: string; state: string } | null; effect_recovery: EffectRecoveryRef[] | null; mirrors: string[] | null; request_recovery: RequestRecoveryRef[] | null;- earlier: RowRef[] | null; ahead: RowRef[] | null }+ request_id: string; backoff_until: string | Date | null; earlier: RowRef[] | null; ahead: RowRef[] | null }- interface EffectRecoveryRef { id: string; error_code: string | null; slug: string | null; path: string | null; before: string | null; after: string | null }+ interface EffectRecoveryRef { id: string; request_id: string | null; error_code: string | null; slug: string | null; path: string | null; before: string | null; after: string | null; version: unknown }interface RequestRecoveryRef { request_id: string; state: RequestState; blocked_reason: string | null; slug: string; version: string | null; path: string | null;- before: string | null; after: string | null }+ before: string | null; after: string | null; files: Array<{ path: string | null; before: string | null; after: string | null }> | null }const REQUEST_RECOVERY = (alias: string) => `jsonb_build_object('request_id',${alias}.request_id::text,'state',${alias}.state,'blocked_reason',${alias}.blocked_reason,- 'slug',${alias}.slug,'version',${alias}.recovery->>'version','path',${alias}.recovery->>'path','before',${alias}.recovery->>'beforeHash','after',${alias}.recovery->>'afterHash')`;+ 'slug',${alias}.slug,'version',${alias}.recovery->>'version','path',${alias}.recovery->>'path','before',${alias}.recovery->>'beforeHash','after',${alias}.recovery->>'afterHash',+ 'files',(SELECT jsonb_agg(jsonb_build_object('path',f->>'path','before',f->>'beforeHash','after',f->>'afterHash'))+ FROM jsonb_array_elements(CASE WHEN jsonb_typeof(${alias}.recovery->'files')='array' THEN ${alias}.recovery->'files' ELSE '[]'::jsonb END) f))`;/*** Whether a recovery's last attempt refused `unexpected_file_bytes` and its file still matches neither recorded hash (the checkdiff --cc test/postgres-unit-arms.txtindex 90b12b2f00,f3eecf5b62..8bf806f30f--- a/test/postgres-unit-arms.txt+++ b/test/postgres-unit-arms.txt@@@ -254,8 -266,17 +266,19 @@@ test/pathological/b5-export-unsafe-slugtest/pathological/b6-triage-verdict-surrogate.test.tstest/pathological/c-23-override-and-doctor-fixes.test.tstest/pathological/c-9-facts-absorb-dead.test.ts+ test/pathological/c1-effect-stuck-recovery.test.ts+ test/pathological/c2-url-clone-fences.test.ts+ test/pathological/c22-stuck-recovery-large-file.test.ts+ test/pathological/c4-bundle-stuck-recovery.test.ts+ test/pathological/c5-writer-transfer-cancel.test.ts+ test/pathological/c7-content-receipt-root.test.ts+ test/pathological/lp-a-segmented-mirror.test.ts+test/pathological/lp-b-transient-retry-budget.test.ts+test/pathological/lp-c-publication-ceiling-retry.test.ts+ test/pathological/lp-d-recovery-version.test.ts+ test/pathological/lp-d-segmented-mirror-gate.test.ts+ test/pathological/lp-f-split-fence-withdrawal-capacity.test.ts+ test/pathological/lp-g-file-digest-fence-bound.test.tstest/persistence-background-pause.test.tstest/persistence-bounded-read-session.test.tstest/persistence-capacity-forecast.test.ts