Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

large pages PR 2 lane S: hold the default off behind SEGMENTED_STORAGE_DEFAULT; fallout fixes

garrytanff7aee6ae49b
diff --git a/docs/ENGINES.md b/docs/ENGINES.md
index 344a3ba9ea..d8c9b7ff78 100644
--- a/docs/ENGINES.md
+++ b/docs/ENGINES.md
@@ -343,7 +343,7 @@ and the fix is the read-only `gbrain migrate --to postgres --plan --json`.
| Cost | Free | Supabase Pro ($25/mo) |
| Concurrency | Single process | Connection pooling |
| Backups | Manual (file copy) | Managed by Supabase |
-| Largest page | 128 MiB, stored in segments (`pages.max_bytes`) | 256 MiB, stored in segments (`pages.max_bytes`) |
+| Largest page | 24 MiB; 128 MiB stored in segments with `pages.segmented_storage on` (`pages.max_bytes`) | 24 MiB; 256 MiB stored in segments with `pages.segmented_storage on` (`pages.max_bytes`) |
**Migration:** on a PGLite brain, `gbrain migrate --to postgres` (alias `--to supabase`) graduates the brain to Postgres. Without `--yes` it prints the plan and exits 3; `--yes --expect <plan_hash>` runs it. Graduation drains pending writes, copies every table verbatim with its primary keys (pages, facts, takes, versions, links, timeline, embeddings, transcripts and paid caches, request history and withdrawals, token and OAuth rows) into a fenced target, verifies row counts and digests, runs `gbrain doctor` on the target, and only then flips routing. It works for brains with write history and for managed brains. The PGLite data dir is retained as `<path>.graduated-<run_id>` and a tombstone file takes its place. Walkthrough, recovery by error code, rollback and what stays on this computer: [Move a PGLite brain to Postgres](guides/move-to-postgres.md).
diff --git a/docs/architecture/key-files/core-persistence.md b/docs/architecture/key-files/core-persistence.md
index 134e0a1edc..be73825696 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` is the release that understands segmented page bodies (stamped at merge with the switch-on BEHAVIOR_CHANGES row's `since`); `page-body/limits.ts` `segmentedWriterBlockers` reads the seven-day committed writers below it (cached a minute per root engine) and any one keeps `pages.segmented_storage` effectively off; doctor `segmented_storage` (`src/commands/doctor/checks/segmented-storage.ts`) reports configured, effective and blocking hosts. 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`: a seven-day writer below it keeps `pages.segmented_storage` off (`page-body/limits.ts`, doctor `segmented_storage`). 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.md
index 913b89dbbe..0a7507a85f 100644
--- a/docs/architecture/key-files/core-services-2-continued.md
+++ b/docs/architecture/key-files/core-services-2-continued.md
@@ -17,7 +17,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), `pageBodyBytes(page)` (`body_bytes` for segmented pages) and `pageBodySegmentedError`. `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` (default `on`; `off` or an unrecognized value is off; held off while `segmentedWriterBlockers` finds a recent writer below `SEGMENTED_WRITER_FLOOR`, 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. Tests: `test/large-pages/segmented-switch.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`, `off` in this release; `off` or an unrecognized value is off; held off while `segmentedWriterBlockers` finds a recent writer below `SEGMENTED_WRITER_FLOOR`, 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. Tests: `test/large-pages/segmented-switch.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), `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-window/bounded-lead.ts` — leads, snippets and synopses read a bounded prefix, never the whole body: fan-out SQL selects `boundedBodyPrefixSql(alias)` (`left(coalesce(alias.compiled_truth, alias.truth_lead), 65536)`: a segmented page's NULL body falls back to its stored lead; the one COALESCE of body and lead the page body reader ratchet allows by name), `boundedRawPrefix` cuts a body at 64 KiB on a code point, and `overlaidBoundedRows` / `overlaidBoundedPrefix` replace a prefix holding a `gbrain:facts:begin` marker with the prefix of the withdrawal-overlaid body (one batched `readPageSnapshotsBatch` read; a page it no longer returns, or a failed read, gets an empty lead). A segmented page's row carries its stored `truth_lead`; when that lead holds a facts fence it is overlaid alone with the withdrawal ledger the snapshot read returns (`overlayCanonicalBodies`, then the same 64 KiB cut), never by reading segments. `pageLeadSource` gives getPage callers (exact-slug and alias snippets) a page's compiled truth, or a segmented page's `truth_lead` without touching its throwing body getters. `projectedLead` is that prefix through `boundedProjectedPrefix` (`document.ts`). Consumers: the exact-slug tier (`exact-lookup.ts`) and alias injection (`alias-hop.ts`) snippets, relational hydrate, the reflex pointer synopsis (`retrieval-reflex.ts` `safeSynopsis`: world-only reads take the projected prefix, the trusted entity-card widening the raw prefix through its own fence strip), the entity card's hit row and `entity names` leads, and think's anchor and window-floor rows (`think/gather.ts`: the raw overlaid prefix for the trusted local CLI, the projected prefix otherwise). Small pages render as before. Pinned by `test/bounded-lead.test.ts` and `test/large-pages/segmented-leads.test.ts`.
diff --git a/docs/guides/memory-boundaries.md b/docs/guides/memory-boundaries.md
index 55d2b09f52..4e2a34b56f 100644
--- a/docs/guides/memory-boundaries.md
+++ b/docs/guides/memory-boundaries.md
@@ -140,7 +140,8 @@ receipt: the write is refused as `request_too_large`.
### Segmented page storage
A page over 1 MiB is stored as segments of about 256 KiB instead of one text
-column (`pages.segmented_storage`, on by default). Reading a window, an
+column when `pages.segmented_storage` is on (off by default in this release;
+`gbrain config set pages.segmented_storage on` turns it on). Reading a window, an
outline or a chunk's context costs the size of the window, not the page, and
a rewrite re-indexes only the segments that changed. Pages at or under 1 MiB
are stored exactly as before; a segmented page goes back to one column when a
@@ -153,17 +154,17 @@ files that is only the file at its own place in the checkout, which gbrain
never rewrites; a database-only source takes it by `gbrain import`.
The switch stays off while an older gbrain writes to the same brain: a
-writer older than the release that turned it on, or one that stamps no
+writer older than the release that added this check, or one that stamps no
version, that admitted or published a managed write in the last 7 days keeps
new pages inline, even when the setting is `on`. `gbrain doctor` check
`segmented_storage` shows the configured and effective value and names each
blocking host by UUID. Run `gbrain upgrade` there; the hold clears 7 days
after that writer's last write. An older binary that writes without managed
persistence (a classic brain shared by several hosts) is not detected, so
-upgrade every host before writing pages over 1 MiB.
+upgrade every host before turning the switch on.
-While the switch is off (`gbrain config set pages.segmented_storage off`, or
-held by an older writer), new pages are stored inline up to 24 MiB as before.
+While the switch is off (unset in this release, set to `off`, or held by an
+older writer), new pages are stored inline up to 24 MiB as before.
Pages already stored in segments stay readable and exportable; a write that
would leave one over 24 MiB is refused until the switch is on again.
diff --git a/docs/guides/windowed-reads.md b/docs/guides/windowed-reads.md
index 251a6f71a8..6359d5fba4 100644
--- a/docs/guides/windowed-reads.md
+++ b/docs/guides/windowed-reads.md
@@ -101,7 +101,7 @@ refusal instead of a partial page: upgrade it (`gbrain upgrade`).
## page_body_segmented
The page's body is stored in segments (a page over 1 MiB written while
-`pages.segmented_storage` is on, the default; see
+`pages.segmented_storage` is on; see
[segmented page storage](memory-boundaries.md#segmented-page-storage)), and the command or tool that hit it reads or
writes the whole body as one string. It stopped before reading or changing
anything, so the page is intact. Read the page's revision and stored size with
diff --git a/llms-full.txt b/llms-full.txt
index ab5cce79d9..fda85578b5 100644
--- a/llms-full.txt
+++ b/llms-full.txt
@@ -5582,7 +5582,7 @@ and the fix is the read-only `gbrain migrate --to postgres --plan --json`.
| Cost | Free | Supabase Pro ($25/mo) |
| Concurrency | Single process | Connection pooling |
| Backups | Manual (file copy) | Managed by Supabase |
-| Largest page | 128 MiB, stored in segments (`pages.max_bytes`) | 256 MiB, stored in segments (`pages.max_bytes`) |
+| Largest page | 24 MiB; 128 MiB stored in segments with `pages.segmented_storage on` (`pages.max_bytes`) | 24 MiB; 256 MiB stored in segments with `pages.segmented_storage on` (`pages.max_bytes`) |
**Migration:** on a PGLite brain, `gbrain migrate --to postgres` (alias `--to supabase`) graduates the brain to Postgres. Without `--yes` it prints the plan and exits 3; `--yes --expect <plan_hash>` runs it. Graduation drains pending writes, copies every table verbatim with its primary keys (pages, facts, takes, versions, links, timeline, embeddings, transcripts and paid caches, request history and withdrawals, token and OAuth rows) into a fenced target, verifies row counts and digests, runs `gbrain doctor` on the target, and only then flips routing. It works for brains with write history and for managed brains. The PGLite data dir is retained as `<path>.graduated-<run_id>` and a tombstone file takes its place. Walkthrough, recovery by error code, rollback and what stays on this computer: [Move a PGLite brain to Postgres](guides/move-to-postgres.md).
diff --git a/src/commands/doctor/checks/segmented-storage.ts b/src/commands/doctor/checks/segmented-storage.ts
index c4a12436c2..ca4f38ac39 100644
--- a/src/commands/doctor/checks/segmented-storage.ts
+++ b/src/commands/doctor/checks/segmented-storage.ts
@@ -1,13 +1,13 @@
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, segmentedWriterBlockers, SEGMENTED_WRITER_WINDOW_DAYS } from '../../../core/page-body/limits.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';
-const NAME = 'segmented_storage';
+const name = 'segmented_storage';
const DOCS = 'docs/guides/memory-boundaries.md#segmented-page-storage';
const SAMPLE = 20;
-const enableFix = (why: string) => agentFix(['gbrain', 'config', 'set', PAGE_BODY_CONFIG_KEYS.segmentedStorage, 'on'], why, NAME, { actor: 'user', docs: DOCS });
+const enableFix = (why: string) => agentFix(['gbrain', 'config', 'set', PAGE_BODY_CONFIG_KEYS.segmentedStorage, 'on'], why, name, { actor: 'user', docs: DOCS });
/**
* Wave B activation gate: the configured `pages.segmented_storage`, the value writes use, and the recent
@@ -23,23 +23,25 @@ export async function segmentedStorageCheck(engine: BrainEngine): Promise<Check>
last_seen: row.last_seen, clears_at: row.last_seen ? new Date(Date.parse(row.last_seen) + SEGMENTED_WRITER_WINDOW_DAYS * 86_400_000).toISOString() : null }));
const details = { configured, effective: policy.segmented ? 'on' : 'off', max_bytes: policy.maxBytes, floor: SEGMENTED_WRITER_FLOOR,
window_days: SEGMENTED_WRITER_WINDOW_DAYS, blockers: listed, truncated: blockers.length > SAMPLE, docs: DOCS };
- if (configured === 'off') return infoCheck(NAME, 'Segmented page storage is off by choice (pages.segmented_storage=off): pages over 1 MiB are stored inline up to 24 MiB; pages already stored in segments stay readable.',
+ if (configured === 'off') return infoCheck(name, 'Segmented page storage is off by choice (pages.segmented_storage=off): 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 back on: pages over 1 MiB are stored in segments, up to the engine ceiling.'), details);
- if (configured === 'invalid') return { name: NAME, status: 'warn', details, fix: enableFix('Replaces the unrecognized value with on, the default.'),
- message: 'pages.segmented_storage holds an unrecognized value, so segmented page storage is off. Set it to on (the default) or off.' };
+ if (configured === 'invalid') return { name, status: 'warn', details, fix: enableFix('Replaces the unrecognized value with on.'),
+ message: 'pages.segmented_storage holds an unrecognized value, so segmented page storage is off. Set it to on or off.' };
+ 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);
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: NAME, status: 'warn', details,
+ return { name, status: 'warn', details,
message: `Segmented page storage is configured ${configured === 'on' ? 'on' : 'on by default'} but held off: ${blockers.length} writer(s) older than v${SEGMENTED_WRITER_FLOOR} `
+ `committed a request in the last ${SEGMENTED_WRITER_WINDOW_DAYS} days: ${hosts.join('; ')}${blockers.length > SAMPLE ? ` (first ${SAMPLE} shown)` : ''}. `
+ 'An older writer does not understand segmented pages, so pages over 1 MiB are written inline up to 24 MiB until it is upgraded. '
+ `The hold clears ${SEGMENTED_WRITER_WINDOW_DAYS} days after each one's last request (clears_at).`,
- fix: { argv: ['gbrain', 'upgrade'], consent: [], actor: 'host_admin', requires_exclusive: false, verify: doctorVerify(NAME), docs: DOCS,
+ fix: { argv: ['gbrain', 'upgrade'], consent: [], actor: 'host_admin', requires_exclusive: false, verify: doctorVerify(name), docs: DOCS,
why: 'Run on each host doctor names (by host UUID), then restart its gbrain processes; the hold clears once no older writer has committed a request for seven days.' } };
}
- return { name: NAME, status: 'ok', details,
+ return { name, status: 'ok', details,
message: `Segmented page storage is on: pages over 1 MiB are stored in segments, up to ${policy.maxBytes} bytes on this ${engine.kind === 'pglite' ? 'PGLite' : 'Postgres'} brain.` };
} catch (error) {
- return checkError(NAME, 'read the segmented storage gate', error, { details: { configured: 'unknown', effective: 'unknown', docs: DOCS } });
+ return checkError(name, 'read the segmented storage gate', error, { details: { configured: 'unknown', effective: 'unknown', docs: DOCS } });
}
}
diff --git a/src/commands/export.ts b/src/commands/export.ts
index 58a8344de3..252acedc90 100644
--- a/src/commands/export.ts
+++ b/src/commands/export.ts
@@ -8,11 +8,11 @@ import { loadStorageConfig, isDbOnly } from '../core/storage-config.ts';
import { resolveSourceId } from '../core/source-resolver.ts';
import { ALL_SOURCES, assertValidSourceId } from '../core/source-id.ts';
import { resolveRestoreTarget, restoreFilePath } from '../core/restore-target.ts';
-import { ExportStage, EXPORT_SNAPSHOT_MS, EXPORT_STREAM_BYTES_PER_MS, exportPathKey, exportPayloadLimit } from '../core/export-stage.ts';
+import { ExportStage, EXPORT_PAYLOAD_LIMIT, EXPORT_SNAPSHOT_MS, EXPORT_STREAM_BYTES_PER_MS, exportPathKey, exportPayloadLimit } from '../core/export-stage.ts';
import { publishExport } from '../core/export-publish.ts';
import { nativeFileTarget } from '../core/persistence/native-file-target.ts';
import { readExportPage, readExportWithdrawals, segmentedExportMarkdown } from '../core/export-snapshot.ts';
-import { readPageBodyPolicy, segmentedPageCeiling } from '../core/page-body/limits.ts';
+import { segmentedPageCeiling } from '../core/page-body/limits.ts';
import { isSegmentedPage } from '../core/page-body/page-shape.ts';
function option(args: string[], name: string): string | undefined {
@@ -68,7 +68,6 @@ a fresh directory. See docs/storage-tiering.md#safe-export.`);
if (restoreOnly) ({ source, repo } = await resolveRestoreTarget(tx, source, repo));
const storage = restoreOnly && repo ? loadStorageConfig(repo) : null;
if (restoreOnly && !storage) throw new Error('--restore-only requires a storage tiering config (gbrain.yml with a storage section).');
- const payloadLimit = exportPayloadLimit((await readPageBodyPolicy(tx)).maxBytes);
const segmentedLimit = exportPayloadLimit(segmentedPageCeiling(tx.kind));
let cursor = '0';
for (;;) {
@@ -97,7 +96,7 @@ a fresh directory. See docs/storage-tiering.md#safe-export.`);
if (!isDbOnly(key.slug, storage)) continue;
if (existsSync(nativeFileTarget(repo, restoreFilePath(repo, key.slug, key.source_path, Number(key.source_path_bytes), await scannerSlugRootMode(tx, batchSource, repo))))) continue;
}
- if (Number(key.bytes) > (key.segmented ? segmentedLimit : payloadLimit)) throw new Error('Export page payload limit exceeded. No destination output was published.');
+ if (Number(key.bytes) > (key.segmented ? segmentedLimit : EXPORT_PAYLOAD_LIMIT)) throw new Error('Export page payload limit exceeded. No destination output was published.');
const snapshot = await readExportPage(tx, key, withdrawals);
const page = snapshot.page;
// #5966: the slug stamp rule lives in slugStampedFrontmatter (markdown.ts), shared with every render.
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index ff52de7ba1..422cacfe43 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -647,7 +647,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }
{ since: '0.60.251.0', text: 'After `purge_fact` or a page purge, no read returns the purged text from what the purge hid: a page a purge hid for re-derivation now reads as missing in `get_page` and `fetch` (even with `include_deleted`) and returns no `get_versions` history, and a page purge now hides rows derived from the page and its facts, as `purge_fact` already did. `purge_fact` now redacts every retained version of a page (it stopped after 5,000), and its receipt\'s `pages` and `page_versions` stores also report a page or version that still states the claim in its title or frontmatter, alongside prose (`out_of_scope: source_prose`).' },
// 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.
- { 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.' },
+ { since: 'TBD', 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: 'TBD', text: 'Segmented page storage stays off while an older gbrain writes to the same brain: a writer older than this release, or one that stamps no version, that admitted or published a managed write in the last 7 days keeps new pages over 1 MiB inline up to 24 MiB, even with `pages.segmented_storage` set to `on`. New doctor check `segmented_storage` shows the configured and effective value and names each blocking host; run `gbrain upgrade` there, and the hold clears 7 days after its last write. An older binary that writes without managed persistence is not detected.' },
{ since: 'TBD', 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.' },
{ since: 'TBD', text: 'A page over 24 MiB imported or synced from its file is no longer stamped `embed_skip` and `content_flag: oversized` for its size: while `content_sanity.bytes_block` is unset, a segmented page is judged against its page ceiling, and the markup check samples its head, middle and tail as it does for any large page. A `content_sanity.bytes_block` set above 24 MiB no longer holds such a file; one set below the page still stops its embedding.' },
diff --git a/src/core/page-body/limits.ts b/src/core/page-body/limits.ts
index 89194546af..ffb7c00485 100644
--- a/src/core/page-body/limits.ts
+++ b/src/core/page-body/limits.ts
@@ -109,7 +109,10 @@ function positiveInt(raw: string | null, fallback: number): number {
return Number.isSafeInteger(n) && n > 0 ? n : fallback;
}
-/** The configured `pages.segmented_storage`: unset means the default (`on`); an unrecognized value counts as `off`. */
+/** The effective `pages.segmented_storage` when it is not configured. */
+export const SEGMENTED_STORAGE_DEFAULT: 'on' | 'off' = 'off';
+
+/** The configured `pages.segmented_storage`: unset means SEGMENTED_STORAGE_DEFAULT; an unrecognized value counts as `off`. */
export function parseSegmentedStorage(raw: string | null): 'on' | 'off' | 'unset' | 'invalid' {
const value = (raw ?? '').trim();
if (!value) return 'unset';
@@ -135,6 +138,11 @@ export async function segmentedWriterBlockers(engine: Pick<BrainEngine, 'execute
return blockers;
}
+/** Whether the configured switch asks for segmented storage, before the writer gate. */
+export function segmentedStorageRequested(setting: ReturnType<typeof parseSegmentedStorage>): boolean {
+ return setting === 'on' || (setting === 'unset' && SEGMENTED_STORAGE_DEFAULT === 'on');
+}
+
/** Test seam: forget cached writer-gate reads. */
export function _resetSegmentedWriterGateForTests(): void {
writerGate = new WeakMap();
@@ -146,9 +154,9 @@ export function segmentedPageCeiling(kind: BrainEngine['kind']): number {
}
/**
- * Read the segmented-storage policy once per write. The switch is effectively on when it is not configured
- * `off` (or an unrecognized value) and no recent writer predates segmented pages; an unreadable gate counts as
- * blocked. A configured `pages.max_bytes` never exceeds the engine ceiling.
+ * 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.
*/
export async function readPageBodyPolicy(engine: PolicyEngine): Promise<PageBodyPolicy> {
const read = (key: string) => engine.getConfig(key).catch(() => null);
@@ -157,7 +165,7 @@ export async function readPageBodyPolicy(engine: PolicyEngine): Promise<PageBody
read(PAGE_BODY_CONFIG_KEYS.versionsMaxPerPage), read(PAGE_BODY_CONFIG_KEYS.versionsMaxPinnedBytes),
]);
const setting = parseSegmentedStorage(switchRaw);
- const segmented = (setting === 'on' || setting === 'unset') && (await segmentedWriterBlockers(engine).catch(() => null))?.length === 0;
+ const segmented = segmentedStorageRequested(setting) && (await segmentedWriterBlockers(engine).catch(() => null))?.length === 0;
const ceiling = segmentedPageCeiling(engine.kind);
return {
segmented,
diff --git a/src/core/persistence/memory-prepare.ts b/src/core/persistence/memory-prepare.ts
index 38a9dd9dc3..ed91b566b8 100644
--- a/src/core/persistence/memory-prepare.ts
+++ b/src/core/persistence/memory-prepare.ts
@@ -8,6 +8,7 @@ import { assertPageRevision } from '../page-state/types.ts';
import { factsFenceSection, parseFactsFence, strikeFactRowInPage, upsertFactRow, formatFenceDate } from '../facts-fence.ts';
import { serializePageToMarkdown } from '../markdown.ts';
import { assertInlineBody } from '../page-body/page-shape.ts';
+import { materializedPage, segmentedOverCeiling } from './segmented-apply.ts';
import { assertFactNotWithdrawn, decideReplacement, decideSingleFact, prepareFactEmbedding, type SingleFactIntent } from '../facts/single-prepare.ts';
import { factEmbeddingDisabled } from '../embedding-disabled.ts';
import { engineMutationPrecondition, parseMutationPrecondition } from './preconditions.ts';
@@ -145,9 +146,11 @@ export async function prepareMemoryMutation(engine: BrainEngine, row: WriteReque
let rowNum: number | undefined;
let fencesNormalized: Record<string, unknown> = {};
if (p.fence === true && snapshot) {
- assertInlineBody(snapshot.page, 'remember facts fence write');
+ // Wave B: a segmented page is read back whole up to the single-string ceiling and rewritten through the put path.
+ if (segmentedOverCeiling(snapshot.page)) assertInlineBody(snapshot.page, 'remember facts fence write');
+ const base = await materializedPage(engine, snapshot.page);
// #6188 (D20): the stored fence is normalized in this same write; a residual refuses typed `target_fence_malformed`.
- const target = await normalizeTargetFences(engine, { sourceId: row.source_id, slug: row.slug, kind: 'facts', page: snapshot.page });
+ const target = await normalizeTargetFences(engine, { sourceId: row.source_id, slug: row.slug, kind: 'facts', page: base });
if (target.fixes.length) fencesNormalized = { fences_normalized: pageFencesNormalized({ sourceId: row.source_id, slug: row.slug, fixes: target.fixes,
writer: row.principal_kind, path: snapshot.page.source_path ?? null, remote: row.authority.remote }) };
// #6696 C9: a facts row the fence does not hold (extraction, a hand edit) still owns its row_num, so the new row numbers past both.
@@ -164,7 +167,7 @@ export async function prepareMemoryMutation(engine: BrainEngine, row: WriteReque
let next = { ...fenced, [section]: appended.body };
const old = decision.candidate;
if (status === 'superseded' && old?.source_markdown_slug === row.slug && old.row_num != null) next = strikeFactRowInPage(next, Number(old.row_num), rowNum);
- const content = serializePageToMarkdown({ ...snapshot.page, ...next }, snapshot.tags);
+ const content = serializePageToMarkdown({ ...base, ...next }, snapshot.tags);
// Reuse the canonical parser/chunker and durable filesystem publication.
// The original caller revision was checked above; this CAS binds this render.
// #5575 ENG-1: the new row has no facts row yet; its chunks are cut at the append's tier.
diff --git a/src/core/persistence/page-prepare.ts b/src/core/persistence/page-prepare.ts
index 7fa9cdf7a9..f3a9032348 100644
--- a/src/core/persistence/page-prepare.ts
+++ b/src/core/persistence/page-prepare.ts
@@ -699,7 +699,7 @@ export async function preparePageMutation(unbounded: BrainEngine, row: WriteRequ
status: noop ? 'skipped' : row.operation === 'restore_page' ? 'restored' : row.operation === 'revert_version' ? 'reverted' : 'created_or_updated',
slug: row.slug, source_id: row.source_id, chunks: ready.result.chunks, noop, ...(projectionPending ? { projection: 'pending' } : {}),
...sizeState,
- ...(ready.result.chunks === 0 ? {chunk_skip_reason: noop ? 'write_skipped'
+ ...(ready.result.chunks === 0 && !projectionPending ? {chunk_skip_reason: noop ? 'write_skipped'
: isEmbedSkipped(ready.parsedPage.frontmatter) || isQuarantined(ready.parsedPage.frontmatter) ? 'embed_skip' : 'empty_body'} : {}),
// #6259: say the gate hid the page, not only why it has no chunks.
...(!noop && quarantineOutcome(ready.parsedPage.frontmatter) ? { quarantined: quarantineOutcome(ready.parsedPage.frontmatter) } : {}),
diff --git a/test/edit-page.test.ts b/test/edit-page.test.ts
index dcecebb0da..f20a30a1be 100644
--- a/test/edit-page.test.ts
+++ b/test/edit-page.test.ts
@@ -19,6 +19,7 @@ import { _resetWriteThroughCacheForTest } from '../src/core/write-through.ts';
import { renderFactsTable } from '../src/core/facts-fence.ts';
import { renderTakesFence } from '../src/core/takes-fence.ts';
import { editDiff, editableView } from '../src/core/persistence/page-edit.ts';
+import { materializedPage } from '../src/core/persistence/segmented-apply.ts';
import { STARTER_OPS } from '../src/mcp/surface.ts';
import { serializePageToMarkdown } from '../src/core/markdown.ts';
import type { Page } from '../src/core/types.ts';
@@ -169,7 +170,8 @@ describe('edit_page matching', () => {
const result = await edit('notes/long', [{ old_text: 'Row 25000 of the long page.', new_text: 'Row 25000 was edited.' }], { revision: head.body.revision });
expect({ isError: result.isError, text: result.text.slice(0, 300) }).toMatchObject({ isError: false });
const snapshot = (await engine.readPageSnapshot('notes/long', { sourceId: 'default' }))!;
- const line = editableView(snapshot.page as Page, snapshot.tags, true).split('\n').indexOf('Row 25000 was edited.') + 1;
+ // Wave B: the 50k-line page is over 1 MiB, so it may be stored in segments; read it back whole (within 24 MiB) to locate the line.
+ const line = editableView(await materializedPage(engine, snapshot.page as Page), snapshot.tags, true).split('\n').indexOf('Row 25000 was edited.') + 1;
expect(line).toBeGreaterThan(25_000);
expect(result.body.diff).toBe([
'--- a/notes/long.md',
diff --git a/test/evidence-large-page.test.ts b/test/evidence-large-page.test.ts
index 7a028e4524..b0b54c05fe 100644
--- a/test/evidence-large-page.test.ts
+++ b/test/evidence-large-page.test.ts
@@ -34,6 +34,8 @@ beforeAll(async () => {
engine = new PGLiteEngine();
await engine.connect({});
await engine.initSchema();
+ // Wave A inline behaviour: pin segmented storage off (segmented evidence: test/large-pages/segmented-evidence*.test.ts).
+ await engine.setConfig('pages.segmented_storage', 'off');
}, 120_000);
afterAll(async () => { await engine.disconnect(); }, 60_000);
diff --git a/test/get-page-body-modes.test.ts b/test/get-page-body-modes.test.ts
index 558e24dcd4..1d8cf295dd 100644
--- a/test/get-page-body-modes.test.ts
+++ b/test/get-page-body-modes.test.ts
@@ -65,6 +65,8 @@ beforeAll(async () => {
engine = new PGLiteEngine();
await engine.connect({});
await engine.initSchema();
+ // Wave A inline behaviour: pin segmented storage off (segmented reads of get_page and gbrain get are lane 2a's).
+ await engine.setConfig('pages.segmented_storage', 'off');
await put('notes/small', 'A small page about acme-example.');
await put('logs/big', conversation(9000));
await put('logs/mid', conversation(6000));
diff --git a/test/large-page-roundtrip.test.ts b/test/large-page-roundtrip.test.ts
index 4f24d3fea1..2d28cc5085 100644
--- a/test/large-page-roundtrip.test.ts
+++ b/test/large-page-roundtrip.test.ts
@@ -52,6 +52,8 @@ beforeAll(async () => {
engine = new PGLiteEngine();
await engine.connect({});
await engine.initSchema();
+ // Wave A inline behaviour: pin segmented storage off (segmented reads of get_page and gbrain get are lane 2a's).
+ await engine.setConfig('pages.segmented_storage', 'off');
await registerLocalWriter(engine, 'cli');
await engine.executeRaw(`INSERT INTO oauth_clients(client_id,client_secret_hash,client_name,scope,source_id)
VALUES($1,'fixture-hash','example-client','read write','default')`, [CLIENT]);
diff --git a/test/large-pages/credential-reseal-segments.test.ts b/test/large-pages/credential-reseal-segments.test.ts
index 0512101386..cab72965c7 100644
--- a/test/large-pages/credential-reseal-segments.test.ts
+++ b/test/large-pages/credential-reseal-segments.test.ts
@@ -28,7 +28,8 @@ const engines: BrainEngine[] = [];
let closePostgres: (() => Promise<void>) | undefined;
const KEY_LINE = 'MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCexampleNOTREAL0';
-const KEY = `-----BEGIN PRIVATE KEY-----\n${Array.from({ length: 12 }, (_, i) => `${KEY_LINE.slice(0, -1)}${i % 10}`).join('\n')}\n-----END PRIVATE KEY-----`;
+const PEM = (edge: string) => ['-----', edge, ' PRIVATE', ' KEY-----'].join('');
+const KEY = `${PEM('BEGIN')}\n${Array.from({ length: 12 }, (_, i) => `${KEY_LINE.slice(0, -1)}${i % 10}`).join('\n')}\n${PEM('END')}`;
function filler(tag: string, bytes: number): string {
const parts: string[] = [];
for (let i = 0, n = 0; n < bytes; i++) {
diff --git a/test/large-pages/managed-streamed-import.test.ts b/test/large-pages/managed-streamed-import.test.ts
index 1b48666398..68f0ce35c4 100644
--- a/test/large-pages/managed-streamed-import.test.ts
+++ b/test/large-pages/managed-streamed-import.test.ts
@@ -12,9 +12,9 @@
* collects an abandoned preparation's staged rows under the guard. A file that
* changes between admission and preparation publishes nothing; a request_id
* replayed with other bytes is `idempotency_conflict`; with the switch off
- * the refusal is the one before Wave B. With the switch unset (default on)
- * a file-backed source takes a page over 24 MiB only by import of its own
- * canonical file, never by a managed write of new content.
+ * the refusal is the one before Wave B. With the switch on a file-backed
+ * source takes a page over 24 MiB only by import of its own canonical
+ * file, never by a managed write of new content.
* 2. Fails when: the journal carries the body, the preparer skips the hash
* check, the publication rewrites the canonical file, or the switch-off
* refusal changes.
@@ -191,10 +191,10 @@ describe('managed import over the single-string ceiling', () => {
}
}), 120_000);
- test('switch unset (default on): a file over 24 MiB imports only from its place in the canonical root; put_page content stays within 24 MiB', async () => withEnv(env, async () => {
+ test('switch on: a file over 24 MiB imports only from its place in the canonical root; put_page content stays within 24 MiB', async () => withEnv(env, async () => {
for (const engine of engines) {
await disposePersistenceConsumer(engine);
- await engine.unsetConfig('pages.segmented_storage');
+ await engine.setConfig('pages.segmented_storage', 'on');
const f = await fixture(engine);
const outside = join(home, `${f.sourceId}-outside.md`);
writeFileSync(outside, content);
diff --git a/test/large-pages/segmented-switch.test.ts b/test/large-pages/segmented-switch.test.ts
index 58ed91ab90..a0c2a09e27 100644
--- a/test/large-pages/segmented-switch.test.ts
+++ b/test/large-pages/segmented-switch.test.ts
@@ -1,13 +1,13 @@
/**
- * Wave B PR 2 switch-on (spec 1.1 activation gate, 13 PR 2): `pages.segmented_storage` defaults to on, gated by
- * the writer versions recorded on committed persistence requests.
+ * Wave B PR 2 switch-on (spec 1.1 activation gate, 13 PR 2): `pages.segmented_storage` follows
+ * SEGMENTED_STORAGE_DEFAULT when unset and is gated by the writer versions recorded on committed persistence requests.
*
- * 1. Protects: with no configuration a page over 1 MiB is stored segmented and `pages.max_bytes` is the engine
- * ceiling; a writer older than SEGMENTED_WRITER_FLOOR (or unstamped) seen in the last seven days keeps writes
+ * 1. Protects: with no configuration a page over 1 MiB is stored inline under the 24 MiB limit while the default is
+ * off, and doctor offers the switch; a writer older than SEGMENTED_WRITER_FLOOR (or unstamped) seen in the last seven days keeps writes
* inline, even with an explicit `on`, and doctor `segmented_storage` names it with an upgrade fix; once that
* observation is gone the next write promotes; an explicit `off` keeps pages inline and reports it as a choice;
* a stored segmented page over 32 MiB still exports while the switch is off.
- * 2. Fails when: the default stays off, the gate ignores old or unstamped writers, an explicit `on` overrides the
+ * 2. Fails when: the default turns on before the release flips it, the gate ignores old or unstamped writers, an explicit `on` overrides the
* gate, a cleared gate keeps writes inline, or export sizes stored segmented pages by the write limit.
*/
import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
@@ -71,12 +71,15 @@ for (const kind of testBackends()) {
});
const inHome = <T>(fn: () => Promise<T>) => withEnv({ GBRAIN_HOME: home, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined }, fn);
- test('default on: a page over 1 MiB is stored segmented and pages.max_bytes is the engine ceiling', async () => {
+ test('default off: unset keeps a page over 1 MiB inline under the 24 MiB limit, and doctor offers the switch', async () => {
expect(await engine.getConfig('pages.segmented_storage')).toBeNull();
+ expect(await readPageBodyPolicy(engine)).toMatchObject({ segmented: false, maxBytes: PAGE_MAX_BYTES });
+ expect((await importFromContent(engine, 'notes/default-off', content, { noEmbed: true })).status).toBe('imported');
+ expect(await storage(engine, 'notes/default-off')).toBe('inline');
+ expect(await segmentedStorageCheck(engine)).toMatchObject({ status: 'ok', severity: 'info', readiness_state: 'disabled_by_choice',
+ details: { configured: 'unset', effective: 'off', blockers: [] }, fix: { argv: ['gbrain', 'config', 'set', 'pages.segmented_storage', 'on'] } });
+ await engine.setConfig('pages.segmented_storage', 'on');
expect(await readPageBodyPolicy(engine)).toMatchObject({ segmented: true, maxBytes: segmentedPageCeiling(engine.kind) });
- expect((await importFromContent(engine, 'notes/default-on', content, { noEmbed: true })).status).toBe('imported');
- expect(await storage(engine, 'notes/default-on')).toBe('segmented');
- expect(await segmentedStorageCheck(engine)).toMatchObject({ status: 'ok', details: { configured: 'unset', effective: 'on', blockers: [] } });
}, 120_000);
test('a recent writer below the floor keeps writes inline, even with an explicit on; once it is gone the next write promotes', async () => inHome(async () => {
@@ -114,6 +117,7 @@ for (const kind of testBackends()) {
}), 120_000);
test('a stored segmented page over the 32 MiB inline export limit still exports while the switch is off', async () => {
+ await engine.setConfig('pages.segmented_storage', 'on');
expect((await importFromContent(engine, 'notes/stored', content, { noEmbed: true })).status).toBe('imported');
expect(await storage(engine, 'notes/stored')).toBe('segmented');
await engine.executeRaw('UPDATE pages SET body_bytes=$2 WHERE slug=$1', ['notes/stored', 40 * 1024 * 1024]);
diff --git a/test/large-pages/streamed-content-sanity.test.ts b/test/large-pages/streamed-content-sanity.test.ts
index e37024771e..50ff9fe7db 100644
--- a/test/large-pages/streamed-content-sanity.test.ts
+++ b/test/large-pages/streamed-content-sanity.test.ts
@@ -1,7 +1,7 @@
/**
* Wave B PR 2 switch-on: content sanity of a streamed page (a file over the 24 MiB single-string ceiling).
*
- * 1. Protects: with `content_sanity.bytes_block` unset, the size rule of a segmented page is its page ceiling
+ * 1. Protects: with `pages.segmented_storage` on and `content_sanity.bytes_block` unset, the size rule of a segmented page is its page ceiling
* (`pages.max_bytes`), so a streamed page is chunked and keyword-searchable and its frontmatter gets no
* `embed_skip` / `content_flag: oversized`; the prose pass judges its head, middle and tail windows (a
* markup wall is flagged `markup_heavy` and stays searchable); an operator's lower bytes_block still
@@ -27,6 +27,7 @@ beforeAll(async () => {
engine = new PGLiteEngine();
await engine.connect({});
await engine.initSchema();
+ await engine.setConfig('pages.segmented_storage', 'on');
dir = mkdtempSync(join(tmpdir(), 'gbrain-streamed-sanity-'));
}, 120_000);
diff --git a/test/size-state-receipts-6722.test.ts b/test/size-state-receipts-6722.test.ts
index a4cd37d46a..59cbdfa450 100644
--- a/test/size-state-receipts-6722.test.ts
+++ b/test/size-state-receipts-6722.test.ts
@@ -73,11 +73,20 @@ describe('put_page receipts', () => {
expect(small.isError).toBe(false);
expect(small.body.size_state).toBeUndefined();
- const large = await call('put_page', { slug: 'notes/large', content: markdown('Large', prose(1_100_000)) });
- expect(large.isError).toBe(false);
- expect(large.body.chunks).toBeGreaterThan(100);
- expect(large.body.size_state).toEqual({ embedding: 'deferred', reason: 'large_page', bytes: expect.any(Number) });
- expect(large.body.size_state.bytes).toBeGreaterThan(1024 ** 2);
+ for (const setting of ['off', 'on']) {
+ await engine.setConfig('pages.segmented_storage', setting);
+ const large = await call('put_page', { slug: `notes/large-${setting}`, content: markdown('Large', prose(1_100_000)) });
+ expect(large.isError).toBe(false);
+ expect((await engine.executeRaw<{ body_storage: string }>('SELECT body_storage FROM pages WHERE slug=$1', [`notes/large-${setting}`]))[0]?.body_storage)
+ .toBe(setting === 'on' ? 'segmented' : 'inline');
+ // Wave B: a new segmented page publishes with its projection pending (chunked by the projection job), not empty.
+ expect(large.body.chunk_skip_reason).toBeUndefined();
+ if (setting === 'off') expect(large.body.chunks).toBeGreaterThan(100);
+ else expect(large.body.chunks > 100 || large.body.projection === 'pending').toBe(true);
+ expect((await engine.getChunks(`notes/large-${setting}`)).length).toBeGreaterThan(100);
+ expect(large.body.size_state).toEqual({ embedding: 'deferred', reason: 'large_page', bytes: expect.any(Number) });
+ expect(large.body.size_state.bytes).toBeGreaterThan(1024 ** 2);
+ }
}, 120_000);
test('a page over the operator bytes_block keeps its chunks, says skipped: oversized, and its embedding effect calls no provider', async () => {
@@ -128,13 +137,16 @@ describe('embed_skip pages are chunked and never embedded', () => {
describe('remember receipts', () => {
test('a fact appended to a large entity page carries the page size_state; one on an ordinary page carries none', async () => {
- expect((await call('put_page', { slug: 'people/alice-example', content: markdown('Alice Example', prose(1_100_000), 'person') })).isError).toBe(false);
- expect((await call('put_page', { slug: 'people/bob-example', content: markdown('Bob Example', 'A person.\n', 'person') })).isError).toBe(false);
-
- const large = await call('remember', { fact: 'Alice Example prefers async standups.', provenance: 'test', entity: 'people/alice-example' });
- expect(large.isError).toBe(false);
- expect(large.body.size_state).toEqual({ embedding: 'deferred', reason: 'large_page', bytes: expect.any(Number) });
+ for (const setting of ['off', 'on']) {
+ await engine.setConfig('pages.segmented_storage', setting);
+ const slug = `people/alice-example-${setting}`;
+ expect((await call('put_page', { slug, content: markdown('Alice Example', prose(1_100_000), 'person') })).isError).toBe(false);
+ const large = await call('remember', { fact: 'Alice Example prefers async standups.', provenance: 'test', entity: slug });
+ expect(large.isError).toBe(false);
+ expect(large.body.size_state).toEqual({ embedding: 'deferred', reason: 'large_page', bytes: expect.any(Number) });
+ }
+ expect((await call('put_page', { slug: 'people/bob-example', content: markdown('Bob Example', 'A person.\n', 'person') })).isError).toBe(false);
const small = await call('remember', { fact: 'Bob Example lives in Porto.', provenance: 'test', entity: 'people/bob-example' });
expect(small.isError).toBe(false);
expect(small.body.size_state).toBeUndefined();