Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(large-pages): stream a stage under an in-progress name; read a segmented page's file in pieces at any size

garrytancd2b7c37fde3
diff --git a/docs/architecture/key-files/core-persistence-request-indexes.md b/docs/architecture/key-files/core-persistence-request-indexes.md
index a692bf12c6..64aa9f4496 100644
--- a/docs/architecture/key-files/core-persistence-request-indexes.md
+++ b/docs/architecture/key-files/core-persistence-request-indexes.md
@@ -5,6 +5,6 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
The online-built request-table indexes (the managed sync checkpoint pair, the page purge's slug index, dream postprocessing's request-id index), the checkpoint validation they serve, the named fault seams the persistence gate and the purge tests inject at, and the stuck-recovery resolution (`gbrain repair stuck-recovery`) that uses them.
- `src/core/persistence/checkpoint-validation.ts` — the managed sync checkpoint's incomplete-receipt validation (#5762): `INCOMPLETE_SYNC_RECEIPT_SQL` is three `LIMIT 1` probes (recovery; an open page receipt of the run; a non-committed page receipt with no committed sibling at its index) served by `persistence_requests_recovery`, `persistence_requests_sync_run_open` and `persistence_requests_sync_run_committed`, with the same result as the former single predicate. `findIncompleteSyncReceipt` returns the blocking receipt's request id and maps only this statement's 57014 statement timeout to the terminal, non-transient `checkpoint_validation_timeout`. `readRequestIndexStates` reads each index of `PERSISTENCE_REQUEST_ONLINE_INDEXES` (or the list passed) as valid, missing, INVALID or building (Postgres `pg_stat_progress_create_index`); `formatCheckpointTimeoutHint` / `checkpointTimeoutHint` is the one formatter for the three-state hint and the filled retry (`gbrain sync --source <id> --no-pull --retry-failed` plus the cursor-selecting options the checkpoint intent records in `syncOptions` and the saved processing flags), used by the sync summary and `get_write_request`. Tests: `test/persistence-sync-checkpoint-validation.test.ts`, `test/e2e/persistence-request-indexes-postgres.test.ts`.
-- `src/core/persistence/fault-points.ts` — named crash seams for the persistence gate. `faultPoint(point, detail)` is a no-op unless a gate worker installed a hook with `installFaultHook`; production never does. Seams: `publication:<boundary>` (the five `PublicationHooks.boundary` names, routed through `withFaultPoints` in `publishMutation`), `effect:<kind>:mid` for every `EffectKind` in `completeEffect` (after the side effect, before its completion is recorded; `EFFECT_FAULT_POINTS` is a `Record<EffectKind, FaultPoint>`), `effect_recovery:before_clear` (`effect-recovery.ts`), `effect_recovery:before_stage` / `effect_recovery:staged` (a streamed, version 2 withdrawal mirror: once its record is durable, before its file is streamed into the publication stage, and after that step, before the recovery transaction renames the stage), `publication_recovery:before_clear` (`recoverPublication`), `sync:mid_checkpoint` (after each committed cursor step in `sync-run.ts` `saveCursor`), `sync:after_freeze` (#6712 PR 0: at the end of `freezeEntry` for an import entry, after its bytes are read and before the request is admitted; detail carries `slug` and `path`), `consumer:prepared` (between preparing a claimed request and publishing it), `stuck_recovery:*` (between the steps of `recovery-resolve.ts`) and the purge lookups `purge:*` (page-purge.ts, intent-redaction.ts, facts/purge.ts; a hook throwing a 57014 models a statement timeout). Used by `scripts/persistence/crash-robot.ts`, the #6511 tests and `test/sync-convergence.serial.test.ts`, which installs it in real `serve`/`sync` processes through the `test/fixtures/convergence-fault-kill.ts` preload (one action registry: kill, uncommitted edit, stall until released, or throw a given SQLSTATE, at the nth hit).
+- `src/core/persistence/fault-points.ts` — named crash seams for the persistence gate. `faultPoint(point, detail)` is a no-op unless a gate worker installed a hook with `installFaultHook`; production never does. Seams: `publication:<boundary>` (the five `PublicationHooks.boundary` names, routed through `withFaultPoints` in `publishMutation`), `effect:<kind>:mid` for every `EffectKind` in `completeEffect` (after the side effect, before its completion is recorded; `EFFECT_FAULT_POINTS` is a `Record<EffectKind, FaultPoint>`), `effect_recovery:before_clear` (`effect-recovery.ts`), `large_file:stage_streaming` (after each piece `stageStreamedContent` writes to a stage's in-progress name), `effect_recovery:before_stage` / `effect_recovery:staged` (a streamed, version 2 withdrawal mirror: once its record is durable, before its file is streamed into the publication stage, and after that step, before the recovery transaction renames the stage), `publication_recovery:before_clear` (`recoverPublication`), `sync:mid_checkpoint` (after each committed cursor step in `sync-run.ts` `saveCursor`), `sync:after_freeze` (#6712 PR 0: at the end of `freezeEntry` for an import entry, after its bytes are read and before the request is admitted; detail carries `slug` and `path`), `consumer:prepared` (between preparing a claimed request and publishing it), `stuck_recovery:*` (between the steps of `recovery-resolve.ts`) and the purge lookups `purge:*` (page-purge.ts, intent-redaction.ts, facts/purge.ts; a hook throwing a 57014 models a statement timeout). Used by `scripts/persistence/crash-robot.ts`, the #6511 tests and `test/sync-convergence.serial.test.ts`, which installs it in real `serve`/`sync` processes through the `test/fixtures/convergence-fault-kill.ts` preload (one action registry: kill, uncommitted edit, stall until released, or throw a given SQLSTATE, at the nth hit).
- `src/core/persistence/recovery-resolve.ts` + `src/core/repair/stuck-recovery.ts` — `gbrain repair stuck-recovery [--source <id>] [--request-id <uuid>]` (#6650 §1.10), explicit-only, preview-bound and destructive (registry `consentText`; `--apply --expect <hash> --keep prior|disk --yes`, a non-interactive apply without `--yes` exits 3). `scanStuckRecoveries` (owner host only, else `owner_unavailable` for a named source) reads the source's queued head blocker (`readHeadBlockers`; its `request_recovery` ids select the records) and every non-terminal recovery record on the worktree blocked on `unexpected_file_bytes` or whose file matches neither recorded version; a v2 shared-skill bundle record refuses `recovery_bundle_unsupported` (catalogue entry, `docs/guides/repair.md#recovery-bundle-unsupported`), a withdrawal-mirror effect recovery on the worktree is listed in `refused` (residual `effect_recovery`; named with `--request-id` it refuses `recovery_effect_unsupported`), a blocked terminal request is listed in `refused` (residual `terminal_refused`; named with `--request-id` it refuses `recovery_choice_refused`, as does a choice the record cannot support), and unblocked terminal cleanups, staging-byte blocks and self-recovering records are residuals. Each item lists every file's prior (or absent) and disk (or deleted) fingerprints and what recovery sees; a local preview writes the prior, disk and unified-diff files 0600 under `~/.gbrain/backups/stuck-recovery/<request>/<digest>/` (a private directory outside every checkout) and prints the `diff -u` command. The item digest binds the recovery identity (attempt, owner epoch, path and published hash per file), the recorded prior hashes, each file's disk view and the page's `knowledge_revision`. `resolveStuckRecovery` runs under `acquireWorktree` with a bounded wait (10 s, then `writer_lock_unavailable`; so the resident recovery pass returns unchanged), re-verifies the digest (`preview_changed`) and journals in `op_checkpoints` op `stuck-recovery-resolution` keyed `<request row id>:<preview hash>` (exempt from the checkpoint purge; the finished row is the audit entry): `backed_up` (disk and prior bytes durable, always), then `written` (`--keep prior`: `upgradeRecoveryStaging` reserves an older record's restoration stage within the recovery budget, `queue_capacity` otherwise, then the prior bytes are published through `publishPersistenceFile` at that stage after `cleanupRecoveryStaging`, an absent prior unlinked) or `abandoned` (`--keep disk`, #6640's drop: `completeWrite` ends the live request `conflict` `source_changed`, or `finishUnpublishedFailure` with its recorded failure; the record is never rewritten, so its reserved bytes are released by the terminal path's `clearResolvedRecovery`), then `recoverPublication(…, alreadyLocked)` finishes by its unchanged rule and the journal records `done` with the result. A step refuses `unexpected_file_bytes` when the file changed again; a different `--keep` for the same hash refuses `idempotency_conflict`; an identical apply after `done` replays the result (also after the approved set aged out). A record the resident consumer (any version) or an earlier killed run already finished reports `finished_by: another_pass`. `--keep prior` on a request with no recorded failure requeues it (the accepted write publishes again). `--keep disk` hands off to `gbrain sources reconcile <source> <slug> --brain host --preview` and never reports the page repaired. Fault seams `stuck_recovery:{backed_up,written,abandoned,recovered}`. Tests: `test/repair-stuck-recovery.test.ts`, `test/e2e/repair-stuck-recovery-postgres.test.ts`.
-- Segmented withdrawal mirror (`src/core/persistence/{effects,effect-recovery,effect-model,staging}.ts`, flip lane A) — a withdrawal's mirror and Git scans treat a page stored in segments as an inline page (older binaries skipped it with `page_body_segmented`). `mirrorPage` renders its file from the segments (`page-prepare.ts` `unreadPageFile`, a `StreamedFileContent`) and reserves a version 2 `EffectRecovery` (`after: null`; `staging.publication` names the streamed file by path and SHA-256; the reservation counts the file once). `recoverEffectPublication` writes that stage before its transaction (`stageStreamedMirror`: from the measured file, or after a crash from the segments at the recorded revision; seams `effect_recovery:before_stage` / `effect_recovery:staged`), then renames the verified stage (`staging.ts` `publishStreamedStage`). A segmented page's withdrawal is not materialized again: its rows were struck in its segments when the withdrawal committed. An older binary refuses a version 2 record (it has no embedded file) and leaves it for this one. Test: `test/large-pages/segmented-withdrawal-mirror.test.ts` (purge and forget twins, Git commits, two interruption seams, both engines).
+- Segmented withdrawal mirror (`src/core/persistence/{effects,effect-recovery,effect-model,staging}.ts`, flip lane A) — a withdrawal's mirror and Git scans treat a page stored in segments as an inline page (older binaries skipped it with `page_body_segmented`). `mirrorPage` renders its file from the segments (`page-prepare.ts` `unreadPageFile`, a `StreamedFileContent`) and reserves a version 2 `EffectRecovery` (`after: null`; `staging.publication` names the streamed file by path and SHA-256; the reservation counts the file once). `recoverEffectPublication` writes that stage before its transaction (`stageStreamedMirror`: from the measured file, or after a crash from the segments at the recorded revision, first discarding a stream a crash cut short under its in-progress name; seams `effect_recovery:before_stage` / `effect_recovery:staged`), then renames the verified stage (`staging.ts` `publishStreamedStage`). A segmented page's withdrawal is not materialized again: its rows were struck in its segments when the withdrawal committed. An older binary refuses a version 2 record (it has no embedded file) and leaves it for this one. Test: `test/large-pages/segmented-withdrawal-mirror.test.ts` (purge and forget twins, Git commits, two interruption seams, both engines).
diff --git a/docs/architecture/key-files/core-services-2-continued.md b/docs/architecture/key-files/core-services-2-continued.md
index 537a5ec9c9..d2bbf5a3d1 100644
--- a/docs/architecture/key-files/core-services-2-continued.md
+++ b/docs/architecture/key-files/core-services-2-continued.md
@@ -26,7 +26,7 @@ The page-state concurrency foundation under `src/core/page-state/` and the share
- `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`.
-- `src/core/persistence/large-file.ts` — Wave B PR 2 fix lane D: canonical files over 24 MiB (`LARGE_FILE_MIN_BYTES`) on the publication path, never one string or Buffer. `hashFile`/`hashDescriptor` (the persistence file hash, read in one-segment pieces), `FileBytes` (a file read on demand through one descriptor, the `ByteSource` the drift check's `fileBodyDigests` takes; `close` refuses `source_changed` when the file changed while read), `StreamedFileContent` (restore_page's file: export's serializer over the segments, measured once in preparation, produced again by `stageStreamedContent` into the reserved publication stage after the recovery record is durable and before the publication transaction; a mismatch removes the stage and refuses `revision_conflict`), and `stageBeforeCopy` (the prior file copied by the kernel into its `before` stage, hashed and fsynced; the recovery record names it by path and SHA-256 instead of embedding base64, and reserves the file once). `largeFileWork` (@internal) counts bytes read, written and copied and the largest piece. Coordinator: `pageRecoveryRecord` → `largeRecoveryRecord`, `stageLargeFiles`, `publishStagedContent`; a group publication never takes such a member (`groupable`). Flip lane A: the withdrawal mirror of a segmented page (`effects.ts` `mirrorPage`, any size) renders its file with `page-prepare.ts` `unreadPageFile` (a `StreamedFileContent`) and writes it with `stageStreamedContent` before its recovery transaction (`effect-recovery.ts` `stageStreamedMirror`); `existsAt` is the lstat-based leaf check it uses. Test: `test/large-pages/segmented-withdrawal-mirror.test.ts`. Tests: `test/large-pages/segmented-delete-restore-file.slow.test.ts` (27 and 90 MiB round trips byte for byte, both engines), `test/large-pages/segmented-delete-crash.slow.test.ts` (SIGKILL between file removal and commit, and after the restoration rename).
+- `src/core/persistence/large-file.ts` — Wave B PR 2 fix lane D: canonical files over 24 MiB (`LARGE_FILE_MIN_BYTES`) on the publication path, never one string or Buffer. `hashFile`/`hashDescriptor` (the persistence file hash, read in one-segment pieces), `FileBytes` (a file read on demand through one descriptor, the `ByteSource` the drift check's `fileBodyDigests` takes; `close` refuses `source_changed` when the file changed while read), `StreamedFileContent` (restore_page's file: export's serializer over the segments, measured once in preparation, produced again by `stageStreamedContent` into the reserved publication stage after the recovery record is durable and before the publication transaction: streamed into an in-progress sibling (`streamingStagePath`, `<stage>.streaming`), verified, fsynced and only then renamed to the stage's name, so a stream a crash cut short is never at that name and recovery removes it unread; a mismatch removes the stream and refuses `revision_conflict`; seam `large_file:stage_streaming` after each piece), and `stageBeforeCopy` (the prior file copied by the kernel into its `before` stage, hashed and fsynced; the recovery record names it by path and SHA-256 instead of embedding base64, and reserves the file once). `largeFileWork` (@internal) counts bytes read, written and copied and the largest piece. Coordinator: `pageRecoveryRecord` → `largeRecoveryRecord`, `stageLargeFiles`, `publishStagedContent`; a group publication never takes such a member (`groupable`). Flip lane A: the withdrawal mirror of a segmented page (`effects.ts` `mirrorPage`, any size) renders its file with `page-prepare.ts` `unreadPageFile` (a `StreamedFileContent`) and writes it with `stageStreamedContent` before its recovery transaction (`effect-recovery.ts` `stageStreamedMirror`); `existsAt` is the lstat-based leaf check it uses. `prepareFileTarget` reads the prior file through `FileBytes` at any size for a page stored in segments or a streamed target (never `readFileSync` whole), so its drift check reads in pieces of at most a segment. Test: `test/large-pages/segmented-withdrawal-mirror.test.ts`. Tests: `test/large-pages/segmented-delete-restore-file.slow.test.ts` (27 and 90 MiB round trips byte for byte, both engines), `test/large-pages/segmented-delete-crash.slow.test.ts` (SIGKILL between file removal and commit, and after the restoration rename).
- `src/core/page-body/body-digests.ts` — Wave B PR 2: the digests the drift check of a segmented page over the single-string ceiling compares (`page-prepare.ts` `segmentedFileMatches`). `fileBodyDigests(bytes, reading, filePath, opts)` runs the streamed importer's pass 1 (`BodyScanner`) over one reading of the file's bytes (an inferred-frontmatter prefix, then the bytes past a BOM), then SHA-256 over each region's byte ranges, and reports a facts fence marker; `storedBodyDigests(engine, pageId, ledger)` hashes each region of the trusted stored body (`readBodyRange`, one segment per read, `readGarbageCollector`). `bodyDigestWork` counts file and stored bytes and the largest piece handed to a scan or hash (at most a segment). In `page-prepare.ts`, `prepareFileTarget` compares a page whose body was not read back through `segmentedFileMatches` (the raw reading, then the inferred one from `streamed-import.ts` `inferredHeadPrefix`; the same normalizations as `fileMatchesSnapshot` via `importedFileType`); a file body with a facts fence under a withdrawal ledger that applies refuses `page_body_segmented` instead of reading as drift. `restore_page` of such a page (`prepareUnreadRestore`) versions it, clears `deleted_at` and reseals (or leaves the projection queued when chunks are missing) without re-importing, and publishes `serializePageToMarkdown`'s bytes streamed from the segments by `segmentedExportMarkdown` into one buffer (under the 25 MiB pre-push scan cap); a core page and an external_untrusted writer refuse `page_body_segmented`, and an agent-tier writer's advisory write-gate scan is not re-run over the unchanged body. Tests: `test/large-pages/segmented-file-drift.test.ts`.
- `src/core/page-body/segment-facts.ts` + `segment-conversation.ts` — Wave B PR 2 lane 2e2 (spec 8, full-pass mode): the facts fence reconcile and conversation facts over a segmented body. `segmentedFactsFenceView` is `factsFenceView` (facts-fence.ts: each section's parsed fence, which sections hold one, and the #3625 timeline marker) read from the segments: one SQL query selects the live manifest rows that carry facts slots, a forced cut, or a begin/end marker (bytea `position`, nothing transferred), and `bodyBlocks`' `want` option reads only the runs holding them; the segmenter never cuts inside a fence, so a fence lies in one block (a longer one is a forced run, refused above `BLOCK_MAX_BYTES` with `page_body_segmented`), and joining one across blocks is a bounded fallback. `segmentedBodyMatchesFile` is `canonicalCacheState`'s stale-cache check for a segmented page: the canonical file streamed through `BodyScanner` against the stored regions, by length and SHA-256. `readSegmentedConversationInput` gives `readConversationInput` (conversation-parser/body.ts) the summary body through ranged reads: whole within `CONVERSATION_WINDOW_BYTES` (`PAGE_MAX_BYTES`), else the newest whole segments that fit (never starting inside a forced run) with the window's `fallbackDate` from its first segment's entry state; extract-conversation-facts parses that window, passes the date to the parse and the extractor, and writes a `tail_window` receipt (`window_rule: no_prior_facts`), but only on a page with no conversation facts: one that has any keeps them and is skipped (`skipped_too_large`, `window_rule: prior_facts_kept`), since the run clears every prior fact. Each loop counts its reads in `segmentedPassWork`. Consumers: `runExtractFacts` (`planFenceReconcile`, the stale-cache guard, the managed fence-facts request), the sweep's fence candidates (segmented pages with facts slots), `extract-conversation-facts`. Tests: `test/large-pages/segmented-facts-reconcile.test.ts`, `segmented-conversation-facts.test.ts`, `segmented-derived-linear.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/architecture/key-files/schema-mutation.md b/docs/architecture/key-files/schema-mutation.md
index 6786dc0259..230f3fc178 100644
--- a/docs/architecture/key-files/schema-mutation.md
+++ b/docs/architecture/key-files/schema-mutation.md
@@ -6,7 +6,7 @@ The schema-pack mutation surface: six foundation modules + a mutate skeleton +
stats/sync data plane + CLI verbs + MCP ops + a first-class agent skill.
Key files:
-- `src/core/persistence/staging.ts` — journaled same-directory staging descriptors reserve names, expected sizes and full hashes before any sink. Owner-locked recovery removes only known complete regular files; partial/unexpected bytes keep the root and recovery quota blocked, including committed receipt cleanup. Legacy records acquire durable staging descriptors before any new restoration. Final accounting requires verified absence and parent-directory durability. Stage digests are read in pieces (`large-file.ts` `hashDescriptor`). Wave B: a `before` stage (`.<sha256>.tmp.before-<uuid>`, a name older binaries refuse) holds the copy of a prior canonical file over 24 MiB; a live request's recovery keeps it (`cleanupRecoveryStaging(record, { keepBefore })`) until `restoreBeforeStage` renames it back over the file with its recorded mode or it is removed because the file already holds the prior bytes. `publishStreamedStage` is the forward half of a version 2 withdrawal-mirror record (`effect-model.ts`): its verified publication stage, streamed from a segmented page's segments, is renamed over the canonical file; a missing stage refuses `unexpected_staging_bytes`. A regular-file ancestor proves an uncreated staging leaf is absent; recovery flushes the containing directory and settles the storage failure without deleting that ancestor or retaining a false recovery fence. Tests: `atomic-write.test.ts`, `atomic-long-staging.test.ts`, `persistence-staging.test.ts`, and eight-boundary process-crash harness.
+- `src/core/persistence/staging.ts` — journaled same-directory staging descriptors reserve names, expected sizes and full hashes before any sink. Owner-locked recovery removes only known complete regular files; partial/unexpected bytes keep the root and recovery quota blocked, including committed receipt cleanup. Legacy records acquire durable staging descriptors before any new restoration. Final accounting requires verified absence and parent-directory durability. Stage digests are read in pieces (`large-file.ts` `hashDescriptor`). Wave B: a `before` stage (`.<sha256>.tmp.before-<uuid>`, a name older binaries refuse) holds the copy of a prior canonical file over 24 MiB; a live request's recovery keeps it (`cleanupRecoveryStaging(record, { keepBefore })`) until `restoreBeforeStage` renames it back over the file with its recorded mode or it is removed because the file already holds the prior bytes. A publication stage's stream still under its in-progress name (`<stage>.streaming`) is removed unread by `cleanupRecoveryStaging` and `discardStreamingStage` (never published; its bytes are produced again) and must be absent for final accounting; a partial file at the stage's own name still refuses. `publishStreamedStage` is the forward half of a version 2 withdrawal-mirror record (`effect-model.ts`): its verified publication stage, streamed from a segmented page's segments, is renamed over the canonical file; a missing stage refuses `unexpected_staging_bytes`. A regular-file ancestor proves an uncreated staging leaf is absent; recovery flushes the containing directory and settles the storage failure without deleting that ancestor or retaining a false recovery fence. Tests: `atomic-write.test.ts`, `atomic-long-staging.test.ts`, `persistence-staging.test.ts`, and eight-boundary process-crash harness.
- `src/core/fs-durable.ts` — the shared durable-flush leaf (imports only `node:fs`). `flushFile(path)` fsyncs a file nobody holds open through `'r+'` on win32 (Windows `FlushFileBuffers` needs write access) and `'r'` elsewhere (a 0444 file stays flushable); a read-only file on win32 cannot be opened writable and is left to the OS. `flushDirectory(path, { bestEffort })` is strict by default: every error propagates except the win32 no-directory-flush codes (`EISDIR`/`EPERM`/`EINVAL`/`ENOTSUP`), a non-directory path fails `ENOTDIR`, and `bestEffort` swallows everything. `sameFileMode(actual, expected)` compares every permission bit on POSIX and only the owner write bit on win32, whose stat reports 0444/0666. A writer that still holds its descriptor sets the mode with `fchmodSync(fd)` and fsyncs that descriptor instead (atomic-write, skill-bundle staging). Callers: atomic-write, the persistence coordinator, identity, root registry, physical-root records, reconcile backups, recovery staging, topology checkouts (`flushTopologyDirectory` re-export, `flushTopologyTree`), skill bundles, agent-install state (`syncDirectory` re-export), `sources reconcile` previews and attendance-repair checkpoints. `scripts/check-durable-flush.ts` keeps new read-handle flushes out of `src/` (docs/TESTING.md#durable-flush-guard). Tests: `test/fs-durable.test.ts`, `test/persistence-windows-flush-5595.test.ts`, `test/bundle-files-windows-5475.test.ts`, `test/init-packaged-skills-native.test.ts`, run natively on windows-latest in the test.yml security-regressions job.
- `src/core/atomic-write.ts` — the shared atomic file writer for brain-repo markdown writers: unique short hidden tmp sibling from `atomicStagingPath` (`.<sha256(full target path)>.tmp.<uuid>`, so a valid basename near NAME_MAX still stages, #5861; `validateAtomicStagingPath` also accepts the historical `<target>.tmp.<uuid>` journal form, and recovery (`persistence/staging.ts` `upgradeRecoveryStaging`) durably swaps in a short stage only for a recorded historical leaf that returns ENAMETOOLONG; `timeline-write-through.ts` reuses the same allocator) → write loop until every byte lands (writeSync may legally short-write under disk pressure; a silent short write could atomically install truncated content) → fsync → close → synchronous staging boundary → optional `verify(onDiskBytes)` callback (throw = abort, tmp removed, target untouched) → atomic rename → parent-directory fsync through `fs-durable.ts` `flushDirectory` (rename durability; strict under `durable`, the journaled-publication flag, best-effort otherwise). The stage is opened with its final mode and `fchmod`-ed on the descriptor past the umask before any byte is written: `AtomicWriteOpts.mode` sets exact bits and reasserts them over an existing target's mode (a legacy 0644 file tightens on its next write); omitted, the target's existing mode is preserved, else 0644 & ~umask. `mkdirPrivate(dir, root = dir)` creates gbrain-private directories: a missing `root` gets default-permission ancestors and is itself made exactly 0700, each missing directory between `root` and `dir` is created 0700 (`O_NOFOLLOW` fchmod), and a directory that already exists, possibly one the user chose, is never chmod-ed; `dir` outside `root` throws. Consumers of the private modes: the Google connector (`google-source.ts`, `sources-ops.ts` Google add) and the persistence coordinator's Google publication. Consumed by `src/commands/backlinks.ts` (which verifies with `parseMarkdown({validate:true})` before the rename). Rename prevents torn writes, NOT lost updates — read-modify-write callers pair it with `withPageLock` (backlinks does). Unifying the per-module copies (skillopt/apply-edits, write-through, lint) is a filed TODO.
- `src/core/schema-pack/unify-types-handler.ts` + `src/core/onboard/checks.ts` (`checkPackUpgradeAvailable`) — pack-upgrade retype (`runUnifyTypes`, the `unify-types` job). #6196: on a managed brain apply runs the dry run first (`applyOnManagedBrain`): with nothing to retype, link or alias it only switches the active pack (`flipActivePack`, DB + file plane); otherwise it refuses `writer_coordinator_required` with the counts and a read-only `gbrain onboard --check --explain` fix before any lock or write, and the dry run warns that apply waits for coordinated retype. `pack_upgrade_available` on a managed brain is an info row (`readiness_state: degraded`) with that preview as its fix and no `unify-types` apply remediation it could not run. Coordinated retype (D2) is deferred.
diff --git a/docs/guides/memory-boundaries.md b/docs/guides/memory-boundaries.md
index 8a545d5dba..00e32944ed 100644
--- a/docs/guides/memory-boundaries.md
+++ b/docs/guides/memory-boundaries.md
@@ -200,8 +200,9 @@ writes for the page; the withdrawal's Git effect commits it. The file is
streamed from the segments into its staging file, one segment at a time, and
never held whole. Its recovery record names that staging file by path and
SHA-256 instead of holding the file, so the mirror reserves the file once in
-the recovery budget. A mirror interrupted before or after writing the staging
-file finishes on the writer's next pass.
+the recovery budget. A mirror interrupted before, during or after writing the
+staging file finishes on the writer's next pass: a staging file a crash cut
+short is discarded and written again.
<a id="segmented-doctor-skips"></a>
**What doctor does not read on a segmented page.** Some doctor checks read a
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index e1d936628a..2b70f6e7a1 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -764,7 +764,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }
{ since: '0.60.290.0', text: '`revert_version` of a page stored in segments, or to a version stored in segments, is refused with `page_body_segmented` (reason `segmented_revert`) before anything is written; it arrives with the segment writer in a later release. With `pages.segmented_storage` on, this includes pages between 1 MiB and 24 MiB that `revert_version` restores today. The versions stay readable: `get_versions` lists them, and a versioned `get_page` window reads one. Write the content you want back with `put_page`.' },
{ since: '0.60.290.0', text: 'Core memory and `gbrain repair frontmatter` on a page stored in segments (`pages.segmented_storage` on): a core page (`always_load: true`) stored in segments up to 24 MiB is now read back whole and rendered, budgeted and listed as its inline twin is; before, it counted as its title alone, and once a fact was withdrawn from it (or a `*` withdrawal existed in its source) session-start core, `context_pack`, `gbrain core status` and every core page write failed with `page_body_segmented`. A core page over 24 MiB is left out of core and doctor `core_memory` counts it (`skipped_segmented`), which now counts only those. `gbrain repair frontmatter --include-ambiguous` re-imports a page stored in segments up to 24 MiB whose title was derived from its slug, as it re-imports an inline page; over 24 MiB the file is listed `needs_review` with `page_body_segmented`, naming the 24 MiB limit, and nothing is written. Before, either case failed the whole preview.' },
// Switch-on flip lane A (withdrawal mirror of segmented pages). `since` is 'TBD' until the merge-slot stamp.
- { since: 'TBD', text: 'With `pages.segmented_storage` on, a withdrawal (`forget`, `forget_fact`, `purge_fact`) now rewrites the canonical file of a page stored in segments on a source backed by files, as it rewrites an inline page\'s: the file loses the withdrawn or purged row, its bytes are those `gbrain export` writes for the page, and the withdrawal\'s Git effect commits it. The file is streamed from the segments into its staging file one segment at a time, and its recovery record names that staging file by path and SHA-256 instead of holding the file. Before, the withdrawal-mirror and Git effects passed such a page by (`skipped` reason `page_body_segmented`) and its file kept the withdrawn text.' },
+ { since: 'TBD', text: 'With `pages.segmented_storage` on, a withdrawal (`forget`, `forget_fact`, `purge_fact`) now rewrites the canonical file of a page stored in segments on a source backed by files, as it rewrites an inline page\'s: the file loses the withdrawn or purged row, its bytes are those `gbrain export` writes for the page, and the withdrawal\'s Git effect commits it. The file is streamed from the segments into its staging file one segment at a time, and its recovery record names that staging file by path and SHA-256 instead of holding the file; the file\'s prior bytes are read in pieces too. A streamed staging file (this mirror\'s, or `restore_page`\'s for a page over 24 MiB) is written under an in-progress name and renamed once complete, so one a crash cut short is discarded and written again instead of blocking the source\'s worktree with `unexpected_staging_bytes`. Before, the withdrawal-mirror and Git effects passed such a page by (`skipped` reason `page_body_segmented`) and its file kept the withdrawn text.' },
// FIFO claim foreground guard (fgp-park-before-claim, #6862).
{ since: '0.60.271.0', text: 'A foreground write no longer loses to an idle drain\'s sync head. While a managed sync drains, a page write that may go ahead of the queued sync groups (none of them names its page) now holds back the next sync group even when the drain\'s lanes are idle and the write\'s own process is still claiming it; before, the drain could start a group in that moment and the write waited for it. The sync side still gets one group after each such write commits, so a stream of writes cannot stall it.' },
// #6858 (GBRA-121; Garry: "take care of fixing" #6858 asks 1-5; ask 5 contained per GBRA-108). `since` is a placeholder equal to the branch's VERSION; the integrator sets it to the merge-slot stamp by hand.
diff --git a/src/core/persistence/effect-recovery.ts b/src/core/persistence/effect-recovery.ts
index 7e8c675b10..486246181c 100644
--- a/src/core/persistence/effect-recovery.ts
+++ b/src/core/persistence/effect-recovery.ts
@@ -15,7 +15,7 @@ import { withFilesystemPublication } from './filesystem-guard.ts';
import { persistenceFileHash, publishPersistenceFile } from './coordinator.ts';
import type { EffectRecovery, PersistenceEffect } from './effect-model.ts';
import { tryAcquirePublicationCapacity } from './pool-capacity.ts';
-import { assertRecoveryStagingAbsent, cleanupRecoveryStaging, publishStreamedStage, upgradeRecoveryStaging } from './staging.ts';
+import { assertRecoveryStagingAbsent, cleanupRecoveryStaging, discardStreamingStage, publishStreamedStage, upgradeRecoveryStaging } from './staging.ts';
import { existsAt, stageStreamedContent, type StreamedFileContent } from './large-file.ts';
import { unreadPageFile } from './page-prepare.ts';
import { isSegmentedPage } from '../page-body/page-shape.ts';
@@ -124,6 +124,8 @@ async function stageStreamedMirror(engine: BrainEngine, effect: PersistenceEffec
const detail = { effectId: effect.id, requestId: effect.request_id, sourceId: effect.source_id, slug: record.slug, path: stage.path };
await faultPoint('effect_recovery:before_stage', detail);
await withFilesystemPublication([record.root], async () => {
+ // A stream a crash cut short is still under its in-progress name; it is discarded and the stage produced again.
+ discardStreamingStage(record);
if (existsAt(stage.path) || record.beforeHash === record.afterHash || persistenceFileHash(record.path) !== record.beforeHash) return;
let file = content;
if (!file) {
diff --git a/src/core/persistence/fault-points.ts b/src/core/persistence/fault-points.ts
index db8e344e30..b6fe4f4d0f 100644
--- a/src/core/persistence/fault-points.ts
+++ b/src/core/persistence/fault-points.ts
@@ -47,7 +47,10 @@ export type FaultPoint = `publication:${PublicationBoundary}` | `effect:${Effect
| 'segmented:texts_staged' | 'segmented:manifest_staged' | 'segmented:chunks_staged' | 'segmented:flipped' | 'segmented:projection_staged'
// A prior file over the single-string ceiling copied to its before stage (large-file.ts `stageBeforeCopy`): after the copy is
// written under its temporary name (unverified, unflushed: a crash during the copy) and once it is flushed, before its rename.
- | 'large_file:stage_copying' | 'large_file:stage_flushed';
+ | 'large_file:stage_copying' | 'large_file:stage_flushed'
+ // A streamed file (large-file.ts `stageStreamedContent`: restore_page, a segmented withdrawal mirror) after each piece is
+ // written to its in-progress name, before the stream is verified, flushed and renamed to the reserved stage name.
+ | 'large_file:stage_streaming';
/**
* `signal` (#6278, `consumer:preparing` only): the preparation's abort signal, so
* a stalling hook can model both the reporter's cases: a preparer that honours
diff --git a/src/core/persistence/large-file.ts b/src/core/persistence/large-file.ts
index af6e8d6588..36adc48e5b 100644
--- a/src/core/persistence/large-file.ts
+++ b/src/core/persistence/large-file.ts
@@ -18,6 +18,7 @@ import { OperationError, opError } from '../ops/contract.ts';
import { assertManagedFilesystemWrite } from './filesystem-guard.ts';
import { sha256 } from './digest.ts';
import type { RecoveryStagingFile } from './staging.ts';
+import { faultPoint } from './fault-points.ts';
/** A canonical file of more bytes than this is read, hashed, copied and written in pieces. */
export const LARGE_FILE_MIN_BYTES = PAGE_MAX_BYTES;
@@ -147,31 +148,46 @@ function removeOwnStage(path: string): void {
}
/**
- * Writes `content` into its reserved staging file (created exclusively with `mode`, else 0644 under the umask), one
- * piece at a time, fsynced. Bytes that are not the measured ones (the page changed since preparation) remove the
- * stage and refuse as `revision_conflict`, so the request is prepared again.
+ * Where `stageStreamedContent` streams a stage before renaming it to the stage's name, so a stream a crash cut short is
+ * never at the stage's name. Recovery removes it unread (staging.ts): the rename is the commit point, so a file still
+ * under this name was never published and its bytes can always be produced again.
+ */
+export function streamingStagePath(stagePath: string): string { return `${stagePath}.streaming`; }
+
+/**
+ * Writes `content` into its reserved staging file one piece at a time: streamed into `streamingStagePath` (created
+ * exclusively with `mode`, else 0644 under the umask), checked to hold the measured bytes, fsynced, and only then renamed
+ * to the stage's name, so a stage under that name is always whole. Bytes that are not the measured ones (the page
+ * changed since preparation) remove the stream and refuse as `revision_conflict`, so the request is prepared again.
+ * Seam `large_file:stage_streaming` after each piece is written (a crash mid-stream).
*/
export async function stageStreamedContent(engine: BrainEngine, path: string, content: StreamedFileContent, stage: RecoveryStagingFile, mode: number | null): Promise<void> {
assertManagedFilesystemWrite(path);
validateAtomicStagingPath(path, stage.path);
- const fd = openSync(stage.path, 'wx', mode ?? 0o644);
+ const streaming = streamingStagePath(stage.path);
+ const fd = openSync(streaming, 'wx', mode ?? 0o644);
let staged = false;
try {
- if (mode !== null) fchmodSync(fd, mode);
- const hash = createHash('sha256');
- let bytes = 0;
- for await (const piece of content.pieces(engine)) {
- writeAll(fd, piece);
- counted(piece.length, 'bytesWritten');
- hash.update(piece);
- bytes += piece.length;
- }
- if (bytes !== stage.bytes || hash.digest('hex') !== stage.hash) throw new OperationError('revision_conflict', 'The page changed during preparation.', 'Read its current revision and submit the updated intent with a new request_id.');
- fsyncSync(fd);
+ try {
+ if (mode !== null) fchmodSync(fd, mode);
+ const hash = createHash('sha256');
+ let bytes = 0;
+ for await (const piece of content.pieces(engine)) {
+ writeAll(fd, piece);
+ counted(piece.length, 'bytesWritten');
+ hash.update(piece);
+ bytes += piece.length;
+ await faultPoint('large_file:stage_streaming', { path: streaming });
+ }
+ if (bytes !== stage.bytes || hash.digest('hex') !== stage.hash) throw new OperationError('revision_conflict', 'The page changed during preparation.', 'Read its current revision and submit the updated intent with a new request_id.');
+ fsyncSync(fd);
+ } finally { closeSync(fd); }
+ if (existsAt(stage.path)) throw opError('unexpected_staging_bytes', 'A file already holds the reserved stage name.',
+ 'A recovery staging file changed outside gbrain. Inspect the pending recovery in writer status and tell the user; never delete or edit staging files by hand.');
+ renameSync(streaming, stage.path);
staged = true;
} finally {
- closeSync(fd);
- if (!staged) removeOwnStage(stage.path);
+ if (!staged) removeOwnStage(streaming);
}
flushDirectory(dirname(stage.path));
}
diff --git a/src/core/persistence/page-prepare.ts b/src/core/persistence/page-prepare.ts
index fefcec18dd..6187d1e57e 100644
--- a/src/core/persistence/page-prepare.ts
+++ b/src/core/persistence/page-prepare.ts
@@ -287,8 +287,11 @@ export async function prepareFileTarget(engine: BrainEngine, row: Pick<WriteRequ
const rel = relative(root, path).split(sep).join('/');
if (matchesAnyGlob(rel, options.excludeTombstone.patterns)) { options.excludeTombstone.onExcluded(rel); return undefined; }
}
- // A prior file over the single-string ceiling is read on demand in pieces (large-file.ts), never whole.
- const before: Buffer | FileBytes | null = !existsSync(path) ? null : statSync(path).size > LARGE_FILE_MIN_BYTES ? FileBytes.open(path) : readFileSync(path);
+ // A prior file over the single-string ceiling is read on demand in pieces (large-file.ts), never whole; so is the file
+ // of a page stored in segments, or of a streamed target, at any size (its comparison reads it piecewise anyway).
+ const piecewise = (snapshot && bodyUnread(snapshot.page)) || (content !== null && isStreamedContent(content));
+ const before: Buffer | FileBytes | null = !existsSync(path) ? null
+ : piecewise || statSync(path).size > LARGE_FILE_MIN_BYTES ? FileBytes.open(path) : readFileSync(path);
try {
return await compareFileTarget(engine, row, snapshot, content, options, { root, path, mode, capturedPath, before });
} finally { if (before instanceof FileBytes) before.close(); }
diff --git a/src/core/persistence/staging.ts b/src/core/persistence/staging.ts
index e0a772b0fc..038a23a6fd 100644
--- a/src/core/persistence/staging.ts
+++ b/src/core/persistence/staging.ts
@@ -7,7 +7,7 @@ import { opError, OperationError } from '../ops/contract.ts';
import { sha256 } from './digest.ts';
import type { BrainEngine } from '../engine.ts';
import { readJournalLimits } from './limits.ts';
-import { beforeStageCopyPath, hashDescriptor, validateBeforeStagePath } from './large-file.ts';
+import { beforeStageCopyPath, hashDescriptor, streamingStagePath, validateBeforeStagePath } from './large-file.ts';
import { declarePersistenceProtocol } from './protocol.ts';
export interface RecoveryStagingFile { path: string; hash: string; bytes: number }
@@ -99,6 +99,7 @@ function removeUnread(path: string): void {
*/
export function cleanupRecoveryStaging(record: StagedRecovery, opts: { keepBefore?: boolean; priorIntact?: boolean } = {}): void {
const before = record.staging?.before;
+ discardStreamingStage(record);
for (const stage of stages(record)) {
if (stage === before) {
removeUnread(beforeStageCopyPath(stage.path));
@@ -127,6 +128,15 @@ export function restoreBeforeStage(record: StagedRecovery & { mode: number | nul
boundary?.('directory_flushed');
}
+/**
+ * Removes, unread, a publication stage's stream still under its in-progress name (`streamingStagePath`): a stream a crash
+ * cut short. It was never renamed to the stage's name, so it was never published and holds no bytes recovery needs.
+ */
+export function discardStreamingStage(record: StagedRecovery): void {
+ const publication = record.staging?.publication;
+ if (publication && stages(record).includes(publication)) removeUnread(streamingStagePath(publication.path));
+}
+
/**
* A version 2 mirror record's forward publication (effect-recovery.ts): its verified publication stage, streamed from
* the page's segments, is renamed over the canonical path. A missing stage refuses (`unexpected_staging_bytes`).
@@ -141,7 +151,8 @@ export function publishStreamedStage(record: StagedRecovery): void {
/** The final accounting fence also protects direct terminal-cleanup callers. */
export function assertRecoveryStagingAbsent(record: StagedRecovery): void {
for (const stage of stages(record)) {
- if (statIfPresent(stage.path) || (stage === record.staging?.before && statIfPresent(beforeStageCopyPath(stage.path)))) throw blocked();
+ if (statIfPresent(stage.path) || (stage === record.staging?.before && statIfPresent(beforeStageCopyPath(stage.path)))
+ || (stage === record.staging?.publication && statIfPresent(streamingStagePath(stage.path)))) throw blocked();
flushParent(stage.path);
}
}
diff --git a/test/large-pages/segmented-withdrawal-mirror.test.ts b/test/large-pages/segmented-withdrawal-mirror.test.ts
index a7a0da5f3f..51f1c43f21 100644
--- a/test/large-pages/segmented-withdrawal-mirror.test.ts
+++ b/test/large-pages/segmented-withdrawal-mirror.test.ts
@@ -17,9 +17,10 @@
* twin's writes and on for the segmented twin's. The interruptions are modelled at the `effect_recovery:before_stage`
* and `effect_recovery:staged` seams (fault-points.ts) with a hook that throws once.
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { afterAll, beforeAll, describe, expect, spyOn, test } from 'bun:test';
import { createHash, randomUUID } from 'node:crypto';
-import { readdirSync, readFileSync, statSync } from 'node:fs';
+import * as fs from 'node:fs';
+import { existsSync, readdirSync, readFileSync, writeFileSync } from 'node:fs';
import { basename, join } from 'node:path';
import { exportBodyLedger, readExportPage, readExportWithdrawals, segmentedExportMarkdown } from '../../src/core/export-snapshot.ts';
import { serializeMarkdown, slugStampedFrontmatter } from '../../src/core/markdown.ts';
@@ -43,11 +44,29 @@ const FORGOTTEN: Record<string, string> = { [INLINE]: 'Twin Example bike lock is
const KEPT = 'Twin Example adopted a narwhalbot';
/** The claim each modelled interruption's purge removes. */
const CRASH_CLAIMS = { 'effect_recovery:before_stage': 'Twin Example vault code is 1902', 'effect_recovery:staged': 'Twin Example vault code is 6640' };
+/** The claims of the mid-stream death and of the partial stage left at the reserved name. */
+const STREAM_CLAIM = 'Twin Example vault code is 2718';
+const PARTIAL_CLAIM = 'Twin Example vault code is 3141';
const fileOf = (brain: TwinBrain, slug: string) => join(brain.root, slug + '.md');
const sha = (bytes: Buffer) => createHash('sha256').update(bytes).digest('hex');
/** A twin's file as `view` neutralizes it, with its own forgotten claim (the twins' only differing text) neutralized too. */
const twinFile = async (brain: TwinBrain, slug: string) => String((await brain.view(slug)).file).split(FORGOTTEN[slug]!).join('<forgotten>');
+/**
+ * Records every whole-file `readFileSync` of `path` made from the persistence layer (the mirror and Git effects, their
+ * drift checks and recovery), with the call's stack as evidence. The purge's own residual scan (facts/purge-verify.ts)
+ * is outside it.
+ */
+function watchWholeReads(path: string) {
+ const original = fs.readFileSync;
+ const hits: string[] = [];
+ const spy = spyOn(fs, 'readFileSync').mockImplementation(((...args: Parameters<typeof fs.readFileSync>) => {
+ const stack = new Error().stack ?? '';
+ if (String(args[0]) === path && stack.includes('/src/core/persistence/')) hits.push(stack.split('\n').slice(1, 4).join(' | '));
+ return original(...args);
+ }) as typeof fs.readFileSync);
+ return { hits, restore: () => spy.mockRestore() };
+}
const resetWork = () => { for (const key of Object.keys(largeFileWork) as (keyof typeof largeFileWork)[]) largeFileWork[key] = 0; };
/** Staging leftovers (hidden `.<sha>.tmp.<uuid>` siblings) next to the twins' files. */
const stagingLeft = (brain: TwinBrain) => readdirSync(join(brain.root, 'people')).filter(name => name.includes('.tmp.'));
@@ -56,7 +75,8 @@ const stagingLeft = (brain: TwinBrain) => readdirSync(join(brain.root, 'people')
* Runs effect passes on this host until the source's mirror and Git effects have all settled; the persistence consumer
* runs them too, so a claim it holds settles meanwhile. Past the deadline the assertions report the effects' state.
*/
-const settle = (brain: TwinBrain, kind: 'pglite' | 'postgres') => waitFor(async () => {
+const settle = (brain: TwinBrain, kind: 'pglite' | 'postgres', beforePass?: () => Promise<void>) => waitFor(async () => {
+ await beforePass?.();
const [open] = await brain.engine.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM persistence_effects
WHERE source_id=$1 AND kind IN ('withdrawal-mirror','git') AND (state<>'committed' OR recovery IS NOT NULL)`, [brain.sourceId]);
if (!open!.n) return true;
@@ -85,14 +105,14 @@ const effectsOf = async (brain: TwinBrain, requestId: string) => (await brain.en
.map(e => ({ kind: e.kind, state: e.state, error: e.error_code, skipped: (typeof e.data === 'string' ? JSON.parse(e.data) : e.data)?.skipped ?? [] }));
const SETTLED = [{ kind: 'git', state: 'committed', error: null, skipped: [] }, { kind: 'withdrawal-mirror', state: 'committed', error: null, skipped: [] }];
-async function purge(brain: TwinBrain, kind: 'pglite' | 'postgres', slug: string, claim: string) {
+async function purge(brain: TwinBrain, kind: 'pglite' | 'postgres', slug: string, claim: string, beforePass?: () => Promise<void>) {
const [fact] = await brain.engine.executeRaw<{ id: number }>('SELECT id FROM facts WHERE source_id=$1 AND source_markdown_slug=$2 AND fact=$3', [brain.sourceId, slug, claim]);
const dry = await brain.call('purge_fact', { id: Number(fact!.id), dry_run: true }, slug);
expect(dry.confirm_token).toBeString();
const requestId = randomUUID();
const done = await brain.call('purge_fact', { id: Number(fact!.id), confirm: dry.confirm_token, expected_revision: dry.expected_revision, request_id: requestId }, slug);
expect(done.state).toBe('committed');
- await settle(brain, kind);
+ await settle(brain, kind, beforePass);
return { requestId, hash8: String(done.purge.hash8) };
}
@@ -127,7 +147,10 @@ for (const kind of testBackends()) {
const inline = await purge(brain, kind, INLINE, CLAIMS[INLINE]!);
resetWork();
- const segmented = await purge(brain, kind, SEGMENTED, CLAIMS[SEGMENTED]!);
+ const reads = watchWholeReads(fileOf(brain, SEGMENTED));
+ let segmented: Awaited<ReturnType<typeof purge>>;
+ try { segmented = await purge(brain, kind, SEGMENTED, CLAIMS[SEGMENTED]!); } finally { reads.restore(); }
+ const wholeReads = reads.hits;
const work = { ...largeFileWork };
// Neither twin's mirror or Git walk passed its page by: both effects committed with nothing skipped.
@@ -149,7 +172,9 @@ for (const kind of testBackends()) {
expect(await gitAsync(brain.root, 'show', `HEAD:${slug}.md`)).toBe(readFileSync(fileOf(brain, slug), 'utf8'));
}
- // Streamed: the mirror staged exactly the file's bytes, and no piece it read or wrote was over one segment.
+ // Streamed: the mirror staged exactly the file's bytes, and no piece it read or wrote was over one segment. The
+ // canonical file itself (the drift check before the overwrite, about 1.1 MB) is read in pieces too, never whole.
+ expect(wholeReads).toEqual([]);
expect(work.bytesWritten).toBe(file.length);
expect(work.bytesRead).toBeGreaterThanOrEqual(work.bytesWritten);
expect(work.largestPiece).toBeGreaterThan(0);
@@ -159,13 +184,15 @@ for (const kind of testBackends()) {
test('forget_fact rewrites the segmented file with the row withdrawn, as the inline twin\'s, and commits it', async () => {
const before = { [INLINE]: readFileSync(fileOf(brain, INLINE), 'utf8'), [SEGMENTED]: readFileSync(fileOf(brain, SEGMENTED), 'utf8') };
const receipts: Record<string, string> = {};
- for (const slug of [INLINE, SEGMENTED]) {
+ const reads = watchWholeReads(fileOf(brain, SEGMENTED));
+ try { for (const slug of [INLINE, SEGMENTED]) {
const [fact] = await brain.engine.executeRaw<{ id: number }>('SELECT id FROM facts WHERE source_id=$1 AND source_markdown_slug=$2 AND fact=$3', [brain.sourceId, slug, FORGOTTEN[slug]]);
receipts[slug] = randomUUID();
expect(await brain.call('forget_fact', { id: Number(fact!.id), request_id: receipts[slug] }, slug)).toMatchObject({ state: 'committed' });
if (slug === INLINE) resetWork();
await settle(brain, kind);
- }
+ } } finally { reads.restore(); }
+ const wholeReads = reads.hits;
const work = { ...largeFileWork };
expect(await effectsOf(brain, receipts[SEGMENTED]!)).toEqual(await effectsOf(brain, receipts[INLINE]!));
@@ -180,6 +207,7 @@ for (const kind of testBackends()) {
expect(await gitAsync(brain.root, 'status', '--porcelain', '--', slug + '.md')).toBe('');
expect(await gitAsync(brain.root, 'show', `HEAD:${slug}.md`)).toBe(readFileSync(fileOf(brain, slug), 'utf8'));
}
+ expect(wholeReads).toEqual([]);
expect(work.bytesWritten).toBe(file.length);
expect(work.largestPiece).toBeGreaterThan(0);
expect(work.largestPiece).toBeLessThanOrEqual(SEGMENT_MAX_BYTES);
@@ -194,7 +222,7 @@ for (const kind of testBackends()) {
await seed.setSwitch(true);
await seed.put(SEGMENTED, 1_100_000);
});
- await extract(brain, SEGMENTED, [...Object.values(CRASH_CLAIMS), KEPT]);
+ await extract(brain, SEGMENTED, [...Object.values(CRASH_CLAIMS), STREAM_CLAIM, PARTIAL_CLAIM, KEPT]);
expect(await brain.storageOf(SEGMENTED)).toBe('segmented');
await settle(brain, kind);
}, 600_000);
@@ -246,5 +274,85 @@ for (const kind of testBackends()) {
expect(work.largestPiece).toBeLessThanOrEqual(SEGMENT_MAX_BYTES);
}, 600_000);
}
+
+ test('a mirror whose process dies mid-stream discards the partial file on recovery and publishes', async () => {
+ const recoveryState = async () => (await brain.engine.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM persistence_effects
+ WHERE source_id=$1 AND kind='withdrawal-mirror' AND state='queued' AND recovery IS NOT NULL`, [brain.sourceId]))[0]!.n;
+ // The seam fires after each piece written to the in-progress file; on the third the process "dies". A death leaves
+ // that file as it is, while the modelled one (a throw) lets the writer remove it, so its bytes are put back at the
+ // same path once the attempt has released its claim and before recovery runs: the state a death leaves.
+ let pieces = 0;
+ let partial: { path: string; bytes: Buffer; stage: string } | null = null;
+ let restored = false;
+ installFaultHook(async (point, detail) => {
+ if (point !== 'large_file:stage_streaming' || partial || ++pieces < 3) return;
+ const [row] = await brain.engine.executeRaw<{ recovery: any }>('SELECT recovery FROM persistence_effects WHERE source_id=$1 AND recovery IS NOT NULL', [brain.sourceId]);
+ const recovery = typeof row!.recovery === 'string' ? JSON.parse(row!.recovery) : row!.recovery;
+ partial = { path: detail.path!, bytes: readFileSync(detail.path!), stage: recovery.staging.publication.path };
+ throw new Error('modelled death mid-stream');
+ });
+ const putBack = async () => {
+ if (!partial || restored || existsSync(partial.path) || !(await recoveryState())) return;
+ writeFileSync(partial.path, partial.bytes, { flag: 'wx' });
+ restored = true;
+ };
+ resetWork();
+ let receipt: Awaited<ReturnType<typeof purge>>;
+ try { receipt = await purge(brain, kind, SEGMENTED, STREAM_CLAIM, putBack); } finally { installFaultHook(undefined); }
+ const work = { ...largeFileWork };
+ const file = readFileSync(fileOf(brain, SEGMENTED));
+
+ // The death left a partial file under its own in-progress name next to the reserved stage name, never at it.
+ expect(partial).not.toBeNull();
+ const died = partial! as { path: string; bytes: Buffer; stage: string };
+ expect(restored).toBe(true);
+ expect(died.path).not.toBe(died.stage);
+ expect(died.bytes.length).toBeGreaterThan(0);
+ expect(died.bytes.length).toBeLessThan(file.length);
+
+ // Recovery discarded it, streamed the stage again from the segments and published the file without the claim.
+ expect(file.toString('utf8')).not.toContain(STREAM_CLAIM);
+ expect(file.toString('utf8')).toContain(KEPT);
+ expect(file.equals(await exported(brain, SEGMENTED))).toBe(true);
+ expect(await effectsOf(brain, receipt!.requestId)).toEqual(SETTLED);
+ expect(stagingLeft(brain)).toEqual([]);
+ const counters = await brain.engine.executeRaw<{ bytes: string }>('SELECT recovery_bytes::text AS bytes FROM persistence_counters');
+ expect(counters.every(row => Number(row.bytes) === 0)).toBe(true);
+ expect(work.bytesWritten).toBe(died.bytes.length + file.length);
+ expect(work.largestPiece).toBeLessThanOrEqual(SEGMENT_MAX_BYTES);
+ }, 600_000);
+
+ // Last: it leaves the source's worktree blocked on purpose.
+ test('a partial file at the reserved stage name still refuses (unexpected_staging_bytes) and leaves the file alone', async () => {
+ const before = readFileSync(fileOf(brain, SEGMENTED));
+ let stage: string | null = null;
+ installFaultHook(async (point, detail) => {
+ if (point !== 'effect_recovery:before_stage' || stage) return;
+ stage = detail.path!;
+ writeFileSync(stage, 'partial bytes', { flag: 'wx' });
+ throw new Error('modelled death after a foreign write at the stage name');
+ });
+ let requestId = '';
+ try {
+ const [fact] = await brain.engine.executeRaw<{ id: number }>('SELECT id FROM facts WHERE source_id=$1 AND source_markdown_slug=$2 AND fact=$3', [brain.sourceId, SEGMENTED, PARTIAL_CLAIM]);
+ const dry = await brain.call('purge_fact', { id: Number(fact!.id), dry_run: true }, SEGMENTED);
+ requestId = randomUUID();
+ expect(await brain.call('purge_fact', { id: Number(fact!.id), confirm: dry.confirm_token, expected_revision: dry.expected_revision, request_id: requestId }, SEGMENTED))
+ .toMatchObject({ state: 'committed' });
+ await waitFor(async () => {
+ await withEnv(brain.env(), async () => {
+ await brain.engine.executeRaw(`UPDATE persistence_effects SET next_attempt_at=now() WHERE source_id=$1 AND state='queued'`, [brain.sourceId]);
+ await runPersistenceEffects(brain.engine, { engine: kind, embedding_disabled: true } as never, { hostId: localHostId(), limit: 20 });
+ });
+ return (await effectsOf(brain, requestId)).find(e => e.kind === 'withdrawal-mirror')?.error === 'unexpected_staging_bytes';
+ }, { timeoutMs: 60_000, intervalMs: 100, label: 'the mirror refused the foreign stage' });
+ } finally { installFaultHook(undefined); }
+ expect(stage).not.toBeNull();
+ expect(readFileSync(stage!, 'utf8')).toBe('partial bytes');
+ expect(readFileSync(fileOf(brain, SEGMENTED)).equals(before)).toBe(true);
+ const [mirror] = await brain.engine.executeRaw<{ recovering: boolean }>(`SELECT e.recovery IS NOT NULL AS recovering FROM persistence_effects e
+ JOIN persistence_requests r ON r.id=e.request_id WHERE r.request_id=$1::uuid AND e.kind='withdrawal-mirror'`, [requestId]);
+ expect(mirror!.recovering).toBe(true);
+ }, 600_000);
});
}