Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(large-pages): lane E — switch-off reads without the manifest grant, segmented withdrawn-fence delete, staging-texts RLS recipe

garrytan0414b1db4bcb
diff --git a/docs/ENGINES.md b/docs/ENGINES.md
index 07f53090df..2f82762ac7 100644
--- a/docs/ENGINES.md
+++ b/docs/ENGINES.md
@@ -252,13 +252,18 @@ 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
+`page_body_staging_parts` (with the segment texts each one holds in
+`page_body_staging_texts`), and view sizes in `page_view_digests`. gbrain
+enables RLS on all six 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
+reads around its hits, `get_chunks` and get_page check a chunk of a page stored
+in segments against `page_body_manifest`. A restricted read role that can see
+such a chunk (a segmented page of one of its sources) needs `SELECT` on it;
+without it those reads fail with `permission_denied` (42501). A role that sees
+no such chunk, as every role does while no page is segmented
+(`pages.segmented_storage` is off by default), reads as before without the
+grant (`test/e2e/segmented-switch-off-rls.test.ts`). 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:
@@ -274,6 +279,11 @@ CREATE POLICY page_body_manifest_scope_filter ON page_body_manifest
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), ',')));
+-- A write role records the texts each staging holds here; without a policy its
+-- segmented writes are refused.
+CREATE POLICY page_body_staging_texts_scope_filter ON page_body_staging_texts
+ 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) = '*'
@@ -301,6 +311,7 @@ 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_body_staging_texts FORCE ROW LEVEL SECURITY;
ALTER TABLE page_view_digests FORCE ROW LEVEL SECURITY;
ALTER TABLE content_chunks FORCE ROW LEVEL SECURITY;
```
@@ -310,6 +321,13 @@ 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.
+A write role that does not own the tables needs `SELECT, INSERT, UPDATE, DELETE`
+on all six, as on any table a migration adds, even while no page is segmented:
+purging soft-deleted pages, the maintenance sweep's facts pass, fact withdrawal
+and doctor's credential check name them. With the policies above it creates
+segmented pages and sees only its sources' rows
+(`test/e2e/segmented-rls-scope.test.ts`).
+
**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/llms-full.txt b/llms-full.txt
index 0f57c54e5a..20000ab232 100644
--- a/llms-full.txt
+++ b/llms-full.txt
@@ -5491,13 +5491,18 @@ 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
+`page_body_staging_parts` (with the segment texts each one holds in
+`page_body_staging_texts`), and view sizes in `page_view_digests`. gbrain
+enables RLS on all six 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
+reads around its hits, `get_chunks` and get_page check a chunk of a page stored
+in segments against `page_body_manifest`. A restricted read role that can see
+such a chunk (a segmented page of one of its sources) needs `SELECT` on it;
+without it those reads fail with `permission_denied` (42501). A role that sees
+no such chunk, as every role does while no page is segmented
+(`pages.segmented_storage` is off by default), reads as before without the
+grant (`test/e2e/segmented-switch-off-rls.test.ts`). 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:
@@ -5513,6 +5518,11 @@ CREATE POLICY page_body_manifest_scope_filter ON page_body_manifest
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), ',')));
+-- A write role records the texts each staging holds here; without a policy its
+-- segmented writes are refused.
+CREATE POLICY page_body_staging_texts_scope_filter ON page_body_staging_texts
+ 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) = '*'
@@ -5540,6 +5550,7 @@ 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_body_staging_texts FORCE ROW LEVEL SECURITY;
ALTER TABLE page_view_digests FORCE ROW LEVEL SECURITY;
ALTER TABLE content_chunks FORCE ROW LEVEL SECURITY;
```
@@ -5549,6 +5560,13 @@ 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.
+A write role that does not own the tables needs `SELECT, INSERT, UPDATE, DELETE`
+on all six, as on any table a migration adds, even while no page is segmented:
+purging soft-deleted pages, the maintenance sweep's facts pass, fact withdrawal
+and doctor's credential check name them. With the policies above it creates
+segmented pages and sees only its sources' rows
+(`test/e2e/segmented-rls-scope.test.ts`).
+
**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/module-size-limits.tsv b/scripts/module-size-limits.tsv
index 6f6bbcac8e..901106f964 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -21,7 +21,7 @@ src/core/import-file.ts 2064 ratchet +2: pre-publication withdrawal validation;
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 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/postgres-engine.ts 3088 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); +3 PR2 fix lane E: getChunkWindows/getChunks/getChunkPage resolve chunkManifestReads inside their scoped transaction (logic in search/safe-chunks.ts; 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/page-body-readers-baseline.tsv b/scripts/page-body-readers-baseline.tsv
index e402d25c9f..c16ecb75f0 100644
--- a/scripts/page-body-readers-baseline.tsv
+++ b/scripts/page-body-readers-baseline.tsv
@@ -411,6 +411,7 @@ src/core/persistence/reconcile-prepare.ts prepareReconcileResult field INLINE
src/core/persistence/reconcile-state.ts readReconcileState sql INLINE
src/core/persistence/reconcile.ts runReconcilePreview call:serializePageToMarkdown SEGW
src/core/persistence/segmented-apply.ts demoteSegmentedPage sql INLINE demotion: the row turns inline with an empty body that the inline write in the same transaction fills
+src/core/persistence/segmented-apply.ts materializedSnapshot field INLINE the body materializedPage read back within PAGE_MAX_BYTES (a page over the ceiling comes back unchanged and is never read), overlaid with the snapshot withdrawals as readPageSnapshot overlays an inline body
src/core/persistence/segmented-apply.ts sealSegmentedPage field LEAD the withdrawal overlay of the stored timeline_lead (a bounded prefix), indexed sanitized
src/core/persistence/segmented-apply.ts stageSegmentedImport field INLINE input.page is the parsed incoming write (strings within PAGE_MAX_BYTES), never a stored segmented row
src/core/persistence/semantic-pages.ts prepareSemanticPageMutation call:serializePageToMarkdown SEGW assertInlineBody first
diff --git a/scripts/structural-suites.tsv b/scripts/structural-suites.tsv
index 47e9106a7c..4bd3b52a52 100644
--- a/scripts/structural-suites.tsv
+++ b/scripts/structural-suites.tsv
@@ -141,7 +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/segmented-rls-scope.test.ts (file-level) 5 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/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 77b39ff41b..abf677b617 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -665,7 +665,8 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }
{ since: 'TBD', text: 'A page purge (`delete_page` with `purge: true`, `gbrain delete --purge` and the 72-hour hard delete of soft-deleted pages) of a page stored in segments no longer breaks another page\'s write that is still being prepared with some of the same text: the purge keeps exactly the segment texts such a write staged, and still deletes every other text only the purged page used. `restore_page` of a page over 24 MiB whose old chunks were still waiting to be removed returns `projection: "pending"` and makes the page searchable once they are gone, instead of showing the old text in search.' },
{ 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: 'The pre-push secret scan (`gbrain sources push` and the automatic pushes) now scans a staged file over 25 MiB in bounded 8 Mi-character windows streamed from git, instead of refusing the push as `blocked_unscannable`: a clean large file pushes, and one holding a secret is refused as `blocked_secrets` naming its file and line. A staged file over 512 MiB still refuses as `blocked_unscannable`.' },
- { 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: 'On Postgres, title search, the source-scoped vector scan, the chunk windows search reads around its hits, `get_chunks` and `get_page` read the new `page_body_manifest` table for a page stored in segments. A database role that neither owns the tables nor bypasses row level security needs `SELECT` on it once it can see a chunk of such a page (a segmented page of one of its sources), or those reads fail with `permission_denied` (42501); while it sees none, as while no page is segmented and `pages.segmented_storage` is off, it reads as before without the grant. Row level security is on for the six new segment tables (`page_segment_texts`, `page_body_manifest`, `page_body_stagings`, `page_body_staging_parts`, `page_body_staging_texts`, `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: '`delete_page` (soft and `purge: true`) of a page stored in segments whose facts fence holds a withdrawn row no longer refuses with `source_changed` ("uncoordinated local edit") while its file is unchanged: a segmented page within 24 MiB is read back with the withdrawal applied, as an inline page is, so it deletes as the same page stored inline does, and `edit_page` edits it with the withdrawn row struck, as for an inline page.' },
{ 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.' },
];
diff --git a/src/core/engine-sql/chunks.ts b/src/core/engine-sql/chunks.ts
index 272cf2bf6e..97f04ebf41 100644
--- a/src/core/engine-sql/chunks.ts
+++ b/src/core/engine-sql/chunks.ts
@@ -391,14 +391,14 @@ async function moveDisplacedChunksAndPrune(exec: SqlExecutor, pageId: number, ch
function chunkReadWhere(
slug: string,
scope: { sourceIds?: string[]; sourceId: string },
- opts?: { excludePrivate?: boolean; requireSafeChunks?: boolean; includeUnsealed?: boolean },
+ opts?: { excludePrivate?: boolean; requireSafeChunks?: boolean; includeUnsealed?: boolean; chunkManifest?: boolean },
): SqlFragment {
const scopeSql = scope.sourceIds
? sqlFragment`p.source_id = ANY(${scope.sourceIds}::text[])`
: sqlFragment`p.source_id = ${scope.sourceId}`;
return sqlFragment`p.slug = ${slug} AND ${scopeSql}
${opts?.excludePrivate ? trustedSql(`AND ${privatePagesFilterFragment('p')}`) : sqlFragment``}
- AND ${trustedSql(opts?.includeUnsealed ? chunkGenerationFilter('p', 'cc') : chunkVisibleFilter('p', 'cc'))}
+ AND ${trustedSql(opts?.includeUnsealed ? chunkGenerationFilter('p', 'cc', opts.chunkManifest ?? true) : chunkVisibleFilter('p', 'cc'))}
${requiresSafeChunks(opts) ? trustedSql(`AND ${safeChunksFilter('p')}`) : sqlFragment``}`;
}
@@ -407,7 +407,7 @@ export async function getChunks(
column: string,
slug: string,
scope: { sourceIds?: string[]; sourceId: string },
- opts?: { includeEmbedding?: boolean; excludePrivate?: boolean; requireSafeChunks?: boolean; includeUnsealed?: boolean; indexRange?: { from: number; to: number; ordinal?: boolean } },
+ opts?: { includeEmbedding?: boolean; excludePrivate?: boolean; requireSafeChunks?: boolean; includeUnsealed?: boolean; chunkManifest?: boolean; indexRange?: { from: number; to: number; ordinal?: boolean } },
): Promise<Chunk[]> {
const colId = trustedSql(quoteIdentifier(column));
const includeEmbedding = opts?.includeEmbedding === true;
@@ -430,7 +430,7 @@ export async function getChunks(
${embedCol}`;
const from = sqlFragment`FROM content_chunks cc
JOIN pages p ON p.id = cc.page_id
- ${trustedSql(chunkManifestJoin('p', 'cc', 'm'))}
+ ${trustedSql(chunkManifestJoin('p', 'cc', 'm', opts?.chunkManifest ?? true))}
WHERE ${chunkReadWhere(slug, scope, opts)}`;
const order = trustedSql(chunkDocumentOrder('cc', 'm'));
const range = opts?.indexRange;
@@ -471,7 +471,7 @@ export async function getChunkPage(
column: string,
slug: string,
scope: { sourceIds?: string[]; sourceId: string },
- opts: { fromIndex: number; limit: number; excludePrivate?: boolean; requireSafeChunks?: boolean },
+ opts: { fromIndex: number; limit: number; excludePrivate?: boolean; requireSafeChunks?: boolean; chunkManifest?: boolean },
): Promise<{ chunks: Chunk[]; total_chunks: number; max_chunk_index: number | null }> {
const { rows } = await exec.run<{ total: number | string; max_index: number | null; segmented: boolean | null; max_page_chunks: number | string | null }>(sqlFragment`
SELECT COALESCE(sum(t.n), 0) AS total, max(t.max_index) AS max_index, bool_or(t.segmented) AS segmented, max(t.n) AS max_page_chunks
@@ -1038,7 +1038,7 @@ export async function getEmbeddingsByChunkIds(exec: LegacyUnscopedRead, ids: num
* rows come back in one UNION so the row cap never hides a page's
* authorization.
*/
-export async function getChunkWindows(exec: ScopedRead, requests: ChunkWindowRequest[], opts: ChunkWindowOpts): Promise<ChunkWindowPage[]> {
+export async function getChunkWindows(exec: ScopedRead, requests: ChunkWindowRequest[], opts: ChunkWindowOpts, chunkManifest = true): Promise<ChunkWindowPage[]> {
if (requests.length === 0) return [];
const maxRows = Math.max(0, Math.floor(opts.maxRows));
const scopeSql = opts.sourceIds && opts.sourceIds.length > 0
@@ -1063,7 +1063,7 @@ export async function getChunkWindows(exec: ScopedRead, requests: ChunkWindowReq
SELECT cc.page_id, cc.id AS chunk_id, cc.chunk_index, cc.chunk_text, cc.chunk_source, cc.projected_byte_start, cc.projected_byte_end, cc.occurrence_id, a.prio
FROM auth a
JOIN content_chunks cc ON cc.page_id = a.id
- WHERE a.sealed AND ${trustedSql(chunkGenerationFilter('a', 'cc'))}
+ WHERE a.sealed AND ${trustedSql(chunkGenerationFilter('a', 'cc', chunkManifest))}
AND cc.chunk_source = ANY(${opts.chunkSources}::text[])
AND COALESCE(cc.modality, 'text') = 'text'
AND EXISTS (SELECT 1 FROM req r WHERE r.page_id = cc.page_id AND cc.chunk_index BETWEEN r.lo AND r.hi)
@@ -1071,7 +1071,7 @@ export async function getChunkWindows(exec: ScopedRead, requests: ChunkWindowReq
LIMIT ${maxRows + 1}
)
SELECT 'page' AS kind, a.id AS page_id, a.slug, a.source_id, a.type, a.revision, a.sealed, a.segmented, a.prio,
- (SELECT MAX(c2.chunk_index) FROM content_chunks c2 WHERE c2.page_id = a.id AND ${trustedSql(chunkGenerationFilter('a', 'c2'))}) AS max_chunk_index,
+ (SELECT MAX(c2.chunk_index) FROM content_chunks c2 WHERE c2.page_id = a.id AND ${trustedSql(chunkGenerationFilter('a', 'c2', chunkManifest))}) AS max_chunk_index,
a.compiled_truth, a.timeline,
NULL::int AS chunk_id, NULL::int AS chunk_index, NULL::text AS chunk_text, NULL::text AS chunk_source,
NULL::bigint AS projected_byte_start, NULL::bigint AS projected_byte_end, NULL::bigint AS occurrence_id
diff --git a/src/core/ops/get-page-body.ts b/src/core/ops/get-page-body.ts
index 1eadfb7770..a71be3b912 100644
--- a/src/core/ops/get-page-body.ts
+++ b/src/core/ops/get-page-body.ts
@@ -48,7 +48,7 @@ import {
import { openSegmentedBody } from '../page-body/read-range.ts';
import { renderTrustedText, type TrustFields } from '../eligibility/labels.ts';
import type { QuarantinedView } from './get-page-projection.ts';
-import { chunkGenerationProbe } from '../search/safe-chunks.ts';
+import { chunkGenerationProbe, chunkManifestReads } from '../search/safe-chunks.ts';
export const BODY_MODES = ['auto', 'full', 'none', 'outline', 'window'] as const;
export type BodyMode = typeof BODY_MODES[number];
@@ -282,7 +282,7 @@ async function aroundChunk(ctx: OperationContext, page: Page, doc: WindowDocumen
Promise<{ window: WindowSlice | null; chunkText: string; anchor: 'stored_span' | 'located' | 'chunk_only'; span?: { byte_start: number; byte_end: number } }> {
const rows = await ctx.engine.executeRaw<{ chunk_text: string; chunk_source: string; occurrence_id: unknown; projected_byte_start: unknown; projected_byte_end: unknown }>(
`SELECT chunk_text, chunk_source, occurrence_id, projected_byte_start, projected_byte_end FROM content_chunks
- WHERE id = $1 AND page_id = $2 AND COALESCE(modality, 'text') = 'text' AND ${chunkGenerationProbe('content_chunks')}`, [chunkId, page.id]);
+ WHERE id = $1 AND page_id = $2 AND COALESCE(modality, 'text') = 'text' AND ${chunkGenerationProbe('content_chunks', await chunkManifestReads(ctx.engine))}`, [chunkId, page.id]);
const row = rows[0];
if (!row || (doc.segments && !doc.segments.body.rows.some(r => r.occurrenceId === Number(row.occurrence_id)))) {
throw opError('revision_changed', `Chunk ${chunkId} is not part of page ${page.slug} at its current revision.`,
@@ -383,7 +383,7 @@ async function noneResult(ctx: OperationContext, page: Page, out: Record<string,
if (isSegmentedPage(page)) return { ...out, ...(fm.embed_skip ? { embed_skip: true } : {}), truncated };
const [counts] = await ctx.engine.executeRaw<{ total: unknown; embedded: unknown }>(
`SELECT count(*) AS total, count(*) FILTER (WHERE embedded_at IS NOT NULL) AS embedded FROM content_chunks
- WHERE page_id = $1 AND ${chunkGenerationProbe('content_chunks')}`, [page.id]);
+ WHERE page_id = $1 AND ${chunkGenerationProbe('content_chunks', await chunkManifestReads(ctx.engine))}`, [page.id]);
return { ...out, chunks: { total: Number(counts?.total ?? 0), embedded: Number(counts?.embedded ?? 0) },
...(fm.embed_skip ? { embed_skip: true } : {}), truncated };
}
diff --git a/src/core/ops/search.ts b/src/core/ops/search.ts
index 453798c191..e8db20ac24 100644
--- a/src/core/ops/search.ts
+++ b/src/core/ops/search.ts
@@ -39,7 +39,7 @@ import { TargetTrace, diagnoseProbe, diagnoseTrace, probeTarget, type ExplainTar
import { assembleEvidenceForHits, capDeliveredSnippets, capEvidenceToBudget, deliverEvidence, pagePlanHits, resolveEvidencePlan, selectLongPages, unsupportedDelivery, withLongPagePolicy, type DeliveryMeta, type DeliveryScope, type EvidencePlan, type FrozenHit, type ReturnUnit } from '../search/evidence-delivery.ts';
import { privateProvenanceFilterFragment, resolveExcludePrivatePages } from '../search/private-visibility.ts';
import { AUDIT_ROW_SOURCES } from '../facts/audit-sources.ts';
-import { SAFE_FENCE_CHUNKER_VERSION } from '../search/safe-chunks.ts';
+import { SAFE_FENCE_CHUNKER_VERSION, chunkManifestReads } from '../search/safe-chunks.ts';
import { expandEngineTypeFilters } from '../schema-pack/query-types.ts';
import { probeProjectionReadiness } from '../search/projection-readiness.ts';
import { resolveBoostMap, resolveHardExcludes } from '../search/source-boost.ts';
@@ -590,7 +590,7 @@ async function prepareExplainTarget(
let probe;
try {
probe = await probeTarget((sql, params) => ctx.engine.executeRaw(sql, params), slug,
- { ...scope, excludePrivate, requireSafeChunks: ctx.remote !== false });
+ { ...scope, excludePrivate, requireSafeChunks: ctx.remote !== false }, await chunkManifestReads(ctx.engine));
} catch {
return { trace: new TargetTrace({ slug, sourceId }) };
}
diff --git a/src/core/persistence/segmented-apply.ts b/src/core/persistence/segmented-apply.ts
index eabaf6fd4b..a06d62d34e 100644
--- a/src/core/persistence/segmented-apply.ts
+++ b/src/core/persistence/segmented-apply.ts
@@ -86,10 +86,18 @@ export function segmentedOverCeiling(page: { body_storage?: string | null; body_
return page.body_storage === 'segmented' && Number(page.body_bytes ?? 0) > PAGE_MAX_BYTES;
}
-/** `materializedPage` over a snapshot (null passes through). */
+/**
+ * `materializedPage` over a snapshot (null passes through), with the read-back body under the snapshot's withdrawal
+ * ledger, as readPageSnapshot gives an inline page's body: a facts row the ledger withdraws is struck (or, purged,
+ * dropped), so the body a write merges into or the drift check compares a file with is the one an inline page has.
+ */
export async function materializedSnapshot(engine: BrainEngine, snapshot: PageSnapshot | null): Promise<PageSnapshot | null> {
if (!snapshot || bodyStorageOf(snapshot.page) !== 'segmented') return snapshot;
- return { ...snapshot, page: await materializedPage(engine, snapshot.page) };
+ const page = await materializedPage(engine, snapshot.page);
+ if (page === snapshot.page) return snapshot;
+ Object.assign(page, await overlayCanonicalBodies(engine.executeRaw.bind(engine), page.compiled_truth, page.timeline ?? '', snapshot.withdrawals,
+ { sourceId: page.source_id, marker: snapshot.globalPurges }));
+ return { ...snapshot, page };
}
/**
diff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.ts
index 98de004f01..0b66c92ea3 100644
--- a/src/core/postgres-engine.ts
+++ b/src/core/postgres-engine.ts
@@ -81,7 +81,7 @@ import {
} from './search/embedding-column.ts';
import { getFtsLanguage, applyFtsLanguagePolicy } from './fts-language.ts';
import { splitEmbeddingSignature, currentSpaceChunkPredicate, lockEmbeddingSources } from './embedding-invalidation.ts';
-import { SAFE_FENCE_CHUNKER_VERSION, bodyWriteChunkVersion, currentTextProjectionFilter, requiresSafeChunks, safeChunksFilter } from './search/safe-chunks.ts';
+import { SAFE_FENCE_CHUNKER_VERSION, bodyWriteChunkVersion, chunkManifestReads, currentTextProjectionFilter, requiresSafeChunks, safeChunksFilter } from './search/safe-chunks.ts';
import type {
Page, PageInput, PageFilters, PageType,
Chunk, ChunkInput, StaleChunkRow, StalePageRow, ChunklessPageRow,
@@ -1190,7 +1190,7 @@ export class PostgresEngine implements BrainEngine {
(read) => this.withScopedReadTransaction(opts?.sourceIds, opts?.sourceId, tx => read(scopedRead(this.engineSqlOn(tx))), { alwaysTransaction: true, jitOff: true }),
query,
opts,
- { statementTimeout: await this.keywordStatementTimeoutSetting(), relaxedPrefersIndex: true, staleProbe: false },
+ { statementTimeout: await this.keywordStatementTimeoutSetting(), relaxedPrefersIndex: true, staleProbe: false, chunkManifest: await chunkManifestReads(this) },
);
}
@@ -1373,7 +1373,7 @@ export class PostgresEngine implements BrainEngine {
// so the HNSW index stays usable; the outer stages re-rank by source
// factor. Statement shape, freshness placement (#5824) and pool counts
// live in search/vector-statement.ts, shared with PGLite and doctor.
- const stmt = buildVectorSearchStatement({ dialect: 'postgres', embedding, limit, offset: opts?.offset || 0, opts, scope: await this.vectorScope(opts) });
+ const stmt = buildVectorSearchStatement({ dialect: 'postgres', embedding, limit, offset: opts?.offset || 0, opts, scope: await this.vectorScope(opts), chunkManifest: await chunkManifestReads(this) });
const iterative = await this.vectorIterativeScanSupported();
const walked = await searchIndexWalk(stmt, limit, async walk => readVectorPool(await this.runVectorAttempt(stmt, walk, iterative, opts, (tx, sql, bound) => tx.unsafe(sql, bound))));
if (walked) return walked.map(rowToSearchResult);
@@ -1405,7 +1405,7 @@ export class PostgresEngine implements BrainEngine {
*/
async explainVectorSearch(embedding: Float32Array, opts?: SearchOpts): Promise<Record<string, unknown>> {
const limit = clampSearchLimit(opts?.limit, 20, searchLimitCap());
- const stmt = buildVectorSearchStatement({ dialect: 'postgres', embedding, limit, offset: opts?.offset || 0, opts, scope: await this.vectorScope(opts) });
+ const stmt = buildVectorSearchStatement({ dialect: 'postgres', embedding, limit, offset: opts?.offset || 0, opts, scope: await this.vectorScope(opts), chunkManifest: await chunkManifestReads(this) });
const iterative = await this.vectorIterativeScanSupported();
const attempt = { innerLimit: stmt.innerLimit, maxScanTuples: stmt.indexWalkSql || stmt.scopeScanSql ? Math.max(2_000, stmt.innerLimit * stmt.indexWalkOverfetch) : POOL_MAX_SCAN_TUPLES, remainingMs: 8_000, exact: false, indexWalk: !!stmt.indexWalkSql, scopeScan: !stmt.indexWalkSql && !!stmt.scopeScanSql };
const [row] = await this.runVectorAttempt(stmt, attempt, iterative, opts, (tx, sql, bound) => tx.unsafe(`EXPLAIN (FORMAT JSON) ${sql}`, bound));
@@ -1548,21 +1548,24 @@ export class PostgresEngine implements BrainEngine {
}
getChunkWindows(requests: ChunkWindowRequest[], opts: ChunkWindowOpts): Promise<ChunkWindowPage[]> {
- return this.withScopedReadTransaction(opts.sourceIds?.length ? opts.sourceIds : undefined, opts.sourceIds?.length ? undefined : opts.sourceId, tx => chunksImpl.getChunkWindows(scopedRead(this.engineSqlOn(tx)), requests, opts));
+ return this.withScopedReadTransaction(opts.sourceIds?.length ? opts.sourceIds : undefined, opts.sourceIds?.length ? undefined : opts.sourceId,
+ async tx => chunksImpl.getChunkWindows(scopedRead(this.engineSqlOn(tx)), requests, opts, requests.length > 0 && await chunkManifestReads(this, this.engineSqlOn(tx))));
}
async getChunks(slug: string, opts?: { sourceId?: string; sourceIds?: string[]; includeEmbedding?: boolean; excludePrivate?: boolean; requireSafeChunks?: boolean; includeUnsealed?: boolean }): Promise<Chunk[]> {
const sourceIds = opts?.sourceIds && opts.sourceIds.length > 0 ? opts.sourceIds : undefined;
const sourceId = opts?.sourceId ?? 'default';
const column = (await resolveActiveEmbeddingColumnFromEngine(this, { fallbackToLegacy: true })).name;
- return this.withScopedReadTransaction(sourceIds, sourceIds ? undefined : sourceId, tx => chunksImpl.getChunks(scopedRead(this.engineSqlOn(tx)), column, slug, { sourceIds, sourceId }, opts));
+ return this.withScopedReadTransaction(sourceIds, sourceIds ? undefined : sourceId,
+ async tx => chunksImpl.getChunks(scopedRead(this.engineSqlOn(tx)), column, slug, { sourceIds, sourceId }, { ...opts, chunkManifest: await chunkManifestReads(this, this.engineSqlOn(tx)) }));
}
async getChunkPage(slug: string, opts: { sourceId?: string; sourceIds?: string[]; excludePrivate?: boolean; requireSafeChunks?: boolean; fromIndex: number; limit: number }) {
const sourceIds = opts.sourceIds && opts.sourceIds.length > 0 ? opts.sourceIds : undefined;
const sourceId = opts.sourceId ?? 'default';
const column = (await resolveActiveEmbeddingColumnFromEngine(this, { fallbackToLegacy: true })).name;
- return this.withScopedReadTransaction(sourceIds, sourceIds ? undefined : sourceId, tx => chunksImpl.getChunkPage(scopedRead(this.engineSqlOn(tx)), column, slug, { sourceIds, sourceId }, opts));
+ return this.withScopedReadTransaction(sourceIds, sourceIds ? undefined : sourceId,
+ async tx => chunksImpl.getChunkPage(scopedRead(this.engineSqlOn(tx)), column, slug, { sourceIds, sourceId }, { ...opts, chunkManifest: await chunkManifestReads(this, this.engineSqlOn(tx)) }));
}
/** S2: quoted identifier of the registry-ACTIVE embedding column for the
@@ -1758,11 +1761,11 @@ export class PostgresEngine implements BrainEngine {
seeds: string[],
opts?: import('./types.ts').RelationalFanoutOpts,
): Promise<import('./types.ts').RelationalFanoutRow[]> {
- return readRelationalFanout(this.executeRaw.bind(this), seeds, opts);
+ return readRelationalFanout(this.executeRaw.bind(this), seeds, opts, await chunkManifestReads(this));
}
async relationalChainHop(frontierPageIds: number[], opts: import('./types.ts').ChainHopOpts): Promise<import('./types.ts').ChainHopEdge[]> {
- return readChainHop(this.executeRaw.bind(this), frontierPageIds, opts);
+ return readChainHop(this.executeRaw.bind(this), frontierPageIds, opts, await chunkManifestReads(this));
}
async getBacklinkCounts(pageIds: number[], opts?: PageReadScope): Promise<Map<number, number>> {
diff --git a/src/core/search/dedup.ts b/src/core/search/dedup.ts
index 567b171b21..3b4242911a 100644
--- a/src/core/search/dedup.ts
+++ b/src/core/search/dedup.ts
@@ -27,7 +27,7 @@
import type { BrainEngine } from '../engine.ts';
import type { SearchResult } from '../types.ts';
-import { chunkManifestJoin, chunkVisibleFilter } from './safe-chunks.ts';
+import { chunkManifestJoin, chunkManifestReads, chunkVisibleFilter } from './safe-chunks.ts';
const COSINE_DEDUP_THRESHOLD = 0.85;
const MAX_TYPE_RATIO = 0.6;
@@ -55,12 +55,13 @@ function pageKey(r: SearchResult): string {
* than MAX_PER_PAGE (otherwise the region rule changes nothing); a failed
* read leaves every page under the inline rule.
*/
-export async function segmentRegions(engine: Pick<BrainEngine, 'executeRaw'>, results: readonly SearchResult[]): Promise<Map<number, number>> {
+export async function segmentRegions(engine: Pick<BrainEngine, 'kind' | 'executeRaw'>, results: readonly SearchResult[]): Promise<Map<number, number>> {
const counts = new Map<string, number>();
for (const r of results) counts.set(pageKey(r), (counts.get(pageKey(r)) ?? 0) + 1);
const ids = results.filter(r => counts.get(pageKey(r))! > MAX_PER_PAGE && r.chunk_id > 0).map(r => r.chunk_id);
if (ids.length === 0) return new Map();
try {
+ if (!await chunkManifestReads(engine)) return new Map();
const rows = await engine.executeRaw<{ id: number; byte_start: number | string }>(`SELECT cc.id, m.byte_start FROM content_chunks cc
JOIN pages p ON p.id = cc.page_id AND p.body_storage = 'segmented'
${chunkManifestJoin('p', 'cc', 'm')}
diff --git a/src/core/search/evidence-delivery.ts b/src/core/search/evidence-delivery.ts
index 2432da4348..371b219fa0 100644
--- a/src/core/search/evidence-delivery.ts
+++ b/src/core/search/evidence-delivery.ts
@@ -29,7 +29,7 @@ import { estimateTokens as heuristicTokens } from './token-budget.ts';
import { redactRetrievalOutput } from './output-redaction.ts';
import { buildSnippetMarker } from './snippet-cap.ts';
import { pageReadFilter } from './read-policy-sql.ts';
-import { chunkGenerationFilter, currentTextProjectionFilter, safeChunksFilter, requiresSafeChunks } from './safe-chunks.ts';
+import { chunkGenerationFilter, chunkManifestReads, currentTextProjectionFilter, safeChunksFilter, requiresSafeChunks } from './safe-chunks.ts';
import { resolveExcludePrivatePages } from './private-visibility.ts';
import { safeSplitIndex } from '../text-safe.ts';
import { loadFenceChunkOverlay, type FenceChunkOverlay } from '../eligibility/fence-overlay.ts';
@@ -1610,7 +1610,7 @@ export async function resolveFrozenHits(
cc.id AS chunk_id, cc.chunk_index, cc.chunk_text, cc.chunk_source
FROM unnest($1::text[], $2::text[], $3::int[], $4::int[]) AS h(source_id, slug, chunk_id, ord)
JOIN pages p ON p.source_id = h.source_id AND p.slug = h.slug
- LEFT JOIN content_chunks cc ON cc.page_id = p.id AND ${chunkGenerationFilter('p', 'cc')}
+ LEFT JOIN content_chunks cc ON cc.page_id = p.id AND ${chunkGenerationFilter('p', 'cc', await chunkManifestReads(engine))}
AND CASE WHEN h.chunk_id > 0 THEN cc.id = h.chunk_id ELSE cc.chunk_index = 0 END
WHERE ${filter} AND ${currentTextProjectionFilter('p')} ${safe}`,
params,
diff --git a/src/core/search/explain-target.ts b/src/core/search/explain-target.ts
index fa66d178e1..705ea2f446 100644
--- a/src/core/search/explain-target.ts
+++ b/src/core/search/explain-target.ts
@@ -175,12 +175,12 @@ export interface TargetProbeRow {
type ReadQuery = <T = Record<string, unknown>>(sql: string, params?: unknown[]) => Promise<T[]>;
/** Every readable live copy of `slug` under the caller's policy (one query). */
-export async function probeTarget(query: ReadQuery, slug: string, policy: PageReadPolicy): Promise<TargetProbeRow[]> {
+export async function probeTarget(query: ReadQuery, slug: string, policy: PageReadPolicy, chunkManifest = true): Promise<TargetProbeRow[]> {
const params: unknown[] = [slug];
const filter = pageReadFilter('p', policy, params, true);
const rows = await query<{ source_id: string; chunks: number; current: boolean; chunker_version: number | null }>(
`SELECT p.source_id,
- (SELECT COUNT(*)::int FROM content_chunks cc WHERE cc.page_id = p.id AND ${chunkGenerationFilter('p', 'cc')}) AS chunks,
+ (SELECT COUNT(*)::int FROM content_chunks cc WHERE cc.page_id = p.id AND ${chunkGenerationFilter('p', 'cc', chunkManifest)}) AS chunks,
((p.text_projection_revision = p.knowledge_revision) IS TRUE) AS current,
p.chunker_version
FROM pages p WHERE p.slug = $1 AND ${filter} ORDER BY p.source_id`, params);
diff --git a/src/core/search/read-enrichment.ts b/src/core/search/read-enrichment.ts
index 33b8164d54..166fbf1271 100644
--- a/src/core/search/read-enrichment.ts
+++ b/src/core/search/read-enrichment.ts
@@ -16,7 +16,7 @@ function originFilter(scope: PageReadScope | undefined, params: unknown[]): stri
}
/** Authorize graph seeds, hops and edge origins before ranking or emitting paths. */
-export async function readRelationalFanout(query: ReadQuery, seeds: string[], opts?: RelationalFanoutOpts): Promise<RelationalFanoutRow[]> {
+export async function readRelationalFanout(query: ReadQuery, seeds: string[], opts?: RelationalFanoutOpts, chunkManifest = true): Promise<RelationalFanoutRow[]> {
if (!seeds?.length) return [];
const depth = Math.min(Math.max(1, opts?.depth ?? 2), 3);
const direction = opts?.direction ?? 'both';
@@ -71,7 +71,7 @@ export async function readRelationalFanout(query: ReadQuery, seeds: string[], op
array_length(n.path, 1) ASC, array_to_string(n.path, chr(9)) ASC))[1] AS path_str,
(array_agg(array_to_string(n.edges, chr(9)) ORDER BY n.depth ASC,
array_length(n.path, 1) ASC, array_to_string(n.path, chr(9)) ASC))[1] AS edges_str,
- (SELECT cc.id FROM content_chunks cc WHERE cc.page_id = n.id AND ${chunkGenerationProbe('cc')}
+ (SELECT cc.id FROM content_chunks cc WHERE cc.page_id = n.id AND ${chunkGenerationProbe('cc', chunkManifest)}
${requiresSafeChunks(opts) ? `AND EXISTS (SELECT 1 FROM pages cp WHERE cp.id = n.id AND ${safeChunksFilter('cp')})` : ''}
ORDER BY cc.chunk_index ASC LIMIT 1) AS canonical_chunk_id
FROM walk n WHERE n.depth > 0 GROUP BY n.source_id, n.slug, n.id
@@ -114,7 +114,7 @@ function inlineIds(ids: number[], label: string): string {
* the relationship-validity predicate) before anything is returned; edge context is returned only when the evidence page's text is
* readable under the policy.
*/
-export async function readChainHop(query: ReadQuery, frontier: number[], opts: ChainHopOpts): Promise<ChainHopEdge[]> {
+export async function readChainHop(query: ReadQuery, frontier: number[], opts: ChainHopOpts, chunkManifest = true): Promise<ChainHopEdge[]> {
if (!frontier.length || !opts.linkTypes.length) return [];
const ids = inlineIds([...new Set(frontier)], 'readChainHop');
// Pages are fetched by primary key behind an optimization fence: the read
@@ -213,7 +213,7 @@ export async function readChainHop(query: ReadQuery, frontier: number[], opts: C
r.link_ids, sf.slug AS stored_from_slug, st.slug AS stored_to_slug,
CASE WHEN ev.id IS NOT NULL ${textGate} THEN el.context END AS context,
el.origin_page_id, op.slug AS origin_slug, deg.degree AS from_degree, (r.per_frontier > $5) AS cap_hit,
- (SELECT cc.id FROM content_chunks cc WHERE cc.page_id = r.next_id AND ${chunkGenerationProbe('cc')}
+ (SELECT cc.id FROM content_chunks cc WHERE cc.page_id = r.next_id AND ${chunkGenerationProbe('cc', chunkManifest)}
${requiresSafeChunks(policy) ? `AND EXISTS (SELECT 1 FROM pages cp WHERE cp.id = r.next_id AND ${safeChunksFilter('cp')})` : ''}
ORDER BY cc.chunk_index ASC LIMIT 1) AS canonical_chunk_id
FROM ranked r
diff --git a/src/core/search/safe-chunks.ts b/src/core/search/safe-chunks.ts
index a96efe9058..b611f9d7e6 100644
--- a/src/core/search/safe-chunks.ts
+++ b/src/core/search/safe-chunks.ts
@@ -1,5 +1,6 @@
import type { ChunkInput, PageReadScope } from '../types.ts';
import { jsonRowBatches } from '../batch-rows.ts';
+import type { BrainEngine } from '../engine.ts';
/** First markdown index built from the strict full-body fence sanitizer. */
export const SAFE_FENCE_CHUNKER_VERSION = 4;
@@ -53,8 +54,11 @@ export function currentTextProjectionFilter(alias: string): string {
* retirement) and rows of a preparation that never published are invisible
* whether or not they were deleted yet. The manifest probe is one primary-key
* lookup per segmented row; `page` must expose `body_storage` and `body_generation`.
+ * `manifest: false` (chunkManifestReads) drops the segmented branch, which then
+ * matches no row the reader can see.
*/
-export function chunkGenerationFilter(page: string, chunk: string): string {
+export function chunkGenerationFilter(page: string, chunk: string, manifest = true): string {
+ if (!manifest) return `(${chunk}.body_generation IS NULL AND ${page}.body_storage <> 'segmented')`;
return `((${chunk}.body_generation IS NULL AND ${page}.body_storage <> 'segmented')
OR (${chunk}.body_generation <= ${page}.body_generation
AND EXISTS (SELECT 1 FROM page_body_manifest lm WHERE lm.page_id = ${chunk}.page_id AND lm.occurrence_id = ${chunk}.occurrence_id
@@ -62,8 +66,32 @@ export function chunkGenerationFilter(page: string, chunk: string): string {
}
/** `chunkGenerationFilter` for a statement that has no page row joined. */
-export function chunkGenerationProbe(chunk: string): string {
- return `EXISTS (SELECT 1 FROM pages gp WHERE gp.id = ${chunk}.page_id AND ${chunkGenerationFilter('gp', chunk)})`;
+export function chunkGenerationProbe(chunk: string, manifest = true): string {
+ return `EXISTS (SELECT 1 FROM pages gp WHERE gp.id = ${chunk}.page_id AND ${chunkGenerationFilter('gp', chunk, manifest)})`;
+}
+
+const CHUNK_MANIFEST_ACCESS_SQL = `-- chunk-visibility-ok: whether any chunk row of a segmented body exists, no row is returned
+SELECT has_table_privilege('page_body_manifest', 'SELECT') AS readable,
+ NOT has_table_privilege('page_body_manifest', 'SELECT')
+ AND (EXISTS (SELECT 1 FROM content_chunks WHERE body_generation IS NOT NULL)
+ OR EXISTS (SELECT 1 FROM content_chunks WHERE occurrence_id IS NOT NULL)) AS segmented`;
+const manifestReadable = new WeakSet<object>();
+
+/**
+ * Whether a read's chunk statements name `page_body_manifest`. Postgres checks the privilege on every relation a
+ * statement names, matched or not, so a role without SELECT on it (docs/ENGINES.md, "Segmented page tables") would
+ * fail every chunk read with 42501 although no page is segmented. True on PGLite, for a role that may read the
+ * manifest (kept per engine: a transaction clone probes again, so its SET LOCAL ROLE counts) and for a role that sees
+ * a chunk row of a segmented body (`body_generation` or `occurrence_id` set, both partial-indexed), which then gets
+ * 42501 as documented. Otherwise every chunk row the role sees is an inline row, and the manifest-free forms of
+ * chunkGenerationFilter, chunkGenerationProbe and chunkManifestJoin select exactly the rows the full forms would.
+ * `db` runs the probe: a scoped read passes its transaction, so the probe sees the rows that read sees.
+ */
+export async function chunkManifestReads(engine: Pick<BrainEngine, 'kind' | 'executeRaw'>, db: Pick<BrainEngine, 'executeRaw'> = engine): Promise<boolean> {
+ if (engine.kind !== 'postgres' || manifestReadable.has(engine)) return true;
+ const [access] = await db.executeRaw<{ readable: boolean; segmented: boolean }>(CHUNK_MANIFEST_ACCESS_SQL);
+ if (access?.readable) manifestReadable.add(engine);
+ return access?.readable === true || access?.segmented === true;
}
/**
@@ -80,8 +108,10 @@ export function chunkVisibleFilter(page: string, chunk: string): string {
/**
* The live manifest row of a segmented chunk (no row for an inline chunk), for
* `chunkDocumentOrder`. LEFT JOIN text; `page` must expose `body_generation`.
+ * `readsManifest: false` (chunkManifestReads) joins no row, as for an inline chunk.
*/
-export function chunkManifestJoin(page: string, chunk: string, manifest: string): string {
+export function chunkManifestJoin(page: string, chunk: string, manifest: string, readsManifest = true): string {
+ if (!readsManifest) return `LEFT JOIN (SELECT NULL::bigint AS byte_start) ${manifest} ON false`;
return `LEFT JOIN page_body_manifest ${manifest} ON ${chunk}.occurrence_id IS NOT NULL
AND ${manifest}.page_id = ${chunk}.page_id AND ${manifest}.occurrence_id = ${chunk}.occurrence_id
AND ${manifest}.staging_id IS NULL AND ${manifest}.gen_from <= ${page}.body_generation
diff --git a/src/core/search/title-statement.ts b/src/core/search/title-statement.ts
index 6525534775..7e5bae7efa 100644
--- a/src/core/search/title-statement.ts
+++ b/src/core/search/title-statement.ts
@@ -27,6 +27,8 @@ export interface SearchTitlesDialect {
relaxedPrefersIndex: boolean;
/** Project `stale` from timeline_entries (PGLite); otherwise `false`. */
staleProbe: boolean;
+ /** chunkManifestReads; unset reads the manifest. */
+ chunkManifest?: boolean;
}
export interface SearchTitlesStatement {
@@ -131,7 +133,7 @@ export function buildSearchTitlesStatement(query: string, opts: SearchOpts | und
LEFT JOIN LATERAL (
SELECT cc.id, cc.chunk_index, cc.chunk_text, cc.chunk_source
FROM content_chunks cc
- WHERE cc.page_id = tp.page_id AND ${chunkGenerationFilter('tp', 'cc')}
+ WHERE cc.page_id = tp.page_id AND ${chunkGenerationFilter('tp', 'cc', dialect.chunkManifest ?? true)}
AND cc.modality = 'text'
${detailLow ? `AND cc.chunk_source = 'compiled_truth'` : ''}
ORDER BY (cc.chunk_source = 'compiled_truth') DESC, cc.chunk_index ASC
diff --git a/src/core/search/vector-statement.ts b/src/core/search/vector-statement.ts
index 2d63dca342..beba16cde5 100644
--- a/src/core/search/vector-statement.ts
+++ b/src/core/search/vector-statement.ts
@@ -80,6 +80,8 @@ export interface VectorSearchStatementInput {
* omitted; at most SCOPE_SCAN_MAX_CHUNKS adds the scope scan.
*/
scope?: VectorScope;
+ /** chunkManifestReads; unset reads the manifest. */
+ chunkManifest?: boolean;
}
export interface VectorSearchStatement {
@@ -399,7 +401,7 @@ export function buildVectorSearchStatement(input: VectorSearchStatementInput): V
${hardExcludeClause}
${pageVisibilityClause}
))
- AND ${chunkGenerationProbe('cc')}
+ AND ${chunkGenerationProbe('cc', input.chunkManifest ?? true)}
AND cc.${col} IS NOT NULL ${modalityFilter}
${chunkFilters.join('\n ')}
${relaxedGeneration}
diff --git a/test/e2e/segmented-rls-scope.test.ts b/test/e2e/segmented-rls-scope.test.ts
index 66214e1e42..809441cceb 100644
--- a/test/e2e/segmented-rls-scope.test.ts
+++ b/test/e2e/segmented-rls-scope.test.ts
@@ -1,8 +1,8 @@
/**
* 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
+ * 1. Protects: the six segment tables (page_segment_texts, page_body_manifest, page_body_stagings,
+ * page_body_staging_parts, page_body_staging_texts, 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,
@@ -22,7 +22,7 @@ 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 { 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';
@@ -31,9 +31,10 @@ 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 WRITER = `gbrain_seg_rls_writer_${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'];
+const PAGE_BODY_RLS_TABLES = ['page_body_manifest', 'page_body_staging_parts', 'page_body_staging_texts', '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'];
@@ -86,7 +87,7 @@ const sourcesOf = (hits: Array<{ source_id?: unknown }>) => [...new Set(hits.map
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]) {
+ for (const role of [OPEN, READER, LEGACY, WRITER]) {
await engine.executeRaw(`DROP OWNED BY ${role}`).catch(() => undefined);
await engine.executeRaw(`DROP ROLE IF EXISTS ${role}`);
}
@@ -182,5 +183,47 @@ const sourcesOf = (hits: Array<{ source_id?: unknown }>) => [...new Set(hits.map
expect(failure).toBe('42501');
expect(sourcesOf(await asRole(engine, LEGACY, tx => tx.searchKeyword(SOURCES['src-a'], { sourceId: 'src-a' })))).toEqual(['src-a']);
}, 120_000);
+
+ test('N7: a non-owner write role under the recipe creates a segmented page, recording its staging holds, and sees only its source', async () => {
+ // A login role, so every pooled connection of its engine runs as it, scoped to src-a by its own default.
+ const password = randomUUID();
+ await engine.executeRaw(`CREATE ROLE ${WRITER} LOGIN PASSWORD '${password}' NOSUPERUSER NOBYPASSRLS`);
+ await engine.executeRaw(`ALTER ROLE ${WRITER} SET app.scopes = 'src-a'`);
+ await engine.executeRaw(`GRANT USAGE ON SCHEMA public TO ${WRITER}`);
+ await engine.executeRaw(`GRANT ALL ON ALL TABLES IN SCHEMA public TO ${WRITER}`);
+ await engine.executeRaw(`GRANT ALL ON ALL SEQUENCES IN SCHEMA public TO ${WRITER}`);
+ // The recipe (and the pages policy) scopes the page tables; every other table under RLS opens to the writer.
+ const scoped = new Set(['pages', ...[...docsRecipe(WRITER).matchAll(/CREATE POLICY \w+ ON (\w+)/g)].map(m => m[1]!)]);
+ const rls = await engine.executeRaw<{ relname: string }>(`SELECT c.relname FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace
+ WHERE n.nspname = 'public' AND c.relkind = 'r' AND c.relrowsecurity ORDER BY 1`);
+ for (const { relname } of rls.filter(r => !scoped.has(r.relname))) {
+ await engine.executeRaw(`CREATE POLICY ${WRITER}_open ON ${relname} FOR ALL TO ${WRITER} USING (true) WITH CHECK (true)`);
+ policies.push({ name: `${WRITER}_open`, table: relname });
+ }
+ const url = new URL(process.env.DATABASE_URL!);
+ url.username = WRITER;
+ url.password = password;
+ const writer = new PostgresEngine();
+ await writer.connect({ database_url: url.toString(), poolSize: 4 });
+ expect(await writer.executeRaw("SELECT current_user AS role, current_setting('app.scopes', true) AS scopes")).toEqual([{ role: WRITER, scopes: 'src-a' }]);
+ try {
+ const holds = async () => Number((await engine.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM page_body_staging_texts t JOIN page_body_stagings s ON s.id = t.staging_id
+ WHERE s.source_id = 'src-a' AND s.slug = 'notes/writer-ledger'`))[0]!.n);
+ const content = conversationPage(2 * 1024 * 1024, { seed: 73, title: 'Writer ledger', needles: [{ at: 0.4, word: 'writerneedle' }] });
+ const imported = await importFromContent(writer, 'notes/writer-ledger', content, { noEmbed: true, sourceId: 'src-a' });
+ expect(imported.status).toBe('imported');
+ expect(await engine.executeRaw("SELECT body_storage FROM pages WHERE slug = 'notes/writer-ledger' AND source_id = 'src-a'")).toEqual([{ body_storage: 'segmented' }]);
+ expect(await holds()).toBeGreaterThan(0);
+ expect({
+ own: sourcesOf(await writer.searchKeyword('writerneedle')),
+ other: sourcesOf(await writer.searchKeyword(SOURCES['src-b'])),
+ texts: sourcesOf(await writer.executeRaw<{ source_id: string }>('SELECT DISTINCT source_id FROM page_segment_texts')),
+ holds: sourcesOf(await writer.executeRaw<{ source_id: string }>('SELECT DISTINCT source_id FROM page_body_staging_texts')),
+ stagings: sourcesOf(await writer.executeRaw<{ source_id: string }>('SELECT DISTINCT source_id FROM page_body_stagings')),
+ }).toEqual({ own: ['src-a'], other: [], texts: ['src-a'], holds: ['src-a'], stagings: ['src-a'] });
+ } finally {
+ await writer.disconnect();
+ }
+ }, 300_000);
});
});
diff --git a/test/e2e/segmented-switch-off-rls.test.ts b/test/e2e/segmented-switch-off-rls.test.ts
new file mode 100644
index 0000000000..6c9a5041fb
--- /dev/null
+++ b/test/e2e/segmented-switch-off-rls.test.ts
@@ -0,0 +1,166 @@
+/**
+ * Segmented page tables while segmented storage is off (Wave B PR 2, fix lane E: E1).
+ *
+ * 1. Protects: "while pages.segmented_storage is off nothing user-visible changes" for a restricted Postgres role
+ * (NOLOGIN, NOBYPASSRLS, not the owner) holding the pre-Wave-B grant set (SELECT on every table except the
+ * segment tables). Postgres checks the privilege of every relation a statement names, matched or not, so a chunk
+ * read that names page_body_manifest fails with 42501 on a brain that has no segmented page. With no segmented
+ * chunk row the role can see, every search arm, the chunk windows, get_chunks and get_page run without the grant,
+ * as a pooled session role and under SET LOCAL ROLE in a transaction, and read only the role's source. A page
+ * segmented in another source changes nothing for it. Once a page of its own source is segmented the documented
+ * grant is required (42501 without it), and with the docs/ENGINES.md manifest policy the role still sees only its
+ * source's manifest rows.
+ * 2. Fails when: a read path a restricted role runs names a segment table although the role can see no segmented
+ * chunk row, or a role that can see one reads its chunks without the manifest.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import type { BrainEngine } from '../../src/core/engine.ts';
+import type { GBrainConfig } from '../../src/core/config.ts';
+import { importFromContent } from '../../src/core/import-file.ts';
+import { operations, type OperationContext } from '../../src/core/operations.ts';
+import { PostgresEngine } from '../../src/core/postgres-engine.ts';
+import { segmentRegions } from '../../src/core/search/dedup.ts';
+import { resolveFrozenHits } from '../../src/core/search/evidence-delivery.ts';
+import type { SearchResult } from '../../src/core/types.ts';
+import { conversationPage } from '../helpers/conversation-page.ts';
+import { installFixtureChunks } from '../helpers/page-projection.ts';
+import { vector } from '../helpers/search-query-contract.ts';
+import { hasDatabase, setupLegacyEmbeddingDB, teardownDB } from './helpers.ts';
+
+const READER = 'gbrain_seg_off_reader_' + randomUUID().replaceAll('-', '').slice(0, 12);
+const SEGMENT_TABLES = ['page_body_manifest', 'page_body_staging_parts', 'page_body_staging_texts', 'page_body_stagings', 'page_segment_texts', 'page_view_digests'];
+const SCOPE = "current_setting('app.scopes', true) = '*' OR source_id = ANY(string_to_array(current_setting('app.scopes', true), ','))";
+const sourcesOf = (rows: ReadonlyArray<{ source_id?: unknown }>) => [...new Set(rows.map(r => String(r.source_id)))].sort();
+
+type Arm = (e: BrainEngine) => Promise<string[]>;
+
+(hasDatabase() ? describe : describe.skip)('segment tables while segmented storage is off (restricted role)', () => {
+ let engine: PostgresEngine;
+ let reader: PostgresEngine;
+ const ids: Record<string, number> = {};
+ let granted: string[] = [];
+
+ const ctxOf = (e: BrainEngine): OperationContext => ({ engine: e, config: {} as GBrainConfig, logger: { info() {}, warn() {}, error() {} },
+ dryRun: false, remote: true, sourceId: 'src-a' }) as unknown as OperationContext;
+ const op = (name: string, params: Record<string, unknown>) => operations.find(o => o.name === name)!.handler;
+ const run = (e: BrainEngine, name: string, params: Record<string, unknown>) => op(name, params)(ctxOf(e), params) as Promise<Record<string, unknown>>;
+
+ /** Arms that only read; each returns the sources it saw. */
+ const engineArms: Record<string, Arm> = {
+ keyword: async e => sourcesOf(await e.searchKeyword('ledgerneedle', { sourceId: 'src-a' })),
+ keywordChunks: async e => sourcesOf(await e.searchKeywordChunks('ledgerneedle', { sourceId: 'src-a' })),
+ titles: async e => sourcesOf(await e.searchTitles('ledger', { sourceId: 'src-a' })),
+ vector: async e => { await e.searchVector(vector, { sourceId: 'src-a' }); return sourcesOf(await e.searchVector(vector, { sourceId: 'src-a' })); },
+ windows: async e => sourcesOf(await e.getChunkWindows([ids['src-a']!, ids['src-b']!].map(page_id => ({ page_id, from_index: 0, to_index: 3, priority: 0 })),
+ { chunkSources: ['compiled_truth', 'timeline'], maxRows: 20 })),
+ chunks: async e => (await e.getChunks('notes/ledger', { sourceId: 'src-a', includeUnsealed: true })).length > 0 ? ['src-a'] : [],
+ chunkPage: async e => (await e.getChunkPage('notes/ledger', { sourceId: 'src-a', fromIndex: 0, limit: 10 })).chunks.length > 0 ? ['src-a'] : [],
+ fanout: async e => sourcesOf(await e.relationalFanout(['notes/ledger'], { sourceId: 'src-a', depth: 1 } as never)),
+ regions: async e => {
+ const hits = [1, 2, 3].map(i => ({ slug: 'notes/ledger', source_id: 'src-a', chunk_id: i, page_id: ids['src-a'] }) as unknown as SearchResult);
+ return (await segmentRegions(e, hits)).size === 0 ? ['src-a'] : [];
+ },
+ frozen: async e => sourcesOf((await resolveFrozenHits(e, ['src-a', 'src-b'].map(source_id => ({ source_id, slug: 'notes/ledger', chunk_id: 0 })), {})).rows),
+ };
+ /** Operations; their best-effort last-retrieved write-back needs a writable role, so they run as the session role only. */
+ const opArms: Record<string, Arm> = {
+ get_page_none: async e => [String((await run(e, 'get_page', { slug: 'notes/ledger', source_id: 'src-a', body: 'none' })).source_id ?? 'src-a')],
+ get_page_full: async e => [String((await run(e, 'get_page', { slug: 'notes/ledger', source_id: 'src-a' })).source_id ?? 'src-a')],
+ get_page_auto: async e => [String((await run(e, 'get_page', { slug: 'notes/ledger', source_id: 'src-a', body: 'auto' })).source_id ?? 'src-a')],
+ get_chunks: async e => { await run(e, 'get_chunks', { slug: 'notes/ledger' }); return ['src-a']; },
+ search: async e => sourcesOf(await run(e, 'search', { query: 'ledgerneedle' }) as never),
+ explain_target: async e => { await run(e, 'search', { query: 'ledgerneedle', explain_target: 'notes/ledger' }); return ['src-a']; },
+ query: async e => sourcesOf(await run(e, 'query', { query: 'ledgerneedle', expand: false }) as never),
+ };
+
+ async function asSessionRole(arms: Record<string, Arm>): Promise<Record<string, unknown>> {
+ const out: Record<string, unknown> = {};
+ for (const [name, arm] of Object.entries(arms)) out[name] = await arm(reader).catch((e: { code?: string }) => 'error ' + e.code);
+ return out;
+ }
+ async function asLocalRole(arms: Record<string, Arm>): Promise<Record<string, unknown>> {
+ const out: Record<string, unknown> = {};
+ for (const [name, arm] of Object.entries(arms)) {
+ out[name] = await engine.transaction(async tx => {
+ await tx.executeRaw('SET LOCAL ROLE ' + READER);
+ await tx.executeRaw("SELECT set_config('app.scopes', 'src-a', true)");
+ return arm(tx);
+ }).catch((e: { code?: string }) => 'error ' + e.code);
+ }
+ return out;
+ }
+ const allSrcA = (arms: Record<string, Arm>) => Object.fromEntries(Object.keys(arms).map(name => [name, ['src-a']]));
+
+ beforeAll(async () => {
+ engine = await setupLegacyEmbeddingDB();
+ for (const id of ['src-a', 'src-b']) {
+ await engine.executeRaw('INSERT INTO sources (id, name) VALUES ($1, $1) ON CONFLICT (id) DO NOTHING', [id]);
+ for (const slug of ['notes/ledger', 'notes/ledger-peer']) {
+ await engine.putPage(slug, { type: 'note', title: 'Ledger ' + id, compiled_truth: 'ledgerneedle ' + id + ' see [[notes/ledger-peer]]' }, { sourceId: id });
+ await installFixtureChunks(engine, slug, [0, 1].map(chunk_index => ({ chunk_index, chunk_source: 'compiled_truth' as const, chunk_text: 'ledgerneedle ' + id + ' part ' + chunk_index, embedding: vector })), { sourceId: id });
+ }
+ await engine.addLink('notes/ledger', 'notes/ledger-peer', '', 'mentions', 'markdown', undefined, undefined, { fromSourceId: id, toSourceId: id } as never).catch(() => undefined);
+ ids[id] = Number((await engine.executeRaw<{ id: number }>("SELECT id FROM pages WHERE slug = 'notes/ledger' AND source_id = $1", [id]))[0]!.id);
+ }
+ // Enough pages outside src-a that its vector search takes the source-scope scan.
+ for (let i = 0; i < 12; i++) {
+ await engine.putPage('notes/filler-' + i, { type: 'note', title: 'Filler ' + i, compiled_truth: 'filler ' + i }, { sourceId: 'src-b' });
+ await installFixtureChunks(engine, 'notes/filler-' + i, [{ chunk_index: 0, chunk_source: 'compiled_truth', chunk_text: 'filler ' + i, embedding: vector }], { sourceId: 'src-b' });
+ }
+ await engine.executeRaw('ANALYZE pages');
+ await engine.executeRaw('ANALYZE content_chunks');
+
+ await engine.executeRaw('CREATE ROLE ' + READER + ' NOLOGIN NOSUPERUSER NOBYPASSRLS');
+ await engine.executeRaw('GRANT USAGE ON SCHEMA public TO ' + READER);
+ granted = (await engine.executeRaw<{ t: string }>("SELECT tablename AS t FROM pg_tables WHERE schemaname = 'public' ORDER BY 1")).map(r => r.t).filter(t => !SEGMENT_TABLES.includes(t));
+ await engine.executeRaw('GRANT SELECT ON ' + granted.join(', ') + ' TO ' + READER);
+ for (const t of granted) {
+ const using = t === 'pages' ? SCOPE : t === 'content_chunks' ? "current_setting('app.scopes', true) = '*' OR EXISTS (SELECT 1 FROM pages p WHERE p.id = page_id)" : 'true';
+ await engine.executeRaw('CREATE POLICY ' + READER + '_read ON ' + t + ' FOR SELECT TO ' + READER + ' USING (' + using + ')');
+ }
+ reader = new PostgresEngine();
+ await reader.connect({ database_url: process.env.DATABASE_URL!, poolSize: 1 });
+ await reader.executeRaw('SET ROLE ' + READER);
+ await reader.executeRaw("SET app.scopes = 'src-a'");
+ }, 300_000);
+
+ afterAll(async () => {
+ await reader?.disconnect();
+ if (engine) {
+ for (const t of [...granted, 'page_body_manifest']) await engine.executeRaw('DROP POLICY IF EXISTS ' + READER + '_read ON ' + t);
+ await engine.executeRaw('DROP OWNED BY ' + READER).catch(() => undefined);
+ await engine.executeRaw('DROP ROLE IF EXISTS ' + READER);
+ }
+ await teardownDB();
+ });
+
+ test('E1: with no segmented page, a role without the manifest grant runs every search arm, the chunk windows, get_chunks and get_page', async () => {
+ expect(await engine.executeRaw("SELECT count(*)::int AS n FROM pages WHERE body_storage = 'segmented'")).toEqual([{ n: 0 }]);
+ expect(await engine.getConfig('pages.segmented_storage')).toBeNull();
+ expect({ session: await asSessionRole({ ...engineArms, ...opArms }), local: await asLocalRole(engineArms) })
+ .toEqual({ session: allSrcA({ ...engineArms, ...opArms }), local: allSrcA(engineArms) });
+ }, 120_000);
+
+ test('E1: a page segmented in another source changes nothing; one in its own source requires the documented grant, and the policy hides the other source', async () => {
+ await engine.setConfig('pages.segmented_storage', 'on');
+ const segment = async (id: string, seed: number) => {
+ const content = conversationPage(2 * 1024 * 1024, { seed, title: 'Ledger big ' + id, needles: [{ at: 0.5, word: 'ledgerneedle' }] });
+ expect((await importFromContent(engine, 'notes/big-ledger', content, { noEmbed: true, sourceId: id })).status).toBe('imported');
+ expect(await engine.executeRaw("SELECT body_storage FROM pages WHERE slug = 'notes/big-ledger' AND source_id = $1", [id])).toEqual([{ body_storage: 'segmented' }]);
+ };
+ await segment('src-b', 81);
+ expect({ session: await asSessionRole(engineArms), local: await asLocalRole(engineArms) }).toEqual({ session: allSrcA(engineArms), local: allSrcA(engineArms) });
+
+ await segment('src-a', 82);
+ expect(await asSessionRole({ titles: engineArms.titles!, windows: engineArms.windows! })).toEqual({ titles: 'error 42501', windows: 'error 42501' });
+ expect(await asLocalRole({ titles: engineArms.titles! })).toEqual({ titles: 'error 42501' });
+
+ await engine.executeRaw('GRANT SELECT ON page_body_manifest TO ' + READER);
+ await engine.executeRaw('CREATE POLICY ' + READER + '_read ON page_body_manifest FOR SELECT TO ' + READER + ' USING (' + SCOPE + ')');
+ const manifestSources = async (e: BrainEngine) => sourcesOf(await e.executeRaw<{ source_id: string }>('SELECT DISTINCT source_id FROM page_body_manifest'));
+ const arms = { ...engineArms, manifest: manifestSources };
+ expect({ session: await asSessionRole(arms), local: await asLocalRole(arms) }).toEqual({ session: allSrcA(arms), local: allSrcA(arms) });
+ expect(await manifestSources(engine)).toEqual(['src-a', 'src-b']);
+ }, 300_000);
+});
diff --git a/test/large-pages/segmented-withdrawn-fence-delete.test.ts b/test/large-pages/segmented-withdrawn-fence-delete.test.ts
new file mode 100644
index 0000000000..4226588f48
--- /dev/null
+++ b/test/large-pages/segmented-withdrawn-fence-delete.test.ts
@@ -0,0 +1,134 @@
+/**
+ * Wave B PR 2 fix lane E (E2): delete_page of a segmented, fenced, managed page whose own facts row is withdrawn.
+ *
+ * 1. Protects: the drift check reads a segmented page within the single-string ceiling back whole
+ * (materializedSnapshot) and compares it with its canonical file overlaid by the snapshot's withdrawal ledger, as
+ * for an inline page. The read-back body gets the same overlay readPageSnapshot gives an inline body, so the page
+ * soft-deletes and purges exactly as the same page stored inline does, for a withdrawal of its own row (subject =
+ * slug) or a source-wide one ('*'), and its read-back body equals the inline snapshot's byte for byte. A page over
+ * the ceiling (compared by digest, never read back whole) deletes under the same ledger too.
+ * 2. Fails when: the read-back body of a segmented page skips the withdrawal overlay, so the unchanged file reads as an
+ * uncoordinated local edit (source_changed) and the page cannot be deleted while its inline twin can.
+ * Runs on PGLite, and on Postgres when DATABASE_URL is set.
+ */
+import { afterAll, beforeAll, expect, test } from 'bun:test';
+import { createHash, randomUUID } from 'node:crypto';
+import { execFileSync } from 'node:child_process';
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';
+import type { BrainEngine } from '../../src/core/engine.ts';
+import type { OperationContext } from '../../src/core/operations.ts';
+import { PAGE_MAX_BYTES } from '../../src/core/page-size-policy.ts';
+import { claimWorktree } from '../../src/core/persistence/ownership.ts';
+import { registerLocalWriter } from '../../src/core/persistence/identity.ts';
+import { importManagedFile } from '../../src/core/persistence/import-mutations.ts';
+import { submitPageMutation } from '../../src/core/persistence/page-mutations.ts';
+import { materializedSnapshot } from '../../src/core/persistence/segmented-apply.ts';
+import { disposePersistenceConsumer } from '../../src/core/persistence/service.ts';
+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';
+import { withEnv } from '../helpers/with-env.ts';
+import { conversationBody, conversationPage } from '../helpers/conversation-page.ts';
+
+const home = mkdtempSync(join(tmpdir(), 'gbrain-segmented-withdrawn-delete-'));
+const engines: BrainEngine[] = [];
+let closePostgres: (() => Promise<void>) | undefined;
+const env = { GBRAIN_HOME: home, OPENAI_API_KEY: undefined, VOYAGE_API_KEY: undefined, ANTHROPIC_API_KEY: undefined };
+const logger = { info() {}, warn() {}, error() {} };
+const SLUG = 'notes/fenced-ledger';
+const WITHDRAWN = 'Door code is 5512';
+
+const ROW = (n: number, claim: string) => '| ' + n + ' | ' + claim + ' | fact | 1.0 | world | medium | 2026-01-01 | | chat | |';
+const FENCE = (rows: string[]) => '<!--- gbrain:facts:begin -->\n| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |\n'
+ + '|---|-------|------|------------|------------|------------|------------|-------------|--------|---------|\n' + rows.join('\n') + '\n<!--- gbrain:facts:end -->';
+// About 2 MiB: segmented with the switch on, inline (under the 24 MiB ceiling) with it off.
+const FENCED = '---\ntitle: Fenced ledger\ntype: note\n---\n\n# Fenced ledger\n\n' + FENCE([ROW(1, WITHDRAWN), ROW(2, 'Likes green tea')]) + '\n\n'
+ + conversationBody(2 * 1024 * 1024, { seed: 5 });
+
+beforeAll(async () => {
+ const lite = new PGLiteEngine(); await lite.connect({}); await lite.initSchema(); engines.push(lite);
+ if (process.env.DATABASE_URL) { const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL); engines.push(pg.engine); closePostgres = pg.close; }
+}, 120_000);
+
+afterAll(async () => {
+ await withEnv(env, async () => {
+ for (const engine of engines) { await disposePersistenceConsumer(engine); await engine.disconnect(); }
+ await closePostgres?.();
+ });
+ rmSync(home, { recursive: true, force: true });
+});
+
+interface Fixture { sourceId: string; root: string; ctx: OperationContext }
+
+async function managedSource(engine: BrainEngine, segmented: boolean): Promise<Fixture> {
+ await disposePersistenceConsumer(engine);
+ await engine.setConfig('pages.segmented_storage', segmented ? 'on' : 'off');
+ const root = join(home, 'src-' + randomUUID().slice(0, 8));
+ mkdirSync(join(root, 'notes'), { recursive: true });
+ execFileSync('git', ['init', '-q'], { cwd: root });
+ const sourceId = 'ledger-' + randomUUID().slice(0, 8);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ await engine.executeRaw("INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,'{}')", [sourceId, root]);
+ await registerLocalWriter(engine, 'cli');
+ await claimWorktree(engine, sourceId, root);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ return { sourceId, root, ctx: { engine, sourceId, remote: false, config: { engine: engine.kind, embedding_disabled: true } as never, dryRun: false, logger } as OperationContext };
+}
+
+async function importPage(engine: BrainEngine, f: Fixture, content: string): Promise<string> {
+ writeFileSync(join(f.root, SLUG + '.md'), content);
+ expect(await importManagedFile(engine, join(f.root, SLUG + '.md'), SLUG + '.md', { sourceId: f.sourceId, noEmbed: true })).toMatchObject({ status: 'imported' });
+ await disposePersistenceConsumer(engine);
+ const [row] = await engine.executeRaw<{ body_storage: string }>('SELECT body_storage FROM pages WHERE source_id=$1 AND slug=$2', [f.sourceId, SLUG]);
+ return row!.body_storage;
+}
+
+const withdraw = (engine: BrainEngine, f: Fixture, subject: string, claim = WITHDRAWN) => engine.executeRaw(
+ "INSERT INTO fact_withdrawals (source_id, visibility, subject, fact_hash) VALUES ($1, 'world', $2, gbrain_fact_fingerprint($3)) ON CONFLICT DO NOTHING", [f.sourceId, subject, claim]);
+
+async function deletion(engine: BrainEngine, f: Fixture, extra: Record<string, unknown> = {}): Promise<string> {
+ const snapshot = await engine.readPageSnapshot(SLUG, { sourceId: f.sourceId, includeDeleted: true });
+ try {
+ const result = await submitPageMutation(f.ctx, { operation: 'delete_page', params: { slug: SLUG, expected_revision: snapshot!.revision, request_id: randomUUID(), ...extra } }) as { status?: string };
+ return String(result.status);
+ } catch (error) {
+ return 'refused ' + (error as { code?: string }).code;
+ } finally {
+ await disposePersistenceConsumer(engine);
+ }
+}
+
+test('a segmented page whose own facts row is withdrawn deletes and purges as its inline twin does, and reads back the inline body', async () => withEnv(env, async () => {
+ for (const engine of engines) {
+ const seen: Record<string, unknown> = {};
+ for (const subject of ['slug', '*']) {
+ const bodies: Record<string, string> = {};
+ for (const storage of ['segmented', 'inline'] as const) {
+ const f = await managedSource(engine, storage === 'segmented');
+ const purged = await managedSource(engine, storage === 'segmented');
+ const stored = [await importPage(engine, f, FENCED), await importPage(engine, purged, FENCED)];
+ for (const fixture of [f, purged]) await withdraw(engine, fixture, subject === 'slug' ? SLUG : '*');
+ const body = (await materializedSnapshot(engine, await engine.readPageSnapshot(SLUG, { sourceId: f.sourceId })))!.page.compiled_truth;
+ bodies[storage] = createHash('sha256').update(body).digest('hex');
+ seen[subject + ':' + storage] = { stored, struck: body.includes('~~' + WITHDRAWN + '~~'), deleted: await deletion(engine, f), purged: await deletion(engine, purged, { purge: true }) };
+ }
+ seen[subject + ':same_body'] = bodies.segmented === bodies.inline;
+ }
+ const twin = (storage: string) => ({ stored: [storage, storage], struck: true, deleted: 'soft_deleted', purged: 'purged' });
+ expect({ engine: engine.kind, seen }).toEqual({ engine: engine.kind, seen: {
+ 'slug:segmented': twin('segmented'), 'slug:inline': twin('inline'), 'slug:same_body': true,
+ '*:segmented': twin('segmented'), '*:inline': twin('inline'), '*:same_body': true } });
+ }
+}), 900_000);
+
+test('a segmented page over the single-string ceiling deletes under a withdrawal ledger that applies to it', async () => withEnv(env, async () => {
+ const huge = conversationPage(PAGE_MAX_BYTES + 512 * 1024, { seed: 98, needles: [{ at: 0.5, word: 'midpointmarker' }] });
+ for (const engine of engines) {
+ const f = await managedSource(engine, true);
+ expect(await importPage(engine, f, huge)).toBe('segmented');
+ await withdraw(engine, f, '*');
+ await withdraw(engine, f, SLUG, 'Some other withdrawn claim');
+ expect({ engine: engine.kind, outcome: await deletion(engine, f) }).toEqual({ engine: engine.kind, outcome: 'soft_deleted' });
+ }
+}), 900_000);
diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txt
index c988f9609f..18a8a41c7f 100644
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@ -122,6 +122,7 @@ test/large-pages/segmented-switch.test.ts
test/large-pages/segmented-think-compile-leads.serial.test.ts
test/large-pages/segmented-timeline-retract-versions.test.ts
test/large-pages/segmented-versions.test.ts
+test/large-pages/segmented-withdrawn-fence-delete.test.ts
test/large-pages/v249-master-reader-compat.test.ts
test/link-cross-source.test.ts
test/link-preparation-shared-index.test.ts