Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(large-pages): mirror cross-cut facts fences, release unstaged mirror records, bound mirror/Git work
garrytanc9e68e7fd65b
diff --git a/docs/architecture/key-files/core-services-2-continued.md b/docs/architecture/key-files/core-services-2-continued.mdindex 5efeb2ad83..280176cecc 100644--- a/docs/architecture/key-files/core-services-2-continued.md+++ b/docs/architecture/key-files/core-services-2-continued.md@@ -23,9 +23,9 @@ The page-state concurrency foundation under `src/core/page-state/` and the share- `src/core/page-body/page-shape.ts` — Wave B PR 1 (spec 1.5): segmented page bodies are unreachable as strings. `guardSegmentedBody` (called by `rowToPage` for a row with `body_storage = 'segmented'`, so by every snapshot and `getPage` read) replaces `compiled_truth` / `timeline` with enumerable getters and setters that throw `page_body_segmented`, so property reads, spread, `JSON.stringify`, `structuredClone` and assignment all fail loud instead of seeing an empty body. `isSegmentedPage`, `assertInlineBody(page, site)` (explicit refusal where a writer would otherwise act before a getter fires, e.g. SQL-only writers; every `page_body_segmented` refusal's fix reads the page with `get_page body: 'auto'`), `pageBodyBytes(page)` (`body_bytes` for segmented pages), `pageBodySegmentedError` and `pageBodyOverCeilingError` (the refusal of a fence or timeline write through the put path on a page over 24 MiB; `wholeBodySnapshot` in `persistence/segmented-apply.ts` reads a page within it back as strings and refuses above it: semantic timeline writes, `takes-prepare.ts`, `facts-prepare.ts`, `reconcile-state.ts`, `gbrain core`). Tag writes on a segmented page never read the body: `prepareSegmentedTagMutation` (`persistence/page-prepare.ts`) flips them in metadata over the live manifest (`test/large-pages/segmented-semantic-writes.test.ts`). `bodyUnread(page)` says a segmented page's body was not read back as strings (over the single-string ceiling, see `materializedPage`); such a body was written by the streamed import, which holds fenced files, so `fenceBody(page)` reads it as empty for the fence merges and `withoutBody(page)` copies the page's other fields for a render whose body comes from the incoming write (a shrunk file rewrites such a page: `test/large-pages/segmented-shrink-below-ceiling.test.ts`). `Page` stays one shape (`body_storage?`, `body_bytes?`); the static half is `scripts/check-page-body-readers.ts` with `scripts/page-body-readers-baseline.tsv` (docs/TESTING.md#page-body-readers). Pinned by `test/large-pages/segmented-body-unreachable.test.ts`.- `src/core/page-body/limits.ts` — Wave B size classes, ceilings, retention numbers and config keys in one place. `readPageBodyPolicy` is the single question every write asks: `segmented` is the effective `pages.segmented_storage` (unset means `SEGMENTED_STORAGE_DEFAULT`, `on`; `off` or an unrecognized value is off; held off while `segmentedWriterBlockers` finds a recent writer that blocks, and an unreadable gate counts as blocked), `maxBytes` the engine ceiling (256 MiB Postgres, 128 MiB PGLite, lowered by `pages.max_bytes`) while on and `PAGE_MAX_BYTES` while off. Config is read per call; only the writer gate is cached (`SEGMENTED_WRITER_GATE_TTL_MS`, `_resetSegmentedWriterGateForTests`). `chooseBodyStorage` applies the 1 MiB / 512 KiB hysteresis. The writer gate (`segmentedGateWriters` in `persistence/writer-versions.ts`) reads seven days of admitted requests in any state, committed publications, `ingest_log` rows and, on Postgres, `persistence_consumers` heartbeats; a row blocks when its version is below `SEGMENTED_WRITER_FLOOR` or unparsable, or when it lacks the segment-reader mark (migration v254: `admitter_segment_reader`, `consumer_segment_reader`, `persistence_consumers.segment_reader`, `ingest_log.writer_segment_reader`), because releases 0.60.252.0-0.60.262.0 have no segment readers and a version string cannot tell them apart. Not seen: an older binary's unmanaged single-page write, a run that dies before it logs, and read-only or export use. `pageRecoveryBytes` is the default `persistence.limits.worktree_recovery_bytes` (read by `persistence/limits.ts` `readJournalLimits` in its one config statement): twice the body the configured switch admits (`segmentedMaxBytes`, or `PAGE_MAX_BYTES` while off) plus `RECOVERY_FILE_HEADROOM_BYTES` per copy, never below 256 MiB, because a restore reserves its file twice; it ignores the writer gate so a page admitted while the switch was effective stays restorable. Tests: `test/large-pages/segmented-switch.test.ts`, `test/large-pages/recovery-budget-default.test.ts`.-- `src/core/page-body/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/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; a trusted read (`trustedSegments`) joins the segments it spans and overlays them whole, refusing `page_body_segmented` above `BLOCK_MAX_BYTES`, or `page_projection_stale` when the read starts inside the block) 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/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` (read-range.ts) 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: 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`.diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 59d4aee5df..cc82dfec85 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -891,6 +891,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }// Large pages switch-on flip (Wave B PR 2 follow-up). `since` is stamped, with SEGMENTED_WRITER_FLOOR, at the merge slot.{ since: 'TBD', text: 'Pages over 1 MiB are now stored in segments: `pages.segmented_storage` is on by default. Reading a window, outline or chunk context of a large page costs the size of the window, not the page, and a rewrite re-indexes only the segments that changed. A page can be up to 256 MiB on Postgres and 128 MiB on PGLite (`pages.max_bytes` lowers it). `put_page`, `put_pages` and `capture` content and `gbrain put` stdin stay limited to 24 MiB per call, so a larger page comes in by `gbrain import` or `gbrain sync` of its file: on a source backed by files only from the file\'s own place in the checkout, which is never rewritten; a database-only source takes it by import. Pages at or under 1 MiB are stored exactly as before. `gbrain config set pages.segmented_storage off` stores new pages inline up to 24 MiB again; pages already stored in segments stay readable. The writer hold now counts any gbrain older than this release, v0.60.290.0 included (its withdrawal mirror leaves a large page\'s file unchanged and its search build can overlap another\'s): while one wrote in the last 7 days, new pages stay inline and doctor `segmented_storage` names the host to upgrade.' },{ since: 'TBD', text: 'With `pages.segmented_storage` on, a withdrawal (`forget`, `forget_fact`, `purge_fact`) now rewrites the canonical file of a page stored in segments on a source backed by files, as it rewrites an inline page\'s: the file loses the withdrawn or purged row, its bytes are those `gbrain export` writes for the page, and the withdrawal\'s Git effect commits it. The file is streamed from the segments into its staging file one segment at a time, and its recovery record names that staging file by path and SHA-256 instead of holding the file; the file\'s prior bytes are read in pieces too. A streamed staging file (this mirror\'s, or `restore_page`\'s for a page over 24 MiB) is written under an in-progress name and renamed once complete, so one a crash cut short is discarded and written again instead of blocking the source\'s worktree with `unexpected_staging_bytes`. Before, the withdrawal-mirror and Git effects passed such a page by (`skipped` reason `page_body_segmented`) and its file kept the withdrawn text. The content gate\'s markers (`embed_skip`, `content_flag`, `quarantine`), which the database stores and the file does not, are now set aside when a page stored in segments is compared with its file, as they are for an inline page; before, any rewrite of a marked page\'s file (a withdrawal, delete, restore or tag change) was skipped or refused as `file_database_drift`.' },+ { since: 'TBD', text: 'A page stored in segments whose facts fence is longer than a segment (so it crosses a forced cut) is now read whole by every trusted reader once its source has a withdrawal: `gbrain export`, the withdrawal mirror and Git walk, the file drift check and the derived passes join the fence\'s segments (up to 8 MiB) and apply the withdrawals to the joined fence, as withdrawal discovery and the purge rewrite already did. Before, they refused with `page_projection_stale`, so a purge committed but its withdrawal mirror failed five times and parked with the purged row still in the canonical file. A fence longer than 8 MiB is recorded as a skipped target (reason `page_body_segmented`) by the mirror and Git walk instead of parking them. A withdrawal mirror whose staging file cannot be written (an I/O error such as EIO or ENOSPC) while the canonical file is unchanged now releases its recovery record and reserved capacity, so other writes and effects on the source\'s worktree proceed and the mirror retries and parks after its attempts like any failed mirror; before, the record held every write on the worktree and the mirror retried every 30 seconds without ever parking. The mirror now renders a segmented page\'s file only when the file exists to be rewritten, the Git walk no longer renders it at all, and both renew their effect claim while they stream the file.' },{ since: 'TBD', text: 'A managed write whose statements the database ends with a statement timeout or cancel (SQLSTATE 57014, at preparation or inside its publication transaction) now counts each such interruption against `persistence.max_preparation_attempts` (default 2), together with preparations cut off at their deadline, and at the limit ends `failed` with `write_interrupted` (the receipt names the attempts, the limit and the SQLSTATE; a worktree-backed write restores its file first) instead of being released as `database_contention` and prepared again without limit. A single interruption still re-prepares and commits; a lock timeout, serialization failure or deadlock (contention with other writers), a dropped connection or a restarting database is never counted. A foreground write needs a new `request_id`; a managed sync re-freezes the file in place, and a run that stops on it is resumable (`gbrain sync status` shows class `connection`, safe action `retry`, no person needed; a rerun on the same entry ending it again names the read-only `gbrain sources writer status`). `persistence.preparation_deadlines false` turns the counting off with the deadlines.' },{ since: 'TBD', text: 'Upgrading builds the index `ingest_log_marked_idx` (migration v257): on Postgres online (`CREATE INDEX CONCURRENTLY`; reads and writes go on while it builds), on PGLite as a plain build that holds writes until it ends. It took 0.4 s for 1M `ingest_log` rows on Postgres and 0.5 s on PGLite. The segmented storage writer hold now judges every recent import, sync or connector run and resident process by its version, including those of a gbrain that already records reading segmented pages (v0.60.290.0), and the index keeps that read to the last 7 days of the log: 600 buffers on a 1M-row log, where a scan reads the whole table.' },];diff --git a/src/core/page-body/read-range.ts b/src/core/page-body/read-range.tsindex fa34818a45..7c9278f0ec 100644--- a/src/core/page-body/read-range.ts+++ b/src/core/page-body/read-range.ts@@ -35,9 +35,11 @@ import { TIMELINE_SEPARATOR } from '../page-window/document.ts';import { sanitizeRemoteBody } from '../remote-body.ts';import { credentialSafeProjection } from '../credential-projection.ts';import { loadFenceChunkOverlay, markFenceChunk, renderFenceLowTier, type FenceChunkOverlay, type FenceLowTierRow } from '../eligibility/fence-overlay.ts';-import { withdrawalFenceBlocks } from '../facts/withdrawal-overlay.ts';+import { partialFenceRuns, withdrawalFenceBlocks } from '../facts/withdrawal-overlay.ts';import { assertRowsTile, generationBodyBytes } from './body-tiling.ts';-import { readBodyLedger, overlaySegmentText, type BodyLedger } from './segment-ledger.ts';+import { readEntryState } from './entry-state.ts';+import { SEGMENT_MAX_BYTES } from './limits.ts';+import { ledgerApplies, readBodyLedger, overlaySegmentText, type BodyLedger } from './segment-ledger.ts';import { regionTrust, SEGMENTER_VERSION, type FactsSlot, type OutlineHeading, type StoredRegion } from './segmenter.ts';import { overlaidPieces, projectionStaleError, projectSegment, type ProjectedPiece, type SegmentProjection } from './segment-projection.ts';import type { BodyRegion, JsonObject } from './types.ts';@@ -373,15 +375,47 @@ export interface TrustedSegment {pieces: ProjectedPiece[];}+/** The longest run of segments joined across forced cuts that a pass holds as one string. */+export const BLOCK_MAX_BYTES = 8 * SEGMENT_MAX_BYTES;++/** `page_body_segmented`: a run a derived pass must read whole is over BLOCK_MAX_BYTES. */+export function blockTooLargeError(slug: string, sourceId: string, bytes: number) {+ return opError('page_body_segmented',+ `Page ${slug} (source ${sourceId}) has a ${bytes}-byte run a derived pass must read whole (a line or fence longer than a segment), over its ${BLOCK_MAX_BYTES}-byte bound. Nothing was derived from it.`,+ 'Break the long line or fence into shorter lines and write the page again.');+}++/** A facts fence block opened in `text` (a segment entered outside one when not `entryOpen`) is still open at its end. */+const fenceRunsOn = (text: string, entryOpen: boolean) => partialFenceRuns(text, entryOpen).tail < text.length;+/*** The trusted body of `rows` (rows of `body`, in order), one segment at a time: what readBodyRange's trusted stored read- * cuts. `stop` is called before each segment text is read; it throws to end the read there.+ * cuts. Under a ledger that applies, a facts fence block a forced cut splits cannot be overlaid from one segment, so the+ * segments it spans are joined (as withdrawal discovery and rewriteLiveSegmentedFences join them), overlaid whole and+ * yielded as one segment covering their rows; a join over BLOCK_MAX_BYTES refuses with `page_body_segmented`. A read+ * that starts inside such a block (a range after its start) still refuses with `page_projection_stale`.+ * `stop` is called before each segment text is read; it throws to end the read there.*/export async function* trustedSegments(engine: BrainEngine, body: SegmentedBody, rows: readonly BodyRow[], stop?: () => void): AsyncIterable<TrustedSegment> {+ const join = ledgerApplies(body.ledger);+ let held: LoadedSegment[] = [];+ const emit = async (segs: LoadedSegment[]): Promise<TrustedSegment> => {+ const first = segs[0]!;+ const bytes = segs.length === 1 ? first.bytes : Buffer.concat(segs.map(seg => seg.bytes));+ const row = segs.length === 1 ? first.row : { ...first.row, byteLen: bytes.length, lineCount: segs.reduce((n, seg) => n + seg.row.lineCount, 0) };+ const raw = utf8.decode(bytes);+ return { row, raw: bytes, entryState: first.entryState, pieces: overlaidPieces(raw, await overlaidText(engine, body, { ...first, row }, raw, 'trusted')) };+ };for await (const seg of loadSegments(engine, body, rows, stop)) {- const raw = utf8.decode(seg.bytes);- yield { row: seg.row, raw: seg.bytes, entryState: seg.entryState, pieces: overlaidPieces(raw, await overlaidText(engine, body, seg, raw, 'trusted')) };+ if (!join) { yield await emit([seg]); continue; }+ const text = utf8.decode(seg.bytes);+ if (!held.length && !fenceRunsOn(text, readEntryState(seg.entryState)?.withdrawal.open === true)) { yield await emit([seg]); continue; }+ held.push(seg);+ const bytes = held.reduce((n, s) => n + s.row.byteLen, 0);+ if (bytes > BLOCK_MAX_BYTES) throw blockTooLargeError(body.slug, body.sourceId, bytes);+ if (held.length > 1 && !fenceRunsOn(text, true)) { yield await emit(held); held = []; }}+ if (held.length) yield await emit(held);}export async function* readBodyRange(engine: BrainEngine, req: BodyRangeRequest): AsyncIterable<BodyRangePiece> {diff --git a/src/core/page-body/segment-blocks.ts b/src/core/page-body/segment-blocks.tsindex 05b1783fc9..6af2dd19b4 100644--- a/src/core/page-body/segment-blocks.ts+++ b/src/core/page-body/segment-blocks.ts@@ -16,13 +16,11 @@* ordinary short lines or dated bullets with no structural candidate are cut* only by force. A joined run longer than BLOCK_MAX_BYTES (a line or fence many* segments long) refuses with `page_body_segmented`; a facts fence crossing a- * forced cut while the source has withdrawals refuses with- * `page_projection_stale` (read-range.ts).+ * forced cut while the source has withdrawals is read joined across it, up to+ * the same bound (read-range.ts `trustedSegments`).*/import type { BrainEngine } from '../engine.ts';-import { opError } from '../ops/contract.ts';-import { SEGMENT_MAX_BYTES } from './limits.ts';-import { bodyRowWork, confirmBodyPin, openSegmentedBody, readBodyRange, trustedSegments, type BodyPin } from './read-range.ts';+import { BLOCK_MAX_BYTES, blockTooLargeError, bodyRowWork, confirmBodyPin, openSegmentedBody, readBodyRange, trustedSegments, type BodyPin } from './read-range.ts';import { ledgerApplies } from './segment-ledger.ts';import { cutBlocked, SEGMENTER_VERSION } from './segmenter.ts';import { assertGenerationTiles } from './body-tiling.ts';@@ -58,8 +56,7 @@ export const segmentedPassWork = { bytes: 0, blocks: 0, windows: 0, carry: 0, liconst utf8 = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true });-/** The longest run of segments joined across forced cuts that a pass holds as one string. */-export const BLOCK_MAX_BYTES = 8 * SEGMENT_MAX_BYTES;+export { BLOCK_MAX_BYTES, blockTooLargeError } from './read-range.ts';export interface BodyBlock {/** The block's region; null for the separator between two regions. */@@ -97,13 +94,6 @@ export class BodyReadStopped extends Error {}}-/** `page_body_segmented`: a run a derived pass must read whole is over BLOCK_MAX_BYTES. */-export function blockTooLargeError(slug: string, sourceId: string, bytes: number) {- return opError('page_body_segmented',- `Page ${slug} (source ${sourceId}) has a ${bytes}-byte run a derived pass must read whole (a line or fence longer than a segment), over its ${BLOCK_MAX_BYTES}-byte bound. Nothing was derived from it.`,- 'Break the long line or fence into shorter lines and write the page again.');-}-/*** Whether the segment after a forced cut starts a block: the cut fell after a `\n` (not inside a line longer than a* segment, not after a bare `\r`) and a structural cut before the segment's first line would have been alloweddiff --git a/src/core/page-body/segment-ledger.ts b/src/core/page-body/segment-ledger.tsindex 76c3625bf5..7cebadc866 100644--- a/src/core/page-body/segment-ledger.ts+++ b/src/core/page-body/segment-ledger.ts@@ -30,7 +30,8 @@ export function ledgerApplies(ledger: BodyLedger): boolean {* The segment's text after the page's withdrawal overlay. A fence block a* forced cut splits cannot be overlaid from one segment: with a ledger that* applies, the read view omits its runs here (`view: 'read'`, fail closed) and- * a trusted body read refuses with `page_projection_stale`.+ * a trusted body read refuses with `page_projection_stale` (read-range.ts+ * `trustedSegments` joins such a block's segments before overlaying them).*/export async function overlaySegmentText(engine: Pick<BrainEngine, 'executeRaw'>, ledger: BodyLedger,segment: { sourceId: string; byteStart: number; entryState: unknown }, raw: string, view: 'read' | 'trusted'): Promise<string> {diff --git a/src/core/persistence/effect-journal.ts b/src/core/persistence/effect-journal.tsindex e057227d6f..dda199abbe 100644--- a/src/core/persistence/effect-journal.ts+++ b/src/core/persistence/effect-journal.ts@@ -206,6 +206,29 @@ export async function releaseAbandonedClaims(engine: BrainEngine, processStartedreturn effects.length + requests.length;}+/** @internal Claim renewals made between the pieces of a segmented page's file (effectClaimKeeper), for the bounded-work test. Counts, not time. */+export const effectClaimWork = { renewals: 0 };++/**+ * Called between the pieces of a long read or write under a withdrawal-mirror or Git claim (a segmented page's file+ * rendered, staged or compared): renews the 2-minute claim once `intervalMs` has passed since the last renewal, also+ * while the mirror holds its recovery record, and refuses with `write_claim_lost` once the claim moved.+ */+export function effectClaimKeeper(engine: BrainEngine, effect: PersistenceEffect, intervalMs: number): () => Promise<void> {+ let last = performance.now();+ return async () => {+ if (performance.now() - last < intervalMs) return;+ last = performance.now();+ effectClaimWork.renewals++;+ const rows = await engine.executeRawDirect(`UPDATE persistence_effects SET claim_expires_at=now()+interval '2 minutes',updated_at=now()+ WHERE id=$1 AND execution_token=$2::uuid AND state='running' AND ${PERSISTENCE_PROTOCOL_PREDICATE} RETURNING id`, [effect.id, effect.execution_token]);+ if (rows.length !== 1) throw opError('write_claim_lost', 'The effect claim changed.',+ `Another worker took over this ${effect.kind} effect of source ${effect.source_id} (its claim expired or was reassigned), so this attempt stopped; the current holder finishes it. Inspect the owner's effects rather than retrying by hand.`,+ { fix: readFix(`Shows source ${effect.source_id}'s canonical owner with its blocking, retrying and parked effects, read-only.`,+ { argv: ['gbrain', 'sources', 'writer', 'status', '--source', effect.source_id, '--json'] }) });+ };+}+export async function renewPersistenceEffectClaim(engine: SqlEngine, effect: PersistenceEffect): Promise<boolean> {const rows = await engine.executeRaw(`UPDATE persistence_effects SET claim_expires_at=now()+interval '2 minutes',updated_at=now()WHERE id=$1 AND execution_token=$2::uuid AND state='running' AND recovery IS NULL AND ${PERSISTENCE_PROTOCOL_PREDICATE} RETURNING id`, [effect.id, effect.execution_token]);diff --git a/src/core/persistence/effect-recovery.ts b/src/core/persistence/effect-recovery.tsindex 486246181c..7ec115fbe5 100644--- a/src/core/persistence/effect-recovery.ts+++ b/src/core/persistence/effect-recovery.ts@@ -1,7 +1,7 @@import { chmodSync, existsSync } from 'node:fs';import { join, resolve } from 'node:path';import type { BrainEngine } from '../engine.ts';-import { opError } from '../ops/contract.ts';+import { OperationError, opError } from '../ops/contract.ts';import { readFix } from '../ops/op-fix.ts';import type { Action } from '../agent-output.ts';import { isWriteTargetContained } from '../path-confine.ts';@@ -115,7 +115,8 @@ function recordBelongs(record: EffectRecovery, effect: PersistenceEffect, bindin* no longer holds its prior bytes, a leaf already holds the stage's name (the transaction verifies or refuses it), the* record no longer belongs to the binding (the transaction refuses it) or the page moved on (the transaction clears it).*/-async function stageStreamedMirror(engine: BrainEngine, effect: PersistenceEffect, hostId: string, content?: StreamedFileContent): Promise<void> {+async function stageStreamedMirror(engine: BrainEngine, effect: PersistenceEffect, hostId: string, content?: StreamedFileContent,+ between?: () => Promise<void>): Promise<void> {const [row] = await engine.executeRaw<{ recovery: EffectRecovery | null }>('SELECT recovery FROM persistence_effects WHERE id=$1 AND execution_token=$2::uuid', [effect.id, effect.execution_token]);const record = row?.recovery;@@ -123,7 +124,7 @@ async function stageStreamedMirror(engine: BrainEngine, effect: PersistenceEffecif (!record || !stage || !recordBelongs(record, effect, await getWorktreeBinding(engine, effect.source_id, hostId))) return;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 () => {+ try { 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;@@ -131,23 +132,58 @@ async function stageStreamedMirror(engine: BrainEngine, effect: PersistenceEffecif (!file) {const snapshot = await engine.readPageSnapshot(record.slug, { sourceId: effect.source_id, includeDeleted: true });if (!snapshot || snapshot.page.id !== record.pageId || snapshot.revision !== record.revision) return;- file = await unreadPageFile(engine, snapshot);+ file = await unreadPageFile(engine, snapshot, between);}await stageStreamedContent(engine, record.path, file, stage, record.mode);- });+ }); } catch (error) {+ if (stagingReported(error)) await releaseUnstagedRecord(engine, effect, hostId, record).catch(() => undefined);+ throw error;+ }await faultPoint('effect_recovery:staged', detail);}+/**+ * The stage write ended with an error this process saw (a filesystem error such as EIO or ENOSPC, or a gbrain refusal),+ * not with its death: the writer removed its in-progress file, so nothing of the stage is on disk.+ */+function stagingReported(error: unknown): boolean {+ if (error instanceof OperationError) return true;+ const { code, syscall } = (error ?? {}) as { code?: unknown; syscall?: unknown };+ return typeof code === 'string' && typeof syscall === 'string';+}++/**+ * A version 2 record whose stage could not be written while the canonical file still holds its prior bytes protects+ * nothing: no file changed and no stage exists. It is cleared with its reserved capacity in one transaction, so the+ * worktree's other writes and effects are no longer held behind it and this effect retries (and parks) as any failed+ * mirror does. A record whose file moved, or whose stage exists, is kept for recovery, as it is when the release+ * itself fails (the staging error is the one reported).+ */+async function releaseUnstagedRecord(engine: BrainEngine, effect: PersistenceEffect, hostId: string, record: EffectRecovery): Promise<void> {+ const stage = record.staging?.publication;+ if (!stage || existsAt(stage.path) || persistenceFileHash(record.path) !== record.beforeHash) return;+ await engine.transaction(async tx => {+ await tx.executeRaw("SELECT set_config('synchronous_commit','on',true),set_config('lock_timeout','1s',true),set_config('statement_timeout','5s',true)");+ await guardEffectSource(tx, effect, hostId);+ await lockCounters(tx, ['brain', `worktree:${effect.worktree_id}`]);+ const current = await lockedEffect(tx, effect);+ if (digest(current.recovery) !== digest(record)) return;+ await clearRecovery(tx, current);+ });+}+/** Under the native lock: finish forward, never restore withdrawn bytes. */export async function recoverEffectPublication(engine: BrainEngine, effect: PersistenceEffect, hostId: string,- hooks: { boundary?: (name: 'before_mirror_file' | 'after_mirror_file' | 'before_mirror_commit') => Promise<void>; content?: StreamedFileContent } = {}): Promise<void> {+ hooks: { boundary?: (name: 'before_mirror_file' | 'after_mirror_file' | 'before_mirror_commit') => Promise<void>; content?: StreamedFileContent;+ /** Called between the pieces of a streamed stage (the effect's claim renewal). */+ between?: () => Promise<void> } = {}): Promise<void> {const releaseCapacity = tryAcquirePublicationCapacity(engine);if (!releaseCapacity) throw opError('writer_pool_capacity', 'Mirror recovery is waiting for publication capacity.',`Every publication slot of the writer pool is busy, so mirror recovery for source ${effect.source_id} has not started; the worker tries again once a slot frees. Nothing needs resubmitting.`,{ fix: effectStatusFix(effect) });try {if (effect.recovery) await upgradeRecoveryStaging(engine, 'persistence_effects', effect.id, effect.worktree_id!, 'forward');- await stageStreamedMirror(engine, effect, hostId, hooks.content);+ await stageStreamedMirror(engine, effect, hostId, hooks.content, hooks.between);await engine.transaction(async tx => {await tx.executeRaw("SELECT set_config('synchronous_commit','on',true),set_config('lock_timeout','1s',true),set_config('statement_timeout','5s',true)");const binding = await guardEffectSource(tx, effect, hostId);diff --git a/src/core/persistence/effects.ts b/src/core/persistence/effects.tsindex bfd6ae9004..5cd45409ae 100644--- a/src/core/persistence/effects.ts+++ b/src/core/persistence/effects.ts@@ -33,10 +33,10 @@ import { acquireWorktree, getWorktreeBinding, type WorktreeBinding } from './ownimport { persistenceFileHash, transientDatabaseFailure } from './coordinator.ts';import { sha256 } from './digest.ts';import { prepareFileTarget, unreadPageFile } from './page-prepare.ts';-import { isStreamedContent } from './large-file.ts';+import { isStreamedContent, type StreamedFileContent } from './large-file.ts';import { atomicStagingPath } from '../atomic-write.ts';import { isSourceDbOnlySlug } from './source-storage.ts';-import { advanceEffectCursor, claimCoalescedGitEffects, claimPersistenceEffect, completeEffect, failEffect, parkEffect, renewPersistenceEffectClaim, requeueEffect, retryEffect, singleFileGitEffect } from './effect-journal.ts';+import { advanceEffectCursor, claimCoalescedGitEffects, claimPersistenceEffect, completeEffect, effectClaimKeeper, failEffect, parkEffect, renewPersistenceEffectClaim, requeueEffect, retryEffect, singleFileGitEffect } from './effect-journal.ts';import { guardEffectSource, recoverEffectPublication, reserveEffectRecovery } from './effect-recovery.ts';import { commitGitTargets, DURABILITY_NOT_ENABLED, publishGitEffect, pushGitRoot } from './effect-git.ts';import { gitDurabilityPolicy } from './git-durability-policy.ts';@@ -171,6 +171,16 @@ function isFileDatabaseDrift(error: unknown): boolean {return error instanceof OperationError && error.code === 'source_changed' && error.detail === 'file_database_drift';}+/**+ * Why a mirror or Git walk passes a page by without writing its file: the file differs from the database, or a+ * segmented page's body holds a run it cannot read whole (a facts fence longer than BLOCK_MAX_BYTES across forced cuts,+ * `page_body_segmented`). The target is recorded as skipped with that reason; any other error retries and parks.+ */+function unmirrorable(error: unknown): SkippedTarget['reason'] | null {+ if (isFileDatabaseDrift(error)) return 'file_database_drift';+ return error instanceof OperationError && error.code === 'page_body_segmented' ? 'page_body_segmented' : null;+}+/** The target a failing attempt was working on; unset means the failure is effect-wide. */interface EffectAttempt { target?: string }@@ -182,19 +192,26 @@ async function mirrorPage(engine: BrainEngine, effect: PersistenceEffect, bindin`Source ${effect.source_id} was replaced after this withdrawal mirror was queued, so the effect ends without writing; the new source has its own effects. Check the owner if files still look stale.`,{ fix: effectStatusFix(effect) });if (isMetafilePage(snapshot)) { await materializeAndAdvance(engine, effect, snapshot, opts.hostId, 'metafile'); return; }- // A segmented page's file is streamed from its segments (unreadPageFile), never rendered as one string.- const content = isSegmentedPage(snapshot.page) ? await unreadPageFile(engine, snapshot) : serializePageToMarkdown(snapshot.page, snapshot.tags);+ // A segmented page's file is streamed from its segments (unreadPageFile), never rendered as one string, and only once+ // the page has a file to rewrite: its comparison reads the stored body, never the rendered file.+ const segmented = isSegmentedPage(snapshot.page);+ const keep = effectClaimKeeper(engine, effect, effectRenewalIntervalMs);let file: Awaited<ReturnType<typeof prepareFileTarget>>;+ let content: string | StreamedFileContent;try {- file = binding?.local_path ? await prepareFileTarget(engine, { ...effect, slug: snapshot.page.slug }, snapshot, content, opts.hostId, { allowMissing: true }) : undefined;+ file = binding?.local_path ? await prepareFileTarget(engine, { ...effect, slug: snapshot.page.slug }, snapshot,+ segmented ? null : serializePageToMarkdown(snapshot.page, snapshot.tags), opts.hostId, { allowMissing: true }) : undefined;+ if (!file || snapshot.page.deleted_at || !existsSync(file.path)) {+ // A withdrawal cannot resurrect a deleted or missing physical page.+ await materializeAndAdvance(engine, effect, snapshot, opts.hostId);+ return;+ }+ await keep();+ content = segmented ? await unreadPageFile(engine, snapshot, keep) : file.content as string;} catch (error) {- if (!isFileDatabaseDrift(error)) throw error;- await materializeAndAdvance(engine, effect, snapshot, opts.hostId, 'file_database_drift');- return;- }- if (!file || snapshot.page.deleted_at || !existsSync(file.path)) {- // A withdrawal cannot resurrect a deleted or missing physical page.- await materializeAndAdvance(engine, effect, snapshot, opts.hostId);+ const skipped = unmirrorable(error);+ if (!skipped) throw error;+ await materializeAndAdvance(engine, effect, snapshot, opts.hostId, skipped);return;}const target = { kind: 'withdrawal-mirror' as const, path: file.path, root: file.root, beforeHash: file.expectedBeforeHash ?? null,@@ -205,7 +222,7 @@ async function mirrorPage(engine: BrainEngine, effect: PersistenceEffect, bindinconst record: EffectRecovery = { ...target, version: 2, afterHash: content.hash, after: null,staging: { publication: { path: atomicStagingPath(file.path), hash: content.hash, bytes: content.bytes } } };await reserveEffectRecovery(engine, effect, record, Buffer.byteLength(JSON.stringify(record)) + content.bytes + 4096, opts.hostId);- await recoverEffectPublication(engine, effect, opts.hostId, { boundary: opts.boundary, content });+ await recoverEffectPublication(engine, effect, opts.hostId, { boundary: opts.boundary, content, between: keep });return;}const after = Buffer.from(content);@@ -266,12 +283,15 @@ async function gitPage(engine: BrainEngine, effect: PersistenceEffect, binding:if (isMetafilePage(snapshot)) { await skipTarget(engine, effect, snapshot, 'metafile'); return; }let file: Awaited<ReturnType<typeof prepareFileTarget>>;try {+ // Only the file's comparison with the stored page is needed here, so a segmented page's file is never rendered.file = await prepareFileTarget(engine, { ...effect, slug: snapshot.page.slug }, snapshot,- snapshot.page.deleted_at ? null : isSegmentedPage(snapshot.page) ? await unreadPageFile(engine, snapshot) : serializePageToMarkdown(snapshot.page, snapshot.tags),+ snapshot.page.deleted_at || isSegmentedPage(snapshot.page) ? null : serializePageToMarkdown(snapshot.page, snapshot.tags),opts.hostId, { allowMissing: true });+ await effectClaimKeeper(engine, effect, effectRenewalIntervalMs)();} catch (error) {- if (!isFileDatabaseDrift(error)) throw error;- await skipTarget(engine, effect, snapshot, 'file_database_drift');+ const skipped = unmirrorable(error);+ if (!skipped) throw error;+ await skipTarget(engine, effect, snapshot, skipped);return;}if (!file) throw opError('source_changed', 'The Git binding changed.',@@ -592,7 +612,10 @@ async function runEffectPass(engine: BrainEngine, config: GBrainConfig, opts: Ef// can provide that proof and no second process can steal this claim now.[claimed] = await engine.executeRaw<PersistenceEffect>(`UPDATE persistence_effects SET state='running',execution_token=$2::uuid,claim_expires_at=now()+interval '2 minutes',attempts=attempts+1,updated_at=now() WHERE id=$1 AND recovery IS NOT NULL AND ${PERSISTENCE_PROTOCOL_PREDICATE} RETURNING *`, [recovery.id, randomUUID()]);- if (claimed) { attempted++; touched.add(claimed.request_id); await recoverEffectPublication(engine, claimed, opts.hostId, opts); }+ if (claimed) {+ attempted++; touched.add(claimed.request_id);+ await recoverEffectPublication(engine, claimed, opts.hostId, { boundary: opts.boundary, between: effectClaimKeeper(engine, claimed, effectRenewalIntervalMs) });+ }} catch (error) { if (claimed) await recordFailure(engine, claimed, error); }finally { await lock.release(); }}diff --git a/src/core/persistence/large-file.ts b/src/core/persistence/large-file.tsindex 36adc48e5b..a43cf55831 100644--- a/src/core/persistence/large-file.ts+++ b/src/core/persistence/large-file.ts@@ -27,9 +27,10 @@ const PIECE_BYTES = SEGMENT_MAX_BYTES;/*** @internal Work the large-file path does, for the memory-bound tests: bytes read from canonical or staged files* (`bytesRead`), streamed into a staging file (`bytesWritten`) or copied by the kernel into a before stage- * (`bytesCopied`), and the largest single piece held (`largestPiece`, at most a segment). Counts, not time.+ * (`bytesCopied`), produced to measure a streamed file (`bytesMeasured`, also counted in `bytesRead`), and the largest+ * single piece held (`largestPiece`, at most a segment). Counts, not time.*/-export const largeFileWork = { bytesRead: 0, bytesWritten: 0, bytesCopied: 0, largestPiece: 0 };+export const largeFileWork = { bytesRead: 0, bytesWritten: 0, bytesCopied: 0, bytesMeasured: 0, largestPiece: 0 };function counted(bytes: number, field: 'bytesRead' | 'bytesWritten'): void {largeFileWork[field] += bytes;@@ -101,7 +102,7 @@ export class StreamedFileContent {static async measure(engine: BrainEngine, produce: (engine: BrainEngine) => AsyncIterable<string | Uint8Array>): Promise<StreamedFileContent> {const hash = createHash('sha256');let bytes = 0;- for await (const piece of pieces(produce(engine))) { counted(piece.length, 'bytesRead'); hash.update(piece); bytes += piece.length; }+ for await (const piece of pieces(produce(engine))) { counted(piece.length, 'bytesRead'); largeFileWork.bytesMeasured += piece.length; hash.update(piece); bytes += piece.length; }return new StreamedFileContent(bytes, hash.digest('hex'), produce);}pieces(engine: BrainEngine): AsyncIterable<Uint8Array> { return pieces(this.produce(engine)); }diff --git a/src/core/persistence/page-prepare.ts b/src/core/persistence/page-prepare.tsindex cd66ff96ac..450718cd90 100644--- a/src/core/persistence/page-prepare.ts+++ b/src/core/persistence/page-prepare.ts@@ -548,12 +548,14 @@ async function prepareUnreadRestore(engine: BrainEngine, row: WriteRequest, snap/*** serializePageToMarkdown's bytes for a page whose body was not read back, streamed from its segments by export's* serializer: measured here, produced again into the publication's staging file (large-file.ts), never concatenated.- * A withdrawal mirror of a segmented page (effects.ts, effect-recovery.ts) renders its file the same way.+ * A withdrawal mirror of a segmented page (effects.ts, effect-recovery.ts) renders its file the same way, with+ * `between` (its claim renewal) run after each piece each time the file is produced.*/-export async function unreadPageFile(engine: BrainEngine, snapshot: PageSnapshot): Promise<StreamedFileContent> {+export async function unreadPageFile(engine: BrainEngine, snapshot: PageSnapshot, between?: () => Promise<void>): Promise<StreamedFileContent> {const head = serializePageToMarkdown({ ...withoutBody(snapshot.page), compiled_truth: '', timeline: '' }, snapshot.tags).slice(0, -1);const ledger = snapshotLedger(snapshot);- return StreamedFileContent.measure(engine, exec => segmentedExportMarkdown(exec, snapshot.page, ledger, head));+ const produce = (exec: BrainEngine) => segmentedExportMarkdown(exec, snapshot.page, ledger, head);+ return StreamedFileContent.measure(engine, !between ? produce : async function* (exec) { for await (const piece of produce(exec)) { yield piece; await between(); } });}/** Work counters of segmented tag flips: `flips` applied, `hashStreams` content hashes recomputed over the segments. */diff --git a/test/large-pages/segmented-withdrawal-mirror.test.ts b/test/large-pages/segmented-withdrawal-mirror.test.tsindex 32a4a07e6a..3ecf146be9 100644--- a/test/large-pages/segmented-withdrawal-mirror.test.ts+++ b/test/large-pages/segmented-withdrawal-mirror.test.ts@@ -10,24 +10,34 @@* (`largeFileWork`), and the bytes it stages are exactly the file's. Its recovery record names the staged file by* path and digest instead of embedding it, and a mirror interrupted before or after writing that stage recovers* forward: the stage is written from the segments, or the written one renamed, exactly once.+ * A facts fence longer than a segment (split by forced cuts) is mirrored joined, after a source withdrawal applies. A+ * stage the filesystem refuses (EIO) leaves no record behind: other writes on the worktree proceed and the mirror+ * retries, then parks after its attempts. The mirror renders the file only when it has a file to rewrite, the Git+ * walk never renders it, and the claim is renewed between the pieces (`largeFileWork.bytesMeasured`,+ * `effectClaimWork.renewals`, counts not time).* 2. Fails when: the withdrawal-mirror effect skips a segmented page (`page_body_segmented`) and leaves the purged claim* on disk, the Git walk skips it, the mirror renders the body as one string (nothing staged in pieces), the record- * embeds the file or reserves it twice, or recovery cannot finish an interrupted mirror.+ * embeds the file or reserves it twice, or recovery cannot finish an interrupted mirror; a cross-cut fence parks the+ * mirror (`page_projection_stale`); a refused stage keeps its record (writes on the worktree stay pending and the+ * mirror never parks); the Git walk or a mirror of a missing file measures the file; no renewal happens mid-stream.* 3. PGLite always; PostgreSQL when DATABASE_URL is set (test/postgres-unit-arms.txt). The switch is off for the inline* 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.+ * and `effect_recovery:staged` seams (fault-points.ts) with a hook that throws once; the EIO at+ * `large_file:stage_streaming`.*/import { afterAll, beforeAll, describe, expect, spyOn, test } from 'bun:test';import { createHash, randomUUID } from 'node:crypto';import * as fs from 'node:fs';-import { existsSync, readdirSync, readFileSync, writeFileSync } from 'node:fs';+import { existsSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';import { basename, join } from 'node:path';import { exportBodyLedger, readExportPage, readExportWithdrawals, segmentedExportMarkdown } from '../../src/core/export-snapshot.ts';import { buildEmbedSkipMarker, EMBED_SKIP_KEY } from '../../src/core/embed-skip.ts';import { serializeMarkdown, slugStampedFrontmatter } from '../../src/core/markdown.ts';import { buildContentFlagMarker, CONTENT_FLAG_KEY } from '../../src/core/quarantine.ts';import { SEGMENT_MAX_BYTES } from '../../src/core/page-body/limits.ts';-import { runPersistenceEffects } from '../../src/core/persistence/effects.ts';+import { __setEffectRenewalIntervalForTests, runPersistenceEffects } from '../../src/core/persistence/effects.ts';+import { effectClaimWork } from '../../src/core/persistence/effect-journal.ts';+import { PARK_AFTER_FAILURES } from '../../src/core/persistence/effect-model.ts';import { installFaultHook } from '../../src/core/persistence/fault-points.ts';import { localHostId } from '../../src/core/persistence/identity.ts';import { largeFileWork } from '../../src/core/persistence/large-file.ts';@@ -52,6 +62,28 @@ const STREAM_CLAIM = 'Twin Example vault code is 2718';const PARTIAL_CLAIM = 'Twin Example vault code is 3141';/** The claim purged from a page the content gate marked in the database only. */const MARKED_CLAIM = 'Twin Example safe code is 6022';+/** A page whose one facts fence is longer than a segment, so the segmenter splits it with forced cuts. */+const CROSS_CUT = 'people/cuts-example';+const CROSS_CLAIM = 'Twin Example gate code is 4410';+const CROSS_KEPT = 'Routine note number 10999 about the weekly planning meeting';+/** The claims whose mirror stage the filesystem refuses (EIO) once, and on every attempt. */+const EIO_ONCE = 'Twin Example vault code is 5021';+const EIO_ALWAYS = 'Twin Example vault code is 5022';+const OTHER = 'people/oth-example';+/** The claim of the bounded-work mirror, and the page whose canonical file is gone before its purge (and its claim). */+const BOUND_CLAIM = 'Twin Example vault code is 7310';+const RENEW_CLAIM = 'Twin Example vault code is 7312';+const GONE = 'people/gone-example';+const GONE_CLAIM = 'Twin Example vault code is 7311';+const eio = () => Object.assign(new Error('EIO: i/o error, write'), { code: 'EIO', errno: -5, syscall: 'write' });+const factRow = (n: number, claim: string) => `| ${n} | ${claim} | fact | 1.0 | world | medium | 2026-01-01 | | chat | |`;+const crossCutPage = () => {+ const rows = Array.from({ length: 11_000 }, (_, i) => factRow(i + 1, `Routine note number ${i} about the weekly planning meeting`));+ rows.splice(5_500, 0, factRow(11_001, CROSS_CLAIM));+ return '---\ntype: person\ntitle: Twin Example\n---\n\n# Twin Example\n\nA page whose facts fence is longer than a segment.\n\n'+ + '<!--- gbrain:facts:begin -->\n| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |\n'+ + '|---|-------|------|------------|------------|------------|------------|-------------|--------|---------|\n' + rows.join('\n') + '\n<!--- gbrain:facts:end -->\n';+};const fileOf = (brain: TwinBrain, slug: string) => join(brain.root, slug + '.md');const sha = (bytes: Buffer) => createHash('sha256').update(bytes).digest('hex');@@ -255,6 +287,165 @@ for (const kind of testBackends()) {}, 600_000);});+ describe(kind + ': a withdrawal mirrors a segmented page whose facts fence crosses a forced cut', () => {+ let brain: TwinBrain;++ beforeAll(async () => {+ brain = await openTwinBrain(kind, [], async seed => { await seed.setSwitch(true); });+ expect(await brain.call('put_page', { slug: CROSS_CUT, content: crossCutPage() })).toMatchObject({ state: 'committed' });+ expect(await brain.storageOf(CROSS_CUT)).toBe('segmented');+ await settle(brain, kind);+ }, 600_000);++ afterAll(() => brain.close(), 120_000);++ test('purge_fact rewrites the file without the claim, the fence joined across the cut as discovery joins it', async () => {+ // The fence runs on across at least one forced cut (a facts slot that opens in one segment and closes in a later one).+ const [split] = await brain.engine.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM page_body_manifest m JOIN pages p ON p.id=m.page_id,+ jsonb_array_elements(m.facts_slots) s WHERE p.source_id=$1 AND p.slug=$2 AND m.gen_to IS NULL AND s ? 'open_start'`, [brain.sourceId, CROSS_CUT]);+ expect(split!.n).toBeGreaterThan(1);+ expect(readFileSync(fileOf(brain, CROSS_CUT), 'utf8')).toContain(CROSS_CLAIM);++ const receipt = await purge(brain, kind, CROSS_CUT, CROSS_CLAIM);+ expect(await effectsOf(brain, receipt.requestId)).toEqual(SETTLED);+ const file = readFileSync(fileOf(brain, CROSS_CUT));+ expect(file.toString('utf8')).not.toContain(CROSS_CLAIM);+ expect(file.toString('utf8')).toContain(CROSS_KEPT);+ expect(file.equals(await exported(brain, CROSS_CUT))).toBe(true);+ expect(stagingLeft(brain)).toEqual([]);+ }, 600_000);+ });++ describe(kind + ': a mirror stage the filesystem refuses holds nothing behind it', () => {+ let brain: TwinBrain;+ const mirrorOf = async (requestId: string) => (await brain.engine.executeRaw<{ state: string; error_code: string | null; recovering: boolean; data: any }>(+ `SELECT e.state, e.error_code, e.recovery IS NOT NULL AS recovering, e.data FROM persistence_effects e JOIN persistence_requests r ON r.id=e.request_id+ WHERE r.request_id=$1::uuid AND e.kind='withdrawal-mirror'`, [requestId]))[0]!;+ const reserved = async () => (await brain.engine.executeRaw<{ bytes: string }>('SELECT recovery_bytes::text AS bytes FROM persistence_counters')).map(row => Number(row.bytes));+ const pass = () => withEnv(brain.env(), async () => {+ await brain.engine.executeRaw(`UPDATE persistence_effects SET next_attempt_at=now() WHERE source_id=$1 AND state='queued'`, [brain.sourceId]);+ await runPersistenceEffects(brain.engine, { engine: kind, embedding_disabled: true } as never, { hostId: localHostId(), limit: 20 });+ });+ /** purge_fact committed; its effects are then run by `pass` only. */+ const submitPurge = async (claim: string) => {+ const [fact] = await brain.engine.executeRaw<{ id: number }>('SELECT id FROM facts WHERE source_id=$1 AND source_markdown_slug=$2 AND fact=$3', [brain.sourceId, SEGMENTED, claim]);+ const dry = await brain.call('purge_fact', { id: Number(fact!.id), dry_run: true }, SEGMENTED);+ const requestId = randomUUID();+ expect(await brain.call('purge_fact', { id: Number(fact!.id), confirm: dry.confirm_token, expected_revision: dry.expected_revision, request_id: requestId }, SEGMENTED))+ .toMatchObject({ state: 'committed' });+ return requestId;+ };++ beforeAll(async () => {+ brain = await openTwinBrain(kind, [], async seed => {+ await seed.setSwitch(true);+ await seed.put(SEGMENTED, 1_100_000);+ });+ await extract(brain, SEGMENTED, [EIO_ONCE, EIO_ALWAYS, KEPT]);+ expect(await brain.storageOf(SEGMENTED)).toBe('segmented');+ await settle(brain, kind);+ }, 600_000);++ afterAll(() => { installFaultHook(undefined); return brain.close(); }, 120_000);++ test('an EIO while staging is retried and the next attempt publishes', async () => {+ let refused = 0;+ installFaultHook(async point => { if (point === 'large_file:stage_streaming' && refused === 0) { refused++; throw eio(); } });+ let requestId = '';+ try {+ requestId = await submitPurge(EIO_ONCE);+ await settle(brain, kind);+ } finally { installFaultHook(undefined); }+ expect(refused).toBe(1);+ const file = readFileSync(fileOf(brain, SEGMENTED));+ expect(file.toString('utf8')).not.toContain(EIO_ONCE);+ expect(file.equals(await exported(brain, SEGMENTED))).toBe(true);+ expect(await effectsOf(brain, requestId)).toEqual(SETTLED);+ expect(await mirrorOf(requestId)).toMatchObject({ recovering: false });+ expect(await reserved()).toEqual((await reserved()).map(() => 0));+ expect(stagingLeft(brain)).toEqual([]);+ }, 600_000);++ test('a stage refused on every attempt parks the mirror after its attempts while other writes on the worktree proceed', async () => {+ const before = readFileSync(fileOf(brain, SEGMENTED));+ let refused = 0;+ installFaultHook(async point => { if (point === 'large_file:stage_streaming') { refused++; throw eio(); } });+ let requestId = '';+ try {+ requestId = await submitPurge(EIO_ALWAYS);+ await waitFor(async () => { await pass(); return refused >= 1; }, { timeoutMs: 60_000, intervalMs: 100, label: 'the first stage write refused' });+ // Another page of the same worktree is written while the mirror retries: the refused stage holds no record that blocks it.+ expect(await brain.call('put_page', { slug: OTHER, content: '---\ntype: person\ntitle: Other Example\n---\n\nWritten while a mirror retries.\n' }))+ .toMatchObject({ state: 'committed' });+ expect(readFileSync(fileOf(brain, OTHER), 'utf8')).toContain('Written while a mirror retries.');+ await waitFor(async () => { await pass(); return (await mirrorOf(requestId)).state === 'failed'; },+ { timeoutMs: 120_000, intervalMs: 100, label: 'the mirror parked' }).catch(() => undefined);+ } finally { installFaultHook(undefined); }+ expect(await mirrorOf(requestId)).toMatchObject({ state: 'failed', error_code: 'targets_parked', recovering: false,+ data: { parked: [{ slug: SEGMENTED, error_code: 'effect_unavailable' }] } });+ expect(refused).toBe(PARK_AFTER_FAILURES);+ expect(await reserved()).toEqual((await reserved()).map(() => 0));+ expect(readFileSync(fileOf(brain, SEGMENTED)).equals(before)).toBe(true);+ expect(stagingLeft(brain)).toEqual([]);+ }, 600_000);+ });++ describe(kind + ': the mirror and Git walk do only the work a target needs', () => {+ let brain: TwinBrain;+ let restoreRenewal: () => void = () => {};++ beforeAll(async () => {+ brain = await openTwinBrain(kind, [], async seed => {+ await seed.setSwitch(true);+ await seed.put(SEGMENTED, 1_100_000);+ await seed.put(GONE, 1_100_000);+ });+ await extract(brain, SEGMENTED, [BOUND_CLAIM, RENEW_CLAIM, KEPT]);+ await extract(brain, GONE, [GONE_CLAIM, KEPT]);+ expect([await brain.storageOf(SEGMENTED), await brain.storageOf(GONE)]).toEqual(['segmented', 'segmented']);+ await settle(brain, kind);+ }, 600_000);++ afterAll(() => { restoreRenewal(); return brain.close(); }, 120_000);++ test('the file is measured once, by the mirror; the Git walk only compares it', async () => {+ resetWork();+ const receipt = await purge(brain, kind, SEGMENTED, BOUND_CLAIM);+ const work = { ...largeFileWork };+ const file = readFileSync(fileOf(brain, SEGMENTED));+ expect(await effectsOf(brain, receipt.requestId)).toEqual(SETTLED);+ expect(file.toString('utf8')).not.toContain(BOUND_CLAIM);+ expect(file.equals(await exported(brain, SEGMENTED))).toBe(true);+ expect(work.bytesMeasured).toBe(file.length);+ expect(work.bytesWritten).toBe(file.length);+ }, 600_000);++ test('the mirror renews its claim between the pieces of the file it measures and stages', async () => {+ // Interval 0: every piece renews, so the count is a function of the pieces, not of time.+ restoreRenewal = __setEffectRenewalIntervalForTests(0);+ effectClaimWork.renewals = 0;+ let receipt: Awaited<ReturnType<typeof purge>>;+ try { receipt = await purge(brain, kind, SEGMENTED, RENEW_CLAIM); } finally { restoreRenewal(); }+ const renewals = effectClaimWork.renewals;+ expect(await effectsOf(brain, receipt!.requestId)).toEqual(SETTLED);+ expect(readFileSync(fileOf(brain, SEGMENTED), 'utf8')).not.toContain(RENEW_CLAIM);+ // At least one renewal per segment of each pass over the file: once measured, once staged.+ const [segments] = await brain.engine.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM page_body_manifest m JOIN pages p ON p.id=m.page_id+ WHERE p.source_id=$1 AND p.slug=$2 AND m.gen_to IS NULL AND m.staging_id IS NULL`, [brain.sourceId, SEGMENTED]);+ expect(segments!.n).toBeGreaterThan(1);+ expect(renewals).toBeGreaterThanOrEqual(2 * segments!.n);+ }, 600_000);++ test('a page whose canonical file is gone is never rendered by its mirror', async () => {+ rmSync(fileOf(brain, GONE));+ resetWork();+ const receipt = await purge(brain, kind, GONE, GONE_CLAIM);+ expect(await effectsOf(brain, receipt.requestId)).toEqual(SETTLED);+ expect(existsSync(fileOf(brain, GONE))).toBe(false);+ expect(largeFileWork.bytesMeasured).toBe(0);+ }, 600_000);+ });+describe(kind + ': an interrupted streamed mirror recovers forward', () => {let brain: TwinBrain;