Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(large-pages): one 24 MiB fence bound everywhere, split facts markers, bounded file digest, renewals during comparison

garrytan40102f80fd7c
diff --git a/docs/architecture/key-files/core-services-2-continued.md b/docs/architecture/key-files/core-services-2-continued.md
index a782246bd1..a2b82775a3 100644
--- a/docs/architecture/key-files/core-services-2-continued.md
+++ b/docs/architecture/key-files/core-services-2-continued.md
@@ -23,7 +23,7 @@ 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` (`page-body/writer-floor.ts`: the `since` of the BEHAVIOR_CHANGES row with id `segmented_switch_on`, this build's VERSION while it is `TBD`, so the merge-slot stamp edits only that row) or unparsable, or when it lacks the segment-reader mark (migration v254: `admitter_segment_reader`, `consumer_segment_reader`, `persistence_consumers.segment_reader`, `ingest_log.writer_segment_reader`), because releases 0.60.252.0-0.60.262.0 have no segment readers and a version string cannot tell them apart. Not seen: an older binary's unmanaged single-page write, a run that dies before it logs, and read-only or export use. `pageRecoveryBytes` is the default `persistence.limits.worktree_recovery_bytes` (read by `persistence/limits.ts` `readJournalLimits` in its one config statement): twice the larger of the body the configured switch admits (`segmentedMaxBytes`, or `PAGE_MAX_BYTES` while off) and the largest page stored in segments (deleted pages included; one probe of `pages_segmented_body_bytes_idx`, v258) plus `RECOVERY_FILE_HEADROOM_BYTES` per copy, never below 256 MiB, because a restore reserves its file twice; it ignores the writer gate, and turning the switch off or lowering `pages.max_bytes` never strands a stored page. `readPageBodyPolicy` treats a failed read of the switch or `pages.max_bytes` as off, never as unset. Doctor `segmented_storage` reports a hold left only by this host's pre-upgrade writes, superseded by a later passing write of this host, as information with its clear time. Tests: `test/large-pages/segmented-switch.test.ts`, `test/large-pages/recovery-budget-default.test.ts`, `test/large-pages/recovery-budget-ceiling.slow.test.ts`.
-- `src/core/page-body/read-range.ts` + `segment-projection.ts` + `segment-ledger.ts` — Wave B PR 2 (spec 7.1, 7.3): the segment reader. `openSegmentedBody` reads a page's live manifest rows and its withdrawal ledger (`readBodyLedger`); `readBodyRange(engine, { pageId, space, start, end, audience, region?, body? })` streams pieces one segment text at a time, never the whole body. Remote reads and every projected-space read serve the read projection: `projectSegment` projects whole segments from their stored protected regions (takes, truncated tail and markers out, keys as the projection token, facts regions rendered world-only and credential-projected), after the withdrawal overlay (`overlaySegmentText`; a fence split by a forced cut is omitted for reads; 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/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 a segment ending inside a facts marker with the next, and overlays them whole, refusing `page_body_segmented` above `FENCE_MAX_BYTES` (limits.ts: counted from the begin marker through the end marker, the bound withdrawal discovery's `readStoredFence`, the purge rewrite and the file's overlaid digest share), 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` (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).
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 0f0cfbe08b..5e9a06bb78 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -891,7 +891,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;
// segmented_switch_on) is SEGMENTED_WRITER_FLOOR (page-body/writer-floor.ts).
{ since: 'TBD', text: 'Pages over 1 MiB are now stored in segments: `pages.segmented_storage` is on by default. Reading a window, outline or chunk context of a large page costs the size of the window, not the page, and a rewrite re-indexes only the segments that changed. A page can be up to 256 MiB on Postgres and 128 MiB on PGLite (`pages.max_bytes` lowers it). `put_page`, `put_pages` and `capture` content and `gbrain put` stdin stay limited to 24 MiB per call, so a larger page comes in by `gbrain import` or `gbrain sync` of its file: on a source backed by files only from the file\'s own place in the checkout, which is never rewritten; a database-only source takes it by import. Pages at or under 1 MiB are stored exactly as before. `gbrain config set pages.segmented_storage off` stores new pages inline up to 24 MiB again; pages already stored in segments stay readable. The writer hold now counts any gbrain older than this release, v0.60.290.0 included (its withdrawal mirror leaves a large page\'s file unchanged and its search build can overlap another\'s): while one wrote in the last 7 days, new pages stay inline and doctor `segmented_storage` names the host to upgrade.', id: 'segmented_switch_on' },
{ since: 'TBD', text: 'With `pages.segmented_storage` on, a withdrawal (`forget`, `forget_fact`, `purge_fact`) now rewrites the canonical file of a page stored in segments on a source backed by files, as it rewrites an inline page\'s: the file loses the withdrawn or purged row, its bytes are those `gbrain export` writes for the page, and the withdrawal\'s Git effect commits it. The file is streamed from the segments into its staging file one segment at a time, and its recovery record names that staging file by path and SHA-256 instead of holding the file; the file\'s prior bytes are read in pieces too. A streamed staging file (this mirror\'s, or `restore_page`\'s for a page over 24 MiB) is written under an in-progress name and renamed once complete, so one a crash cut short is discarded and written again instead of blocking the source\'s worktree with `unexpected_staging_bytes`. Before, the withdrawal-mirror and Git effects passed such a page by (`skipped` reason `page_body_segmented`) and its file kept the withdrawn text. The content gate\'s markers (`embed_skip`, `content_flag`, `quarantine`), which the database stores and the file does not, are now set aside when a page stored in segments is compared with its file, as they are for an inline page; before, any rewrite of a marked page\'s file (a withdrawal, delete, restore or tag change) was skipped or refused as `file_database_drift`.' },
- { since: 'TBD', text: 'A 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 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 and apply the withdrawals to the joined fence, as withdrawal discovery and the purge rewrite do. 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. Every one of them now reads a fence up to 24 MiB, counted from its begin marker through its end marker, and refuses a longer one with `page_body_segmented`: a purge in such a fence is refused before it commits, and a mirror or Git walk that meets one retries and parks, listed by writer status and doctor, instead of passing the page by. A purge or forget of a row in a fence whose begin or end marker a forced cut splits now commits and leaves the stored segments, the canonical file and its Git commit without the row; before, withdrawal discovery refused it with `withdrawal_provenance`. A withdrawal mirror whose staging file cannot be written (an I/O error such as EIO or ENOSPC) while the canonical file is unchanged and no part of the staging file is left on disk 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 or compare 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 holds the file and moves on (`gbrain sync status` lists the hold with class `page`, safe action `retry`, and the read-only `gbrain sources writer status` diagnosis), and `gbrain sources retry-held` re-admits it. A shared read of a group the database cancels charges no member, and the charge commits with the release of the claim, so a crash between them never counts an interruption twice. `persistence.preparation_deadlines false` turns the counting off with the deadlines.' },
{ since: 'TBD', text: 'Upgrading builds the index `ingest_log_marked_idx` (migration v257): on Postgres online (`CREATE INDEX CONCURRENTLY`; reads and writes go on while it builds), on PGLite as a plain build that holds writes until it ends. It took 0.4 s for 1M `ingest_log` rows on Postgres and 0.5 s on PGLite. The segmented storage writer hold now judges every recent import, sync or connector run and resident process by its version, including those of a gbrain that already records reading segmented pages (v0.60.290.0), and the index keeps that read to the last 7 days of the log: 600 buffers on a 1M-row log, where a scan reads the whole table.' },
{ since: 'TBD', text: 'Upgrading builds the index `pages_segmented_body_bytes_idx` (migration v258) over pages stored in segments: on Postgres online (`CREATE INDEX CONCURRENTLY`), on PGLite as a plain build that holds writes until it ends. With it, the default `persistence.limits.worktree_recovery_bytes` also leaves room for the largest page already stored in segments, deleted pages included: turning `pages.segmented_storage` off or lowering `pages.max_bytes` no longer makes a delete, restore or withdrawal mirror of such a page fail with `request_too_large` (a withdrawn row stayed in its file). A value you set is kept, and a request it cannot hold is refused with `request_too_large` naming both recovery budgets and the bytes it needed.' },
diff --git a/src/core/facts/withdrawal-discovery.ts b/src/core/facts/withdrawal-discovery.ts
index 95f122c6be..24d37bf8d6 100644
--- a/src/core/facts/withdrawal-discovery.ts
+++ b/src/core/facts/withdrawal-discovery.ts
@@ -3,8 +3,9 @@ import { OperationError } from '../ops/contract.ts';
import { getCode } from '../retry-matcher.ts';
import { parseRowCells, isSeparatorRow, stripStrikethrough } from '../fence-shared.ts';
import { withdrawalFenceBlocks, ambiguousWithdrawalFenceSegments } from './withdrawal-overlay.ts';
-import { PAGE_MAX_BYTES } from '../page-size-policy.ts';
-import { pageBodySegmentedError } from '../page-body/page-shape.ts';
+import { fenceTooLargeError, readStoredFence } from '../page-body/read-range.ts';
+import { FENCE_MAX_BYTES } from '../page-body/limits.ts';
+import type { BodyRegion } from '../page-body/types.ts';
export const WITHDRAWAL_LIMITS = { targets: 256, targetBytes: 1024 * 1024, scanMs: 10_000, batch: 128 } as const;
export interface WithdrawalTarget { slug: string; page_id: number; revision: string }
@@ -48,11 +49,13 @@ function fenceClaims(id: number, slug: string, body: string): Array<{ id: number
/**
* Wave B (spec 11): every live facts fence of a segmented page that a forced
- * cut split (its slots carry `open_start`), joined from its slots' bytes in
- * segment order and kept when its lowered text holds every token of a claim
- * keyed to the page. Private rows never reach chunks, so this is the only
- * scan that sees them. A fence above PAGE_MAX_BYTES is refused, never
- * skipped. Keyset by (page, region, fence start); one fence in memory.
+ * cut split (its slots carry `open_start`), read from its begin marker through
+ * its end marker across the cuts (readStoredFence: a cut inside either marker
+ * leaves part of it outside every slot) and kept when its lowered text holds
+ * every token of a claim keyed to the page. Private rows never reach chunks, so
+ * this is the only scan that sees them. A fence above FENCE_MAX_BYTES is
+ * refused, never skipped. Keyset by (page, region, fence start); one fence in
+ * memory.
*/
async function* splitFactsFences(engine: BrainEngine, sourceId: string, keyed: readonly KeyedClaim[], subjects: string[] | null, deadline: number):
AsyncIterable<{ id: number; slug: string; fence: string }> {
@@ -67,11 +70,10 @@ async function* splitFactsFences(engine: BrainEngine, sourceId: string, keyed: r
[sourceId, subjects, after[0], after[1], after[2], WITHDRAWAL_LIMITS.batch]);
for (const f of fences) {
if (performance.now() > deadline) refuse();
- if (Number(f.bytes) > PAGE_MAX_BYTES) throw pageBodySegmentedError({ slug: f.slug, source_id: sourceId }, 'withdrawal discovery of a fence larger than the single-string ceiling');
- const parts = await engine.executeRaw<{ part: Uint8Array }>(`SELECT substring(t.body from (s->>'start')::int + 1 for (s->>'end')::int - (s->>'start')::int) AS part
- FROM page_body_manifest m CROSS JOIN LATERAL jsonb_array_elements(m.facts_slots) s JOIN page_segment_texts t ON t.source_id=m.source_id AND t.sha256=m.sha256
- WHERE m.page_id=$1 AND m.region=$2 AND m.gen_to IS NULL AND m.staging_id IS NULL AND (s->>'open_start')::bigint=$3::bigint ORDER BY m.seq`, [f.page_id, f.region, f.open_start]);
- const fence = Buffer.concat(parts.map(p => Buffer.from(p.part))).toString('utf8');
+ // Its slots hold part of the fence (a cut inside a marker leaves the marker's bytes outside them), so slots over the
+ // bound prove the fence is, before any of it is read.
+ if (Number(f.bytes) > FENCE_MAX_BYTES) throw fenceTooLargeError(f.slug, sourceId, Number(f.bytes));
+ const fence = await readStoredFence(engine, { id: Number(f.page_id), slug: f.slug, sourceId }, f.region as BodyRegion, Number(f.open_start));
const lowered = fence.toLowerCase();
if (keyed.some(k => (k.subject === '*' || k.subject === f.slug) && (k.norm ?? '').split(' ').filter(Boolean).every(token => lowered.includes(token)))) {
yield { id: Number(f.page_id), slug: f.slug, fence };
diff --git a/src/core/page-body/body-digests.ts b/src/core/page-body/body-digests.ts
index e8297f44be..2bd2c48168 100644
--- a/src/core/page-body/body-digests.ts
+++ b/src/core/page-body/body-digests.ts
@@ -13,9 +13,10 @@ import type { BrainEngine } from '../engine.ts';
import type { ParseOpts } from '../markdown.ts';
import { BodyScanner, type BodyPiece, type BodyScan } from './body-scan.ts';
import { openSegmentedBody, readBodyRange, type BodyLedger } from './read-range.ts';
-import { BLOCK_MAX_BYTES, readGarbageCollector } from './segment-blocks.ts';
+import { readGarbageCollector } from './segment-blocks.ts';
import { partialFenceRuns } from '../facts/withdrawal-overlay.ts';
-import { SEGMENT_MAX_BYTES } from './limits.ts';
+import { FACTS_FENCE_BEGIN, FACTS_FENCE_END } from '../facts-fence.ts';
+import { FENCE_MAX_BYTES, SEGMENT_MAX_BYTES } from './limits.ts';
import type { BodyRegion } from './types.ts';
const FACTS_MARKER = Buffer.from('gbrain:facts:begin', 'utf8');
@@ -24,9 +25,10 @@ const REGIONS: readonly BodyRegion[] = ['truth', 'timeline'];
/**
* @internal Work a digest comparison does, for the memory-bound tests: file bytes the scan and the region hashes read
* (`fileBytes`), stored bytes hashed (`segmentBytes`), and the largest single piece handed to a scan or hash
- * (`largestPiece`, at most a segment). Counts, not time.
+ * (`largestPiece`, at most a segment), and the longest file text a withdrawal overlay holds at once (`largestHeld`, UTF-16
+ * units: the text waiting for a fence block to close, or handed to the overlay). Counts, not time.
*/
-export const bodyDigestWork = { fileBytes: 0, segmentBytes: 0, largestPiece: 0 };
+export const bodyDigestWork = { fileBytes: 0, segmentBytes: 0, largestPiece: 0, largestHeld: 0 };
/** SHA-256 (hex) of each region's UTF-8 bytes. */
export type RegionDigests = Record<BodyRegion, string>;
@@ -82,15 +84,21 @@ export function fileBodyDigests(bytes: ByteSource, reading: FileReading, filePat
regions: { truth: scan.truth, timeline: scan.timeline } };
}
+/** A fence opener keeps at most this much of its line before it (UTF-16 units): the stored side overlays a segment, so it sees at most that much. */
+const OPENER_CONTEXT = SEGMENT_MAX_BYTES;
+const MARKER_KEEP = Math.max(FACTS_FENCE_BEGIN.length, FACTS_FENCE_END.length) - 1;
+
/**
* The digest of each file region after `overlay` (the withdrawal overlay of one complete text, overlayCanonicalBodies),
- * applied as the stored side applies it per segment: to complete lines, each chunk ending outside every facts fence
- * block (partialFenceRuns), so a block is always overlaid whole. Text before the first fence marker of a chunk is
- * hashed as read. A block that stays open past BLOCK_MAX_BYTES (a fence the stored side can only hold split across
- * forced cuts) calls `refuse`: such a body is not overlaid in pieces.
+ * applied as the stored side applies it: each chunk handed to it ends outside every facts fence block (partialFenceRuns)
+ * and before any marker the next bytes could complete, so a block is always overlaid whole. The text held is the open
+ * block, with at most OPENER_CONTEXT of the line before its opener, or that much of the current line when no block is
+ * open, plus the piece just read: never a whole long line. A block longer than FENCE_MAX_BYTES, counted from its begin
+ * marker, calls `refuse` with its length so far before anything more is held or overlaid. `between` runs after each
+ * piece (an effect's claim renewal).
*/
export async function overlaidFileBodyDigests(bytes: ByteSource, reading: FileReading, regions: Record<BodyRegion, readonly BodyPiece[]>,
- overlay: (text: string) => Promise<string>, refuse: () => Error): Promise<RegionDigests> {
+ overlay: (text: string) => Promise<string>, refuse: (bytes: number) => Error, between?: () => Promise<void>): Promise<RegionDigests> {
const digests = {} as RegionDigests;
for (const region of REGIONS) {
const hash = createHash('sha256');
@@ -98,35 +106,50 @@ export async function overlaidFileBodyDigests(bytes: ByteSource, reading: FileRe
const buffer = Buffer.from(text, 'utf8');
for (let at = 0; at < buffer.length; at += SEGMENT_MAX_BYTES) hash.update(count(buffer.subarray(at, at + SEGMENT_MAX_BYTES), 'fileBytes'));
};
- const emit = async (text: string) => update(text.includes('gbrain:facts:begin') ? await overlay(text) : text);
+ const emit = async (text: string) => {
+ if (text.length > bodyDigestWork.largestHeld) bodyDigestWork.largestHeld = text.length;
+ update(text.includes('gbrain:facts:begin') ? await overlay(text) : text);
+ };
const decoder = new TextDecoder('utf-8');
let pending = '';
- const drain = async () => {
- const end = pending.lastIndexOf('\n') + 1;
- if (end === 0) return;
- const complete = pending.slice(0, end);
- const { tail } = partialFenceRuns(complete, false);
- const cut = tail === complete.length ? end : complete.lastIndexOf('\n', tail - 1) + 1;
- if (cut > 0) await emit(complete.slice(0, cut));
+ // The start of the line holding `at`, at most OPENER_CONTEXT before it, never inside a block that ends before `at`.
+ const keepFrom = (at: number) => {
+ const lastEnd = pending.lastIndexOf(FACTS_FENCE_END, at - FACTS_FENCE_END.length);
+ return Math.max(pending.lastIndexOf('\n', at - 1) + 1, at - OPENER_CONTEXT, lastEnd === -1 ? 0 : lastEnd + FACTS_FENCE_END.length);
+ };
+ const drain = async (final: boolean) => {
+ const { tail } = partialFenceRuns(pending, false);
+ if (tail < pending.length) {
+ const fence = Buffer.byteLength(pending.slice(tail), 'utf8');
+ if (fence > FENCE_MAX_BYTES) throw refuse(fence);
+ }
+ const lastEnd = pending.lastIndexOf(FACTS_FENCE_END);
+ const closedAt = Math.max(0, pending.length - MARKER_KEEP, lastEnd === -1 ? 0 : lastEnd + FACTS_FENCE_END.length);
+ const cut = final ? pending.length : keepFrom(tail < pending.length ? tail : closedAt);
+ if (cut > 0) await emit(pending.slice(0, cut));
pending = pending.slice(cut);
- if (Buffer.byteLength(pending, 'utf8') > BLOCK_MAX_BYTES) throw refuse();
};
for (const piece of regions[region]) {
const parts = 'text' in piece ? [Buffer.from(piece.text, 'utf8')] : virtualSlice(bytes, reading, piece.start, piece.end);
for (const part of parts) {
pending += decoder.decode(count(part, 'fileBytes'), { stream: true });
- await drain();
+ if (pending.length > bodyDigestWork.largestHeld) bodyDigestWork.largestHeld = pending.length;
+ await drain(false);
+ await between?.();
}
}
pending += decoder.decode();
- if (pending) await emit(pending);
+ await drain(true);
digests[region] = hash.digest('hex');
}
return digests;
}
-/** The digest of each region of a segmented page's trusted stored body under `ledger` (the snapshot's withdrawals), one segment at a time. */
-export async function storedBodyDigests(engine: BrainEngine, pageId: number, ledger: BodyLedger): Promise<RegionDigests> {
+/**
+ * The digest of each region of a segmented page's trusted stored body under `ledger` (the snapshot's withdrawals), one
+ * segment (or one joined fence) at a time; `between` runs after each piece (an effect's claim renewal).
+ */
+export async function storedBodyDigests(engine: BrainEngine, pageId: number, ledger: BodyLedger, between?: () => Promise<void>): Promise<RegionDigests> {
const body = await openSegmentedBody(engine, { pageId, ledger });
const collect = readGarbageCollector();
const digests = {} as RegionDigests;
@@ -135,6 +158,7 @@ export async function storedBodyDigests(engine: BrainEngine, pageId: number, led
for await (const piece of readBodyRange(engine, { pageId, space: 'stored', start: 0, end: Infinity, audience: 'trusted', region, body })) {
hash.update(count(piece.bytes, 'segmentBytes'));
collect(piece.bytes.length);
+ await between?.();
}
digests[region] = hash.digest('hex');
}
diff --git a/src/core/page-body/limits.ts b/src/core/page-body/limits.ts
index 7bf6b80202..0f0df210ea 100644
--- a/src/core/page-body/limits.ts
+++ b/src/core/page-body/limits.ts
@@ -36,6 +36,13 @@ export const SEGMENT_TARGET_BYTES = 256 * 1024;
export const SEGMENT_RANK4_BYTES = 384 * 1024;
/** Hard bound, matched by the `page_segment_texts.byte_len` CHECK. */
export const SEGMENT_MAX_BYTES = 1024 * 1024;
+/**
+ * The longest facts fence a withdrawal holds as one string, counted from its begin marker through its end marker
+ * (UTF-8 bytes): withdrawal discovery, the purge and forget rewrite of the segments (segment-rewrite.ts), the trusted
+ * read's join (read-range.ts `trustedSegments`) and the canonical file's overlaid digest (body-digests.ts) all count a
+ * fence this way and refuse a longer one with `page_body_segmented` (`fenceTooLargeError`).
+ */
+export const FENCE_MAX_BYTES = PAGE_MAX_BYTES;
/** Raw prefix of each region kept on the page row (`truth_lead`, `timeline_lead`), equal to Wave A's bounded prefix. */
export const BODY_LEAD_BYTES = 64 * 1024;
diff --git a/src/core/page-body/read-range.ts b/src/core/page-body/read-range.ts
index 7c9278f0ec..864951fcac 100644
--- a/src/core/page-body/read-range.ts
+++ b/src/core/page-body/read-range.ts
@@ -36,9 +36,10 @@ 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 { partialFenceRuns, withdrawalFenceBlocks } from '../facts/withdrawal-overlay.ts';
+import { FACTS_FENCE_BEGIN, FACTS_FENCE_END } from '../facts-fence.ts';
import { assertRowsTile, generationBodyBytes } from './body-tiling.ts';
import { readEntryState } from './entry-state.ts';
-import { SEGMENT_MAX_BYTES } from './limits.ts';
+import { FENCE_MAX_BYTES, 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';
@@ -385,20 +386,61 @@ export function blockTooLargeError(slug: string, sourceId: string, bytes: number
'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;
+/** `page_body_segmented`: a facts fence a withdrawal must read whole is longer than FENCE_MAX_BYTES (limits.ts). */
+export function fenceTooLargeError(slug: string, sourceId: string, bytes: number) {
+ return opError('page_body_segmented',
+ `Page ${slug} (source ${sourceId}) has a facts fence of at least ${bytes} bytes, over the ${FENCE_MAX_BYTES}-byte bound a withdrawal reads a fence whole within. Nothing was read from it.`,
+ 'Split the facts fence into fences under the bound and write the page again.');
+}
+
+const MARKER_CARRY_MAX = Math.max(FACTS_FENCE_BEGIN.length, FACTS_FENCE_END.length) - 1;
+/** The end of `text` that begins a facts marker without completing it: the bytes of a marker a forced cut splits. */
+export function markerCarry(text: string): string {
+ for (let k = Math.min(text.length, MARKER_CARRY_MAX); k > 0; k--) {
+ const tail = text.slice(-k);
+ if (FACTS_FENCE_BEGIN.startsWith(tail) || FACTS_FENCE_END.startsWith(tail)) return tail;
+ }
+ return '';
+}
+
+/**
+ * The stored text of the facts fence a forced cut splits that begins at stored byte `openStart` of `region` (its slots'
+ * `open_start`): read from the live segments one at a time, from the one holding its opener (one that records no slot
+ * of it when the cut fell inside the opener) through its end marker, or to the region's end for a fence that never
+ * closes. A fence longer than FENCE_MAX_BYTES, counted from its begin marker, refuses before more is read.
+ */
+export async function readStoredFence(engine: Pick<BrainEngine, 'readManifest' | 'readSegmentTexts'>, page: { id: number; slug: string; sourceId: string }, region: BodyRegion, openStart: number): Promise<string> {
+ const end = Buffer.from(FACTS_FENCE_END, 'utf8');
+ const parts: Buffer[] = [];
+ let bytes = 0;
+ for (const row of await engine.readManifest(page.id, { region })) {
+ if (row.byteStart + row.byteLen <= openStart) continue;
+ const sha = Buffer.from(row.sha256).toString('hex');
+ const text = (await engine.readSegmentTexts(page.sourceId, [row.sha256])).get(sha);
+ if (!text) throw new Error(`Segment text ${sha} of page ${page.id} is missing.`);
+ const part = Buffer.from(text).subarray(Math.max(0, openStart - row.byteStart));
+ const seam = Buffer.concat([...parts.slice(-1).map(p => p.subarray(Math.max(0, p.length - end.length + 1))), part]);
+ const at = seam.indexOf(end);
+ const seamStart = bytes - (seam.length - part.length);
+ parts.push(part);
+ bytes += part.length;
+ const fenceBytes = at === -1 ? bytes : seamStart + at + end.length;
+ if (fenceBytes > FENCE_MAX_BYTES) throw fenceTooLargeError(page.slug, page.sourceId, fenceBytes);
+ if (at !== -1) return Buffer.concat(parts).subarray(0, fenceBytes).toString('utf8');
+ }
+ return Buffer.concat(parts).toString('utf8');
+}
/**
* The trusted body of `rows` (rows of `body`, in order), one segment at a time: what readBodyRange's trusted stored read
- * 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`.
+ * cuts. Under a ledger that applies, a facts fence block cannot be overlaid in pieces, so the segments a block spans,
+ * and a segment that ends inside a facts marker (a marker a forced cut splits) with the next one, are joined, overlaid
+ * whole and yielded as one segment covering their rows, as withdrawal discovery and rewriteLiveSegmentedFences join
+ * them. A fence longer than FENCE_MAX_BYTES, counted from its begin marker through its end marker, refuses with
+ * `page_body_segmented`; a read that starts inside a block (a range after its start) 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));
@@ -406,14 +448,27 @@ export async function* trustedSegments(engine: BrainEngine, body: SegmentedBody,
const raw = utf8.decode(bytes);
return { row, raw: bytes, entryState: first.entryState, pieces: overlaidPieces(raw, await overlaidText(engine, body, { ...first, row }, raw, 'trusted')) };
};
+ if (!ledgerApplies(body.ledger)) {
+ for await (const seg of loadSegments(engine, body, rows, stop)) yield await emit([seg]);
+ return;
+ }
+ const bound = (bytes: number) => { if (bytes > FENCE_MAX_BYTES) throw fenceTooLargeError(body.slug, body.sourceId, bytes); };
+ let held: LoadedSegment[] = [];
+ // After the held segments: whether a fence block is open, the marker bytes they end with, and where the open block begins.
+ let open = false, carry = '', openAt = 0;
for await (const seg of loadSegments(engine, body, rows, stop)) {
- 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; }
+ if (held.length && !open && !carry) { yield await emit(held); held = []; }
+ if (!held.length) { open = readEntryState(seg.entryState)?.withdrawal.open === true; carry = ''; openAt = seg.row.byteStart; }
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 = []; }
+ const text = carry + utf8.decode(seg.bytes);
+ const base = seg.row.byteStart - Buffer.byteLength(carry, 'utf8');
+ const { head, tail } = partialFenceRuns(text, open);
+ if (open && head > 0) bound(base + Buffer.byteLength(text.slice(0, head), 'utf8') - openAt);
+ const carried = open && head === 0;
+ open = tail < text.length;
+ if (open && !carried) openAt = base + Buffer.byteLength(text.slice(0, tail), 'utf8');
+ if (open) bound(seg.row.byteStart + seg.row.byteLen - openAt);
+ carry = markerCarry(text);
}
if (held.length) yield await emit(held);
}
diff --git a/src/core/page-body/segment-blocks.ts b/src/core/page-body/segment-blocks.ts
index 6af2dd19b4..6fad6d2e17 100644
--- a/src/core/page-body/segment-blocks.ts
+++ b/src/core/page-body/segment-blocks.ts
@@ -16,8 +16,10 @@
* 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 is read joined across it, up to
- * the same bound (read-range.ts `trustedSegments`).
+ * forced cut while the source has withdrawals is read joined across it by
+ * read-range.ts `trustedSegments` (up to FENCE_MAX_BYTES, the bound withdrawal
+ * discovery and the purge rewrite share), and a block it yields longer than
+ * BLOCK_MAX_BYTES still refuses here.
*/
import type { BrainEngine } from '../engine.ts';
import { BLOCK_MAX_BYTES, blockTooLargeError, bodyRowWork, confirmBodyPin, openSegmentedBody, readBodyRange, trustedSegments, type BodyPin } from './read-range.ts';
diff --git a/src/core/page-body/segment-facts.ts b/src/core/page-body/segment-facts.ts
index fc76971377..a504af950d 100644
--- a/src/core/page-body/segment-facts.ts
+++ b/src/core/page-body/segment-facts.ts
@@ -16,9 +16,10 @@
* cuts inside a fence, so a fence lies in one block: a fence longer than a
* segment is a run of forced cuts, which bodyBlocks joins up to
* BLOCK_MAX_BYTES and refuses above with `page_body_segmented`. Joining a
- * fence across blocks is a fallback that keeps the same bound. A fence
- * crossing a forced cut while the source has withdrawals refuses with
- * `page_projection_stale` (read-range.ts).
+ * fence across blocks is a fallback that keeps the same bound. While the
+ * source has withdrawals, a fence crossing a forced cut is read joined across
+ * it and overlaid whole (read-range.ts `trustedSegments`, up to
+ * FENCE_MAX_BYTES), then cut into blocks here as any run is.
*
* `segmentedBodyMatchesFile` is the stale-cache check (canonicalCacheState)
* for a segmented page: the canonical file's split regions, streamed from
diff --git a/src/core/page-body/segment-rewrite.ts b/src/core/page-body/segment-rewrite.ts
index 591ea9dce3..d45783bdab 100644
--- a/src/core/page-body/segment-rewrite.ts
+++ b/src/core/page-body/segment-rewrite.ts
@@ -13,13 +13,15 @@
*/
import type { BrainEngine } from '../engine.ts';
import { isQuarantined } from '../quarantine.ts';
-import { PAGE_MAX_BYTES } from '../page-size-policy.ts';
+import { FACTS_FENCE_END } from '../facts-fence.ts';
import { maintenanceAttribution } from '../persistence/attribution.ts';
import { applySegmentedBody, sealSegmentedPage } from '../persistence/segmented-apply.ts';
import { withPageTierKept } from '../trust/fence-append.ts';
import { prepareSegmentedBody, readSegmentedBody, type SegmentedStagingOwner } from './ingest.ts';
-import { readPageBodyPolicy, STAGE_BATCH_BYTES } from './limits.ts';
+import { FENCE_MAX_BYTES, readPageBodyPolicy, STAGE_BATCH_BYTES } from './limits.ts';
+import { fenceTooLargeError } from './read-range.ts';
import { pageBodySegmentedError } from './page-shape.ts';
+import { readEntryState } from './entry-state.ts';
import { ContentHashStream } from './content-hash-stream.ts';
import type { StoredRegion } from './segmenter.ts';
import type { BodyRegion, JsonObject, ManifestRow } from './types.ts';
@@ -37,17 +39,45 @@ const fenceRegions = (row: ManifestRow) => (row.protectedRegions as StoredRegion
/** The region runs on into the next segment (it crosses a forced cut there). */
const runsOn = (r: StoredRegion) => r.open_start !== undefined && r.open_end === undefined;
-/** Every fence unit of `rows` the transform changes, in order. Reads only segments holding a fence. */
+/**
+ * Every fence unit of `rows` the transform changes, in order. Reads only segments holding a fence. A unit joins the
+ * segments a fence region runs on through, and a segment that ends inside a facts marker (the next one's entry state
+ * carries the marker's first bytes) with the next: a fence region of a segment starting inside its opener begins at the
+ * region's recorded `open_start`, in the segment before, and a facts fence whose closer a cut splits ends after the
+ * closer's last bytes, which the next segment holds outside any facts region. A fence longer than FENCE_MAX_BYTES,
+ * counted from its begin marker through its end marker, refuses before its segments are read.
+ */
async function changedUnits(engine: BrainEngine, sourceId: string, rows: readonly ManifestRow[], transform: FenceTransform): Promise<FenceUnit[]> {
const units: FenceUnit[] = [];
+ const joinsNext = (i: number) => i + 1 < rows.length && rows[i + 1]!.region === rows[i]!.region
+ && (fenceRegions(rows[i]!).some(runsOn) || !!readEntryState(rows[i + 1]!.entryState)?.withdrawal.carry);
for (let from = 0; from < rows.length; from++) {
- if (!fenceRegions(rows[from]!).length) continue;
+ if (!fenceRegions(rows[from]!).length && !joinsNext(from)) continue;
let to = from;
- while (to + 1 < rows.length && rows[to + 1]!.region === rows[from]!.region && fenceRegions(rows[to]!).some(runsOn)) to++;
+ while (joinsNext(to)) to++;
const span = rows.slice(from, to + 1);
- if (span.reduce((n, row) => n + row.byteLen, 0) > PAGE_MAX_BYTES) {
+ const spanStart = span[0]!.byteStart;
+ const extents: Array<{ start: number; end: number; closer: boolean }> = [];
+ for (const row of span) {
+ const regions = fenceRegions(row);
+ const last = extents[extents.length - 1];
+ const entry = row === span[0] ? undefined : readEntryState(row.entryState)?.withdrawal;
+ if (entry?.open && entry.carry && last?.end === row.byteStart && !regions.some(r => r.start === 0)) {
+ last.end += Buffer.byteLength(FACTS_FENCE_END, 'utf8') - Buffer.byteLength(entry.carry, 'utf8');
+ last.closer = true;
+ }
+ for (const r of regions) {
+ const start = row.byteStart + r.start, end = row.byteStart + r.end;
+ const tail = extents[extents.length - 1];
+ if (tail && tail.end === start) tail.end = end;
+ else extents.push({ start: Math.min(start, r.open_start ?? start), end, closer: false });
+ }
+ }
+ const overBound = extents.find(e => e.end - e.start > FENCE_MAX_BYTES);
+ if (overBound || (extents[0] && extents[0].start < spanStart)) {
const [page] = await engine.executeRaw<{ slug: string }>('SELECT slug FROM pages WHERE id=$1', [span[0]!.pageId]);
- throw pageBodySegmentedError({ slug: page?.slug, source_id: sourceId }, 'fence rewrite of a fence larger than the single-string ceiling');
+ if (overBound) throw fenceTooLargeError(page?.slug ?? String(span[0]!.pageId), sourceId, overBound.end - overBound.start);
+ throw pageBodySegmentedError({ slug: page?.slug, source_id: sourceId }, 'fence rewrite of a fence whose opener lies before the segments joined for it');
}
const texts = await engine.readSegmentTexts(sourceId, span.map(row => row.sha256));
const raw = Buffer.concat(span.map(row => {
@@ -55,20 +85,12 @@ async function changedUnits(engine: BrainEngine, sourceId: string, rows: readonl
if (!text) throw new Error(`Segment text ${hex(row.sha256)} of page ${row.pageId} is missing.`);
return text;
}));
- const regions: Array<{ start: number; end: number }> = [];
- let offset = 0;
- for (const row of span) {
- for (const r of fenceRegions(row)) {
- const last = regions[regions.length - 1];
- if (last && last.end === offset + r.start) last.end = offset + r.end;
- else regions.push({ start: offset + r.start, end: offset + r.end });
- }
- offset += row.byteLen;
- }
const parts: Buffer[] = [];
let cursor = 0, changed = false;
- for (const r of regions) {
+ for (const e of extents) {
+ const r = { start: e.start - spanStart, end: e.end - spanStart };
const fence = raw.subarray(r.start, r.end).toString('utf8');
+ if (e.closer && !fence.endsWith(FACTS_FENCE_END)) throw new Error(`Facts fence at stored byte ${e.start} of page ${span[0]!.pageId} does not end with its end marker across the cut.`);
const next = await transform(fence, { region: span[0]!.region });
parts.push(raw.subarray(cursor, r.start), Buffer.from(next, 'utf8'));
cursor = r.end;
diff --git a/src/core/persistence/effect-journal.ts b/src/core/persistence/effect-journal.ts
index dda199abbe..da8917e8eb 100644
--- a/src/core/persistence/effect-journal.ts
+++ b/src/core/persistence/effect-journal.ts
@@ -206,8 +206,8 @@ export async function releaseAbandonedClaims(engine: BrainEngine, processStarted
return 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 };
+/** @internal Claim renewals made between the pieces of a segmented page's file (effectClaimKeeper), by effect kind, for the bounded-work test. Counts, not time. */
+export const effectClaimWork: Record<string, number> = {};
/**
* Called between the pieces of a long read or write under a withdrawal-mirror or Git claim (a segmented page's file
@@ -219,7 +219,7 @@ export function effectClaimKeeper(engine: BrainEngine, effect: PersistenceEffect
return async () => {
if (performance.now() - last < intervalMs) return;
last = performance.now();
- effectClaimWork.renewals++;
+ effectClaimWork[effect.kind] = (effectClaimWork[effect.kind] ?? 0) + 1;
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.',
diff --git a/src/core/persistence/effect-recovery.ts b/src/core/persistence/effect-recovery.ts
index 3b1edd5d13..bc4b068589 100644
--- a/src/core/persistence/effect-recovery.ts
+++ b/src/core/persistence/effect-recovery.ts
@@ -16,7 +16,7 @@ import { persistenceFileHash, publishPersistenceFile } from './coordinator.ts';
import type { EffectRecovery, PersistenceEffect } from './effect-model.ts';
import { tryAcquirePublicationCapacity } from './pool-capacity.ts';
import { assertRecoveryStagingAbsent, cleanupRecoveryStaging, discardStreamingStage, publishStreamedStage, upgradeRecoveryStaging } from './staging.ts';
-import { existsAt, stageStreamedContent, type StreamedFileContent } from './large-file.ts';
+import { existsAt, stageStreamedContent, streamingStagePath, type StreamedFileContent } from './large-file.ts';
import { unreadPageFile } from './page-prepare.ts';
import { isSegmentedPage } from '../page-body/page-shape.ts';
import { declarePersistenceProtocol } from './protocol.ts';
@@ -154,14 +154,15 @@ function stagingReported(error: unknown): boolean {
/**
* 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).
+ * nothing: no file changed and no stage, whole or in progress, 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 or in-progress stream is still on disk
+ * (the writer could not remove it), 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;
+ if (!stage || existsAt(stage.path) || existsAt(streamingStagePath(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);
diff --git a/src/core/persistence/effects.ts b/src/core/persistence/effects.ts
index 5cd45409ae..b8d724ce40 100644
--- a/src/core/persistence/effects.ts
+++ b/src/core/persistence/effects.ts
@@ -171,16 +171,6 @@ 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 }
@@ -200,18 +190,18 @@ async function mirrorPage(engine: BrainEngine, effect: PersistenceEffect, bindin
let content: string | StreamedFileContent;
try {
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;
+ segmented ? null : serializePageToMarkdown(snapshot.page, snapshot.tags), opts.hostId, { allowMissing: true, between: keep }) : 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) {
- const skipped = unmirrorable(error);
- if (!skipped) throw error;
- await materializeAndAdvance(engine, effect, snapshot, opts.hostId, skipped);
+ // A segmented page whose fence a withdrawal cannot read whole (page_body_segmented) retries and parks like any failed
+ // target, so writer status and doctor list it; only a file that differs from the database is passed by.
+ if (!isFileDatabaseDrift(error)) throw error;
+ await materializeAndAdvance(engine, effect, snapshot, opts.hostId, 'file_database_drift');
return;
}
const target = { kind: 'withdrawal-mirror' as const, path: file.path, root: file.root, beforeHash: file.expectedBeforeHash ?? null,
@@ -286,12 +276,12 @@ async function gitPage(engine: BrainEngine, effect: PersistenceEffect, binding:
// 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 || isSegmentedPage(snapshot.page) ? null : serializePageToMarkdown(snapshot.page, snapshot.tags),
- opts.hostId, { allowMissing: true });
- await effectClaimKeeper(engine, effect, effectRenewalIntervalMs)();
+ opts.hostId, { allowMissing: true, between: effectClaimKeeper(engine, effect, effectRenewalIntervalMs) });
} catch (error) {
- const skipped = unmirrorable(error);
- if (!skipped) throw error;
- await skipTarget(engine, effect, snapshot, skipped);
+ // A segmented page whose fence a withdrawal cannot read whole (page_body_segmented) retries and parks like any failed
+ // target, so writer status and doctor list it; only a file that differs from the database is passed by.
+ if (!isFileDatabaseDrift(error)) throw error;
+ await skipTarget(engine, effect, snapshot, 'file_database_drift');
return;
}
if (!file) throw opError('source_changed', 'The Git binding changed.',
diff --git a/src/core/persistence/page-prepare.ts b/src/core/persistence/page-prepare.ts
index 450718cd90..d6ce41ec4e 100644
--- a/src/core/persistence/page-prepare.ts
+++ b/src/core/persistence/page-prepare.ts
@@ -50,6 +50,7 @@ import { bodyUnread, isSegmentedPage, pageBodySegmentedError, withoutBody } from
import { fileBodyDigests, overlaidFileBodyDigests, storedBodyDigests, type ByteSource, type FileReading, type RegionDigests } from '../page-body/body-digests.ts';
import { ledgerApplies, type BodyLedger } from '../page-body/segment-ledger.ts';
import { inferredHeadPrefix } from '../page-body/streamed-import.ts';
+import { fenceTooLargeError } from '../page-body/read-range.ts';
import { FRONTMATTER_HEAD_MAX_BYTES } from '../page-body/limits.ts';
import { occurrencesWithoutChunks, readSegmentedBody } from '../page-body/ingest.ts';
import { ContentHashStream } from '../page-body/content-hash-stream.ts';
@@ -216,22 +217,23 @@ function snapshotLedger(snapshot: PageSnapshot): BodyLedger {
* that applies cannot be overlaid streamed, so it refuses (`page_body_segmented`) instead of reading as drift.
*/
async function segmentedFileMatches(engine: BrainEngine, slug: string, bytes: ByteSource, snapshot: PageSnapshot,
- sourcePath: () => Promise<string>, activePack?: ParseOpts['activePack']): Promise<boolean> {
+ sourcePath: () => Promise<string>, activePack?: ParseOpts['activePack'], between?: () => Promise<void>): Promise<boolean> {
const ledger = snapshotLedger(snapshot);
let stored: RegionDigests | undefined;
const matches = async (reading: FileReading, inferred: boolean) => {
const file = fileBodyDigests(bytes, reading, slug, { activePack });
+ await between?.();
if (file.kind !== 'ok') return file.reason;
- // A facts fence under a ledger that applies is compared overlaid, one complete fence block at a time; a block too
- // long to overlay whole (held split across forced cuts) still refuses.
+ // A facts fence under a ledger that applies is compared overlaid, one complete fence block at a time; a fence longer
+ // than FENCE_MAX_BYTES refuses, as the stored side's trusted read does.
const fileDigests = file.factsFence && ledgerApplies(ledger)
? await overlaidFileBodyDigests(bytes, reading, file.regions, async text => (await overlayCanonicalBodies(engine.executeRaw.bind(engine), text, '',
ledger.withdrawals, { sourceId: snapshot.page.source_id, marker: ledger.globalPurges })).compiled_truth,
- () => pageBodySegmentedError(snapshot.page, 'fileMatchesSnapshot (a facts fence block under withdrawals longer than a block)'))
+ fence => fenceTooLargeError(slug, snapshot.page.source_id, fence), between)
: file.digests;
const parsed = { ...file.parsed, compiled_truth: fileDigests.truth, timeline: fileDigests.timeline };
const type = importedFileType(parsed, snapshot.page, inferred);
- stored ??= await storedBodyDigests(engine, Number(snapshot.page.id), ledger);
+ stored ??= await storedBodyDigests(engine, Number(snapshot.page.id), ledger, between);
return digest(canonical({ ...parsed, frontmatter: withoutSafetyAssessments(parsed.frontmatter), type }, parsed.tags))
=== digest(canonical({ ...withoutBody(snapshot.page), frontmatter: withoutSafetyAssessments(snapshot.page.frontmatter ?? {}), compiled_truth: stored.truth, timeline: stored.timeline }, snapshot.tags));
};
@@ -248,7 +250,9 @@ export async function prepareFileTarget(engine: BrainEngine, row: Pick<WriteRequ
/** #6368: a tombstone purge whose file matches these sync.exclude globs (relative to the source root) owns no file. */
excludeTombstone?: { patterns: string[]; onExcluded: (path: string) => void };
/** #6517: a delete whose file another live page of the source records owns no file; the census target and claimants are reported. */
- sharedOrigin?: { onShared: (shared: SharedOrigin) => void } } = {}): Promise<PreparedMutation['file']> {
+ sharedOrigin?: { onShared: (shared: SharedOrigin) => void };
+ /** Runs between the pieces of a segmented page's file comparison (an effect's claim renewal). */
+ between?: () => Promise<void> } = {}): Promise<PreparedMutation['file']> {
if (!row.worktree_id) return undefined;
// An in-memory canonical file over the 25 MiB push-scan cap is refused (only a page over the 24 MiB single-string
// ceiling renders one). That page's file is streamed instead (restore_page of a page whose body was not read back,
@@ -328,7 +332,7 @@ async function compareFileTarget(engine: BrainEngine, row: Pick<WriteRequest, 's
if (before && snapshot) {
const importPath = async () => scannerSourcePath(root, path, mode ?? await scannerSlugRootMode(engine, row.source_id, root));
// An inline page's file over the push-scan cap cannot hold its body (at most 24 MiB): drift, never read whole.
- const matches = bodyUnread(snapshot.page) ? await segmentedFileMatches(engine, row.slug, before, snapshot, importPath, options.activePack)
+ const matches = bodyUnread(snapshot.page) ? await segmentedFileMatches(engine, row.slug, before, snapshot, importPath, options.activePack, options.between)
: before.length <= PUSH_SCAN_MAX_FILE_BYTES && await fileMatchesSnapshot(engine, row.slug, (before instanceof FileBytes ? Buffer.from(before.subarray()) : before).toString('utf8'), snapshot, importPath, options.activePack);
if (!matches) {
const held = await heldFileRefusal(engine, row, root, path, 'drift', options.remote === true);
diff --git a/test/helpers/segmented-withdrawal.ts b/test/helpers/segmented-withdrawal.ts
new file mode 100644
index 0000000000..fe50d54fe2
--- /dev/null
+++ b/test/helpers/segmented-withdrawal.ts
@@ -0,0 +1,66 @@
+/**
+ * Shared steps of the segmented withdrawal tests (segmented-withdrawal-mirror.test.ts, segmented-withdrawal-fences.test.ts):
+ * a purge through the MCP verb on a twin brain (segmented-twins.ts), effect passes run until the mirror and Git effects
+ * settle, the page's streamed export to compare the canonical file with, and the effects' outcome.
+ */
+import { expect } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { readdirSync } from 'node:fs';
+import { join } from 'node:path';
+import { exportBodyLedger, readExportPage, readExportWithdrawals, segmentedExportMarkdown } from '../../src/core/export-snapshot.ts';
+import { serializeMarkdown, slugStampedFrontmatter } from '../../src/core/markdown.ts';
+import { runPersistenceEffects } from '../../src/core/persistence/effects.ts';
+import { localHostId } from '../../src/core/persistence/identity.ts';
+import type { TwinBrain } from './segmented-twins.ts';
+import { waitFor } from './wait-for.ts';
+import { withEnv } from './with-env.ts';
+
+export const fileOf = (brain: TwinBrain, slug: string) => join(brain.root, slug + '.md');
+/** Staging leftovers (hidden `.<sha>.tmp.<uuid>` siblings) next to the twins' files. */
+export const stagingLeft = (brain: TwinBrain) => readdirSync(join(brain.root, 'people')).filter(name => name.includes('.tmp.'));
+
+/**
+ * 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.
+ */
+export 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 NOT IN ('committed','failed') OR recovery IS NOT NULL)`, [brain.sourceId]);
+ if (!open!.n) return true;
+ 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 false;
+}, { timeoutMs: 120_000, intervalMs: 100, label: 'the mirror and Git effects settled' }).catch(() => undefined);
+
+/** The page's export, streamed as `gbrain export` streams a segmented page (export.ts), concatenated here only to compare. */
+export const exported = (brain: TwinBrain, slug: string) => brain.engine.transaction(async tx => {
+ const [key] = await tx.executeRaw<{ id: string; source_id: string; slug: string }>(
+ 'SELECT id::text AS id, source_id, slug FROM pages WHERE source_id=$1 AND slug=$2', [brain.sourceId, slug]);
+ const withdrawals = await readExportWithdrawals(tx, brain.sourceId);
+ const { page, tags } = await readExportPage(tx, key!, withdrawals);
+ const head = serializeMarkdown(slugStampedFrontmatter(page.slug, page.frontmatter ?? {}), '', '', { type: page.type, title: page.title, tags }).slice(0, -1);
+ const parts: Buffer[] = [];
+ for await (const piece of segmentedExportMarkdown(tx, page, exportBodyLedger(page.slug, withdrawals), head)) parts.push(Buffer.from(piece));
+ return Buffer.concat(parts);
+});
+
+export const effectsOf = async (brain: TwinBrain, requestId: string) => (await brain.engine.executeRaw<{ kind: string; state: string; error_code: string | null; data: any }>(
+ `SELECT e.kind, e.state, e.error_code, 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 IN ('withdrawal-mirror','git') ORDER BY e.kind`, [requestId]))
+ .map(e => ({ kind: e.kind, state: e.state, error: e.error_code, skipped: (typeof e.data === 'string' ? JSON.parse(e.data) : e.data)?.skipped ?? [] }));
+export const SETTLED = [{ kind: 'git', state: 'committed', error: null, skipped: [] }, { kind: 'withdrawal-mirror', state: 'committed', error: null, skipped: [] }];
+
+export 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]);
+ expect(fact).toBeDefined();
+ 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, beforePass);
+ return { requestId, hash8: String(done.purge.hash8) };
+}
diff --git a/test/large-pages/segmented-file-drift-ledger.test.ts b/test/large-pages/segmented-file-drift-ledger.test.ts
index 6456668a84..c31b480eda 100644
--- a/test/large-pages/segmented-file-drift-ledger.test.ts
+++ b/test/large-pages/segmented-file-drift-ledger.test.ts
@@ -9,9 +9,10 @@
* so the overlaid file digests equal the stored digests of the same body
* (also with a fence across a 1 MiB read boundary and a withdrawn row), and
* a file edited on disk to add a fence is refused as drift (source_changed,
- * the refusal an inline page gets), not as page_body_segmented. A fence
- * block longer than BLOCK_MAX_BYTES (one the stored side holds split across
- * forced cuts) still refuses page_body_segmented (fail closed).
+ * the refusal an inline page gets), not as page_body_segmented, also when
+ * the fence is longer than 8 MiB. A fence block longer than FENCE_MAX_BYTES
+ * still refuses page_body_segmented (fail closed), before the file's digest
+ * holds more than the bound and one read (`bodyDigestWork.largestHeld`).
* 2. Fails when: the check refuses every fenced file whenever the source has
* any withdrawal (page_body_segmented), or the file overlay differs from the
* stored overlay.
@@ -27,8 +28,8 @@ import { PGLiteEngine } from '../../src/core/pglite-engine.ts';
import type { BrainEngine } from '../../src/core/engine.ts';
import type { OperationContext } from '../../src/core/operations.ts';
import { parseMarkdown } from '../../src/core/markdown.ts';
-import { SEGMENT_MAX_BYTES } from '../../src/core/page-body/limits.ts';
-import { fileBodyDigests, overlaidFileBodyDigests, storedBodyDigests } from '../../src/core/page-body/body-digests.ts';
+import { FENCE_MAX_BYTES, SEGMENT_MAX_BYTES } from '../../src/core/page-body/limits.ts';
+import { bodyDigestWork, fileBodyDigests, overlaidFileBodyDigests, storedBodyDigests } from '../../src/core/page-body/body-digests.ts';
import { readBodyLedger } from '../../src/core/page-body/segment-ledger.ts';
import { overlayCanonicalBodies } from '../../src/core/page-state/snapshot.ts';
import { PAGE_MAX_BYTES } from '../../src/core/page-size-policy.ts';
@@ -175,13 +176,23 @@ test('under a source withdrawal, a fence added on disk is drift and a fence too
expect(await refusal(submit(engine, f, 'delete_page', 'notes/huge'))).toEqual(inline);
expect(await refusal(submit(engine, f, 'delete_page', 'notes/huge', { purge: true }))).toEqual(inline);
- const rows = Array.from({ length: 90_000 }, (_, i) => ROW(i + 1, `Routine note number ${i + 1} about the weekly planning meeting`));
- const long = FENCE(rows);
+ // A fence longer than a segment run is overlaid whole up to FENCE_MAX_BYTES (the bound withdrawal discovery and
+ // the purge rewrite read a fence within), so a 9 MiB fence added on disk is drift like any other.
+ const rows = (n: number) => Array.from({ length: n }, (_, i) => ROW(i + 1, `Routine note number ${i + 1} about the weekly planning meeting`));
+ const long = FENCE(rows(90_000));
expect(Buffer.byteLength(long)).toBeGreaterThan(8 * 1024 * 1024);
writeFileSync(file, huge.replace('midpointmarker', `midpointmarker\n\n${long}\n`));
+ expect(await refusal(submit(engine, f, 'delete_page', 'notes/huge'))).toEqual(inline);
+ // Over FENCE_MAX_BYTES the file's digest refuses before it holds more of the fence than the bound and one read.
+ const longer = FENCE(rows(Math.ceil(FENCE_MAX_BYTES / ROW(1, 'x').length)));
+ expect(Buffer.byteLength(longer)).toBeGreaterThan(FENCE_MAX_BYTES);
+ writeFileSync(file, huge.replace('midpointmarker', `midpointmarker\n\n${longer}\n`));
+ bodyDigestWork.largestHeld = 0;
const refused = await refusal(submit(engine, f, 'delete_page', 'notes/huge'));
expect(refused.code).toBe('page_body_segmented');
- expect(refused.message).toContain('longer than a block');
+ expect(refused.message).toContain(`over the ${FENCE_MAX_BYTES}-byte bound`);
+ expect(bodyDigestWork.largestHeld).toBeGreaterThan(FENCE_MAX_BYTES - SEGMENT_MAX_BYTES);
+ expect(bodyDigestWork.largestHeld).toBeLessThanOrEqual(FENCE_MAX_BYTES + 2 * SEGMENT_MAX_BYTES);
expect(readFileSync(file, 'utf8').includes('Routine note number 90000')).toBe(true);
} finally {
await disposePersistenceConsumer(engine);
diff --git a/test/large-pages/segmented-withdrawal-mirror.test.ts b/test/large-pages/segmented-withdrawal-mirror.test.ts
index 3ecf146be9..fa65e941e2 100644
--- a/test/large-pages/segmented-withdrawal-mirror.test.ts
+++ b/test/large-pages/segmented-withdrawal-mirror.test.ts
@@ -12,14 +12,25 @@
* 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).
+ * retries, then parks after its attempts; one whose in-progress stream could not be removed keeps its record, and
+ * recovery removes the stream and publishes. The mirror renders the file only when it has a file to rewrite, the Git
+ * walk never renders it, and both renew their claims between the pieces of the file they compare, measure and stage
+ * (`largeFileWork.bytesMeasured`, `effectClaimWork` per effect kind, counts not time).
+ * A purge in a facts fence leaves the stored segments, the canonical file and its Git commit, with both effects
+ * committed and nothing skipped, whatever the fence's size up to FENCE_MAX_BYTES (just over 8 MiB, and about 10 MiB:
+ * one bound and one count, begin marker through end marker, for discovery, the purge rewrite, the trusted read and
+ * the file's digest) and wherever a forced cut falls (inside its opener, inside its closer, or a line of four segments
+ * running into it, its digest holding at most a segment of that line: `bodyDigestWork.largestHeld`).
* 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; 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.
+ * mirror never parks), or a refused stage whose stream is left on disk loses its record; the Git walk or a mirror of a
+ * missing file measures the file; no renewal happens mid-stream or mid-comparison.
+ * For the fences: the trusted read refuses a fence over 8 MiB, so the mirror and Git walk pass the page by
+ * (`page_body_segmented`) and the file keeps the row; discovery or the rewrite reads a split fence from its slots
+ * only and misses the marker bytes outside them (`withdrawal_provenance`, or the row stays in the segments); the
+ * file's digest holds the whole long line.
* 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; the EIO at
@@ -28,12 +39,11 @@
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, rmSync, writeFileSync } from 'node:fs';
+import { existsSync, 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 { bodyDigestWork } from '../../src/core/page-body/body-digests.ts';
import { SEGMENT_MAX_BYTES } from '../../src/core/page-body/limits.ts';
import { __setEffectRenewalIntervalForTests, runPersistenceEffects } from '../../src/core/persistence/effects.ts';
import { effectClaimWork } from '../../src/core/persistence/effect-journal.ts';
@@ -44,6 +54,7 @@ import { largeFileWork } from '../../src/core/persistence/large-file.ts';
import { durableGitRepo, gitAsync } from '../helpers/git-publication.ts';
import { withManagedFixtureWrite } from '../helpers/managed-e2e-fixture-write.ts';
import { openTwinBrain, type TwinBrain } from '../helpers/segmented-twins.ts';
+import { effectsOf, exported, fileOf, purge, settle, SETTLED, stagingLeft } from '../helpers/segmented-withdrawal.ts';
import { testBackends } from '../helpers/test-backends.ts';
import { waitFor } from '../helpers/wait-for.ts';
import { withEnv } from '../helpers/with-env.ts';
@@ -69,6 +80,8 @@ 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';
+/** The claim whose refused stage also leaves its in-progress stream on disk (removing it fails once). */
+const EIO_STREAM_LEFT = 'Twin Example vault code is 5023';
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';
@@ -85,7 +98,6 @@ const crossCutPage = () => {
+ '|---|-------|------|------------|------------|------------|------------|-------------|--------|---------|\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');
/** 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>');
@@ -105,53 +117,6 @@ function watchWholeReads(path: string) {
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.'));
-
-/**
- * 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', 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;
- 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 false;
-}, { timeoutMs: 120_000, intervalMs: 100, label: 'the mirror and Git effects settled' }).catch(() => undefined);
-
-/** The page's export, streamed as `gbrain export` streams a segmented page (export.ts), concatenated here only to compare. */
-const exported = (brain: TwinBrain, slug: string) => brain.engine.transaction(async tx => {
- const [key] = await tx.executeRaw<{ id: string; source_id: string; slug: string }>(
- 'SELECT id::text AS id, source_id, slug FROM pages WHERE source_id=$1 AND slug=$2', [brain.sourceId, slug]);
- const withdrawals = await readExportWithdrawals(tx, brain.sourceId);
- const { page, tags } = await readExportPage(tx, key!, withdrawals);
- const head = serializeMarkdown(slugStampedFrontmatter(page.slug, page.frontmatter ?? {}), '', '', { type: page.type, title: page.title, tags }).slice(0, -1);
- const parts: Buffer[] = [];
- for await (const piece of segmentedExportMarkdown(tx, page, exportBodyLedger(page.slug, withdrawals), head)) parts.push(Buffer.from(piece));
- return Buffer.concat(parts);
-});
-
-const effectsOf = async (brain: TwinBrain, requestId: string) => (await brain.engine.executeRaw<{ kind: string; state: string; error_code: string | null; data: any }>(
- `SELECT e.kind, e.state, e.error_code, 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 IN ('withdrawal-mirror','git') ORDER BY e.kind`, [requestId]))
- .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, 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, beforePass);
- return { requestId, hash8: String(done.purge.hash8) };
-}
async function extract(brain: TwinBrain, slug: string, facts: string[]) {
brain.setChatReply(JSON.stringify({ facts: facts.map(fact => ({ fact, kind: 'fact', entity: slug, confidence: 1, notability: 'high' })) }));
@@ -341,7 +306,7 @@ for (const kind of testBackends()) {
await seed.setSwitch(true);
await seed.put(SEGMENTED, 1_100_000);
});
- await extract(brain, SEGMENTED, [EIO_ONCE, EIO_ALWAYS, KEPT]);
+ await extract(brain, SEGMENTED, [EIO_ONCE, EIO_ALWAYS, EIO_STREAM_LEFT, KEPT]);
expect(await brain.storageOf(SEGMENTED)).toBe('segmented');
await settle(brain, kind);
}, 600_000);
@@ -366,6 +331,34 @@ for (const kind of testBackends()) {
expect(stagingLeft(brain)).toEqual([]);
}, 600_000);
+ test('a refused stage whose in-progress stream cannot be removed keeps its record, and recovery publishes', async () => {
+ let refused = 0, kept = 0, left = '';
+ installFaultHook(async point => { if (point === 'large_file:stage_streaming' && refused === 0) { refused++; throw eio(); } });
+ const unlink = fs.unlinkSync;
+ const spy = spyOn(fs, 'unlinkSync').mockImplementation(((path: fs.PathLike) => {
+ if (String(path).endsWith('.streaming') && kept === 0) { kept++; left = String(path); throw Object.assign(new Error('EIO: i/o error, unlink'), { code: 'EIO', errno: -5, syscall: 'unlink' }); }
+ return unlink(path);
+ }) as typeof fs.unlinkSync);
+ let requestId = '';
+ try {
+ requestId = await submitPurge(EIO_STREAM_LEFT);
+ await waitFor(async () => { await pass(); return kept === 1; }, { timeoutMs: 60_000, intervalMs: 100, label: 'the stream left on disk' });
+ // The stream stayed on disk, so the record naming its stage was kept and recovery (on whichever worker claims the
+ // effect next) removes the stream before it stages again; a released record leaves the stream to block every retry.
+ await settle(brain, kind);
+ } finally { installFaultHook(undefined); spy.mockRestore(); }
+ expect([refused, kept]).toEqual([1, 1]);
+ expect(left.startsWith(brain.root)).toBe(true);
+ expect(existsSync(left)).toBe(false);
+ const file = readFileSync(fileOf(brain, SEGMENTED));
+ expect(file.toString('utf8')).not.toContain(EIO_STREAM_LEFT);
+ 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;
@@ -420,20 +413,22 @@ for (const kind of testBackends()) {
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 () => {
+ test('the mirror and the Git walk renew their claims between the pieces of the file they compare, measure and stage', async () => {
// Interval 0: every piece renews, so the count is a function of the pieces, not of time.
restoreRenewal = __setEffectRenewalIntervalForTests(0);
- effectClaimWork.renewals = 0;
+ for (const effect of Object.keys(effectClaimWork)) delete effectClaimWork[effect];
let receipt: Awaited<ReturnType<typeof purge>>;
try { receipt = await purge(brain, kind, SEGMENTED, RENEW_CLAIM); } finally { restoreRenewal(); }
- const renewals = effectClaimWork.renewals;
+ const renewals = { ...effectClaimWork };
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.
+ // At least one renewal per segment of each pass over the file: the mirror measures and stages it; the Git walk
+ // compares it with the stored body (the file's digest and the segments' digest).
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);
+ expect(renewals['withdrawal-mirror'] ?? 0).toBeGreaterThanOrEqual(2 * segments!.n);
+ expect(renewals.git ?? 0).toBeGreaterThanOrEqual(2 * segments!.n);
}, 600_000);
test('a page whose canonical file is gone is never rendered by its mirror', async () => {
@@ -588,3 +583,111 @@ for (const kind of testBackends()) {
}, 600_000);
});
}
+
+const MB = 1024 * 1024;
+const BEGIN = '<!--- gbrain:facts:begin -->';
+const END = '<!--- gbrain:facts:end -->';
+const HEADER = '| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |\n'
+ + '|---|-------|------|------------|------------|------------|------------|-------------|--------|---------|\n';
+const row = (n: number, claim: string, context = '') => `| ${n} | ${claim} | fact | 1.0 | world | medium | 2026-01-01 | | chat | ${context} |`;
+/** A routine row's context: long, so a fence is megabytes long in fewer rows than withdrawal discovery checks at once (16,384). */
+const CONTEXT = 'Planning notes from the weekly meeting about the roadmap. '.repeat(13);
+const page = (body: string) => '---\ntype: person\ntitle: Twin Example\n---\n\n# Twin Example\n\n' + body;
+/** A fence of `n` routine rows with `claim` in the middle and `kept` after it. */
+const fence = (n: number, claim: string, kept: string) => {
+ const rows = Array.from({ length: n }, (_, i) => row(i + 1, `Routine note number ${i} about the weekly planning meeting`, CONTEXT));
+ rows.splice(Math.floor(n / 2), 0, row(n + 1, claim), row(n + 2, kept));
+ return BEGIN + '\n' + HEADER + rows.join('\n') + '\n' + END;
+};
+
+interface Case { slug: string; claim: string; kept: string; content: string; fenceBytes?: number }
+const bigCase = (slug: string, n: number, code: number): Case => {
+ const f = fence(n, `Twin Example vault code is ${code}`, `Twin Example kept code is ${code}`);
+ return { slug, claim: `Twin Example vault code is ${code}`, kept: `Twin Example kept code is ${code}`, content: page('Intro.\n\n' + f + '\n'), fenceBytes: Buffer.byteLength(f) };
+};
+/** A fence whose opener a forced cut splits: a line of a segment less 10 bytes runs into it. */
+const openerCut: Case = { slug: 'people/opn-example', claim: 'Twin Example vault code is 6101', kept: 'Twin Example kept code is 6101',
+ content: page('x'.repeat(SEGMENT_MAX_BYTES - 10) + fence(4, 'Twin Example vault code is 6101', 'Twin Example kept code is 6101') + '\n\nAfter the fence.\n') };
+/** A fence whose closer a forced cut splits: its last line is a segment of blanks less 10 bytes, then the closer. */
+const closerCut: Case = { slug: 'people/cls-example', claim: 'Twin Example vault code is 6102', kept: 'Twin Example kept code is 6102',
+ content: page('Intro.\n\n' + fence(4, 'Twin Example vault code is 6102', 'Twin Example kept code is 6102').replace('\n' + END, '\n' + ' '.repeat(SEGMENT_MAX_BYTES - 10) + END) + '\n\nAfter the fence.\n') };
+/** A line of four segments runs into the fence's opener. */
+const longLine: Case = { slug: 'people/lng-example', claim: 'Twin Example vault code is 6103', kept: 'Twin Example kept code is 6103',
+ content: page('w'.repeat(4 * SEGMENT_MAX_BYTES + 100) + fence(4, 'Twin Example vault code is 6103', 'Twin Example kept code is 6103') + '\n\nAfter the fence.\n') };
+
+/** Live segments of the page whose stored text still holds `text`. */
+const segmentsHolding = async (brain: TwinBrain, slug: string, text: string) => (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 JOIN page_segment_texts t ON t.source_id=m.source_id AND t.sha256=m.sha256
+ WHERE p.source_id=$1 AND p.slug=$2 AND m.gen_to IS NULL AND m.staging_id IS NULL AND position(convert_to($3,'UTF8') in t.body)>0`, [brain.sourceId, slug, text]))[0]!.n;
+/** Live segments that start inside a facts marker (the segmenter carried its first bytes across the cut). */
+const segmentsInsideMarker = async (brain: TwinBrain, slug: string) => (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
+ AND coalesce(m.entry_state->'withdrawal'->>'carry','')<>''`, [brain.sourceId, slug]))[0]!.n;
+
+async function purgedEverywhere(brain: TwinBrain, kind: 'pglite' | 'postgres', c: Case) {
+ expect(await segmentsHolding(brain, c.slug, c.claim)).toBeGreaterThan(0);
+ expect(readFileSync(fileOf(brain, c.slug), 'utf8')).toContain(c.claim);
+ const receipt = await purge(brain, kind, c.slug, c.claim);
+ expect(await effectsOf(brain, receipt.requestId)).toEqual(SETTLED);
+ expect(await segmentsHolding(brain, c.slug, c.claim)).toBe(0);
+ const file = readFileSync(fileOf(brain, c.slug));
+ expect(file.includes(c.claim)).toBe(false);
+ expect(file.includes(c.kept)).toBe(true);
+ expect(file.equals(await exported(brain, c.slug))).toBe(true);
+ expect(await gitAsync(brain.root, 'status', '--porcelain', '--', c.slug + '.md')).toBe('');
+ expect(stagingLeft(brain)).toEqual([]);
+}
+
+async function openWith(kind: 'pglite' | 'postgres', cases: Case[]): Promise<TwinBrain> {
+ const brain = await openTwinBrain(kind, [], async seed => { await seed.setSwitch(true); });
+ for (const c of cases) {
+ expect(await brain.call('put_page', { slug: c.slug, content: c.content })).toMatchObject({ state: 'committed' });
+ expect(await brain.storageOf(c.slug)).toBe('segmented');
+ }
+ await settle(brain, kind);
+ durableGitRepo(brain.root, cases.map(c => c.slug + '.md'));
+ return brain;
+}
+
+for (const kind of testBackends()) {
+ describe(kind + ': a purge in a facts fence longer than 8 MiB leaves the canonical file', () => {
+ const cases = [bigCase('people/big-example', 9_800, 6201), bigCase('people/hge-example', 12_900, 6202)];
+ let brain: TwinBrain;
+ beforeAll(async () => { brain = await openWith(kind, cases); }, 600_000);
+ afterAll(() => brain.close(), 120_000);
+
+ test('a fence just over 8 MiB', async () => {
+ expect(cases[0]!.fenceBytes).toBeGreaterThan(8 * MB);
+ expect(cases[0]!.fenceBytes).toBeLessThan(8.5 * MB);
+ await purgedEverywhere(brain, kind, cases[0]!);
+ }, 600_000);
+
+ test('a fence of about 10 MiB', async () => {
+ expect(cases[1]!.fenceBytes).toBeGreaterThan(10 * MB);
+ await purgedEverywhere(brain, kind, cases[1]!);
+ }, 600_000);
+ });
+
+ describe(kind + ': a purge in a facts fence whose marker a forced cut splits leaves the canonical file', () => {
+ let brain: TwinBrain;
+ beforeAll(async () => { brain = await openWith(kind, [openerCut, closerCut, longLine]); }, 600_000);
+ afterAll(() => brain.close(), 120_000);
+
+ test('the opener split by a forced cut', async () => {
+ expect(await segmentsInsideMarker(brain, openerCut.slug)).toBe(1);
+ await purgedEverywhere(brain, kind, openerCut);
+ }, 600_000);
+
+ test('the closer split by a forced cut', async () => {
+ expect(await segmentsInsideMarker(brain, closerCut.slug)).toBe(1);
+ await purgedEverywhere(brain, kind, closerCut);
+ }, 600_000);
+
+ test('a line of four segments running into the opener, its digest holding at most a segment of it', async () => {
+ bodyDigestWork.largestHeld = 0;
+ await purgedEverywhere(brain, kind, longLine);
+ expect(bodyDigestWork.largestHeld).toBeGreaterThan(0);
+ expect(bodyDigestWork.largestHeld).toBeLessThanOrEqual(2 * SEGMENT_MAX_BYTES + 4096);
+ }, 600_000);
+ });
+}