Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
flip gate: config-read errors keep the switch off, recovery budget holds stored segmented pages, floor follows the switch-on BEHAVIOR row, doctor info for this host's pre-upgrade hold
garrytanb00884067717
diff --git a/docs/architecture/key-files/core-persistence.md b/docs/architecture/key-files/core-persistence.mdindex fb1c8bf0aa..d818e3ccbe 100644--- a/docs/architecture/key-files/core-persistence.md+++ b/docs/architecture/key-files/core-persistence.md@@ -14,7 +14,7 @@ Managed facts extraction (withdrawn-candidate skip and recovery, conversation fa- `src/core/persistence/git-durability-policy.ts` + `git-durability-administration.ts` — whether the persistence owner commits and pushes page writes through its Git effect is a per-host-binding setting (#5182): `persistence_host_bindings.git_durability` (`enabled` | `disabled` | NULL, migration v234, column SQL kept out of the replayed schema blob as `PERSISTENCE_GIT_DURABILITY_COLUMN_SQL`). `gitDurabilityPolicy(binding, root)` is tri-state and fail-closed: a recorded value wins, NULL falls back to the legacy post-commit-hook probe, a probe error fails the effect instead of skipping it; `effects.ts` takes its per-root verdict from it. `gitDurabilityState` renders `on`/`off`/`unknown` for `writer status` and `writer activate`'s `git_durability` listing. `planGitDurabilityCatchUp`/`requeueGitDurabilityCatchUp` re-queue the Git effects completed `durability_not_enabled` while the setting was off by resetting the existing rows, never inserting under `UNIQUE(request_id, kind)`. The verb `writer_git_durability` (`gbrain sources writer git-durability <source> --enable|--disable [--pat-file <path>] [--dry-run]`, administration-gated like the other writer verbs) runs a read-only `git push --dry-run` probe before enabling (codes `git_branch_unborn`, `git_checkout_required`, `git_detached_head`), wires the repo-scoped credential under `gbrain.durability.managedcredential` from a 0600 `--pat-file` (`pat_file_unreadable` otherwise) and retries the worktree's parked pushes. `sources push` (`managedPushRefusal` in `workspace-push.ts`), `bootstrap verify`'s `checkPushProbe` and the skill-pack writer guard name this route on a managed worktree (#5606). Pinned by `test/persistence-admin-git-durability.test.ts`, `test/managed-push-remedy.serial.test.ts`.- `src/core/persistence/deactivation.ts` — private CLI `sources writer deactivate` (#5455/#5628), brain-wide and trusted-local. `deactivationBlockers` lists the admin lock, queued/running/recovering requests, recovering topology changes, uncommitted effects, held connector items (managed holds that classic mode would not read) and live `gbrain_cycle_locks` leases, each with its CLI exit; `physicalRootBlockers(engine, mode)` (#5914 [R9a]) adds `physical_root` for this host's owned checkouts, probed as the mode's real run will: strict `assertPhysicalRoot` for managed, `assertPhysicalRootReservation` for the classic pre-activation release, so each preview lists exactly what its real operation refuses on; `--dry-run` returns them plus the worktrees that would retire, the kept shared-skill settings and, when clean, `apply_command` bound to the admin state read before the preview. `deactivatePersistence` takes the local native worktree locks, then in one transaction locks `persistence_brain FOR UPDATE`, checks the expected admin state and the admin lock, locks worktrees then sources `FOR UPDATE` (admission's order), rechecks the blockers, sets `enabled=false`, increments `mode_epoch`, retires every worktree, deletes source and host bindings and records a committed `writer_deactivate` topology change (brain id, retired epoch, retired worktree ids and roots, source roots). `cleanupRetiredManagedMarkers` runs on CLI connect, after deactivate and from `writer status`: it removes this brain's registry records, `.gbrain-managed` / Git `gbrain-managed.json`, `.gbrain-owner.json` and reservations only when their `mode_epoch` is a retired one below the current epoch, or, without an epoch, their worktree id (or, for markers without one, their root outside any active binding) is recorded as retired; unknown or newer epochs are kept and reported `pending`, each file is re-read before unlinking and other brains' files are never touched. `root-registry.ts` writes `mode_epoch` into new registry records and managed markers. Tests: `test/persistence-deactivate.test.ts` (PGLite and Postgres), `test/e2e/persistence-deactivate-race.test.ts`. See [persistence stalls](persistence-stalls.md).-- `src/core/persistence/{admin-lock,blocking-effects,writer-versions}.ts` — `admin-lock.ts` owns the opt-in brain-level writer admin lock: reserved config key `persistence.writer_admin_lock` (`{locked, set_at, host_id, generation}`), written only by local `gbrain sources writer lock|unlock` under the `persistence_brain` row `FOR UPDATE`; lock refuses while a prepared transfer is unaccepted. `assertWriterAdminUnlocked` runs inside the claim, managed claim, activation, shared-skill activation and transfer prepare/accept transactions for every caller (share lock on the brain row) and refuses with `writer_admin_locked`; only the ordinary first-write auto-claim (`claimWorktree(..., { automatic: true })` from page and memory mutations) is exempt. Generic `config set`/`unset`/`unset --pattern` refuse the key; engine migration copies it. It is not a security boundary and older binaries ignore it. `blocking-effects.ts` lists queued, running or recovering effects (`listBlockingEffects`) and builds `writer_not_quiesced` suggestions naming the first blocking request or effect with `gbrain sources writer status <source> --json`. `writer-versions.ts` stamps admitter version/host at admission and consumer version/host/`published_at` only on committed publication (migration 178, cutoff `persistence_brain.writer_version_cutoff` on the database clock); replay and compaction keep stamps. `sources writer status` reports `admin_lock`, `local_host_id`, `blocking_effects` and `writer_versions`; `src/commands/doctor/checks/writer-version.ts` is the seven-day `writer_version` advisory. `SEGMENTED_WRITER_FLOOR`: a seven-day writer below it or unmarked keeps `pages.segmented_storage` off (`page-body/limits.ts`, doctor `segmented_storage`); marked rows of any role meet the floor (ingest log: two partial indexes, v254/v257). Tests: `test/persistence-writer-admin-lock.test.ts`, `test/persistence-writer-versions.test.ts`, `test/persistence-blocking-effects.test.ts`, `test/e2e/persistence-writer-{admin-lock,stamps}.test.ts`.+- `src/core/persistence/{admin-lock,blocking-effects,writer-versions}.ts` — `admin-lock.ts` owns the opt-in brain-level writer admin lock: reserved config key `persistence.writer_admin_lock` (`{locked, set_at, host_id, generation}`), written only by local `gbrain sources writer lock|unlock` under the `persistence_brain` row `FOR UPDATE`; lock refuses while a prepared transfer is unaccepted. `assertWriterAdminUnlocked` runs inside the claim, managed claim, activation, shared-skill activation and transfer prepare/accept transactions for every caller (share lock on the brain row) and refuses with `writer_admin_locked`; only the ordinary first-write auto-claim (`claimWorktree(..., { automatic: true })` from page and memory mutations) is exempt. Generic `config set`/`unset`/`unset --pattern` refuse the key; engine migration copies it. It is not a security boundary and older binaries ignore it. `blocking-effects.ts` lists queued, running or recovering effects (`listBlockingEffects`) and builds `writer_not_quiesced` suggestions naming the first blocking request or effect with `gbrain sources writer status <source> --json`. `writer-versions.ts` stamps admitter version/host at admission and consumer version/host/`published_at` only on committed publication (migration 178, cutoff `persistence_brain.writer_version_cutoff` on the database clock); replay and compaction keep stamps. `sources writer status` reports `admin_lock`, `local_host_id`, `blocking_effects` and `writer_versions`; `src/commands/doctor/checks/writer-version.ts` is the seven-day `writer_version` advisory. `SEGMENTED_WRITER_FLOOR` (`page-body/writer-floor.ts`): a seven-day writer below it or unmarked keeps `pages.segmented_storage` off (`page-body/limits.ts`, doctor `segmented_storage`); marked rows of any role meet the floor (ingest log: two partial indexes, v254/v257). Tests: `test/persistence-writer-admin-lock.test.ts`, `test/persistence-writer-versions.test.ts`, `test/persistence-blocking-effects.test.ts`, `test/e2e/persistence-writer-{admin-lock,stamps}.test.ts`.- `src/core/persistence/{atom-maintenance,atom-retry,page-prepare,facts-maintenance,facts-prepare,prepared-maintenance}.ts` — resident dispatch for durable atom publication/completion, explicit atom retry (`retryManagedAtomBatch` takes the job's signal and deadline, stops between stages on caller cancel, deadline or cycle-lock loss, shares one deadline-bound `MaintenanceWriteWait` with the model rerun, and reports a stop after admission as `write_pending` or an `AbortError` carrying the receipts, never `cancelled`; #6622), authorized multi-entity fact-fence/backstop append, local synthesize/patterns/consolidation, and the cycle's lint repairs on a managed brain (`runLintCore` publishes each fix through `maintenancePreflight` + `publishMaintenancePage`; #5180, `test/managed-lint.test.ts`). `page-prepare.ts` exports `fileMatchesSnapshot`, the canonical file-versus-page comparison `prepareFileTarget` applies, so lint can bind a repair to the revision it read (it takes the importer's path for the file: a frontmatter-less file under a directory-inference rule also matches when `readCanonicalAsImported` (BOM strip + `applyInference` at `scannerSourcePath`) reproduces the stored row, with an inferred type treated as undeclared, #6605; reconcile reads the file side through `reconcileFileReading` in `reconcile-state.ts`); the uncoordinated-local-edit refusal carries detail `file_database_drift` and a `sources reconcile <src> <slug> --brain host --preview` fix; a shared-origin delete: canonical-reconciliation.md. In `prepareFileTarget`, a live page whose canonical file is missing refuses `source_changed` unless it is declared or derive-phase database-only, or it is a `delete_page` (`deleting`, no content) of a page with no recorded `source_path` and no captured file URI: that delete plans no file, so it publishes database-only and its receipt reports no file or Git effect (`test/persistence-captured-file-target.test.ts`, `test/persistence-never-published-delete.test.ts`). `atomOwnerTarget` is the one owner decision for an atom session and for `atomDrainOwnerRefusal`, the auto-drain dispatch pre-check; an unbound Google/GitHub source publishes atom maintenance through the `connector_database` target (its `local_path` is connector state, not a checkout) and the publication refuses with `source_changed` when the source gained an owner after preflight. `submitMaintenance` scans every content-carrying intent with `scanCanonicalFences` (the check the canonical projection runs) over the whole submitted body and timeline before a request exists (#6278): a defect no adoption clears (a second facts fence in the timeline; `replaceOrInsertFactsFence` replaces only the first) is refused with its fence reason, so `fenceManaged` reports the page in `failed_pages` and the others still adopt, while a repair whose postimage is clean passes. `prepareFactFenceAdoption` names its steps for `enterClaimStep`, compares the fence cell with the legacy fact modulo whitespace, writes the cell's parsed text back into `facts.fact` in the same `UPDATE` that sets `row_num` (so the projection keeps the fact's id), and throws the registered `fence_unrenderable` (class `server`) as its last-line defence. `maintenancePreflight` creates the job's `MaintenanceWriteWait` (optional `deadlineAtMs`) and `submitMaintenance` uses it for new and replayed requests; its owner check goes through `checkOwner` / `ownerUnavailableError` (`owner-refusal.ts`), so a missing binding, a changed incarnation, another owner host, a draining or recovering worktree and a missing local or coordination path each refuse `owner_unavailable` with their own `reason`, and nothing claims or transfers ownership to get past them. #6325: `resumeManagedAtoms` returns `run | done | held`. The drain does not replay a failed batch: it resumes the next automatic attempt, whose run key is `digest([drainKey, failedRequestId, 'automatic'])` (one stable id per failure, so a crashed attempt resumes and two runs admit the same requests), and whose completion advances the failed drain-key checkpoint by the same compare-and-set an explicit retry uses. The completion counts one strike per completed failure on that checkpoint (`attempts`); at `MAX_DETERMINISTIC_FAILURES` it sets `held`, which `MANAGED_ATOM_DISCOVERY_SQL` excludes from discovery and the backlog and `listHeldManagedAtoms` reports (doctor `extract_atoms_held_failed`, code `held_failed`). Reading a held or failed checkpoint never strikes; storage, authority and conflict errors fail the attempt without completing it, so they never strike either. A content change is a new drain key, so the count starts over. An explicit retry (`session.retry`) ignores `held`, and its failure refusal (`extraction_failed`) names the recorded failure reason (malformed output or a response stopped before the end) and carries a paid `fix` (`gbrain jobs submit extract-atoms-drain --params '{sourceId, retryRequestId}'`) with a read-only `gbrain write-request` verify; the drain raises it only for a failed batch whose checkpoint is gone. Tests: `test/managed-atoms-retry.test.ts`. Managed facts extraction (the withdrawn-candidate skip and its recovery route, the conversation facts batches, the unmanaged derived index) continues in [Core Persistence (managed facts)](core-persistence-facts.md).- `src/core/persistence/maintenance-wait.ts` — how long a maintenance publisher waits for its accepted write to commit before the receipt reports `write_pending` (#5854). `MAINTENANCE_WRITE_WAIT_MS` is 30 s; `MaintenanceWriteWait` is one budget per job: each wait is capped by the job's remaining deadline (zero at or past it), and once one publish is still pending after its wait (`observe`) every later publish in that job waits zero and is deferred like it. A pending write keeps its request identity and commits later; it is never reported as committed. A `MaintenanceWriteWait` with no deadline also sets the replay window of a subagent tool write whose job has none (`minions/tool-write-identity.ts`). `__setMaintenanceWriteWaitForTests` replaces the base wait, those tool writes included. Tests: `test/maintenance-write-wait.test.ts`, `test/e2e/maintenance-write-wait.test.ts`.diff --git a/docs/architecture/key-files/core-services-2-continued.md b/docs/architecture/key-files/core-services-2-continued.mdindex 5efeb2ad83..4c7cd2b343 100644--- a/docs/architecture/key-files/core-services-2-continued.md+++ b/docs/architecture/key-files/core-services-2-continued.md@@ -22,7 +22,7 @@ The page-state concurrency foundation under `src/core/page-state/` and the share- `src/core/progressive-batch/` — shared ramp-up + cost-cap + verification primitive (trial 10 → ramp 100 → ramp 500 → full, with verification at each stage), with verifier+policy injection (callers describe HOW TO MEASURE SUCCESS, not WHEN TO WAIT FOR CTRL-C). Modules: `types.ts` (Stage, StageVerdict, AbortReason, discriminated `Verifier` union `OutputCountVerifier | IdempotentMutationVerifier | NoopVerifier`, Policy, StageReport), `orchestrator.ts` (`runProgressiveBatch(items, verifier, policy, runner)` — reads `getCurrentBudgetTracker()` ahead of `Policy.maxCostUsd` fail-closed; null both ways triggers `abort_cost_cap reason='no_budget_safety_net'`), `audit.ts` (ISO-week JSONL at `~/.gbrain/audit/progressive-batch-YYYY-Www.jsonl` via the shared `audit-writer` primitive), `stage-report.ts` (ASCII formatter for the default `Policy.onStageReport`). Env knobs: `GBRAIN_PROGRESSIVE_BATCH_DISABLED=1`, `GBRAIN_PROGRESSIVE_BATCH_AUTO=1` (skip Ctrl-C grace), `GBRAIN_PROGRESSIVE_BATCH_STAGES=10,100,500`. Sites that "jump straight to full" stay that way by default; ramp is opt-in per-site via `Policy.interactiveAbortMs > 0`. Pinned by `test/progressive-batch/orchestrator.test.ts` (35 cases, every verdict path).- `src/core/page-body/page-shape.ts` — Wave B PR 1 (spec 1.5): segmented page bodies are unreachable as strings. `guardSegmentedBody` (called by `rowToPage` for a row with `body_storage = 'segmented'`, so by every snapshot and `getPage` read) replaces `compiled_truth` / `timeline` with enumerable getters and setters that throw `page_body_segmented`, so property reads, spread, `JSON.stringify`, `structuredClone` and assignment all fail loud instead of seeing an empty body. `isSegmentedPage`, `assertInlineBody(page, site)` (explicit refusal where a writer would otherwise act before a getter fires, e.g. SQL-only writers; every `page_body_segmented` refusal's fix reads the page with `get_page body: 'auto'`), `pageBodyBytes(page)` (`body_bytes` for segmented pages), `pageBodySegmentedError` and `pageBodyOverCeilingError` (the refusal of a fence or timeline write through the put path on a page over 24 MiB; `wholeBodySnapshot` in `persistence/segmented-apply.ts` reads a page within it back as strings and refuses above it: semantic timeline writes, `takes-prepare.ts`, `facts-prepare.ts`, `reconcile-state.ts`, `gbrain core`). Tag writes on a segmented page never read the body: `prepareSegmentedTagMutation` (`persistence/page-prepare.ts`) flips them in metadata over the live manifest (`test/large-pages/segmented-semantic-writes.test.ts`). `bodyUnread(page)` says a segmented page's body was not read back as strings (over the single-string ceiling, see `materializedPage`); such a body was written by the streamed import, which holds fenced files, so `fenceBody(page)` reads it as empty for the fence merges and `withoutBody(page)` copies the page's other fields for a render whose body comes from the incoming write (a shrunk file rewrites such a page: `test/large-pages/segmented-shrink-below-ceiling.test.ts`). `Page` stays one shape (`body_storage?`, `body_bytes?`); the static half is `scripts/check-page-body-readers.ts` with `scripts/page-body-readers-baseline.tsv` (docs/TESTING.md#page-body-readers). Pinned by `test/large-pages/segmented-body-unreachable.test.ts`.-- `src/core/page-body/limits.ts` — Wave B size classes, ceilings, retention numbers and config keys in one place. `readPageBodyPolicy` is the single question every write asks: `segmented` is the effective `pages.segmented_storage` (unset means `SEGMENTED_STORAGE_DEFAULT`, `on`; `off` or an unrecognized value is off; held off while `segmentedWriterBlockers` finds a recent writer that blocks, and an unreadable gate counts as blocked), `maxBytes` the engine ceiling (256 MiB Postgres, 128 MiB PGLite, lowered by `pages.max_bytes`) while on and `PAGE_MAX_BYTES` while off. Config is read per call; only the writer gate is cached (`SEGMENTED_WRITER_GATE_TTL_MS`, `_resetSegmentedWriterGateForTests`). `chooseBodyStorage` applies the 1 MiB / 512 KiB hysteresis. The writer gate (`segmentedGateWriters` in `persistence/writer-versions.ts`) reads seven days of admitted requests in any state, committed publications, `ingest_log` rows and, on Postgres, `persistence_consumers` heartbeats; a row blocks when its version is below `SEGMENTED_WRITER_FLOOR` or unparsable, or when it lacks the segment-reader mark (migration v254: `admitter_segment_reader`, `consumer_segment_reader`, `persistence_consumers.segment_reader`, `ingest_log.writer_segment_reader`), because releases 0.60.252.0-0.60.262.0 have no segment readers and a version string cannot tell them apart. Not seen: an older binary's unmanaged single-page write, a run that dies before it logs, and read-only or export use. `pageRecoveryBytes` is the default `persistence.limits.worktree_recovery_bytes` (read by `persistence/limits.ts` `readJournalLimits` in its one config statement): twice the body the configured switch admits (`segmentedMaxBytes`, or `PAGE_MAX_BYTES` while off) plus `RECOVERY_FILE_HEADROOM_BYTES` per copy, never below 256 MiB, because a restore reserves its file twice; it ignores the writer gate so a page admitted while the switch was effective stays restorable. Tests: `test/large-pages/segmented-switch.test.ts`, `test/large-pages/recovery-budget-default.test.ts`.+- `src/core/page-body/limits.ts` — Wave B size classes, ceilings, retention numbers and config keys in one place. `readPageBodyPolicy` is the single question every write asks: `segmented` is the effective `pages.segmented_storage` (unset means `SEGMENTED_STORAGE_DEFAULT`, `on`; `off` or an unrecognized value is off; held off while `segmentedWriterBlockers` finds a recent writer that blocks, and an unreadable gate counts as blocked), `maxBytes` the engine ceiling (256 MiB Postgres, 128 MiB PGLite, lowered by `pages.max_bytes`) while on and `PAGE_MAX_BYTES` while off. Config is read per call; only the writer gate is cached (`SEGMENTED_WRITER_GATE_TTL_MS`, `_resetSegmentedWriterGateForTests`). `chooseBodyStorage` applies the 1 MiB / 512 KiB hysteresis. The writer gate (`segmentedGateWriters` in `persistence/writer-versions.ts`) reads seven days of admitted requests in any state, committed publications, `ingest_log` rows and, on Postgres, `persistence_consumers` heartbeats; a row blocks when its version is below `SEGMENTED_WRITER_FLOOR` (`page-body/writer-floor.ts`: the `since` of the BEHAVIOR_CHANGES row with id `segmented_switch_on`, this build's VERSION while it is `TBD`, so the merge-slot stamp edits only that row) or unparsable, or when it lacks the segment-reader mark (migration v254: `admitter_segment_reader`, `consumer_segment_reader`, `persistence_consumers.segment_reader`, `ingest_log.writer_segment_reader`), because releases 0.60.252.0-0.60.262.0 have no segment readers and a version string cannot tell them apart. Not seen: an older binary's unmanaged single-page write, a run that dies before it logs, and read-only or export use. `pageRecoveryBytes` is the default `persistence.limits.worktree_recovery_bytes` (read by `persistence/limits.ts` `readJournalLimits` in its one config statement): twice the larger of the body the configured switch admits (`segmentedMaxBytes`, or `PAGE_MAX_BYTES` while off) and the largest page stored in segments (deleted pages included; one probe of `pages_segmented_body_bytes_idx`, v258) plus `RECOVERY_FILE_HEADROOM_BYTES` per copy, never below 256 MiB, because a restore reserves its file twice; it ignores the writer gate, and turning the switch off or lowering `pages.max_bytes` never strands a stored page. `readPageBodyPolicy` treats a failed read of the switch or `pages.max_bytes` as off, never as unset. Doctor `segmented_storage` reports a hold left only by this host's pre-upgrade writes, superseded by a later passing write of this host, as information with its clear time. Tests: `test/large-pages/segmented-switch.test.ts`, `test/large-pages/recovery-budget-default.test.ts`, `test/large-pages/recovery-budget-ceiling.slow.test.ts`.- `src/core/page-body/read-range.ts` + `segment-projection.ts` + `segment-ledger.ts` — Wave B PR 2 (spec 7.1, 7.3): the segment reader. `openSegmentedBody` reads a page's live manifest rows and its withdrawal ledger (`readBodyLedger`); `readBodyRange(engine, { pageId, space, start, end, audience, region?, body? })` streams pieces one segment text at a time, never the whole body. Remote reads and every projected-space read serve the read projection: `projectSegment` projects whole segments from their stored protected regions (takes, truncated tail and markers out, keys as the projection token, facts regions rendered world-only and credential-projected), after the withdrawal overlay (`overlaySegmentText`; a fence split by a forced cut is omitted for reads and refuses a trusted read) and the fence overlay (held and purged rows out, rows below the page tier in the low-tier block after the truth). A transform or stale metadata recomputes the regions from the segment's entry state; with none usable the read refuses `page_projection_stale`, never raw text. Trusted stored-space reads give the overlaid stored stream. `projectedLayout` (cached on the handle), `projectedUnits` (rows and fixed text in projected order, for `page-window/segmented.ts`), `projectedTotals`, `projectedLineStart` and `projectedOutline` (outline from stored metadata, no segment text) locate projected bytes; the concatenation equals `projectPageText` of the joined body byte for byte except where a facts fence is longer than a segment (shows less). The chunker (`segment-chunks.ts`) chunks the same projection, so sealed segmented pages carry `MARKDOWN_CHUNKER_VERSION`; `sealSegmentedPage` indexes the overlaid, sanitized timeline lead. Pinned by `test/large-pages/projection-parity.test.ts`, `remote-window-privacy.test.ts` and `sealed-segmented-search.test.ts` (fixture `test/helpers/segmented-privacy-fixture.ts`).- `src/core/page-body/segment-rewrite.ts` — fence rewrites of a segmented body without holding it as one string (forget strikes, purge drops). Only stored `facts`/`takes` protected regions are decoded and passed, in body order with their region, to a `FenceTransform` (a region crossing forced cuts is joined with its neighbours, refused above `PAGE_MAX_BYTES`). `rewriteLiveSegmentedFences` re-stages the live body through `prepareSegmentedBody` from the segment stream with the changed units replaced and flips it in the caller's transaction (trust tier and soft delete kept; null when nothing changed); `rewriteSegmentedGeneration` rebuilds one retained generation under its own number and updates its versions' hash and size; `rewrittenContentHash` streams the hash of a rewritten generation; `segmentedBodyContains` searches a body segment by segment with the previous segment's tail carried over. Tests: `test/large-pages/purge-segments.test.ts`, `forget-scope.test.ts`, `page-purge-segments.test.ts`.- `src/core/page-body/segment-blocks.ts` + `segment-links.ts` + `segment-takes.ts` — Wave B PR 2 (spec 8, full-pass mode): the derived passes over a segmented body, O(page) work and O(segment) memory, not yet incremental. `bodyBlocks(engine, page, { regions?, separator?, want? })` yields the trusted, withdrawal-overlaid joined body one block at a time (a segment, or a run joined across forced cuts, refused above `BLOCK_MAX_BYTES` with `page_body_segmented`; `want` skips a run unread), so each block starts where the parsers start fresh; `truthLead` reads a bounded lead; `readGarbageCollector` forces a collection every 4 MiB read; `detachedValue` copies a result kept past its block so it pins no segment text; `segmentedPassWork` counts the passes' work for the linearity test. `extractSegmentedPageLinks` runs `extractBodyLinks` over each block in a window (`bodyWindows`: the whole blocks before it, 4096 chars after, the headings still open), with the role phrases a first pass found (`segmentedRoleText`), and merges candidates in `extractPageLinks` order, plus the temporal inputs (`TemporalBody`). `parseTakesFenceBlocks` gives `parseTakesFence` of the joined body. Consumers: link preparation and the links effect, stale-links maintenance, source reconciliation, the sweep, `extract links|timeline|takes --source db`, `extract --stale` (the stale list includes segmented pages since PR 2 fix lane J1; test `test/large-pages/segmented-extraction-stale.test.ts`), the mention pass (`pageMentions`), the canonical prior view (`segmentedPriorView`), `segmentedTimelineText`, the chronicle judge and the facts planner (`planSegmentedExtraction`). Tests: `test/large-pages/segmented-derived-parity.test.ts`, `segmented-derived-passes.test.ts`, `segmented-derived-linear.test.ts`, `segmented-derived-memory.slow.test.ts`, `segmented-derived-work.test.ts`. `segment-lines.ts` serves the line-local maintenance scans: `bodyLines` yields the joined text's complete lines a block at a time (a line cut by a block boundary is carried, counted in `segmentedPassWork.carry`), consumed by `gbrain integrity` and `reconcile-links`; `segmentedRegionContains` searches one region for literal markers across block boundaries (repair `connector-fences`). Test: `test/large-pages/segmented-maintenance-commands.test.ts`.diff --git a/scripts/structural-suites.tsv b/scripts/structural-suites.tsvindex 1352064a01..090feab83e 100644--- a/scripts/structural-suites.tsv+++ b/scripts/structural-suites.tsv@@ -209,6 +209,7 @@ test/jobs-list-get-json.serial.test.ts help advertises --json on list/get/statstest/jobs-thin-client-date-rehydration.test.ts thin-client unpack sites route through rehydrateJobDates (source audit) 2 source-surface-helpertest/jobs-worker-startup-recovery.test.ts work-handler recovery placement (structural) 1 source-surface-helpertest/large-pages-skill-guidance.test.ts large-page guidance in shipped skills 3 readFileSync+test/large-pages/segmented-writer-floor.test.ts (file-level) 1 readFileSynctest/link-source-check-repair.test.ts regex literal drift guard (#4613) 1 readFileSynctest/longmemeval-embed-cache.test.ts EmbeddingCache — canonical hash 4 readFileSynctest/loops-extract-wiring.test.ts jobs.ts wiring 2 source-surface-helperdiff --git a/src/commands/doctor/checks/segmented-storage.ts b/src/commands/doctor/checks/segmented-storage.tsindex 4f43506c69..7ea7ee3d8d 100644--- a/src/commands/doctor/checks/segmented-storage.ts+++ b/src/commands/doctor/checks/segmented-storage.ts@@ -2,7 +2,11 @@ import type { BrainEngine } from '../../../core/engine.ts';import type { Check } from '../../doctor.ts';import { agentFix, checkError, doctorVerify, infoCheck } from '../check-fix.ts';import { PAGE_BODY_CONFIG_KEYS, parseSegmentedStorage, readPageBodyPolicy, segmentedStorageRequested, segmentedWriterBlockers, SEGMENTED_WRITER_WINDOW_DAYS } from '../../../core/page-body/limits.ts';-import { SEGMENTED_WRITER_FLOOR } from '../../../core/persistence/writer-versions.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 { VERSION } from '../../../version.ts';const name = 'segmented_storage';const DOCS = 'docs/guides/memory-boundaries.md#segmented-page-storage';@@ -13,7 +17,11 @@ const enableFix = (why: string) => agentFix(['gbrain', 'config', 'set', PAGE_BOD* Wave B activation gate: the configured `pages.segmented_storage`, the value writes use, and the writers seen in* 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.+ * 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, this host has since written with a build that passes the gate (every blocker is+ * older than that write), and no older process of this host still renews its heartbeat. Without a later passing+ * write the same rows cannot be told from an older gbrain still writing on this host, which keeps the warning.*/export async function segmentedStorageCheck(engine: BrainEngine): Promise<Check> {try {@@ -30,8 +38,21 @@ export async function segmentedStorageCheck(engine: BrainEngine): Promise<Check>message: 'pages.segmented_storage holds an unrecognized value, so segmented page storage is off. Set it to on or off.' };if (!segmentedStorageRequested(configured)) return infoCheck(name, 'Segmented page storage is off by default in this release (pages.segmented_storage unset): pages over 1 MiB are stored inline up to 24 MiB; pages already stored in segments stay readable.','disabled_by_choice', enableFix('Turns segmented storage on: pages over 1 MiB are stored in segments, up to the engine ceiling.'), details);+ 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));+ // This host's newest write that passes the gate: blockers older than it were written before the upgrade.+ const passedAt = ownOnly ? Math.max(-Infinity, ...(await segmentedGateEvidence(engine, SEGMENTED_WRITER_WINDOW_DAYS))+ .filter(row => row.host_id === self && row.segment_reader && row.last_seen && !writerVersionBelowFloor(row.version, SEGMENTED_WRITER_FLOOR))+ .map(row => Date.parse(row.last_seen!))) : -Infinity;+ if (ownOnly && blockers.every(row => Date.parse(row.last_seen!) < passedAt)) {+ 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.`,+ 'degraded', undefined, details);+ }if (blockers.length) {- const hosts = listed.map(row => `host ${row.host_id ?? 'unknown (not recorded)'} (principal ${row.principal}) ${row.role} ${row.version}, last seen ${row.last_seen}`);return { name, status: 'warn', details,message: `Segmented page storage is configured ${configured === 'on' ? 'on' : 'on by default'} but held off: ${blockers.length} writer(s) that do not read segmented pages `+ `(a gbrain older than this release, or stamped below v${SEGMENTED_WRITER_FLOOR}) wrote in the last ${SEGMENTED_WRITER_WINDOW_DAYS} days: ${hosts.join('; ')}${blockers.length > SAMPLE ? ` (first ${SAMPLE} shown)` : ''}. `diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 59d4aee5df..dc9dab7481 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -223,7 +223,7 @@ const DOCTOR_ARGV = ['gbrain', 'doctor', '--only', BEHAVIOR_NOTICE_CODE, '--jsontype ChangeText = string | ((chain: ChainDisclosure | null, remote: boolean) => string | null);/** Every disclosed behavior change, with the release that introduced it. Append new rows; never edit a shipped `since`. */-export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }> = [+export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText; id?: string }> = [{ since: '0.60.68.0', text: (chain, remote) => {if (!chain) return null;if (remote) return 'A chat fallback chain is configured on this brain host: when a chat call\'s own model fails it is retried on other models. Its entries and providers are visible to the brain host operator in gbrain doctor --only chat_fallback_chain.';@@ -729,8 +729,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }{ since: '0.60.269.0', text: 'A managed sync no longer forks a second page for a file whose page an older gbrain imported under a slug the current slug fold spells differently (#6727: punctuation, spaces, accents, emoji, full-width characters): a file with no recorded origin and no page at its slug imports into the one live page without a recorded file that folds to it, keeping that page\'s id, links and history. When several such pages match, the file is held `legacy_slug_conflict` (needs a person: keep one, remove the others, then sync); with `sync.holds=fail` the run stops `page_identity_changed`. Pages already forked by older syncs are not merged.' },{ since: '0.60.269.0', text: 'A managed sync\'s final checkpoint validation reads at most one committed receipt per unfinished receipt, so a catch-up of tens of thousands of entries no longer times out at its last step (#6735). A checkpoint that still hits `checkpoint_validation_timeout` is re-validated by the next sync of the source (once per run, after the stop is recorded) instead of rediscovering the whole manifest.' },{ since: '0.60.269.0', text: 'Doctor no longer warns that a managed sync cursor has been idle "over an hour" right after the cursor was discovered (#6763): idle time counts from the cursor\'s last advance, or from its discovery when it has not advanced yet.' },- // Wave B PR 2 (segmented page storage, switch on). `since` is 'TBD' until the merge-slot stamp, which also stamps- // SEGMENTED_WRITER_FLOOR (persistence/writer-versions.ts) with the same release.+ // Wave B PR 2 (segmented page storage behind the switch).{ since: '0.60.290.0', text: '`gbrain config set pages.segmented_storage on` stores pages over 1 MiB in segments; it is off by default in this release. Reading a window, outline or chunk context of a large page costs the size of the window, not the page, and a rewrite re-indexes only the segments that changed. A page can be up to 256 MiB on Postgres and 128 MiB on PGLite (`pages.max_bytes` lowers it). `put_page`, `put_pages` and `capture` content and `gbrain put` stdin stay limited to 24 MiB per call, so a larger page comes in by `gbrain import` or `gbrain sync` of its file: on a source backed by files only from the file\'s own place in the checkout, which is never rewritten; a database-only source takes it by import. Pages at or under 1 MiB are stored exactly as before. Turning it off again stores new pages inline up to 24 MiB; pages already stored in segments stay readable.' },{ since: '0.60.290.0', text: 'Segmented page storage stays off while an older gbrain writes to the same brain: a gbrain older than this release that in the last 7 days admitted or published a managed write, logged an import, sync or connector run, or (on Postgres) ran a resident `serve`, `sync`, `jobs`, `autopilot` or `mcp` process keeps new pages over 1 MiB inline up to 24 MiB, even with `pages.segmented_storage` set to `on`; writes from before the upgrade count too. New doctor check `segmented_storage` shows the configured and effective value and names each blocking host and how it was seen; run `gbrain upgrade` there, and the hold clears 7 days after its last write. Not detected: an older binary\'s single-page write on a brain without managed persistence, a run that dies before it logs, and an older binary that only reads or exports.' },{ since: '0.60.290.0', text: 'Pages stored in segments keep at most `versions.segmented_max_per_page` (default 50) version snapshots, and fewer when the old text they pin exceeds `versions.segmented_max_pinned_bytes` (default 64 MiB, never below the page size). A snapshot of such a page records its segment generation instead of copying the body. History of every other page is unchanged.' },@@ -888,11 +887,14 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }{ since: '0.60.289.0', text: '`gbrain repair ghost-pages` now retires legacy knowledge ghosts under `skills/` that no live pack skill owns, as a database-only soft delete, and lists ghosts on files the adopted skillpack owns apart as `ghost_skill_pack_member` with a restore step; a per-item caller refusal is recorded `refused` instead of aborting the run.' },{ since: '0.60.289.0', text: 'Managed fact extraction that gives one entity more than 50 facts in one batch now publishes them as parts of at most 50, each its own extract_facts request published in queue order, so one publication no longer holds the brain-wide write counters for every fact. Each part\'s receipt says so (publication: partial or final_part, part.index/of, part.deferred_facts, part.follow_up); the batch\'s completion receipt still counts the whole group. Conversation entity hints never name a retired alias page (canonical: false, superseded_by/merged_into, alias or redirect status): its canonical page is hinted instead, or nothing when the redirect cannot be followed.' },{ since: '0.60.289.0', text: 'OpenClaw context engine: when a module that assemble() loads lazily fails to load (for example, a host runtime that rejects Bun-only imports), it now prints one stderr line per module, `[gbrain] context engine: failed to load <module> (<error code>); brain context is degraded`, instead of failing silently. Context assembly still fails open, and nothing else changes.' },- // Large pages switch-on flip (Wave B PR 2 follow-up). `since` is stamped, with SEGMENTED_WRITER_FLOOR, at the merge slot.- { since: 'TBD', text: 'Pages over 1 MiB are now stored in segments: `pages.segmented_storage` is on by default. Reading a window, outline or chunk context of a large page costs the size of the window, not the page, and a rewrite re-indexes only the segments that changed. A page can be up to 256 MiB on Postgres and 128 MiB on PGLite (`pages.max_bytes` lowers it). `put_page`, `put_pages` and `capture` content and `gbrain put` stdin stay limited to 24 MiB per call, so a larger page comes in by `gbrain import` or `gbrain sync` of its file: on a source backed by files only from the file\'s own place in the checkout, which is never rewritten; a database-only source takes it by import. Pages at or under 1 MiB are stored exactly as before. `gbrain config set pages.segmented_storage off` stores new pages inline up to 24 MiB again; pages already stored in segments stay readable. The writer hold now counts any gbrain older than this release, v0.60.290.0 included (its withdrawal mirror leaves a large page\'s file unchanged and its search build can overlap another\'s): while one wrote in the last 7 days, new pages stay inline and doctor `segmented_storage` names the host to upgrade.' },+ // Large pages switch-on flip (Wave B PR 2 follow-up). `since` is stamped at the merge slot; the first row's (id+ // segmented_switch_on) is SEGMENTED_WRITER_FLOOR (page-body/writer-floor.ts).+ { since: 'TBD', text: 'Pages over 1 MiB are now stored in segments: `pages.segmented_storage` is on by default. Reading a window, outline or chunk context of a large page costs the size of the window, not the page, and a rewrite re-indexes only the segments that changed. A page can be up to 256 MiB on Postgres and 128 MiB on PGLite (`pages.max_bytes` lowers it). `put_page`, `put_pages` and `capture` content and `gbrain put` stdin stay limited to 24 MiB per call, so a larger page comes in by `gbrain import` or `gbrain sync` of its file: on a source backed by files only from the file\'s own place in the checkout, which is never rewritten; a database-only source takes it by import. Pages at or under 1 MiB are stored exactly as before. `gbrain config set pages.segmented_storage off` stores new pages inline up to 24 MiB again; pages already stored in segments stay readable. The writer hold now counts any gbrain older than this release, v0.60.290.0 included (its withdrawal mirror leaves a large page\'s file unchanged and its search build can overlap another\'s): while one wrote in the last 7 days, new pages stay inline and doctor `segmented_storage` names the host to upgrade.', id: 'segmented_switch_on' },{ since: 'TBD', text: 'With `pages.segmented_storage` on, a withdrawal (`forget`, `forget_fact`, `purge_fact`) now rewrites the canonical file of a page stored in segments on a source backed by files, as it rewrites an inline page\'s: the file loses the withdrawn or purged row, its bytes are those `gbrain export` writes for the page, and the withdrawal\'s Git effect commits it. The file is streamed from the segments into its staging file one segment at a time, and its recovery record names that staging file by path and SHA-256 instead of holding the file; the file\'s prior bytes are read in pieces too. A streamed staging file (this mirror\'s, or `restore_page`\'s for a page over 24 MiB) is written under an in-progress name and renamed once complete, so one a crash cut short is discarded and written again instead of blocking the source\'s worktree with `unexpected_staging_bytes`. Before, the withdrawal-mirror and Git effects passed such a page by (`skipped` reason `page_body_segmented`) and its file kept the withdrawn text. The content gate\'s markers (`embed_skip`, `content_flag`, `quarantine`), which the database stores and the file does not, are now set aside when a page stored in segments is compared with its file, as they are for an inline page; before, any rewrite of a marked page\'s file (a withdrawal, delete, restore or tag change) was skipped or refused as `file_database_drift`.' },{ since: 'TBD', text: 'A managed write whose statements the database ends with a statement timeout or cancel (SQLSTATE 57014, at preparation or inside its publication transaction) now counts each such interruption against `persistence.max_preparation_attempts` (default 2), together with preparations cut off at their deadline, and at the limit ends `failed` with `write_interrupted` (the receipt names the attempts, the limit and the SQLSTATE; a worktree-backed write restores its file first) instead of being released as `database_contention` and prepared again without limit. A single interruption still re-prepares and commits; a lock timeout, serialization failure or deadlock (contention with other writers), a dropped connection or a restarting database is never counted. A foreground write needs a new `request_id`; a managed sync re-freezes the file in place, and a run that stops on it is resumable (`gbrain sync status` shows class `connection`, safe action `retry`, no person needed; a rerun on the same entry ending it again names the read-only `gbrain sources writer status`). `persistence.preparation_deadlines false` turns the counting off with the deadlines.' },{ since: 'TBD', text: 'Upgrading builds the index `ingest_log_marked_idx` (migration v257): on Postgres online (`CREATE INDEX CONCURRENTLY`; reads and writes go on while it builds), on PGLite as a plain build that holds writes until it ends. It took 0.4 s for 1M `ingest_log` rows on Postgres and 0.5 s on PGLite. The segmented storage writer hold now judges every recent import, sync or connector run and resident process by its version, including those of a gbrain that already records reading segmented pages (v0.60.290.0), and the index keeps that read to the last 7 days of the log: 600 buffers on a 1M-row log, where a scan reads the whole table.' },+ { since: 'TBD', text: 'Upgrading builds the index `pages_segmented_body_bytes_idx` (migration v258) over pages stored in segments: on Postgres online (`CREATE INDEX CONCURRENTLY`), on PGLite as a plain build that holds writes until it ends. With it, the default `persistence.limits.worktree_recovery_bytes` also leaves room for the largest page already stored in segments, deleted pages included: turning `pages.segmented_storage` off or lowering `pages.max_bytes` no longer makes a delete, restore or withdrawal mirror of such a page fail with `request_too_large` (a withdrawn row stayed in its file). A value you set is kept, and a request it cannot hold is refused with `request_too_large` naming both recovery budgets and the bytes it needed.' },+ { since: 'TBD', 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 it has since written with the upgraded gbrain: it reports the hold as information with the time it clears. Another host, or an older `serve` or worker still running on this host, keeps the warning and the `gbrain upgrade` fix.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/page-body/limits.ts b/src/core/page-body/limits.tsindex 84a921e7d9..b454cc60cd 100644--- a/src/core/page-body/limits.ts+++ b/src/core/page-body/limits.ts@@ -3,8 +3,8 @@* number and config key in one place. The product numbers (ceilings, version* retention) are open product calls; change them here and nowhere else.*- * `pages.segmented_storage` defaults to `off` (SEGMENTED_STORAGE_DEFAULT); set- * `on`, it is effectively on only while no recent writer predates segmented+ * `pages.segmented_storage` defaults to `on` (SEGMENTED_STORAGE_DEFAULT); on, it+ * is effectively on only while no recent writer predates segmented* pages (`segmentedWriterBlockers`). While* it is off no page is newly segmented, every page stays inline up to* `PAGE_MAX_BYTES` (Wave A) and no code path below the inline threshold changes.@@ -138,7 +138,7 @@ export const segmentedWriterGateWork = { reads: 0 };/*** Writers seen in the last `SEGMENTED_WRITER_WINDOW_DAYS` days that do not read segmented pages* (`segmentedGateWriters`: evidence without the segment-reader mark, or marked evidence of any role stamped below- * `SEGMENTED_WRITER_FLOOR`). Any one keeps segmented storage off. Cached per engine for+ * `SEGMENTED_WRITER_FLOOR`, writer-floor.ts). Any one keeps segmented storage off. Cached per engine for* `SEGMENTED_WRITER_GATE_TTL_MS`; `fresh` (doctor) reads through.*/export async function segmentedWriterBlockers(engine: Pick<BrainEngine, 'executeRaw'>, opts: { fresh?: boolean } = {}): Promise<SegmentedGateWriter[]> {@@ -146,9 +146,9 @@ export async function segmentedWriterBlockers(engine: Pick<BrainEngine, 'executefor (let proto = Object.getPrototypeOf(root); proto && !Object.hasOwn(proto, 'constructor'); proto = Object.getPrototypeOf(proto)) root = proto;const cached = writerGate.get(root);if (!opts.fresh && cached && Date.now() - cached.at < SEGMENTED_WRITER_GATE_TTL_MS) return cached.blockers;- const { segmentedGateWriters } = await import('../persistence/writer-versions.ts');+ const [{ segmentedGateWriters }, { SEGMENTED_WRITER_FLOOR }] = await Promise.all([import('../persistence/writer-versions.ts'), import('./writer-floor.ts')]);segmentedWriterGateWork.reads++;- const blockers = await segmentedGateWriters(engine, SEGMENTED_WRITER_WINDOW_DAYS);+ const blockers = await segmentedGateWriters(engine, SEGMENTED_WRITER_WINDOW_DAYS, SEGMENTED_WRITER_FLOOR);writerGate.set(root, { at: Date.now(), blockers });return blockers;}@@ -178,33 +178,37 @@ export function segmentedMaxBytes(kind: BrainEngine['kind'], maxRaw: string | nuexport const RECOVERY_FILE_HEADROOM_BYTES = 1024 ** 2;/**- * The default `persistence.limits.worktree_recovery_bytes` (persistence/limits.ts): never below `floor`, and room for- * the largest page the configured switch admits. A restore that writes a page's file back reserves the file twice- * (persistence/coordinator.ts `pageRecoveryRecord`: its staging file and the file), so a page near the ceiling needs- * twice its body plus RECOVERY_FILE_HEADROOM_BYTES per copy. It follows the configured switch, not the writer gate: a- * page admitted while the switch was effective stays deletable and restorable while an older writer holds it off.+ * The default `persistence.limits.worktree_recovery_bytes` (persistence/limits.ts): never below `floor`, room for the+ * largest page the configured switch admits, and room for the largest page already stored in segments+ * (`storedSegmentedBytes`, deleted pages included, which a restore brings back). A restore that writes a page's file+ * back reserves the file twice (persistence/coordinator.ts `pageRecoveryRecord`: its staging file and the file), so a+ * page needs twice its body plus RECOVERY_FILE_HEADROOM_BYTES per copy. It ignores the writer gate, and a switch turned+ * off or a lowered `pages.max_bytes` never shrinks it below a stored page: that page stays deletable, restorable and+ * mirrorable (a withdrawal rewrites its file) instead of being refused `request_too_large` with its file unchanged.*/-export function pageRecoveryBytes(kind: BrainEngine['kind'], switchRaw: string | null, maxRaw: string | null, floor: number): number {+export function pageRecoveryBytes(kind: BrainEngine['kind'], switchRaw: string | null, maxRaw: string | null, floor: number, storedSegmentedBytes = 0): number {const maxBytes = segmentedStorageRequested(parseSegmentedStorage(switchRaw)) ? segmentedMaxBytes(kind, maxRaw) : PAGE_MAX_BYTES;- return Math.max(floor, 2 * (maxBytes + RECOVERY_FILE_HEADROOM_BYTES));+ return Math.max(floor, 2 * (Math.max(maxBytes, storedSegmentedBytes) + RECOVERY_FILE_HEADROOM_BYTES));}/*** Read the segmented-storage policy once per write. The switch is effectively on when it is configured `on`* (or unset while SEGMENTED_STORAGE_DEFAULT is `on`) and no recent writer predates segmented pages; an- * unreadable gate counts as blocked. A configured `pages.max_bytes` never exceeds the engine ceiling.+ * unreadable gate counts as blocked, and so does a failed read of `pages.segmented_storage` or `pages.max_bytes`+ * (only a missing row is unset, which means on). A configured `pages.max_bytes` never exceeds the engine ceiling.*/export async function readPageBodyPolicy(engine: PolicyEngine): Promise<PageBodyPolicy> {const read = (key: string) => engine.getConfig(key).catch(() => null);- const [switchRaw, maxRaw, retireRaw, versionsRaw, pinnedRaw] = await Promise.all([- read(PAGE_BODY_CONFIG_KEYS.segmentedStorage), read(PAGE_BODY_CONFIG_KEYS.maxBytes), read(PAGE_BODY_CONFIG_KEYS.flipRetireMaxRows),+ const readOrFail = (key: string) => engine.getConfig(key).then(value => ({ value }), () => null);+ const [switchRead, maxRead, retireRaw, versionsRaw, pinnedRaw] = await Promise.all([+ readOrFail(PAGE_BODY_CONFIG_KEYS.segmentedStorage), readOrFail(PAGE_BODY_CONFIG_KEYS.maxBytes), read(PAGE_BODY_CONFIG_KEYS.flipRetireMaxRows),read(PAGE_BODY_CONFIG_KEYS.versionsMaxPerPage), read(PAGE_BODY_CONFIG_KEYS.versionsMaxPinnedBytes),]);- const setting = parseSegmentedStorage(switchRaw);+ const setting = switchRead && maxRead ? parseSegmentedStorage(switchRead.value) : 'off';const segmented = segmentedStorageRequested(setting) && (await segmentedWriterBlockers(engine).catch(() => null))?.length === 0;return {segmented,- maxBytes: segmented ? segmentedMaxBytes(engine.kind, maxRaw) : PAGE_MAX_BYTES,+ maxBytes: segmented ? segmentedMaxBytes(engine.kind, maxRead!.value) : PAGE_MAX_BYTES,flipRetireMaxRows: positiveInt(retireRaw, DEFAULT_FLIP_RETIRE_MAX_ROWS),versionsMaxPerPage: positiveInt(versionsRaw, DEFAULT_SEGMENTED_VERSIONS_MAX_PER_PAGE),versionsMaxPinnedBytes: positiveInt(pinnedRaw, DEFAULT_SEGMENTED_VERSIONS_MAX_PINNED_BYTES),diff --git a/src/core/page-body/writer-floor.ts b/src/core/page-body/writer-floor.tsnew file mode 100644index 0000000000..c1cc1437bc--- /dev/null+++ b/src/core/page-body/writer-floor.ts@@ -0,0 +1,31 @@+/**+ * SEGMENTED_WRITER_FLOOR: writers older than this do not understand segmented page bodies (Wave B). A pre-Wave-B+ * binary reads a segmented page's NULL body columns; the release that added segmented storage behind the switch+ * purges, forgets and exports without its segment texts; and v0.60.290.0, which reads segments with the switch off,+ * still keeps a withdrawn row in a segmented page's file (its withdrawal mirror skips such pages) and renews a+ * projection claim it may have lost. So the floor is the release that turns the switch on: the `since` of the+ * switch-on BEHAVIOR_CHANGES row, and this build's VERSION while that row says 'TBD'. The merge-slot stamp then edits+ * only the row's `since`, a line the stamp-only "same tree" rule allows, and never a floor of its own.+ * The CHANGELOG entry that turns the switch on says "`pages.segmented_storage` is on by default" and names the same+ * release (test/large-pages/segmented-switch.test.ts). A recent writer below the floor, or one whose writes lack the+ * segment-reader mark (migration v254), keeps `pages.segmented_storage` effectively off (`page-body/limits.ts`,+ * `persistence/writer-versions.ts` `segmentedGateWriters`).+ *+ * Kept apart from writer-versions.ts, which the engines load, because the BEHAVIOR_CHANGES table pulls in its own+ * modules: the gate loads this file when it reads, and doctor loads it with its check.+ */+import { BEHAVIOR_CHANGES } from '../behavior-change-notice.ts';+import { VERSION } from '../../version.ts';++/** The `id` of the BEHAVIOR_CHANGES row that turns `pages.segmented_storage` on by default. */+export const SEGMENTED_SWITCH_ON_CHANGE = 'segmented_switch_on';++/** The floor for a switch-on row stamped `since`: that release, or `version` (this build) while it is 'TBD'. */+export function segmentedWriterFloorFor(since: string, version: string): string {+ return since === 'TBD' ? version : since;+}++const switchOn = BEHAVIOR_CHANGES.find(change => change.id === SEGMENTED_SWITCH_ON_CHANGE);+if (!switchOn) throw new Error(`BEHAVIOR_CHANGES has no row with id ${SEGMENTED_SWITCH_ON_CHANGE}`);++export const SEGMENTED_WRITER_FLOOR: string = segmentedWriterFloorFor(switchOn.since, VERSION);diff --git a/src/core/persistence/effect-recovery.ts b/src/core/persistence/effect-recovery.tsindex 486246181c..f40abd83da 100644--- a/src/core/persistence/effect-recovery.ts+++ b/src/core/persistence/effect-recovery.ts@@ -7,7 +7,7 @@ import type { Action } from '../agent-output.ts';import { isWriteTargetContained } from '../path-confine.ts';import { materializePageSnapshot } from '../page-state/materialize.ts';import type { JournalLimits } from './model.ts';-import { readJournalLimits } from './limits.ts';+import { journalLimitKey, readJournalLimits } from './limits.ts';import { lockCounters } from './journal.ts';import { digest, sha256 } from './digest.ts';import { getWorktreeBinding, type WorktreeBinding } from './ownership.ts';@@ -67,7 +67,7 @@ export async function reserveEffectRecovery(engine: BrainEngine, effect: Persist{ fix: effectStatusFix(effect) });if (!Number.isSafeInteger(bytes) || bytes < 1 || bytes > limits.brainRecoveryBytes || bytes > limits.worktreeRecoveryBytes) {throw opError('request_too_large', 'The physical mirror exceeds recovery capacity; the withdrawal remains committed.',- `Mirroring this withdrawal into its file in source ${effect.source_id} needs ${bytes} bytes of recovery space, more than the brain or worktree recovery limit (${Math.min(limits.brainRecoveryBytes, limits.worktreeRecoveryBytes)} bytes), so the file was not touched. Inspect the owner's effects and tell the user; the canonical file still holds the withdrawn text until it is mirrored.`,+ `Mirroring this withdrawal into its file in source ${effect.source_id} needs ${bytes} bytes of recovery space, more than the recovery budget (${journalLimitKey('worktreeRecoveryBytes')} ${limits.worktreeRecoveryBytes}, ${journalLimitKey('brainRecoveryBytes')} ${limits.brainRecoveryBytes}), so the file was not touched. Inspect the owner's effects and tell the user: a configured budget is theirs to raise (an unset worktree budget holds the largest page stored in segments); the canonical file still holds the withdrawn text until it is mirrored.`,{ fix: effectStatusFix(effect) });}await engine.transaction(async tx => {diff --git a/src/core/persistence/journal.ts b/src/core/persistence/journal.tsindex 9737643cf0..d8725f66e1 100644--- a/src/core/persistence/journal.ts+++ b/src/core/persistence/journal.ts@@ -784,12 +784,20 @@ export async function releaseUnpublishedClaim(engine: SqlEngine, row: WriteRequeAND state='running' AND recovery IS NULL AND publication_started=false AND ${PERSISTENCE_PROTOCOL_PREDICATE}`, [row.id, row.execution_token, reason, opts.charge === true]);}+/** A recovery larger than a budget: names both budgets and the bytes needed, since a configured budget is the user's. */+function recoveryTooLarge(bytes: number, limits: JournalLimits): OperationError {+ const worktree = journalLimitKey('worktreeRecoveryBytes'), brain = journalLimitKey('brainRecoveryBytes');+ return new OperationError('request_too_large',+ `This request needs ${bytes} bytes of recovery space, more than the recovery budget (${worktree} ${limits.worktreeRecoveryBytes}, ${brain} ${limits.brainRecoveryBytes}); nothing was changed.`,+ `A configured budget is the user's choice: ask them before raising it with gbrain config set, or unset ${worktree} for the default, which holds the largest page stored in segments.`);+}+/** Called while holding the root lock; the durable record precedes any rename. */export async function prepareRecovery(engine: BrainEngine, row: WriteRequest, recovery: RecoveryRecord, bytes: number,overrides?: Partial<JournalLimits>): Promise<void> {const limits = await readJournalLimits(engine,overrides);if (!row.worktree_id) throw new TypeError('Filesystem recovery requires a worktree.');- if (bytes > limits.worktreeRecoveryBytes || bytes > limits.brainRecoveryBytes) throw new OperationError('request_too_large', 'This request exceeds the configured recovery capacity.', 'Increase recovery capacity before submitting a new request.');+ if (bytes > limits.worktreeRecoveryBytes || bytes > limits.brainRecoveryBytes) throw recoveryTooLarge(bytes, limits);await engine.transaction(async tx => {// A crash after rename must never lose the earlier recovery reservation,// even when the deployment defaults ordinary transactions to async commit.@@ -834,9 +842,8 @@ export async function prepareRecoveries(engine: BrainEngine, members: { row: Wriif (!worktree || members.some(member => member.row.worktree_id !== worktree)) throw new TypeError('Grouped filesystem recovery requires one worktree.');const limits = knownLimits ?? await readJournalLimits(engine);const total = members.reduce((sum, member) => sum + member.bytes, 0);- if (members.some(member => member.bytes > limits.worktreeRecoveryBytes || member.bytes > limits.brainRecoveryBytes)) {- throw new OperationError('request_too_large', 'This request exceeds the configured recovery capacity.', 'Increase recovery capacity before submitting a new request.');- }+ const largest = Math.max(...members.map(member => member.bytes));+ if (largest > limits.worktreeRecoveryBytes || largest > limits.brainRecoveryBytes) throw recoveryTooLarge(largest, limits);await transaction(async tx => {const [, counters] = await pipelined(tx, [() => declareDurablePersistence(tx), () => lockCounters(tx, ['brain', `worktree:${worktree}`])]) as [unknown, Counter[]];for (const c of counters) if (Number(c.recovery_bytes) + total > (c.key === 'brain' ? limits.brainRecoveryBytes : limits.worktreeRecoveryBytes)) throw capacityError('recovery bytes currently reserved by other requests');diff --git a/src/core/persistence/limits.ts b/src/core/persistence/limits.tsindex e31db1bbe5..c9c872263f 100644--- a/src/core/persistence/limits.ts+++ b/src/core/persistence/limits.ts@@ -25,14 +25,17 @@ export function parseJournalConfigValue(key:string,value:string):number {}/*** Database configuration applies to every server sharing this brain. An unset `worktree_recovery_bytes` defaults to- * room for the largest page `pages.max_bytes` admits (page-body/limits.ts `pageRecoveryBytes`, never below 256 MiB); an+ * room for the largest page `pages.max_bytes` admits and the largest page stored in segments (page-body/limits.ts+ * `pageRecoveryBytes`, never below 256 MiB; the stored maximum is one probe of pages_segmented_body_bytes_idx, v258); an* engine that is not PGLite (or a stub without a `kind`) counts as Postgres, the larger ceiling.*/export async function readJournalLimits(engine:SqlEngine & { kind?: string },overrides?:Partial<JournalLimits>):Promise<JournalLimits> {- const rows=await engine.executeRaw<{key:string;value:string}>(`SELECT key,value FROM config WHERE key LIKE 'persistence.limits.%' OR key IN ('${PAGE_BODY_CONFIG_KEYS.segmentedStorage}','${PAGE_BODY_CONFIG_KEYS.maxBytes}')`);- const configured=new Map(rows.map(row=>[row.key,row.value]));+ const rows=await engine.executeRaw<{key:string|null;value:string|null}>(`SELECT key,value FROM config WHERE key LIKE 'persistence.limits.%' OR key IN ('${PAGE_BODY_CONFIG_KEYS.segmentedStorage}','${PAGE_BODY_CONFIG_KEYS.maxBytes}')+ UNION ALL SELECT NULL,max(body_bytes)::text FROM pages WHERE body_storage='segmented'`);+ const configured=new Map(rows.filter(row=>row.key!==null && row.value!==null).map(row=>[row.key!,row.value!]));+ const storedSegmented=Number(rows.find(row=>row.key===null)?.value ?? 0);const limits={...DEFAULT_JOURNAL_LIMITS,worktreeRecoveryBytes:pageRecoveryBytes(engine.kind === 'pglite' ? 'pglite' : 'postgres',configured.get(PAGE_BODY_CONFIG_KEYS.segmentedStorage) ?? null,- configured.get(PAGE_BODY_CONFIG_KEYS.maxBytes) ?? null,DEFAULT_JOURNAL_LIMITS.worktreeRecoveryBytes)};+ configured.get(PAGE_BODY_CONFIG_KEYS.maxBytes) ?? null,DEFAULT_JOURNAL_LIMITS.worktreeRecoveryBytes,storedSegmented)};for(const key of Object.keys(limits) as Array<keyof JournalLimits>) {const value=configured.get(journalLimitKey(key));if(value!==undefined) limits[key]=parseJournalConfigValue(journalLimitKey(key),value);diff --git a/src/core/persistence/writer-versions.ts b/src/core/persistence/writer-versions.tsindex fc80bbfd49..8e47d0cee5 100644--- a/src/core/persistence/writer-versions.ts+++ b/src/core/persistence/writer-versions.ts@@ -6,19 +6,6 @@ import type { SqlEngine } from './model.ts';/** Writers older than this may still delete database-only timeline rows during publication. */export const WRITER_VERSION_FLOOR = '0.60.5.0';export const UNSTAMPED_WRITER = 'unstamped (binary older than this release)';-/**- * Writers older than this do not understand segmented page bodies (Wave B): a pre-Wave-B binary reads a segmented- * page's NULL body columns, and the release that added segmented storage behind the switch purges, forgets and exports- * without its segment texts. A recent one keeps `pages.segmented_storage` effectively off (`page-body/limits.ts`).- * v0.60.290.0 shipped segment readers with the switch off, but its withdrawal mirror skips segmented pages and its- * projection builder renews a claim it may have lost, so the floor is the release that turns the switch on: a- * placeholder equal to the branch's VERSION until the merge-slot stamp sets it and the `since` of the switch-on- * BEHAVIOR_CHANGES row to the same release (pinned by test/large-pages/segmented-switch.test.ts). A version alone- * cannot tell a build with segment readers from a release of the same version without them (every release from- * v0.60.252.0 until the stamp has none), so the gate also requires the segment-reader mark (migration v254) on- * every write it sees: an unmarked writer blocks whatever its version, the floor included (`segmentedGateWriters`).- */-export const SEGMENTED_WRITER_FLOOR = '0.60.293.0';/** Numeric comparison on all four components; null when either side is not a version. */export function compareWriterVersions(a: string, b: string): number | null {@@ -114,17 +101,24 @@ export interface SegmentedGateWriter {}/**- * Writers seen in the last `days` that keep segmented storage off: evidence without the segment-reader mark (an- * older binary inserts NULL into a column it does not know; rows from before v254 count too), or marked evidence- * stamped below `floor` (an unparsable or missing stamp counts as below) from any role: a release below the floor- * may write the mark (v0.60.290.0 does). Admitters count in any state, so a failed or still-queued request of an+ * Writers seen in the last `days` that keep segmented storage off (`floor`: page-body/writer-floor.ts+ * SEGMENTED_WRITER_FLOOR): evidence without the segment-reader mark (an older binary inserts NULL into a column it does+ * not know; rows from before v254 count too), or marked evidence stamped below `floor` (an unparsable or missing stamp+ * counts as below) from any role. Both are needed: a version string cannot tell a build with segment readers from a+ * build of the same version without them, so an unmarked writer blocks whatever its version, and a release below the+ * floor may write the mark (v0.60.290.0 does). Admitters count in any state, so a failed or still-queued request of an* older binary is seen as well. The ingest log is read in two arms, unmarked and marked rows, each over its* window on its partial index (ingest_log_unmarked_idx, v254; ingest_log_marked_idx, v257), so the read never* scans the whole log. Not seen: an older binary that writes neither a request nor an* ingest-log row (a single-page put on a brain without managed persistence, a run that dies before logging), and* one-shot readers and exporters, which write nothing.*/-export async function segmentedGateWriters(engine: SqlEngine, days: number, floor = SEGMENTED_WRITER_FLOOR): Promise<SegmentedGateWriter[]> {+export async function segmentedGateWriters(engine: SqlEngine, days: number, floor: string): Promise<SegmentedGateWriter[]> {+ return (await segmentedGateEvidence(engine, days)).filter(row => !row.segment_reader || writerVersionBelowFloor(row.version, floor));+}++/** Every writer the gate read in the last `days`, passing or not, grouped as `segmentedGateWriters` groups them. */+export async function segmentedGateEvidence(engine: SqlEngine, days: number): Promise<SegmentedGateWriter[]> {const rows = await engine.executeRaw<Omit<SegmentedGateWriter, 'version_label' | 'last_seen' | 'requests'> & { last_seen: unknown; requests: number }>(`WITH win AS (SELECT now()-($1::double precision*interval '1 day') AS since)SELECT 'admitter' AS role,r.admitter_host_id::text AS host_id,r.principal_kind||':'||r.principal_id AS principal,r.admitter_version AS version,@@ -146,6 +140,5 @@ export async function segmentedGateWriters(engine: SqlEngine, days: number, flooFROM persistence_consumers c CROSS JOIN win WHERE c.renewed_at>=win.since GROUP BY 2,3,4,5ORDER BY last_seen DESC`, [days]);return rows.map(row => ({ role: row.role, host_id: row.host_id, principal: row.principal, version: row.version, version_label: writerVersionLabel(row.version),- segment_reader: row.segment_reader === true, last_seen: iso(row.last_seen), requests: Number(row.requests) }))- .filter(row => !row.segment_reader || writerVersionBelowFloor(row.version, floor));+ segment_reader: row.segment_reader === true, last_seen: iso(row.last_seen), requests: Number(row.requests) }));}diff --git a/src/core/schema-migrations/latest.generated.ts b/src/core/schema-migrations/latest.generated.tsindex d769ca9622..eccb95f764 100644--- a/src/core/schema-migrations/latest.generated.ts+++ b/src/core/schema-migrations/latest.generated.ts@@ -4,4 +4,4 @@// The highest schema migration version (migrate.ts LATEST_VERSION), importable without// loading the migrations themselves.-export const LATEST_SCHEMA_VERSION = 257;+export const LATEST_SCHEMA_VERSION = 258;diff --git a/src/core/schema-migrations/registry.generated.ts b/src/core/schema-migrations/registry.generated.tsindex 84adda2632..ec603d4b28 100644--- a/src/core/schema-migrations/registry.generated.ts+++ b/src/core/schema-migrations/registry.generated.ts@@ -258,6 +258,7 @@ import { v254 } from './v254-segment-reader-marks.ts';import { v255 } from './v255-page-body-staging-texts.ts';import { v256 } from './v256-chunk-retirement-index.ts';import { v257 } from './v257-ingest-log-marked-index.ts';+import { v258 } from './v258-segmented-page-size-index.ts';// Array order is historical (see HISTORICAL_ARRAY_ORDER in the generator); the// runner sorts by version before applying.@@ -514,4 +515,5 @@ export const MIGRATIONS: Migration[] = [v255,v256,v257,+ v258,];diff --git a/src/core/schema-migrations/v258-segmented-page-size-index.ts b/src/core/schema-migrations/v258-segmented-page-size-index.tsnew file mode 100644index 0000000000..51ba97afdd--- /dev/null+++ b/src/core/schema-migrations/v258-segmented-page-size-index.ts@@ -0,0 +1,33 @@+import type { Migration } from './types.ts';+import { buildIndexOnline, migrationNotice } from './helpers.ts';++// Applied by src/core/migrate.ts on the next initSchema(); see docs/ENGINES.md+// ("Canonical schema sources") for when schema.sql or a TS fragment also changes.+//+// Large pages switch-on flip: the default worktree recovery budget+// (page-body/limits.ts pageRecoveryBytes, read by persistence/limits.ts+// readJournalLimits on every journal limit read) leaves room for the largest+// page already stored in segments, so a page stored while the switch was on+// stays deletable, restorable and mirrorable after the switch goes off or+// pages.max_bytes is lowered. pages_segmented_body_bytes_idx answers+// max(body_bytes) over segmented pages with one probe from its upper end, and+// stays as small as the set of segmented pages (only pages over 1 MiB). Soft-+// deleted pages stay in it: a restore brings them back. Built online+// (CONCURRENTLY on Postgres); an interrupted build leaves an INVALID index that+// the next initSchema drops and rebuilds.+export const PAGES_SEGMENTED_BODY_BYTES_INDEX = {+ name: 'pages_segmented_body_bytes_idx',+ table: 'pages',+ sql: "CREATE INDEX IF NOT EXISTS pages_segmented_body_bytes_idx ON pages (body_bytes) WHERE body_storage = 'segmented'",+};++export const v258: Migration = {+ version: 258,+ name: 'segmented_page_size_index',+ idempotent: true,+ transaction: false,+ sql: '',+ handler: async engine => {+ await buildIndexOnline(engine, 257, PAGES_SEGMENTED_BODY_BYTES_INDEX, { notice: migrationNotice });+ },+};diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-default.json b/test/fixtures/goldens/catalog/pglite-engine-init-default.jsonindex 042f4cfd3f..710e27b08e 100644--- a/test/fixtures/goldens/catalog/pglite-engine-init-default.json+++ b/test/fixtures/goldens/catalog/pglite-engine-init-default.json@@ -1291,6 +1291,7 @@"pages_links_extracted_at_idx": "CREATE INDEX pages_links_extracted_at_idx ON public.pages USING btree (source_id, links_extracted_at)","pages_pkey": "CREATE UNIQUE INDEX pages_pkey ON public.pages USING btree (id)","pages_safe_chunk_pending_idx": "CREATE INDEX pages_safe_chunk_pending_idx ON public.pages USING btree (source_id) WHERE (chunker_version < 4)",+ "pages_segmented_body_bytes_idx": "CREATE INDEX pages_segmented_body_bytes_idx ON public.pages USING btree (body_bytes) WHERE (body_storage = 'segmented'::text)","pages_source_path_idx": "CREATE INDEX pages_source_path_idx ON public.pages USING btree (source_path) WHERE (source_path IS NOT NULL)","pages_source_path_name_idx": "CREATE INDEX pages_source_path_name_idx ON public.pages USING btree (source_id, regexp_replace(replace(btrim(source_path), chr(92), '/'::text), '^.*/'::text, ''::text)) WHERE (source_path IS NOT NULL)","pages_source_slug_key": "CREATE UNIQUE INDEX pages_source_slug_key ON public.pages USING btree (source_id, slug)",diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json b/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.jsonindex bff844dbbd..934aa322e9 100644--- a/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json+++ b/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json@@ -1291,6 +1291,7 @@"pages_links_extracted_at_idx": "CREATE INDEX pages_links_extracted_at_idx ON public.pages USING btree (source_id, links_extracted_at)","pages_pkey": "CREATE UNIQUE INDEX pages_pkey ON public.pages USING btree (id)","pages_safe_chunk_pending_idx": "CREATE INDEX pages_safe_chunk_pending_idx ON public.pages USING btree (source_id) WHERE (chunker_version < 4)",+ "pages_segmented_body_bytes_idx": "CREATE INDEX pages_segmented_body_bytes_idx ON public.pages USING btree (body_bytes) WHERE (body_storage = 'segmented'::text)","pages_source_path_idx": "CREATE INDEX pages_source_path_idx ON public.pages USING btree (source_path) WHERE (source_path IS NOT NULL)","pages_source_path_name_idx": "CREATE INDEX pages_source_path_name_idx ON public.pages USING btree (source_id, regexp_replace(replace(btrim(source_path), chr(92), '/'::text), '^.*/'::text, ''::text)) WHERE (source_path IS NOT NULL)","pages_source_slug_key": "CREATE UNIQUE INDEX pages_source_slug_key ON public.pages USING btree (source_id, slug)",diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json b/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.jsonindex f6b70b56d0..33056503bd 100644--- a/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json+++ b/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json@@ -1287,6 +1287,7 @@"pages_links_extracted_at_idx": "CREATE INDEX pages_links_extracted_at_idx ON public.pages USING btree (source_id, links_extracted_at)","pages_pkey": "CREATE UNIQUE INDEX pages_pkey ON public.pages USING btree (id)","pages_safe_chunk_pending_idx": "CREATE INDEX pages_safe_chunk_pending_idx ON public.pages USING btree (source_id) WHERE (chunker_version < 4)",+ "pages_segmented_body_bytes_idx": "CREATE INDEX pages_segmented_body_bytes_idx ON public.pages USING btree (body_bytes) WHERE (body_storage = 'segmented'::text)","pages_source_path_idx": "CREATE INDEX pages_source_path_idx ON public.pages USING btree (source_path) WHERE (source_path IS NOT NULL)","pages_source_path_name_idx": "CREATE INDEX pages_source_path_name_idx ON public.pages USING btree (source_id, regexp_replace(replace(btrim(source_path), chr(92), '/'::text), '^.*/'::text, ''::text)) WHERE (source_path IS NOT NULL)","pages_source_slug_key": "CREATE UNIQUE INDEX pages_source_slug_key ON public.pages USING btree (source_id, slug)",diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-default.json b/test/fixtures/goldens/catalog/postgres-engine-init-default.jsonindex e8391545b0..e61350d4d9 100644--- a/test/fixtures/goldens/catalog/postgres-engine-init-default.json+++ b/test/fixtures/goldens/catalog/postgres-engine-init-default.json@@ -1295,6 +1295,7 @@"pages_links_extracted_at_idx": "CREATE INDEX pages_links_extracted_at_idx ON public.pages USING btree (source_id, links_extracted_at)","pages_pkey": "CREATE UNIQUE INDEX pages_pkey ON public.pages USING btree (id)","pages_safe_chunk_pending_idx": "CREATE INDEX pages_safe_chunk_pending_idx ON public.pages USING btree (source_id) WHERE (chunker_version < 4)",+ "pages_segmented_body_bytes_idx": "CREATE INDEX pages_segmented_body_bytes_idx ON public.pages USING btree (body_bytes) WHERE (body_storage = 'segmented'::text)","pages_source_path_idx": "CREATE INDEX pages_source_path_idx ON public.pages USING btree (source_path) WHERE (source_path IS NOT NULL)","pages_source_path_name_idx": "CREATE INDEX pages_source_path_name_idx ON public.pages USING btree (source_id, regexp_replace(replace(btrim(source_path), chr(92), '/'::text), '^.*/'::text, ''::text)) WHERE (source_path IS NOT NULL)","pages_source_slug_key": "CREATE UNIQUE INDEX pages_source_slug_key ON public.pages USING btree (source_id, slug)",diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json b/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.jsonindex 3a54feede2..f40477900a 100644--- a/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json+++ b/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json@@ -1295,6 +1295,7 @@"pages_links_extracted_at_idx": "CREATE INDEX pages_links_extracted_at_idx ON public.pages USING btree (source_id, links_extracted_at)","pages_pkey": "CREATE UNIQUE INDEX pages_pkey ON public.pages USING btree (id)","pages_safe_chunk_pending_idx": "CREATE INDEX pages_safe_chunk_pending_idx ON public.pages USING btree (source_id) WHERE (chunker_version < 4)",+ "pages_segmented_body_bytes_idx": "CREATE INDEX pages_segmented_body_bytes_idx ON public.pages USING btree (body_bytes) WHERE (body_storage = 'segmented'::text)","pages_source_path_idx": "CREATE INDEX pages_source_path_idx ON public.pages USING btree (source_path) WHERE (source_path IS NOT NULL)","pages_source_path_name_idx": "CREATE INDEX pages_source_path_name_idx ON public.pages USING btree (source_id, regexp_replace(replace(btrim(source_path), chr(92), '/'::text), '^.*/'::text, ''::text)) WHERE (source_path IS NOT NULL)","pages_source_slug_key": "CREATE UNIQUE INDEX pages_source_slug_key ON public.pages USING btree (source_id, slug)",diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json b/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.jsonindex 867d8b12e2..f79128effe 100644--- a/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json+++ b/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json@@ -1291,6 +1291,7 @@"pages_links_extracted_at_idx": "CREATE INDEX pages_links_extracted_at_idx ON public.pages USING btree (source_id, links_extracted_at)","pages_pkey": "CREATE UNIQUE INDEX pages_pkey ON public.pages USING btree (id)","pages_safe_chunk_pending_idx": "CREATE INDEX pages_safe_chunk_pending_idx ON public.pages USING btree (source_id) WHERE (chunker_version < 4)",+ "pages_segmented_body_bytes_idx": "CREATE INDEX pages_segmented_body_bytes_idx ON public.pages USING btree (body_bytes) WHERE (body_storage = 'segmented'::text)","pages_source_path_idx": "CREATE INDEX pages_source_path_idx ON public.pages USING btree (source_path) WHERE (source_path IS NOT NULL)","pages_source_path_name_idx": "CREATE INDEX pages_source_path_name_idx ON public.pages USING btree (source_id, regexp_replace(replace(btrim(source_path), chr(92), '/'::text), '^.*/'::text, ''::text)) WHERE (source_path IS NOT NULL)","pages_source_slug_key": "CREATE UNIQUE INDEX pages_source_slug_key ON public.pages USING btree (source_id, slug)",diff --git a/test/fixtures/goldens/migrations/records.json b/test/fixtures/goldens/migrations/records.jsonindex 333d2bbf20..34d9699fa6 100644--- a/test/fixtures/goldens/migrations/records.json+++ b/test/fixtures/goldens/migrations/records.json@@ -1,6 +1,6 @@{"golden": {- "count": 252,+ "count": 253,"gaps": [17,18,@@ -27,6 +27,7 @@"OPEN_LOOPS_COUNTERPARTY_SOURCE_INDEX": "e9b472d9db37733e908ea40512ad3f9520d7a6729ce207b0d279d43d3beb5b2f","PAGES_NAME_LOOKUP_INDEXES": "1ca830342164b5606e96cf0090645364f9145d36178d90f166230189fe8d2705","PAGES_RECONCILE_NAME_INDEXES": "8805e35341b22324b932b1cc05030cc8f2bfc95532bf810ec35330783f29c59a",+ "PAGES_SEGMENTED_BODY_BYTES_INDEX": "c904a4f68cf190cce6bc68c03219c7b62d05b77eeb557db946a4f58a4f965e57","PAGE_TIMELINE_FTS_MAX_CHARS": "f7d29264f4144976bbe2e1ded0251095b638175f8e1d711c36f1e80d2263e172","PERSISTENCE_COMMITTED_WATERMARK_INDEX": "f472fa0acb542c1caebaaa3bc69fb2da1647e5e201239429fc02ccef0d669533","PERSISTENCE_COMPACTABLE_INDEX": "25ee657878efb41ba9ea3a7624464ddcf66407d861659456c230366e57f230a0",@@ -66,7 +67,7 @@"tableRows": "906d2413b13d76a06d5910885e47ed5c544be4ff3a2266e83146715721b24270","verifyProjectionStatistics": "0d231b04ecfbc5a4109d6fca9567bf4e8c9e9db6c3fbbb35212e026579ed6f67"},- "latest": 257,+ "latest": 258,"records": [{"handler": {@@ -4031,6 +4032,32 @@"transaction": false,"verify": "absent","version": 257+ },+ {+ "handler": {+ "form": "arrow",+ "helpers": [+ "PAGES_SEGMENTED_BODY_BYTES_INDEX",+ "PLANNER_REPAIR_TABLES",+ "analyzeAfterIndexBuild",+ "buildIndexOnline",+ "dropInvalidConcurrentIndex",+ "migrationNotice",+ "quietMigrationNotices",+ "tableRows"+ ],+ "sha256": "31dd240d88d93fffe8ae2d3193b474f303d3454924d2d4b1764cc04249b6fb82"+ },+ "idempotent": true,+ "name": "segmented_page_size_index",+ "sql": {+ "length": 0,+ "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"+ },+ "sqlFor": "absent",+ "transaction": false,+ "verify": "absent",+ "version": 258}],"versions": [@@ -4285,7 +4312,8 @@254,255,256,- 257+ 257,+ 258]},"normalizer": "migrations-record-v1"diff --git a/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json b/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.jsonindex 2fcf71b041..84414588fa 100644--- a/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json+++ b/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json@@ -1291,6 +1291,7 @@"pages_links_extracted_at_idx": "CREATE INDEX pages_links_extracted_at_idx ON public.pages USING btree (source_id, links_extracted_at)","pages_pkey": "CREATE UNIQUE INDEX pages_pkey ON public.pages USING btree (id)","pages_safe_chunk_pending_idx": "CREATE INDEX pages_safe_chunk_pending_idx ON public.pages USING btree (source_id) WHERE (chunker_version < 4)",+ "pages_segmented_body_bytes_idx": "CREATE INDEX pages_segmented_body_bytes_idx ON public.pages USING btree (body_bytes) WHERE (body_storage = 'segmented'::text)","pages_source_path_idx": "CREATE INDEX pages_source_path_idx ON public.pages USING btree (source_path) WHERE (source_path IS NOT NULL)","pages_source_path_name_idx": "CREATE INDEX pages_source_path_name_idx ON public.pages USING btree (source_id, regexp_replace(replace(btrim(source_path), chr(92), '/'::text), '^.*/'::text, ''::text)) WHERE (source_path IS NOT NULL)","pages_source_slug_key": "CREATE UNIQUE INDEX pages_source_slug_key ON public.pages USING btree (source_id, slug)",diff --git a/test/helpers/doctor-json-golden.ts b/test/helpers/doctor-json-golden.tsindex 2dfe3b5713..d17e67bdbb 100644--- a/test/helpers/doctor-json-golden.ts+++ b/test/helpers/doctor-json-golden.ts@@ -27,7 +27,7 @@ import { delimiter, join } from 'node:path';import { defineNormalizer, mapStrings, scrubKeys, scrubPaths, scrubTimestamps } from './golden.ts';import { PROVIDER_ENV_KEYS } from './provider-env.ts';import { MIGRATIONS } from '../../src/core/schema-migrations/registry.generated.ts';-import { SEGMENTED_WRITER_FLOOR } from '../../src/core/persistence/writer-versions.ts';+import { SEGMENTED_WRITER_FLOOR } from '../../src/core/page-body/writer-floor.ts';const REPO_ROOT = join(import.meta.dir, '..', '..');const CLI = join(REPO_ROOT, 'src', 'cli.ts');diff --git a/test/large-pages/recovery-budget-ceiling.slow.test.ts b/test/large-pages/recovery-budget-ceiling.slow.test.tsindex 44ebaf8903..22a2d847d9 100644--- a/test/large-pages/recovery-budget-ceiling.slow.test.ts+++ b/test/large-pages/recovery-budget-ceiling.slow.test.ts@@ -7,8 +7,10 @@* restore reserves the file twice (its staging file and the file), over 256 MiB for both pages; with* `persistence.limits.worktree_recovery_bytes` configured to that old default the restore refuses with* `request_too_large` before touching anything (the page stays deleted, no file or staging appears, nothing stays- * reserved).- * 2. Fails when: the default budget stays 256 MiB (the restore refuses), or a configured budget is overridden.+ * reserved). With `pages.segmented_storage` turned off after the page is stored, the default still holds it (it+ * follows the largest stored segmented page), so it deletes and restores byte for byte again.+ * 2. Fails when: the default budget stays 256 MiB (the restore refuses), follows the switch alone (the restore after+ * off refuses), or a configured budget is overridden.* 3. Existing coverage: segmented-delete-restore-file.slow.test.ts deletes and restores 27 and 90 MiB pages, within the* old budget; recovery-budget-default.test.ts pins the default's arithmetic.* 4. Runs on PGLite, and on Postgres when DATABASE_URL is set.@@ -131,6 +133,17 @@ async function roundTrip(engine: BrainEngine): Promise<void> {expect(fileSha(file)).toBe(original.sha);expect(stagingLeft(f)).toEqual([]);+ // Switched off after the page was stored: the default budget still follows the stored page, so it deletes and+ // restores byte for byte (the default used to follow the switch alone and refuse the restore).+ await engine.setConfig('pages.segmented_storage', 'off');+ expect(await submit(engine, f, 'delete_page', slug)).toMatchObject({ status: 'soft_deleted', noop: false });+ const afterOff = await submit(engine, f, 'restore_page', slug).catch((error: Error & { code?: string }) => ({ refused: error.code, message: error.message }));+ expect(afterOff).toMatchObject({ status: 'restored', noop: false });+ expect(statSync(file).size).toBe(original.size);+ expect(fileSha(file)).toBe(original.sha);+ expect(stagingLeft(f)).toEqual([]);+ await engine.setConfig('pages.segmented_storage', 'on');+expect(await submit(engine, f, 'delete_page', slug, { purge: true })).toMatchObject({ status: 'purged' });expect(existsSync(file)).toBe(false);await recoveryCleared(engine, f);diff --git a/test/large-pages/recovery-budget-default.test.ts b/test/large-pages/recovery-budget-default.test.tsindex 020f975205..f55a8d8e74 100644--- a/test/large-pages/recovery-budget-default.test.ts+++ b/test/large-pages/recovery-budget-default.test.ts@@ -4,7 +4,9 @@* 1. Protects: with `pages.segmented_storage on`, an unset `persistence.limits.worktree_recovery_bytes` reads as twice* the effective `pages.max_bytes` (the engine ceiling when unset) plus headroom per copy, never below 256 MiB, so* a restore of a page at the ceiling (which reserves its file twice) fits; with the switch off it stays 256 MiB. A- * configured value is kept as the user's choice, and the 1 GiB brain budget already holds the largest default.+ * configured value is kept as the user's choice, and the 1 GiB brain budget already holds the largest default. A+ * page already stored in segments keeps the default at twice its body plus headroom after the switch goes off or+ * `pages.max_bytes` is lowered (soft-deleted too, since a restore brings it back).* 2. Fails when: the default stays a flat 256 MiB under a 256 MiB (Postgres) or 128 MiB (PGLite) ceiling, follows a* `pages.max_bytes` above the ceiling, drops below 256 MiB for a lowered `pages.max_bytes`, or overrides a configured* value.@@ -17,6 +19,8 @@ import type { BrainEngine } from '../../src/core/engine.ts';import { PGLiteEngine } from '../../src/core/pglite-engine.ts';import { RECOVERY_FILE_HEADROOM_BYTES, SEGMENTED_PAGE_CEILING_BYTES, SEGMENTED_STORAGE_DEFAULT } from '../../src/core/page-body/limits.ts';import { readJournalLimits } from '../../src/core/persistence/limits.ts';+import { importFromContent } from '../../src/core/import-file.ts';+import { conversationPage } from '../helpers/conversation-page.ts';import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';import { testBackends } from '../helpers/test-backends.ts';@@ -73,6 +77,32 @@ for (const kind of testBackends()) describe(`worktree recovery default follows texpect(await worktree()).toBe(2 * (ceiling + RECOVERY_FILE_HEADROOM_BYTES));});+ test('a stored segmented page keeps room for its restore after the switch goes off or pages.max_bytes is lowered', async () => {+ const slug = 'notes/stored-at-ceiling';+ try {+ expect((await importFromContent(engine, slug, conversationPage(2 * MiB, { seed: 71 }), { noEmbed: true })).status).toBe('imported');+ expect((await engine.executeRaw<{ s: string }>('SELECT body_storage AS s FROM pages WHERE slug=$1', [slug]))[0]!.s).toBe('segmented');+ // A page stored at the ceiling while the switch was on (only its recorded size is read).+ await engine.executeRaw('UPDATE pages SET body_bytes=$2 WHERE slug=$1', [slug, ceiling]);+ const expected = 2 * (ceiling + RECOVERY_FILE_HEADROOM_BYTES);+ expect(expected).toBeGreaterThan(OLD_DEFAULT);+ await engine.setConfig('pages.segmented_storage', 'off');+ expect(await worktree()).toBe(expected);+ await engine.setConfig('pages.segmented_storage', 'on');+ await engine.setConfig('pages.max_bytes', String(64 * MiB));+ expect(await worktree()).toBe(expected);+ // A soft-deleted page can still be restored, so it still counts; a purged one does not.+ await engine.executeRaw('UPDATE pages SET deleted_at=now() WHERE slug=$1', [slug]);+ expect(await worktree()).toBe(expected);+ await engine.setConfig('persistence.limits.worktree_recovery_bytes', String(OLD_DEFAULT));+ expect(await worktree()).toBe(OLD_DEFAULT);+ } finally {+ await engine.executeRaw('DELETE FROM pages WHERE slug=$1', [slug]);+ }+ await engine.executeRaw("DELETE FROM config WHERE key='persistence.limits.worktree_recovery_bytes'");+ expect(await worktree()).toBe(OLD_DEFAULT);+ }, 120_000);+test('a configured worktree_recovery_bytes is the user\'s choice', async () => {await engine.setConfig('pages.segmented_storage', 'on');await engine.setConfig('persistence.limits.worktree_recovery_bytes', String(OLD_DEFAULT));diff --git a/test/large-pages/segmented-switch.test.ts b/test/large-pages/segmented-switch.test.tsindex f507b924cb..183051b692 100644--- a/test/large-pages/segmented-switch.test.ts+++ b/test/large-pages/segmented-switch.test.ts@@ -10,7 +10,9 @@* segment-reader mark (v254): a release at exactly the floor version without it, an older binary's import or sync* run (ingest_log), its resident heartbeat and its uncommitted requests all block; this build's do not. An* unreadable gate blocks, an unparsable stamp blocks, the 7-day window ends between day 6 and day 8, and the gate is- * read once per TTL (work counter) while doctor reads through.+ * read once per TTL (work counter) while doctor reads through. A failed read of the switch or `pages.max_bytes` keeps+ * it off (never "unset", which is on). Doctor reports a hold left only by this host's pre-upgrade writes, after a+ * later passing write of this host, as information. (The floor's derivation: segmented-writer-floor.test.ts.)* 2. Fails when: the default stays off, the gate ignores old or unstamped writers, an explicit `on` overrides the* gate, a cleared gate keeps writes inline, export sizes stored segmented pages by the write limit, a writer without* the mark passes on its version, a write path of this build stops marking, or the gate's error, window, parse or@@ -26,8 +28,8 @@ import { importFromContent } from '../../src/core/import-file.ts';import { PAGE_MAX_BYTES } from '../../src/core/page-size-policy.ts';import { _resetSegmentedWriterGateForTests, readPageBodyPolicy, SEGMENTED_WRITER_GATE_TTL_MS, SEGMENTED_WRITER_WINDOW_DAYS, segmentedPageCeiling, segmentedWriterGateWork } from '../../src/core/page-body/limits.ts';import { declarePersistenceProtocol } from '../../src/core/persistence/protocol.ts';-import { compareWriterVersions, SEGMENTED_WRITER_FLOOR, segmentedGateWriters, UNSTAMPED_WRITER } from '../../src/core/persistence/writer-versions.ts';-import { BEHAVIOR_CHANGES } from '../../src/core/behavior-change-notice.ts';+import { compareWriterVersions, segmentedGateWriters, UNSTAMPED_WRITER } from '../../src/core/persistence/writer-versions.ts';+import { SEGMENTED_WRITER_FLOOR } from '../../src/core/page-body/writer-floor.ts';import { VERSION } from '../../src/version.ts';import { localHostId } from '../../src/core/persistence/identity.ts';import { segmentedStorageCheck } from '../../src/commands/doctor/checks/segmented-storage.ts';@@ -43,13 +45,6 @@ async function storage(engine: BrainEngine, slug: string): Promise<string | undereturn (await engine.executeRaw<{ body_storage: string }>('SELECT body_storage FROM pages WHERE slug=$1', [slug]))[0]?.body_storage;}-test('SEGMENTED_WRITER_FLOOR is this build\'s VERSION until the stamp, then the release of the switch-on BEHAVIOR_CHANGES row, and never above this build', () => {- const row = BEHAVIOR_CHANGES.find(c => typeof c.text === 'string' && c.text.startsWith('Pages over 1 MiB are now stored in segments'));- expect(row).toBeDefined();- expect(row!.since === 'TBD' ? VERSION : row!.since).toBe(SEGMENTED_WRITER_FLOOR);- expect(compareWriterVersions(SEGMENTED_WRITER_FLOOR, VERSION)).toBeLessThanOrEqual(0);-});-for (const kind of testBackends()) {describe(`segmented storage switch: ${kind}`, () => {let factory: Awaited<ReturnType<typeof freshBrainFactory>>;@@ -173,7 +168,7 @@ for (const kind of testBackends()) {VALUES ('default', 'sync', $1, '[]'::jsonb, 'run', $2, $3::uuid, $4)`, [ref, version, randomUUID(), marked]);const heartbeat = (nonce: string, version: string, marked: boolean | null) => engine.executeRaw(`INSERT INTO persistence_consumers (host_id, pid, nonce, kind, mode, host_json_path, persistence_home, version, segment_reader)VALUES ($1::uuid, 4242, $2, 'serve', 'full', '/tmp/host.json', '/tmp', $3, $4)`, [randomUUID(), nonce, version, marked]);- const seen = async (floor?: string) => (await segmentedGateWriters(engine, SEGMENTED_WRITER_WINDOW_DAYS, floor)).map(b => [b.role, b.version, b.segment_reader]).sort();+ const seen = async (floor = SEGMENTED_WRITER_FLOOR) => (await segmentedGateWriters(engine, SEGMENTED_WRITER_WINDOW_DAYS, floor)).map(b => [b.role, b.version, b.segment_reader]).sort();await importRun('marked-run', SEGMENTED_WRITER_FLOOR, true);await heartbeat('marked-nonce', SEGMENTED_WRITER_FLOOR, true);@@ -267,6 +262,60 @@ for (const kind of testBackends()) {expect(await blockersNow()).toEqual([expect.objectContaining({ role: 'admitter', version: 'nightly-build', segment_reader: true })]);}), 120_000);+ test('a failed read of pages.segmented_storage or pages.max_bytes keeps the switch off; it never reads as unset (on by default)', async () => {+ const failing = (key: string) => Object.create(engine, { getConfig: { value: (k: string) => k === key+ ? Promise.reject(Object.assign(new Error('canceling statement due to statement timeout'), { code: '57014' }))+ : engine.getConfig(k) } }) as BrainEngine;+ await engine.setConfig('pages.segmented_storage', 'off');+ expect(await readPageBodyPolicy(failing('pages.segmented_storage'))).toMatchObject({ segmented: false, maxBytes: PAGE_MAX_BYTES });+ await engine.executeRaw("DELETE FROM config WHERE key='pages.segmented_storage'");+ expect(await segmentedNow()).toBe(true);+ expect(await readPageBodyPolicy(failing('pages.segmented_storage'))).toMatchObject({ segmented: false, maxBytes: PAGE_MAX_BYTES });+ await engine.setConfig('pages.max_bytes', String(8 * 1024 * 1024));+ expect(await readPageBodyPolicy(engine)).toMatchObject({ segmented: true, maxBytes: 8 * 1024 * 1024 });+ expect(await readPageBodyPolicy(failing('pages.max_bytes'))).toMatchObject({ segmented: false, maxBytes: PAGE_MAX_BYTES });+ }, 120_000);++ test('doctor: a hold left only by this host\'s writes from before it upgraded is information with its clear time; another host or a live older process on this host keeps the upgrade warning', async () => inHome(async () => {+ await engine.setConfig('pages.segmented_storage', 'on');+ const self = localHostId();+ const older = '0.60.290.0';+ expect(compareWriterVersions(older, SEGMENTED_WRITER_FLOOR)).toBeLessThan(0);+ await 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 ('default', 'sync', 'self-before-upgrade', '[]'::jsonb, 'run', $1, $2::uuid, true, now() - interval '1 hour')`, [older, self]);+ await engine.executeRaw(`INSERT INTO persistence_consumers (host_id, pid, nonce, kind, mode, host_json_path, persistence_home, version, segment_reader, renewed_at)+ VALUES ($1::uuid, 4242, 'self-old-serve', 'serve', 'full', '/tmp/host.json', '/tmp', $2, true, now() - interval '10 minutes')`, [self, older]);+ expect(await segmentedNow()).toBe(false);+ // Until this host writes with a build that passes the gate, the rows cannot be told from an older gbrain still+ // writing here: the upgrade warning stays.+ expect(await segmentedStorageCheck(engine)).toMatchObject({ status: 'warn', fix: { argv: ['gbrain', 'upgrade'] } });+ await engine.logIngest({ source_type: 'import', source_ref: 'self-after-upgrade', pages_updated: [], summary: 'this build' });+ expect(Number((await engine.executeRaw<{ n: number }>("SELECT count(*)::int AS n FROM ingest_log WHERE writer_host_id=$1::uuid AND writer_segment_reader AND writer_version=$2", [self, VERSION]))[0]!.n)).toBe(1);+ expect(await segmentedNow()).toBe(false);+ const own = await segmentedStorageCheck(engine);+ expect(own).toMatchObject({ status: 'ok', severity: 'info', details: { effective: 'off' } });+ expect(own.fix).toBeUndefined();+ const listed = own.details!.blockers as Array<{ host_id: string; role: string; version: string; clears_at: string }>;+ expect(listed.map(b => [b.host_id, b.role, b.version]).sort()).toEqual([[self, 'importer', older], [self, 'resident', older]]);+ const clears = listed.map(b => b.clears_at).sort().at(-1)!;+ expect(own.message).toContain(self);+ expect(own.message).toContain(clears);+ expect(own.message).not.toContain('gbrain upgrade');++ // An older serve on this host that is still renewing its heartbeat is a process to restart: still a warning.+ await engine.executeRaw("UPDATE persistence_consumers SET renewed_at=now() WHERE nonce='self-old-serve'");+ expect(await segmentedStorageCheck(engine)).toMatchObject({ status: 'warn', fix: { argv: ['gbrain', 'upgrade'] } });+ await engine.executeRaw("UPDATE persistence_consumers SET renewed_at=now() - interval '10 minutes' WHERE nonce='self-old-serve'");+ expect(await segmentedStorageCheck(engine)).toMatchObject({ status: 'ok', severity: 'info' });++ const other = randomUUID();+ await engine.executeRaw(`INSERT INTO ingest_log (source_id, source_type, source_ref, pages_updated, summary, writer_version, writer_host_id, writer_segment_reader)+ VALUES ('default', 'import', 'other-host', '[]'::jsonb, 'run', $1, $2::uuid, true)`, [older, other]);+ const both = await segmentedStorageCheck(engine);+ expect(both).toMatchObject({ status: 'warn', fix: { argv: ['gbrain', 'upgrade'], actor: 'host_admin' } });+ expect(both.message).toContain(other);+ }), 120_000);+test('explicit off keeps pages inline and doctor reports it as a choice', async () => {await engine.setConfig('pages.segmented_storage', 'off');expect((await importFromContent(engine, 'notes/off', content, { noEmbed: true })).status).toBe('imported');diff --git a/test/large-pages/segmented-writer-floor.test.ts b/test/large-pages/segmented-writer-floor.test.tsnew file mode 100644index 0000000000..24c2ac9832--- /dev/null+++ b/test/large-pages/segmented-writer-floor.test.ts@@ -0,0 +1,34 @@+/**+ * SEGMENTED_WRITER_FLOOR follows the switch-on BEHAVIOR_CHANGES row (page-body/writer-floor.ts).+ *+ * 1. Protects: the floor is the `since` of the row with id `segmented_switch_on` (this build's VERSION while it is+ * 'TBD'), never a version literal of its own, so the merge-slot stamp edits only allowlisted lines; and the CHANGELOG+ * entry that turns the switch on ("`pages.segmented_storage` is on by default") names that same release.+ * 2. Fails when: the floor holds its own version again, the row loses its id, or a stamp writes the switch-on CHANGELOG+ * entry and VERSION but leaves the row's since at 'TBD'.+ * 3. Structural (reads writer-floor.ts and CHANGELOG.md); no database.+ */+import { expect, test } from 'bun:test';+import { readFileSync } from 'node:fs';+import { join } from 'node:path';+import { BEHAVIOR_CHANGES } from '../../src/core/behavior-change-notice.ts';+import { SEGMENTED_SWITCH_ON_CHANGE, SEGMENTED_WRITER_FLOOR, segmentedWriterFloorFor } from '../../src/core/page-body/writer-floor.ts';+import { compareWriterVersions } from '../../src/core/persistence/writer-versions.ts';+import { VERSION } from '../../src/version.ts';++test('SEGMENTED_WRITER_FLOOR follows the switch-on BEHAVIOR_CHANGES row\'s since (this build while it is TBD), and the CHANGELOG entry that turns the switch on names that release', () => {+ const rows = BEHAVIOR_CHANGES.filter(c => (c as { id?: string }).id === SEGMENTED_SWITCH_ON_CHANGE);+ expect(rows).toHaveLength(1);+ const since = rows[0]!.since;+ expect(SEGMENTED_WRITER_FLOOR).toBe(since === 'TBD' ? VERSION : since);+ expect([segmentedWriterFloorFor('TBD', '1.2.3.4'), segmentedWriterFloorFor('0.60.294.0', '0.60.295.0')]).toEqual(['1.2.3.4', '0.60.294.0']);+ expect(compareWriterVersions(SEGMENTED_WRITER_FLOOR, VERSION)).toBeLessThanOrEqual(0);+ // The merge-slot stamp edits only allowlisted lines (the row's since, VERSION, the CHANGELOG header): the floor+ // holds no version of its own. A stamp that writes the CHANGELOG entry turning the switch on but forgets the since+ // fails here.+ expect(readFileSync(join(import.meta.dir, '../../src/core/page-body/writer-floor.ts'), 'utf8')).not.toMatch(/'\d+\.\d+\.\d+\.\d+'/);+ const announcing = readFileSync(join(import.meta.dir, '../../CHANGELOG.md'), 'utf8').split(/^## /m).slice(1)+ .filter(entry => /`pages\.segmented_storage`\)? (?:is )?(?:now )?on by default/i.test(entry)).map(entry => /^\[([^\]]+)\]/.exec(entry)?.[1]);+ expect(announcing.length).toBeLessThanOrEqual(1);+ if (announcing.length) expect(since).toBe(announcing[0]!);+});