Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(persistence): refuse unknown recovery record versions; hold segmented mirrors while an older writer could claim their v2 record (LPH d)
garrytan6f3674c07ecc
diff --git a/docs/architecture/key-files/core-persistence-request-indexes.md b/docs/architecture/key-files/core-persistence-request-indexes.mdindex f28bd029be..20ee85ba11 100644--- a/docs/architecture/key-files/core-persistence-request-indexes.md+++ b/docs/architecture/key-files/core-persistence-request-indexes.md@@ -7,4 +7,5 @@ The online-built request-table indexes (the managed sync checkpoint pair, the pa- `src/core/persistence/checkpoint-validation.ts` — the managed sync checkpoint's incomplete-receipt validation (#5762): `INCOMPLETE_SYNC_RECEIPT_SQL` is three `LIMIT 1` probes (recovery; an open page receipt of the run; a non-committed page receipt with no committed sibling at its index) served by `persistence_requests_recovery`, `persistence_requests_sync_run_open` and `persistence_requests_sync_run_committed`, with the same result as the former single predicate. `findIncompleteSyncReceipt` returns the blocking receipt's request id and maps only this statement's 57014 statement timeout to the terminal, non-transient `checkpoint_validation_timeout`. `readRequestIndexStates` reads each index of `PERSISTENCE_REQUEST_ONLINE_INDEXES` (or the list passed) as valid, missing, INVALID or building (Postgres `pg_stat_progress_create_index`); `formatCheckpointTimeoutHint` / `checkpointTimeoutHint` is the one formatter for the three-state hint and the filled retry (`gbrain sync --source <id> --no-pull --retry-failed` plus the cursor-selecting options the checkpoint intent records in `syncOptions` and the saved processing flags), used by the sync summary and `get_write_request`. Tests: `test/persistence-sync-checkpoint-validation.test.ts`, `test/e2e/persistence-request-indexes-postgres.test.ts`.- `src/core/persistence/fault-points.ts` — named crash seams for the persistence gate. `faultPoint(point, detail)` is a no-op unless a gate worker installed a hook with `installFaultHook`; production never does. Seams: `publication:<boundary>` (the five `PublicationHooks.boundary` names, routed through `withFaultPoints` in `publishMutation`), `effect:<kind>:mid` for every `EffectKind` in `completeEffect` (after the side effect, before its completion is recorded; `EFFECT_FAULT_POINTS` is a `Record<EffectKind, FaultPoint>`), `effect_recovery:before_clear` (`effect-recovery.ts`), `large_file:stage_streaming` (after each piece `stageStreamedContent` writes to a stage's in-progress name), `effect_recovery:before_stage` / `effect_recovery:staged` (a streamed, version 2 withdrawal mirror: once its record is durable, before its file is streamed into the publication stage, and after that step, before the recovery transaction renames the stage), `publication_recovery:before_clear` (`recoverPublication`), `sync:mid_checkpoint` (after each committed cursor step in `sync-run.ts` `saveCursor`), `sync:after_freeze` (#6712 PR 0: at the end of `freezeEntry` for an import entry, after its bytes are read and before the request is admitted; detail carries `slug` and `path`), `consumer:prepared` (between preparing a claimed request and publishing it), `stuck_recovery:*` (between the steps of `recovery-resolve.ts`) and the purge lookups `purge:*` (page-purge.ts, intent-redaction.ts, facts/purge.ts; a hook throwing a 57014 models a statement timeout). Used by `scripts/persistence/crash-robot.ts`, the #6511 tests and `test/sync-convergence.serial.test.ts`, which installs it in real `serve`/`sync` processes through the `test/fixtures/convergence-fault-kill.ts` preload (one action registry: kill, uncommitted edit, stall until released, or throw a given SQLSTATE, at the nth hit).- `src/core/persistence/recovery-resolve.ts` + `src/core/repair/stuck-recovery.ts` — `gbrain repair stuck-recovery [--source <id>] [--request-id <uuid>]` (#6650 §1.10), explicit-only, preview-bound and destructive (registry `consentText`; `--apply --expect <hash> --keep prior|disk --yes`, a non-interactive apply without `--yes` exits 3). `scanStuckRecoveries` (owner host only, else `owner_unavailable` for a named source) reads the source's queued head blocker (`readHeadBlockers`; its `request_recovery` ids select the records) and every non-terminal recovery record on the worktree blocked on `unexpected_file_bytes` or whose file matches neither recorded version; a v2 shared-skill bundle record refuses `recovery_bundle_unsupported` (catalogue entry, `docs/guides/repair.md#recovery-bundle-unsupported`), a withdrawal-mirror effect recovery on the worktree is listed in `refused` (residual `effect_recovery`; named with `--request-id` it refuses `recovery_effect_unsupported`), a blocked terminal request is listed in `refused` (residual `terminal_refused`; named with `--request-id` it refuses `recovery_choice_refused`, as does a choice the record cannot support), and unblocked terminal cleanups, staging-byte blocks and self-recovering records are residuals. Each item lists every file's prior (or absent) and disk (or deleted) fingerprints and what recovery sees; a local preview writes the prior, disk and unified-diff files 0600 under `~/.gbrain/backups/stuck-recovery/<request>/<digest>/` (a private directory outside every checkout) and prints the `diff -u` command. The item digest binds the recovery identity (attempt, owner epoch, path and published hash per file), the recorded prior hashes, each file's disk view and the page's `knowledge_revision`. `resolveStuckRecovery` runs under `acquireWorktree` with a bounded wait (10 s, then `writer_lock_unavailable`; so the resident recovery pass returns unchanged), re-verifies the digest (`preview_changed`) and journals in `op_checkpoints` op `stuck-recovery-resolution` keyed `<request row id>:<preview hash>` (exempt from the checkpoint purge; the finished row is the audit entry): `backed_up` (disk and prior bytes durable, always), then `written` (`--keep prior`: `upgradeRecoveryStaging` reserves an older record's restoration stage within the recovery budget, `queue_capacity` otherwise, then the prior bytes are published through `publishPersistenceFile` at that stage after `cleanupRecoveryStaging`, an absent prior unlinked) or `abandoned` (`--keep disk`, #6640's drop: `completeWrite` ends the live request `conflict` `source_changed`, or `finishUnpublishedFailure` with its recorded failure; the record is never rewritten, so its reserved bytes are released by the terminal path's `clearResolvedRecovery`), then `recoverPublication(…, alreadyLocked)` finishes by its unchanged rule and the journal records `done` with the result. A step refuses `unexpected_file_bytes` when the file changed again; a different `--keep` for the same hash refuses `idempotency_conflict`; an identical apply after `done` replays the result (also after the approved set aged out). A record the resident consumer (any version) or an earlier killed run already finished reports `finished_by: another_pass`. `--keep prior` on a request with no recorded failure requeues it (the accepted write publishes again). `--keep disk` hands off to `gbrain sources reconcile <source> <slug> --brain host --preview` and never reports the page repaired. A record whose prior file is over the single-string ceiling (`staging.before`) resolves the same way in bounded memory: the disk file and the staged copy are hashed in pieces (the copy's state, `verified`, `missing` or `mismatched`, is in the prior view and the digest), backups are kernel copies checked by streamed hash, the diff file is a summary (both fingerprints, the first differing byte, a window of at most 1 KiB; `cmp` reproduces it), `--keep prior` runs recovery's `restoreBeforeStage` after `cleanupRecoveryStaging(keepBefore)`, and `--keep disk` backs up a mismatched copy (`<index>.prior-stage`) and removes it before abandoning. `--keep prior` without a verified copy refuses `recovery_prior_stage_unavailable` (registry entry; its fix is the `--keep disk` apply under the same hash). Fault seams `stuck_recovery:{backed_up,written,abandoned,recovered}`. Tests: `test/repair-stuck-recovery.test.ts`, `test/e2e/repair-stuck-recovery-postgres.test.ts`, `test/large-pages/stuck-recovery-large.slow.test.ts`.-- Segmented withdrawal mirror (`src/core/persistence/{effects,effect-recovery,effect-model,staging}.ts`, flip lane A) — a withdrawal's mirror and Git scans treat a page stored in segments as an inline page (older binaries skipped it with `page_body_segmented`). `mirrorPage` renders its file from the segments (`page-prepare.ts` `unreadPageFile`, a `StreamedFileContent`) and reserves a version 2 `EffectRecovery` (`after: null`; `staging.publication` names the streamed file by path and SHA-256; the reservation counts the file once). `recoverEffectPublication` writes that stage before its transaction (`stageStreamedMirror`: from the measured file, or after a crash from the segments at the recorded revision, first discarding a stream a crash cut short under its in-progress name; seams `effect_recovery:before_stage` / `effect_recovery:staged`), then renames the verified stage (`staging.ts` `publishStreamedStage`). A segmented page's withdrawal is not materialized again: its rows were struck in its segments when the withdrawal committed. An older binary refuses a version 2 record (it has no embedded file) and leaves it for this one. Test: `test/large-pages/segmented-withdrawal-mirror.test.ts` (purge and forget twins, Git commits, two interruption seams, both engines).+- Segmented withdrawal mirror (`src/core/persistence/{effects,effect-recovery,effect-model,staging}.ts`, flip lane A) — a withdrawal's mirror and Git scans treat a page stored in segments as an inline page (older binaries skipped it with `page_body_segmented`). `mirrorPage` renders its file from the segments (`page-prepare.ts` `unreadPageFile`, a `StreamedFileContent`) and reserves a version 2 `EffectRecovery` (`after: null`; `staging.publication` names the streamed file by path and SHA-256; the reservation counts the file once). `recoverEffectPublication` writes that stage before its transaction (`stageStreamedMirror`: from the measured file, or after a crash from the segments at the recorded revision, first discarding a stream a crash cut short under its in-progress name; seams `effect_recovery:before_stage` / `effect_recovery:staged`), then renames the verified stage (`staging.ts` `publishStreamedStage`). A segmented page's withdrawal is not materialized again: its rows were struck in its segments when the withdrawal committed. v0.60.290.0 reads a version 2 record as version 1 (`Buffer.from(null)`, untyped `effect_unavailable` on every attempt, never parks) but never deletes it or its stage, so `mirrorPage` writes none while that binary could claim it (next entry). Test: `test/large-pages/segmented-withdrawal-mirror.test.ts` (purge and forget twins, Git commits, two interruption seams, both engines).+- `src/core/persistence/{recovery-version,segmented-mirror-gate}.ts` — forward compatibility of recovery records. `recovery-version.ts` lists the record versions this binary reads (`EFFECT_RECOVERY_VERSIONS`, `REQUEST_RECOVERY_VERSIONS`); `assertRecoveryVersion` refuses any other `recovery_version_unsupported` (fix `gbrain upgrade`, `host_admin`) before a reader touches the record: `recoverEffectPublication`, `reserveEffectRecovery`, `upgradeRecoveryStaging` (both tables) and `model.ts` `recoveryFiles` (request recovery, clearing, stuck-recovery); `head-blocker.ts` reports such a record as an intervention with the same fix. `segmented-mirror-gate.ts`: `mirrorPage` calls `assertSegmentedMirrorGate` before streaming a segmented page's file; while `segmentedWriterBlockers` (the switch's TTL-cached gate) sees a writer below SEGMENTED_WRITER_FLOOR it refuses `segmented_mirror_writer_gate` without reserving a record, and the target retries and parks as usual. `resumeGatedMirrors` (each effect pass, at most once per gate TTL per engine) requeues, via `retryParkedEffects`, requests whose parked targets all carry that code once the gate is clear. No version 1 fallback: it would hold the file whole, and v0.60.290.0's recovery of it refuses to materialize a segmented page forever. Tests: `test/pathological/lp-d-recovery-version.test.ts`, `test/pathological/lp-d-segmented-mirror-gate.test.ts` (both engines).diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.mdindex db5de82ffa..d7b9c5fd3b 100644--- a/docs/guides/error-codes.md+++ b/docs/guides/error-codes.md@@ -2922,6 +2922,16 @@ More: [docs/guides/repair.md#recovery-prior-stage-unavailable](../../docs/guides|---|---|---|---|---|---|---|| An earlier write left state that must be inspected and recovered before new writes. | Details name the exit when there is one: physical_root_device_changed (the checkout's filesystem device number changed; re-stamped by itself when ownership verifies) and physical_root_directory_changed (the directory at the recorded path was recreated, or its birth time drifted beyond 1 µs; the relocated-root self-transfer, `transfer prepare/accept <source> --self-transfer --confirm-relocated-root`, re-stamps it). Both are explained in docs/guides/write-refusals.md. | Only the brain host's operator can resolve this. Tell the user the message and run `gbrain doctor --json` on the brain host. | host_admin | `gbrain doctor --json` | 1 | no |+### recovery_version_unsupported++<a id="recovery_version_unsupported"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| A newer gbrain wrote this recovery record (its version is unknown here), so this gbrain left the record, its staged files and the canonical file untouched; writes on that worktree wait for it. | A recovery record says how to finish an interrupted publication; reading a newer layout as an older one can publish wrong bytes, delete a staged file or clear the record. Only a gbrain that knows the version may recover it, so the fix is upgrading gbrain on the canonical owner host and restarting its writer processes. | Only the brain host's operator can resolve this. Tell the user the message and run `gbrain doctor --json` on the brain host. | host_admin | `gbrain doctor --json` | 1 | no |++More: [docs/guides/write-refusals.md#recovery_version_unsupported](../../docs/guides/write-refusals.md#recovery_version_unsupported)+### redirect_uri_mismatch<a id="redirect_uri_mismatch"></a>@@ -3234,6 +3244,16 @@ More: [docs/guides/google-connect.md#troubleshooting](../../docs/guides/google-c|---|---|---|---|---|---|---|| A search offset was over the 10,000 limit. | The request itself was wrong or no longer matches the brain; nothing was changed. | Page with match: "keyword" and the next object each response returns; a cursor has no depth limit. | agent | `repeat the read that failed` | 1 | no |+### segmented_mirror_writer_gate++<a id="segmented_mirror_writer_gate"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| A withdrawal mirror of a page stored in segments waits because a gbrain that cannot read its recovery record wrote to this brain in the last 7 days; the withdrawal is committed and the canonical file keeps the withdrawn row until the mirror runs. | The mirror's version 2 recovery record names a streamed staging file; a gbrain below the segmented writer floor (v0.60.290.0) misreads it and wedges the worktree, so no record is written while the segmented-storage writer gate sees such a writer. The mirror retries, parks, and runs again by itself once the gate clears. | Only the brain host's operator can resolve this. Tell the user the message and run `gbrain doctor --json` on the brain host. | host_admin | `gbrain doctor --json` | 1 | no |++More: [docs/guides/write-refusals.md#segmented_mirror_writer_gate](../../docs/guides/write-refusals.md#segmented_mirror_writer_gate)+### serve_build_drift<a id="serve_build_drift"></a>diff --git a/docs/guides/troubleshooting.md b/docs/guides/troubleshooting.mdindex 32db39d239..68c4189559 100644--- a/docs/guides/troubleshooting.md+++ b/docs/guides/troubleshooting.md@@ -12,6 +12,7 @@| Symptom | Next step | Who acts | Consent | Verify ||---|---|---|---|---|+| A withdrawal committed but a large page's file still shows the withdrawn row; writer status lists its mirror parked with [`segmented_mirror_writer_gate`](write-refusals.md#segmented_mirror_writer_gate), or an effect retrying with [`recovery_version_unsupported`](write-refusals.md#recovery_version_unsupported) (or `effect_unavailable` on v0.60.290.0) holds every write on the worktree | `gbrain upgrade` on the hosts the refusal or doctor `segmented_storage` names (for `recovery_version_unsupported`, the owner host), then restart their serve, sync and worker processes. A gated mirror resumes by itself once the older writes are 7 days old; never delete a recovery record or its staging file | brain host | none | `gbrain sources writer status --source <source> --json` shows no parked or retrying mirror || The dream cycle's purge phase fails every night with `managed_purge_failed` (`42P01`, relation `query_cache` does not exist), or doctor `schema_missing_tables` warns | upgrade (#6911: the purge skips a missing rebuildable cache), then preview recreating it: `gbrain repair missing-tables` ([missing tables](repair.md#missing-tables)); apply the printed `--apply --expect <hash>` command. Pages parked by the earlier failures: `gbrain pages purge-deleted --retry-parked --dry-run`, then without `--dry-run` | agent, after the user agrees | `destructive` (the parked-page retry purges them) | `gbrain doctor --only schema_missing_tables --json` reports ok || A managed source's autopilot freshness `sync` jobs each land about one page, or `sources status` says `parked` while a sync job runs | upgrade (#6706: sync jobs drain to their deadline and count as the source's live drain), then restart `gbrain jobs work` / the supervisor so the worker loads the handler; a job result with `incomplete: true` names its follow-up (`continuation_job_id`) or the next step in `next` | agent | none | `gbrain sync status --source <id> --json` shows `live_job_id` or a cursor at `done`; `gbrain jobs get <id> --json` shows `outcome` || Doctor `sync_freshness` says a source has "no successful sync recorded" or "first sync running" | follow the check's `fix`: `first sync running` (code `sync_first_run_in_progress`, warn) means wait; `no successful sync recorded` (code `sync_no_successful_sync`, fail) names the last attempt and its `reason`: wait for a queued job, inspect holds (`gbrain sync status --source <id> --json`), or retry (`gbrain sync --source <id>`) ([details](#sync-freshness-no-successful-sync)) | agent | none | `gbrain doctor --only sync_freshness --json` |diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.mdindex f4d9f267bb..260652200e 100644--- a/docs/guides/write-refusals.md+++ b/docs/guides/write-refusals.md@@ -75,6 +75,8 @@ of making a duplicate.| <a id="connector-holds-exhausted"></a>`connector_holds_exhausted` | `connector_holds_exhausted` | A Google or GitHub source already holds 100 items and this sync would hold another. The sync stopped without advancing its cursor. So many held items usually means a source-wide problem (a broken renderer, a revoked scope), not bad items. | `gbrain sources status <source>` to see the held items and their error codes, fix the cause, then `gbrain sources retry-held <source>` and `gbrain sync --source <source>`. `gbrain sync --source <source> --full` also clears every hold. || <a id="connector-fence-below-timeline"></a>`fence_not_carried` | `connector_fence_below_timeline` | A managed connector re-render would have dropped a facts or takes fence the stored page keeps below its timeline sentinel, or one that is duplicated, unbalanced or unparseable. The write was refused so those rows are not expired; the item is counted toward a hold. | Preview `gbrain repair connector-fences --source <source>`, apply it after review with `--apply`, then `gbrain sources retry-held <source>`. A page the repair counts as ambiguous needs a manual edit (see [repair](repair.md)). || <a id="unsupported-mutation-protocol"></a>`consumer_upgrade_required` | `unsupported_mutation_protocol` | A connector on v0.60.11.0 or later sent a `connector_v2_*` write to a persistence consumer older than v0.60.11.0, which does not know the format. Other `permission_denied` refusals on connector receipts are never relabeled as upgrades. | `gbrain upgrade` on every consumer and worktree-owner host, then `gbrain sync --source <source>`. Upgrade those hosts before connector hosts. |+| <a id="recovery_version_unsupported"></a>`recovery_version_unsupported` | `recovery_version_unsupported` (effect `error_code`; head blocker state) | A publication or withdrawal-mirror recovery record on the source's worktree has a version this gbrain does not know: a newer gbrain wrote it. Recovery refused before reading it, so the record, its staged files and the canonical file are exactly as they were; the effect keeps retrying (it never parks) and writes on that worktree wait for it. `gbrain sources writer status` and a stalled sync name it (`effect_recovery` or `request_recovery` with this state) as needing intervention. v0.60.290.0 and older predate this check: they read a version 2 withdrawal-mirror record as version 1 and fail every attempt with `effect_unavailable` (an untyped TypeError) instead, without deleting the record or its staging file. | `fix.next` is `tell_user_to_run` `gbrain upgrade`: upgrade gbrain on the host that owns the source's canonical worktree and restart its serve, sync and worker processes; the upgraded writer finishes the recovery. Verify with `gbrain sources writer status --source <source> --json`. Never delete the record or its staged files, and never transfer the source to an older host to force it through. |+| <a id="segmented_mirror_writer_gate"></a>`segmented_mirror_writer_gate` | effect `error_code`, then the parked target's code (`targets_parked`) | A withdrawal (`forget`, `forget_fact`, `purge_fact`) on a page stored in segments committed, but a gbrain older than the segmented writer floor wrote to the brain in the last 7 days (the evidence that keeps `pages.segmented_storage` off; doctor `segmented_storage` names the host and when the hold clears). Its mirror would write a version 2 recovery record that gbrain cannot read (v0.60.290.0 wedges the worktree on it, see [`recovery_version_unsupported`](#recovery_version_unsupported)), so it wrote nothing: the canonical file keeps the withdrawn row, the withdrawal's Git effect waits, and the mirror retries and parks after five attempts like any failed target, so writes on the worktree go on. The refusal names each older host with its version, the kind of write and when it was last seen. | `fix.next` is `tell_user_to_run` `gbrain upgrade` on the named hosts (and a restart of their serve, sync or worker processes). Once those hosts are upgraded and their older writes are 7 days old, the owner retries the parked mirror by itself (checked at most once a minute); the file loses the row and the Git effect commits it. `gbrain sources writer retry-effects <source> --request-id <request>` retries it sooner; it parks again while the hold lasts. || `unbound_source` | `owner_unavailable` (`remember`: `unavailable` with `write_error: owner_unavailable`) | On Postgres, a page write or a `remember` about an existing page went to a source that has a checkout path but no canonical owner. It is refused by default because another host may own the files. The same reason appears when the source was bound, or the page gained a canonical file, after a database-only write was accepted, and (as a `source_changed` sync failure) when a canonical file appears at the path of a page written while the source was unbound. | Classic mode: write the file, commit, `gbrain sync --source <source>` (a remote agent asks the user to). Otherwise bind the source (`gbrain sources writer status <source> --json`, then `gbrain sources writer claim <source> --path <checkout> --admin-intent writer_claim --expected-state <admin_state>`), or opt in with `gbrain config set persistence.unbound_write database_only`. Not retryable. See [unbound sources on Postgres](#unbound-sources-on-postgres). || <a id="embedding_zero_norm"></a>`zero_norm`, `non_finite` or `empty_input` | `embedding_zero_norm` | The embedding provider returned a vector with no direction (all zeros, NaN or infinity) for a chunk, or the chunk text was empty. A vector index silently skips such a row, so gbrain refuses to store it. Only that chunk is refused: the page text and every other chunk's vector are saved, and the page is left for `gbrain embed --stale`. It is never retried as a rate limit or network error. | Inspect the named page's chunk text (empty, whitespace- or symbol-only chunks are the usual cause) or the embedding provider, fix it, then run `gbrain embed <slug>` (add `--source <source>` for a non-default source). If normal text also returns zero vectors, the provider or model is broken; check it with `gbrain doctor`. || `targets_parked` (doctor: `parked_effects`) | effect `error_code` | A Git backup or withdrawal target failed five times in a row and was set aside so the other pages keep committing. An effect `error_code` of `git_index_stale` means an index lock older than 10 minutes blocks the checkout: `.git/index.lock` in it (`git -C <checkout> rev-parse --git-path index.lock` for a linked worktree). The canonical writer removes such a lock by itself when it can prove no process holds it and no git runs in that checkout, and then retries the effects it parked; the error's `fix` says why it could not prove that (another platform, a container, a network filesystem, or a live git). Otherwise remove it only if no git command is running there, then run the `retry-effects` command. A fresher lock (`git_index_locked`) is retried as contention and never parks. An effect `error_code` of `git_target_pending` means Git still lists a removed page file in the index (on Windows, a program such as a sync watcher, an indexer or antivirus may still hold it open): close that program, check with `git -c core.fscache=false status` on the brain host, then run the `retry-effects` command. It is retried 30 seconds apart and parks after five attempts like other target failures. The page write itself committed; its Git backup or withdrawal is incomplete. Contention, dependency waits, shutdown and transient database errors never count toward the five. | `gbrain sources writer status <source>`, fix the cause it names, preview with `gbrain sources writer retry-effects <source> --request-id <id> --dry-run`, then run it without `--dry-run`. Each run grants one more attempt per parked target; a target that fails again parks again. |@@ -522,7 +524,7 @@ retry_after_ms, eta_seconds, rate_pages_per_min, why, docs }`. Run| <a id="drain-write-capacity"></a>`write_capacity` | `queue_capacity` | `blocked` | The sync could not admit its next write for the whole no-progress window (30 s) because other writers' requests held the outstanding-request cap of its write principal (`persistence.limits.principal_outstanding`, default 100; the brain cap `persistence.limits.brain_outstanding`, 1000, works the same way): on one host the CLI sync and a maintenance run (fact-fence adoption, `dream`) share the `local_cli` principal, so a long adoption queue leaves no room for a sync write. Nothing failed and the cursor is intact: the drain retried the admission with backoff while they settled, printing `waiting for write capacity (N outstanding of M)`, and stopped only when the window passed. `drain.capacity` carries the counts and the wait; exit 1. A cumulative cap (permanent request IDs, receipt bytes) is a different refusal: it names its config key and stops at once. | `gbrain sources writer status --source <source> --json` lists the outstanding requests (read-only). Let them finish, or raise the cap (`gbrain config set persistence.limits.principal_outstanding 200`), then rerun the same sync; it resumes where it stopped. || <a id="drain-connection-lost"></a>`connection_lost` | `connection_lost` | `blocked` | The database connection dropped three times in a row (`write ECONNABORTED`, `ECONNRESET`, `ETIMEDOUT`, `EPIPE`: a pooler closing the socket mid-statement) with no page committed between the drops (#6340). Each drop was reconnected and retried after 5, 15 and 45 s; a drop that then moves data is not reported at all. Nothing is recorded against the source: the cursor and its frozen manifest stand, and `drain.connection` carries the count and the last error text (never a URL). Exit 1. | Check the database and pooler (`gbrain doctor --json`), then rerun `next.command` (`safe_to_loop` is true, `retry_after_ms` 60 s): it resumes at the stored cursor without re-freezing the manifest. Runbook: [sync unblock](sync-unblock-runbook.md#connection). || <a id="drain-capacity-paused"></a>`capacity_paused` | `capacity_paused` | `resumable` | The run passed its capacity preflight, then a cumulative write cap refused its next admission (`write_quota_exhausted`) or, for a background sync, the pause line did (`write_capacity_backpressure`): another writer used the room the preflight counted on. Nothing failed; the cursor and every accepted write stand, and `drain.capacity_pause` names the refusal and its config raise. | Run the `gbrain config set` the report names on the brain host (request ids never free; receipt bytes also free as receipts compact), then rerun the same `gbrain sync`. Verify with `gbrain doctor --only persistence_capacity --json`. |-| <a id="head-blocked"></a>`drain_stalled` with `cause: head_blocked` | `drain_stalled` | `blocked` | The queued write at the head of the source cannot be claimed by any consumer, and its blocker needs an operator (#6543). `drain.stall.blocked_by` names the predicate, its ids, state and owner: `refresh_fence` (a refresh left the checkout `fenced`, `merged` or `recovery_required` and no refresh process holds its lock), `zombie_publication` (a running request ahead of the head is held by a process that reports `restart_required`), or `effect_recovery` with state `unexpected_file_bytes` (a fact-withdrawal mirror's page file was edited while the mirror was publishing, so its forward-only recovery refuses to overwrite it), or `request_recovery` with state `unexpected_file_bytes` (a page write's file was edited while it was publishing, #6650; this also covers a head that is itself that recovering write). For both, `blocked_by.file` names the page and path. A recovery stuck on `unexpected_staging_bytes` is not classified yet and still waits out the window. The drain stops after one governor tick of confirmation instead of the no-progress window. Live blockers (`root_hold`, a foreground publication; `lease`, a lapsed claim the next consumer reclaims; `withdrawal_mirror`, an `effect_recovery` or `request_recovery` that can still finish, `worktree_owner`) never stop it: the stall line names them as `blocked_by=` beside `consumer=` and the drain keeps waiting. `claimable here` is read for the head itself and prints `unknown` when the probe could not read it. | Run `next.fix`: `refresh_fence` resumes the refresh (`gbrain sources refresh <source> --resume`, which lifts the fence or names why it cannot); `zombie_publication` tells the host admin to restart the named process; `effect_recovery` asks the user to copy the edited file aside and put it back to a version gbrain recorded (undo the edit, or restore the committed version), never to delete it, and to redo the edit after the withdrawal finishes; `request_recovery` runs the [`gbrain repair stuck-recovery --source <source>`](repair.md#stuck-recovery) preview, and the user either keeps one version through it or undoes the edit. Then rerun the sync. `gbrain sources writer status --source <source> --json` names the same blocker for every queued head and, only when the caller may cancel the blocking request, `gbrain cancel-write-request <request_id>`. |+| <a id="head-blocked"></a>`drain_stalled` with `cause: head_blocked` | `drain_stalled` | `blocked` | The queued write at the head of the source cannot be claimed by any consumer, and its blocker needs an operator (#6543). `drain.stall.blocked_by` names the predicate, its ids, state and owner: `refresh_fence` (a refresh left the checkout `fenced`, `merged` or `recovery_required` and no refresh process holds its lock), `zombie_publication` (a running request ahead of the head is held by a process that reports `restart_required`), or `effect_recovery` with state `unexpected_file_bytes` (a fact-withdrawal mirror's page file was edited while the mirror was publishing, so its forward-only recovery refuses to overwrite it), or `request_recovery` with state `unexpected_file_bytes` (a page write's file was edited while it was publishing, #6650; this also covers a head that is itself that recovering write). For both, `blocked_by.file` names the page and path. `effect_recovery` or `request_recovery` with state [`recovery_version_unsupported`](#recovery_version_unsupported) is a record a newer gbrain wrote, which no recovery here finishes. A recovery stuck on `unexpected_staging_bytes` is not classified yet and still waits out the window. The drain stops after one governor tick of confirmation instead of the no-progress window. Live blockers (`root_hold`, a foreground publication; `lease`, a lapsed claim the next consumer reclaims; `withdrawal_mirror`, an `effect_recovery` or `request_recovery` that can still finish, `worktree_owner`) never stop it: the stall line names them as `blocked_by=` beside `consumer=` and the drain keeps waiting. `claimable here` is read for the head itself and prints `unknown` when the probe could not read it. | Run `next.fix`: `refresh_fence` resumes the refresh (`gbrain sources refresh <source> --resume`, which lifts the fence or names why it cannot); `zombie_publication` tells the host admin to restart the named process; `effect_recovery` asks the user to copy the edited file aside and put it back to a version gbrain recorded (undo the edit, or restore the committed version), never to delete it, and to redo the edit after the withdrawal finishes; `request_recovery` runs the [`gbrain repair stuck-recovery --source <source>`](repair.md#stuck-recovery) preview, and the user either keeps one version through it or undoes the edit; `recovery_version_unsupported` tells the user to run `gbrain upgrade` on the owner host. Then rerun the sync. `gbrain sources writer status --source <source> --json` names the same blocker for every queued head and, only when the caller may cancel the blocking request, `gbrain cancel-write-request <request_id>`. || <a id="sync_drain_lease_held"></a>`drain_lease_held` | `sync_drain_lease_held` | `resumable` | Another process holds the source's drain lease (#6712): one managed drainer per source, and that holder (a serve, a `sync` job, the dream cycle, another terminal) is still committing pages. `gbrain sync` follows it within its own `--timeout` and run deadline, printing the holder (kind, pid, host, gbrain version) and the pages it commits (every 10 s on a terminal, 60 s otherwise), and takes the lease when the holder releases it. This code means the budget ended first, or the lease moved to another process mid-pass (`lost`); nothing this run admitted is lost and the cursor is intact. `--no-delegate` never skips the lease. `drain.lease_held.holder` reuses the drain's owner fields: `kind`, `id`, `host`, `pid`, `started_at`, `last_heartbeat_at`, `version` and `progress` (`committed`, `last_committed_at`, `last_progress_at`); `next.retry_after_ms` is 60 s and `next.safe_to_loop` is true. Exit 0. A cron that runs `gbrain sync` every few minutes beside a serve exits 0 here on each tick while the serve works. | Rerun `next.command` after `next.retry_after_ms`, or let the holder finish. Ctrl-C while following stops only this run; the holder keeps going. A holder that commits nothing for 5 minutes is not reported here: the run stops [`drain_stalled`](#drain-lease-stalled) instead. || <a id="drain-lease-stalled"></a>`drain_stalled` with `cause: no_progress` and `stall.lease_holder` | `drain_stalled` | `blocked` | The process holding the source's drain lease committed no page and saved no cursor for 5 minutes, so following it would exit 0 forever (#6712). `drain.stall.lease_holder` names it with the fields above; the lease itself is renewed by a live process, so a wedged holder keeps it. A holder that died lets its lease lapse within 2 minutes and the next run takes over without this stop. Exit 1, `next.safe_to_loop` false. | `gbrain sources writer status --source <source> --json` (read-only) shows what the holder is waiting on. Stop or restart the named process; when it is gone but its lock row remains, `gbrain sync --source <source> --no-pull --break-lock` releases a lock whose pid is dead (`--force-break-lock` skips the liveness check: only when you know the holder is gone). Then rerun the same sync. |diff --git a/llms-full.txt b/llms-full.txtindex 1ace5531d2..a937b5f91c 100644--- a/llms-full.txt+++ b/llms-full.txt@@ -10645,6 +10645,7 @@ Source: https://raw.githubusercontent.com/garrytan/gbrain/master/docs/guides/tro| Symptom | Next step | Who acts | Consent | Verify ||---|---|---|---|---|+| A withdrawal committed but a large page's file still shows the withdrawn row; writer status lists its mirror parked with [`segmented_mirror_writer_gate`](write-refusals.md#segmented_mirror_writer_gate), or an effect retrying with [`recovery_version_unsupported`](write-refusals.md#recovery_version_unsupported) (or `effect_unavailable` on v0.60.290.0) holds every write on the worktree | `gbrain upgrade` on the hosts the refusal or doctor `segmented_storage` names (for `recovery_version_unsupported`, the owner host), then restart their serve, sync and worker processes. A gated mirror resumes by itself once the older writes are 7 days old; never delete a recovery record or its staging file | brain host | none | `gbrain sources writer status --source <source> --json` shows no parked or retrying mirror || The dream cycle's purge phase fails every night with `managed_purge_failed` (`42P01`, relation `query_cache` does not exist), or doctor `schema_missing_tables` warns | upgrade (#6911: the purge skips a missing rebuildable cache), then preview recreating it: `gbrain repair missing-tables` ([missing tables](repair.md#missing-tables)); apply the printed `--apply --expect <hash>` command. Pages parked by the earlier failures: `gbrain pages purge-deleted --retry-parked --dry-run`, then without `--dry-run` | agent, after the user agrees | `destructive` (the parked-page retry purges them) | `gbrain doctor --only schema_missing_tables --json` reports ok || A managed source's autopilot freshness `sync` jobs each land about one page, or `sources status` says `parked` while a sync job runs | upgrade (#6706: sync jobs drain to their deadline and count as the source's live drain), then restart `gbrain jobs work` / the supervisor so the worker loads the handler; a job result with `incomplete: true` names its follow-up (`continuation_job_id`) or the next step in `next` | agent | none | `gbrain sync status --source <id> --json` shows `live_job_id` or a cursor at `done`; `gbrain jobs get <id> --json` shows `outcome` || Doctor `sync_freshness` says a source has "no successful sync recorded" or "first sync running" | follow the check's `fix`: `first sync running` (code `sync_first_run_in_progress`, warn) means wait; `no successful sync recorded` (code `sync_no_successful_sync`, fail) names the last attempt and its `reason`: wait for a queued job, inspect holds (`gbrain sync status --source <id> --json`), or retry (`gbrain sync --source <id>`) ([details](#sync-freshness-no-successful-sync)) | agent | none | `gbrain doctor --only sync_freshness --json` |diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 3d3753be42..b772c912ea 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -903,6 +903,9 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;{ 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.' },+ // 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) wrote to the brain in the last 7 days (the same evidence that keeps `pages.segmented_storage` off; doctor `segmented_storage` 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.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/error-catalogue.ts b/src/core/error-catalogue.tsindex 0d8166cdd3..de22469092 100644--- a/src/core/error-catalogue.ts+++ b/src/core/error-catalogue.ts@@ -56,6 +56,9 @@ export const ERROR_CATALOGUE = {recovery_choice_refused: { code: 'recovery_choice_refused', docs: 'docs/guides/repair.md#recovery-choice-refused' },// #6650: a withdrawal-mirror effect recovery only finishes forward, so stuck-recovery lists it as refused.recovery_effect_unsupported: { code: 'recovery_effect_unsupported', docs: 'docs/guides/repair.md#recovery-effect-unsupported' },+ // LPH (d): a recovery record a newer gbrain wrote is refused unread; a segmented mirror waits for older writers.+ recovery_version_unsupported: { code: 'recovery_version_unsupported', docs: 'docs/guides/write-refusals.md#recovery_version_unsupported' },+ segmented_mirror_writer_gate: { code: 'segmented_mirror_writer_gate', docs: 'docs/guides/write-refusals.md#segmented_mirror_writer_gate' },colon_slug_windows_write_through: { code: 'colon_slug_windows_write_through', docs: 'docs/guides/write-refusals.md#colon_slug_windows_write_through' },embedding_auth_failed: { code: 'embedding_auth_failed', docs: 'docs/guides/write-refusals.md#embedding_auth_failed' },activation_source_path_missing: { code: 'source_changed', docs: 'docs/guides/write-refusals.md#activation_source_path_missing' },diff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex e885922ff7..8d73284ff9 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -506,6 +506,7 @@ export const CODES = {suggestion: "Check the checkout with git -C <dir> status, then rerun the read-only status; report it with gbrain doctor --json if it repeats.",fix: { argv: ['gbrain', 'sync', 'status', '--source', '{source_id}', '--detail', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Re-reads the convergence shadow; writes nothing.' } },recovery_prior_stage_unavailable: { class: 'consent', actor: 'user', summary: "gbrain repair stuck-recovery cannot apply that --keep choice to a page recovery over the single-string ceiling, because the staged copy of its prior file is missing, does not match its recorded SHA-256, or is not a regular file; nothing was changed.", why: "A prior file over 24 MiB is not embedded in its recovery record: the record names a staged copy beside the file by path and SHA-256, and only that copy can put the prior bytes back. Without it --keep prior has nothing safe to restore, so the remaining exit is --keep disk, which the user must agree to.", docs: 'docs/guides/repair.md#recovery-prior-stage-unavailable' },+ recovery_version_unsupported: { class: 'host_only', actor: 'host_admin', summary: "A newer gbrain wrote this recovery record (its version is unknown here), so this gbrain left the record, its staged files and the canonical file untouched; writes on that worktree wait for it.", why: "A recovery record says how to finish an interrupted publication; reading a newer layout as an older one can publish wrong bytes, delete a staged file or clear the record. Only a gbrain that knows the version may recover it, so the fix is upgrading gbrain on the canonical owner host and restarting its writer processes.", docs: 'docs/guides/write-refusals.md#recovery_version_unsupported' },recovery_required: { class: 'host_only', summary: "An earlier write left state that must be inspected and recovered before new writes.", why: "Details name the exit when there is one: physical_root_device_changed (the checkout's filesystem device number changed; re-stamped by itself when ownership verifies) and physical_root_directory_changed (the directory at the recorded path was recreated, or its birth time drifted beyond 1 µs; the relocated-root self-transfer, `transfer prepare/accept <source> --self-transfer --confirm-relocated-root`, re-stamps it). Both are explained in docs/guides/write-refusals.md." },redirect_uri_mismatch: { class: 'caller', summary: "Google connect credential error: redirect uri mismatch.", docs: 'docs/guides/google-connect.md#troubleshooting' },ref_not_in_answer: { class: 'caller', summary: "The rated page is not one of the pages the answer used.", docs: 'docs/guides/retrieval-feedback.md#ref_not_in_answer' },@@ -538,6 +539,7 @@ export const CODES = {search_mode_local_only: { class: 'caller', summary: "An agent-facing caller set search's mode, which only the brain's operator chooses.", suggestion: 'Omit mode; for keyword-only matching with a total and paging, pass match: "keyword".' },scorecard_group_by_local_only: { class: 'caller', summary: "An agent-facing caller asked takes_scorecard for group_by or min_n, which read the private forecast journal and run only from the trusted local CLI.", suggestion: 'Omit group_by and min_n; the brain owner runs gbrain takes scorecard --group-by on the brain host.' },search_offset_over_cap: { class: 'caller', summary: "A search offset was over the 10,000 limit.", suggestion: 'Page with match: "keyword" and the next object each response returns; a cursor has no depth limit.' },+ segmented_mirror_writer_gate: { class: 'host_only', actor: 'host_admin', summary: "A withdrawal mirror of a page stored in segments waits because a gbrain that cannot read its recovery record wrote to this brain in the last 7 days; the withdrawal is committed and the canonical file keeps the withdrawn row until the mirror runs.", why: "The mirror's version 2 recovery record names a streamed staging file; a gbrain below the segmented writer floor (v0.60.290.0) misreads it and wedges the worktree, so no record is written while the segmented-storage writer gate sees such a writer. The mirror retries, parks, and runs again by itself once the gate clears.", docs: 'docs/guides/write-refusals.md#segmented_mirror_writer_gate' },serve_build_drift: { class: 'host_only', summary: "A live `serve` or resident worker on this host runs an older gbrain build than this checkout: its `persistence_consumers` heartbeat `version` is below this binary's VERSION.", why: "Upgrading or pulling the checkout does not restart the processes already running from it, so one-shot commands from the checkout (`gbrain sync`, `bun run src/cli.ts`) run newer code against the older consumer until serve and its workers restart. A serve older than the heartbeat table writes no row; `consumers_without_heartbeat` names it.", docs: 'docs/guides/troubleshooting.md#serve-build-drift', suggestion: 'Restart serve with the command the check prints (`systemctl --user restart gbrain-serve.service`, `launchctl kickstart -k gui/<uid>/com.gbrain.serve`, or stop the named pid and start it again), then restart each other listed worker; nothing restarts automatically.', fix: { argv: ['gbrain', 'sources', 'writer', 'status', '--json'], consent: [], actor: 'agent', why: 'Read-only: lists the consumers alive on this host with each heartbeat row\'s kind, pid and gbrain version.', requires_exclusive: false, verify: { argv: ['gbrain', 'doctor', '--only', 'serve_build_drift', '--json'] } } },serve_port_in_use: { class: 'unavailable', summary: "gbrain serve --http could not listen: another process already holds that host and port.", suggestion: 'Stop the process on that port, or start the server with another --port and point the harnesses at it.' },serve_status_only: { class: 'unavailable', summary: "gbrain serve is in status-only mode: its brain is locked by another server, missing, damaged, or its config is unreadable.", reasons: ['lock_held', 'no_brain', 'config_unreadable', 'missing_brain', 'brain_unopenable', 'repair_failed', 'unavailable'], suggestion: 'Call gbrain_status for the cause, the fix and what to tell the user.' },diff --git a/src/core/persistence/effect-recovery.ts b/src/core/persistence/effect-recovery.tsindex bc4b068589..147571b5bc 100644--- a/src/core/persistence/effect-recovery.ts+++ b/src/core/persistence/effect-recovery.ts@@ -22,6 +22,7 @@ import { isSegmentedPage } from '../page-body/page-shape.ts';import { declarePersistenceProtocol } from './protocol.ts';import { advanceEffectCursor } from './effect-journal.ts';import { faultPoint } from './fault-points.ts';+import { assertRecoveryVersion } from './recovery-version.ts';const effectStatusFix = (effect: Pick<PersistenceEffect, 'source_id'>): Action => readFix(`Shows source ${effect.source_id}'s canonical owner with its blocking, retrying and parked effects, read-only.`,@@ -76,6 +77,7 @@ export async function reserveEffectRecovery(engine: BrainEngine, effect: Persistconst counters = await lockCounters(tx, ['brain', `worktree:${effect.worktree_id}`]);const current = await lockedEffect(tx, effect);if (current.recovery) {+ assertRecoveryVersion('persistence_effects', current.recovery, current.source_id);if (digest(current.recovery) !== digest(record)) throw opError('recovery_required', 'The prior mirror publication must be reconciled first.',`This effect of source ${effect.source_id} still holds an earlier mirror publication's recovery record, so a new one was not reserved; the worker recovers the earlier one first. Inspect the owner's effects rather than resubmitting anything.`,{ fix: effectStatusFix(effect) });@@ -183,6 +185,7 @@ export async function recoverEffectPublication(engine: BrainEngine, effect: Pers`Every publication slot of the writer pool is busy, so mirror recovery for source ${effect.source_id} has not started; the worker tries again once a slot frees. Nothing needs resubmitting.`,{ fix: effectStatusFix(effect) });try {+ assertRecoveryVersion('persistence_effects', effect.recovery, effect.source_id);if (effect.recovery) await upgradeRecoveryStaging(engine, 'persistence_effects', effect.id, effect.worktree_id!, 'forward');await stageStreamedMirror(engine, effect, hostId, hooks.content, hooks.between);await engine.transaction(async tx => {@@ -192,6 +195,7 @@ export async function recoverEffectPublication(engine: BrainEngine, effect: Persconst current = await lockedEffect(tx, effect);const record = current.recovery;if (!record) return;+ assertRecoveryVersion('persistence_effects', record, current.source_id);const streamed = record.version === 2;if (!recordBelongs(record, current, binding) || (streamed ? record.staging?.publication?.hash !== record.afterHash: sha256(Buffer.from(record.after ?? '', 'base64')) !== record.afterHash)) throw opError('recovery_required', 'Mirror recovery no longer belongs to this canonical binding.',diff --git a/src/core/persistence/effects.ts b/src/core/persistence/effects.tsindex ade3b71455..97883128ab 100644--- a/src/core/persistence/effects.ts+++ b/src/core/persistence/effects.ts@@ -40,6 +40,7 @@ import { advanceEffectCursor, claimCoalescedGitEffects, claimPersistenceEffect,import { guardEffectSource, recoverEffectPublication, reserveEffectRecovery } from './effect-recovery.ts';import { commitGitTargets, DURABILITY_NOT_ENABLED, publishGitEffect, pushGitRoot, type GitEffectOwner } from './effect-git.ts';import { retryIndexLockParks } from './effect-retry.ts';+import { assertSegmentedMirrorGate, resumeGatedMirrors } from './segmented-mirror-gate.ts';import { gitDurabilityPolicy } from './git-durability-policy.ts';import { EFFECT_FAULT_POINTS, faultPoint } from './fault-points.ts';import { dispatchFactsBackstopEffect } from './effect-facts.ts';@@ -197,6 +198,7 @@ async function mirrorPage(engine: BrainEngine, effect: PersistenceEffect, bindinawait materializeAndAdvance(engine, effect, snapshot, opts.hostId);return;}+ if (segmented) await assertSegmentedMirrorGate(engine, effect, snapshot.page.slug);content = segmented ? await unreadPageFile(engine, snapshot, keep) : file.content as string;} catch (error) {// A segmented page whose fence a withdrawal cannot read whole (page_body_segmented) retries and parks like any failed@@ -598,6 +600,7 @@ export async function runPersistenceEffects(engine: BrainEngine, config: GBrainCasync function runEffectPass(engine: BrainEngine, config: GBrainConfig, opts: EffectWorkerOptions, touched: Set<string>): Promise<number> {const limit = Math.max(1, Math.min(opts.limit ?? 2, 20));+ await resumeGatedMirrors(engine, opts.hostId);const recoveries = await selectEffectRecoveries(engine, opts.hostId, limit);let attempted = 0;for (const recovery of recoveries) {diff --git a/src/core/persistence/head-blocker.ts b/src/core/persistence/head-blocker.tsindex 8dd8dea998..5f7e6458ff 100644--- a/src/core/persistence/head-blocker.ts+++ b/src/core/persistence/head-blocker.ts@@ -7,7 +7,8 @@* reports `restart_required` (a zombie publication), or a withdrawal-mirror effect recovery its own last attempt refused* `unexpected_file_bytes` whose file still matches neither recorded version (an edit made while the mirror was publishing;* recovery only finishes forward and never overwrites it), or a page write's publication recovery refused the same way (#6650;- * `gbrain repair stuck-recovery` is its exit), whether it blocks a queued head or is the head itself. Every other blocker is live and transient (a foreground publication,+ * `gbrain repair stuck-recovery` is its exit), whether it blocks a queued head or is the head itself, or an effect or request+ * recovery record a newer gbrain wrote (`recovery_version_unsupported`: an upgrade is its exit). Every other blocker is live and transient (a foreground publication,* a refresh or recovery making progress, a lapsed lease the next consumer reclaims), so the drain keeps its progress-aware wait.*/import { existsSync, readFileSync } from 'node:fs';@@ -18,6 +19,7 @@ import { claimStateOf } from './claim-phase.ts';import { isTerminal, type RequestState } from './model.ts';import { sha256 } from './digest.ts';import { claimableWriteSql, EARLIER_HEAD, foregroundPrioritySql, SYNC_KIND } from './journal.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';@@ -43,7 +45,7 @@ interface RowRef { request_id: string; state: string; claim_phase: unknown; execinterface 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 }-interface EffectRecoveryRef { id: string; error_code: string | null; slug: string | null; path: string | null; before: string | null; after: string | null }+interface EffectRecoveryRef { id: string; 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 }const REQUEST_RECOVERY = (alias: string) => `jsonb_build_object('request_id',${alias}.request_id::text,'state',${alias}.state,'blocked_reason',${alias}.blocked_reason,@@ -65,7 +67,12 @@ const effectRecoveryStuck = (effect: EffectRecoveryRef) => stuckOnFile(effect.er/** A live page recovery (a terminal one never restores its file; a skill bundle has no stuck-recovery exit). */const requestRecoveryStuck = (request: RequestRecoveryRef) => request.version === '1' && !isTerminal(request)&& stuckOnFile(request.blocked_reason, request.path, request.before, request.after);+/** A record a newer gbrain wrote (recovery-version.ts): no recovery here finishes it, so only an upgrade clears it. */+const newerRecord = (table: RecoveryTable, version: unknown) => !recoveryVersionKnown(table, { version: typeof version === 'string' && /^\d+$/.test(version) ? Number(version) : version });+const newerBlocker = (predicate: 'effect_recovery' | 'request_recovery', ids: string[]): HeadBlocker =>+ ({ predicate, ids, state: 'recovery_version_unsupported', owner: null, intervention: true });const requestRecoveryBlocker = (refs: RequestRecoveryRef[]): HeadBlocker => {+ if (refs.some(ref => newerRecord('persistence_requests', ref.version))) return newerBlocker('request_recovery', refs.map(ref => ref.request_id));const stuck = refs.find(requestRecoveryStuck);return { predicate: 'request_recovery', ids: refs.map(ref => ref.request_id), state: stuck ? 'unexpected_file_bytes' : null, owner: null, intervention: !!stuck,...(stuck ? { file: { slug: stuck.slug, path: stuck.path! } } : {}) };@@ -89,7 +96,7 @@ export async function readHeadBlockers(engine: BrainEngine, ids: string[], hostI(SELECT jsonb_build_object('id',f.id::text,'state',f.state) FROM persistence_worktree_refreshes fWHERE f.worktree_id=r.worktree_id AND f.state IN ('fenced','merged','recovery_required') LIMIT 1) AS fence,(SELECT jsonb_agg(jsonb_build_object('id',e.id::text,'error_code',e.error_code,'slug',e.recovery->>'slug','path',e.recovery->>'path',- 'before',e.recovery->>'beforeHash','after',e.recovery->>'afterHash') ORDER BY e.id) FROM persistence_effects e WHERE e.worktree_id=r.worktree_id AND e.recovery IS NOT NULL) AS effect_recovery,+ 'before',e.recovery->>'beforeHash','after',e.recovery->>'afterHash','version',e.recovery->'version') ORDER BY e.id) FROM persistence_effects e WHERE e.worktree_id=r.worktree_id AND e.recovery IS NOT NULL) AS effect_recovery,(SELECT array_agg(m.id::text) FROM persistence_effects m WHERE m.worktree_id=r.worktree_id AND m.kind='withdrawal-mirror' AND m.state IN ('queued','running')AND (NOT (m.data ? 'targets') OR m.data->'targets' @> jsonb_build_array(jsonb_build_object('slug',r.slug)))) AS mirrors,(SELECT jsonb_agg(${REQUEST_RECOVERY('b')} ORDER BY b.sequence) FROM persistence_requests b WHERE b.worktree_id=r.worktree_id AND b.recovery IS NOT NULL) AS request_recovery,@@ -114,6 +121,10 @@ export async function readHeadBlockers(engine: BrainEngine, ids: string[], hostIintervention: row.fence.state === 'recovery_required' || live === false });continue;}+ if (row.effect_recovery?.length && row.effect_recovery.some(effect => newerRecord('persistence_effects', effect.version))) {+ blocked(newerBlocker('effect_recovery', row.effect_recovery.map(effect => effect.id)));+ continue;+ }if (row.effect_recovery?.length) {const stuck = row.effect_recovery.find(effectRecoveryStuck);blocked({ predicate: 'effect_recovery', ids: row.effect_recovery.map(effect => effect.id), state: stuck ? 'unexpected_file_bytes' : null, owner: null, intervention: !!stuck,@@ -147,7 +158,7 @@ export async function readHeadBlockers(engine: BrainEngine, ids: string[], hostIasync function recoveringHeadBlocker(engine: BrainEngine, id: string, hostId: string | null, opts: { timeoutMs?: number; signal?: AbortSignal }): Promise<HeadBlocker | null> {const [row] = await engine.executeRaw<{ ref: RequestRecoveryRef; owner_host_id: string | null }>(`SELECT ${REQUEST_RECOVERY('r')} AS ref, w.owner_host_id::text AS owner_host_idFROM persistence_requests r JOIN persistence_worktrees w ON w.id=r.worktree_id WHERE r.id=$1::uuid AND r.recovery IS NOT NULL`, [id], opts);- if (!row || !hostId || row.owner_host_id !== hostId || !requestRecoveryStuck(row.ref)) return null;+ if (!row || !hostId || row.owner_host_id !== hostId || (!requestRecoveryStuck(row.ref) && !newerRecord('persistence_requests', row.ref.version))) return null;return requestRecoveryBlocker([row.ref]);}@@ -179,6 +190,12 @@ export function headBlockerAction(blocker: HeadBlocker, sourceId: string, resume+ `Resuming it finishes (or names why it cannot finish) the refresh and lifts the fence; then rerun: ${resumeCommand}`,verify: { argv: status } };}+ if (blocker.state === 'recovery_version_unsupported') {+ const kind = blocker.predicate === 'effect_recovery' ? 'withdrawal-mirror effect' : 'write request';+ return { ...recoveryUpgradeFix(sourceId),+ why: `A ${kind} recovery record on source ${sourceId}'s worktree (${blocker.ids.join(', ')}) was written by a newer gbrain, so this gbrain cannot finish it and every write there waits; `+ + `waiting does not clear it. Upgrading gbrain on the owner host lets its writer finish the recovery; then rerun: ${resumeCommand}` };+ }if (blocker.predicate === 'zombie_publication') {const who = `the gbrain ${blocker.owner?.kind ?? 'owner'} process${blocker.owner?.pid ? ` (pid ${blocker.owner.pid})` : ''}`;return { argv: status, consent: [], actor: 'host_admin', requires_exclusive: false,diff --git a/src/core/persistence/model.ts b/src/core/persistence/model.tsindex 4639dfedef..59a421adf2 100644--- a/src/core/persistence/model.ts+++ b/src/core/persistence/model.ts@@ -1,4 +1,5 @@import type { BrainEngine } from '../engine.ts';+import { assertRecoveryVersion } from './recovery-version.ts';export type Principal = { kind: 'oauth_client' | 'legacy_token' | 'local_cli' | 'local_stdio' | 'application'; id: string };export type RequestState = 'queued' | 'running' | 'recovering' | 'committed' | 'conflict' | 'failed' | 'cancelled';@@ -58,6 +59,7 @@ export interface BundleRecoveryRecord {}export type RecoveryRecord = FileRecoveryRecord | BundleRecoveryRecord;export function recoveryFiles(record: RecoveryRecord): FileRecoveryRecord[] {+ assertRecoveryVersion('persistence_requests', record, null);if (record.version === 1) return [record];if (record.version === 2 && record.target === 'skill_bundle' && Array.isArray(record.files)&& record.files.length > 0 && record.files.length <= 128 && record.files.every(file => file.version === 1)) return record.files;diff --git a/src/core/persistence/recovery-version.ts b/src/core/persistence/recovery-version.tsnew file mode 100644index 0000000000..d7f37a301b--- /dev/null+++ b/src/core/persistence/recovery-version.ts@@ -0,0 +1,46 @@+/**+ * Recovery record versions this binary reads, and the refusal of every other version. A recovery record a newer gbrain+ * wrote (a version not listed here) is refused `recovery_version_unsupported` before any of its fields is read: it is+ * never misread, rewritten (`upgradeRecoveryStaging`), cleared, or its staged files removed, so the binary that wrote it+ * finishes it once this host is upgraded. v0.60.290.0, which predates this check, reads a version 2 withdrawal-mirror+ * record (`after: null`) as a version 1 record and fails every attempt with an untyped TypeError+ * (`effect_unavailable`); `segmented-mirror-gate.ts` keeps this release from writing one while such a binary is seen.+ */+import { opError, type OperationError } from '../ops/contract.ts';+import type { Action } from '../agent-output.ts';++/** `persistence_effects.recovery` (effect-model.ts `EffectRecovery`): 1 embeds the file, 2 names a streamed stage. */+export const EFFECT_RECOVERY_VERSIONS: readonly number[] = [1, 2];+/** `persistence_requests.recovery` (model.ts `RecoveryRecord`): 1 one file, 2 a shared-skill bundle. */+export const REQUEST_RECOVERY_VERSIONS: readonly number[] = [1, 2];++export type RecoveryTable = 'persistence_requests' | 'persistence_effects';+const KNOWN: Record<RecoveryTable, readonly number[]> = { persistence_requests: REQUEST_RECOVERY_VERSIONS, persistence_effects: EFFECT_RECOVERY_VERSIONS };++/** True for a record this binary knows how to recover (an absent record is not refused). */+export function recoveryVersionKnown(table: RecoveryTable, record: unknown): boolean {+ if (record === null || record === undefined) return true;+ const version = (record as { version?: unknown }).version;+ return typeof version === 'number' && KNOWN[table].includes(version);+}++/** The upgrade fix: only a newer gbrain on the canonical owner host reads the record. */+export function recoveryUpgradeFix(sourceId: string | null): Action {+ return { argv: ['gbrain', 'upgrade'], consent: [], actor: 'host_admin', requires_exclusive: false,+ why: 'A newer gbrain wrote this recovery record; only a gbrain that knows its version can finish it.',+ user_message: `Run gbrain upgrade on the host that owns ${sourceId ? `source ${sourceId}'s` : 'the source\'s'} canonical worktree, and restart its serve, sync or worker processes; the upgraded writer finishes the recovery. Do not delete the record or its staged files.`,+ verify: { argv: ['gbrain', 'sources', 'writer', 'status', ...(sourceId ? ['--source', sourceId] : []), '--json'] } };+}++export function recoveryVersionUnsupported(table: RecoveryTable, record: unknown, sourceId: string | null): OperationError {+ const version = JSON.stringify((record as { version?: unknown } | null)?.version ?? null);+ const what = table === 'persistence_effects' ? 'withdrawal-mirror effect' : 'write request';+ return opError('recovery_version_unsupported', `A newer gbrain wrote this ${what}'s recovery record (version ${version}); this gbrain cannot read it.`,+ `The ${what} recovery record${sourceId ? ` of source ${sourceId}` : ''} has version ${version}, which this gbrain does not know, so it left the record, its staged files and the canonical file untouched; writes on that worktree wait for it. Tell the user to upgrade gbrain on the owner host (fix); the upgraded writer finishes the recovery.`,+ { fix: recoveryUpgradeFix(sourceId) });+}++/** Refuses a record of a version this binary does not read; call before reading, rewriting or clearing it. */+export function assertRecoveryVersion(table: RecoveryTable, record: unknown, sourceId: string | null): void {+ if (!recoveryVersionKnown(table, record)) throw recoveryVersionUnsupported(table, record, sourceId);+}diff --git a/src/core/persistence/segmented-mirror-gate.ts b/src/core/persistence/segmented-mirror-gate.tsnew file mode 100644index 0000000000..8dc2c213a7--- /dev/null+++ b/src/core/persistence/segmented-mirror-gate.ts@@ -0,0 +1,87 @@+/**+ * A withdrawal mirror of a page stored in segments writes a version 2 recovery record (effect-model.ts): the file is staged+ * by path and digest, never embedded. A gbrain below SEGMENTED_WRITER_FLOOR cannot read that record: v0.60.290.0 reads it+ * as version 1 (`Buffer.from(record.after)` with `after: null`) and fails every attempt with an untyped TypeError+ * (`effect_unavailable`), retrying every 30 seconds without parking, while the record holds every write and effect on+ * the worktree; it never deletes the record or its stage (recovery-version.ts refuses unknown versions from this release+ * on). That binary cannot be changed, so this one does not write such a record while the segmented-storage writer gate+ * (page-body/limits.ts `segmentedWriterBlockers`, the evidence that keeps `pages.segmented_storage` off, read at most+ * once per SEGMENTED_WRITER_GATE_TTL_MS) sees a writer that cannot read it in its window: the mirror refuses+ * `segmented_mirror_writer_gate` before it streams the file, retries and parks like any failed mirror (writer status and+ * doctor list it), and the file keeps the withdrawn row meanwhile. A version 1 record is no way out: it would hold the+ * whole file in memory and in the record, and v0.60.290.0's recovery of it publishes the file and then refuses forever+ * to materialize a segmented page (`assertInlineBody`). Once the gate clears (the older writer upgraded and outside the+ * window), `resumeGatedMirrors` gives each request whose parked targets all carry this code the one more attempt+ * `gbrain sources writer retry-effects` would authorize.+ */+import type { BrainEngine } from '../engine.ts';+import type { Action } from '../agent-output.ts';+import { opError, type OperationError } from '../ops/contract.ts';+import { SEGMENTED_WRITER_GATE_TTL_MS, SEGMENTED_WRITER_WINDOW_DAYS, segmentedWriterBlockers } from '../page-body/limits.ts';+import type { PersistenceEffect } from './effect-model.ts';+import type { SegmentedGateWriter } from './writer-versions.ts';++export const SEGMENTED_MIRROR_GATE_CODE = 'segmented_mirror_writer_gate';+const SAMPLE = 5;++function gateFix(hosts: string[]): Action {+ return { argv: ['gbrain', 'upgrade'], consent: [], actor: 'host_admin', requires_exclusive: false,+ why: 'A gbrain that cannot read a large page\'s withdrawal-mirror recovery record wrote to this brain recently, so the mirror waits instead of leaving a record that binary would wedge on.',+ user_message: `Run gbrain upgrade on ${hosts.join('; ')}, and restart its serve, sync or worker processes. The hold clears ${SEGMENTED_WRITER_WINDOW_DAYS} days after the last write of an older gbrain (gbrain doctor's segmented_storage check names when); the parked mirror then runs again by itself.`,+ verify: { argv: ['gbrain', 'doctor', '--json'] } };+}++export function segmentedMirrorWriterGate(effect: Pick<PersistenceEffect, 'source_id'>, slug: string, blockers: SegmentedGateWriter[]): OperationError {+ const byHost = new Map<string, SegmentedGateWriter>();+ for (const row of blockers) {+ const key = row.host_id ?? 'an unidentified host';+ const seen = byHost.get(key);+ if (!seen || (row.last_seen ?? '') > (seen.last_seen ?? '')) byHost.set(key, row);+ }+ const hosts = [...byHost].slice(0, SAMPLE).map(([host, row]) => `host ${host} (${row.version_label}, ${row.principal}, last ${row.last_seen ?? 'unknown'})`);+ const more = byHost.size > SAMPLE ? ` and ${byHost.size - SAMPLE} more` : '';+ return opError(SEGMENTED_MIRROR_GATE_CODE, 'The withdrawal mirror of a page stored in segments waits for older gbrain writers to be upgraded.',+ `Page ${slug} in source ${effect.source_id} is stored in segments, and a gbrain that cannot read the recovery record its mirror writes wrote here in the last ${SEGMENTED_WRITER_WINDOW_DAYS} days: ${hosts.join('; ')}${more}. The withdrawal is committed and nothing was staged; the canonical file keeps the withdrawn row until the mirror runs. Tell the user to upgrade those hosts (fix); the mirror retries, parks, and resumes by itself once the hold clears.`,+ { fix: gateFix([...hosts, ...(more ? [more.trim()] : [])]) });+}++/** Refuses the mirror of a segmented page while the writer gate sees a writer that cannot read its version 2 record. */+export async function assertSegmentedMirrorGate(engine: BrainEngine, effect: PersistenceEffect, slug: string): Promise<void> {+ const blockers = await segmentedWriterBlockers(engine);+ if (blockers.length) throw segmentedMirrorWriterGate(effect, slug, blockers);+}++let lastResume = new WeakMap<object, number>();+/** Test seam: forget when parked gated mirrors were last looked for. */+export function _resetGatedMirrorResumeForTests(): void { lastResume = new WeakMap(); }++/**+ * Once the writer gate is clear, requeues (through `retryParkedEffects`, with its authority, claim and recovery checks)+ * up to 100 requests on worktrees this host owns whose every parked target was parked by the gate. Looked for at most+ * once per SEGMENTED_WRITER_GATE_TTL_MS per engine; never throws, so an effect pass is never stopped by it.+ */+export async function resumeGatedMirrors(engine: BrainEngine, hostId: string): Promise<number> {+ const last = lastResume.get(engine);+ if (last !== undefined && Date.now() - last < SEGMENTED_WRITER_GATE_TTL_MS) return 0;+ lastResume.set(engine, Date.now());+ let requeued = 0;+ try {+ const requests = await engine.executeRaw<{ id: string; source_id: string; request_id: string }>(+ `SELECT DISTINCT r.id::text AS id,r.source_id,r.request_id::text AS request_id FROM persistence_effects e+ JOIN persistence_requests r ON r.id=e.request_id JOIN persistence_worktrees w ON w.id=e.worktree_id+ WHERE e.kind='withdrawal-mirror' AND e.state='failed' AND e.error_code='targets_parked' AND w.owner_host_id=$1::uuid+ AND e.data->'parked' @> $2::text::jsonb+ AND NOT EXISTS (SELECT 1 FROM persistence_effects o CROSS JOIN LATERAL jsonb_array_elements(COALESCE(o.data->'parked','[]'::jsonb)) AS p(target)+ WHERE o.request_id=e.request_id AND o.state<>'committed' AND COALESCE(p.target->>'error_code','')<>$3)+ LIMIT 100`, [hostId, JSON.stringify([{ error_code: SEGMENTED_MIRROR_GATE_CODE }]), SEGMENTED_MIRROR_GATE_CODE]);+ if (!requests.length || (await segmentedWriterBlockers(engine)).length) return 0;+ const { retryParkedEffects } = await import('./effect-retry.ts');+ for (const request of requests) {+ try {+ const result = await retryParkedEffects(engine, request.source_id, request.request_id, false, { internalId: request.id });+ if ((result?.effects as { action?: string }[] | undefined)?.some(effect => effect.action === 'retry_queued')) requeued++;+ } catch { /* refused (authority, claim, host identity): it stays parked with its retry command */ }+ }+ } catch { /* the parked effects keep their retry commands */ }+ return requeued;+}diff --git a/src/core/persistence/staging.ts b/src/core/persistence/staging.tsindex 038a23a6fd..1e8fbd8364 100644--- a/src/core/persistence/staging.ts+++ b/src/core/persistence/staging.ts@@ -9,6 +9,7 @@ import type { BrainEngine } from '../engine.ts';import { readJournalLimits } from './limits.ts';import { beforeStageCopyPath, hashDescriptor, streamingStagePath, validateBeforeStagePath } from './large-file.ts';import { declarePersistenceProtocol } from './protocol.ts';+import { assertRecoveryVersion } from './recovery-version.ts';export interface RecoveryStagingFile { path: string; hash: string; bytes: number }/**@@ -181,7 +182,7 @@ function upgradeFileStaging(record: StoredFileRecovery, mode: 'restore' | 'forwareturn changed ? { ...record, staging } : record;}-/** Old records remain readable; reserve new names before an old recovery writes. */+/** Old records remain readable; reserve new names before an old recovery writes. A newer record is refused unchanged (recovery-version.ts). */export async function upgradeRecoveryStaging(engine: BrainEngine, table: 'persistence_requests' | 'persistence_effects',id: string | number, worktreeId: string, mode: 'restore' | 'forward'): Promise<void> {const limits = await readJournalLimits(engine);@@ -190,9 +191,10 @@ export async function upgradeRecoveryStaging(engine: BrainEngine, table: 'persisawait declarePersistenceProtocol(tx);await tx.executeRaw("SELECT set_config('synchronous_commit','on',true),set_config('lock_timeout','1s',true),set_config('statement_timeout','5s',true)");const counters = await lockCounters(tx, ['brain', `worktree:${worktreeId}`]);- const [row] = await tx.executeRaw<{ recovery_bytes: number | string; recovery: StoredRecovery | null }>(- `SELECT recovery,recovery_bytes FROM ${table} WHERE id=$1 FOR UPDATE`, [id]);+ const [row] = await tx.executeRaw<{ recovery_bytes: number | string; recovery: StoredRecovery | null; source_id: string }>(+ `SELECT recovery,recovery_bytes,source_id FROM ${table} WHERE id=$1 FOR UPDATE`, [id]);if (!row?.recovery) return;+ assertRecoveryVersion(table, row.recovery, row.source_id);const record = row.recovery;const prior = 'files' in record ? record.files : [record];const files = prior.map(file => upgradeFileStaging(file, mode));diff --git a/test/pathological/lp-d-recovery-version.test.ts b/test/pathological/lp-d-recovery-version.test.tsnew file mode 100644index 0000000000..afb64c12a2--- /dev/null+++ b/test/pathological/lp-d-recovery-version.test.ts@@ -0,0 +1,155 @@+/**+ * LPH (d) part 1: a recovery record of a version this gbrain does not know is refused, never misread.+ *+ * 1. Protects: a withdrawal-mirror effect recovery record (persistence_effects.recovery) or a write request recovery+ * record (persistence_requests.recovery) whose `version` this binary does not know (a synthetic version 3, as a+ * future release could write) is refused `recovery_version_unsupported` with fix.next `tell_user_to_run`+ * `gbrain upgrade`, before anything reads it: the record stays byte for byte, its streamed stage stays on disk with+ * its bytes, the canonical file keeps its bytes, nothing is cleared and the effect keeps retrying (never parks). The+ * head blocker names it as needing intervention with the same upgrade fix.+ * 2. Fails when: recovery reads a version 3 record as version 1 (it embeds `after`, so the old reading removes the+ * stage, publishes the embedded bytes and clears the record) or as anything else, `upgradeRecoveryStaging` rewrites an+ * unknown request record's staging, or the refusal is untyped (`recovery_required`, `effect_unavailable`, a bare Error).+ * 3. PGLite always; PostgreSQL when DATABASE_URL is set. The record is written by the real segmented mirror (crash+ * modelled at the `effect_recovery:staged` seam, where the hook rewrites the record's version while this pass still+ * holds the worktree lock), so the stage, the reservation and the binding are real.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { createHash, randomUUID } from 'node:crypto';+import { existsSync, readFileSync } from 'node:fs';+import { cliRenderContext, renderAction } from '../../src/core/agent-output.ts';+import { OperationError } from '../../src/core/ops/contract.ts';+import { recoverEffectPublication } from '../../src/core/persistence/effect-recovery.ts';+import { runPersistenceEffects } from '../../src/core/persistence/effects.ts';+import { installFaultHook } from '../../src/core/persistence/fault-points.ts';+import { headBlockerAction } from '../../src/core/persistence/head-blocker.ts';+import { localHostId } from '../../src/core/persistence/identity.ts';+import { clearResolvedRecovery } from '../../src/core/persistence/journal.ts';+import { recoveryFiles } from '../../src/core/persistence/model.ts';+import { upgradeRecoveryStaging } from '../../src/core/persistence/staging.ts';+import { openTwinBrain, type TwinBrain } from '../helpers/segmented-twins.ts';+import { fileOf, settle } from '../helpers/segmented-withdrawal.ts';+import { testBackends } from '../helpers/test-backends.ts';+import { waitFor } from '../helpers/wait-for.ts';+import { withEnv } from '../helpers/with-env.ts';++const SEGMENTED = 'people/sei-example';+const CLAIM = 'Twin Example vault code is 4401';+const KEPT = 'Twin Example adopted a narwhalbot';+const sha = (bytes: Buffer) => createHash('sha256').update(bytes).digest('hex');+const json = (value: unknown) => typeof value === 'string' ? JSON.parse(value) : value;++function expectUpgradeRefusal(error: unknown) {+ expect(error).toBeInstanceOf(OperationError);+ const refusal = error as OperationError;+ expect(refusal.code).toBe('recovery_version_unsupported');+ expect(refusal.fix?.argv).toEqual(['gbrain', 'upgrade']);+ expect(renderAction(refusal.fix!, cliRenderContext()).next).toBe('tell_user_to_run');+}++for (const kind of testBackends()) {+ describe(kind + ': a recovery record of an unknown version is refused, never misread', () => {+ let brain: TwinBrain;++ beforeAll(async () => {+ brain = await openTwinBrain(kind, [], async seed => { await seed.setSwitch(true); await seed.put(SEGMENTED, 1_100_000); });+ brain.setChatReply(JSON.stringify({ facts: [CLAIM, KEPT].map(fact => ({ fact, kind: 'fact', entity: SEGMENTED, confidence: 1, notability: 'high' })) }));+ expect(await brain.call('extract_facts', { turn_text: 'Synthetic meeting record. ' + CLAIM + '. ' + KEPT + '.', visibility: 'world', valid_from: '2026-10-15T00:00:00Z' }, SEGMENTED))+ .toMatchObject({ inserted: 2 });+ expect(await brain.storageOf(SEGMENTED)).toBe('segmented');+ await settle(brain, kind);+ }, 600_000);++ afterAll(() => { installFaultHook(undefined); return brain.close(); }, 120_000);++ test('a version 3 withdrawal-mirror record keeps its bytes, its stage and the file; the effect retries with recovery_version_unsupported', async () => {+ const file = fileOf(brain, SEGMENTED);+ const before = readFileSync(file);+ expect(before.toString('utf8')).toContain(CLAIM);+ // At the staged seam the version 2 record and its stage are durable; the hook turns the record into a version 3 one+ // that also embeds the staged bytes as `after` (a layout a version 1 reader would act on), then the pass "crashes".+ let written: any = null;+ let effectId = '';+ installFaultHook(async (point, detail) => {+ if (point !== 'effect_recovery:staged' || written) return;+ const [row] = await brain.engine.executeRaw<{ recovery: unknown }>('SELECT recovery FROM persistence_effects WHERE id=$1', [detail.effectId]);+ const v2 = json(row!.recovery);+ expect(v2).toMatchObject({ version: 2, after: null });+ effectId = String(detail.effectId);+ written = { ...v2, version: 3, after: readFileSync(v2.staging.publication.path).toString('base64'), next: { layout: 'future' } };+ await brain.engine.executeRaw('UPDATE persistence_effects SET recovery=$2::text::jsonb WHERE id=$1', [detail.effectId, JSON.stringify(written)]);+ throw new Error('modelled crash after the stage was written');+ });+ const [fact] = await brain.engine.executeRaw<{ id: number }>('SELECT id FROM facts WHERE source_id=$1 AND source_markdown_slug=$2 AND fact=$3', [brain.sourceId, SEGMENTED, CLAIM]);+ const dry = await brain.call('purge_fact', { id: Number(fact!.id), dry_run: true }, SEGMENTED);+ expect((await brain.call('purge_fact', { id: Number(fact!.id), confirm: dry.confirm_token, expected_revision: dry.expected_revision, request_id: randomUUID() }, SEGMENTED)).state).toBe('committed');+ const pass = () => withEnv(brain.env(), async () => {+ await brain.engine.executeRaw(`UPDATE persistence_effects SET next_attempt_at=now() WHERE source_id=$1 AND state='queued'`, [brain.sourceId]);+ await runPersistenceEffects(brain.engine, { engine: kind, embedding_disabled: true } as never, { hostId: localHostId(), limit: 20 });+ });+ try {+ // The resident consumer may hold the mirror's claim; passes run until one of them reaches the seam.+ await waitFor(async () => { if (!written) await pass(); return written !== null; }, { timeoutMs: 120_000, intervalMs: 100, label: 'the mirror reached the staged seam' });+ const counters = await brain.engine.executeRaw<{ key: string; bytes: string }>('SELECT key, recovery_bytes::text AS bytes FROM persistence_counters ORDER BY key');+ // Recovery attempts after the crash, more than PARK_AFTER_FAILURES of them, by this process or the resident consumer.+ const read = async () => (await brain.engine.executeRaw<{ id: string; state: string; error_code: string | null; recovery: unknown; data: any; attempts: number }>(+ 'SELECT id::text AS id, state, error_code, recovery, data, attempts FROM persistence_effects WHERE id=$1', [effectId]))[0]!;+ const start = (await read()).attempts;+ // A reader that misreads the record may clear it; the wait ends then too, and the assertions below say so.+ await waitFor(async () => { await pass(); const row = await read(); return !row.recovery || row.attempts >= start + 7; }, { timeoutMs: 120_000, intervalMs: 100, label: 'seven recovery attempts' });+ await waitFor(async () => (await read()).state !== 'running', { timeoutMs: 30_000, label: 'the effect released' });+ const effect = await read();+ // Untouched: the record (byte for byte), its stage, the canonical file and the reserved capacity.+ expect(json(effect!.recovery)).toEqual(written);+ expect(existsSync(written.staging.publication.path)).toBe(true);+ expect(sha(readFileSync(written.staging.publication.path))).toBe(written.staging.publication.hash);+ expect(readFileSync(file).equals(before)).toBe(true);+ expect(await brain.engine.executeRaw<{ key: string; bytes: string }>('SELECT key, recovery_bytes::text AS bytes FROM persistence_counters ORDER BY key')).toEqual(counters);+ // Typed and retrying: the effect is queued with the code, never parked.+ expect(effect!.error_code).toBe('recovery_version_unsupported');+ expect(effect!.state).toBe('queued');+ expect(json(effect!.data).parked ?? []).toEqual([]);++ // The refusal itself, as the recovery worker meets it.+ const [claimed] = await brain.engine.executeRaw<any>(`UPDATE persistence_effects SET state='running',execution_token=$2::uuid,claim_expires_at=now()+interval '2 minutes'+ WHERE id=$1 RETURNING *`, [effect!.id, randomUUID()]);+ const refused = await withEnv(brain.env(), () => recoverEffectPublication(brain.engine, claimed, localHostId())).then(() => null, error => error);+ expectUpgradeRefusal(refused);+ expect(json((await brain.engine.executeRaw<{ recovery: unknown }>('SELECT recovery FROM persistence_effects WHERE id=$1', [effect!.id]))[0]!.recovery)).toEqual(written);+ await brain.engine.executeRaw(`UPDATE persistence_effects SET state='queued',execution_token=NULL,claim_expires_at=NULL WHERE id=$1`, [effect!.id]);++ // The head blocker's exit for it is the same upgrade, told to the user.+ const action = headBlockerAction({ predicate: 'effect_recovery', ids: [effect!.id], state: 'recovery_version_unsupported', owner: null, intervention: true }, brain.sourceId, `gbrain sync --source ${brain.sourceId}`);+ expect(action.argv).toEqual(['gbrain', 'upgrade']);+ expect(renderAction(action, cliRenderContext()).next).toBe('tell_user_to_run');+ } finally { installFaultHook(undefined); }+ }, 600_000);++ test('a version 3 write request recovery record is refused by staging upgrade, file listing and clearing, and left as it is', async () => {+ const [request] = await brain.engine.executeRaw<{ id: string; worktree_id: string }>(+ `SELECT id::text AS id, worktree_id::text AS worktree_id FROM persistence_requests WHERE source_id=$1 AND state='committed' AND worktree_id IS NOT NULL ORDER BY sequence DESC LIMIT 1`, [brain.sourceId]);+ // No staging: a version 1 reader's upgradeRecoveryStaging would allocate a restoration stage from `before` and rewrite the record.+ const record = { version: 3, path: fileOf(brain, SEGMENTED), root: brain.root, before: Buffer.from('prior bytes').toString('base64'), beforeHash: sha(Buffer.from('prior bytes')),+ afterHash: sha(readFileSync(fileOf(brain, SEGMENTED))), mode: null, ownerEpoch: '1', attempt: randomUUID(), next: { layout: 'future' } };+ // The request protocol trigger admits only the record shapes this schema knows; a newer gbrain's would come with its+ // own schema, so the trigger is set aside for this one write (replica role) to model that brain.+ const unguarded = (sql: string, params: unknown[]) => brain.engine.transaction(async tx => {+ await tx.executeRaw("SET LOCAL session_replication_role = 'replica'");+ await tx.executeRaw(sql, params);+ });+ await unguarded('UPDATE persistence_requests SET recovery=$2::text::jsonb WHERE id=$1::uuid', [request!.id, JSON.stringify(record)]);+ const stored = async () => json((await brain.engine.executeRaw<{ recovery: unknown }>('SELECT recovery FROM persistence_requests WHERE id=$1::uuid', [request!.id]))[0]!.recovery);+ try {+ expectUpgradeRefusal(await upgradeRecoveryStaging(brain.engine, 'persistence_requests', request!.id, request!.worktree_id, 'restore').then(() => null, error => error));+ expect(await stored()).toEqual(record);+ let listed: unknown = null;+ try { recoveryFiles(record as never); } catch (error) { listed = error; }+ expectUpgradeRefusal(listed);+ expectUpgradeRefusal(await clearResolvedRecovery(brain.engine, request!.id).then(() => null, error => error));+ expect(await stored()).toEqual(record);+ } finally {+ await unguarded('UPDATE persistence_requests SET recovery=NULL WHERE id=$1::uuid', [request!.id]);+ }+ }, 120_000);+ });+}diff --git a/test/pathological/lp-d-segmented-mirror-gate.test.ts b/test/pathological/lp-d-segmented-mirror-gate.test.tsnew file mode 100644index 0000000000..95d710ccc8--- /dev/null+++ b/test/pathological/lp-d-segmented-mirror-gate.test.ts@@ -0,0 +1,131 @@+/**+ * LPH (d) part 2: no version 2 withdrawal-mirror record while a gbrain that cannot read one may claim it.+ *+ * 1. Protects: while the segmented-storage writer gate sees a writer below SEGMENTED_WRITER_FLOOR in its 7-day window (an+ * import run of v0.60.290.0, which reads a version 2 record's `after: null` as a version 1 record and wedges the+ * worktree), a withdrawal on a segmented, file-backed page commits but its mirror writes no recovery record and stages+ * nothing: it refuses `segmented_mirror_writer_gate` (fix.next `tell_user_to_run` `gbrain upgrade`, naming the host),+ * retries, and parks after PARK_AFTER_FAILURES attempts like any failed mirror, so writes on the worktree are not held;+ * the canonical file keeps the withdrawn row meanwhile. The gate is read from its TTL cache, not once per attempt. Once+ * the older writer is outside the window, the parked mirror runs again by itself and the file loses the row.+ * 2. Fails when: the mirror stages a version 2 record while the gate holds (master), the hold never parks or parks without+ * its code, the gate is read per attempt, or the parked mirror never resumes after the gate clears.+ * 3. PGLite always; PostgreSQL when DATABASE_URL is set. The older writer is an ingest_log row stamped v0.60.290.0 with the+ * segment-reader mark, as test/large-pages/segmented-switch.test.ts seeds the doctor segmented_storage cases.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { readFileSync } from 'node:fs';+import { cliRenderContext, renderAction } from '../../src/core/agent-output.ts';+import { OperationError } from '../../src/core/ops/contract.ts';+import { SEGMENTED_WRITER_FLOOR } from '../../src/core/page-body/writer-floor.ts';+import { _resetSegmentedWriterGateForTests, segmentedWriterGateWork } from '../../src/core/page-body/limits.ts';+import { runPersistenceEffects } from '../../src/core/persistence/effects.ts';+import { PARK_AFTER_FAILURES } from '../../src/core/persistence/effect-model.ts';+import { installFaultHook } from '../../src/core/persistence/fault-points.ts';+import { localHostId } from '../../src/core/persistence/identity.ts';+import { _resetGatedMirrorResumeForTests, assertSegmentedMirrorGate } from '../../src/core/persistence/segmented-mirror-gate.ts';+import { compareWriterVersions } from '../../src/core/persistence/writer-versions.ts';+import { openTwinBrain, type TwinBrain } from '../helpers/segmented-twins.ts';+import { exported, fileOf, settle } from '../helpers/segmented-withdrawal.ts';+import { testBackends } from '../helpers/test-backends.ts';+import { waitFor } from '../helpers/wait-for.ts';+import { withEnv } from '../helpers/with-env.ts';++const SEGMENTED = 'people/sei-example';+const CLAIM = 'Twin Example vault code is 5510';+const KEPT = 'Twin Example adopted a narwhalbot';+const OLDER = '0.60.290.0';+const json = (value: unknown) => typeof value === 'string' ? JSON.parse(value) : value;++for (const kind of testBackends()) {+ describe(kind + ': a segmented mirror holds while an older gbrain could claim its recovery record', () => {+ let brain: TwinBrain;+ const oldHost = randomUUID();++ beforeAll(async () => {+ brain = await openTwinBrain(kind, [], async seed => { await seed.setSwitch(true); await seed.put(SEGMENTED, 1_100_000); });+ brain.setChatReply(JSON.stringify({ facts: [CLAIM, KEPT].map(fact => ({ fact, kind: 'fact', entity: SEGMENTED, confidence: 1, notability: 'high' })) }));+ expect(await brain.call('extract_facts', { turn_text: 'Synthetic meeting record. ' + CLAIM + '. ' + KEPT + '.', visibility: 'world', valid_from: '2026-10-15T00:00:00Z' }, SEGMENTED))+ .toMatchObject({ inserted: 2 });+ expect(await brain.storageOf(SEGMENTED)).toBe('segmented');+ await settle(brain, kind);+ }, 600_000);++ afterAll(() => { installFaultHook(undefined); return brain.close(); }, 120_000);++ test('the mirror writes no version 2 record, parks with segmented_mirror_writer_gate, and resumes once the older writer ages out', async () => {+ expect(compareWriterVersions(OLDER, SEGMENTED_WRITER_FLOOR)).toBeLessThan(0);+ await brain.engine.executeRaw(`INSERT INTO ingest_log (source_id, source_type, source_ref, pages_updated, summary, writer_version, writer_host_id, writer_segment_reader, created_at)+ VALUES ($1, 'import', 'lp-d-older-writer', '[]'::jsonb, 'run', $2, $3::uuid, true, now() - interval '1 hour')`, [brain.sourceId, OLDER, oldHost]);+ _resetSegmentedWriterGateForTests();+ _resetGatedMirrorResumeForTests();+ const file = fileOf(brain, SEGMENTED);+ const before = readFileSync(file);+ expect(before.toString('utf8')).toContain(CLAIM);++ // Every recovery record the mirror reserves passes the before_stage seam; none may be reserved while the gate holds.+ const reserved: unknown[] = [];+ installFaultHook(async (point, detail) => {+ if (point !== 'effect_recovery:before_stage') return;+ const [row] = await brain.engine.executeRaw<{ recovery: unknown }>('SELECT recovery FROM persistence_effects WHERE id=$1', [detail.effectId]);+ reserved.push(json(row?.recovery));+ });+ const reads = segmentedWriterGateWork.reads;+ const [fact] = await brain.engine.executeRaw<{ id: number }>('SELECT id FROM facts WHERE source_id=$1 AND source_markdown_slug=$2 AND fact=$3', [brain.sourceId, SEGMENTED, CLAIM]);+ const dry = await brain.call('purge_fact', { id: Number(fact!.id), dry_run: true }, SEGMENTED);+ const requestId = randomUUID();+ expect((await brain.call('purge_fact', { id: Number(fact!.id), confirm: dry.confirm_token, expected_revision: dry.expected_revision, request_id: requestId }, SEGMENTED)).state).toBe('committed');+ const mirror = async () => (await brain.engine.executeRaw<{ state: string; error_code: string | null; recovery: unknown; data: any; attempts: number }>(+ `SELECT e.state, e.error_code, e.recovery, e.data, e.attempts FROM persistence_effects e JOIN persistence_requests r ON r.id=e.request_id+ WHERE r.request_id=$1::uuid AND e.kind='withdrawal-mirror'`, [requestId]))[0]!;+ const pass = () => withEnv(brain.env(), async () => {+ await brain.engine.executeRaw(`UPDATE persistence_effects SET next_attempt_at=now() WHERE source_id=$1 AND state='queued'`, [brain.sourceId]);+ await runPersistenceEffects(brain.engine, { engine: kind, embedding_disabled: true } as never, { hostId: localHostId(), limit: 20 });+ });+ try {+ const recordsSeen: unknown[] = [];+ await waitFor(async () => {+ await pass();+ const row = await mirror();+ if (row.recovery) recordsSeen.push(json(row.recovery));+ return row.state === 'failed' || row.state === 'committed';+ }, { timeoutMs: 120_000, intervalMs: 100, label: 'the mirror parked or committed' });+ const held = await mirror();+ // No record was reserved or seen, nothing was staged, and the file still holds the purged claim.+ expect(reserved).toEqual([]);+ expect(recordsSeen).toEqual([]);+ expect(held.recovery).toBeNull();+ expect(readFileSync(file).equals(before)).toBe(true);+ // Parked like any failed mirror after its attempts, with the gate's code on the target.+ expect(held.state).toBe('failed');+ expect(held.error_code).toBe('targets_parked');+ expect(json(held.data).parked).toEqual([{ slug: SEGMENTED, error_code: 'segmented_mirror_writer_gate' }]);+ expect(held.attempts).toBeGreaterThanOrEqual(PARK_AFTER_FAILURES);+ // The gate was read from its cache: at most once for all of those attempts.+ expect(segmentedWriterGateWork.reads - reads).toBeLessThanOrEqual(1);+ // Its refusal names the older host and tells the user to upgrade it.+ const refusal = await assertSegmentedMirrorGate(brain.engine, { source_id: brain.sourceId } as never, SEGMENTED).then(() => null, error => error);+ expect(refusal).toBeInstanceOf(OperationError);+ expect((refusal as OperationError).code).toBe('segmented_mirror_writer_gate');+ expect((refusal as OperationError).suggestion).toContain(oldHost);+ expect((refusal as OperationError).fix?.argv).toEqual(['gbrain', 'upgrade']);+ expect((refusal as OperationError).fix?.user_message).toContain(oldHost);+ expect(renderAction((refusal as OperationError).fix!, cliRenderContext()).next).toBe('tell_user_to_run');++ // The older writer ages out of the window: the parked mirror runs again by itself and the file loses the row.+ await brain.engine.executeRaw(`UPDATE ingest_log SET created_at=now() - interval '8 days' WHERE source_ref='lp-d-older-writer'`);+ _resetSegmentedWriterGateForTests();+ _resetGatedMirrorResumeForTests();+ await waitFor(async () => { await pass(); return (await mirror()).state === 'committed'; }, { timeoutMs: 120_000, intervalMs: 100, label: 'the mirror resumed and committed' });+ await settle(brain, kind);+ const after = readFileSync(file);+ expect(after.toString('utf8')).not.toContain(CLAIM);+ expect(after.toString('utf8')).toContain(KEPT);+ expect(after.equals(await exported(brain, SEGMENTED))).toBe(true);+ expect(reserved).toHaveLength(1);+ expect(reserved[0]).toMatchObject({ version: 2, after: null });+ } finally { installFaultHook(undefined); }+ }, 600_000);+ });+}diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txtindex 36e1413f6a..63c2589928 100644--- a/test/postgres-unit-arms.txt+++ b/test/postgres-unit-arms.txt@@ -254,6 +254,8 @@ test/pathological/b-9-enrich-retired-alias.test.tstest/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/lp-d-recovery-version.test.ts+test/pathological/lp-d-segmented-mirror-gate.test.tstest/persistence-background-pause.test.tstest/persistence-bounded-read-session.test.tstest/persistence-capacity-forecast.test.ts