Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(large-pages): segment-table RLS, writer gate segment-reader marks, remote get_page size (PR2 fix lane B)

garrytan56b7cd222b16
diff --git a/docs/ENGINES.md b/docs/ENGINES.md
index d8c9b7ff78..07f53090df 100644
--- a/docs/ENGINES.md
+++ b/docs/ENGINES.md
@@ -249,6 +249,67 @@ run under the role default and are not backstopped per caller. This is layer 2;
the app-layer source filters remain layer 1 and stay mandatory. Behavioral pins
live in `test/postgres-engine-rls-scope.test.ts`.
+**Segmented page tables.** A page over 1 MiB stored in segments (`pages.segmented_storage`)
+keeps its text in `page_segment_texts`, its layout and headings in
+`page_body_manifest`, uploads in progress in `page_body_stagings` /
+`page_body_staging_parts`, and view sizes in `page_view_digests`. gbrain
+enables RLS on all five on every schema replay, as it does on `pages` and
+`content_chunks`, so with no policy a role that does not bypass RLS reads no row
+of them. Title search, the source-scoped vector scan, the chunk windows search
+reads around its hits and get_page check chunks against `page_body_manifest`
+(inline pages included), so a restricted read role needs `SELECT` on it; without
+it those reads fail with `permission_denied` (42501). Grant it together with
+these policies, never with an open one, or the role reads every source's segment
+text. A scoped role then sees exactly the segment rows of its sources:
+
+<!-- gbrain:segmented-rls-recipe:begin (applied verbatim by test/e2e/segmented-rls-scope.test.ts) -->
+```sql
+-- The pages_scope_filter predicate, on each table's own source_id.
+CREATE POLICY page_segment_texts_scope_filter ON page_segment_texts
+ USING (current_setting('app.scopes', true) = '*'
+ OR source_id = ANY(string_to_array(current_setting('app.scopes', true), ',')));
+CREATE POLICY page_body_manifest_scope_filter ON page_body_manifest
+ USING (current_setting('app.scopes', true) = '*'
+ OR source_id = ANY(string_to_array(current_setting('app.scopes', true), ',')));
+CREATE POLICY page_body_stagings_scope_filter ON page_body_stagings
+ USING (current_setting('app.scopes', true) = '*'
+ OR source_id = ANY(string_to_array(current_setting('app.scopes', true), ',')));
+-- Search joins sources; a scoped role sees its own.
+CREATE POLICY sources_scope_filter ON sources
+ USING (current_setting('app.scopes', true) = '*'
+ OR id = ANY(string_to_array(current_setting('app.scopes', true), ',')));
+-- No source_id of their own: visible exactly when their staging or page is
+-- (the pages policy filters the subquery). content_chunks holds every page's
+-- chunk text, segmented or not.
+CREATE POLICY page_body_staging_parts_scope_filter ON page_body_staging_parts
+ USING (current_setting('app.scopes', true) = '*'
+ OR EXISTS (SELECT 1 FROM page_body_stagings s WHERE s.id = staging_id));
+CREATE POLICY page_view_digests_scope_filter ON page_view_digests
+ USING (current_setting('app.scopes', true) = '*'
+ OR EXISTS (SELECT 1 FROM pages p WHERE p.id = page_id));
+CREATE POLICY content_chunks_scope_filter ON content_chunks
+ USING (current_setting('app.scopes', true) = '*'
+ OR EXISTS (SELECT 1 FROM pages p WHERE p.id = page_id));
+
+-- A read role that searches and reads pages. The other tables it reads
+-- (config, timeline_entries, facts, ...) need policies of their own.
+GRANT SELECT ON pages, content_chunks, page_body_manifest, page_segment_texts,
+ page_view_digests, sources TO <reader-role>;
+
+-- If the runtime role OWNS these tables, as for pages:
+ALTER TABLE page_segment_texts FORCE ROW LEVEL SECURITY;
+ALTER TABLE page_body_manifest FORCE ROW LEVEL SECURITY;
+ALTER TABLE page_body_stagings FORCE ROW LEVEL SECURITY;
+ALTER TABLE page_body_staging_parts FORCE ROW LEVEL SECURITY;
+ALTER TABLE page_view_digests FORCE ROW LEVEL SECURITY;
+ALTER TABLE content_chunks FORCE ROW LEVEL SECURITY;
+```
+<!-- gbrain:segmented-rls-recipe:end -->
+
+A role whose reads do not run through the scoped helper is scoped by its own
+default (`ALTER ROLE <reader-role> SET app.scopes = 'source-a,source-b'`). The
+policies read `app.scopes` only; the app-layer source filters stay layer 1.
+
**In engine-sql.** A read in a migrated domain takes a `ScopedRead` when it
runs through this helper and a `LegacyUnscopedRead` when it runs on the pool
(`src/core/engine-sql/brands.ts`); the engine obtains the branded executor, so
diff --git a/docs/architecture/key-files/core-persistence.md b/docs/architecture/key-files/core-persistence.md
index c97f2c198c..032aecd909 100644
--- a/docs/architecture/key-files/core-persistence.md
+++ b/docs/architecture/key-files/core-persistence.md
@@ -14,7 +14,7 @@ Managed facts extraction (withdrawn-candidate skip and recovery, conversation fa
- `src/core/persistence/git-durability-policy.ts` + `git-durability-administration.ts` — whether the persistence owner commits and pushes page writes through its Git effect is a per-host-binding setting (#5182): `persistence_host_bindings.git_durability` (`enabled` | `disabled` | NULL, migration v234, column SQL kept out of the replayed schema blob as `PERSISTENCE_GIT_DURABILITY_COLUMN_SQL`). `gitDurabilityPolicy(binding, root)` is tri-state and fail-closed: a recorded value wins, NULL falls back to the legacy post-commit-hook probe, a probe error fails the effect instead of skipping it; `effects.ts` takes its per-root verdict from it. `gitDurabilityState` renders `on`/`off`/`unknown` for `writer status` and `writer activate`'s `git_durability` listing. `planGitDurabilityCatchUp`/`requeueGitDurabilityCatchUp` re-queue the Git effects completed `durability_not_enabled` while the setting was off by resetting the existing rows, never inserting under `UNIQUE(request_id, kind)`. The verb `writer_git_durability` (`gbrain sources writer git-durability <source> --enable|--disable [--pat-file <path>] [--dry-run]`, administration-gated like the other writer verbs) runs a read-only `git push --dry-run` probe before enabling (codes `git_branch_unborn`, `git_checkout_required`, `git_detached_head`), wires the repo-scoped credential under `gbrain.durability.managedcredential` from a 0600 `--pat-file` (`pat_file_unreadable` otherwise) and retries the worktree's parked pushes. `sources push` (`managedPushRefusal` in `workspace-push.ts`), `bootstrap verify`'s `checkPushProbe` and the skill-pack writer guard name this route on a managed worktree (#5606). Pinned by `test/persistence-admin-git-durability.test.ts`, `test/managed-push-remedy.serial.test.ts`.
- `src/core/persistence/deactivation.ts` — private CLI `sources writer deactivate` (#5455/#5628), brain-wide and trusted-local. `deactivationBlockers` lists the admin lock, queued/running/recovering requests, recovering topology changes, uncommitted effects, held connector items (managed holds that classic mode would not read) and live `gbrain_cycle_locks` leases, each with its CLI exit; `physicalRootBlockers(engine, mode)` (#5914 [R9a]) adds `physical_root` for this host's owned checkouts, probed as the mode's real run will: strict `assertPhysicalRoot` for managed, `assertPhysicalRootReservation` for the classic pre-activation release, so each preview lists exactly what its real operation refuses on; `--dry-run` returns them plus the worktrees that would retire, the kept shared-skill settings and, when clean, `apply_command` bound to the admin state read before the preview. `deactivatePersistence` takes the local native worktree locks, then in one transaction locks `persistence_brain FOR UPDATE`, checks the expected admin state and the admin lock, locks worktrees then sources `FOR UPDATE` (admission's order), rechecks the blockers, sets `enabled=false`, increments `mode_epoch`, retires every worktree, deletes source and host bindings and records a committed `writer_deactivate` topology change (brain id, retired epoch, retired worktree ids and roots, source roots). `cleanupRetiredManagedMarkers` runs on CLI connect, after deactivate and from `writer status`: it removes this brain's registry records, `.gbrain-managed` / Git `gbrain-managed.json`, `.gbrain-owner.json` and reservations only when their `mode_epoch` is a retired one below the current epoch, or, without an epoch, their worktree id (or, for markers without one, their root outside any active binding) is recorded as retired; unknown or newer epochs are kept and reported `pending`, each file is re-read before unlinking and other brains' files are never touched. `root-registry.ts` writes `mode_epoch` into new registry records and managed markers. Tests: `test/persistence-deactivate.test.ts` (PGLite and Postgres), `test/e2e/persistence-deactivate-race.test.ts`. See [persistence stalls](persistence-stalls.md).
-- `src/core/persistence/{admin-lock,blocking-effects,writer-versions}.ts` — `admin-lock.ts` owns the opt-in brain-level writer admin lock: reserved config key `persistence.writer_admin_lock` (`{locked, set_at, host_id, generation}`), written only by local `gbrain sources writer lock|unlock` under the `persistence_brain` row `FOR UPDATE`; lock refuses while a prepared transfer is unaccepted. `assertWriterAdminUnlocked` runs inside the claim, managed claim, activation, shared-skill activation and transfer prepare/accept transactions for every caller (share lock on the brain row) and refuses with `writer_admin_locked`; only the ordinary first-write auto-claim (`claimWorktree(..., { automatic: true })` from page and memory mutations) is exempt. Generic `config set`/`unset`/`unset --pattern` refuse the key; engine migration copies it. It is not a security boundary and older binaries ignore it. `blocking-effects.ts` lists queued, running or recovering effects (`listBlockingEffects`) and builds `writer_not_quiesced` suggestions naming the first blocking request or effect with `gbrain sources writer status <source> --json`. `writer-versions.ts` stamps admitter version/host at admission and consumer version/host/`published_at` only on committed publication (migration 178, cutoff `persistence_brain.writer_version_cutoff` on the database clock); replay and compaction keep stamps. `sources writer status` reports `admin_lock`, `local_host_id`, `blocking_effects` and `writer_versions`; `src/commands/doctor/checks/writer-version.ts` is the seven-day `writer_version` advisory. `SEGMENTED_WRITER_FLOOR`: a seven-day writer below it keeps `pages.segmented_storage` off (`page-body/limits.ts`, doctor `segmented_storage`). Tests: `test/persistence-writer-admin-lock.test.ts`, `test/persistence-writer-versions.test.ts`, `test/persistence-blocking-effects.test.ts`, `test/e2e/persistence-writer-{admin-lock,stamps}.test.ts`.
+- `src/core/persistence/{admin-lock,blocking-effects,writer-versions}.ts` — `admin-lock.ts` owns the opt-in brain-level writer admin lock: reserved config key `persistence.writer_admin_lock` (`{locked, set_at, host_id, generation}`), written only by local `gbrain sources writer lock|unlock` under the `persistence_brain` row `FOR UPDATE`; lock refuses while a prepared transfer is unaccepted. `assertWriterAdminUnlocked` runs inside the claim, managed claim, activation, shared-skill activation and transfer prepare/accept transactions for every caller (share lock on the brain row) and refuses with `writer_admin_locked`; only the ordinary first-write auto-claim (`claimWorktree(..., { automatic: true })` from page and memory mutations) is exempt. Generic `config set`/`unset`/`unset --pattern` refuse the key; engine migration copies it. It is not a security boundary and older binaries ignore it. `blocking-effects.ts` lists queued, running or recovering effects (`listBlockingEffects`) and builds `writer_not_quiesced` suggestions naming the first blocking request or effect with `gbrain sources writer status <source> --json`. `writer-versions.ts` stamps admitter version/host at admission and consumer version/host/`published_at` only on committed publication (migration 178, cutoff `persistence_brain.writer_version_cutoff` on the database clock); replay and compaction keep stamps. `sources writer status` reports `admin_lock`, `local_host_id`, `blocking_effects` and `writer_versions`; `src/commands/doctor/checks/writer-version.ts` is the seven-day `writer_version` advisory. `SEGMENTED_WRITER_FLOOR`: a seven-day writer below it or unmarked keeps `pages.segmented_storage` off (`page-body/limits.ts`, doctor `segmented_storage`). Tests: `test/persistence-writer-admin-lock.test.ts`, `test/persistence-writer-versions.test.ts`, `test/persistence-blocking-effects.test.ts`, `test/e2e/persistence-writer-{admin-lock,stamps}.test.ts`.
- `src/core/persistence/{atom-maintenance,atom-retry,page-prepare,facts-maintenance,facts-prepare,prepared-maintenance}.ts` — resident dispatch for durable atom publication/completion, explicit atom retry (`retryManagedAtomBatch` takes the job's signal and deadline, stops between stages on caller cancel, deadline or cycle-lock loss, shares one deadline-bound `MaintenanceWriteWait` with the model rerun, and reports a stop after admission as `write_pending` or an `AbortError` carrying the receipts, never `cancelled`; #6622), authorized multi-entity fact-fence/backstop append, local synthesize/patterns/consolidation, and the cycle's lint repairs on a managed brain (`runLintCore` publishes each fix through `maintenancePreflight` + `publishMaintenancePage`; #5180, `test/managed-lint.test.ts`). `page-prepare.ts` exports `fileMatchesSnapshot`, the canonical file-versus-page comparison `prepareFileTarget` applies, so lint can bind a repair to the revision it read (it takes the importer's path for the file: a frontmatter-less file under a directory-inference rule also matches when `readCanonicalAsImported` (BOM strip + `applyInference` at `scannerSourcePath`) reproduces the stored row, with an inferred type treated as undeclared, #6605; reconcile reads the file side through `reconcileFileReading` in `reconcile-state.ts`); the uncoordinated-local-edit refusal carries detail `file_database_drift` and a `sources reconcile <src> <slug> --brain host --preview` fix; a shared-origin delete: canonical-reconciliation.md. In `prepareFileTarget`, a live page whose canonical file is missing refuses `source_changed` unless it is declared or derive-phase database-only, or it is a `delete_page` (`deleting`, no content) of a page with no recorded `source_path` and no captured file URI: that delete plans no file, so it publishes database-only and its receipt reports no file or Git effect (`test/persistence-captured-file-target.test.ts`, `test/persistence-never-published-delete.test.ts`). `atomOwnerTarget` is the one owner decision for an atom session and for `atomDrainOwnerRefusal`, the auto-drain dispatch pre-check; an unbound Google/GitHub source publishes atom maintenance through the `connector_database` target (its `local_path` is connector state, not a checkout) and the publication refuses with `source_changed` when the source gained an owner after preflight. `submitMaintenance` scans every content-carrying intent with `scanCanonicalFences` (the check the canonical projection runs) over the whole submitted body and timeline before a request exists (#6278): a defect no adoption clears (a second facts fence in the timeline; `replaceOrInsertFactsFence` replaces only the first) is refused with its fence reason, so `fenceManaged` reports the page in `failed_pages` and the others still adopt, while a repair whose postimage is clean passes. `prepareFactFenceAdoption` names its steps for `enterClaimStep`, compares the fence cell with the legacy fact modulo whitespace, writes the cell's parsed text back into `facts.fact` in the same `UPDATE` that sets `row_num` (so the projection keeps the fact's id), and throws the registered `fence_unrenderable` (class `server`) as its last-line defence. `maintenancePreflight` creates the job's `MaintenanceWriteWait` (optional `deadlineAtMs`) and `submitMaintenance` uses it for new and replayed requests; its owner check goes through `checkOwner` / `ownerUnavailableError` (`owner-refusal.ts`), so a missing binding, a changed incarnation, another owner host, a draining or recovering worktree and a missing local or coordination path each refuse `owner_unavailable` with their own `reason`, and nothing claims or transfers ownership to get past them. #6325: `resumeManagedAtoms` returns `run | done | held`. The drain does not replay a failed batch: it resumes the next automatic attempt, whose run key is `digest([drainKey, failedRequestId, 'automatic'])` (one stable id per failure, so a crashed attempt resumes and two runs admit the same requests), and whose completion advances the failed drain-key checkpoint by the same compare-and-set an explicit retry uses. The completion counts one strike per completed failure on that checkpoint (`attempts`); at `MAX_DETERMINISTIC_FAILURES` it sets `held`, which `MANAGED_ATOM_DISCOVERY_SQL` excludes from discovery and the backlog and `listHeldManagedAtoms` reports (doctor `extract_atoms_held_failed`, code `held_failed`). Reading a held or failed checkpoint never strikes; storage, authority and conflict errors fail the attempt without completing it, so they never strike either. A content change is a new drain key, so the count starts over. An explicit retry (`session.retry`) ignores `held`, and its failure refusal (`extraction_failed`) names the recorded failure reason (malformed output or a response stopped before the end) and carries a paid `fix` (`gbrain jobs submit extract-atoms-drain --params '{sourceId, retryRequestId}'`) with a read-only `gbrain write-request` verify; the drain raises it only for a failed batch whose checkpoint is gone. Tests: `test/managed-atoms-retry.test.ts`. Managed facts extraction (the withdrawn-candidate skip and its recovery route, the conversation facts batches, the unmanaged derived index) continues in [Core Persistence (managed facts)](core-persistence-facts.md).
- `src/core/persistence/maintenance-wait.ts` — how long a maintenance publisher waits for its accepted write to commit before the receipt reports `write_pending` (#5854). `MAINTENANCE_WRITE_WAIT_MS` is 30 s; `MaintenanceWriteWait` is one budget per job: each wait is capped by the job's remaining deadline (zero at or past it), and once one publish is still pending after its wait (`observe`) every later publish in that job waits zero and is deferred like it. A pending write keeps its request identity and commits later; it is never reported as committed. A `MaintenanceWriteWait` with no deadline also sets the replay window of a subagent tool write whose job has none (`minions/tool-write-identity.ts`). `__setMaintenanceWriteWaitForTests` replaces the base wait, those tool writes included. Tests: `test/maintenance-write-wait.test.ts`, `test/e2e/maintenance-write-wait.test.ts`.
diff --git a/docs/architecture/key-files/core-services-2-continued.md b/docs/architecture/key-files/core-services-2-continued.md
index f27ff64954..5d42de3a45 100644
--- a/docs/architecture/key-files/core-services-2-continued.md
+++ b/docs/architecture/key-files/core-services-2-continued.md
@@ -17,7 +17,7 @@ The page-state concurrency foundation under `src/core/page-state/` and the share
- `src/core/progressive-batch/` — shared ramp-up + cost-cap + verification primitive (trial 10 → ramp 100 → ramp 500 → full, with verification at each stage), with verifier+policy injection (callers describe HOW TO MEASURE SUCCESS, not WHEN TO WAIT FOR CTRL-C). Modules: `types.ts` (Stage, StageVerdict, AbortReason, discriminated `Verifier` union `OutputCountVerifier | IdempotentMutationVerifier | NoopVerifier`, Policy, StageReport), `orchestrator.ts` (`runProgressiveBatch(items, verifier, policy, runner)` — reads `getCurrentBudgetTracker()` ahead of `Policy.maxCostUsd` fail-closed; null both ways triggers `abort_cost_cap reason='no_budget_safety_net'`), `audit.ts` (ISO-week JSONL at `~/.gbrain/audit/progressive-batch-YYYY-Www.jsonl` via the shared `audit-writer` primitive), `stage-report.ts` (ASCII formatter for the default `Policy.onStageReport`). Env knobs: `GBRAIN_PROGRESSIVE_BATCH_DISABLED=1`, `GBRAIN_PROGRESSIVE_BATCH_AUTO=1` (skip Ctrl-C grace), `GBRAIN_PROGRESSIVE_BATCH_STAGES=10,100,500`. Sites that "jump straight to full" stay that way by default; ramp is opt-in per-site via `Policy.interactiveAbortMs > 0`. Pinned by `test/progressive-batch/orchestrator.test.ts` (35 cases, every verdict path).
- `src/core/page-body/page-shape.ts` — Wave B PR 1 (spec 1.5): segmented page bodies are unreachable as strings. `guardSegmentedBody` (called by `rowToPage` for a row with `body_storage = 'segmented'`, so by every snapshot and `getPage` read) replaces `compiled_truth` / `timeline` with enumerable getters and setters that throw `page_body_segmented`, so property reads, spread, `JSON.stringify`, `structuredClone` and assignment all fail loud instead of seeing an empty body. `isSegmentedPage`, `assertInlineBody(page, site)` (explicit refusal where a writer would otherwise act before a getter fires, e.g. SQL-only writers; every `page_body_segmented` refusal's fix reads the page with `get_page body: 'auto'`), `pageBodyBytes(page)` (`body_bytes` for segmented pages) and `pageBodySegmentedError`. `bodyUnread(page)` says a segmented page's body was not read back as strings (over the single-string ceiling, see `materializedPage`); such a body was written by the streamed import, which holds fenced files, so `fenceBody(page)` reads it as empty for the fence merges and `withoutBody(page)` copies the page's other fields for a render whose body comes from the incoming write (a shrunk file rewrites such a page: `test/large-pages/segmented-shrink-below-ceiling.test.ts`). `Page` stays one shape (`body_storage?`, `body_bytes?`); the static half is `scripts/check-page-body-readers.ts` with `scripts/page-body-readers-baseline.tsv` (docs/TESTING.md#page-body-readers). Pinned by `test/large-pages/segmented-body-unreachable.test.ts`.
-- `src/core/page-body/limits.ts` — Wave B size classes, ceilings, retention numbers and config keys in one place. `readPageBodyPolicy` is the single question every write asks: `segmented` is the effective `pages.segmented_storage` (unset means `SEGMENTED_STORAGE_DEFAULT`, `off` in this release; `off` or an unrecognized value is off; held off while `segmentedWriterBlockers` finds a recent writer below `SEGMENTED_WRITER_FLOOR`, 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. Tests: `test/large-pages/segmented-switch.test.ts`.
+- `src/core/page-body/limits.ts` — Wave B size classes, ceilings, retention numbers and config keys in one place. `readPageBodyPolicy` is the single question every write asks: `segmented` is the effective `pages.segmented_storage` (unset means `SEGMENTED_STORAGE_DEFAULT`, `off` in this release; `off` or an unrecognized value is off; held off while `segmentedWriterBlockers` finds a recent writer that blocks, and an unreadable gate counts as blocked), `maxBytes` the engine ceiling (256 MiB Postgres, 128 MiB PGLite, lowered by `pages.max_bytes`) while on and `PAGE_MAX_BYTES` while off. Config is read per call; only the writer gate is cached (`SEGMENTED_WRITER_GATE_TTL_MS`, `_resetSegmentedWriterGateForTests`). `chooseBodyStorage` applies the 1 MiB / 512 KiB hysteresis. The writer gate (`segmentedGateWriters` in `persistence/writer-versions.ts`) reads seven days of admitted requests in any state, committed publications, `ingest_log` rows and, on Postgres, `persistence_consumers` heartbeats; a row blocks when its version is below `SEGMENTED_WRITER_FLOOR` or unparsable, or when it lacks the segment-reader mark (migration v251: `admitter_segment_reader`, `consumer_segment_reader`, `persistence_consumers.segment_reader`, `ingest_log.writer_segment_reader`), because releases 0.60.252.0-0.60.262.0 have no segment readers and a version string cannot tell them apart. Not seen: an older binary's unmanaged single-page write, a run that dies before it logs, and read-only or export use. Tests: `test/large-pages/segmented-switch.test.ts`.
- `src/core/page-body/read-range.ts` + `segment-projection.ts` + `segment-ledger.ts` — Wave B PR 2 (spec 7.1, 7.3): the segment reader. `openSegmentedBody` reads a page's live manifest rows and its withdrawal ledger (`readBodyLedger`); `readBodyRange(engine, { pageId, space, start, end, audience, region?, body? })` streams pieces one segment text at a time, never the whole body. Remote reads and every projected-space read serve the read projection: `projectSegment` projects whole segments from their stored protected regions (takes, truncated tail and markers out, keys as the projection token, facts regions rendered world-only and credential-projected), after the withdrawal overlay (`overlaySegmentText`; a fence split by a forced cut is omitted for reads and refuses a trusted read) and the fence overlay (held and purged rows out, rows below the page tier in the low-tier block after the truth). A transform or stale metadata recomputes the regions from the segment's entry state; with none usable the read refuses `page_projection_stale`, never raw text. Trusted stored-space reads give the overlaid stored stream. `projectedLayout` (cached on the handle), `projectedUnits` (rows and fixed text in projected order, for `page-window/segmented.ts`), `projectedTotals`, `projectedLineStart` and `projectedOutline` (outline from stored metadata, no segment text) locate projected bytes; the concatenation equals `projectPageText` of the joined body byte for byte except where a facts fence is longer than a segment (shows less). The chunker (`segment-chunks.ts`) chunks the same projection, so sealed segmented pages carry `MARKDOWN_CHUNKER_VERSION`; `sealSegmentedPage` indexes the overlaid, sanitized timeline lead. Pinned by `test/large-pages/projection-parity.test.ts`, `remote-window-privacy.test.ts` and `sealed-segmented-search.test.ts` (fixture `test/helpers/segmented-privacy-fixture.ts`).
- `src/core/page-body/segment-rewrite.ts` — fence rewrites of a segmented body without holding it as one string (forget strikes, purge drops). Only stored `facts`/`takes` protected regions are decoded and passed, in body order with their region, to a `FenceTransform` (a region crossing forced cuts is joined with its neighbours, refused above `PAGE_MAX_BYTES`). `rewriteLiveSegmentedFences` re-stages the live body through `prepareSegmentedBody` from the segment stream with the changed units replaced and flips it in the caller's transaction (trust tier and soft delete kept; null when nothing changed); `rewriteSegmentedGeneration` rebuilds one retained generation under its own number and updates its versions' hash and size; `rewrittenContentHash` streams the hash of a rewritten generation; `segmentedBodyContains` searches a body segment by segment with the previous segment's tail carried over. Tests: `test/large-pages/purge-segments.test.ts`, `forget-scope.test.ts`, `page-purge-segments.test.ts`.
- `src/core/page-body/segment-blocks.ts` + `segment-links.ts` + `segment-takes.ts` — Wave B PR 2 (spec 8, full-pass mode): the derived passes over a segmented body, O(page) work and O(segment) memory, not yet incremental. `bodyBlocks(engine, page, { regions?, separator?, want? })` yields the trusted, withdrawal-overlaid joined body one block at a time (a segment, or a run joined across forced cuts, refused above `BLOCK_MAX_BYTES` with `page_body_segmented`; `want` skips a run unread), so each block starts where the parsers start fresh; `truthLead` reads a bounded lead; `readGarbageCollector` forces a collection every 4 MiB read; `detachedValue` copies a result kept past its block so it pins no segment text; `segmentedPassWork` counts the passes' work for the linearity test. `extractSegmentedPageLinks` runs `extractBodyLinks` over each block in a window (`bodyWindows`: the whole blocks before it, 4096 chars after, the headings still open), with the role phrases a first pass found (`segmentedRoleText`), and merges candidates in `extractPageLinks` order, plus the temporal inputs (`TemporalBody`). `parseTakesFenceBlocks` gives `parseTakesFence` of the joined body. Consumers: link preparation and the links effect, stale-links maintenance, source reconciliation, the sweep, `extract links|timeline|takes --source db`, the mention pass (`pageMentions`), the canonical prior view (`segmentedPriorView`), `segmentedTimelineText`, the chronicle judge and the facts planner (`planSegmentedExtraction`). Tests: `test/large-pages/segmented-derived-parity.test.ts`, `segmented-derived-passes.test.ts`, `segmented-derived-linear.test.ts`, `segmented-derived-memory.slow.test.ts`, `segmented-derived-work.test.ts`. `segment-lines.ts` serves the line-local maintenance scans: `bodyLines` yields the joined text's complete lines a block at a time (a line cut by a block boundary is carried, counted in `segmentedPassWork.carry`), consumed by `gbrain integrity` and `reconcile-links`; `segmentedRegionContains` searches one region for literal markers across block boundaries (repair `connector-fences`). Test: `test/large-pages/segmented-maintenance-commands.test.ts`.
diff --git a/llms-full.txt b/llms-full.txt
index fda85578b5..0f57c54e5a 100644
--- a/llms-full.txt
+++ b/llms-full.txt
@@ -5488,6 +5488,67 @@ run under the role default and are not backstopped per caller. This is layer 2;
the app-layer source filters remain layer 1 and stay mandatory. Behavioral pins
live in `test/postgres-engine-rls-scope.test.ts`.
+**Segmented page tables.** A page over 1 MiB stored in segments (`pages.segmented_storage`)
+keeps its text in `page_segment_texts`, its layout and headings in
+`page_body_manifest`, uploads in progress in `page_body_stagings` /
+`page_body_staging_parts`, and view sizes in `page_view_digests`. gbrain
+enables RLS on all five on every schema replay, as it does on `pages` and
+`content_chunks`, so with no policy a role that does not bypass RLS reads no row
+of them. Title search, the source-scoped vector scan, the chunk windows search
+reads around its hits and get_page check chunks against `page_body_manifest`
+(inline pages included), so a restricted read role needs `SELECT` on it; without
+it those reads fail with `permission_denied` (42501). Grant it together with
+these policies, never with an open one, or the role reads every source's segment
+text. A scoped role then sees exactly the segment rows of its sources:
+
+<!-- gbrain:segmented-rls-recipe:begin (applied verbatim by test/e2e/segmented-rls-scope.test.ts) -->
+```sql
+-- The pages_scope_filter predicate, on each table's own source_id.
+CREATE POLICY page_segment_texts_scope_filter ON page_segment_texts
+ USING (current_setting('app.scopes', true) = '*'
+ OR source_id = ANY(string_to_array(current_setting('app.scopes', true), ',')));
+CREATE POLICY page_body_manifest_scope_filter ON page_body_manifest
+ USING (current_setting('app.scopes', true) = '*'
+ OR source_id = ANY(string_to_array(current_setting('app.scopes', true), ',')));
+CREATE POLICY page_body_stagings_scope_filter ON page_body_stagings
+ USING (current_setting('app.scopes', true) = '*'
+ OR source_id = ANY(string_to_array(current_setting('app.scopes', true), ',')));
+-- Search joins sources; a scoped role sees its own.
+CREATE POLICY sources_scope_filter ON sources
+ USING (current_setting('app.scopes', true) = '*'
+ OR id = ANY(string_to_array(current_setting('app.scopes', true), ',')));
+-- No source_id of their own: visible exactly when their staging or page is
+-- (the pages policy filters the subquery). content_chunks holds every page's
+-- chunk text, segmented or not.
+CREATE POLICY page_body_staging_parts_scope_filter ON page_body_staging_parts
+ USING (current_setting('app.scopes', true) = '*'
+ OR EXISTS (SELECT 1 FROM page_body_stagings s WHERE s.id = staging_id));
+CREATE POLICY page_view_digests_scope_filter ON page_view_digests
+ USING (current_setting('app.scopes', true) = '*'
+ OR EXISTS (SELECT 1 FROM pages p WHERE p.id = page_id));
+CREATE POLICY content_chunks_scope_filter ON content_chunks
+ USING (current_setting('app.scopes', true) = '*'
+ OR EXISTS (SELECT 1 FROM pages p WHERE p.id = page_id));
+
+-- A read role that searches and reads pages. The other tables it reads
+-- (config, timeline_entries, facts, ...) need policies of their own.
+GRANT SELECT ON pages, content_chunks, page_body_manifest, page_segment_texts,
+ page_view_digests, sources TO <reader-role>;
+
+-- If the runtime role OWNS these tables, as for pages:
+ALTER TABLE page_segment_texts FORCE ROW LEVEL SECURITY;
+ALTER TABLE page_body_manifest FORCE ROW LEVEL SECURITY;
+ALTER TABLE page_body_stagings FORCE ROW LEVEL SECURITY;
+ALTER TABLE page_body_staging_parts FORCE ROW LEVEL SECURITY;
+ALTER TABLE page_view_digests FORCE ROW LEVEL SECURITY;
+ALTER TABLE content_chunks FORCE ROW LEVEL SECURITY;
+```
+<!-- gbrain:segmented-rls-recipe:end -->
+
+A role whose reads do not run through the scoped helper is scoped by its own
+default (`ALTER ROLE <reader-role> SET app.scopes = 'source-a,source-b'`). The
+policies read `app.scopes` only; the app-layer source filters stay layer 1.
+
**In engine-sql.** A read in a migrated domain takes a `ScopedRead` when it
runs through this helper and a `LegacyUnscopedRead` when it runs on the pool
(`src/core/engine-sql/brands.ts`); the engine obtains the branded executor, so
diff --git a/scripts/build-schema.ts b/scripts/build-schema.ts
index fed80f5157..d233e5f8b7 100644
--- a/scripts/build-schema.ts
+++ b/scripts/build-schema.ts
@@ -33,7 +33,7 @@ import { FACT_WITHDRAWAL_SCHEMA_STATEMENTS } from '../src/core/facts/withdrawal-
import { GRANT_AUDIT_SCHEMA_SQL } from '../src/core/grants/schema.ts';
import { LEASE_TOKEN_SCHEMA_SQL } from '../src/core/lease-schema.ts';
import { LINK_TEMPORAL_SCHEMA_SQL } from '../src/core/link-temporal-schema.ts';
-import { PAGE_BODY_SCHEMA_SQL, PAGE_GENERATION_BUMP_FN_SQL } from '../src/core/page-body/schema.ts';
+import { PAGE_BODY_RLS_SQL, PAGE_BODY_SCHEMA_SQL, PAGE_GENERATION_BUMP_FN_SQL } from '../src/core/page-body/schema.ts';
import { PAGE_PROJECTION_SCHEMA_SQL } from '../src/core/page-state/projection-schema.ts';
import { PAGE_STATE_SCHEMA_SQL } from '../src/core/page-state/schema.ts';
import { POSTGRES_CONCURRENT_PERSISTENCE_INDEXES, PERSISTENCE_SCHEMA_STATEMENTS } from '../src/core/persistence/schema.ts';
@@ -87,6 +87,8 @@ export const FRAGMENTS: readonly Fragment[] = [
},
{ source: 'src/core/lease-schema.ts', expr: 'LEASE_TOKEN_SCHEMA_SQL', postgres: LEASE_TOKEN_SCHEMA_SQL, pglite: LEASE_TOKEN_SCHEMA_SQL },
{ source: 'src/core/page-body/schema.ts', expr: 'PAGE_BODY_SCHEMA_SQL', postgres: PAGE_BODY_SCHEMA_SQL, pglite: PAGE_BODY_SCHEMA_SQL },
+ // Capability rule: PGLite has no role system and enables RLS on no core table, so the segment tables' RLS block is Postgres-only.
+ { source: 'src/core/page-body/schema.ts', expr: 'PAGE_BODY_RLS_SQL', postgres: PAGE_BODY_RLS_SQL, pglite: '' },
{ source: 'src/core/page-state/schema.ts', expr: 'PAGE_STATE_SCHEMA_SQL', postgres: PAGE_STATE_SCHEMA_SQL, pglite: PAGE_STATE_SCHEMA_SQL },
{
source: 'src/core/persistence/schema.ts',
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index f05728110b..6f6bbcac8e 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -20,8 +20,8 @@ src/core/engine.ts 2822 ratchet grown v0.46.26.0 megawave: relational/visibility
src/core/import-file.ts 2064 ratchet +2: pre-publication withdrawal validation; grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); security: durable queued authority and confined filesystem dispatch; master integration: grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: withdrawal preservation after data-only frontmatter parsing; #5105: small legacy writer/refusal and shared revision CAS delegates; #5105: +8 prepared contextual retrieval policy and retry boundary wiring; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: shared provider-free Markdown and code preparation; merged company ingestion/schema routing changes; master retrieval/projection integration with company ingestion; shared content: prepare managed image imports without bypassing canonical publication; +29 write-path wave: identity move/collision wiring (logic in import-identity.ts), deferred embedding on provider failure, image index completeness, file-time date anchor; +22 fw3 A13: markdown re-import reuses unchanged chunk vectors under the seal/wrapper/signature/protected-fence gate; +2 fw3 A12: importFromFile firstCommitAt option; +3 fw3 A14: managed imports keep add-only tags; +4 #5675: record the file origin move inference binds to (logic in import-identity.ts); fw3 integration: A12/A13/A14 (+27) and #5675 (+4) compose; +17 wave-2 W4: safe-chunk re-seal of unchanged legacy markdown/code pages (#5050 #5247) and embedding-input provenance on inline imports (#5553); -1 fix wave 2 (v0.60.5.0) integration: W4 delta re-summed over the merged master line count; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +16 at the merge; +11 #4616: markdown and code imports keep the usable vectors of a partially refused batch and leave refused chunks for embed --stale; lowered to 2230: #5621 contextual-mode resolution peeled to core/import-contextual-mode.ts (shared with gbrain repair contextual-mode); +2 wave 8 lane D1 #5158: key-order fallback equality call (comparison lives in page-state/import-guard.ts); +1 F1c: direct imports run in maintenanceTransaction (write attribution; helper in persistence/attribution.ts); lowered to 2178: #5988 content screen and content-sanity config peeled to core/import-screen.ts; +1 #6007: the prepared apply returns its page id and seal (PreparedImportApplied); +1 #5333: trusted imports drop a stale oversized embed_skip/content_flag the gate no longer sets, and an embed_skip transition defeats both unchanged fast paths; wave 10 collector: lane E (#5333) and the other lanes compose at 2183; grown #6188 (+17): fence options interface, result fields and the Tier 1 step call (logic in fence-repair/import-step.ts); +2 #5984 single-write fast path: the coordinated existingSnapshot option (interface field) composes with the lane apply diet at 2202; +1 GBRA-69: a coordinated apply defers its chunker seal to the caller (sealImportedPage in page-state/projections.ts); lowered to 2023: #5001 the edge-mapping loop moved to code-chunks.ts mapCodeEdges (shared with the prepared apply); W14 P3.13 (#5001) lowered 2049→2023 by moving the edge loop to mapCodeEdges; +2 W13 PR1 on top (2025 measured); +2 #6529: the unchanged-image skip path records source_path (refreshSourcePath, as #4588 does for Markdown); +4 large pages A6/T33: code files keep CODE_FILE_MAX_BYTES, a page over PAGE_INLINE_MAX_BYTES commits with NULL vectors for the metered stale sweep; +1 #6722: an embed_skip page is chunked and never embedded (noEmbed folds the marker); merge v0.60.240.0: large pages and master growth compose at 2032; +24 Wave B lane 1d: the segmented storage step (stage before publication, flip in the apply, seal and post-commit projection; logic in persistence/segmented-apply.ts and page-body/ingest.ts) and the streamed-import dispatch over the single-string ceiling (logic in page-body/streamed-import.ts); merge v0.60.248.0: Wave B PR 1 and master growth compose at 2056; +4 Wave B review: a rename re-preparation reuses the staged segmented body (reuseSegments option) and the remote fence merge reads an unread body as fence-free (fenceBody in page-body/page-shape.ts); +2 Wave B gem A: a coordinated demotion versions the segmented page before demoting it (createVersion order); lanes compose at 2062; +2 Wave B lane 2q: ImportResult.searchable (interface field; the value comes from SegmentedImport.afterCommit)
src/core/migrate.ts 602 ratchet schema-migration runner only; migrations live in src/core/schema-migrations/ (W3); +3 #5216: resumable page revision backfill runs after every migration pass while pages.knowledge_revision is nullable
src/core/operations.ts 240 ratchet peel target: containment sprint C4-C7; grown v0.46.26.0 megawave op wiring; +chat-connectors wiring (master merge); +5 v0.47 gmail-loops: loopsOperations spread + OP_AREAS; #5105: receipt operation registry wiring; shared-skills integration on company-ingestion base; +2 security wave: withOutputRedaction applied at op registration; +1 #5616: pageEditOperations import (spread shares the pages line); +1 Foundations 1 F1b: attributionOperations import (spread shares the admin line); +1 agent operator wave A6: ops/notices.ts import (mute_notice); +2 agent operator closeout A1: registerOpRoutes import + call (routing logic in fix-routing.ts); +2 retrieval feedback: feedbackOperations import and spread (ops/feedback.ts); +1 #6007: pageBatchOperations import (spread shares the pages line); +1 P5: wanted_pages area row; lowered GBRA-75 W11 cold start: OP_AREAS + finalize step moved to operation-load.ts (shared with the CLI per-op loader); +1 C4 pinned questions: questionsOperations import and spread (ops/questions.ts; its areas live in operation-load.ts OP_AREAS)
-src/core/pglite-engine.ts 3065 ratchet +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2983 measured); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2983 measured); +4 P7 relationalChainHop delegate; +8 contributor audit wave P0: listFactsKeyset delegate (SQL in engine-sql/facts.ts); +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); +2 #5984 lane apply diet: putPage/setPageAliases write inline in the caller's page transaction (engine methods cannot move); +4 GBRA-69: replaceDerivedLinksBatch delegate (logic in derived-links.ts); +5 GBRA-67: readPageSnapshotsBatch delegate (batch logic in page-snapshot-batch.ts); +1 GBRA-75 wave 10: findDuplicatePages delegate (SQL in engine-sql/pages.ts); +2 GBRA-76: transaction/transactionDirect take TransactionOptions and refuse an already-aborted signal before BEGIN; +2 #4772 (W14 PR3): entityTypes HealthDeps delegate + import (policy in schema-pack/entity-types.ts, SQL in engine-sql/health.ts); +2 W14 P3.12 (#4772): entityTypes HealthDeps delegate + import on top of W13; +11 Cat 40 Hard fix wave F2 (#6271) on top: countKeywordPages/searchKeywordPages delegations (SQL in engine-sql/keyword-pages.ts) and the rankQuery score parameter (3023 measured); +3 W15 P1.2 (#6454): three one-line stale-frontmatter-key delegates (SQL in engine-sql/pages.ts); +6 large pages Wave A sub-a: getChunkPage delegate (SQL in engine-sql/chunks.ts); +11 #6696 B3: readEmbeddingStateCounts/listEmbeddingStateRows delegations + type import; +22 Wave B lane 1a: segmented page storage delegations (allocateBodyOccurrenceIds..sweepSegments, SQL in engine-sql/page-body.ts) and their imports
-src/core/postgres-engine.ts 3082 ratchet +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); ceiling rationale: docs/architecture/key-files/engines-2.md entry for src/core/postgres-engine.ts; evidence delivery: getChunkWindows scoped-read delegate + type import (+5; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +10 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3242 #5824: searchVector SQL moved to search/vector-statement.ts, +explainVectorSearch/runVectorAttempt (-156); +6 #5730: onpoisoned wiring on the instance/module/connection-manager pools + poisonedDiscards in getPoolDiagnostics (counter in pool-gauge.ts); +5 #5801: onCheckout observer seam (fires after reserve resolution / transaction-callback entry; listeners in pool-gauge.ts); lowered to 3119 #5889: searchTitles SQL moved to engine-sql/titles.ts (-133); lowered to 2914 F4a: getHealth SQL moved to engine-sql/health.ts (-216); +2 #5984: transactions track held page guards like PGLite (withHeldPageKeys), so repeated guards in one transaction cost no round trips; +1 #5984: traceSqlOptions import for the env-gated GBRAIN_SQL_TRACE bench hook (src/core/sql-trace.ts); v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (2917 measured); +2 engine graduation (GBRA-50 G2a): initSchema sizing parameter (the source embedding layout sizes a fresh target); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2920 measured); +4 P7 relationalChainHop delegate; +8 contributor audit wave P0: listFactsKeyset delegate (SQL in engine-sql/facts.ts); +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); 6 #6085: initSchema pins advisory lock 42, bootstrap, schema replay and unlock to one reserved backend when the DDL pool has more than one slot (gauge only, no long-hold permit), released in finally; wave 10 collector: lane E (#6085), lane G (#5375) and master compose at 2939; +2 #6110: search transactions pass jitOff to withScopedReadTransaction (SET LOCAL jit = off in postgres-engine/search-settings.ts); +2 #5984 lane apply diet: putPage/setPageAliases write inline in the caller's page transaction (engine methods cannot move); +1 #5984 single-write fast path composes with the lane apply diet at 2944; +2 #5984 shared parameter types: the instance pool passes shared_types and initSchema clears them after migrations (helpers in db.ts); +2 #6276: the remote alias-resolving readPageSnapshot runs with JIT off (withScopedReadTransaction jitOff); +5 #6278: executeRaw timeoutMs delegate (statement in postgres-engine/bounded-statement.ts); +23 #6278 PR 1.5: cancelSettleMs() and the settle timer in runUnsafe that discards a reserved connection whose cancel a transaction-mode pooler never completed; +3 #6317 lane 2: getPoolDiagnostics().pool from the vendored driver (postgres-engine/pool-stats.ts) and the prepare mark; +4 GBRA-69: replaceDerivedLinksBatch delegate (logic in derived-links.ts); +1 GBRA-69 extract batching: replaceDerivedLinksBatch delegate (batch logic in derived-links.ts); +9 GBRA-75: getBacklinkCounts and getHealth statements run JIT-off through the private jitOffRead transaction helper (engine methods cannot move); +3 GBRA-75 wave 7: searchKeyword and searchVector start the once-per-engine background search statistics guard (logic in search/projection-statistics.ts); +7 GBRA-67: readPageSnapshotsBatch scoped-read delegate (batch logic in page-snapshot-batch.ts); +1 GBRA-75 wave 10: findDuplicatePages scoped-read delegate (SQL in engine-sql/pages.ts); +7 #6383: poolIncidents hooks on the instance/module/connection-manager pools (counter and lines in pool-gauge.ts, budget in db.ts) and stuckDiscards/buildFailures in getPoolDiagnostics; +3 GBRA-76: transaction/transactionDirect take TransactionOptions; transactionOn attaches the begin handle to withTransactionAbort (logic in postgres-engine/transaction-abort.ts); +2 W14 P3.12 (#4772): entityTypes HealthDeps delegate + import on top of W13; +1 #5227: schema.sql replay under withSchemaLockTimeout (wave 14 PR1); +1 driver desync tripwire: desyncDiscards in getPoolDiagnostics (counter and line in pool-gauge.ts); +11 Cat 40 Hard fix wave F2 (#6271) on top: countKeywordPages/searchKeywordPages scoped-read delegations (SQL in engine-sql/keyword-pages.ts) and the rankQuery score parameter (3027 measured); +3 W15 P1.2 (#6454): three one-line stale-frontmatter-key delegates, reads scoped (SQL in engine-sql/pages.ts); +12 wave 16 G5.1 (#6495): keywordStatementTimeout memo field, its connect/disconnect resets and the keywordStatementTimeoutSetting accessor, plus one awaited setting per keyword/chunk/CJK transaction (resolver in postgres-engine/keyword-statement-timeout.ts); wave 16 G5.1 gate fix: keywordStatementTimeoutSetting resolves the knob once per connection on the first keyword statement from the saved connect config (connect issues no statement for it; 3042 measured); +7 large pages Wave A sub-a: getChunkPage scoped-read delegate (SQL in engine-sql/chunks.ts); +11 #6696 B3: readEmbeddingStateCounts/listEmbeddingStateRows delegations + type import; +22 Wave B lane 1a: segmented page storage delegations (allocateBodyOccurrenceIds..sweepSegments, SQL in engine-sql/page-body.ts) and their imports
+src/core/pglite-engine.ts 3068 ratchet +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2983 measured); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2983 measured); +4 P7 relationalChainHop delegate; +8 contributor audit wave P0: listFactsKeyset delegate (SQL in engine-sql/facts.ts); +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); +2 #5984 lane apply diet: putPage/setPageAliases write inline in the caller's page transaction (engine methods cannot move); +4 GBRA-69: replaceDerivedLinksBatch delegate (logic in derived-links.ts); +5 GBRA-67: readPageSnapshotsBatch delegate (batch logic in page-snapshot-batch.ts); +1 GBRA-75 wave 10: findDuplicatePages delegate (SQL in engine-sql/pages.ts); +2 GBRA-76: transaction/transactionDirect take TransactionOptions and refuse an already-aborted signal before BEGIN; +2 #4772 (W14 PR3): entityTypes HealthDeps delegate + import (policy in schema-pack/entity-types.ts, SQL in engine-sql/health.ts); +2 W14 P3.12 (#4772): entityTypes HealthDeps delegate + import on top of W13; +11 Cat 40 Hard fix wave F2 (#6271) on top: countKeywordPages/searchKeywordPages delegations (SQL in engine-sql/keyword-pages.ts) and the rankQuery score parameter (3023 measured); +3 W15 P1.2 (#6454): three one-line stale-frontmatter-key delegates (SQL in engine-sql/pages.ts); +6 large pages Wave A sub-a: getChunkPage delegate (SQL in engine-sql/chunks.ts); +11 #6696 B3: readEmbeddingStateCounts/listEmbeddingStateRows delegations + type import; +22 Wave B lane 1a: segmented page storage delegations (allocateBodyOccurrenceIds..sweepSegments, SQL in engine-sql/page-body.ts) and their imports; +3 PR2 fix lane B: logIngest stamps writer_version/writer_host_id/writer_segment_reader and getIngestLog names its columns (engine methods cannot move)
+src/core/postgres-engine.ts 3085 ratchet +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); ceiling rationale: docs/architecture/key-files/engines-2.md entry for src/core/postgres-engine.ts; evidence delivery: getChunkWindows scoped-read delegate + type import (+5; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +10 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3242 #5824: searchVector SQL moved to search/vector-statement.ts, +explainVectorSearch/runVectorAttempt (-156); +6 #5730: onpoisoned wiring on the instance/module/connection-manager pools + poisonedDiscards in getPoolDiagnostics (counter in pool-gauge.ts); +5 #5801: onCheckout observer seam (fires after reserve resolution / transaction-callback entry; listeners in pool-gauge.ts); lowered to 3119 #5889: searchTitles SQL moved to engine-sql/titles.ts (-133); lowered to 2914 F4a: getHealth SQL moved to engine-sql/health.ts (-216); +2 #5984: transactions track held page guards like PGLite (withHeldPageKeys), so repeated guards in one transaction cost no round trips; +1 #5984: traceSqlOptions import for the env-gated GBRAIN_SQL_TRACE bench hook (src/core/sql-trace.ts); v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (2917 measured); +2 engine graduation (GBRA-50 G2a): initSchema sizing parameter (the source embedding layout sizes a fresh target); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2920 measured); +4 P7 relationalChainHop delegate; +8 contributor audit wave P0: listFactsKeyset delegate (SQL in engine-sql/facts.ts); +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); 6 #6085: initSchema pins advisory lock 42, bootstrap, schema replay and unlock to one reserved backend when the DDL pool has more than one slot (gauge only, no long-hold permit), released in finally; wave 10 collector: lane E (#6085), lane G (#5375) and master compose at 2939; +2 #6110: search transactions pass jitOff to withScopedReadTransaction (SET LOCAL jit = off in postgres-engine/search-settings.ts); +2 #5984 lane apply diet: putPage/setPageAliases write inline in the caller's page transaction (engine methods cannot move); +1 #5984 single-write fast path composes with the lane apply diet at 2944; +2 #5984 shared parameter types: the instance pool passes shared_types and initSchema clears them after migrations (helpers in db.ts); +2 #6276: the remote alias-resolving readPageSnapshot runs with JIT off (withScopedReadTransaction jitOff); +5 #6278: executeRaw timeoutMs delegate (statement in postgres-engine/bounded-statement.ts); +23 #6278 PR 1.5: cancelSettleMs() and the settle timer in runUnsafe that discards a reserved connection whose cancel a transaction-mode pooler never completed; +3 #6317 lane 2: getPoolDiagnostics().pool from the vendored driver (postgres-engine/pool-stats.ts) and the prepare mark; +4 GBRA-69: replaceDerivedLinksBatch delegate (logic in derived-links.ts); +1 GBRA-69 extract batching: replaceDerivedLinksBatch delegate (batch logic in derived-links.ts); +9 GBRA-75: getBacklinkCounts and getHealth statements run JIT-off through the private jitOffRead transaction helper (engine methods cannot move); +3 GBRA-75 wave 7: searchKeyword and searchVector start the once-per-engine background search statistics guard (logic in search/projection-statistics.ts); +7 GBRA-67: readPageSnapshotsBatch scoped-read delegate (batch logic in page-snapshot-batch.ts); +1 GBRA-75 wave 10: findDuplicatePages scoped-read delegate (SQL in engine-sql/pages.ts); +7 #6383: poolIncidents hooks on the instance/module/connection-manager pools (counter and lines in pool-gauge.ts, budget in db.ts) and stuckDiscards/buildFailures in getPoolDiagnostics; +3 GBRA-76: transaction/transactionDirect take TransactionOptions; transactionOn attaches the begin handle to withTransactionAbort (logic in postgres-engine/transaction-abort.ts); +2 W14 P3.12 (#4772): entityTypes HealthDeps delegate + import on top of W13; +1 #5227: schema.sql replay under withSchemaLockTimeout (wave 14 PR1); +1 driver desync tripwire: desyncDiscards in getPoolDiagnostics (counter and line in pool-gauge.ts); +11 Cat 40 Hard fix wave F2 (#6271) on top: countKeywordPages/searchKeywordPages scoped-read delegations (SQL in engine-sql/keyword-pages.ts) and the rankQuery score parameter (3027 measured); +3 W15 P1.2 (#6454): three one-line stale-frontmatter-key delegates, reads scoped (SQL in engine-sql/pages.ts); +12 wave 16 G5.1 (#6495): keywordStatementTimeout memo field, its connect/disconnect resets and the keywordStatementTimeoutSetting accessor, plus one awaited setting per keyword/chunk/CJK transaction (resolver in postgres-engine/keyword-statement-timeout.ts); wave 16 G5.1 gate fix: keywordStatementTimeoutSetting resolves the knob once per connection on the first keyword statement from the saved connect config (connect issues no statement for it; 3042 measured); +7 large pages Wave A sub-a: getChunkPage scoped-read delegate (SQL in engine-sql/chunks.ts); +11 #6696 B3: readEmbeddingStateCounts/listEmbeddingStateRows delegations + type import; +22 Wave B lane 1a: segmented page storage delegations (allocateBodyOccurrenceIds..sweepSegments, SQL in engine-sql/page-body.ts) and their imports; +3 PR2 fix lane B: logIngest stamps writer_version/writer_host_id/writer_segment_reader and getIngestLog names its columns (engine methods cannot move)
src/core/search/hybrid.ts 1648 ratchet +5 GBRA-81 item 5 per-stage search timings: HybridSearchOpts._timings (interface field) and the timer bindings and import in hybridSearch/hybridSearchCached (collector logic in search/stage-timings.ts); +2 W5 page-unit ranking cut: HybridSearchOpts.pageRankCut (logic in search/page-rank-cut.ts); +9 W3 confidence-gated reranking: HybridSearchOpts.rerankGate and the gate/lookup threading through rerankAndPin and sizeReturnPool (logic in search/hybrid/rerank-gate.ts, crag.ts gradePreRerank); re-summed at the W3 merge onto master v0.60.168.0 (1641 measured); +2 System One v1: HybridSearchOpts.decide (search/decide-stage.ts); refactor wave 1 split target (W4 hybrid, cut line); ceiling rationale: docs/architecture/key-files/core-search-1.md entry for src/core/search/hybrid.ts; +10 #5691: per-request embedding_query_prefix read once and threaded to the embeds and cache key; +5 green master wave (embedding opt-out): HybridSearchOpts._embeddingOptedOut (interface field) read once per request and threaded to the cache-lookup embed and the keyword-only gate; +24 P2 explain RRF attribution stamp in rrfFusionWeighted, backlink_count stamp, explain_target stage observations, explain/explainTarget opts; +14 fix wave 13 P4.8 #6400: lazyQueryEmbedDeadline (the query-embed deadline starts when the embed starts) and the _queryEmbedDeadline getter; +1 query facts arm: HybridSearchOpts.onQueryEmbedding (interface field; its one-line call is paid inside the ceiling) after the vector arms, so the facts arm reuses the query embedding without a second model call; re-summed at the master a08578ca5 merge (1591 master lines + 3 integration lines: the onQueryEmbedding hook)
src/core/types.ts 2319 ratchet +4 Wave B PR 1 (1c): Page.body_storage/body_bytes (interface fields; guard logic in page-body/page-shape.ts); +8 W3 confidence-gated reranking: HybridSearchMeta.rerank_gate (RerankGateMeta in search/hybrid/rerank-gate.ts); re-summed at the W3 merge onto master v0.60.168.0 (2279 measured); +7 fix wave 11 W6.2/W6.3 (#5989, #6132): SearchOpts.hnswIterativeScan and cjkKeyword, the keyword_candidates_incomplete stage and HybridSearchMeta.keyword_candidates (logic in engine-sql/cjk-search.ts); +5 System One v1 retrieval lane: SearchResult injection_p/injection_suspected, HybridSearchMeta answerability, egress_denied degraded reason; +4 System One v1: SearchResult rerank_score_kind/decide_evidence, HybridSearchMeta decide/rerank; +3 wave review: PAGE_SORT_SQL.updated_asc source_id + id tiebreakers (total order under federated scopes); +5 #4881: OntologyReadOpts extends PageReadScope doc; +3 #4857: PAGE_SORT_SQL.slug total-order tiebreaker comment; grown v0.46.26.0 megawave: EvidenceOpts, pacing/usage result fields, PageFilters growth (#4352 #4218); wave-k: +9 SalienceOpts/AnomaliesOpts source scope (#3867); +20 2026-09 adversarial batch 2: keyword_relaxed_carried stage + relaxed_dropped meta field docs; +16 2026-09 fix wave: SearchResult.keyword_relaxed field + full fusion-demotion doc; (#3867); +9: #4648 rerank_passthrough degraded stage + empty_result_set/malformed_shape reasons | merged v0.48.1.0 true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); corrective release: shared internal PageReadScope and PageReadPolicy; ranker wave v0.48.4.0: HybridSearchMeta relational_rerank_pin / keyword_arm_confidence / metadata_boost_gate + SearchResult.relational_pinned (+48 over master's peel); +12: #4681 Page.updated_at_iso + keyset cursor precision docs; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: public page revision fields; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: typed vector pool and readiness metadata; merged company ingestion/schema routing changes; retired provider integration removed; +1 write-path wave: 'created' effective-date source; +3 read-path wave: rerank_failed degraded stage + budget reason (closed vocabularies) and its recall classification note; +8 fw3-search: SearchOpts.source_boosts + keyword_arm_failed/title_arm_failed stages; +2 wave-2 W4: ChunkInput.embedding_input_hash (#5553); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +2 at the merge; evidence delivery: optional SearchResult.delivered (+2; shape in search/evidence-delivery.ts); +2 eval wave N1-3: OntologyReadOpts.visibility (remote world-only ontology reads); +4 #5827: GraphNode.source_id and GraphPath from_source_id/to_source_id; +2 #5824: SearchOpts.vectorLegacyGuard rollback switch; +7 #5154: PageFilters.listColumnsOnly (interface field); +11 Foundations 1 F1b: WriteAttributionView + AttributedPageVersion (get_versions / get_write_attribution read shapes); +1 #5988: SearchResult.stale carries the held-file detail (interface field); +6 retrieval feedback: SearchResult feedback_boost/content_hash/relational_path_edges stamps and RelationalFanoutRow.path_edges (interface fields); +2 RelationalFanoutOpts.wide (interface field); 1 GBRA-49: temporal annotation field on link rows; 1 GBRA-49: temporal annotation field on link rows; 1 GBRA-49: temporal annotation field on link rows; +44 P7 ChainHopOpts/ChainHopEdge chain-hop contract types; P7 SearchResult.relational evidence + RelationalEvidence type + relational_plan meta + planner per-call overrides; +2 P7 SearchOpts.relationalChainSlots per-call override; +1 P7 ChainHopOpts.temporal (relationship-validity policy per hop); P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 1 GBRA-49: temporal annotation field on link rows; +44 P7 ChainHopOpts/ChainHopEdge chain-hop contract types; P7 SearchResult.relational evidence + RelationalEvidence type + relational_plan meta + planner per-call overrides; +2 P7 SearchOpts.relationalChainSlots per-call override; +1 P7 ChainHopOpts.temporal (relationship-validity policy per hop); +1 green master wave: embedding_disabled degraded reason (closed vocabulary); +2 #5951: Chunk.source_id (get_chunks names each row's source); 1 P2 SearchResult explain fields (rrf attribution, blend_norm_rrf, score_details, backlink_count) + RrfAttribution (interface fields); +11 #5575 (L1b): PageReadScope minTrust/suppressFlagged, SearchResult trust_tier/origin/unconfirmed, TimelineOpts eligibility (interface fields cannot move); +8 #4772 (W14 PR3): BrainHealth.entity_types_status field (interface fields cannot move); +1 C4: question page type row; +6 entity anchoring: optional SearchResult.entity_anchored row stamp (logic in search/entity-anchor.ts); +4 query facts arm: optional SearchResult.fact_row and superseded_claim row fields (logic in search/facts-arm.ts); +2 query facts arm: SearchResult result_type/fact_id/page_slug/follow_up (fact rows are never page-shaped); +9 Cat 40 Hard fix wave (#6271): SearchResult matched_alias/evidence_omitted/provenance, SearchOpts.rankQuery, keyword_count_unavailable stage and rerank_failed reasons; +12 fix wave 15 P2.1 (#6500): PageFilters.slugAfter (single-source slug keyset, interface field + doc) and the updated_desc tiebreaker comment (the keyset walk lives in facts/conversation-enumeration.ts); +2 wave 16 G5.1 (#6495): EngineConfig.keyword_statement_timeout_ms (interface field + doc); +2 GBRA-92: EngineConfig.pglite_shared_buffers (interface field + doc); +11 large pages (Wave A): Chunk/ChunkInput projected_byte_start/end interface fields (span logic in chunkers/recursive.ts, page-window/document.ts)
src/core/minions/queue.ts 2528 ratchet grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; security: durable queued authority and confined filesystem dispatch; master integration: grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: durable authority and delegated admission both enforced; typed readiness, configuration-blocked lifecycle and bounded release; +9: prune archives completed dream synthesis keys; +18 Lane D: deferJob (a deferral returns a job to delayed with no attempt counted and no stacktrace growth); the ceiling had 17 lines of slack; +5 agent operator follow-up Item 5 merged over master: claim-time spend fence token and legacy_default stamp (logic in minions/spend-authorization.ts)
diff --git a/scripts/structural-suites.tsv b/scripts/structural-suites.tsv
index 9f2f7d9bd0..47e9106a7c 100644
--- a/scripts/structural-suites.tsv
+++ b/scripts/structural-suites.tsv
@@ -141,6 +141,7 @@ test/e2e/bootstrap-real-codex.serial.test.ts bootstrap rendered protocol — amb
test/e2e/codex-plugin-install-real.serial.test.ts (file-level) 2 readFileSync
test/e2e/migration-flow.test.ts (file-level) 4 readFileSync
test/e2e/openclaw-reference-compat.test.ts OpenClaw reference workspace compat (W1 + W2 + W3) 8 readFileSync
+test/e2e/segmented-rls-scope.test.ts (file-level) 4 readFileSync
test/e2e/workspace-generic-compat.test.ts generic agent-workspace compat (INSTALL_FOR_AGENTS.md flow) 6 readFileSync
test/embedding-dim-check-facts.test.ts doctor checkFactsEmbeddingWidthConsistency wiring (T6) 4 doctor-source-helper
test/embedding-dim-check-facts.test.ts postgres-engine fact insert cast (T6, codex #20) 1 source-surface-helper
diff --git a/src/commands/doctor/checks/segmented-storage.ts b/src/commands/doctor/checks/segmented-storage.ts
index ca4f38ac39..4f43506c69 100644
--- a/src/commands/doctor/checks/segmented-storage.ts
+++ b/src/commands/doctor/checks/segmented-storage.ts
@@ -10,16 +10,17 @@ const SAMPLE = 20;
const enableFix = (why: string) => agentFix(['gbrain', 'config', 'set', PAGE_BODY_CONFIG_KEYS.segmentedStorage, 'on'], why, name, { actor: 'user', docs: DOCS });
/**
- * Wave B activation gate: the configured `pages.segmented_storage`, the value writes use, and the recent
- * writers (committed requests in the last seven days) older than SEGMENTED_WRITER_FLOOR or unstamped that keep
- * it off. While it is off, pages over 1 MiB are written inline up to 24 MiB; stored segmented pages stay readable.
+ * Wave B activation gate: the configured `pages.segmented_storage`, the value writes use, and the writers seen in
+ * the last seven days that do not read segmented pages and keep it off (`segmentedGateWriters`: managed requests,
+ * ingest-log runs and resident consumers without the segment-reader mark, or stamped below SEGMENTED_WRITER_FLOOR).
+ * While it is off, pages over 1 MiB are written inline up to 24 MiB; stored segmented pages stay readable.
*/
export async function segmentedStorageCheck(engine: BrainEngine): Promise<Check> {
try {
const configured = parseSegmentedStorage(await engine.getConfig(PAGE_BODY_CONFIG_KEYS.segmentedStorage));
const blockers = await segmentedWriterBlockers(engine, { fresh: true });
const policy = await readPageBodyPolicy(engine);
- const listed = blockers.slice(0, SAMPLE).map(row => ({ host_id: row.host_id, principal: row.principal, role: row.role, version: row.version_label,
+ const listed = blockers.slice(0, SAMPLE).map(row => ({ host_id: row.host_id, principal: row.principal, role: row.role, version: row.version_label, segment_reader: row.segment_reader,
last_seen: row.last_seen, clears_at: row.last_seen ? new Date(Date.parse(row.last_seen) + SEGMENTED_WRITER_WINDOW_DAYS * 86_400_000).toISOString() : null }));
const details = { configured, effective: policy.segmented ? 'on' : 'off', max_bytes: policy.maxBytes, floor: SEGMENTED_WRITER_FLOOR,
window_days: SEGMENTED_WRITER_WINDOW_DAYS, blockers: listed, truncated: blockers.length > SAMPLE, docs: DOCS };
@@ -32,12 +33,12 @@ export async function segmentedStorageCheck(engine: BrainEngine): Promise<Check>
if (blockers.length) {
const hosts = listed.map(row => `host ${row.host_id ?? 'unknown (not recorded)'} (principal ${row.principal}) ${row.role} ${row.version}, last seen ${row.last_seen}`);
return { name, status: 'warn', details,
- message: `Segmented page storage is configured ${configured === 'on' ? 'on' : 'on by default'} but held off: ${blockers.length} writer(s) older than v${SEGMENTED_WRITER_FLOOR} `
- + `committed a request in the last ${SEGMENTED_WRITER_WINDOW_DAYS} days: ${hosts.join('; ')}${blockers.length > SAMPLE ? ` (first ${SAMPLE} shown)` : ''}. `
+ message: `Segmented page storage is configured ${configured === 'on' ? 'on' : 'on by default'} but held off: ${blockers.length} writer(s) that do not read segmented pages `
+ + `(a gbrain older than this release, or stamped below v${SEGMENTED_WRITER_FLOOR}) wrote in the last ${SEGMENTED_WRITER_WINDOW_DAYS} days: ${hosts.join('; ')}${blockers.length > SAMPLE ? ` (first ${SAMPLE} shown)` : ''}. `
+ 'An older writer does not understand segmented pages, so pages over 1 MiB are written inline up to 24 MiB until it is upgraded. '
- + `The hold clears ${SEGMENTED_WRITER_WINDOW_DAYS} days after each one's last request (clears_at).`,
+ + `The hold clears ${SEGMENTED_WRITER_WINDOW_DAYS} days after each one's last write (clears_at).`,
fix: { argv: ['gbrain', 'upgrade'], consent: [], actor: 'host_admin', requires_exclusive: false, verify: doctorVerify(name), docs: DOCS,
- why: 'Run on each host doctor names (by host UUID), then restart its gbrain processes; the hold clears once no older writer has committed a request for seven days.' } };
+ why: 'Run on each host doctor names (by host UUID), then restart its gbrain processes; the hold clears once no older writer has written for seven days.' } };
}
return { name, status: 'ok', details,
message: `Segmented page storage is on: pages over 1 MiB are stored in segments, up to ${policy.maxBytes} bytes on this ${engine.kind === 'pglite' ? 'PGLite' : 'Postgres'} brain.` };
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index af6c9e3b93..c09f4e5905 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -648,7 +648,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }
// Wave B PR 2 (segmented page storage, switch on). `since` is 'TBD' until the merge-slot stamp, which also stamps
// SEGMENTED_WRITER_FLOOR (persistence/writer-versions.ts) with the same release.
{ since: 'TBD', text: '`gbrain config set pages.segmented_storage on` stores pages over 1 MiB in segments; it is off by default in this release. 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. Turning it off again stores new pages inline up to 24 MiB; pages already stored in segments stay readable.' },
- { since: 'TBD', text: 'Segmented page storage stays off while an older gbrain writes to the same brain: a writer older than this release, or one that stamps no version, that admitted or published a managed write in the last 7 days keeps new pages over 1 MiB inline up to 24 MiB, even with `pages.segmented_storage` set to `on`. New doctor check `segmented_storage` shows the configured and effective value and names each blocking host; run `gbrain upgrade` there, and the hold clears 7 days after its last write. An older binary that writes without managed persistence is not detected.' },
+ { since: 'TBD', text: 'Segmented page storage stays off while an older gbrain writes to the same brain: a gbrain older than this release that in the last 7 days admitted or published a managed write, logged an import, sync or connector run, or (on Postgres) ran a resident `serve`, `sync`, `jobs`, `autopilot` or `mcp` process keeps new pages over 1 MiB inline up to 24 MiB, even with `pages.segmented_storage` set to `on`; writes from before the upgrade count too. New doctor check `segmented_storage` shows the configured and effective value and names each blocking host and how it was seen; run `gbrain upgrade` there, and the hold clears 7 days after its last write. Not detected: an older binary\'s single-page write on a brain without managed persistence, a run that dies before it logs, and an older binary that only reads or exports.' },
{ since: 'TBD', text: 'Pages stored in segments keep at most `versions.segmented_max_per_page` (default 50) version snapshots, and fewer when the old text they pin exceeds `versions.segmented_max_pinned_bytes` (default 64 MiB, never below the page size). A snapshot of such a page records its segment generation instead of copying the body. History of every other page is unchanged.' },
{ since: 'TBD', text: 'A page over 24 MiB imported or synced from its file is no longer stamped `embed_skip` and `content_flag: oversized` for its size: while `content_sanity.bytes_block` is unset, a segmented page is judged against its page ceiling, and the markup check samples its head, middle and tail as it does for any large page. A `content_sanity.bytes_block` set above 24 MiB no longer holds such a file; one set below the page still stops its embedding.' },
{ since: 'TBD', text: 'Forget and purge on a page stored in segments now rewrite and re-index only the segments that hold the struck or purged row.' },
@@ -661,6 +661,8 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }
{ since: 'TBD', text: 'A write that stores a page in segments says in its receipt whether search sees it: `searchable: true` when it commits (every new page up to 4 MiB and every rewrite), or `searchable: "pending"` for a larger new page while its chunks are built after commit, with `searchable_retry_after_ms` and a `searchable_fix` that reads the receipt again (`get_write_request`) until it says `searchable: true`. A new page up to 4 MiB was previously searchable only once a post-commit build finished.' },
{ since: 'TBD', text: '`gbrain projections drain` now builds pages stored in segments whose post-commit build never ran or died, skipping one another process is still building (claim renewed within 60 s), so a brain with no resident writer can make a large new page searchable. A pending receipt\'s `searchable_fix` names it as the fallback after the re-read wait, and doctor `text_projection_readiness` counts such pages (`segmented_pending`) and points to it.' },
{ since: 'TBD', text: 'Chunks of a page stored in segments keep a Markdown heading with the text after it, so a section appended after a full last chunk re-embeds only its own chunk (was two). Inline pages chunk as before.' },
+ { since: 'TBD', text: 'On Postgres, title search, the source-scoped vector scan, the chunk windows search reads around its hits and `get_page` now read the new `page_body_manifest` table for every page, inline ones included, whether or not `pages.segmented_storage` is on. A database role that neither owns the tables nor bypasses row level security needs `SELECT` on it, or those reads fail with `permission_denied` (42501). Row level security is on for the new segment tables (`page_segment_texts`, `page_body_manifest`, `page_body_stagings`, `page_body_staging_parts`, `page_view_digests`) and is re-enabled on every schema replay, as for `pages`, so a role without a policy reads none of their rows. Grant the table together with the source-scoped policies in docs/ENGINES.md ("Segmented page tables"), never with an open policy, or the role reads every source\'s segment text. A runtime role that owns the tables or bypasses row level security, the default setup, needs nothing.' },
+ { since: 'TBD', text: 'MCP `get_page` of a page stored in segments no longer reports `size.body_bytes` or `size.body_lines` (the stored body) to a remote caller, and its `page_body_segmented` refusal names the size of the body that caller may read, as for an inline page; the difference told how much text privacy fences and withdrawals hide. A local `gbrain get` still reports both.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/deletion-inventory.ts b/src/core/deletion-inventory.ts
index bf2deeb003..a605c50445 100644
--- a/src/core/deletion-inventory.ts
+++ b/src/core/deletion-inventory.ts
@@ -77,7 +77,7 @@ const ROWS: readonly Row[] = [
['facts', 'swept', 'fact', 'source_id entity_slug fact kind visibility notability context source source_session embedding source_markdown_slug claim_metric claim_unit claim_period event_type dimension value value_hash dim_status embedding_model embedded_text_hash write_principal_kind write_principal_id last_write_principal_kind last_write_principal_id attributed_to trust_tier write_origin'],
['files', 'swept', 'page_files', 'source_id page_slug filename storage_path mime_type content_hash metadata'],
['gbrain_cycle_locks', 'out_of_scope', 'no_memory_text', 'id holder_host'],
- ['ingest_log', 'out_of_scope', 'probed_reported', 'source_id source_type source_ref pages_updated summary', 'summary pages_updated'],
+ ['ingest_log', 'out_of_scope', 'probed_reported', 'source_id source_type source_ref pages_updated summary writer_version', 'summary pages_updated'],
['link_edge_proposals', 'out_of_scope', 'probed_reported', 'source_id link_type evidence_hash status model generated_line detail', 'generated_line detail'],
['link_relationships', 'out_of_scope', 'no_memory_text', 'link_type scope source_id semantics status_now evidence_hash'],
['link_transitions', 'out_of_scope', 'no_memory_text', 'source_id link_type kind date_precision producer line_hash'],
diff --git a/src/core/ops/get-page-body.ts b/src/core/ops/get-page-body.ts
index 7c732af4c1..1eadfb7770 100644
--- a/src/core/ops/get-page-body.ts
+++ b/src/core/ops/get-page-body.ts
@@ -216,10 +216,13 @@ export async function assertFullReadFits(ctx: OperationContext, page: Pick<Page,
* A segmented page is never built whole (spec 7.2). Every caller gets page_body_segmented with a fix that reads it in
* pieces (body: 'auto' gives the outline and the first window), and a trusted local `gbrain get` answers it by
* streaming the page. The thin client's whole-page read keeps page_too_large_for_inline: that is its paging signal
- * (it pages view: 'markdown' to the end), refused from body_bytes before any body is read.
+ * (it pages view: 'markdown' to the end), refused before any window is read. A remote caller is told the size of the
+ * read projection (as an inline page reports its privacy-stripped body), never the stored body_bytes, whose difference
+ * would say how much text the projection hides.
*/
-export function segmentedFullReadError(ctx: OperationContext, page: Page, req: BodyRequest): OperationError {
- const total = pageBodyBytes(page);
+export async function segmentedFullReadError(ctx: OperationContext, page: Page, req: BodyRequest): Promise<OperationError> {
+ const total = ctx.remote === false ? pageBodyBytes(page)
+ : (await segmentedReadDocument(ctx.engine, await openSegmentedBody(ctx.engine, { pageId: page.id }))).total;
const windows = "Read it in pieces: get_page body: 'auto' returns the outline and the first window, then body: 'window' with lines, bytes, around_chunk_id or next_cursor reads on.";
const fix = segmentedReadFix(page.slug, page.source_id);
if (ctx.remote === false) {
@@ -338,13 +341,14 @@ function inlineDocument(doc: PageDocument): WindowDocument {
/**
* A segmented page's document and size (spec 7.2): read-view totals from the stored sums (the line count cached
- * per revision), the stored body size, and for `none` the tail digest; a markdown view's size is its cached digest.
+ * per revision), for a trusted caller the stored body size, and for `none` the tail digest; a markdown view's size
+ * is its cached digest. A remote caller gets projected totals only, as for an inline page.
*/
async function segmentedWindows(ctx: OperationContext, input: PartialReadInput, req: BodyRequest, mode: BodyMode): Promise<{ doc: WindowDocument; size: Record<string, unknown> }> {
const { page, revision, tags } = input;
const body = await openSegmentedBody(ctx.engine, { pageId: page.id });
const audience = ctx.remote === false ? 'trusted' : 'remote';
- const stored = { body_bytes: body.bodyBytes, body_lines: body.bodyLines };
+ const stored = audience === 'trusted' ? { body_bytes: body.bodyBytes, body_lines: body.bodyLines } : {};
let seg: SegmentedDocument;
let size: Record<string, unknown>;
if (req.view === 'markdown') {
diff --git a/src/core/ops/pages.ts b/src/core/ops/pages.ts
index 1fc4013831..d26eb55edb 100644
--- a/src/core/ops/pages.ts
+++ b/src/core/ops/pages.ts
@@ -230,7 +230,7 @@ const get_page: Operation = {
...(resolved_slug ? { resolved_slug } : {}), ...(content_flag ? { content_flag } : {}) } }, bodyRequest);
return lineGrammar ? { ...partial, line_grammar: lineGrammar } : partial;
}
- if (segmented) throw segmentedFullReadError(ctx, page, bodyRequest);
+ if (segmented) throw await segmentedFullReadError(ctx, page, bodyRequest);
const projected = projectGetPage(visibleBody, {
revision: snapshot!.revision, tags, includeContent, contentOnly, resolved_slug, content_flag, quarantined, trust: readable.trust,
...(timelineEntries ? { timeline_entries: timelineEntries } : {}),
diff --git a/src/core/page-body/limits.ts b/src/core/page-body/limits.ts
index df360a8e20..4f4930c115 100644
--- a/src/core/page-body/limits.ts
+++ b/src/core/page-body/limits.ts
@@ -10,7 +10,7 @@
*/
import type { BrainEngine } from '../engine.ts';
import { PAGE_INLINE_MAX_BYTES, PAGE_MAX_BYTES } from '../page-size-policy.ts';
-import type { RecentWriterVersion } from '../persistence/writer-versions.ts';
+import type { SegmentedGateWriter } from '../persistence/writer-versions.ts';
export { PAGE_INLINE_MAX_BYTES };
@@ -130,20 +130,24 @@ export function parseSegmentedStorage(raw: string | null): 'on' | 'off' | 'unset
return /^(off|false|0|no)$/i.test(value) ? 'off' : 'invalid';
}
-let writerGate = new WeakMap<object, { at: number; blockers: RecentWriterVersion[] }>();
+let writerGate = new WeakMap<object, { at: number; blockers: SegmentedGateWriter[] }>();
+/** Work counter: reads of the writer-version gate (the TTL cache answers the rest). */
+export const segmentedWriterGateWork = { reads: 0 };
/**
- * Writers that committed a request in the last `SEGMENTED_WRITER_WINDOW_DAYS` days with a version below
- * `SEGMENTED_WRITER_FLOOR` or no stamp. Any one keeps segmented storage off. Cached per engine for
+ * Writers seen in the last `SEGMENTED_WRITER_WINDOW_DAYS` days that do not read segmented pages
+ * (`segmentedGateWriters`: evidence without the segment-reader mark, or a managed write stamped below
+ * `SEGMENTED_WRITER_FLOOR`). Any one keeps segmented storage off. Cached per engine for
* `SEGMENTED_WRITER_GATE_TTL_MS`; `fresh` (doctor) reads through.
*/
-export async function segmentedWriterBlockers(engine: Pick<BrainEngine, 'executeRaw'>, opts: { fresh?: boolean } = {}): Promise<RecentWriterVersion[]> {
+export async function segmentedWriterBlockers(engine: Pick<BrainEngine, 'executeRaw'>, opts: { fresh?: boolean } = {}): Promise<SegmentedGateWriter[]> {
let root: object = engine;
for (let proto = Object.getPrototypeOf(root); proto && !Object.hasOwn(proto, 'constructor'); proto = Object.getPrototypeOf(proto)) root = proto;
const cached = writerGate.get(root);
if (!opts.fresh && cached && Date.now() - cached.at < SEGMENTED_WRITER_GATE_TTL_MS) return cached.blockers;
- const { recentWriterVersions, SEGMENTED_WRITER_FLOOR, writerVersionBelowFloor } = await import('../persistence/writer-versions.ts');
- const blockers = (await recentWriterVersions(engine, SEGMENTED_WRITER_WINDOW_DAYS)).filter(row => writerVersionBelowFloor(row.version, SEGMENTED_WRITER_FLOOR));
+ const { segmentedGateWriters } = await import('../persistence/writer-versions.ts');
+ segmentedWriterGateWork.reads++;
+ const blockers = await segmentedGateWriters(engine, SEGMENTED_WRITER_WINDOW_DAYS);
writerGate.set(root, { at: Date.now(), blockers });
return blockers;
}
diff --git a/src/core/page-body/schema.ts b/src/core/page-body/schema.ts
index 7eb2ada6fa..99e700a91e 100644
--- a/src/core/page-body/schema.ts
+++ b/src/core/page-body/schema.ts
@@ -134,3 +134,28 @@ CREATE TABLE IF NOT EXISTS page_body_staging_parts (
body BYTEA NOT NULL,
PRIMARY KEY (staging_id, part_no)
);`;
+
+/**
+ * The segment tables hold page text (`page_segment_texts`, `page_body_staging_parts`) or a page's shape and
+ * headings (`page_body_manifest`, `page_body_stagings`, `page_view_digests`), so they get the posture of `pages`
+ * and `content_chunks`: RLS on, re-asserted on every schema replay like the core list in src/schema.sql, so a brain
+ * the auto-RLS event trigger (v35) missed, or one where it was dropped or disabled, never serves segment text to a
+ * role `pages` returns no rows to. Only under a role that bypasses RLS (else the runtime role would lock itself out),
+ * and only for a table still without it (ENABLE takes an ACCESS EXCLUSIVE lock even when RLS is on, #5227).
+ * `page_view_digests` is absent while migration v248 runs. Postgres only: PGLite has no role system, and its
+ * bootstrap enables RLS on no core table either. Source-scoped policies are operator SQL (docs/ENGINES.md).
+ */
+export const PAGE_BODY_RLS_TABLES = ['page_segment_texts', 'page_body_manifest', 'page_body_stagings', 'page_body_staging_parts', 'page_view_digests'] as const;
+export const PAGE_BODY_RLS_SQL = `DO $rls$
+DECLARE target TEXT;
+BEGIN
+ IF EXISTS (SELECT 1 FROM pg_roles r WHERE pg_has_role(current_user, r.oid, 'USAGE') AND (r.rolbypassrls OR r.rolsuper)) THEN
+ FOREACH target IN ARRAY ARRAY[${PAGE_BODY_RLS_TABLES.map(t => `'${t}'`).join(',')}] LOOP
+ IF EXISTS (SELECT 1 FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace
+ WHERE n.nspname = current_schema() AND c.relname = target AND c.relkind = 'r' AND NOT c.relrowsecurity) THEN
+ EXECUTE format('ALTER TABLE %I ENABLE ROW LEVEL SECURITY', target);
+ END IF;
+ END LOOP;
+ END IF;
+END $rls$;`;
+
diff --git a/src/core/persistence/consumer-heartbeat.ts b/src/core/persistence/consumer-heartbeat.ts
index eaaf47b33e..4341fe9c76 100644
--- a/src/core/persistence/consumer-heartbeat.ts
+++ b/src/core/persistence/consumer-heartbeat.ts
@@ -215,10 +215,10 @@ export interface ConsumerHeartbeat {
type DirectEngine = SqlEngine & Partial<Pick<BrainEngine, 'kind' | 'executeRawDirect'>>;
const RENEW_SQL = `WITH purged AS (
DELETE FROM persistence_consumers WHERE host_id=$1::uuid AND renewed_at < now() - ($14::integer * interval '1 millisecond') AND NOT (pid=$2::integer AND nonce=$3))
- INSERT INTO persistence_consumers(host_id,pid,nonce,pid_ns,kind,mode,restart_required,root_barrier_age_ms,pool,host_json_path,persistence_home,minted_under,version,boot_id,process_start)
- VALUES($1::uuid,$2::integer,$3,$4,$5,$6,$7::boolean,$8::integer,$9::text::jsonb,$10,$11,$12::text::jsonb,$13,$15,$16)
+ INSERT INTO persistence_consumers(host_id,pid,nonce,pid_ns,kind,mode,restart_required,root_barrier_age_ms,pool,host_json_path,persistence_home,minted_under,version,boot_id,process_start,segment_reader)
+ VALUES($1::uuid,$2::integer,$3,$4,$5,$6,$7::boolean,$8::integer,$9::text::jsonb,$10,$11,$12::text::jsonb,$13,$15,$16,true)
ON CONFLICT (host_id,pid,nonce) DO UPDATE SET renewed_at=now(),mode=EXCLUDED.mode,restart_required=EXCLUDED.restart_required,
- root_barrier_age_ms=EXCLUDED.root_barrier_age_ms,pool=EXCLUDED.pool,version=EXCLUDED.version`;
+ root_barrier_age_ms=EXCLUDED.root_barrier_age_ms,pool=EXCLUDED.pool,version=EXCLUDED.version,segment_reader=EXCLUDED.segment_reader`;
/**
* Starts this process's heartbeat row for `hostId` and renews it every
diff --git a/src/core/persistence/group-publish.ts b/src/core/persistence/group-publish.ts
index de5a9a902f..bb42fab5e0 100644
--- a/src/core/persistence/group-publish.ts
+++ b/src/core/persistence/group-publish.ts
@@ -492,7 +492,7 @@ export async function completeGroup(tx: BrainEngine, rows: WriteRequest[], outco
), done AS (
UPDATE persistence_requests r SET state='committed',outcome=m.outcome::jsonb,error_code=NULL,error_message=NULL,
completed_at=now(),updated_at=now(),claim_expires_at=NULL,blocked_reason=NULL,
- consumer_version=$6,consumer_host_id=$7::uuid,published_at=now(),preparation_attempts=0,
+ consumer_version=$6,consumer_host_id=$7::uuid,consumer_segment_reader=true,published_at=now(),preparation_attempts=0,
terminal_reservation=CASE WHEN COALESCE(e.unfinished,false) THEN r.terminal_reservation
ELSE LEAST(r.terminal_reservation,m.retained+COALESCE(e.bytes,0)) END
FROM m LEFT JOIN e ON e.request_id=m.id
diff --git a/src/core/persistence/journal.ts b/src/core/persistence/journal.ts
index a55b55cebd..b005012c34 100644
--- a/src/core/persistence/journal.ts
+++ b/src/core/persistence/journal.ts
@@ -293,8 +293,8 @@ async function prepareAdmission(engine: BrainEngine, input: WriteAdmission, over
INSERT INTO persistence_requests
(principal_kind,principal_id,request_id,operation,source_id,source_incarnation,page_id,slug,
worktree_id,topology_generation,digest,intent,authority,intent_bytes,terminal_reservation,target_kind,protocol_version,
- admitter_version,admitter_host_id,client_request_id)
- VALUES($1,$2,$3::uuid,$4,$5,$6::uuid,$7,$8,$9::uuid,$10,$11,$12::text::jsonb,$13::text::jsonb,$14,$15,$16,$17,$18,$19::uuid,$21)
+ admitter_version,admitter_host_id,client_request_id,admitter_segment_reader)
+ VALUES($1,$2,$3::uuid,$4,$5,$6::uuid,$7,$8,$9::uuid,$10,$11,$12::text::jsonb,$13::text::jsonb,$14,$15,$16,$17,$18,$19::uuid,$21,true)
RETURNING *`, [input.principal.kind, input.principal.id, requestId, input.operation, input.sourceId,
input.sourceIncarnation, input.pageId ?? null, input.slug, input.worktreeId ?? null, input.topologyGeneration ?? null,
fingerprint, JSON.stringify(input.intent), JSON.stringify(input.authority), bytes, terminalBytes, input.targetKind ?? 'page', input.protocolVersion ?? 1,
@@ -370,9 +370,9 @@ export async function admitWriteGroupInTransaction(tx: BrainEngine, inputs: Writ
const [rows] = await pipelined(tx, [() => tx.executeRaw<WriteRequest>(`INSERT INTO persistence_requests
(principal_kind,principal_id,request_id,operation,source_id,source_incarnation,page_id,slug,
worktree_id,topology_generation,digest,intent,authority,intent_bytes,terminal_reservation,target_kind,protocol_version,
- admitter_version,admitter_host_id,client_request_id)
+ admitter_version,admitter_host_id,client_request_id,admitter_segment_reader)
SELECT $1,$2,(e->>'request_id')::uuid,$3,$4,$5::uuid,(e->>'page_id')::integer,e->>'slug',$6::uuid,$7,e->>'digest',e->'intent',$8::text::jsonb,
- (e->>'intent_bytes')::bigint,(e->>'terminal_reservation')::bigint,'page',1,$9,$10::uuid,e->>'client_request_id'
+ (e->>'intent_bytes')::bigint,(e->>'terminal_reservation')::bigint,'page',1,$9,$10::uuid,e->>'client_request_id',true
FROM jsonb_array_elements($11::text::jsonb) WITH ORDINALITY AS t(e,n) ORDER BY n
RETURNING *`, [first.principal.kind, first.principal.id, first.operation, first.sourceId, first.sourceIncarnation, first.worktreeId ?? null,
first.topologyGeneration ?? null, JSON.stringify(first.authority), stamp.version, stamp.hostId,
@@ -848,6 +848,7 @@ export async function completeWrite(tx: SqlEngine, row: WriteRequest, state: 'co
error_code=$4,error_message=$5,error_detail=COALESCE($8::text::jsonb,error_detail),completed_at=now(),updated_at=now(),claim_expires_at=NULL,blocked_reason=NULL,
consumer_version=CASE WHEN $2='committed' THEN $6 ELSE consumer_version END,
consumer_host_id=CASE WHEN $2='committed' THEN $7::uuid ELSE consumer_host_id END,
+ consumer_segment_reader=CASE WHEN $2='committed' THEN true ELSE consumer_segment_reader END,
published_at=CASE WHEN $2='committed' THEN now() ELSE published_at END,
preparation_attempts=CASE WHEN $2='committed' THEN 0 ELSE preparation_attempts END,
terminal_reservation=CASE WHEN (SELECT unfinished FROM effects) THEN terminal_reservation
diff --git a/src/core/persistence/schema.ts b/src/core/persistence/schema.ts
index 0aacb5d148..5fe0d64c69 100644
--- a/src/core/persistence/schema.ts
+++ b/src/core/persistence/schema.ts
@@ -92,6 +92,7 @@ export const PERSISTENCE_CONSUMERS_TABLE_SQL = `CREATE TABLE IF NOT EXISTS persi
version text NOT NULL,
boot_id text,
process_start text,
+ segment_reader boolean,
PRIMARY KEY(host_id,pid,nonce)
)`;
/** Indexes the Postgres blob omits because a migration builds them CONCURRENTLY. */
diff --git a/src/core/persistence/writer-versions.ts b/src/core/persistence/writer-versions.ts
index 55682a0c3c..d22bc6a19b 100644
--- a/src/core/persistence/writer-versions.ts
+++ b/src/core/persistence/writer-versions.ts
@@ -1,6 +1,6 @@
/** Writer-version stamps on persistence_requests (migration 178): observation of older writers, not prevention. */
import { VERSION } from '../../version.ts';
-import { localHostId } from './identity.ts';
+import { existingLocalHostId, localHostId } from './identity.ts';
import type { SqlEngine } from './model.ts';
/** Writers older than this may still delete database-only timeline rows during publication. */
@@ -12,7 +12,10 @@ export const UNSTAMPED_WRITER = 'unstamped (binary older than this release)';
* without its segment texts. A recent one keeps `pages.segmented_storage` effectively off (`page-body/limits.ts`).
* A placeholder equal to the branch's VERSION until the merge-slot stamp, which sets it to the release that turns the
* switch on (the `since` of its BEHAVIOR_CHANGES row, pinned by test/large-pages/segmented-switch.test.ts). That
- * release must be above v0.60.252.0, the release that added segmented storage with the switch off.
+ * release must be above v0.60.252.0, the release that added segmented storage with the switch off. A version alone
+ * cannot tell a build with segment readers from a release of the same version without them (every release from
+ * v0.60.252.0 until the stamp has none), so the gate also requires the segment-reader mark (migration v251) on
+ * every write it sees: an unmarked writer blocks whatever its version, the floor included (`segmentedGateWriters`).
*/
export const SEGMENTED_WRITER_FLOOR = '0.60.252.0';
@@ -35,10 +38,16 @@ export function writerVersionBelowFloor(version: string | null, floor = WRITER_V
return order === null || order < 0;
}
-/** This binary's stamp. An unavailable host identity stamps no host rather than failing the write. */
-export function writerStamp(): { version: string; hostId: string | null } {
+/**
+ * This binary's stamp. An unavailable host identity stamps no host rather than failing the write; `mint: false` (the
+ * ingest log, written by commands that never register a writer) reads an existing identity and never creates one.
+ * Every write path that stamps it also sets the segment-reader mark (migration v251), which only binaries that read
+ * segmented pages write: a version string cannot tell a build with segment readers from a release of the same
+ * version without them.
+ */
+export function writerStamp(opts: { mint?: boolean } = {}): { version: string; hostId: string | null } {
let hostId: string | null = null;
- try { hostId = localHostId(); } catch { /* unwritable or invalid identity: stamp the version only */ }
+ try { hostId = opts.mint === false ? existingLocalHostId() : localHostId(); } catch { /* unwritable or invalid identity: stamp the version only */ }
return { version: VERSION, hostId };
}
@@ -88,3 +97,49 @@ export async function recentWriterVersions(engine: SqlEngine, days = 7): Promise
return rows.map(row => ({ role: row.role, host_id: row.host_id, principal: row.principal, version: row.version,
version_label: writerVersionLabel(row.version), last_seen: iso(row.last_seen), requests: Number(row.requests) }));
}
+
+/** A writer the segmented-storage gate saw in its window, by the evidence it left. */
+export interface SegmentedGateWriter {
+ /**
+ * admitter / consumer: a managed write's admitting and publishing binary (persistence_requests); importer: a run
+ * logged in ingest_log (gbrain import, sync, connectors, facts); resident: a live persistence consumer
+ * (serve, sync, jobs, autopilot, mcp; Postgres only).
+ */
+ role: 'admitter' | 'consumer' | 'importer' | 'resident';
+ host_id: string | null; principal: string; version: string | null; version_label: string;
+ /** The rows carried the segment-reader mark (migration v251), which only binaries that read segmented pages write. */
+ segment_reader: boolean;
+ last_seen: string | null; requests: number;
+}
+
+/**
+ * Writers seen in the last `days` that keep segmented storage off: evidence without the segment-reader mark (an
+ * older binary inserts NULL into a column it does not know; rows from before v251 count too), or a managed write
+ * stamped below `floor` (an unparsable or missing stamp counts as below). Admitters count in any state, so a
+ * failed or still-queued request of an older binary is seen as well; ingest-log and consumer rows are read only
+ * when unmarked (ingest_log_unmarked_idx). Not seen: an older binary that writes neither a request nor an
+ * ingest-log row (a single-page put on a brain without managed persistence, a run that dies before logging), and
+ * one-shot readers and exporters, which write nothing.
+ */
+export async function segmentedGateWriters(engine: SqlEngine, days: number, floor = SEGMENTED_WRITER_FLOOR): Promise<SegmentedGateWriter[]> {
+ const rows = await engine.executeRaw<Omit<SegmentedGateWriter, 'version_label' | 'last_seen' | 'requests'> & { last_seen: unknown; requests: number }>(
+ `WITH win AS (SELECT now()-($1::double precision*interval '1 day') AS since)
+ SELECT 'admitter' AS role,r.admitter_host_id::text AS host_id,r.principal_kind||':'||r.principal_id AS principal,r.admitter_version AS version,
+ COALESCE(r.admitter_segment_reader,false) AS segment_reader,MAX(r.created_at) AS last_seen,COUNT(*)::integer AS requests
+ FROM persistence_requests r CROSS JOIN win WHERE r.created_at>=win.since GROUP BY 2,3,4,5
+ UNION ALL
+ SELECT 'consumer',COALESCE(r.consumer_host_id,w.owner_host_id)::text,r.principal_kind||':'||r.principal_id,r.consumer_version,
+ COALESCE(r.consumer_segment_reader,false),MAX(COALESCE(r.published_at,r.completed_at)),COUNT(*)::integer
+ FROM persistence_requests r LEFT JOIN persistence_worktrees w ON w.id=r.worktree_id CROSS JOIN win
+ WHERE r.state='committed' AND COALESCE(r.published_at,r.completed_at)>=win.since GROUP BY 2,3,4,5
+ UNION ALL
+ SELECT 'importer',l.writer_host_id::text,'ingest:'||l.source_type,l.writer_version,false,MAX(l.created_at),COUNT(*)::integer
+ FROM ingest_log l CROSS JOIN win WHERE l.writer_segment_reader IS NOT TRUE AND l.created_at>=win.since GROUP BY 2,3,4
+ UNION ALL
+ SELECT 'resident',c.host_id::text,'process:'||c.kind,c.version,false,MAX(c.renewed_at),COUNT(*)::integer
+ FROM persistence_consumers c CROSS JOIN win WHERE c.segment_reader IS NOT TRUE AND c.renewed_at>=win.since GROUP BY 2,3,4
+ ORDER BY last_seen DESC`, [days]);
+ return rows.map(row => ({ role: row.role, host_id: row.host_id, principal: row.principal, version: row.version, version_label: writerVersionLabel(row.version),
+ segment_reader: row.segment_reader === true, last_seen: iso(row.last_seen), requests: Number(row.requests) }))
+ .filter(row => !row.segment_reader || writerVersionBelowFloor(row.version, floor));
+}
diff --git a/src/core/pglite-engine.ts b/src/core/pglite-engine.ts
index 07bcb5e4d6..8b733cbc43 100644
--- a/src/core/pglite-engine.ts
+++ b/src/core/pglite-engine.ts
@@ -1,4 +1,5 @@
import { registerManagedFilesystemEngine } from './persistence/filesystem-guard.ts';
+import { writerStamp } from './persistence/writer-versions.ts';
import { replaceDerivedLinks, replaceDerivedLinksBatch, type DerivedLinkBatchItem, type DerivedLinkOrigin, type DerivedLinkReplacementOptions } from './derived-links.ts';
import { trackPgliteDatabase, PgliteClosingError, notifyPgliteOpened } from './pglite-lifecycle.ts';
import { mutatePageTag } from './page-state/tags.ts';
@@ -2756,10 +2757,12 @@ export class PGLiteEngine implements BrainEngine {
// v0.31.2 (codex P1 #3): source_id threaded so multi-source brains can
// scope ingest_log queries. Default 'default' matches the column DEFAULT.
const sourceId = entry.source_id ?? 'default';
+ // v251: the writer's version, host and segment-reader mark (writer-versions.ts writerStamp).
+ const stamp = writerStamp({ mint: false });
await this.db.query(
- `INSERT INTO ingest_log (source_id, source_type, source_ref, pages_updated, summary)
- VALUES ($1, $2, $3, $4::jsonb, $5)`,
- [sourceId, entry.source_type, entry.source_ref, JSON.stringify(entry.pages_updated), entry.summary]
+ `INSERT INTO ingest_log (source_id, source_type, source_ref, pages_updated, summary, writer_version, writer_host_id, writer_segment_reader)
+ VALUES ($1, $2, $3, $4::jsonb, $5, $6, $7::uuid, true)`,
+ [sourceId, entry.source_type, entry.source_ref, JSON.stringify(entry.pages_updated), entry.summary, stamp.version, stamp.hostId]
);
}
@@ -2770,8 +2773,8 @@ export class PGLiteEngine implements BrainEngine {
const scoped = opts?.sourceIds && opts.sourceIds.length > 0;
const { rows } = await this.db.query(
scoped
- ? `SELECT * FROM ingest_log WHERE source_id = ANY($2::text[]) ORDER BY created_at DESC LIMIT $1`
- : `SELECT * FROM ingest_log ORDER BY created_at DESC LIMIT $1`,
+ ? `SELECT id, source_id, source_type, source_ref, pages_updated, summary, created_at FROM ingest_log WHERE source_id = ANY($2::text[]) ORDER BY created_at DESC LIMIT $1`
+ : `SELECT id, source_id, source_type, source_ref, pages_updated, summary, created_at FROM ingest_log ORDER BY created_at DESC LIMIT $1`,
scoped ? [limit, opts?.sourceIds] : [limit]
);
// Belt-and-suspenders source_id fallback for any pre-v50 row that
diff --git a/src/core/pglite-schema.generated.ts b/src/core/pglite-schema.generated.ts
index 292dafef19..638eaaf452 100644
--- a/src/core/pglite-schema.generated.ts
+++ b/src/core/pglite-schema.generated.ts
@@ -300,7 +300,10 @@ CREATE TABLE IF NOT EXISTS ingest_log (
source_ref TEXT NOT NULL,
pages_updated JSONB NOT NULL DEFAULT '[]',
summary TEXT NOT NULL DEFAULT '',
- created_at TIMESTAMPTZ NOT NULL DEFAULT now()
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ writer_version TEXT,
+ writer_host_id UUID,
+ writer_segment_reader BOOLEAN
);
CREATE INDEX IF NOT EXISTS idx_ingest_log_source_type_created
@@ -1370,6 +1373,8 @@ CREATE TABLE IF NOT EXISTS page_body_staging_parts (
PRIMARY KEY (staging_id, part_no)
);
+
+
-- Durable concurrent persistence (migration 151).
CREATE TABLE IF NOT EXISTS persistence_brain (
singleton integer PRIMARY KEY CHECK (singleton = 1),
@@ -1499,6 +1504,7 @@ CREATE TABLE IF NOT EXISTS persistence_consumers (
version text NOT NULL,
boot_id text,
process_start text,
+ segment_reader boolean,
PRIMARY KEY(host_id,pid,nonce)
);
diff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.ts
index 26366f8fe6..525cb5f389 100644
--- a/src/core/postgres-engine.ts
+++ b/src/core/postgres-engine.ts
@@ -160,6 +160,7 @@ export function cancelSettleMs(): number {
}
import type { SqlExecutor } from './engine-sql/executor.ts';
import { scopedRead, unscopedExecutor } from './engine-sql/brands.ts';
+import { writerStamp } from './persistence/writer-versions.ts';
function escapeSqlStringLiteral(value: string): string {
return value.replace(/'/g, "''");
@@ -2555,9 +2556,11 @@ export class PostgresEngine implements BrainEngine {
// v0.31.2 (codex P1 #3): source_id threaded so multi-source brains can
// scope ingest_log queries. Default 'default' matches the column DEFAULT.
const sourceId = entry.source_id ?? 'default';
+ // v251: the writer's version, host and segment-reader mark (writer-versions.ts writerStamp).
+ const stamp = writerStamp({ mint: false });
await sql`
- INSERT INTO ingest_log (source_id, source_type, source_ref, pages_updated, summary)
- VALUES (${sourceId}, ${entry.source_type}, ${entry.source_ref}, ${sql.json(entry.pages_updated)}, ${entry.summary})
+ INSERT INTO ingest_log (source_id, source_type, source_ref, pages_updated, summary, writer_version, writer_host_id, writer_segment_reader)
+ VALUES (${sourceId}, ${entry.source_type}, ${entry.source_ref}, ${sql.json(entry.pages_updated)}, ${entry.summary}, ${stamp.version}, ${stamp.hostId}::uuid, true)
`;
}
@@ -2570,7 +2573,7 @@ export class PostgresEngine implements BrainEngine {
? sql`WHERE source_id = ANY(${opts.sourceIds}::text[])`
: sql``;
const rows = await sql`
- SELECT * FROM ingest_log ${scope} ORDER BY created_at DESC LIMIT ${limit}
+ SELECT id, source_id, source_type, source_ref, pages_updated, summary, created_at FROM ingest_log ${scope} ORDER BY created_at DESC LIMIT ${limit}
`;
// Belt-and-suspenders source_id fallback for any pre-v50 row.
return (rows as unknown as IngestLogEntry[]).map(r => ({
diff --git a/src/core/schema-embedded.generated.ts b/src/core/schema-embedded.generated.ts
index 4a29aef8f6..f0cf036a58 100644
--- a/src/core/schema-embedded.generated.ts
+++ b/src/core/schema-embedded.generated.ts
@@ -680,7 +680,11 @@ CREATE TABLE IF NOT EXISTS ingest_log (
source_ref TEXT NOT NULL,
pages_updated JSONB NOT NULL DEFAULT '[]',
summary TEXT NOT NULL DEFAULT '',
- created_at TIMESTAMPTZ NOT NULL DEFAULT now()
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ -- Migration v251: the writing binary's version, host and segment-reader mark (NULL from a binary older than v251).
+ writer_version TEXT,
+ writer_host_id UUID,
+ writer_segment_reader BOOLEAN
);
CREATE INDEX IF NOT EXISTS idx_ingest_log_source_type_created
@@ -2106,6 +2110,21 @@ CREATE TABLE IF NOT EXISTS page_body_staging_parts (
);
-- END GENERATED from src/core/page-body/schema.ts (PAGE_BODY_SCHEMA_SQL)
+-- BEGIN GENERATED from src/core/page-body/schema.ts (PAGE_BODY_RLS_SQL). Edit that file, then run: bun run build:schema
+DO \$rls\$
+DECLARE target TEXT;
+BEGIN
+ IF EXISTS (SELECT 1 FROM pg_roles r WHERE pg_has_role(current_user, r.oid, 'USAGE') AND (r.rolbypassrls OR r.rolsuper)) THEN
+ FOREACH target IN ARRAY ARRAY['page_segment_texts','page_body_manifest','page_body_stagings','page_body_staging_parts','page_view_digests'] LOOP
+ IF EXISTS (SELECT 1 FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace
+ WHERE n.nspname = current_schema() AND c.relname = target AND c.relkind = 'r' AND NOT c.relrowsecurity) THEN
+ EXECUTE format('ALTER TABLE %I ENABLE ROW LEVEL SECURITY', target);
+ END IF;
+ END LOOP;
+ END IF;
+END \$rls\$;
+-- END GENERATED from src/core/page-body/schema.ts (PAGE_BODY_RLS_SQL)
+
-- Durable concurrent persistence (migration 151).
-- BEGIN GENERATED from src/core/persistence/schema.ts (PERSISTENCE_SCHEMA_STATEMENTS). Edit that file, then run: bun run build:schema
CREATE TABLE IF NOT EXISTS persistence_brain (
@@ -2224,6 +2243,7 @@ CREATE TABLE IF NOT EXISTS persistence_consumers (
version text NOT NULL,
boot_id text,
process_start text,
+ segment_reader boolean,
PRIMARY KEY(host_id,pid,nonce)
);
diff --git a/src/core/schema-migrations/latest.generated.ts b/src/core/schema-migrations/latest.generated.ts
index a37b519c57..e61c389fc5 100644
--- a/src/core/schema-migrations/latest.generated.ts
+++ b/src/core/schema-migrations/latest.generated.ts
@@ -4,4 +4,4 @@
// The highest schema migration version (migrate.ts LATEST_VERSION), importable without
// loading the migrations themselves.
-export const LATEST_SCHEMA_VERSION = 250;
+export const LATEST_SCHEMA_VERSION = 251;
diff --git a/src/core/schema-migrations/registry.generated.ts b/src/core/schema-migrations/registry.generated.ts
index 1ee0a2a347..1299e62608 100644
--- a/src/core/schema-migrations/registry.generated.ts
+++ b/src/core/schema-migrations/registry.generated.ts
@@ -251,6 +251,7 @@ import { v247 } from './v247-page-extraction-state.ts';
import { v248 } from './v248-segmented-page-storage.ts';
import { v249 } from './v249-segmented-chunk-gc-index.ts';
import { v250 } from './v250-page-view-digests.ts';
+import { v251 } from './v251-segment-reader-marks.ts';
// Array order is historical (see HISTORICAL_ARRAY_ORDER in the generator); the
// runner sorts by version before applying.
@@ -500,4 +501,5 @@ export const MIGRATIONS: Migration[] = [
v248,
v249,
v250,
+ v251,
];
diff --git a/src/core/schema-migrations/v251-segment-reader-marks.ts b/src/core/schema-migrations/v251-segment-reader-marks.ts
new file mode 100644
index 0000000000..694ac59702
--- /dev/null
+++ b/src/core/schema-migrations/v251-segment-reader-marks.ts
@@ -0,0 +1,50 @@
+import type { Migration } from './types.ts';
+import { buildIndexOnline, migrationNotice } from './helpers.ts';
+
+// Applied by src/core/migrate.ts on the next initSchema(); see docs/ENGINES.md
+// ("Canonical schema sources") for when schema.sql or a TS fragment also changes.
+//
+// Wave B segment-reader marks (fix lane B, B3/B6): the segmented-storage gate
+// (page-body/limits.ts segmentedWriterBlockers) must see every binary that
+// writes without understanding segmented pages. A version string cannot say
+// so (a branch build and a release of the same VERSION stamp the same text),
+// so each write path of a binary with segment readers sets a mark, and a
+// binary older than this migration, which does not know the column, leaves it
+// NULL in every row it inserts:
+// - persistence_requests.admitter_segment_reader / consumer_segment_reader:
+// managed writes, next to the v178 version stamps (migration-only, like them);
+// - ingest_log.writer_version / writer_host_id / writer_segment_reader: the
+// row `gbrain import`, sync, connectors and the facts paths log per run
+// (engine logIngest), which unmanaged writes leave behind; also in
+// schema.sql's CREATE TABLE, appended, so fresh and upgraded brains share
+// the column order;
+// - persistence_consumers.segment_reader: the heartbeat of a resident serve,
+// sync, jobs, autopilot or mcp process (also in PERSISTENCE_CONSUMERS_TABLE_SQL).
+// Never backfilled: a past writer cannot be proven to read segments, so rows
+// from before this migration count as unmarked for the gate's 7-day window.
+// ingest_log_unmarked_idx keeps the gate's read off a scan of the whole log:
+// partial on the unmarked rows (every row before this migration, then only
+// what an older binary writes), built online (CONCURRENTLY on Postgres).
+export const INGEST_LOG_UNMARKED_INDEX = {
+ name: 'ingest_log_unmarked_idx',
+ table: 'ingest_log',
+ sql: 'CREATE INDEX IF NOT EXISTS ingest_log_unmarked_idx ON ingest_log (created_at) WHERE writer_segment_reader IS NOT TRUE',
+};
+
+export const v251: Migration = {
+ version: 251,
+ name: 'segment_reader_marks',
+ idempotent: true,
+ transaction: false,
+ sql: `
+ ALTER TABLE persistence_requests ADD COLUMN IF NOT EXISTS admitter_segment_reader boolean;
+ ALTER TABLE persistence_requests ADD COLUMN IF NOT EXISTS consumer_segment_reader boolean;
+ ALTER TABLE persistence_consumers ADD COLUMN IF NOT EXISTS segment_reader boolean;
+ ALTER TABLE ingest_log ADD COLUMN IF NOT EXISTS writer_version text;
+ ALTER TABLE ingest_log ADD COLUMN IF NOT EXISTS writer_host_id uuid;
+ ALTER TABLE ingest_log ADD COLUMN IF NOT EXISTS writer_segment_reader boolean;
+ `,
+ handler: async engine => {
+ await buildIndexOnline(engine, 251, INGEST_LOG_UNMARKED_INDEX, { notice: migrationNotice });
+ },
+};
diff --git a/src/schema.sql b/src/schema.sql
index 58ce56ff50..c545aefd0c 100644
--- a/src/schema.sql
+++ b/src/schema.sql
@@ -676,7 +676,11 @@ CREATE TABLE IF NOT EXISTS ingest_log (
source_ref TEXT NOT NULL,
pages_updated JSONB NOT NULL DEFAULT '[]',
summary TEXT NOT NULL DEFAULT '',
- created_at TIMESTAMPTZ NOT NULL DEFAULT now()
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ -- Migration v251: the writing binary's version, host and segment-reader mark (NULL from a binary older than v251).
+ writer_version TEXT,
+ writer_host_id UUID,
+ writer_segment_reader BOOLEAN
);
CREATE INDEX IF NOT EXISTS idx_ingest_log_source_type_created
@@ -2102,6 +2106,21 @@ CREATE TABLE IF NOT EXISTS page_body_staging_parts (
);
-- END GENERATED from src/core/page-body/schema.ts (PAGE_BODY_SCHEMA_SQL)
+-- BEGIN GENERATED from src/core/page-body/schema.ts (PAGE_BODY_RLS_SQL). Edit that file, then run: bun run build:schema
+DO $rls$
+DECLARE target TEXT;
+BEGIN
+ IF EXISTS (SELECT 1 FROM pg_roles r WHERE pg_has_role(current_user, r.oid, 'USAGE') AND (r.rolbypassrls OR r.rolsuper)) THEN
+ FOREACH target IN ARRAY ARRAY['page_segment_texts','page_body_manifest','page_body_stagings','page_body_staging_parts','page_view_digests'] LOOP
+ IF EXISTS (SELECT 1 FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace
+ WHERE n.nspname = current_schema() AND c.relname = target AND c.relkind = 'r' AND NOT c.relrowsecurity) THEN
+ EXECUTE format('ALTER TABLE %I ENABLE ROW LEVEL SECURITY', target);
+ END IF;
+ END LOOP;
+ END IF;
+END $rls$;
+-- END GENERATED from src/core/page-body/schema.ts (PAGE_BODY_RLS_SQL)
+
-- Durable concurrent persistence (migration 151).
-- BEGIN GENERATED from src/core/persistence/schema.ts (PERSISTENCE_SCHEMA_STATEMENTS). Edit that file, then run: bun run build:schema
CREATE TABLE IF NOT EXISTS persistence_brain (
@@ -2220,6 +2239,7 @@ CREATE TABLE IF NOT EXISTS persistence_consumers (
version text NOT NULL,
boot_id text,
process_start text,
+ segment_reader boolean,
PRIMARY KEY(host_id,pid,nonce)
);
diff --git a/test/e2e/segmented-rls-scope.test.ts b/test/e2e/segmented-rls-scope.test.ts
new file mode 100644
index 0000000000..66214e1e42
--- /dev/null
+++ b/test/e2e/segmented-rls-scope.test.ts
@@ -0,0 +1,186 @@
+/**
+ * Segmented page tables under Postgres RLS (Wave B PR 2, fix lane B: B1, B2).
+ *
+ * 1. Protects: the five segment tables (page_segment_texts, page_body_manifest, page_body_stagings,
+ * page_body_staging_parts, page_view_digests) get the RLS posture of `pages`: enabled on every schema replay, so a
+ * non-owner NOBYPASSRLS role with table SELECT and no policy reads none of their rows, as it reads no page. The
+ * operator recipe in docs/ENGINES.md (applied here verbatim) scopes them by source: a role scoped to src-a searches
+ * and reads its segmented page through every arm that probes the manifest, and never sees src-b's segment text,
+ * manifest rows or digests, with or without the GBRAIN_RLS_SCOPE_BINDING per-read binding. A role holding only the
+ * pre-Wave-B grant set (no page_body_manifest) fails title search with permission_denied, the behavior change the
+ * BEHAVIOR_CHANGES row names.
+ * 2. Fails when: the schema replay stops re-enabling RLS on a segment table, the docs recipe is removed or stops
+ * isolating sources, a search arm reads a segment table the recipe does not cover, or the manifest stops being
+ * read by title search without the docs saying so.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { readFileSync } from 'node:fs';
+import { join } from 'node:path';
+import type { BrainEngine } from '../../src/core/engine.ts';
+import { importFromContent } from '../../src/core/import-file.ts';
+import type { GBrainConfig } from '../../src/core/config.ts';
+import { operations, type OperationContext } from '../../src/core/operations.ts';
+import { materializeSegmentedBody } from '../../src/core/page-body/ingest.ts';
+import type { PostgresEngine } from '../../src/core/postgres-engine.ts';
+import { conversationPage } from '../helpers/conversation-page.ts';
+import { withEnv } from '../helpers/with-env.ts';
+import { hasDatabase, setupDB, teardownDB } from './helpers.ts';
+
+const tag = randomUUID().replaceAll('-', '').slice(0, 12);
+const OPEN = `gbrain_seg_rls_open_${tag}`;
+const READER = `gbrain_seg_rls_reader_${tag}`;
+const LEGACY = `gbrain_seg_rls_legacy_${tag}`;
+const SOURCES = { 'src-a': 'alphaneedle', 'src-b': 'bravoneedle' } as const;
+const slugOf = (id: string) => `notes/ledger-${id}`;
+const PAGE_BODY_RLS_TABLES = ['page_body_manifest', 'page_body_staging_parts', 'page_body_stagings', 'page_segment_texts', 'page_view_digests'];
+/** What a search and a body read touch besides the recipe's tables, opened to the reader. */
+const SEARCH_SIDE_TABLES = ['config', 'timeline_entries'];
+
+/** The SQL between the recipe markers in docs/ENGINES.md, for `role`. */
+function docsRecipe(role: string): string {
+ const doc = readFileSync(join(import.meta.dir, '../../docs/ENGINES.md'), 'utf8');
+ const block = /<!-- gbrain:segmented-rls-recipe:begin[^>]*-->\s*\`\`\`sql\n([\s\S]*?)\`\`\`\s*<!-- gbrain:segmented-rls-recipe:end -->/.exec(doc);
+ if (!block) throw new Error('docs/ENGINES.md has no segmented-rls-recipe block');
+ return block[1]!.replaceAll('<reader-role>', role);
+}
+
+async function asRole<T>(engine: BrainEngine, role: string, fn: (tx: BrainEngine) => Promise<T>, scopes?: string): Promise<T> {
+ return engine.transaction(async tx => {
+ await tx.executeRaw(`SET LOCAL ROLE ${role}`);
+ if (scopes !== undefined) await tx.executeRaw(`SELECT set_config('app.scopes', $1, true)`, [scopes]);
+ return fn(tx);
+ });
+}
+
+const sourcesOf = (hits: Array<{ source_id?: unknown }>) => [...new Set(hits.map(h => String(h.source_id)))].sort();
+
+(hasDatabase() ? describe : describe.skip)('segmented page tables under RLS', () => {
+ let engine: PostgresEngine;
+ const pageIds: Record<string, number> = {};
+ let policies: Array<{ name: string; table: string }> = [];
+ let forced: string[] = [];
+
+ beforeAll(async () => {
+ engine = await setupDB();
+ await engine.setConfig('pages.segmented_storage', 'on');
+ for (const [id, needle] of Object.entries(SOURCES)) {
+ await engine.executeRaw('INSERT INTO sources (id, name) VALUES ($1, $1) ON CONFLICT (id) DO NOTHING', [id]);
+ const content = conversationPage(2 * 1024 * 1024, { seed: id === 'src-a' ? 71 : 72, title: `Ledger ${needle}`, needles: [{ at: 0.6, word: needle }] });
+ expect((await importFromContent(engine, slugOf(id), content, { noEmbed: true, sourceId: id })).status).toBe('imported');
+ const [row] = await engine.executeRaw<{ id: number; body_storage: string }>('SELECT id, body_storage FROM pages WHERE slug = $1 AND source_id = $2', [slugOf(id), id]);
+ expect(row!.body_storage).toBe('segmented');
+ pageIds[id] = row!.id;
+ // A trusted read caches the page's read-view line count in page_view_digests.
+ const ctx = { engine, config: {} as GBrainConfig, logger: { info() {}, warn() {}, error() {} }, dryRun: false, remote: false, sourceId: id } as unknown as OperationContext;
+ await operations.find(o => o.name === 'get_page')!.handler(ctx, { slug: slugOf(id), source_id: id, body: 'none' });
+ }
+ expect(Number((await engine.executeRaw<{ n: number }>('SELECT count(DISTINCT page_id)::int AS n FROM page_view_digests'))[0]!.n)).toBe(2);
+ for (const role of [OPEN, READER, LEGACY]) {
+ await engine.executeRaw(`CREATE ROLE ${role} NOLOGIN NOSUPERUSER NOBYPASSRLS`);
+ await engine.executeRaw(`GRANT USAGE ON SCHEMA public TO ${role}`);
+ }
+ }, 300_000);
+
+ afterAll(async () => {
+ if (engine) {
+ for (const p of policies) await engine.executeRaw(`DROP POLICY IF EXISTS ${p.name} ON ${p.table}`);
+ for (const t of forced) await engine.executeRaw(`ALTER TABLE ${t} NO FORCE ROW LEVEL SECURITY`);
+ for (const role of [OPEN, READER, LEGACY]) {
+ await engine.executeRaw(`DROP OWNED BY ${role}`).catch(() => undefined);
+ await engine.executeRaw(`DROP ROLE IF EXISTS ${role}`);
+ }
+ await engine.initSchema();
+ }
+ await teardownDB();
+ });
+
+ test('B1: every schema replay re-enables RLS on the segment tables, so a role with SELECT and no policy reads no segment row, as it reads no page', async () => {
+ for (const t of PAGE_BODY_RLS_TABLES) await engine.executeRaw(`ALTER TABLE ${t} DISABLE ROW LEVEL SECURITY`);
+ await engine.initSchema();
+ const state = await engine.executeRaw<{ relname: string; relrowsecurity: boolean }>(
+ 'SELECT relname, relrowsecurity FROM pg_class WHERE relname = ANY($1::text[]) AND relkind = \'r\' ORDER BY relname', [['pages', ...PAGE_BODY_RLS_TABLES]]);
+ expect(state).toEqual(['pages', ...PAGE_BODY_RLS_TABLES].sort().map(relname => ({ relname, relrowsecurity: true })));
+
+ await engine.executeRaw(`GRANT SELECT ON ALL TABLES IN SCHEMA public TO ${OPEN}`);
+ const counts = await asRole(engine, OPEN, async tx => {
+ const out: Record<string, number> = {};
+ for (const t of ['pages', ...PAGE_BODY_RLS_TABLES]) out[t] = Number((await tx.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM ${t}`))[0]!.n);
+ return out;
+ });
+ expect(counts).toEqual(Object.fromEntries(['pages', ...PAGE_BODY_RLS_TABLES].map(t => [t, 0])));
+ expect(Number((await engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM page_segment_texts'))[0]!.n)).toBeGreaterThan(0);
+ }, 120_000);
+
+ describe('the docs/ENGINES.md recipe', () => {
+ beforeAll(async () => {
+ await engine.executeRaw(`CREATE POLICY ${READER}_pages ON pages
+ USING (current_setting('app.scopes', true) = '*' OR source_id = ANY(string_to_array(current_setting('app.scopes', true), ',')))`);
+ policies.push({ name: `${READER}_pages`, table: 'pages' });
+ const recipe = docsRecipe(READER);
+ for (const m of recipe.matchAll(/CREATE POLICY (\w+) ON (\w+)/g)) policies.push({ name: m[1]!, table: m[2]! });
+ forced = [...recipe.matchAll(/ALTER TABLE (\w+) FORCE ROW LEVEL SECURITY/g)].map(m => m[1]!);
+ expect(policies.map(p => p.table)).toEqual(expect.arrayContaining([...PAGE_BODY_RLS_TABLES, 'content_chunks', 'sources']));
+ await engine.executeRaw(recipe);
+ // The recipe grants the page tables; the other tables a search reads open to the reader, so the recipe is the only
+ // thing that filters page text.
+ await engine.executeRaw(`GRANT SELECT ON ${SEARCH_SIDE_TABLES.join(', ')} TO ${READER}`);
+ const covered = new Set(policies.map(p => p.table));
+ for (const t of SEARCH_SIDE_TABLES.filter(t => !covered.has(t))) {
+ await engine.executeRaw(`CREATE POLICY ${READER}_open ON ${t} FOR SELECT TO ${READER} USING (true)`);
+ policies.push({ name: `${READER}_open`, table: t });
+ }
+ }, 120_000);
+
+ test('B2: a role scoped to src-a searches and reads its segmented page and never sees src-b segment text', async () => {
+ await withEnv({ GBRAIN_RLS_SCOPE_BINDING: undefined }, async () => {
+ const seen = await asRole(engine, READER, async tx => ({
+ alpha: sourcesOf(await tx.searchKeyword(SOURCES['src-a'])),
+ bravo: sourcesOf(await tx.searchKeyword(SOURCES['src-b'])),
+ alphaChunks: sourcesOf(await tx.searchKeywordChunks(SOURCES['src-a'])),
+ bravoChunks: sourcesOf(await tx.searchKeywordChunks(SOURCES['src-b'])),
+ titles: sourcesOf(await tx.searchTitles('ledger')),
+ windows: (await tx.getChunkWindows(Object.values(pageIds).map(id => ({ page_id: id, from_index: 0, to_index: 3, priority: 0 })),
+ { chunkSources: ['compiled_truth', 'timeline'], maxRows: 20 })).map(w => w.source_id).sort(),
+ body: (await materializeSegmentedBody(tx, pageIds['src-a']!, 'src-a')).compiled_truth.includes(SOURCES['src-a']),
+ rows: await tx.executeRaw<{ t: string; source_id: string }>(
+ `SELECT 'texts' AS t, source_id FROM page_segment_texts UNION SELECT 'manifest', source_id FROM page_body_manifest
+ UNION SELECT 'chunks', p.source_id FROM content_chunks c JOIN pages p ON p.id = c.page_id ORDER BY 1, 2`),
+ bravoText: Number((await tx.executeRaw<{ n: number }>(
+ `SELECT count(*)::int AS n FROM page_segment_texts WHERE position($1::bytea IN body) > 0`, [Buffer.from(SOURCES['src-b'])]))[0]!.n),
+ bravoManifest: Number((await tx.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM page_body_manifest WHERE page_id = $1', [pageIds['src-b']]))[0]!.n),
+ bravoChunkText: Number((await tx.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM content_chunks WHERE position($1 IN chunk_text) > 0', [SOURCES['src-b']]))[0]!.n),
+ digests: (await tx.executeRaw<{ page_id: number }>('SELECT DISTINCT page_id FROM page_view_digests')).map(r => Number(r.page_id)),
+ }), 'src-a');
+ expect(seen).toEqual({ alpha: ['src-a'], bravo: [], alphaChunks: ['src-a'], bravoChunks: [], titles: ['src-a'], windows: ['src-a'], body: true,
+ rows: [{ t: 'chunks', source_id: 'src-a' }, { t: 'manifest', source_id: 'src-a' }, { t: 'texts', source_id: 'src-a' }], bravoText: 0, bravoManifest: 0, bravoChunkText: 0, digests: [pageIds['src-a']] });
+ const owner = Number((await engine.executeRaw<{ n: number }>(
+ `SELECT count(*)::int AS n FROM page_segment_texts WHERE position($1::bytea IN body) > 0`, [Buffer.from(SOURCES['src-b'])]))[0]!.n);
+ expect(owner).toBeGreaterThan(0);
+ });
+ }, 120_000);
+
+ test('B2: with the per-read binding, each request sees only the source it names', async () => {
+ await withEnv({ GBRAIN_RLS_SCOPE_BINDING: '1' }, async () => {
+ const seen = await asRole(engine, READER, async tx => ({
+ alphaAsA: sourcesOf(await tx.searchKeyword(SOURCES['src-a'], { sourceId: 'src-a' })),
+ bravoAsA: sourcesOf(await tx.searchKeyword(SOURCES['src-b'], { sourceId: 'src-a' })),
+ bravoAsB: sourcesOf(await tx.searchKeyword(SOURCES['src-b'], { sourceId: 'src-b' })),
+ titlesAsB: sourcesOf(await tx.searchTitles('ledger', { sourceId: 'src-b' })),
+ }), '');
+ expect(seen).toEqual({ alphaAsA: ['src-a'], bravoAsA: [], bravoAsB: ['src-b'], titlesAsB: ['src-b'] });
+ });
+ }, 120_000);
+
+ test('B2: a role holding the pre-Wave-B grant set (no page_body_manifest) fails title search with permission_denied', async () => {
+ await engine.executeRaw(`GRANT SELECT ON pages, content_chunks, sources, timeline_entries, config TO ${LEGACY}`);
+ for (const t of ['pages', 'content_chunks', 'sources', 'timeline_entries', 'config']) {
+ await engine.executeRaw(`CREATE POLICY ${LEGACY}_open ON ${t} FOR SELECT TO ${LEGACY} USING (true)`);
+ policies.push({ name: `${LEGACY}_open`, table: t });
+ }
+ const failure = await asRole(engine, LEGACY, tx => tx.searchTitles('ledger', { sourceId: 'src-a' })).then(() => null, (e: { code?: string }) => e.code);
+ expect(failure).toBe('42501');
+ expect(sourcesOf(await asRole(engine, LEGACY, tx => tx.searchKeyword(SOURCES['src-a'], { sourceId: 'src-a' })))).toEqual(['src-a']);
+ }, 120_000);
+ });
+});
diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-default.json b/test/fixtures/goldens/catalog/pglite-engine-init-default.json
index 7bb7c75abe..3ac8871d92 100644
--- a/test/fixtures/goldens/catalog/pglite-engine-init-default.json
+++ b/test/fixtures/goldens/catalog/pglite-engine-init-default.json
@@ -1145,6 +1145,7 @@
"idx_timeline_page": "CREATE INDEX idx_timeline_page ON public.timeline_entries USING btree (page_id)",
"idx_versions_page": "CREATE INDEX idx_versions_page ON public.page_versions USING btree (page_id)",
"ingest_log_pkey": "CREATE UNIQUE INDEX ingest_log_pkey ON public.ingest_log USING btree (id)",
+ "ingest_log_unmarked_idx": "CREATE INDEX ingest_log_unmarked_idx ON public.ingest_log USING btree (created_at) WHERE (writer_segment_reader IS NOT TRUE)",
"link_edge_proposals_from_page_id_a_to_page_id_b_to_page_id__key": "CREATE UNIQUE INDEX link_edge_proposals_from_page_id_a_to_page_id_b_to_page_id__key ON public.link_edge_proposals USING btree (from_page_id, a_to_page_id, b_to_page_id, link_type, evidence_hash)",
"link_edge_proposals_pkey": "CREATE UNIQUE INDEX link_edge_proposals_pkey ON public.link_edge_proposals USING btree (id)",
"link_edge_proposals_status_idx": "CREATE INDEX link_edge_proposals_status_idx ON public.link_edge_proposals USING btree (source_id, status, created_at)",
@@ -2159,7 +2160,10 @@
"4 source_ref text/text NOT NULL",
"5 pages_updated jsonb/jsonb NOT NULL DEFAULT '[]'::jsonb",
"6 summary text/text NOT NULL DEFAULT ''::text",
- "7 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"
+ "7 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",
+ "8 writer_version text/text NULL",
+ "9 writer_host_id uuid/uuid NULL",
+ "10 writer_segment_reader boolean/bool NULL"
],
"flags": "relkind=r rls=false force_rls=false"
},
@@ -2911,7 +2915,8 @@
"14 minted_under jsonb/jsonb NULL",
"15 version text/text NOT NULL",
"16 boot_id text/text NULL",
- "17 process_start text/text NULL"
+ "17 process_start text/text NULL",
+ "18 segment_reader boolean/bool NULL"
],
"flags": "relkind=r rls=false force_rls=false"
},
@@ -3034,7 +3039,9 @@
"39 error_detail jsonb/jsonb NULL",
"40 claim_phase jsonb/jsonb NULL",
"41 preparation_attempts integer/int4 NOT NULL DEFAULT 0",
- "42 client_request_id text/text NULL"
+ "42 client_request_id text/text NULL",
+ "43 admitter_segment_reader boolean/bool NULL",
+ "44 consumer_segment_reader boolean/bool NULL"
],
"flags": "relkind=r rls=false force_rls=false"
},
diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json b/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json
index b1ca140212..2e991d3c73 100644
--- a/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json
+++ b/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json
@@ -1145,6 +1145,7 @@
"idx_timeline_page": "CREATE INDEX idx_timeline_page ON public.timeline_entries USING btree (page_id)",
"idx_versions_page": "CREATE INDEX idx_versions_page ON public.page_versions USING btree (page_id)",
"ingest_log_pkey": "CREATE UNIQUE INDEX ingest_log_pkey ON public.ingest_log USING btree (id)",
+ "ingest_log_unmarked_idx": "CREATE INDEX ingest_log_unmarked_idx ON public.ingest_log USING btree (created_at) WHERE (writer_segment_reader IS NOT TRUE)",
"link_edge_proposals_from_page_id_a_to_page_id_b_to_page_id__key": "CREATE UNIQUE INDEX link_edge_proposals_from_page_id_a_to_page_id_b_to_page_id__key ON public.link_edge_proposals USING btree (from_page_id, a_to_page_id, b_to_page_id, link_type, evidence_hash)",
"link_edge_proposals_pkey": "CREATE UNIQUE INDEX link_edge_proposals_pkey ON public.link_edge_proposals USING btree (id)",
"link_edge_proposals_status_idx": "CREATE INDEX link_edge_proposals_status_idx ON public.link_edge_proposals USING btree (source_id, status, created_at)",
@@ -2159,7 +2160,10 @@
"4 source_ref text/text NOT NULL",
"5 pages_updated jsonb/jsonb NOT NULL DEFAULT '[]'::jsonb",
"6 summary text/text NOT NULL DEFAULT ''::text",
- "7 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"
+ "7 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",
+ "8 writer_version text/text NULL",
+ "9 writer_host_id uuid/uuid NULL",
+ "10 writer_segment_reader boolean/bool NULL"
],
"flags": "relkind=r rls=false force_rls=false"
},
@@ -2911,7 +2915,8 @@
"14 minted_under jsonb/jsonb NULL",
"15 version text/text NOT NULL",
"16 boot_id text/text NULL",
- "17 process_start text/text NULL"
+ "17 process_start text/text NULL",
+ "18 segment_reader boolean/bool NULL"
],
"flags": "relkind=r rls=false force_rls=false"
},
@@ -3034,7 +3039,9 @@
"39 error_detail jsonb/jsonb NULL",
"40 claim_phase jsonb/jsonb NULL",
"41 preparation_attempts integer/int4 NOT NULL DEFAULT 0",
- "42 client_request_id text/text NULL"
+ "42 client_request_id text/text NULL",
+ "43 admitter_segment_reader boolean/bool NULL",
+ "44 consumer_segment_reader boolean/bool NULL"
],
"flags": "relkind=r rls=false force_rls=false"
},
diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json b/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json
index 67a76a3a88..4956bcd3c3 100644
--- a/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json
+++ b/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json
@@ -1141,6 +1141,7 @@
"idx_timeline_page": "CREATE INDEX idx_timeline_page ON public.timeline_entries USING btree (page_id)",
"idx_versions_page": "CREATE INDEX idx_versions_page ON public.page_versions USING btree (page_id)",
"ingest_log_pkey": "CREATE UNIQUE INDEX ingest_log_pkey ON public.ingest_log USING btree (id)",
+ "ingest_log_unmarked_idx": "CREATE INDEX ingest_log_unmarked_idx ON public.ingest_log USING btree (created_at) WHERE (writer_segment_reader IS NOT TRUE)",
"link_edge_proposals_from_page_id_a_to_page_id_b_to_page_id__key": "CREATE UNIQUE INDEX link_edge_proposals_from_page_id_a_to_page_id_b_to_page_id__key ON public.link_edge_proposals USING btree (from_page_id, a_to_page_id, b_to_page_id, link_type, evidence_hash)",
"link_edge_proposals_pkey": "CREATE UNIQUE INDEX link_edge_proposals_pkey ON public.link_edge_proposals USING btree (id)",
"link_edge_proposals_status_idx": "CREATE INDEX link_edge_proposals_status_idx ON public.link_edge_proposals USING btree (source_id, status, created_at)",
@@ -2155,7 +2156,10 @@
"4 source_ref text/text NOT NULL",
"5 pages_updated jsonb/jsonb NOT NULL DEFAULT '[]'::jsonb",
"6 summary text/text NOT NULL DEFAULT ''::text",
- "7 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"
+ "7 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",
+ "8 writer_version text/text NULL",
+ "9 writer_host_id uuid/uuid NULL",
+ "10 writer_segment_reader boolean/bool NULL"
],
"flags": "relkind=r rls=false force_rls=false"
},
@@ -2907,7 +2911,8 @@
"14 minted_under jsonb/jsonb NULL",
"15 version text/text NOT NULL",
"16 boot_id text/text NULL",
- "17 process_start text/text NULL"
+ "17 process_start text/text NULL",
+ "18 segment_reader boolean/bool NULL"
],
"flags": "relkind=r rls=false force_rls=false"
},
@@ -3030,7 +3035,9 @@
"39 error_detail jsonb/jsonb NULL",
"40 claim_phase jsonb/jsonb NULL",
"41 preparation_attempts integer/int4 NOT NULL DEFAULT 0",
- "42 client_request_id text/text NULL"
+ "42 client_request_id text/text NULL",
+ "43 admitter_segment_reader boolean/bool NULL",
+ "44 consumer_segment_reader boolean/bool NULL"
],
"flags": "relkind=r rls=false force_rls=false"
},
diff --git a/test/fixtures/goldens/catalog/pglite-schema-blob-default.json b/test/fixtures/goldens/catalog/pglite-schema-blob-default.json
index 83401c7a12..d3b4a182fc 100644
--- a/test/fixtures/goldens/catalog/pglite-schema-blob-default.json
+++ b/test/fixtures/goldens/catalog/pglite-schema-blob-default.json
@@ -1575,7 +1575,10 @@
"4 source_ref text/text NOT NULL",
"5 pages_updated jsonb/jsonb NOT NULL DEFAULT '[]'::jsonb",
"6 summary text/text NOT NULL DEFAULT ''::text",
- "7 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"
+ "7 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",
+ "8 writer_version text/text NULL",
+ "9 writer_host_id uuid/uuid NULL",
+ "10 writer_segment_reader boolean/bool NULL"
],
"flags": "relkind=r rls=false force_rls=false"
},
@@ -2152,7 +2155,8 @@
"14 minted_under jsonb/jsonb NULL",
"15 version text/text NOT NULL",
"16 boot_id text/text NULL",
- "17 process_start text/text NULL"
+ "17 process_start text/text NULL",
+ "18 segment_reader boolean/bool NULL"
],
"flags": "relkind=r rls=false force_rls=false"
},
diff --git a/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.json b/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.json
index bcf77c9d5f..7351b7260c 100644
--- a/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.json
+++ b/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.json
@@ -1575,7 +1575,10 @@
"4 source_ref text/text NOT NULL",
"5 pages_updated jsonb/jsonb NOT NULL DEFAULT '[]'::jsonb",
"6 summary text/text NOT NULL DEFAULT ''::text",
- "7 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"
+ "7 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",
+ "8 writer_version text/text NULL",
+ "9 writer_host_id uuid/uuid NULL",
+ "10 writer_segment_reader boolean/bool NULL"
],
"flags": "relkind=r rls=false force_rls=false"
},
@@ -2152,7 +2155,8 @@
"14 minted_under jsonb/jsonb NULL",
"15 version text/text NOT NULL",
"16 boot_id text/text NULL",
- "17 process_start text/text NULL"
+ "17 process_start text/text NULL",
+ "18 segment_reader boolean/bool NULL"
],
"flags": "relkind=r rls=false force_rls=false"
},
diff --git a/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.json b/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.json
index 29e0418b17..44e5b60e40 100644
--- a/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.json
+++ b/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.json
@@ -1574,7 +1574,10 @@
"4 source_ref text/text NOT NULL",
"5 pages_updated jsonb/jsonb NOT NULL DEFAULT '[]'::jsonb",
"6 summary text/text NOT NULL DEFAULT ''::text",
- "7 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"
+ "7 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",
+ "8 writer_version text/text NULL",
+ "9 writer_host_id uuid/uuid NULL",
+ "10 writer_segment_reader boolean/bool NULL"
],
"flags": "relkind=r rls=false force_rls=false"
},
@@ -2151,7 +2154,8 @@
"14 minted_under jsonb/jsonb NULL",
"15 version text/text NOT NULL",
"16 boot_id text/text NULL",
- "17 process_start text/text NULL"
+ "17 process_start text/text NULL",
+ "18 segment_reader boolean/bool NULL"
],
"flags": "relkind=r rls=false force_rls=false"
},
diff --git a/test/fixtures/goldens/catalog/postgres-db-initschema.json b/test/fixtures/goldens/catalog/postgres-db-initschema.json
index 53dfba0d3c..b292ecc228 100644
--- a/test/fixtures/goldens/catalog/postgres-db-initschema.json
+++ b/test/fixtures/goldens/catalog/postgres-db-initschema.json
@@ -1654,7 +1654,10 @@
"4 source_ref text/text NOT NULL",
"5 pages_updated jsonb/jsonb NOT NULL DEFAULT '[]'::jsonb",
"6 summary text/text NOT NULL DEFAULT ''::text",
- "7 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"
+ "7 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",
+ "8 writer_version text/text NULL",
+ "9 writer_host_id uuid/uuid NULL",
+ "10 writer_segment_reader boolean/bool NULL"
],
"flags": "relkind=r rls=true force_rls=false"
},
@@ -2010,7 +2013,7 @@
"23 staging_id uuid/uuid NULL",
"24 staging_key uuid/uuid NOT NULL"
],
- "flags": "relkind=r rls=false force_rls=false"
+ "flags": "relkind=r rls=true force_rls=false"
},
"page_body_staging_parts": {
"columns": [
@@ -2021,7 +2024,7 @@
"5 sha256 bytea/bytea NOT NULL",
"6 body bytea/bytea NOT NULL"
],
- "flags": "relkind=r rls=false force_rls=false"
+ "flags": "relkind=r rls=true force_rls=false"
},
"page_body_stagings": {
"columns": [
@@ -2049,7 +2052,7 @@
"22 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",
"23 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"
],
- "flags": "relkind=r rls=false force_rls=false"
+ "flags": "relkind=r rls=true force_rls=false"
},
"page_embedding_budget": {
"columns": [
@@ -2121,7 +2124,7 @@
"5 body bytea/bytea NOT NULL",
"6 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"
],
- "flags": "relkind=r rls=false force_rls=false"
+ "flags": "relkind=r rls=true force_rls=false"
},
"page_versions": {
"columns": [
@@ -2151,7 +2154,7 @@
"7 sha256 text/text NULL",
"8 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"
],
- "flags": "relkind=r rls=false force_rls=false"
+ "flags": "relkind=r rls=true force_rls=false"
},
"page_write_guards": {
"columns": [
@@ -2221,7 +2224,8 @@
"14 minted_under jsonb/jsonb NULL",
"15 version text/text NOT NULL",
"16 boot_id text/text NULL",
- "17 process_start text/text NULL"
+ "17 process_start text/text NULL",
+ "18 segment_reader boolean/bool NULL"
],
"flags": "relkind=r rls=false force_rls=false"
},
diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-default.json b/test/fixtures/goldens/catalog/postgres-engine-init-default.json
index 73c9dc4f02..caa8e44dc0 100644
--- a/test/fixtures/goldens/catalog/postgres-engine-init-default.json
+++ b/test/fixtures/goldens/catalog/postgres-engine-init-default.json
@@ -1148,6 +1148,7 @@
"idx_timeline_page": "CREATE INDEX idx_timeline_page ON public.timeline_entries USING btree (page_id)",
"idx_versions_page": "CREATE INDEX idx_versions_page ON public.page_versions USING btree (page_id)",
"ingest_log_pkey": "CREATE UNIQUE INDEX ingest_log_pkey ON public.ingest_log USING btree (id)",
+ "ingest_log_unmarked_idx": "CREATE INDEX ingest_log_unmarked_idx ON public.ingest_log USING btree (created_at) WHERE (writer_segment_reader IS NOT TRUE)",
"link_edge_proposals_from_page_id_a_to_page_id_b_to_page_id__key": "CREATE UNIQUE INDEX link_edge_proposals_from_page_id_a_to_page_id_b_to_page_id__key ON public.link_edge_proposals USING btree (from_page_id, a_to_page_id, b_to_page_id, link_type, evidence_hash)",
"link_edge_proposals_pkey": "CREATE UNIQUE INDEX link_edge_proposals_pkey ON public.link_edge_proposals USING btree (id)",
"link_edge_proposals_status_idx": "CREATE INDEX link_edge_proposals_status_idx ON public.link_edge_proposals USING btree (source_id, status, created_at)",
@@ -2171,7 +2172,10 @@
"4 source_ref text/text NOT NULL",
"5 pages_updated jsonb/jsonb NOT NULL DEFAULT '[]'::jsonb",
"6 summary text/text NOT NULL DEFAULT ''::text",
- "7 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"
+ "7 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",
+ "8 writer_version text/text NULL",
+ "9 writer_host_id uuid/uuid NULL",
+ "10 writer_segment_reader boolean/bool NULL"
],
"flags": "relkind=r rls=true force_rls=false"
},
@@ -2923,7 +2927,8 @@
"14 minted_under jsonb/jsonb NULL",
"15 version text/text NOT NULL",
"16 boot_id text/text NULL",
- "17 process_start text/text NULL"
+ "17 process_start text/text NULL",
+ "18 segment_reader boolean/bool NULL"
],
"flags": "relkind=r rls=true force_rls=false"
},
@@ -3046,7 +3051,9 @@
"39 error_detail jsonb/jsonb NULL",
"40 claim_phase jsonb/jsonb NULL",
"41 preparation_attempts integer/int4 NOT NULL DEFAULT 0",
- "42 client_request_id text/text NULL"
+ "42 client_request_id text/text NULL",
+ "43 admitter_segment_reader boolean/bool NULL",
+ "44 consumer_segment_reader boolean/bool NULL"
],
"flags": "relkind=r rls=true force_rls=false"
},
diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json b/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json
index 84ae9371dd..620437f53f 100644
--- a/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json
+++ b/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json
@@ -1148,6 +1148,7 @@
"idx_timeline_page": "CREATE INDEX idx_timeline_page ON public.timeline_entries USING btree (page_id)",
"idx_versions_page": "CREATE INDEX idx_versions_page ON public.page_versions USING btree (page_id)",
"ingest_log_pkey": "CREATE UNIQUE INDEX ingest_log_pkey ON public.ingest_log USING btree (id)",
+ "ingest_log_unmarked_idx": "CREATE INDEX ingest_log_unmarked_idx ON public.ingest_log USING btree (created_at) WHERE (writer_segment_reader IS NOT TRUE)",
"link_edge_proposals_from_page_id_a_to_page_id_b_to_page_id__key": "CREATE UNIQUE INDEX link_edge_proposals_from_page_id_a_to_page_id_b_to_page_id__key ON public.link_edge_proposals USING btree (from_page_id, a_to_page_id, b_to_page_id, link_type, evidence_hash)",
"link_edge_proposals_pkey": "CREATE UNIQUE INDEX link_edge_proposals_pkey ON public.link_edge_proposals USING btree (id)",
"link_edge_proposals_status_idx": "CREATE INDEX link_edge_proposals_status_idx ON public.link_edge_proposals USING btree (source_id, status, created_at)",
@@ -2171,7 +2172,10 @@
"4 source_ref text/text NOT NULL",
"5 pages_updated jsonb/jsonb NOT NULL DEFAULT '[]'::jsonb",
"6 summary text/text NOT NULL DEFAULT ''::text",
- "7 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"
+ "7 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",
+ "8 writer_version text/text NULL",
+ "9 writer_host_id uuid/uuid NULL",
+ "10 writer_segment_reader boolean/bool NULL"
],
"flags": "relkind=r rls=true force_rls=false"
},
@@ -2923,7 +2927,8 @@
"14 minted_under jsonb/jsonb NULL",
"15 version text/text NOT NULL",
"16 boot_id text/text NULL",
- "17 process_start text/text NULL"
+ "17 process_start text/text NULL",
+ "18 segment_reader boolean/bool NULL"
],
"flags": "relkind=r rls=true force_rls=false"
},
@@ -3046,7 +3051,9 @@
"39 error_detail jsonb/jsonb NULL",
"40 claim_phase jsonb/jsonb NULL",
"41 preparation_attempts integer/int4 NOT NULL DEFAULT 0",
- "42 client_request_id text/text NULL"
+ "42 client_request_id text/text NULL",
+ "43 admitter_segment_reader boolean/bool NULL",
+ "44 consumer_segment_reader boolean/bool NULL"
],
"flags": "relkind=r rls=true force_rls=false"
},
diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json b/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json
index d0cebea7f3..bfc889d464 100644
--- a/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json
+++ b/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json
@@ -1144,6 +1144,7 @@
"idx_timeline_page": "CREATE INDEX idx_timeline_page ON public.timeline_entries USING btree (page_id)",
"idx_versions_page": "CREATE INDEX idx_versions_page ON public.page_versions USING btree (page_id)",
"ingest_log_pkey": "CREATE UNIQUE INDEX ingest_log_pkey ON public.ingest_log USING btree (id)",
+ "ingest_log_unmarked_idx": "CREATE INDEX ingest_log_unmarked_idx ON public.ingest_log USING btree (created_at) WHERE (writer_segment_reader IS NOT TRUE)",
"link_edge_proposals_from_page_id_a_to_page_id_b_to_page_id__key": "CREATE UNIQUE INDEX link_edge_proposals_from_page_id_a_to_page_id_b_to_page_id__key ON public.link_edge_proposals USING btree (from_page_id, a_to_page_id, b_to_page_id, link_type, evidence_hash)",
"link_edge_proposals_pkey": "CREATE UNIQUE INDEX link_edge_proposals_pkey ON public.link_edge_proposals USING btree (id)",
"link_edge_proposals_status_idx": "CREATE INDEX link_edge_proposals_status_idx ON public.link_edge_proposals USING btree (source_id, status, created_at)",
@@ -2167,7 +2168,10 @@
"4 source_ref text/text NOT NULL",
"5 pages_updated jsonb/jsonb NOT NULL DEFAULT '[]'::jsonb",
"6 summary text/text NOT NULL DEFAULT ''::text",
- "7 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"
+ "7 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",
+ "8 writer_version text/text NULL",
+ "9 writer_host_id uuid/uuid NULL",
+ "10 writer_segment_reader boolean/bool NULL"
],
"flags": "relkind=r rls=true force_rls=false"
},
@@ -2919,7 +2923,8 @@
"14 minted_under jsonb/jsonb NULL",
"15 version text/text NOT NULL",
"16 boot_id text/text NULL",
- "17 process_start text/text NULL"
+ "17 process_start text/text NULL",
+ "18 segment_reader boolean/bool NULL"
],
"flags": "relkind=r rls=true force_rls=false"
},
@@ -3042,7 +3047,9 @@
"39 error_detail jsonb/jsonb NULL",
"40 claim_phase jsonb/jsonb NULL",
"41 preparation_attempts integer/int4 NOT NULL DEFAULT 0",
- "42 client_request_id text/text NULL"
+ "42 client_request_id text/text NULL",
+ "43 admitter_segment_reader boolean/bool NULL",
+ "44 consumer_segment_reader boolean/bool NULL"
],
"flags": "relkind=r rls=true force_rls=false"
},
diff --git a/test/fixtures/goldens/doctor/json-postgres-fresh.json b/test/fixtures/goldens/doctor/json-postgres-fresh.json
index 12a7ed644c..4e637731d1 100644
--- a/test/fixtures/goldens/doctor/json-postgres-fresh.json
+++ b/test/fixtures/goldens/doctor/json-postgres-fresh.json
@@ -881,7 +881,7 @@
{
"category": "meta",
"elapsed_ms": "<volatile>",
- "message": "1205 column(s) verified against live schema",
+ "message": "1209 column(s) verified against live schema",
"name": "schema_columns",
"status": "ok"
},
diff --git a/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json b/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json
index 46634a10c7..cbe6a6ec0f 100644
--- a/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json
+++ b/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json
@@ -1145,6 +1145,7 @@
"idx_timeline_page": "CREATE INDEX idx_timeline_page ON public.timeline_entries USING btree (page_id)",
"idx_versions_page": "CREATE INDEX idx_versions_page ON public.page_versions USING btree (page_id)",
"ingest_log_pkey": "CREATE UNIQUE INDEX ingest_log_pkey ON public.ingest_log USING btree (id)",
+ "ingest_log_unmarked_idx": "CREATE INDEX ingest_log_unmarked_idx ON public.ingest_log USING btree (created_at) WHERE (writer_segment_reader IS NOT TRUE)",
"link_edge_proposals_from_page_id_a_to_page_id_b_to_page_id__key": "CREATE UNIQUE INDEX link_edge_proposals_from_page_id_a_to_page_id_b_to_page_id__key ON public.link_edge_proposals USING btree (from_page_id, a_to_page_id, b_to_page_id, link_type, evidence_hash)",
"link_edge_proposals_pkey": "CREATE UNIQUE INDEX link_edge_proposals_pkey ON public.link_edge_proposals USING btree (id)",
"link_edge_proposals_status_idx": "CREATE INDEX link_edge_proposals_status_idx ON public.link_edge_proposals USING btree (source_id, status, created_at)",
@@ -2159,7 +2160,10 @@
"4 source_ref text/text NOT NULL",
"5 pages_updated jsonb/jsonb NOT NULL DEFAULT '[]'::jsonb",
"6 summary text/text NOT NULL DEFAULT ''::text",
- "7 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"
+ "7 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",
+ "8 writer_version text/text NULL",
+ "9 writer_host_id uuid/uuid NULL",
+ "10 writer_segment_reader boolean/bool NULL"
],
"flags": "relkind=r rls=false force_rls=false"
},
@@ -2911,7 +2915,8 @@
"14 minted_under jsonb/jsonb NULL",
"15 version text/text NOT NULL",
"16 boot_id text/text NULL",
- "17 process_start text/text NULL"
+ "17 process_start text/text NULL",
+ "18 segment_reader boolean/bool NULL"
],
"flags": "relkind=r rls=false force_rls=false"
},
@@ -3034,7 +3039,9 @@
"39 error_detail jsonb/jsonb NULL",
"40 claim_phase jsonb/jsonb NULL",
"41 preparation_attempts integer/int4 NOT NULL DEFAULT 0",
- "42 client_request_id text/text NULL"
+ "42 client_request_id text/text NULL",
+ "43 admitter_segment_reader boolean/bool NULL",
+ "44 consumer_segment_reader boolean/bool NULL"
],
"flags": "relkind=r rls=false force_rls=false"
},
diff --git a/test/large-pages/remote-get-page-privacy.test.ts b/test/large-pages/remote-get-page-privacy.test.ts
index fb2c3525ce..907873180d 100644
--- a/test/large-pages/remote-get-page-privacy.test.ts
+++ b/test/large-pages/remote-get-page-privacy.test.ts
@@ -8,10 +8,12 @@
* facts rows, private keys, ledger rows and a takes block left open to EOF.
* The paged markdown view must hash to the advertised size.sha256, and the
* remote tail digest is withheld when the tail rows hold a protected region.
+ * A remote caller's sizes (body none, the full-read refusal) are projected
+ * totals; only a trusted read reports the stored body_bytes.
* 2. Fails when: a segmented window, outline or markdown page is cut from the
* stored body instead of the read projection, the markdown digest hashes
- * trusted text, or tail_sha256 hashes hidden text. PUBLIC tokens must still
- * appear.
+ * trusted text, tail_sha256 hashes hidden text, or a remote response
+ * carries the stored body size. PUBLIC tokens must still appear.
*/
import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
import { createHash } from 'node:crypto';
@@ -95,7 +97,20 @@ for (const kind of testBackends()) {
const slug = 'notes/get-windows';
await importSegmented(engine, slug, pageContent(privacyText(r, 1_600_000) + crossingFacts(), privacyText(r, 300_000)));
const none = await expectNoLeak(slug);
- expect(none.size.body_bytes).toBeGreaterThan(1_900_000);
+ // A remote caller sees projected totals only, as for an inline page: the stored size would say how much the
+ // projection hides. The trusted read keeps it.
+ expect(none.size.body_bytes).toBeUndefined();
+ expect(none.size.body_lines).toBeUndefined();
+ const local = await get({ slug, body: 'none' }, false);
+ expect(local.size.body_bytes).toBeGreaterThan(1_900_000);
+ expect(none.size.total_bytes).toBeLessThan(local.size.body_bytes);
+ const refusal = await get({ slug, body: 'full' }).then(() => null, (e: { code?: string; message: string; detail?: string }) => e);
+ expect(refusal?.code).toBe('page_body_segmented');
+ expect(JSON.parse(refusal!.detail!).total_bytes).toBe(none.size.total_bytes);
+ expect(refusal!.message).toContain(`its ${none.size.total_bytes}-byte body`);
+ expect(refusal!.message).not.toContain(String(local.size.body_bytes));
+ const localRefusal = await get({ slug, body: 'full' }, false).then(() => null, (e: { message: string }) => e);
+ expect(localRefusal!.message).toContain(`its ${local.size.body_bytes}-byte body`);
}, 300_000);
test('withdrawn, purged and held rows stay hidden once the ledger records them', async () => {
diff --git a/test/large-pages/segmented-get-page-parity.test.ts b/test/large-pages/segmented-get-page-parity.test.ts
index 495f9f16ea..1185b06fae 100644
--- a/test/large-pages/segmented-get-page-parity.test.ts
+++ b/test/large-pages/segmented-get-page-parity.test.ts
@@ -108,7 +108,9 @@ for (const kind of testBackends()) {
test(`${who}: body none, auto and every outline page agree`, async () => {
const none = await expectSame(remote, { body: 'none' });
- expect(none.segmented.size.body_bytes).toBeGreaterThan(1_900_000);
+ // The stored size is a trusted read's only: a remote caller sees projected totals, as for an inline page.
+ if (remote) expect(none.segmented.size.body_bytes).toBeUndefined();
+ else expect(none.segmented.size.body_bytes).toBeGreaterThan(1_900_000);
if (remote) await expectSame(remote, {});
let from = 0;
let pages = 0;
diff --git a/test/large-pages/segmented-switch.test.ts b/test/large-pages/segmented-switch.test.ts
index a0c2a09e27..f4404562ad 100644
--- a/test/large-pages/segmented-switch.test.ts
+++ b/test/large-pages/segmented-switch.test.ts
@@ -6,24 +6,32 @@
* off, and doctor offers the switch; a writer older than SEGMENTED_WRITER_FLOOR (or unstamped) seen in the last seven days keeps writes
* inline, even with an explicit `on`, and doctor `segmented_storage` names it with an upgrade fix; once that
* observation is gone the next write promotes; an explicit `off` keeps pages inline and reports it as a choice;
- * a stored segmented page over 32 MiB still exports while the switch is off.
+ * a stored segmented page over 32 MiB still exports while the switch is off. Every write the gate sees must carry the
+ * segment-reader mark (v251): a release at exactly the floor version without it, an older binary's import or sync
+ * run (ingest_log), its resident heartbeat and its uncommitted requests all block; this build's do not. An
+ * unreadable gate blocks, an unparsable stamp blocks, the 7-day window ends between day 6 and day 8, and the gate is
+ * read once per TTL (work counter) while doctor reads through.
* 2. Fails when: the default turns on before the release flips it, the gate ignores old or unstamped writers, an explicit `on` overrides the
- * gate, a cleared gate keeps writes inline, or export sizes stored segmented pages by the write limit.
+ * gate, a cleared gate keeps writes inline, export sizes stored segmented pages by the write limit, a writer without
+ * the mark passes on its version, a write path of this build stops marking, or the gate's error, window, parse or
+ * cache handling changes.
*/
-import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import { afterAll, beforeAll, beforeEach, describe, expect, setSystemTime, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
import { mkdtempSync, readFileSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import type { BrainEngine } from '../../src/core/engine.ts';
import { importFromContent } from '../../src/core/import-file.ts';
import { PAGE_MAX_BYTES } from '../../src/core/page-size-policy.ts';
-import { _resetSegmentedWriterGateForTests, readPageBodyPolicy, segmentedPageCeiling } from '../../src/core/page-body/limits.ts';
+import { _resetSegmentedWriterGateForTests, readPageBodyPolicy, SEGMENTED_WRITER_GATE_TTL_MS, segmentedPageCeiling, segmentedWriterGateWork } from '../../src/core/page-body/limits.ts';
import { declarePersistenceProtocol } from '../../src/core/persistence/protocol.ts';
-import { compareWriterVersions, SEGMENTED_WRITER_FLOOR } from '../../src/core/persistence/writer-versions.ts';
+import { compareWriterVersions, SEGMENTED_WRITER_FLOOR, UNSTAMPED_WRITER } from '../../src/core/persistence/writer-versions.ts';
import { BEHAVIOR_CHANGES } from '../../src/core/behavior-change-notice.ts';
import { VERSION } from '../../src/version.ts';
import { localHostId } from '../../src/core/persistence/identity.ts';
import { segmentedStorageCheck } from '../../src/commands/doctor/checks/segmented-storage.ts';
+import { startConsumerHeartbeat } from '../../src/core/persistence/consumer-heartbeat.ts';
import { runExport } from '../../src/commands/export.ts';
import { conversationPage } from '../helpers/conversation-page.ts';
import { editRequest, freshBrainFactory, requestFixture } from '../helpers/persistence-request-fixture.ts';
@@ -127,6 +135,128 @@ for (const kind of testBackends()) {
expect(readFileSync(join(out, 'notes/stored.md'), 'utf8')).toContain(content.trimEnd().slice(-120));
}, 120_000);
+ /** The gate as a write reads it, after the per-engine cache is dropped. */
+ const segmentedNow = async (e: BrainEngine = engine) => { _resetSegmentedWriterGateForTests(); return (await readPageBodyPolicy(e)).segmented; };
+ const blockersNow = async () => (await segmentedStorageCheck(engine)).details!.blockers as Array<{ role: string; principal: string; version: string; segment_reader: boolean }>;
+ /** What a binary older than v251 leaves on a request it admitted and published: its version stamp, and no segment-reader mark. */
+ const asOlderBinary = (id: string, version: string | null) =>
+ editRequest(engine, id, 'admitter_version=$2,consumer_version=$2,admitter_segment_reader=NULL,consumer_segment_reader=NULL', [version]);
+
+ test('B6: a writer at exactly the floor passes only with the segment-reader mark; the same version from a release without segment readers blocks', async () => inHome(async () => {
+ await engine.setConfig('pages.segmented_storage', 'on');
+ const requests = await requestFixture(engine);
+ const published = await requests.publish(await requests.admit('page'));
+ await editRequest(engine, published.id, 'admitter_version=$2,consumer_version=$2', [SEGMENTED_WRITER_FLOOR]);
+ expect(await segmentedNow()).toBe(true);
+ await asOlderBinary(published.id, SEGMENTED_WRITER_FLOOR);
+ expect(await segmentedNow()).toBe(false);
+ expect((await blockersNow()).map(b => [b.role, b.version, b.segment_reader]).sort())
+ .toEqual([['admitter', SEGMENTED_WRITER_FLOOR, false], ['consumer', SEGMENTED_WRITER_FLOOR, false]]);
+ expect((await importFromContent(engine, 'notes/floor', content, { noEmbed: true })).status).toBe('imported');
+ expect(await storage(engine, 'notes/floor')).toBe('inline');
+ }), 120_000);
+
+ test('B3: an import or sync run an older binary logged (an unmarked ingest_log row) blocks for 7 days; this build\'s runs do not', async () => {
+ await engine.setConfig('pages.segmented_storage', 'on');
+ await engine.logIngest({ source_type: 'import', source_ref: 'this-build', pages_updated: [], summary: 'this build' });
+ expect(await segmentedNow()).toBe(true);
+ // The statement every older binary's logIngest runs.
+ await engine.executeRaw(`INSERT INTO ingest_log (source_id, source_type, source_ref, pages_updated, summary) VALUES ('default', 'sync', 'older-binary', '[]'::jsonb, 'older binary run')`);
+ expect(await segmentedNow()).toBe(false);
+ expect(await blockersNow()).toEqual([expect.objectContaining({ role: 'importer', principal: 'ingest:sync', version: UNSTAMPED_WRITER, segment_reader: false })]);
+ expect((await importFromContent(engine, 'notes/after-old-sync', content, { noEmbed: true })).status).toBe('imported');
+ expect(await storage(engine, 'notes/after-old-sync')).toBe('inline');
+ await engine.executeRaw(`UPDATE ingest_log SET created_at = now() - interval '8 days' WHERE source_ref = 'older-binary'`);
+ expect(await segmentedNow()).toBe(true);
+ }, 120_000);
+
+ test('B3: a resident process of an older binary (an unmarked consumer heartbeat) blocks while its row is recent', async () => {
+ await engine.setConfig('pages.segmented_storage', 'on');
+ // The heartbeat an older serve writes: no segment_reader column.
+ await engine.executeRaw(`INSERT INTO persistence_consumers (host_id, pid, nonce, kind, mode, host_json_path, persistence_home, version)
+ VALUES ($1::uuid, 4242, 'older-nonce', 'serve', 'full', '/tmp/host.json', '/tmp', '0.60.262.0')`, [randomUUID()]);
+ expect(await segmentedNow()).toBe(false);
+ expect(await blockersNow()).toEqual([expect.objectContaining({ role: 'resident', principal: 'process:serve', version: '0.60.262.0', segment_reader: false })]);
+ await engine.executeRaw(`UPDATE persistence_consumers SET renewed_at = now() - interval '8 days' WHERE nonce = 'older-nonce'`);
+ expect(await segmentedNow()).toBe(true);
+ if (kind !== 'postgres') return;
+ // This build's heartbeat carries the mark (PGLite admits one process and writes no heartbeat).
+ const heartbeat = startConsumerHeartbeat(engine, randomUUID(), { kind: 'serve', mode: 'full', everyMs: 3_600_000,
+ report: () => ({ restart_required: false, root_barrier_age_ms: null }), paths: { host_json_path: '/tmp/host.json', persistence_home: '/tmp', minted_under: null } });
+ try {
+ await heartbeat.renew();
+ expect(Number((await engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM persistence_consumers WHERE segment_reader'))[0]!.n)).toBe(1);
+ expect(await segmentedNow()).toBe(true);
+ } finally { await heartbeat.stop(); }
+ }, 120_000);
+
+ test('B3: a request an older binary admitted counts in any state, not only once committed', async () => inHome(async () => {
+ await engine.setConfig('pages.segmented_storage', 'on');
+ const requests = await requestFixture(engine);
+ const queued = await requests.admit('queued-page');
+ expect(queued.state).not.toBe('committed');
+ expect(await segmentedNow()).toBe(true);
+ await editRequest(engine, queued.id, "admitter_version='0.60.262.0',admitter_segment_reader=NULL");
+ expect(await segmentedNow()).toBe(false);
+ expect(await blockersNow()).toEqual([expect.objectContaining({ role: 'admitter', version: '0.60.262.0', segment_reader: false })]);
+ }), 120_000);
+
+ test('B4: an unreadable gate keeps the switch off, and doctor reports the gate as unreadable', async () => {
+ await engine.setConfig('pages.segmented_storage', 'on');
+ const denied = Object.create(engine, { executeRaw: { value: (sql: string, ...rest: unknown[]) => /persistence_requests/.test(sql)
+ ? Promise.reject(Object.assign(new Error('permission denied for table persistence_requests'), { code: '42501' }))
+ : (engine.executeRaw as (...a: unknown[]) => Promise<unknown>)(sql, ...rest) } }) as BrainEngine;
+ expect(await readPageBodyPolicy(engine)).toMatchObject({ segmented: true });
+ expect(await segmentedNow(denied)).toBe(false);
+ expect(await readPageBodyPolicy(denied)).toMatchObject({ segmented: false, maxBytes: PAGE_MAX_BYTES });
+ expect(await segmentedStorageCheck(denied)).toMatchObject({ details: { effective: 'unknown' } });
+ }, 120_000);
+
+ test('B4: the gate is read once per TTL per engine; a blocker that appears is seen when the entry expires, and doctor reads through', async () => {
+ await engine.setConfig('pages.segmented_storage', 'on');
+ _resetSegmentedWriterGateForTests();
+ const start = Date.now();
+ try {
+ setSystemTime(new Date(start));
+ const reads = segmentedWriterGateWork.reads;
+ expect((await readPageBodyPolicy(engine)).segmented).toBe(true);
+ expect((await readPageBodyPolicy(engine)).segmented).toBe(true);
+ expect(segmentedWriterGateWork.reads - reads).toBe(1);
+ await engine.executeRaw(`INSERT INTO ingest_log (source_id, source_type, source_ref, pages_updated, summary) VALUES ('default', 'import', 'older-binary', '[]'::jsonb, 'older binary run')`);
+ setSystemTime(new Date(start + SEGMENTED_WRITER_GATE_TTL_MS - 1_000));
+ expect((await readPageBodyPolicy(engine)).segmented).toBe(true);
+ expect(segmentedWriterGateWork.reads - reads).toBe(1);
+ setSystemTime(new Date(start + SEGMENTED_WRITER_GATE_TTL_MS + 1_000));
+ expect((await readPageBodyPolicy(engine)).segmented).toBe(false);
+ expect(segmentedWriterGateWork.reads - reads).toBe(2);
+ expect((await segmentedStorageCheck(engine)).details).toMatchObject({ effective: 'off', blockers: [expect.objectContaining({ role: 'importer' })] });
+ expect(segmentedWriterGateWork.reads - reads).toBe(3);
+ } finally {
+ setSystemTime();
+ }
+ }, 120_000);
+
+ test('B4: a managed writer below the floor blocks 6 days after its last write and not 8 days after', async () => inHome(async () => {
+ await engine.setConfig('pages.segmented_storage', 'on');
+ const requests = await requestFixture(engine);
+ const published = await requests.publish(await requests.admit('page'));
+ await editRequest(engine, published.id, "admitter_version='0.60.200.0',consumer_version='0.60.200.0'");
+ for (const [days, segmented] of [[6, false], [8, true]] as const) {
+ await editRequest(engine, published.id, `created_at=now()-interval '${days} days',published_at=now()-interval '${days} days',completed_at=now()-interval '${days} days'`);
+ expect({ days, segmented: await segmentedNow() }).toEqual({ days, segmented });
+ }
+ }), 120_000);
+
+ test('B4: a stamped version the gate cannot parse blocks, even with the segment-reader mark', async () => inHome(async () => {
+ await engine.setConfig('pages.segmented_storage', 'on');
+ const requests = await requestFixture(engine);
+ const published = await requests.publish(await requests.admit('page'));
+ expect(await segmentedNow()).toBe(true);
+ await editRequest(engine, published.id, "admitter_version='nightly-build'");
+ expect(await segmentedNow()).toBe(false);
+ expect(await blockersNow()).toEqual([expect.objectContaining({ role: 'admitter', version: 'nightly-build', segment_reader: true })]);
+ }), 120_000);
+
test('explicit off keeps pages inline and doctor reports it as a choice', async () => {
await engine.setConfig('pages.segmented_storage', 'off');
expect((await importFromContent(engine, 'notes/off', content, { noEmbed: true })).status).toBe('imported');
diff --git a/test/schema-bootstrap-coverage.test.ts b/test/schema-bootstrap-coverage.test.ts
index 2ad854d444..9e109008b0 100644
--- a/test/schema-bootstrap-coverage.test.ts
+++ b/test/schema-bootstrap-coverage.test.ts
@@ -1107,6 +1107,12 @@ const COLUMN_EXEMPTIONS = new Set<string>([
// posture as v178/v198: persistence_requests is migration-created on PGLite,
// no index references the column, and every reader treats NULL as "sent a UUID or nothing".
'persistence_requests.client_request_id',
+ // Wave B fix lane B (migration v251) — segment-reader marks next to the v178
+ // stamps. Same posture as v178: persistence_requests is migration-created on
+ // PGLite, no index references the columns, and every reader treats NULL as a
+ // writer that does not read segmented pages.
+ 'persistence_requests.admitter_segment_reader',
+ 'persistence_requests.consumer_segment_reader',
// #5455 (migration v183) — managed mode epoch. persistence_brain is
// migration-created on PGLite; no index in either blob references it, and
// pre-migration readers go through to_jsonb(persistence_brain)->'mode_epoch'.