Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Fix lane M: worktree recovery budget defaults to twice the page ceiling; regression test that restore re-projects segmented pages

garrytana5091f555e6f
diff --git a/docs/architecture/key-files/core-services-2-continued.md b/docs/architecture/key-files/core-services-2-continued.md
index aaae34de04..0f56f9ae3b 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; every `page_body_segmented` refusal's fix reads the page with `get_page body: 'auto'`), `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` (unset means `SEGMENTED_STORAGE_DEFAULT`, `off` in this release; `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 v251: `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. 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 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 v251: `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/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/docs/guides/concurrent-writes.md b/docs/guides/concurrent-writes.md
index 4d0447c3ac..012eb7a13b 100644
--- a/docs/guides/concurrent-writes.md
+++ b/docs/guides/concurrent-writes.md
@@ -865,7 +865,7 @@ Default admission limits are enforced atomically:
| Queued intent bytes | 32 MiB | 256 MiB |
| Lifetime request IDs | 2,000,000 | 8,000,000 |
| Terminal receipt reservation | 16 GiB | 64 GiB |
-| Recovery bytes | — | 1 GiB, also 256 MiB per worktree |
+| Recovery bytes | — | 1 GiB, also 256 MiB per worktree (with `pages.segmented_storage on`: twice `pages.max_bytes` plus 2 MiB, at least 256 MiB) |
Completion space is reserved at admission. Beforeimage/recovery bytes are
reserved before filesystem publication. Reaching a limit refuses additional
diff --git a/docs/guides/memory-boundaries.md b/docs/guides/memory-boundaries.md
index e0bf842187..9c4e49c3fd 100644
--- a/docs/guides/memory-boundaries.md
+++ b/docs/guides/memory-boundaries.md
@@ -180,6 +180,17 @@ pages wait. A quarantined page says
`searchable: false`. `gbrain import` waits for the build and reports
`searchable` in its result the same way.
+Deleting and restoring a segmented page on a source backed by files works up
+to the page ceiling. A restore reserves room for its file twice (the staging
+file and the file) in the worktree recovery budget, so with the switch on
+`persistence.limits.worktree_recovery_bytes` defaults to twice `pages.max_bytes`
+plus 2 MiB, never less than 256 MiB (514 MiB on Postgres and 258 MiB on PGLite
+at the default ceilings). A value you set is kept; a page that does not fit it
+is refused with `request_too_large` before anything is touched. A restored
+page is searchable when the restore commits, or, when its chunks were never
+built, right after it (`gbrain projections drain` builds it if that build
+dies).
+
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
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index f2c76e28d4..7021252ab6 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -715,11 +715,11 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }
{ since: 'TBD', text: '`gbrain import` of a Markdown file over 24 MiB from outside its source root now says in the error itself to move the file into the source root and import it there, naming the target path.' },
{ since: 'TBD', text: 'Upgrading builds the index `content_chunks_occurrence_generation_idx` (migration v253): 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.8 s for 1M chunk rows on Postgres and 0.35 s on a PGLite brain holding a 100 MB page. With it, rebuilding the search projection of a page stored in segments (after a crash, for embedding readiness, by the projection job or `gbrain projections drain`) reads in proportion to the chunk rows it retires and the page\'s segments instead of every chunk row times its newer rows: a 26 MB page half rewritten by a replace read 2.2M buffers to select its stale rows, now 1.8k.' },
{ since: 'TBD', text: 'Maintenance on pages stored in segments: `gbrain repair timeline` (and `repair --all`) no longer crashes on one; it repairs inline pages and reports segmented pages carrying timeline rows as `segmented_pages` / `segmented_rows` with their slugs, and doctor `timeline_history` counts them separately without recommending a repair for them. `repair timeline-comments`, `connector-fences`, `split-facts` and `conversation-labels` report the segmented pages they do not handle instead of skipping them silently, and a repair item refused with `page_body_segmented` is listed in `failed[]` while the run goes on. `gbrain integrity check` / `integrity auto` and `gbrain reconcile-links` read a segmented page block by block and give the results its text gives inline; `gbrain reindex --aliases` derives its aliases as its import did; `gbrain quarantine scan` lists it under `skipped` (not re-checked). A page one of these commands cannot read is listed under `skipped` and the run goes on.' },
- { since: 'TBD', text: '`delete_page` (soft and `purge: true`), `restore_page`, `gbrain delete` and `gbrain restore` now work on a page over 24 MiB on a source backed by files: the file is compared with the page by digest, streamed, and a file edited on disk still refuses as before. Restoring such a page clears its deletion without re-importing it and writes its file back from the database; the 25 MiB pre-push scan cap on written files still applies, and a core page or an external_untrusted writer still refuses.' },
+ { since: 'TBD', text: '`delete_page` (soft and `purge: true`), `restore_page`, `gbrain delete` and `gbrain restore` now work on a page over 24 MiB on a source backed by files: the file is compared with the page by digest, streamed, and a file edited on disk still refuses as before. Restoring such a page clears its deletion without re-importing it and writes its file back from the database. Its chunks and keyword index come back with it: a page whose chunks were complete is searchable when the restore commits, and one whose chunks were never built (or whose old chunks still wait to be removed) is queued, built right after the commit, and built by `gbrain projections drain` if that build dies. The restore adds no text, so it does not rescan the body with the write gate, stamp a new trust tier or fold the timeline again; the 25 MiB pre-push scan cap on written files still applies, and a core page or an external_untrusted writer still refuses.' },
{ since: 'TBD', text: 'A write that stores a page in segments says in its receipt whether search sees it: `searchable: true` when it commits (every new page up to 4 MiB and every rewrite), or `searchable: "pending"` for a larger new page while its chunks are built after commit, with `searchable_retry_after_ms` and a `searchable_fix` that reads the receipt again (`get_write_request`) until it says `searchable: true`. A new page up to 4 MiB was previously searchable only once a post-commit build finished.' },
{ since: 'TBD', text: '`gbrain projections drain` now builds pages stored in segments whose post-commit build never ran or died, skipping one another process is still building (claim renewed within 60 s), so a brain with no resident writer can make a large new page searchable. A pending receipt\'s `searchable_fix` names it as the fallback after the re-read wait, and doctor `text_projection_readiness` counts such pages (`segmented_pending`) and points to it.' },
{ since: 'TBD', text: 'The maintenance sweep (`gbrain sweep`, the serve idle sweep) links a page stored in segments on its own after the inline pages, smallest first, and stops reading one at its time budget; a page that does not fit, though it started with at least half of the sweep\'s budget, is skipped with reason `budget_deferred:segmented_page`, left for `gbrain extract --stale`, and later sweeps in the same process leave it out (`segmented_page_deferred`) until it changes, so the pages behind it are still reached; one that started with less is left for the next sweep (`budget_exhausted:links_timeline`). Derived passes over a page stored in segments, timeline retraction over its earlier versions (the timeline orphan prune, `gbrain extract timeline --source db` and doctor `timeline_orphans`) included, no longer refuse a page of short lines or dated bullets over 8 MiB with `page_body_segmented`.' },
- { since: 'TBD', text: 'Deleting and restoring a page over 24 MiB on a source backed by files is now lossless up to the page ceiling (`pages.max_bytes`). `restore_page` and `gbrain restore` write the file back byte for byte by streaming it from the stored segments into its staging file, including a file over the 25 MiB pre-push scan cap (the restore used to refuse with `request_too_large`, so the file a soft delete had removed could not be put back on disk). A delete or restore that replaces or removes a file over 24 MiB keeps the prior file as a staged copy beside it (a hidden `.<sha256>.tmp.before-<uuid>` file) until the write commits, named in its recovery record by path and SHA-256 instead of embedded in it: the record stays a few hundred bytes, the recovery reservation counts the file once (a 90 MiB delete used to need 283 MB against the 256 MiB `persistence.limits.worktree_recovery_bytes` budget and was refused), and a crash between removing the file and committing renames the copy back. A page whose file plus its staging does not fit that budget (a Postgres page near the 256 MiB ceiling) is still refused with `request_too_large` before anything is touched. The copy is written under a temporary name and renamed once it is complete and flushed, so a crash while it is being copied leaves nothing the recovery waits on: recovery removes a copy that never got its name, and drops a copy that is incomplete while the file still holds its prior bytes. `gbrain repair stuck-recovery` lists such a recovery as refused with `recovery_large_file_unsupported` (resolve it by hand; the resident writer finishes it) and still previews the other recoveries of the source.' },
+ { since: 'TBD', text: 'Deleting and restoring a page over 24 MiB on a source backed by files is now lossless up to the page ceiling (`pages.max_bytes`). `restore_page` and `gbrain restore` write the file back byte for byte by streaming it from the stored segments into its staging file, including a file over the 25 MiB pre-push scan cap (the restore used to refuse with `request_too_large`, so the file a soft delete had removed could not be put back on disk). A delete or restore that replaces or removes a file over 24 MiB keeps the prior file as a staged copy beside it (a hidden `.<sha256>.tmp.before-<uuid>` file) until the write commits, named in its recovery record by path and SHA-256 instead of embedded in it: the record stays a few hundred bytes, the recovery reservation counts the file once (a 90 MiB delete used to need 283 MB against the 256 MiB `persistence.limits.worktree_recovery_bytes` budget and was refused), and a crash between removing the file and committing renames the copy back. With `pages.segmented_storage on`, that budget now defaults to twice `pages.max_bytes` (the engine ceiling when unset: 256 MiB on Postgres, 128 MiB on PGLite) plus 1 MiB per copy, never less than 256 MiB, so a page up to the ceiling deletes and restores: a restore reserves its file twice, and a 200 MiB Postgres page or a page at the PGLite ceiling used to be refused. A value set with `gbrain config set persistence.limits.worktree_recovery_bytes` is kept, and a page that does not fit it is refused with `request_too_large` before anything is touched. The copy is written under a temporary name and renamed once it is complete and flushed, so a crash while it is being copied leaves nothing the recovery waits on: recovery removes a copy that never got its name, and drops a copy that is incomplete while the file still holds its prior bytes. `gbrain repair stuck-recovery` lists such a recovery as refused with `recovery_large_file_unsupported` (resolve it by hand; the resident writer finishes it) and still previews the other recoveries of the source.' },
{ since: 'TBD', text: 'A page purge (`delete_page` with `purge: true`, `gbrain delete --purge` and the 72-hour hard delete of soft-deleted pages) of a page stored in segments no longer breaks another page\'s write that is still being prepared with some of the same text: the purge keeps exactly the segment texts such a write staged, and still deletes every other text only the purged page used. `restore_page` of a page over 24 MiB whose old chunks were still waiting to be removed returns `projection: "pending"` and makes the page searchable once they are gone, instead of showing the old text in search.' },
{ since: 'TBD', text: 'Chunks of a page stored in segments keep a Markdown heading with the text after it, so a section appended after a full last chunk re-embeds only its own chunk (was two). Inline pages chunk as before.' },
{ since: 'TBD', text: 'The pre-push secret scan (`gbrain sources push` and the automatic pushes) now scans a staged file over 25 MiB in bounded 8 Mi-character windows streamed from git, instead of refusing the push as `blocked_unscannable`: a clean large file pushes, and one holding a secret is refused as `blocked_secrets` naming its file and line. A staged file over 512 MiB still refuses as `blocked_unscannable`.' },
diff --git a/src/core/page-body/limits.ts b/src/core/page-body/limits.ts
index b48f75ac6d..aaed16868d 100644
--- a/src/core/page-body/limits.ts
+++ b/src/core/page-body/limits.ts
@@ -168,6 +168,27 @@ export function segmentedPageCeiling(kind: BrainEngine['kind']): number {
return kind === 'pglite' ? SEGMENTED_PAGE_CEILING_BYTES.pglite : SEGMENTED_PAGE_CEILING_BYTES.postgres;
}
+/** The largest body admitted while the switch is on: a configured `pages.max_bytes`, never above the engine ceiling. */
+export function segmentedMaxBytes(kind: BrainEngine['kind'], maxRaw: string | null): number {
+ const ceiling = segmentedPageCeiling(kind);
+ return Math.min(positiveInt(maxRaw, ceiling), ceiling);
+}
+
+/** Bytes a page's file adds over its body, per staged copy, in the recovery default: frontmatter, separators, the record. */
+export 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.
+ */
+export function pageRecoveryBytes(kind: BrainEngine['kind'], switchRaw: string | null, maxRaw: string | null, floor: number): number {
+ const maxBytes = segmentedStorageRequested(parseSegmentedStorage(switchRaw)) ? segmentedMaxBytes(kind, maxRaw) : PAGE_MAX_BYTES;
+ return Math.max(floor, 2 * (maxBytes + 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
@@ -181,10 +202,9 @@ export async function readPageBodyPolicy(engine: PolicyEngine): Promise<PageBody
]);
const setting = parseSegmentedStorage(switchRaw);
const segmented = segmentedStorageRequested(setting) && (await segmentedWriterBlockers(engine).catch(() => null))?.length === 0;
- const ceiling = segmentedPageCeiling(engine.kind);
return {
segmented,
- maxBytes: segmented ? Math.min(positiveInt(maxRaw, ceiling), ceiling) : PAGE_MAX_BYTES,
+ maxBytes: segmented ? segmentedMaxBytes(engine.kind, maxRaw) : 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/persistence/limits.ts b/src/core/persistence/limits.ts
index 2c2b08c487..e31db1bbe5 100644
--- a/src/core/persistence/limits.ts
+++ b/src/core/persistence/limits.ts
@@ -1,4 +1,5 @@
import { opError } from '../ops/contract.ts';
+import { PAGE_BODY_CONFIG_KEYS, pageRecoveryBytes } from '../page-body/limits.ts';
import { DEFAULT_JOURNAL_LIMITS, type JournalLimits, type SqlEngine } from './model.ts';
import { COMPACTED_HEADROOM_BYTES, RECEIPT_RESERVATION_FLOOR } from './receipt-bytes.ts';
@@ -22,11 +23,16 @@ export function parseJournalConfigValue(key:string,value:string):number {
}
return Number(value);
}
-/** Database configuration applies to every server sharing this brain. */
-export async function readJournalLimits(engine:SqlEngine,overrides?:Partial<JournalLimits>):Promise<JournalLimits> {
- const rows=await engine.executeRaw<{key:string;value:string}>("SELECT key,value FROM config WHERE key LIKE 'persistence.limits.%'");
+/**
+ * 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
+ * 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 limits={...DEFAULT_JOURNAL_LIMITS};
+ 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)};
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/test/large-pages/recovery-budget-ceiling.slow.test.ts b/test/large-pages/recovery-budget-ceiling.slow.test.ts
new file mode 100644
index 0000000000..82343431ed
--- /dev/null
+++ b/test/large-pages/recovery-budget-ceiling.slow.test.ts
@@ -0,0 +1,146 @@
+/**
+ * Delete and restore of a file-backed segmented page the old 256 MiB worktree recovery budget refused (Wave B PR 2,
+ * fix lane M, item 4).
+ *
+ * 1. Protects: with the recovery budget at its default, a 200 MiB page on Postgres and a page at the 128 MiB PGLite
+ * ceiling delete and restore on a source backed by files, the restored file byte-identical (size and SHA-256). A
+ * 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.
+ * 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.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { execFileSync } from 'node:child_process';
+import { appendFileSync, existsSync, mkdirSync, mkdtempSync, readdirSync, rmSync, statSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';
+import type { BrainEngine } from '../../src/core/engine.ts';
+import type { OperationContext } from '../../src/core/operations.ts';
+import { SEGMENTED_PAGE_CEILING_BYTES } from '../../src/core/page-body/limits.ts';
+import { claimWorktree } from '../../src/core/persistence/ownership.ts';
+import { registerLocalWriter } from '../../src/core/persistence/identity.ts';
+import { importManagedFile } from '../../src/core/persistence/import-mutations.ts';
+import { submitPageMutation } from '../../src/core/persistence/page-mutations.ts';
+import { disposePersistenceConsumer } from '../../src/core/persistence/service.ts';
+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';
+import { testBackends } from '../helpers/test-backends.ts';
+import { withEnv } from '../helpers/with-env.ts';
+import { fileSha, writeCanonicalPage } from '../helpers/large-page-file.ts';
+
+const home = mkdtempSync(join(tmpdir(), 'gbrain-recovery-ceiling-'));
+const env = { GBRAIN_HOME: home, OPENAI_API_KEY: undefined, VOYAGE_API_KEY: undefined, ANTHROPIC_API_KEY: undefined };
+const logger = { info() {}, warn() {}, error() {} };
+const MiB = 1024 * 1024;
+const OLD_DEFAULT = 256 * MiB;
+
+afterAll(() => { rmSync(home, { recursive: true, force: true }); });
+
+interface Fixture { sourceId: string; root: string; ctx: OperationContext }
+
+async function managedSource(engine: BrainEngine): Promise<Fixture> {
+ await disposePersistenceConsumer(engine);
+ await engine.setConfig('pages.segmented_storage', 'on');
+ const root = join(home, `src-${randomUUID().slice(0, 8)}`);
+ mkdirSync(join(root, 'notes'), { recursive: true });
+ execFileSync('git', ['init', '-q'], { cwd: root });
+ const sourceId = `rb-${randomUUID().slice(0, 8)}`;
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ await engine.executeRaw("INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,'{}')", [sourceId, root]);
+ await registerLocalWriter(engine, 'cli');
+ await claimWorktree(engine, sourceId, root);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ const ctx = { engine, sourceId, remote: false, config: { engine: engine.kind, embedding_disabled: true } as never, dryRun: false, logger } as OperationContext;
+ return { sourceId, root, ctx };
+}
+
+const revisionOf = async (engine: BrainEngine, f: Fixture, slug: string) => (await engine.readPageSnapshot(slug, { sourceId: f.sourceId, includeDeleted: true }))!.revision;
+
+/** A write this large can outlast the reply wait: the same call (same request_id) is repeated until it settles. */
+async function settled<T>(call: () => Promise<T>): Promise<T> {
+ for (let attempt = 0; ; attempt++) {
+ try { return await call(); }
+ catch (error) { if ((error as { code?: string }).code !== 'write_pending' || attempt >= 3600) throw error; await Bun.sleep(1000); }
+ }
+}
+
+async function submit(engine: BrainEngine, f: Fixture, operation: 'delete_page' | 'restore_page', slug: string, extra: Record<string, unknown> = {}) {
+ const params = { slug, expected_revision: await revisionOf(engine, f, slug), request_id: randomUUID(), ...extra };
+ return settled(() => submitPageMutation(f.ctx, { operation, params }) as Promise<Record<string, any>>);
+}
+
+const deletedAt = async (engine: BrainEngine, f: Fixture, slug: string) => (await engine.executeRaw<{ deleted: boolean }>(
+ 'SELECT deleted_at IS NOT NULL AS deleted FROM pages WHERE source_id=$1 AND slug=$2', [f.sourceId, slug]))[0]?.deleted;
+const stagingLeft = (f: Fixture) => readdirSync(join(f.root, 'notes')).filter(name => name.includes('.tmp.'));
+const reserved = async (engine: BrainEngine) => (await engine.executeRaw<{ bytes: string }>('SELECT recovery_bytes::text AS bytes FROM persistence_counters'))
+ .reduce((sum, row) => sum + Number(row.bytes), 0);
+
+/**
+ * A canonical page file of exactly `fileBytes` bytes: the helper's conversation, then one filler paragraph that
+ * brings it to the size (a body at the PGLite ceiling whose file, read twice, is over 256 MiB).
+ */
+function pageOfSize(file: string, fileBytes: number, seed: number): { sha: string; size: number } {
+ const written = writeCanonicalPage(file, fileBytes - 256 * 1024, seed).size;
+ const fill = fileBytes - written - 2;
+ appendFileSync(file, `\n${'filler '.repeat(Math.ceil(fill / 7)).slice(0, fill - 1)}z\n`);
+ return { sha: fileSha(file), size: statSync(file).size };
+}
+
+async function roundTrip(engine: BrainEngine): Promise<void> {
+ const f = await managedSource(engine);
+ const slug = `notes/ceiling-${engine.kind}`;
+ const file = join(f.root, `${slug}.md`);
+ const fileBytes = engine.kind === 'postgres' ? 200 * MiB : SEGMENTED_PAGE_CEILING_BYTES.pglite;
+ try {
+ const original = pageOfSize(file, fileBytes, 301);
+ expect(original.size).toBe(fileBytes);
+ // A restore reserves the file twice plus 4 KiB (coordinator.ts pageRecoveryRecord).
+ expect(2 * original.size + 4096).toBeGreaterThan(OLD_DEFAULT);
+ expect(await settled(() => importManagedFile(engine, file, `${slug}.md`, { sourceId: f.sourceId, noEmbed: true }))).toMatchObject({ status: 'imported' });
+ expect(await submit(engine, f, 'delete_page', slug)).toMatchObject({ status: 'soft_deleted', noop: false });
+ expect(existsSync(file)).toBe(false);
+
+ // The old default, configured: the restore is refused before anything is touched.
+ await engine.setConfig('persistence.limits.worktree_recovery_bytes', String(OLD_DEFAULT));
+ const refused = await submit(engine, f, 'restore_page', slug).catch((error: Error & { code?: string }) => ({ refused: error.code }));
+ expect(refused).toEqual({ refused: 'request_too_large' });
+ expect(await deletedAt(engine, f, slug)).toBe(true);
+ expect(existsSync(file)).toBe(false);
+ expect(stagingLeft(f)).toEqual([]);
+ expect(await reserved(engine)).toBe(0);
+
+ // The default: the restore fits and writes the file back byte for byte.
+ await engine.executeRaw("DELETE FROM config WHERE key='persistence.limits.worktree_recovery_bytes'");
+ const restored = await submit(engine, f, 'restore_page', slug).catch((error: Error & { code?: string }) => ({ refused: error.code }));
+ expect(restored).toMatchObject({ status: 'restored', noop: false });
+ expect(await deletedAt(engine, f, slug)).toBe(false);
+ expect(statSync(file).size).toBe(original.size);
+ expect(fileSha(file)).toBe(original.sha);
+ expect(stagingLeft(f)).toEqual([]);
+
+ expect(await submit(engine, f, 'delete_page', slug, { purge: true })).toMatchObject({ status: 'purged' });
+ expect(existsSync(file)).toBe(false);
+ expect(await reserved(engine)).toBe(0);
+ } finally {
+ await engine.executeRaw("DELETE FROM config WHERE key='persistence.limits.worktree_recovery_bytes'");
+ await disposePersistenceConsumer(engine);
+ rmSync(f.root, { recursive: true, force: true });
+ }
+}
+
+for (const kind of testBackends()) describe(`recovery budget at the page ceiling (${kind})`, () => {
+ let engine: BrainEngine;
+ let close: () => Promise<void>;
+ beforeAll(async () => {
+ if (kind === 'postgres') ({ engine, close } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));
+ else { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); close = () => engine.disconnect(); }
+ }, 120_000);
+ afterAll(async () => withEnv(env, async () => { await disposePersistenceConsumer(engine); await close?.(); }));
+
+ test('a page the old 256 MiB recovery budget could not restore deletes and restores byte for byte', async () => withEnv(env, () => roundTrip(engine)), 3_600_000);
+});
diff --git a/test/large-pages/recovery-budget-default.test.ts b/test/large-pages/recovery-budget-default.test.ts
new file mode 100644
index 0000000000..4a9ca19bd0
--- /dev/null
+++ b/test/large-pages/recovery-budget-default.test.ts
@@ -0,0 +1,78 @@
+/**
+ * The default worktree recovery budget leaves room for a page at the ceiling (Wave B PR 2, fix lane M, item 4).
+ *
+ * 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.
+ * 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.
+ * 3. Existing coverage: segmented-delete-restore-file.slow.test.ts deletes and restores 27 and 90 MiB pages within the
+ * old budget; recovery-budget-ceiling.slow.test.ts deletes and restores a page the old budget refused.
+ * 4. Runs on PGLite, and on Postgres when DATABASE_URL is set.
+ */
+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+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 } from '../../src/core/page-body/limits.ts';
+import { readJournalLimits } from '../../src/core/persistence/limits.ts';
+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';
+import { testBackends } from '../helpers/test-backends.ts';
+
+const MiB = 1024 * 1024;
+const OLD_DEFAULT = 256 * MiB;
+
+for (const kind of testBackends()) describe(`worktree recovery default follows the page ceiling (${kind})`, () => {
+ let engine: BrainEngine;
+ let close: () => Promise<void>;
+ const ceiling = SEGMENTED_PAGE_CEILING_BYTES[kind];
+ beforeAll(async () => {
+ if (kind === 'postgres') ({ engine, close } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));
+ else { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); close = () => engine.disconnect(); }
+ }, 120_000);
+ afterAll(async () => { await close?.(); });
+ beforeEach(async () => {
+ await engine.executeRaw("DELETE FROM config WHERE key LIKE 'persistence.limits.%' OR key IN ('pages.segmented_storage','pages.max_bytes')");
+ });
+ const worktree = async () => (await readJournalLimits(engine)).worktreeRecoveryBytes;
+
+ test('switch off or unset: 256 MiB', async () => {
+ expect(await worktree()).toBe(OLD_DEFAULT);
+ await engine.setConfig('pages.segmented_storage', 'off');
+ await engine.setConfig('pages.max_bytes', String(ceiling));
+ expect(await worktree()).toBe(OLD_DEFAULT);
+ });
+
+ test('switch on: twice the ceiling plus headroom, so a restore of a page at the ceiling fits', async () => {
+ await engine.setConfig('pages.segmented_storage', 'on');
+ const expected = 2 * (ceiling + RECOVERY_FILE_HEADROOM_BYTES);
+ expect(await worktree()).toBe(expected);
+ expect(expected).toBeGreaterThan(OLD_DEFAULT);
+ // A restore reserves its file twice plus the record's 4 KiB (coordinator.ts pageRecoveryRecord); a file at the ceiling
+ // with a 64 KiB frontmatter fits, which the old default refused on both engines.
+ const restoreOfCeilingPage = 2 * (ceiling + 64 * 1024) + 4096;
+ expect(restoreOfCeilingPage).toBeLessThanOrEqual(expected);
+ expect(restoreOfCeilingPage).toBeGreaterThan(OLD_DEFAULT);
+ // The brain-wide budget already holds the largest default, so it is left as it is.
+ expect((await readJournalLimits(engine)).brainRecoveryBytes).toBeGreaterThanOrEqual(expected);
+ });
+
+ test('pages.max_bytes: a lowered value never drops below 256 MiB, a value above the ceiling clamps to it', async () => {
+ await engine.setConfig('pages.segmented_storage', 'on');
+ await engine.setConfig('pages.max_bytes', String(64 * MiB));
+ expect(await worktree()).toBe(OLD_DEFAULT);
+ await engine.setConfig('pages.max_bytes', String(200 * MiB));
+ expect(await worktree()).toBe(Math.max(OLD_DEFAULT, 2 * (Math.min(200 * MiB, ceiling) + RECOVERY_FILE_HEADROOM_BYTES)));
+ await engine.setConfig('pages.max_bytes', String(4 * ceiling));
+ expect(await worktree()).toBe(2 * (ceiling + RECOVERY_FILE_HEADROOM_BYTES));
+ });
+
+ 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));
+ expect(await worktree()).toBe(OLD_DEFAULT);
+ await engine.setConfig('persistence.limits.worktree_recovery_bytes', '1048576');
+ expect(await worktree()).toBe(1048576);
+ });
+});
diff --git a/test/large-pages/restore-segmented-reprojects.test.ts b/test/large-pages/restore-segmented-reprojects.test.ts
new file mode 100644
index 0000000000..d8634d58bf
--- /dev/null
+++ b/test/large-pages/restore-segmented-reprojects.test.ts
@@ -0,0 +1,156 @@
+/**
+ * restore_page of a page stored in segments ends chunked, sealed and searchable (Wave B PR 2, fix lane M, item 11).
+ *
+ * 1. Protects: after a soft delete and restore_page, a segmented page (one within the single-string ceiling, which the
+ * restore re-imports, and one over it, which the restore clears without re-importing) is sealed at its new revision,
+ * has a chunk row for every live occurrence and none of a retired one, has no queued projection, and keyword search
+ * finds text from its last segment. A page whose chunks were never built (its create's post-commit projection died
+ * and it was deleted before the resident built it) and whose restore's post-commit projection dies too is queued by
+ * the restore, and `gbrain projections drain` builds it exactly once, leaving no stale row.
+ * 2. Fails when: a restore seals a page an occurrence of which has no chunks, or leaves an unsealed page with no queued
+ * projection (the soft delete removed its queue row and nothing queues it again).
+ * 3. Existing coverage: restore-deferred-retire.test.ts restores a page whose deferred retirement left rows of retired
+ * occurrences, with its post-commit projection running.
+ * 4. Runs on PGLite, and on Postgres when DATABASE_URL is set. The lost projections are forced with the
+ * `segmented:projection_staged` fault seam (each build stages its chunks, then throws before sealing); the create's
+ * rows are then removed, as a process killed before its chunk batches committed leaves the page.
+ */
+import { afterAll, afterEach, beforeAll, describe, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type { BrainEngine } from '../../src/core/engine.ts';
+import type { OperationContext } from '../../src/core/ops/contract.ts';
+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';
+import { importFromFile } from '../../src/core/import-file.ts';
+import { operations } from '../../src/core/operations.ts';
+import { occurrencesWithoutChunks } from '../../src/core/page-body/ingest.ts';
+import { readPageBodyPolicy } from '../../src/core/page-body/limits.ts';
+import { hasStaleChunks } from '../../src/core/page-body/projection.ts';
+import { drainProjections } from '../../src/core/page-state/projections.ts';
+import { PAGE_MAX_BYTES } from '../../src/core/page-size-policy.ts';
+import { withCoordinatedWrite } from '../../src/core/persistence/context.ts';
+import { installFaultHook } from '../../src/core/persistence/fault-points.ts';
+import { registerLocalWriter } from '../../src/core/persistence/identity.ts';
+import { disposePersistenceConsumer } from '../../src/core/persistence/service.ts';
+import { conversationBody } from '../helpers/conversation-page.ts';
+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';
+import { segmentedPageRow } from '../helpers/segmented-page-checks.ts';
+import { testBackends } from '../helpers/test-backends.ts';
+import { withEnv } from '../helpers/with-env.ts';
+import { TEST_WRITE_ATTRIBUTION } from '../helpers/write-attribution.ts';
+
+const home = mkdtempSync(join(tmpdir(), 'gbrain-restore-reprojects-'));
+const env = { GBRAIN_HOME: home, OPENAI_API_KEY: undefined, VOYAGE_API_KEY: undefined, ANTHROPIC_API_KEY: undefined };
+const MiB = 1024 * 1024;
+const ctx = (engine: BrainEngine): OperationContext => ({ engine, sourceId: 'default', remote: false, dryRun: false,
+ config: { engine: engine.kind, embedding_disabled: true, storage: { backend: 'local', bucket: 'b', localPath: join(home, 'storage') } },
+ logger: { info() {}, warn() {}, error() {} } } as OperationContext);
+const restoreOp = operations.find(o => o.name === 'restore_page')!;
+const page = (bytes: number, needle: string, seed: number) =>
+ `---\ntitle: Group chat\ntype: note\n---\n\n${conversationBody(bytes, { seed, needles: [{ at: 0.995, word: needle }] })}\n`;
+
+afterAll(() => { rmSync(home, { recursive: true, force: true }); });
+afterEach(() => installFaultHook(undefined));
+
+for (const kind of testBackends()) describe(`restore_page re-projects a segmented page (${kind})`, () => {
+ let engine: BrainEngine;
+ let close: () => Promise<void>;
+ beforeAll(async () => withEnv(env, async () => {
+ if (kind === 'postgres') ({ engine, close } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));
+ else { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); close = () => engine.disconnect(); }
+ await registerLocalWriter(engine, 'cli');
+ await engine.setConfig('pages.segmented_storage', 'on');
+ }), 120_000);
+ afterAll(async () => withEnv(env, async () => { await disposePersistenceConsumer(engine); await close?.(); }));
+
+ const found = async (needle: string, slug: string) => (await engine.searchKeyword(needle, { limit: 10 })).some(hit => hit.slug === slug);
+ const queued = async (slug: string) => (await engine.executeRaw<{ reason: string }>(`SELECT reason FROM page_projection_jobs
+ WHERE slug=$1 AND source_incarnation=(SELECT incarnation FROM sources WHERE id='default')`, [slug])).map(row => row.reason);
+ const softDelete = (slug: string) => engine.transaction(tx => withCoordinatedWrite(tx, ['default'], () => tx.softDeletePage(slug, { sourceId: 'default' }), TEST_WRITE_ATTRIBUTION));
+ /** A restore over the single-string ceiling can outlast the reply wait: the same call (same request_id) is repeated until it settles. */
+ async function restore(slug: string): Promise<Record<string, unknown>> {
+ const params = { slug, request_id: randomUUID(), expected_revision: (await engine.readPageSnapshot(slug, { sourceId: 'default', includeDeleted: true }))!.revision };
+ for (let attempt = 0; ; attempt++) {
+ try { return await restoreOp.handler(ctx(engine), params) as Record<string, unknown>; }
+ catch (error) { if ((error as { code?: string }).code !== 'write_pending' || attempt >= 300) throw error; await Bun.sleep(1000); }
+ }
+ }
+
+ /** Sealed at the live revision, every live occurrence chunked, no row of another occurrence, nothing queued. */
+ async function expectProjected(slug: string, needle: string): Promise<void> {
+ const row = await segmentedPageRow(engine, slug);
+ expect(row.body_storage).toBe('segmented');
+ expect(row.text_projection_revision).toBe(row.knowledge_revision);
+ const live = await engine.readManifest(row.id);
+ expect(live.length).toBeGreaterThan(1);
+ expect(await occurrencesWithoutChunks(engine, row.id, row.body_generation, live)).toEqual([]);
+ expect(await hasStaleChunks(engine, row.id, row.body_generation, live.map(occurrence => Number(occurrence.occurrenceId)))).toBe(false);
+ expect(await queued(slug)).toEqual([]);
+ expect(await found(needle, slug)).toBe(true);
+ }
+
+ /** Imported from a file, as sync imports it (a page over the single-string ceiling is streamed). */
+ async function imported(slug: string, bytes: number, needle: string, seed: number) {
+ const dir = join(home, randomUUID().slice(0, 8));
+ mkdirSync(dir, { recursive: true });
+ writeFileSync(join(dir, 'page.md'), page(bytes, needle, seed));
+ return importFromFile(engine, join(dir, 'page.md'), `${slug}.md`, { noEmbed: true, bodyPolicy: await readPageBodyPolicy(engine) });
+ }
+
+ /** A create whose post-commit projection died before any chunk row committed, then soft-deleted (its queue row goes). */
+ async function unbuiltDeletedPage(slug: string, bytes: number, needle: string, seed: number): Promise<void> {
+ installFaultHook(point => { if (point === 'segmented:projection_staged') throw new Error('post-commit build died (probe)'); });
+ expect(await imported(slug, bytes, needle, seed)).toMatchObject({ status: 'imported', searchable: 'pending' });
+ installFaultHook(undefined);
+ await engine.executeRaw("DELETE FROM content_chunks WHERE page_id=(SELECT id FROM pages WHERE source_id='default' AND slug=$1)", [slug]);
+ await softDelete(slug);
+ expect(await queued(slug)).toEqual([]);
+ }
+
+ for (const [label, bytes] of [['within the single-string ceiling', 6 * MiB], ['over the single-string ceiling', PAGE_MAX_BYTES + MiB]] as const) {
+ test(`a sealed page ${label} is sealed, chunked and searchable after its restore`, async () => withEnv(env, async () => {
+ const slug = `notes/sealed-${bytes}-${randomUUID().slice(0, 8)}`;
+ const needle = `zzrestoredsealed${kind}${bytes}`;
+ expect(await imported(slug, bytes, needle, 31)).toMatchObject({ status: 'imported' });
+ await drainProjections(engine);
+ await expectProjected(slug, needle);
+ await softDelete(slug);
+ expect(await found(needle, slug)).toBe(false);
+ expect((await restore(slug)).status).toBe('restored');
+ await expectProjected(slug, needle);
+ }), 600_000);
+
+ test(`a page ${label} whose chunks were never built is projected by its restore, or queued by it and built by one drain`, async () => withEnv(env, async () => {
+ const slug = `notes/unbuilt-${bytes}-${randomUUID().slice(0, 8)}`;
+ const needle = `zzrestoredunbuilt${kind}${bytes}`;
+ await unbuiltDeletedPage(slug, bytes, needle, 47);
+ let lost = 0;
+ installFaultHook(point => { if (point === 'segmented:projection_staged') { lost++; throw new Error('post-commit build died (probe)'); } });
+ const restored = await restore(slug);
+ expect(restored.status).toBe('restored');
+ // The restore's post-commit build (if it runs one) dies before its seal; wait for it to have died.
+ for (let polls = 0; restored.projection === 'pending' && lost === 0 && polls < 600; polls++) await Bun.sleep(100);
+ // The resident's queue route may have tried it under the probe too (`rebuild_failed`); stop it so the drain is the only build.
+ await disposePersistenceConsumer(engine);
+ installFaultHook(undefined);
+ if (bytes <= PAGE_MAX_BYTES) {
+ // The restore re-imports the body: its preparation chunks every occurrence and its publication seals.
+ await expectProjected(slug, needle);
+ return;
+ }
+ expect(restored.projection).toBe('pending');
+ expect(await found(needle, slug)).toBe(false);
+ const row = await segmentedPageRow(engine, slug);
+ expect(row.text_projection_revision).not.toBe(row.knowledge_revision);
+ expect((await queued(slug)).length).toBe(1);
+ let builds = 0;
+ installFaultHook(point => { if (point === 'segmented:projection_staged') builds++; });
+ const drained = await drainProjections(engine);
+ expect(drained.failed).toEqual([]);
+ expect(builds).toBe(1);
+ await expectProjected(slug, needle);
+ }), 600_000);
+ }
+});
diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txt
index 4fbc0e19c1..767f9f51c9 100644
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@ -87,10 +87,13 @@ test/large-pages/purge-inflight-create.test.ts
test/large-pages/purge-segment-residue.test.ts
test/large-pages/purge-segmented-versions-batch.test.ts
test/large-pages/purge-segments.test.ts
+test/large-pages/recovery-budget-ceiling.slow.test.ts
+test/large-pages/recovery-budget-default.test.ts
test/large-pages/remote-get-page-privacy.test.ts
test/large-pages/remote-versions-storage-change.test.ts
test/large-pages/remote-window-privacy.test.ts
test/large-pages/restore-deferred-retire.test.ts
+test/large-pages/restore-segmented-reprojects.test.ts
test/large-pages/sealed-segmented-search.test.ts
test/large-pages/second-write-deferred-retire.test.ts
test/large-pages/segment-rewrite-cr-tier.test.ts