Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(persistence): segmented mirror gate holds only on live older writers, sharing doctor segmented_storage classification (LPH d)

garrytanb0ab44d322c2
diff --git a/docs/architecture/key-files/core-persistence-request-indexes.md b/docs/architecture/key-files/core-persistence-request-indexes.md
index 20ee85ba11..6be827a0ff 100644
--- a/docs/architecture/key-files/core-persistence-request-indexes.md
+++ b/docs/architecture/key-files/core-persistence-request-indexes.md
@@ -8,4 +8,4 @@ The online-built request-table indexes (the managed sync checkpoint pair, the pa
- `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. 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).
+- `src/core/persistence/{recovery-version,segmented-mirror-gate,segmented-gate-hold}.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 `mirrorGateBlockers` sees a live writer below SEGMENTED_WRITER_FLOOR (the switch's TTL-cached `segmentedWriterBlockers`, filtered by `segmented-gate-hold.ts` `liveSegmentedBlockers`, the classification doctor `segmented_storage` uses: this host's own pre-upgrade writes superseded by the same kind of write from this build are not live; cached per gate read and host) 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.md
index d7b9c5fd3b..7f25025b15 100644
--- a/docs/guides/error-codes.md
+++ b/docs/guides/error-codes.md
@@ -3250,7 +3250,7 @@ More: [docs/guides/google-connect.md#troubleshooting](../../docs/guides/google-c
| 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 |
+| A withdrawal mirror of a page stored in segments waits because a gbrain that cannot read its recovery record, and that doctor segmented_storage still warns about, 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 live writer (this host's own pre-upgrade writes, superseded by the upgraded build, do not count). 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)
diff --git a/docs/guides/troubleshooting.md b/docs/guides/troubleshooting.md
index 68c4189559..0572ea3857 100644
--- a/docs/guides/troubleshooting.md
+++ b/docs/guides/troubleshooting.md
@@ -12,7 +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 |
+| 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 a doctor `segmented_storage` warning names (for `recovery_version_unsupported`, the owner host; doctor's information case, this host's own superseded pre-upgrade writes, does not hold the mirror), 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.md
index 260652200e..0789d860e6 100644
--- a/docs/guides/write-refusals.md
+++ b/docs/guides/write-refusals.md
@@ -76,7 +76,7 @@ of making a duplicate.
| <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. |
+| <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 that doctor `segmented_storage` still warns about wrote to the brain in the last 7 days: another host, an older `serve` or worker still running on this host, or an older write this build has not matched (doctor names the host and when the hold clears). This host's own writes from before it upgraded, once the upgraded build has made the same kind of write after them (doctor's information case), keep `pages.segmented_storage` off but do not hold the mirror. 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. |
diff --git a/llms-full.txt b/llms-full.txt
index a937b5f91c..099bf36fd0 100644
--- a/llms-full.txt
+++ b/llms-full.txt
@@ -10645,7 +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 |
+| 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 a doctor `segmented_storage` warning names (for `recovery_version_unsupported`, the owner host; doctor's information case, this host's own superseded pre-upgrade writes, does not hold the mirror), 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/commands/doctor/checks/segmented-storage.ts b/src/commands/doctor/checks/segmented-storage.ts
index 2f6c8204ff..6111e35f27 100644
--- a/src/commands/doctor/checks/segmented-storage.ts
+++ b/src/commands/doctor/checks/segmented-storage.ts
@@ -3,9 +3,8 @@ import type { Check } from '../../doctor.ts';
import { agentFix, checkError, doctorVerify, infoCheck } from '../check-fix.ts';
import { PAGE_BODY_CONFIG_KEYS, parseSegmentedStorage, readPageBodyPolicy, segmentedWriterBlockers, SEGMENTED_WRITER_WINDOW_DAYS } from '../../../core/page-body/limits.ts';
import { SEGMENTED_WRITER_FLOOR } from '../../../core/page-body/writer-floor.ts';
-import { compareWriterVersions, segmentedGateEvidence, writerVersionBelowFloor } from '../../../core/persistence/writer-versions.ts';
import { existingLocalHostId } from '../../../core/persistence/identity.ts';
-import { CONSUMER_PURGE_MS } from '../../../core/persistence/consumer-heartbeat.ts';
+import { liveSegmentedBlockers } from '../../../core/persistence/segmented-gate-hold.ts';
import { VERSION } from '../../../version.ts';
const name = 'segmented_storage';
@@ -18,11 +17,9 @@ const enableFix = (why: string) => agentFix(['gbrain', 'config', 'set', PAGE_BOD
* the last seven days that do not read segmented pages and keep it off (`segmentedGateWriters`: managed requests,
* ingest-log runs and resident consumers without the segment-reader mark, or stamped below SEGMENTED_WRITER_FLOOR).
* While it is off, pages over 1 MiB are written inline up to 24 MiB; stored segmented pages stay readable. A hold left
- * only by this host's own writes from before it upgraded is information with its clear time, not an upgrade fix: this
- * build is at or above the floor, no older process of this host still renews its heartbeat, and for each blocker this
- * host has since written the same kind of write (role and principal) with a build that passes the gate, every write of
- * the blocker coming before the first of those. Otherwise the rows may be a second older gbrain on this host (a cron
- * job, an npx run, a pinned install), which keeps the warning and the upgrade fix.
+ * only by this host's own writes from before it upgraded (no live blocker, persistence/segmented-gate-hold.ts
+ * `liveSegmentedBlockers`) is information with its clear time, not an upgrade fix; any live blocker keeps the warning
+ * and the upgrade fix.
*/
export async function segmentedStorageCheck(engine: BrainEngine): Promise<Check> {
try {
@@ -38,20 +35,8 @@ export async function segmentedStorageCheck(engine: BrainEngine): Promise<Check>
if (configured === 'invalid') return { name, status: 'warn', details, fix: enableFix('Replaces the unrecognized value with on.'),
message: 'pages.segmented_storage holds an unrecognized value, so segmented page storage is off. Set it to on or off.' };
const hosts = listed.map(row => `host ${row.host_id ?? 'unknown (not recorded)'} (principal ${row.principal}) ${row.role} ${row.version}, last seen ${row.last_seen}`);
- const self = blockers.length && (compareWriterVersions(VERSION, SEGMENTED_WRITER_FLOOR) ?? -1) >= 0 ? existingLocalHostId() : null;
- const ownOnly = self !== null && blockers.every(row => row.host_id === self && row.last_seen !== null
- && (row.role !== 'resident' || Date.now() - Date.parse(row.last_seen) > CONSUMER_PURGE_MS));
- // Per role and principal (an ingest source type, a resident kind, a managed principal), when this host first wrote
- // it with a build that passes the gate. A blocker is pre-upgrade only if this build has written the same kind of
- // write and every one of the blocker's writes came before the first of those: anything else may be a second older
- // gbrain on this host (a cron job, an npx run, a pinned install).
- const passedFirst = new Map<string, number>();
- if (ownOnly) for (const row of await segmentedGateEvidence(engine, SEGMENTED_WRITER_WINDOW_DAYS)) {
- if (row.host_id !== self || !row.segment_reader || !row.first_seen || writerVersionBelowFloor(row.version, SEGMENTED_WRITER_FLOOR)) continue;
- const key = `${row.role}\0${row.principal}`;
- passedFirst.set(key, Math.min(passedFirst.get(key) ?? Infinity, Date.parse(row.first_seen)));
- }
- if (ownOnly && blockers.every(row => Date.parse(row.last_seen!) < (passedFirst.get(`${row.role}\0${row.principal}`) ?? -Infinity))) {
+ const self = blockers.length ? existingLocalHostId() : null;
+ if (blockers.length && !(await liveSegmentedBlockers(engine, blockers, self)).length) {
const clears = new Date(Math.max(...blockers.map(row => Date.parse(row.last_seen!))) + SEGMENTED_WRITER_WINDOW_DAYS * 86_400_000).toISOString();
return infoCheck(name, `Segmented page storage is configured ${configured === 'on' ? 'on' : 'on by default'} but held off until ${clears} by writes this host (${self}) made before it upgraded: ${hosts.join('; ')}${blockers.length > SAMPLE ? ` (first ${SAMPLE} shown)` : ''}. `
+ `This host now runs v${VERSION}, at or above v${SEGMENTED_WRITER_FLOOR}, so nothing needs upgrading; the hold clears ${SEGMENTED_WRITER_WINDOW_DAYS} days after the last of those writes (clears_at), and until then pages over 1 MiB are written inline up to 24 MiB.`,
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index b772c912ea..35682c61a2 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -905,7 +905,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;
{ 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.' },
+ { since: 'TBD', text: 'While a gbrain older than the segmented writer floor (v0.60.290.0 included) that doctor `segmented_storage` still warns about wrote to the brain in the last 7 days (another host, an older `serve` or worker still running on this host, or an older write this build has not matched; doctor names the host), a withdrawal (`forget`, `forget_fact`, `purge_fact`) on a page stored in segments still commits, but its withdrawal mirror no longer writes a version 2 recovery record, which that older gbrain cannot read and would wedge the worktree on. The mirror refuses `segmented_mirror_writer_gate` (its fix names the hosts to upgrade), retries, and parks after five attempts like any failed mirror, so writes on the worktree are not held; the page\'s canonical file keeps the withdrawn row and the withdrawal\'s Git effect waits meanwhile. Once the older writer is upgraded and out of the 7-day window, the parked mirror runs again by itself (checked at most once a minute), rewrites the file and the Git effect commits it. `gbrain sources writer retry-effects` retries it at any time. A hold left only by this host\'s own writes from before it upgraded, which the upgraded gbrain has since superseded with the same kind of write (doctor reports it as information), still keeps new pages inline but does not hold the mirror: an upgraded single-host brain mirrors withdrawals at once.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/error-registry.ts b/src/core/error-registry.ts
index 8d73284ff9..0212b9edfa 100644
--- a/src/core/error-registry.ts
+++ b/src/core/error-registry.ts
@@ -539,7 +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' },
+ 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, and that doctor segmented_storage still warns about, 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 live writer (this host's own pre-upgrade writes, superseded by the upgraded build, do not count). 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/effects.ts b/src/core/persistence/effects.ts
index 97883128ab..6dd13281e8 100644
--- a/src/core/persistence/effects.ts
+++ b/src/core/persistence/effects.ts
@@ -198,7 +198,7 @@ async function mirrorPage(engine: BrainEngine, effect: PersistenceEffect, bindin
await materializeAndAdvance(engine, effect, snapshot, opts.hostId);
return;
}
- if (segmented) await assertSegmentedMirrorGate(engine, effect, snapshot.page.slug);
+ if (segmented) await assertSegmentedMirrorGate(engine, effect, snapshot.page.slug, opts.hostId);
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
diff --git a/src/core/persistence/segmented-gate-hold.ts b/src/core/persistence/segmented-gate-hold.ts
new file mode 100644
index 0000000000..cc6b29f528
--- /dev/null
+++ b/src/core/persistence/segmented-gate-hold.ts
@@ -0,0 +1,33 @@
+/**
+ * Which segmented-storage gate blockers are still live (page-body/limits.ts `segmentedWriterBlockers`). A blocker is
+ * superseded when it is only this host's own write from before it upgraded: this build is at or above
+ * SEGMENTED_WRITER_FLOOR, the blocker is this host's, it is not an older resident process still renewing its heartbeat
+ * (CONSUMER_PURGE_MS), and this host has since made the same kind of write (role and principal: an ingest source type, a
+ * resident kind, a managed principal) with a build that passes the gate, every write of the blocker coming before the
+ * first of those. Anything else may be a second older gbrain (another host, a cron job, an npx run, a pinned install,
+ * an older serve still running here) and stays live. Doctor `segmented_storage` reports a hold with no live blocker as
+ * information and keeps its upgrade warning otherwise; the segmented withdrawal mirror (segmented-mirror-gate.ts) holds
+ * only on live blockers. The pages switch itself still counts every blocker.
+ */
+import { VERSION } from '../../version.ts';
+import { SEGMENTED_WRITER_WINDOW_DAYS } from '../page-body/limits.ts';
+import type { SqlEngine } from './model.ts';
+import { compareWriterVersions, segmentedGateEvidence, writerVersionBelowFloor, type SegmentedGateWriter } from './writer-versions.ts';
+
+/** `blockers` without those that are `self`'s superseded pre-upgrade writes; reads the gate evidence only when one could be. */
+export async function liveSegmentedBlockers(engine: SqlEngine, blockers: SegmentedGateWriter[], self: string | null): Promise<SegmentedGateWriter[]> {
+ if (!blockers.length || self === null) return blockers;
+ const [{ SEGMENTED_WRITER_FLOOR }, { CONSUMER_PURGE_MS }] = await Promise.all([import('../page-body/writer-floor.ts'), import('./consumer-heartbeat.ts')]);
+ if ((compareWriterVersions(VERSION, SEGMENTED_WRITER_FLOOR) ?? -1) < 0) return blockers;
+ const candidates = blockers.filter(row => row.host_id === self && row.last_seen !== null
+ && (row.role !== 'resident' || Date.now() - Date.parse(row.last_seen) > CONSUMER_PURGE_MS));
+ if (!candidates.length) return blockers;
+ const key = (row: SegmentedGateWriter) => `${row.role}\0${row.principal}`;
+ const passedFirst = new Map<string, number>();
+ for (const row of await segmentedGateEvidence(engine, SEGMENTED_WRITER_WINDOW_DAYS)) {
+ if (row.host_id !== self || !row.segment_reader || !row.first_seen || writerVersionBelowFloor(row.version, SEGMENTED_WRITER_FLOOR)) continue;
+ passedFirst.set(key(row), Math.min(passedFirst.get(key(row)) ?? Infinity, Date.parse(row.first_seen)));
+ }
+ const superseded = new Set(candidates.filter(row => Date.parse(row.last_seen!) < (passedFirst.get(key(row)) ?? -Infinity)));
+ return blockers.filter(row => !superseded.has(row));
+}
diff --git a/src/core/persistence/segmented-mirror-gate.ts b/src/core/persistence/segmented-mirror-gate.ts
index 8dc2c213a7..d7c983199c 100644
--- a/src/core/persistence/segmented-mirror-gate.ts
+++ b/src/core/persistence/segmented-mirror-gate.ts
@@ -6,7 +6,8 @@
* 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
+ * once per SEGMENTED_WRITER_GATE_TTL_MS) sees a live writer that cannot read it in its window (segmented-gate-hold.ts:
+ * not this host's own pre-upgrade writes that this build has since superseded, which doctor reports as information): 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
@@ -20,6 +21,7 @@ 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';
+import { liveSegmentedBlockers } from './segmented-gate-hold.ts';
export const SEGMENTED_MIRROR_GATE_CODE = 'segmented_mirror_writer_gate';
const SAMPLE = 5;
@@ -45,15 +47,32 @@ export function segmentedMirrorWriterGate(effect: Pick<PersistenceEffect, 'sourc
{ 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> {
+/** Live blockers per gate read: keyed on the TTL-cached blocker list, so a fresh gate read classifies again. */
+let liveByRead = new WeakMap<SegmentedGateWriter[], Map<string, SegmentedGateWriter[]>>();
+
+/**
+ * The gate blockers that hold the mirror: those doctor `segmented_storage` still warns about (segmented-gate-hold.ts).
+ * This host's own writes from before it upgraded, superseded by the same kind of write from this build, do not.
+ */
+export async function mirrorGateBlockers(engine: BrainEngine, hostId: string): Promise<SegmentedGateWriter[]> {
const blockers = await segmentedWriterBlockers(engine);
+ if (!blockers.length) return blockers;
+ const byHost = liveByRead.get(blockers) ?? new Map<string, SegmentedGateWriter[]>();
+ liveByRead.set(blockers, byHost);
+ let live = byHost.get(hostId);
+ if (!live) byHost.set(hostId, live = await liveSegmentedBlockers(engine, blockers, hostId));
+ return live;
+}
+
+/** Refuses the mirror of a segmented page while a live writer that cannot read its version 2 record may claim it. */
+export async function assertSegmentedMirrorGate(engine: BrainEngine, effect: PersistenceEffect, slug: string, hostId: string): Promise<void> {
+ const blockers = await mirrorGateBlockers(engine, hostId);
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(); }
+export function _resetGatedMirrorResumeForTests(): void { lastResume = new WeakMap(); liveByRead = new WeakMap(); }
/**
* Once the writer gate is clear, requeues (through `retryParkedEffects`, with its authority, claim and recovery checks)
@@ -74,7 +93,7 @@ export async function resumeGatedMirrors(engine: BrainEngine, hostId: string): P
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;
+ if (!requests.length || (await mirrorGateBlockers(engine, hostId)).length) return 0;
const { retryParkedEffects } = await import('./effect-retry.ts');
for (const request of requests) {
try {
diff --git a/test/pathological/lp-d-segmented-mirror-gate.test.ts b/test/pathological/lp-d-segmented-mirror-gate.test.ts
index 95d710ccc8..101bdadc62 100644
--- a/test/pathological/lp-d-segmented-mirror-gate.test.ts
+++ b/test/pathological/lp-d-segmented-mirror-gate.test.ts
@@ -1,31 +1,37 @@
/**
* 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
+ * 1. Protects: while the segmented-storage writer gate sees a live writer below SEGMENTED_WRITER_FLOOR in its 7-day window
+ * (an import run of v0.60.290.0 on another host, 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. A hold left only by this host's own writes from before it upgraded, which the upgraded build has since
+ * superseded with the same kind of write (doctor `segmented_storage` reports it as information), keeps the pages switch
+ * off but does not hold the mirror; an older write from another host on top of it does, and doctor warns again.
+ * 2. Fails when: the mirror stages a version 2 record while a live older writer is seen (master), the hold never parks or
+ * parks without its code, the gate is read per attempt, the parked mirror never resumes after the gate clears, or a
+ * superseded self-hold keeps withdrawn rows in files for its whole window.
+ * 3. PGLite always; PostgreSQL when DATABASE_URL is set. The older writers are ingest_log rows 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 { segmentedStorageCheck } from '../../src/commands/doctor/checks/segmented-storage.ts';
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 { _resetSegmentedWriterGateForTests, readPageBodyPolicy, 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 { VERSION } from '../../src/version.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';
@@ -34,6 +40,8 @@ import { withEnv } from '../helpers/with-env.ts';
const SEGMENTED = 'people/sei-example';
const CLAIM = 'Twin Example vault code is 5510';
+const SELF_CLAIM = 'Twin Example vault code is 5520';
+const OTHER_CLAIM = 'Twin Example vault code is 5530';
const KEPT = 'Twin Example adopted a narwhalbot';
const OLDER = '0.60.290.0';
const json = (value: unknown) => typeof value === 'string' ? JSON.parse(value) : value;
@@ -41,91 +49,137 @@ const json = (value: unknown) => typeof value === 'string' ? JSON.parse(value) :
for (const kind of testBackends()) {
describe(kind + ': a segmented mirror holds while an older gbrain could claim its recovery record', () => {
let brain: TwinBrain;
+ let self = '';
const oldHost = randomUUID();
+ const otherHost = randomUUID();
+ /** Every recovery record the mirror reserves passes the before_stage seam. */
+ const reserved: unknown[] = [];
+
+ const olderRun = (host: string, type: string, ref: string, version: string, ago: string) => 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, $2, $3, '[]'::jsonb, 'run', $4, $5::uuid, true, now() - $6::interval)`, [brain.sourceId, type, ref, version, host, ago]);
+ const resetGate = () => { _resetSegmentedWriterGateForTests(); _resetGatedMirrorResumeForTests(); };
+ 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 });
+ });
+ const mirrorOf = async (requestId: string) => (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]!;
+ /** Purges `claim` and runs effect passes until its mirror parks or commits; returns the request id and any record it held. */
+ const purgeUntilSettled = async (claim: string) => {
+ 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 recordsSeen: unknown[] = [];
+ await waitFor(async () => {
+ await pass();
+ const row = await mirrorOf(requestId);
+ 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' });
+ return { requestId, recordsSeen };
+ };
+ const doctor = () => withEnv(brain.env(), () => segmentedStorageCheck(brain.engine));
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 });
+ const facts = [CLAIM, SELF_CLAIM, OTHER_CLAIM, KEPT];
+ brain.setChatReply(JSON.stringify({ facts: facts.map(fact => ({ fact, kind: 'fact', entity: SEGMENTED, confidence: 1, notability: 'high' })) }));
+ expect(await brain.call('extract_facts', { turn_text: 'Synthetic meeting record. ' + facts.join('. ') + '.', visibility: 'world', valid_from: '2026-10-15T00:00:00Z' }, SEGMENTED))
+ .toMatchObject({ inserted: facts.length });
expect(await brain.storageOf(SEGMENTED)).toBe('segmented');
await settle(brain, kind);
+ self = await withEnv(brain.env(), async () => localHostId());
+ 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));
+ });
}, 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();
+ await olderRun(oldHost, 'import', 'lp-d-older-writer', OLDER, '1 hour');
+ resetGate();
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');
+ reserved.length = 0;
+ const { requestId, recordsSeen } = await purgeUntilSettled(CLAIM);
+ const held = await mirrorOf(requestId);
+ // 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, self).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); }
+ // 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'`);
+ resetGate();
+ await waitFor(async () => { await pass(); return (await mirrorOf(requestId)).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 });
+ }, 600_000);
+
+ test('this host\'s own superseded pre-upgrade writes do not hold the mirror; an older write from another host does', async () => {
+ const file = fileOf(brain, SEGMENTED);
+ // This host synced with v0.60.290.0, then upgraded and synced again: the switch stays held for 7 days, doctor reports
+ // the hold as information, and the mirror proceeds.
+ await olderRun(self, 'sync', 'lp-d-self-before-upgrade', OLDER, '2 hours');
+ await olderRun(self, 'sync', 'lp-d-self-after-upgrade', VERSION, '1 hour');
+ resetGate();
+ expect((await readPageBodyPolicy(brain.engine)).segmented).toBe(false);
+ expect(await doctor()).toMatchObject({ status: 'ok', severity: 'info' });
+ reserved.length = 0;
+ const selfHold = await purgeUntilSettled(SELF_CLAIM);
+ expect(await mirrorOf(selfHold.requestId)).toMatchObject({ state: 'committed', error_code: null, recovery: null });
+ expect(readFileSync(file, 'utf8')).not.toContain(SELF_CLAIM);
+ expect(reserved).toHaveLength(1);
+ expect(reserved[0]).toMatchObject({ version: 2, after: null });
+ await settle(brain, kind);
+
+ // Another host's older write on top of it is live: doctor warns, and the mirror holds and parks naming only that host.
+ await olderRun(otherHost, 'import', 'lp-d-other-host', OLDER, '30 minutes');
+ resetGate();
+ expect(await doctor()).toMatchObject({ status: 'warn', fix: { argv: ['gbrain', 'upgrade'] } });
+ reserved.length = 0;
+ const before = readFileSync(file);
+ const otherHold = await purgeUntilSettled(OTHER_CLAIM);
+ const held = await mirrorOf(otherHold.requestId);
+ expect(reserved).toEqual([]);
+ expect(otherHold.recordsSeen).toEqual([]);
+ expect(held.state).toBe('failed');
+ expect(json(held.data).parked).toEqual([{ slug: SEGMENTED, error_code: 'segmented_mirror_writer_gate' }]);
+ expect(readFileSync(file).equals(before)).toBe(true);
+ const refusal = await assertSegmentedMirrorGate(brain.engine, { source_id: brain.sourceId } as never, SEGMENTED, self).then(() => null, error => error) as OperationError;
+ expect(refusal.code).toBe('segmented_mirror_writer_gate');
+ expect(refusal.suggestion).toContain(otherHost);
+ expect(refusal.suggestion).not.toContain(self);
}, 600_000);
});
}