Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix: JIT-off reads stay unscoped (jitOffRead); statistics gate uses autovacuum's 50 + 10% threshold; goldens for the JIT-off transactions

time-attack6197b7121356
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 7666341d1c..0605c4cf26 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -32,7 +32,7 @@ Wave 6 of the efficiency work. Nothing changes in search results, chunk boundari
| unchanged re-import, 3,700 pages | PGLite 5k | 23.7 s | 19.7 s |
| chunk pass, 2,000 CJK prose pages | in-process | 1,214 ms | 180 ms |
-- **Write passes.** Import, sync and reindex refreshed the planner statistics after every pass that changed a page: on Postgres `ANALYZE pages(...)` plus `ANALYZE content_chunks(...)` (about 650 ms at 50k), on PGLite a full `ANALYZE` of every table. A pass that changed fewer than max(500, 10% of pages) pages now leaves statistics that already exist alone; PGLite still analyzes any hot table its row deltas mark stale. Larger passes and brains without statistics refresh as before.
+- **Write passes.** Import, sync and reindex refreshed the planner statistics after every pass that changed a page: on Postgres `ANALYZE pages(...)` plus `ANALYZE content_chunks(...)` (about 650 ms at 50k), on PGLite a full `ANALYZE` of every table. A pass that changed fewer than 50 + 10% of pages pages now leaves statistics that already exist alone; PGLite still analyzes any hot table its row deltas mark stale. Larger passes and brains without statistics refresh as before.
- **PGLite queue upkeep.** Every short-lived CLI process vacuumed all five persistence queue tables on its first tick (0.6 s per sync at 5k). A queue table is now vacuumed once its heap grows more than 10% past the size its last VACUUM or ANALYZE recorded.
- **Edits.** `gbrain import` and a classic sync now keep every stored chunk row identical to its new chunk in place, as `put_page` and managed sync already did, `--no-embed` included: unchanged chunks keep their vectors, and `embed --stale` re-embeds only the chunks that changed. A never-embedded row stays in place under a chunk that gets no vector either. A one-paragraph edit now deletes and inserts one chunk row instead of every row of the page.
- **Postgres JIT.** Search's backlink count (about 370 candidate ids under query expansion) and `doctor`'s three health statements crossed `jit_above_cost` at 50k, and LLVM compilation was most of their time (backlink count 170 → 20 ms). They now run with JIT off, like the search statements.
diff --git a/docs/architecture/key-files/core-search-1.md b/docs/architecture/key-files/core-search-1.md
index 0628dab45f..ebd17431c7 100644
--- a/docs/architecture/key-files/core-search-1.md
+++ b/docs/architecture/key-files/core-search-1.md
@@ -58,7 +58,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/search/projection-readiness.ts` — EXISTS probe for unsealed text revisions in the visible scope: ready, projection_pending or unknown. Cached per scope by DB generation (page clock, `pages` filenode, archive flags, no open transaction); `GBRAIN_PROJECTION_READINESS_CACHE=0` disables.
-- `src/core/search/projection-statistics.ts` — current-projection expression statistics, strict migration postconditions and owner-authorized batch refresh. Migration 160 verifies object identity and populated samples before advancing the ledger, distinguishing empty tables and row-security-hidden statistics. Import, sync, reindex and drained recovery refresh outside page locks; failures preserve completed writes and give a maintenance hint. A pass that changed fewer pages than `plannerStatsThreshold` (max(500, 10% of pages)) leaves the statistics alone once they exist (the projection statistic, and on Postgres `pages.deleted_at` and `content_chunks.model`), and PGLite then analyzes only the hot tables its row deltas mark stale. On Postgres the refresh also samples the page columns search filters read (`SEARCH_PAGE_STATISTICS_SQL`) and, behind a savepoint so a held lock skips only that step, `content_chunks(model, modality, page_id)`; `refreshChunkStatistics` runs the chunk step alone once at the end of an embed drain that embedded: without them the vector candidate statement sorts every eligible chunk instead of walking the HNSW index (`test/e2e/vector-chunk-statistics-postgres.test.ts`). Migration 161 adds the scoped pending-projection index.
+- `src/core/search/projection-statistics.ts` — current-projection expression statistics, strict migration postconditions and owner-authorized batch refresh. Migration 160 verifies object identity and populated samples before advancing the ledger, distinguishing empty tables and row-security-hidden statistics. Import, sync, reindex and drained recovery refresh outside page locks; failures preserve completed writes and give a maintenance hint. A pass that changed fewer than 50 + 10% of the sampled pages leaves the statistics alone once they exist (the projection statistic, and on Postgres `pages.deleted_at` and `content_chunks.model`), and PGLite then analyzes only the hot tables its row deltas mark stale. On Postgres the refresh also samples the page columns search filters read (`SEARCH_PAGE_STATISTICS_SQL`) and, behind a savepoint so a held lock skips only that step, `content_chunks(model, modality, page_id)`; `refreshChunkStatistics` runs the chunk step alone once at the end of an embed drain that embedded: without them the vector candidate statement sorts every eligible chunk instead of walking the HNSW index (`test/e2e/vector-chunk-statistics-postgres.test.ts`). Migration 161 adds the scoped pending-projection index.
- `src/core/search/query-cache.ts` — stored semantic-cache data and maintenance remain, but `semanticResultCacheAvailable()` is false. `hybridSearchCached` bypasses both result lookup and writes regardless of configuration or `useCache`, and skips the key/config setup (merged config, cache config, intent-pattern state) so the wrapper adds no engine round-trips; request-local query embeddings still work. Search metadata, cache_stats and the mode dashboard report effective caching as disabled. Historical hit counts and search_telemetry remain intact. Restoration requires complete response-dependency provenance.
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index a0ee317758..d4b256e89f 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -21,7 +21,7 @@ src/core/import-file.ts 2202 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 340 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
src/core/pglite-engine.ts 3002 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)
-src/core/postgres-engine.ts 2988 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); +5 GBRA-75: getBacklinkCounts and getHealth statements run JIT-off (withScopedReadTransaction jitOff; engine methods cannot move)
+src/core/postgres-engine.ts 2992 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)
src/core/search/hybrid.ts 1615 ratchet +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
src/core/types.ts 2239 ratchet +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)
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/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index b9f444dbae..8004a033d2 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -358,7 +358,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }
{ since: '0.60.132.0', text: `The repair model (\`models.fence_repair\`, or \`models.content_repair\` for slug conflicts) now also classifies the cases the deterministic rules mark ambiguous, under the same \`fences.repair.max_usd_per_page\` ($0.30) and \`fences.repair.max_usd_per_day\` ($1.00) caps and one shared daily ledger: whether the lines after an unclosed fence on a world-visible page are prose or table rows, and whether two pages a \`slug:\` line ties together are the same thing. The model chooses among coded answers and never writes text: a world-page close that would expose hidden lines waits for your hash-bound approval (\`tail_exposure_approval\`), a page merge is recommended, never executed (\`merge_recommended\` names the canonical page), and an undecided case is \`needs_human\`. ${CONTENT_REPAIR_MEASURED} \`gbrain config set fences.repair.llm false\` turns the model tier off for the whole lane; \`--no-llm\` keeps one run to the free tiers.` },
{ since: '0.60.132.0', text: '`gbrain sync unblock --source <id> --apply` now writes: for every held file the content-repair lane clears (`invalid_fence` and `frontmatter_slug_conflict`) it runs the lane on exactly those paths as one bounded hash-bound apply under the `fences.repair` caps, prints a receipt per file and schedules the re-screen, and reports each path as `repaired`, `held`, `needs_human` or `skipped` with the reason and its next step; a hold whose stored state waits on a person, your spend decision or the owner host is listed, never retried. Before this release unblock refused every repair-class hold. `--no-llm` keeps the repairs to the free tiers; `--no-repair` restores the refuse-only behaviour. `gbrain sync status` now reports a fence hold the lane marked manual or paid, and a recommended merge, as `needs_human` with the paragraph in `human_reason`.' },
{ since: '0.60.134.0', text: 'A `put_page` edit (and a managed sync of an edited file) keeps the unchanged chunks and their vectors and re-embeds only the chunks that changed. `gbrain serve` answers the MCP handshake before it starts its IPC socket, persistence consumer and startup sweep. Scoped vector search counts a source\'s chunks instead of inferring them from its share of pages, and a source of up to 120,000 chunks falls back to an exact scan when the index comes back short.' },
- { since: '0.60.137.0', text: '`gbrain import` and a classic sync of an edited file keep the unchanged chunk rows and their vectors, `--no-embed` included, so `embed --stale` re-embeds only the chunks that changed. An import, sync or reindex that changed fewer than max(500, 10% of pages) pages no longer re-runs ANALYZE when planner statistics already exist. Migration v225 drops `idx_chunks_embedding_null`, a duplicate of `content_chunks_stale_idx`.' },
+ { since: '0.60.137.0', text: '`gbrain import` and a classic sync of an edited file keep the unchanged chunk rows and their vectors, `--no-embed` included, so `embed --stale` re-embeds only the chunks that changed. An import, sync or reindex that changed fewer than 50 + 10% of pages pages no longer re-runs ANALYZE when planner statistics already exist. Migration v225 drops `idx_chunks_embedding_null`, a duplicate of `content_chunks_stale_idx`.' },
// E5.4 HNSW scale wave (GBRA-60).
{ since: '0.60.135.0', text: 'Vector search that reaches the bounded candidate pool (a visibility scope, a type or date filter, or a source too large for the exact scope scan) now scans up to 20,000 index entries before it settles (it stopped at 2,000), so it returns the scope\'s true nearest pages instead of the first few hundred it reached: on 1M chunks with real embeddings, recall@50 under a random 10% visibility scope rose from 0.77 to 0.97, for about 15 to 35 ms more per such search. Unscoped search and small source scopes return the same results.' },
{ since: '0.60.135.0', text: 'On Postgres, import, sync, reindex and every embed drain that embedded something now finish with a bounded ANALYZE (30 s statement, 2 s lock timeout) of `content_chunks(model, modality, page_id)` and the page columns search filters read. Without those statistics, vector search on a freshly loaded brain of 1M chunks or more sorted every candidate: scoped searches took 0.5 to 8 s, and many hit the 8 s budget and fell back to keyword-only results (`vector_candidates_incomplete`) until autovacuum ran.' },
diff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.ts
index 568bf5e5ba..11b9964f31 100644
--- a/src/core/postgres-engine.ts
+++ b/src/core/postgres-engine.ts
@@ -353,6 +353,11 @@ export class PostgresEngine implements BrainEngine {
});
}
+ /** An unscoped read in its own transaction with JIT off (search-settings.ts); a savepoint inside a caller's transaction. */
+ private jitOffRead<T>(callback: (tx: ReturnType<typeof postgres>) => Promise<T>): Promise<T> {
+ return this.transaction(engine => withSearchJitOff((engine as PostgresEngine).sql, this._pageTransaction, () => callback((engine as PostgresEngine).sql)));
+ }
+
// Lifecycle
async connect(config: EngineConfig & { poolSize?: number; parentConnectionManager?: ConnectionManager }): Promise<void> {
this.vectorIterativeScan = undefined;
@@ -1691,8 +1696,8 @@ export class PostgresEngine implements BrainEngine {
async getBacklinkCounts(pageIds: number[], opts?: PageReadScope): Promise<Map<number, number>> {
// JIT off (search-settings.ts): ~370 expanded-query ids cross jit_above_cost; at 50k compiling was ~140 of ~170 ms.
- return !pageIds.length ? new Map() : this.withScopedReadTransaction(undefined, undefined, tx => readBacklinkCounts(async (query, params) =>
- Array.from(await tx.unsafe(query, params as never, { prepare: true })) as never, pageIds, opts), { alwaysTransaction: true, jitOff: true });
+ return !pageIds.length ? new Map() : this.jitOffRead(tx => readBacklinkCounts(async (query, params) =>
+ Array.from(await tx.unsafe(query, params as never, { prepare: true })) as never, pageIds, opts));
}
async getAdjacencyBoosts(pageIds: number[], opts?: PageReadScope): Promise<Map<number, import('./types.ts').AdjacencyRow>> {
@@ -2446,8 +2451,7 @@ export class PostgresEngine implements BrainEngine {
async getHealth(opts?: { sourceId?: string; sourceIds?: string[] }): Promise<BrainHealth> {
// Each statement in its own JIT-off transaction (at 50k two spent ~0.5 of ~0.56 s compiling); the deps stay on the pool.
- const exec: SqlExecutor = { ...this.engineSql, run: (fragment, runOpts) => this.withScopedReadTransaction(undefined, undefined,
- tx => this.engineSqlOn(tx).run(fragment, runOpts), { alwaysTransaction: true, jitOff: true }) };
+ const exec: SqlExecutor = { ...this.engineSql, run: (fragment, runOpts) => this.jitOffRead(tx => this.engineSqlOn(tx).run(fragment, runOpts)) };
return healthImpl.getHealth(unscopedExecutor(exec, 'health: unscoped on master (EO4 inventory)'), opts, {
embeddingColumn: async () => (await resolveActiveEmbeddingColumnFromEngine(this, { fallbackToLegacy: true })).name,
countStalePagesForExtraction: (o) => this.countStalePagesForExtraction(o),
diff --git a/src/core/search/projection-statistics.ts b/src/core/search/projection-statistics.ts
index 0dc886969d..c1e435033a 100644
--- a/src/core/search/projection-statistics.ts
+++ b/src/core/search/projection-statistics.ts
@@ -1,5 +1,5 @@
import type { BrainEngine } from '../engine.ts';
-import { beginFullAnalyze, maybeRefreshPlannerStats, plannerAutoAnalyzeEnabled, plannerStatsThreshold } from '../planner-stats.ts';
+import { beginFullAnalyze, maybeRefreshPlannerStats, plannerAutoAnalyzeEnabled } from '../planner-stats.ts';
export const PROJECTION_STATISTICS_NAME = 'pages_text_projection_current_stats';
@@ -108,10 +108,11 @@ export async function withChunkStatisticsRefresh<T>(engine: BrainEngine, changed
}
/**
- * Whether a write pass that changed `changedPages` pages can leave the planner statistics alone: it changed fewer
- * pages than the planner-statistics threshold (max(500, 10% of pages), autovacuum's scale) and the statistics this
- * refresh collects already exist. Such a pass barely moves them, and the refresh cost 170 ms per one-page sync at
- * 50k pages on Postgres and a full ANALYZE of every table on PGLite.
+ * Whether a write pass that changed `changedPages` pages can leave the planner statistics alone: pages were sampled
+ * with rows, the statistics this refresh collects exist, and the pass changed fewer than 50 + 10% of the sampled
+ * pages (autovacuum's analyze threshold, as the projection-recovery debt in page-state/projections.ts). Such a pass
+ * barely moves them, and the refresh cost ~650 ms per one-page sync at 50k pages on Postgres and a full ANALYZE of
+ * every table on PGLite.
*/
async function statisticsStillCurrent(engine: BrainEngine, changedPages: number): Promise<boolean> {
if (!Number.isFinite(changedPages)) return false;
@@ -120,7 +121,8 @@ async function statisticsStillCurrent(engine: BrainEngine, changedPages: number)
$1::text <> 'postgres' OR (SELECT count(*) FROM pg_stats s WHERE s.schemaname = current_schema()
AND ((s.tablename = 'pages' AND s.attname = 'deleted_at') OR (s.tablename = 'content_chunks' AND s.attname = 'model'))) = 2 AS columns
FROM pg_class c WHERE c.oid = 'pages'::regclass`, [engine.kind]);
- if (!state?.columns || changedPages >= plannerStatsThreshold(Number(state.reltuples))) return false;
+ const rows = Number(state?.reltuples ?? -1);
+ if (!state?.columns || rows <= 0 || changedPages >= 50 + 0.1 * rows) return false;
return verifyProjectionStatistics(engine).then(() => true, () => false);
}
diff --git a/test/fixtures/goldens/postgres-engine-gauge/sequence.json b/test/fixtures/goldens/postgres-engine-gauge/sequence.json
index e686a69e03..fe533ca1cb 100644
--- a/test/fixtures/goldens/postgres-engine-gauge/sequence.json
+++ b/test/fixtures/goldens/postgres-engine-gauge/sequence.json
@@ -128,9 +128,9 @@
"prepare": null,
"tracked": {
"direct": 1,
- "raw": 3,
+ "raw": 2,
"reserved": 1,
- "tx": 1
+ "tx": 2
}
},
"step": "+ getBacklinkCounts in flight (executeRaw-backed, counted raw)"
diff --git a/test/fixtures/goldens/rls-scope-inventory.json b/test/fixtures/goldens/rls-scope-inventory.json
index 5d6f4f0876..9ee8e408aa 100644
--- a/test/fixtures/goldens/rls-scope-inventory.json
+++ b/test/fixtures/goldens/rls-scope-inventory.json
@@ -998,9 +998,10 @@
},
"getHealth#default": {
"flagOffLanes": [
- "pool"
+ "pool",
+ "tx"
],
- "flagOffOpensTransaction": false,
+ "flagOffOpensTransaction": true,
"flagOn": "scoped",
"flagOnLanes": [
"pool",
@@ -3461,6 +3462,7 @@
"insertFacts": "none",
"invalidateContentDriftEmbeddings": "none",
"invalidateStaleSignatureEmbeddings": "none",
+ "jitOffRead": "none",
"listActiveTakesForPages": "none",
"listAllPageRefs": "none",
"listAllSources": "none",
diff --git a/test/projection-statistics.test.ts b/test/projection-statistics.test.ts
index 84a3b3e0d3..6630b44c6f 100644
--- a/test/projection-statistics.test.ts
+++ b/test/projection-statistics.test.ts
@@ -73,7 +73,7 @@ describe('projection statistics refresh after a write pass', () => {
const planRows = async (db: PGlite) => (await db.query<{ 'QUERY PLAN': Array<{ Plan: { 'Plan Rows': number } }> }>(
`EXPLAIN (FORMAT JSON) SELECT * FROM pages p WHERE ${currentTextProjectionFilter('p')}`)).rows[0]['QUERY PLAN'][0].Plan['Plan Rows'];
- test('a pass below max(500, 10% of pages) keeps collected statistics; a larger pass or uncollected statistics refresh', async () => {
+ test('a pass below 50 + 10% of pages keeps collected statistics; a larger pass or uncollected statistics refresh', async () => {
const db = new PGlite();
try {
const engine = fixtureEngine(db);
@@ -86,7 +86,9 @@ describe('projection statistics refresh after a write pass', () => {
expect(stale).toBeGreaterThan(9001);
expect(await refreshProjectionStatistics(engine, 999)).toBe(true);
expect(await planRows(db)).toBe(stale);
- expect(await refreshProjectionStatistics(engine, 1000)).toBe(true);
+ expect(await refreshProjectionStatistics(engine, 1049)).toBe(true);
+ expect(await planRows(db)).toBe(stale);
+ expect(await refreshProjectionStatistics(engine, 1050)).toBe(true);
expect(await planRows(db)).toBe(9001);
await db.exec(`DROP STATISTICS pages_text_projection_current_stats;
CREATE STATISTICS pages_text_projection_current_stats ON ((text_projection_revision = knowledge_revision)) FROM pages;`);