Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

perf(evidence): read a segmented page's evidence in 3 serial steps and overlap segmented pages

garrytanbfd37f0516d3
diff --git a/docs/architecture/key-files/core-services-2-continued.md b/docs/architecture/key-files/core-services-2-continued.md
index 7d06b3862d..d01105a307 100644
--- a/docs/architecture/key-files/core-services-2-continued.md
+++ b/docs/architecture/key-files/core-services-2-continued.md
@@ -29,7 +29,7 @@ The page-state concurrency foundation under `src/core/page-state/` and the share
- `src/core/ops/page-upload.ts` — the five upload-session operations (`begin_page_upload`, `upload_page_part`, `get_page_upload`, `commit_page_upload`, `abort_page_upload`; write scope, client slug-fence allowlist). Begin routes the source and slug as put_page does, runs put_page's grant and visibility authorization before reading the page (a private page answers as a missing one), and reserves the declared bytes; every later call re-checks the binding (creating principal, write source inside the read scope, source incarnation, the page id or, for create, a still-absent slug) and answers any mismatch with an `upload_not_found` identical to an unknown id; abort needs only the creating principal, its source and the slug fences, so a session whose page or incarnation moved can still be freed. A refusal at commit (stale revision, sha mismatch) and a commit whose write ended without committing discard the session; only a write whose `body_ref` names the session is recorded as its commit, so a begin request_id another write already used attaches nothing. Commit claims the session with an atomic open-to-sealed `sealUpload` before hashing; a call that loses the claim, or finds a lapsed session another call already moved on (`settleLapse`), reads the session again and follows its real state (sealed or committing replays the commit, committed returns the first receipt), so `upload_expired` is answered only when this call expired it (`uploadCommitProbe` is the forced-race seam, `test/large-pages/upload-review.test.ts`). After the hash check commit submits an ordinary put_page carrying `body_ref` (`stagedBody`), so a second commit replays the first receipt; a replace re-checks `expected_revision` and the shrink guard. Append commits through `admitPageAppend` (persistence/page-append.ts) with the staged `body_ref`. Begin admits create and replace up to the page ceiling (`pages.max_bytes`, the engine ceiling by default) and an append up to PAGE_MAX_BYTES; over PAGE_MAX_BYTES a remote writer is refused `file_too_large` at begin where the write gate applies to an agent-written page.
- `src/core/persistence/page-upload.ts` — upload-session storage: `page_body_stagings` rows of kind `upload` and their raw `page_body_staging_parts`, `part_max_frame_bytes` from the transport's `ctx.inboundFrameBytes` (at most 4 MiB, minus a 4 KiB envelope), part UTF-8 and code-point checks, the staged-quota reservation (limits.ts `stagedCounterKeys`, recounted under the counter locks at begin) and its release on commit, abort or expiry (`transitionUploads` with `RELEASE_STAGED_CTE`, which deletes the parts in the same statement; the segment sweep expires lapsed sessions the same way). An open session expires past its idle or hard deadline, a sealed one only past its hard deadline, which sealing extends by one idle period; a lapsed session is never sealed, so the brain-wide sum at begin leaves out other principals' lapsed sessions; `expireIfLapsed` reports whether its update changed the row. A session takes at most `uploadPartLimit` parts (64 plus one per 64 KiB declared) unless the part completes it (`upload_too_many_parts`). `withStagedUpload` binds a put_page or append_page preparation to the sealed session and marks it committed in the publication transaction; `prepareStagedUpload` (from `preparePageMutation`) reads a body within PAGE_MAX_BYTES back as put_page content and hands a larger one to upload-streamed.ts. `stagedUploadWork` counts whole-body reads for the memory tests.
- `src/core/persistence/upload-streamed.ts` — a committed upload over PAGE_MAX_BYTES: the sealed parts are spooled one part at a time into a private temporary file that the segmented streamed import (page-body/streamed-import.ts) reads, verifying the admitted sha256; the spool is removed before publication. A remote replace of a page holding a takes fence, a facts fence with a non-world row (or one that does not parse; `segmentedFactsFenceView` reads only the fence runs of a segmented page), or timeline rows (without `drop_timeline`) refuses `upload_protected_content`, since put_page's whole-body takes, hidden-facts and timeline checks cannot run streamed. A remote writer gets put_page's gate and page tier (`content.writer`), so where the write gate applies the commit refuses `file_too_large`; a trusted local writer takes the source owner's tier, as a streamed local `put --file` does. A worktree-bound page publishes database-only (`db_only`).
-- `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/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`), the rows (and, given `expect`, the caller's slug and source, the ledger) alongside the page row: rows of another generation than the page row names, or a ledger read under another name, are read again; `loadSegments` reads a batch's metadata alongside its first text; `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/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index 8be1506e75..f9521d7794 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -44,6 +44,6 @@ src/core/ops/pages.ts 728 ratchet crossed the unlisted 1500 cap in the fix wave:
src/core/search/mode.ts 1704 ratchet +53 W3 confidence-gated reranking: reranker_gate / reranker_gate_min_gap bundle fields, overrides, config parse and KNOB_CONFIG_KEY rows, knobsHash v=31 rrg=/rrgg=/ecf= parts (parse contracts in crag.ts); +10 System One v1: decide.* snapshot subset in loadSearchModeConfig, append-only dec= knobsHash part; +5 #3617 follow-up: v27 same-knobs behavioral-change note (relaxed-row fusion demotion rides the bump); new row: crossed the 1500 unlisted cap in the 2026-08 eval fix wave — KNOBS_HASH v=27 adaptive-return fold (ar/arem/arom/armk/ari parts + KnobsHashContext.adaptiveReturn field + contamination rationale comments) | merged v0.48.1.0 (+#4787) true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); ranker wave v0.48.4.0: four knobs (expansion_variant_budget, relational_rerank_pin, keyword_arm_confidence_floor, metadata_boost_gate) + v29 hash parts + doc receipts (+218); #4781 loadSearchModeConfig reads the config table once via loadConfigSnapshot (+6); +4 #4359: update loadSearchModeConfig docstring — the cached path now reads config once (threaded snapshot), not twice; retired provider integration removed; +12 fw3-search: search.source_boosts + search.alias_token_hop read in the mode snapshot; +10 #5691: KnobsHashContext.queryPrefix and its append-only qp= part; P7 relational_planner / relational_orient_onehop knobs (interface docs, bundles, overrides, config parse, hash parts); +18 P7 relational_chain_slots knob (interface doc, bundles, override, config parse, rcs= hash part); +22 GBRA-60 S1 diverse_pool_depth knob (interface doc, bundles, overrides, pick, config parse, append-only dpd= hash part); +35 GBRA-154: collapse and rank_priors knobs (interface docs, bundles, overrides, pick, config parse, append-only col=/rpr= hash parts); GBRA-151 retrieval P0 x operability wave merge: both sides grew the file, re-summed (1704 measured)
src/commands/eval-longmemeval.ts 1544 ratchet new row: crossed the 1500 unlisted cap in fw3-search (#5092 benchmark-brain recycling: configureBrain split + recycler wiring + test seams; the recycler itself lives in src/eval/longmemeval/harness.ts); +1 P6: tokenmax synopsis-tier wiring (logic in eval/longmemeval/synopsis-tier.ts); +13 GBRA-81 lane A: --via-operation query|search (flags, per-call expansion pin, the run's expectExpansion, the op branch in runOneQuestion, row field, via_operation_summary and its FAIL line; logic in eval/longmemeval/via-operation.ts); +12 --call-plan FILE / --call-plan-gate CMD: two LME_FLAGS entries (CLI help lines), two ParsedArgs fields, the parseArgs pairing check and the header invariant (planner lives in eval/longmemeval/call-plan.ts; runEvalLongMemEval is one line shorter)
src/commands/doctor/checks/extraction-sync.ts 1500 ratchet +7 GBRA-130 A-1: links_extraction_lag held bucket and its retry fix (logic in core/extraction-lag.ts heldExtractionReport); +1 undeclared_db_only_pages computes the source Git scope once per source (logic in core/markdown.ts sourceGitScope); new row: crossed the 1500 unlisted cap at the fix wave 9 merge: +7 lane W #5028 (extract_atoms freshness judged by the phase itself) and +3 lane F #5863 (extract_health dates a high halt rate by its last halt), each under the cap alone; +7 #5019: content_hash_duplicates fix pins the pairs' source (GBRAIN_SOURCE) and names a delete that runs; +1 fix wave 10 lane L1 #5556: links_extraction_lag denominator excludes quarantined pages (quarantineFilterFragment import); +11 fix wave 15 P2.8 (#5495): extract_health reads the 7-day halt reasons per kind (halt_reasons, top_halt_reason in details and the top reason in the warn line); the read, the unknown bucket and the ranking live in core/extract/rollup-writer.ts; +20 wave 18b lane 1: links_extraction_lag names the columns its pre-migration degrade reads (#6599 strict predicate), sync_freshness separates sync outcome from freshness for a source with no successful sync (#4960; verdict text, fixes and the attempt read live in doctor/sync-outcome.ts and core/sync-attempt.ts) and exempts read-only skill-pack catalogs (#6076; core/shared-skills/adopted-packs.ts); -51 #6803 (D1): links_extraction_lag reads its counts and verdict from core/extraction-lag.ts (shared with the sync nudge); +1 #7145: content_hash_duplicates reads one group past its list to report a floor ("at least 50")
-src/core/search/evidence-delivery.ts 1712 ratchet +5 W5: EvidencePlan.rankCut resolved with the plan (logic in search/page-rank-cut.ts); +20 W5 whole_pages: wholeCost prices a block as delivery would emit it whole (needs the private Block/enrichBlock internals) and the cut is wired before allocate (cutWholePages lives in search/page-rank-cut.ts); new row: crossed the 1500 unlisted cap at the #6367 merge (master 1479, its explicit-budget cap) by the C1 date header threaded through every block path, cap included; pagePlanHits (search/page-plan-hits.ts) and the header loader (evidence-date.ts blockDateHeaders) were peeled first; peel candidate: allocateCapped; +8 at the #6396 merge: page evidence text cut through the fence-chunk trust overlay and the caller minTrust floor (re-summed: our 1504 + master +8); +119 Cat 40 next wave F2: the search.long_page_unit policy (withLongPagePolicy, selectLongPages size preflight with page/byte/deadline limits) and the long-page fetch and fallback in deliverEvidence, kept in the shared seam the plan names (gbrain-evals docs/plans/2026-10-11-cat40-next-wave, F2); +17 F2 rework to the frozen-comparison policy: search.long_page_min_chars (rendered-body characters, default 20,000) read in withLongPagePolicy, a character count in the preflight, the rendered-body confirmation in deliverEvidence, and the long-page row exemption in capDeliveredSnippets (re-summed at the 0.60.225.0 merge: master 1537 + F2 136); +39 Wave B PR 2 lane 2b: planSegmentedBlock joins the windows search/segmented-evidence.ts reads around a segmented page's hits into one run-marked document (needs the private Doc/Piece/buildDoc/locateAnchor internals), planBlock's unit cut split into blockFromDoc for both, sections bounded by their run, selectionCost counts a gap between runs, and the fetch skips the whole-body fence overlay for a segmented page
+src/core/search/evidence-delivery.ts 1716 ratchet +5 W5: EvidencePlan.rankCut resolved with the plan (logic in search/page-rank-cut.ts); +20 W5 whole_pages: wholeCost prices a block as delivery would emit it whole (needs the private Block/enrichBlock internals) and the cut is wired before allocate (cutWholePages lives in search/page-rank-cut.ts); new row: crossed the 1500 unlisted cap at the #6367 merge (master 1479, its explicit-budget cap) by the C1 date header threaded through every block path, cap included; pagePlanHits (search/page-plan-hits.ts) and the header loader (evidence-date.ts blockDateHeaders) were peeled first; peel candidate: allocateCapped; +8 at the #6396 merge: page evidence text cut through the fence-chunk trust overlay and the caller minTrust floor (re-summed: our 1504 + master +8); +119 Cat 40 next wave F2: the search.long_page_unit policy (withLongPagePolicy, selectLongPages size preflight with page/byte/deadline limits) and the long-page fetch and fallback in deliverEvidence, kept in the shared seam the plan names (gbrain-evals docs/plans/2026-10-11-cat40-next-wave, F2); +17 F2 rework to the frozen-comparison policy: search.long_page_min_chars (rendered-body characters, default 20,000) read in withLongPagePolicy, a character count in the preflight, the rendered-body confirmation in deliverEvidence, and the long-page row exemption in capDeliveredSnippets (re-summed at the 0.60.225.0 merge: master 1537 + F2 136); +39 Wave B PR 2 lane 2b: planSegmentedBlock joins the windows search/segmented-evidence.ts reads around a segmented page's hits into one run-marked document (needs the private Doc/Piece/buildDoc/locateAnchor internals), planBlock's unit cut split into blockFromDoc for both, sections bounded by their run, selectionCost counts a gap between runs, and the fetch skips the whole-body fence overlay for a segmented page; +4 segmented pages read at once before planning (segmentedReads; the read is search/segmented-evidence.ts, the statements page-body/read-range.ts)
src/commands/config.ts 1522 ratchet new row: crossed the 1500 unlisted cap in wave 15 P7.4 #5461: set-time validation of think.pages_budget_chars / think.excerpt_ceiling_chars (range + parser live in core/think/pages-budget.ts), mirroring the cycle.consolidate.cluster_threshold hook; +1 wave 16 G5.1 (#6495): set-time refusal hook for search.keyword_statement_timeout_ms (check lives in commands/config/keyword-timeout-value.ts); +1 wave 18b lane 5 (#5012 item 6): search.contextual_retrieval prints the existing-pages hint after the write (text lives in commands/config/contextual-mode-hint.ts); +1 #6712 PR 2: retired/rollback sync key dispatch line (logic in core/sync-config-keys.ts handleSyncKeyConfig); +1 #6865: sync.slug_conflicts.auto_remove boolean validation at set time (refusal text in repair/slug-autoheal.ts); +1 #6948: sync.origin_twins.auto_resolve boolean validation at set time (refusal text in repair/origin-twins-heal.ts); +2 #6795: config set chat_model/expansion_model help line and the model-pin import (shadow report and file-pin unset live in commands/config/model-pin-shadow.ts); +1 #6712 PR 4b: sync.admission set-time hook (value logic in commands/config/sync-admission-value.ts); +4 #7130: set-time refusal hook for sync.max_deletes / sync.max_delete_ratio (and .source.<id>) / purge.retention_hours (check lives in core/sync-reconcile.ts deleteSafetyConfigRefusal); +1 GBRA-150: sync.metafile_pages set-time route (body in config/sync-metafile-pages-value.ts); re-summed at the v0.60.330.0 merge (1520 measured); +2 #7242 minions.terminal_hook file-plane key and its set branch (logic in minions/terminal-hook.ts)
src/commands/mcp-expose.ts 1512 ratchet hosted_option: Session carries the gbrain.io coaching notice on the first-receipt run and Tailscale/service friction exits (copy, refs and gating live in core/onboard/hosted-option.ts)
diff --git a/src/core/page-body/read-range.ts b/src/core/page-body/read-range.ts
index 750eaec0e1..916cb598d7 100644
--- a/src/core/page-body/read-range.ts
+++ b/src/core/page-body/read-range.ts
@@ -170,22 +170,38 @@ async function checkPin(pin: BodyPin, page: Record<string, unknown> | undefined,
await pin.admit?.();
}
+/** A generation's manifest rows, each carrying the generation read (`generation` null: the page's live one at the statement). */
+function manifestRows(engine: BrainEngine, pageId: number, generation: number | null): Promise<Record<string, unknown>[]> {
+ return engine.executeRaw<Record<string, unknown>>(`SELECT m.seq, m.occurrence_id, m.region, m.sha256, m.byte_start, m.byte_len,
+ m.line_start, m.line_count, m.static_proj_bytes, m.static_proj_lines, jsonb_array_length(m.outline) AS outline_count,
+ jsonb_array_length(m.facts_slots) > 0 AS has_facts, m.date_min IS NOT NULL AS has_date, g.generation
+ FROM (SELECT COALESCE($2::bigint, (SELECT body_generation FROM pages WHERE id=$1)) AS generation) g
+ JOIN page_body_manifest m ON m.page_id=$1 AND m.staging_id IS NULL AND m.gen_from<=g.generation AND (m.gen_to IS NULL OR m.gen_to>g.generation)
+ ORDER BY m.seq`, [pageId, generation]);
+}
+
/**
* Open a segmented body. With `pin` the read is the authorized one: the page must still be at the pinned revision (and
* generation), the caller's admission is re-run, and the rows read are that generation's.
+ *
+ * The page row, the manifest rows and (given `expect`, the slug and source the caller already holds) the ledger are
+ * read at once: rows read for another generation than the page row names (a body published between the statements)
+ * are read again, and a ledger read under a name the page row does not carry is read again under its own.
*/
-export async function openSegmentedBody(engine: BrainEngine, opts: { pageId: number; generation?: number; ledger?: BodyLedger; pin?: BodyPin }): Promise<SegmentedBody> {
- const [page] = await engine.executeRaw<Record<string, unknown>>(`SELECT id, source_id, slug, body_storage, body_generation, body_bytes, body_lines, truth_bytes,
- body_flags, segmenter_version, knowledge_revision::text AS revision FROM pages WHERE id=$1`, [opts.pageId]);
+export async function openSegmentedBody(engine: BrainEngine, opts: { pageId: number; generation?: number; ledger?: BodyLedger; pin?: BodyPin;
+ expect?: { slug: string; sourceId: string } }): Promise<SegmentedBody> {
+ const requested = opts.pin?.generation ?? opts.generation ?? null;
+ const [[page], read, expected] = await Promise.all([
+ engine.executeRaw<Record<string, unknown>>(`SELECT id, source_id, slug, body_storage, body_generation, body_bytes, body_lines, truth_bytes,
+ body_flags, segmenter_version, knowledge_revision::text AS revision FROM pages WHERE id=$1`, [opts.pageId]),
+ manifestRows(engine, opts.pageId, requested),
+ opts.ledger || !opts.expect ? undefined : readBodyLedger(engine, opts.expect.sourceId, opts.expect.slug),
+ ]);
if (opts.pin) await checkPin(opts.pin, page, opts.pageId);
- const generation = opts.pin?.generation ?? opts.generation ?? Number(page?.body_generation);
+ const generation = requested ?? Number(page?.body_generation);
// An earlier generation (a segmented version) keeps its manifest rows after the page was demoted to inline storage.
if (!page || (page.body_storage !== 'segmented' && generation === Number(page.body_generation))) throw new Error(`Page ${opts.pageId} is not a segmented page.`);
- const rows = await engine.executeRaw<Record<string, unknown>>(`SELECT m.seq, m.occurrence_id, m.region, m.sha256, m.byte_start, m.byte_len,
- m.line_start, m.line_count, m.static_proj_bytes, m.static_proj_lines, jsonb_array_length(m.outline) AS outline_count,
- jsonb_array_length(m.facts_slots) > 0 AS has_facts, m.date_min IS NOT NULL AS has_date
- FROM page_body_manifest m
- WHERE m.page_id=$1 AND m.staging_id IS NULL AND m.gen_from<=$2 AND (m.gen_to IS NULL OR m.gen_to>$2) ORDER BY m.seq`, [opts.pageId, generation]);
+ const rows = requested === null && Number(read[0]?.generation) !== generation ? await manifestRows(engine, opts.pageId, generation) : read;
const slug = String(page.slug);
const sourceId = String(page.source_id);
const bodyRows = rows.map(r => ({
@@ -194,7 +210,7 @@ export async function openSegmentedBody(engine: BrainEngine, opts: { pageId: num
staticProjLines: Number(r.static_proj_lines), outlineCount: Number(r.outline_count), hasFacts: r.has_facts === true, hasDate: r.has_date === true,
}));
assertRowsTile(bodyRows, { slug, sourceId, total: await generationBodyBytes(engine, { id: opts.pageId, body_generation: page.body_generation, body_bytes: page.body_bytes }, generation) });
- const ledger = opts.ledger ?? await readBodyLedger(engine, sourceId, slug);
+ const ledger = opts.ledger ?? (expected && opts.expect!.slug === slug && opts.expect!.sourceId === sourceId ? expected : await readBodyLedger(engine, sourceId, slug));
return {
pageId: opts.pageId, sourceId, slug, generation, bodyBytes: Number(page.body_bytes ?? 0), bodyLines: Number(page.body_lines ?? 0), truthBytes: Number(page.truth_bytes ?? 0),
flags: (toJson(page.body_flags) ?? {}) as JsonObject, ledger, stale: Number(page.segmenter_version) !== SEGMENTER_VERSION, ...(opts.pin ? { pin: opts.pin } : {}),
@@ -218,17 +234,18 @@ interface LoadedSegment {
mismatch: boolean;
}
-/** The rows' texts and JSON metadata, one text at a time (metadata in batches). */
+/** The rows' texts and JSON metadata, one text at a time (metadata in batches, read alongside the batch's first text). */
async function* loadSegments(engine: BrainEngine, body: SegmentedBody, rows: readonly BodyRow[], stop?: () => void): AsyncIterable<LoadedSegment> {
+ const readText = (row: BodyRow) => { stop?.(); return engine.readSegmentTexts(body.sourceId, [row.sha256]); };
for (let at = 0; at < rows.length; at += HEAVY_BATCH) {
const batch = rows.slice(at, at + HEAVY_BATCH);
- const meta = new Map((await engine.executeRaw<Record<string, unknown>>(`SELECT occurrence_id, entry_state, protected_regions
+ const [first, metaRows] = await Promise.all([readText(batch[0]!), engine.executeRaw<Record<string, unknown>>(`SELECT occurrence_id, entry_state, protected_regions
FROM page_body_manifest WHERE page_id=$1 AND occurrence_id=ANY($2::bigint[]) AND staging_id IS NULL AND gen_from<=$3 AND (gen_to IS NULL OR gen_to>$3)`,
- [body.pageId, batch.map(r => r.occurrenceId), body.generation])).map(m => [Number(m.occurrence_id), m]));
- for (const row of batch) {
- stop?.();
+ [body.pageId, batch.map(r => r.occurrenceId), body.generation])]);
+ const meta = new Map(metaRows.map(m => [Number(m.occurrence_id), m]));
+ for (const [i, row] of batch.entries()) {
const m = meta.get(row.occurrenceId);
- const bytes = (await engine.readSegmentTexts(body.sourceId, [row.sha256])).get(Buffer.from(row.sha256).toString('hex'));
+ const bytes = (i === 0 ? first : await readText(row)).get(Buffer.from(row.sha256).toString('hex'));
if (!m || bytes === undefined) throw projectionStaleError(row.byteStart, 'its manifest row or text is missing');
yield {
row, bytes, entryState: toJson(m.entry_state), protectedRegions: (toJson(m.protected_regions) ?? []) as StoredRegion[],
diff --git a/src/core/search/evidence-delivery.ts b/src/core/search/evidence-delivery.ts
index 371b219fa0..17e88df1cc 100644
--- a/src/core/search/evidence-delivery.ts
+++ b/src/core/search/evidence-delivery.ts
@@ -1263,6 +1263,11 @@ export async function deliverEvidence(
for (const h of g.hits) passthrough.push({ rank: hits.indexOf(h), hit: h, reason: 'long_page_chunk' });
};
+ const unit = plan.unit === 'auto' ? 'page' : plan.unit;
+ const segmentedReads = new Map(groups.flatMap(g => {
+ const page = !fetchFailure && g.reason !== 'long_page' && g.pageId !== null ? pages?.get(g.pageId) : undefined;
+ return page?.segmented ? [[g, planSegmentedBlock(engine, page, g.hits, unit, plan.window, scope.detail !== 'low').catch(() => null)] as const] : [];
+ }));
// C1 date headers: one line per block (passthrough rows included), paid for inside the budget like the title.
const headerFor = plan.dateHeader ? await blockDateHeaders(engine, hits, () => fallbacks.add('date_header_unavailable')) : () => '';
@@ -1287,8 +1292,7 @@ export async function deliverEvidence(
} else {
const page = pages?.get(g.pageId);
if (!page) { dropped.not_readable = (dropped.not_readable ?? 0) + 1; continue; }
- const unit = plan.unit === 'auto' ? 'page' : plan.unit;
- const read = page.segmented ? await planSegmentedBlock(engine, page, g.hits, unit, plan.window, scope.detail !== 'low').catch(() => null) : planBlock(page, g.hits, unit, plan.window, scope.detail !== 'low');
+ const read = page.segmented ? await segmentedReads.get(g)! : planBlock(page, g.hits, unit, plan.window, scope.detail !== 'low');
if (!read && opts.liveHits === false) { dropped.not_readable = (dropped.not_readable ?? 0) + 1; continue; }
b = read ?? fallbackBlock(g.hits[0], g.hits, 'segment_read_failed');
}
diff --git a/src/core/search/segmented-evidence.ts b/src/core/search/segmented-evidence.ts
index 3cbf130908..ba16930d9b 100644
--- a/src/core/search/segmented-evidence.ts
+++ b/src/core/search/segmented-evidence.ts
@@ -24,7 +24,8 @@
* The windows are read at the revision getChunkWindows authorized the page at
* (`page.revision`): a page that changed since (a visibility flip, a new
* body, a delete) refuses the read, and the assembler falls back to the hit's
- * chunk.
+ * chunk. The windows (and the segments unspanned hits are matched in) are read
+ * at once; the revision is confirmed after every read has answered.
*/
import type { BrainEngine } from '../engine.ts';
import type { ChunkWindowPage } from './chunk-windows.ts';
@@ -52,7 +53,7 @@ interface Located extends EvidenceSpan { row: number; text: string }
export async function readSegmentedWindows(engine: BrainEngine, page: ChunkWindowPage,
hits: ReadonlyArray<{ chunk_id: number; chunk_index: number; text: string }>,
opts: { unit: 'window' | 'section' | 'page'; radius: number; includeTimeline: boolean }): Promise<SegmentedWindows> {
- const body = await openSegmentedBody(engine, { pageId: page.page_id, pin: { revision: page.revision } });
+ const body = await openSegmentedBody(engine, { pageId: page.page_id, pin: { revision: page.revision }, expect: { slug: page.slug, sourceId: page.source_id } });
const layout = await projectedLayout(engine, body);
const region = opts.includeTimeline ? undefined : 'truth' as const;
const bytes = region && layout.timelineByte >= 0 ? layout.timelineByte - Buffer.byteLength(TIMELINE_SEPARATOR, 'utf8') : layout.totalBytes;
@@ -72,14 +73,23 @@ export async function readSegmentedWindows(engine: BrainEngine, page: ChunkWindo
const placedBytes = new Map<number, { start: number; end: number }>();
const homes: Array<{ start: number; end: number; chunkIndex: number; row: number }> = [];
- for (const hit of hits) {
- const own = located.find(l => l.id === hit.chunk_id);
- if (own) { homes.push({ ...own, chunkIndex: own.chunk_index }); continue; }
+ const unspanned = (hit: typeof hits[number]) => {
+ if (located.some(l => l.id === hit.chunk_id)) return undefined;
const chunk = page.chunks.find(c => c.id === hit.chunk_id);
const row = chunk && chunk.projected_byte_start == null ? rowAt(chunk.occurrence_id) : undefined;
+ return row !== undefined && hit.text.trim().length >= 16 ? row : undefined;
+ };
+ const segments = await Promise.all(hits.map(hit => {
+ const row = unspanned(hit);
+ return row === undefined ? undefined : readLines(engine, body, region, layout.rowStart[row]!, rowEnd(row), bytes);
+ }));
+ for (const [k, hit] of hits.entries()) {
+ const own = located.find(l => l.id === hit.chunk_id);
+ if (own) { homes.push({ ...own, chunkIndex: own.chunk_index }); continue; }
+ const row = unspanned(hit);
const needle = hit.text.trim();
- if (row !== undefined && needle.length >= 16) {
- const segment = (await readLines(engine, body, region, layout.rowStart[row]!, rowEnd(row), bytes)).bytes.toString('utf8');
+ if (row !== undefined) {
+ const segment = segments[k]!.bytes.toString('utf8');
const at = segment.indexOf(needle);
if (at >= 0 && segment.lastIndexOf(needle) === at) {
const start = layout.rowStart[row]! + Buffer.byteLength(segment.slice(0, at), 'utf8');
@@ -109,8 +119,8 @@ export async function readSegmentedWindows(engine: BrainEngine, page: ChunkWindo
const runs: SegmentedWindows['runs'] = [];
const placed: SegmentedWindows['placed'] = new Map();
- for (const w of merged) {
- const read = await readLines(engine, body, region, w.start, w.end, bytes);
+ const reads = await Promise.all(merged.map(w => readLines(engine, body, region, w.start, w.end, bytes)));
+ for (const read of reads) {
const runEnd = read.start + read.bytes.length;
if (read.bytes.length === 0) continue;
const text = read.bytes.toString('utf8');
diff --git a/test/large-pages/segmented-evidence-pipelining.test.ts b/test/large-pages/segmented-evidence-pipelining.test.ts
new file mode 100644
index 0000000000..1a1a629ca4
--- /dev/null
+++ b/test/large-pages/segmented-evidence-pipelining.test.ts
@@ -0,0 +1,116 @@
+/**
+ * Evidence on segmented pages costs as few round trips in series as the pin allows.
+ *
+ * 1. Protects: one segmented page's evidence read issues its manifest rows and withdrawal ledger before the page row
+ * answers, and the batch's segment metadata before its first segment text answers; the pin confirm still starts
+ * only after every segment read answered. Several segmented hits are read at once, not one page after another.
+ * 2. Fails when: openSegmentedBody waits for the page row before reading rows or the ledger, loadSegments waits for
+ * the metadata before the first text, the confirm runs alongside a read, or deliverEvidence plans segmented pages
+ * one after another again. Each statement in series is a round trip of wall time on a pooled Postgres.
+ * 3. Existing coverage: test/large-pages/segmented-evidence.test.ts pins what the windows hold and
+ * test/large-pages/pinned-segmented-reads.test.ts that a raced read is refused; neither pins when statements run.
+ * 4. Seam: none. Statement start and finish are observed on the PGLite handle the engine uses (one connection, so a
+ * statement issued before another one answered was issued concurrently).
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';
+import { operations, type OperationContext } from '../../src/core/operations.ts';
+import { openSegmentedBody } from '../../src/core/page-body/read-range.ts';
+import { readBodyLedger } from '../../src/core/page-body/segment-ledger.ts';
+import { conversationPage } from '../helpers/conversation-page.ts';
+import { importSegmented } from '../helpers/segmented-privacy-fixture.ts';
+
+const PAGE_BYTES = 1536 * 1024;
+const assemble = operations.find(o => o.name === 'assemble_evidence')!;
+let engine: PGLiteEngine;
+const events: Array<{ at: 'start' | 'end'; sql: string; params: unknown[] }> = [];
+const pages: Record<string, { id: number; chunk: number }> = {};
+
+const ctx = (): OperationContext => ({ engine, config: {}, logger: { info() {}, warn() {}, error() {} }, dryRun: false, remote: true, sourceId: 'default',
+ emitResponseMeta: () => {} } as unknown as OperationContext);
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ for (const [slug, word, seed] of [['chat/pipeline-a', 'zzpipelinealpha', 3], ['chat/pipeline-b', 'zzpipelinebeta', 5]] as const) {
+ const id = await importSegmented(engine, slug, conversationPage(PAGE_BYTES, { seed, needles: [{ at: 0.6, word }] }));
+ const [hit] = await engine.executeRaw<{ id: number }>('SELECT id FROM content_chunks WHERE page_id=$1 AND strpos(chunk_text, $2) > 0 ORDER BY chunk_index LIMIT 1', [id, word]);
+ pages[slug] = { id, chunk: Number(hit!.id) };
+ }
+ const db = engine.db as unknown as { query: (sql: string, ...rest: unknown[]) => Promise<unknown> };
+ const query = db.query.bind(db);
+ db.query = (sql: string, ...rest: unknown[]) => {
+ const text = sql.replace(/\s+/g, ' ').trim();
+ const params = Array.isArray(rest[0]) ? rest[0] as unknown[] : [];
+ events.push({ at: 'start', sql: text, params });
+ return query(sql, ...rest).finally(() => events.push({ at: 'end', sql: text, params }));
+ };
+}, 600_000);
+
+afterAll(async () => { await engine?.disconnect(); });
+
+type Match = (e: { sql: string; params: unknown[] }) => boolean;
+const first = (at: 'start' | 'end', match: Match) => events.findIndex(e => e.at === at && match(e));
+const last = (at: 'start' | 'end', match: Match) => events.findLastIndex(e => e.at === at && match(e));
+const onPage = (prefix: string, id: number): Match => e => e.sql.startsWith(prefix) && Number(e.params[0]) === id;
+const OPEN = 'SELECT id, source_id, slug, body_storage, body_generation';
+const ROWS = 'SELECT m.seq, m.occurrence_id';
+const META = 'SELECT occurrence_id, entry_state, protected_regions';
+const CONFIRM = 'SELECT slug, body_generation, knowledge_revision::text AS revision';
+const isText: Match = e => e.sql.includes('FROM page_segment_texts');
+const isLedger = (slug: string): Match => e => e.sql.startsWith('WITH chosen AS') && e.params[0] === slug;
+
+async function evidence(slugs: string[]) {
+ events.length = 0;
+ const out = await assemble.handler(ctx(), { hits: slugs.map(slug => ({ source_id: 'default', slug, chunk_id: pages[slug]!.chunk })), return_unit: 'window', return_window: 2,
+ token_budget: 30_000 }) as { results: Array<{ slug: string; chunk_text: string; delivered: { unit: string } }> };
+ return out.results;
+}
+
+describe('segmented evidence reads (PGLite)', () => {
+ test('one page: rows and ledger are issued with the page row, metadata with the first text, and the pin confirm after every read', async () => {
+ const results = await evidence(['chat/pipeline-a']);
+ expect(results.map(r => [r.slug, r.delivered.unit, r.chunk_text.includes('zzpipelinealpha')])).toEqual([['chat/pipeline-a', 'window', true]]);
+ const { id } = pages['chat/pipeline-a']!;
+ const openEnd = first('end', onPage(OPEN, id));
+ expect(openEnd).toBeGreaterThan(-1);
+ expect(first('start', onPage(ROWS, id))).toBeGreaterThan(-1);
+ expect(first('start', onPage(ROWS, id))).toBeLessThan(openEnd);
+ expect(first('start', isLedger('chat/pipeline-a'))).toBeGreaterThan(-1);
+ expect(first('start', isLedger('chat/pipeline-a'))).toBeLessThan(openEnd);
+ expect(first('start', onPage(META, id))).toBeGreaterThan(-1);
+ expect(first('start', onPage(META, id))).toBeLessThan(first('end', isText));
+ expect(first('start', isText)).toBeLessThan(first('end', onPage(META, id)));
+ const confirmStart = first('start', onPage(CONFIRM, id));
+ expect(confirmStart).toBeGreaterThan(last('end', isText));
+ expect(confirmStart).toBeGreaterThan(last('end', onPage(META, id)));
+ expect(confirmStart).toBeGreaterThan(last('end', onPage(ROWS, id)));
+ expect(confirmStart).toBeGreaterThan(last('end', isLedger('chat/pipeline-a')));
+ }, 120_000);
+
+ test('two pages: the second page is opened before the first page is confirmed', async () => {
+ const results = await evidence(['chat/pipeline-a', 'chat/pipeline-b']);
+ expect(results.map(r => [r.slug, r.delivered.unit])).toEqual([['chat/pipeline-a', 'window'], ['chat/pipeline-b', 'window']]);
+ expect(results[0]!.chunk_text).toContain('zzpipelinealpha');
+ expect(results[1]!.chunk_text).toContain('zzpipelinebeta');
+ const [a, b] = [pages['chat/pipeline-a']!.id, pages['chat/pipeline-b']!.id];
+ const opened = (id: number) => first('start', onPage(OPEN, id));
+ const confirmed = (id: number) => first('end', onPage(CONFIRM, id));
+ expect(Math.min(opened(a), opened(b))).toBeGreaterThan(-1);
+ expect(Math.max(opened(a), opened(b))).toBeLessThan(Math.min(confirmed(a), confirmed(b)));
+ }, 120_000);
+
+ test('a ledger read under a name the page row does not carry is read again under its own', async () => {
+ const { id } = pages['chat/pipeline-a']!;
+ await engine.executeRaw("INSERT INTO fact_withdrawals (source_id, visibility, subject, fact_hash) VALUES ('default', 'world', 'chat/pipeline-a', gbrain_fact_fingerprint('zz withdrawn claim')) ON CONFLICT DO NOTHING");
+ try {
+ const own = await readBodyLedger(engine, 'default', 'chat/pipeline-a');
+ expect(own.withdrawals.length).toBeGreaterThan(0);
+ const body = await openSegmentedBody(engine, { pageId: id, expect: { slug: 'chat/pipeline-b', sourceId: 'default' } });
+ expect(body.ledger).toEqual(own);
+ } finally {
+ await engine.executeRaw("DELETE FROM fact_withdrawals WHERE subject='chat/pipeline-a'");
+ }
+ }, 120_000);
+});