Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Guard Postgres search against absent planner statistics (GBRA-75 wave 7)

time-attack8fffb75ad8f1
diff --git a/docs/architecture/key-files/core-search-1.md b/docs/architecture/key-files/core-search-1.md
index ebd17431c7..c30d607cb9 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 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/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, every `SEARCH_STATISTICS_COLUMNS` column: `missingSearchStatistics`), 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`). Absent search statistics (pg_upgrade, a deleted pg_statistic; 50-60 s searches at 5k pages) get `ensureSearchStatistics`: PostgresEngine runs it once per engine in the background on its first pool search (never awaited; disconnect waits), and doctor `planner_stats_stale` plus `repair planner-stats` report and apply the same refresh (`test/search-statistics-guard.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/docs/architecture/key-files/core-utilities-1.md b/docs/architecture/key-files/core-utilities-1.md
index 2637bae08f..9ae08af818 100644
--- a/docs/architecture/key-files/core-utilities-1.md
+++ b/docs/architecture/key-files/core-utilities-1.md
@@ -12,7 +12,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/brain-score-recommendations.ts` — pure data layer consumed by both `gbrain doctor --remediation-plan` / `--remediate` and `gbrain features`. Extraction-watermark staleness produces source-scoped `extract.stale` against database pages, including DB-only pages without a checkout; it does not imply a filesystem sync or block embedding on one. `RecommendationContext.staleExtractionBlocked` (probed by `staleExtractionBlocked()` in `remediation/context.ts`, shared with autopilot) withholds `extract.stale` and classifies `links_extraction_lag` as blocked while the remediated source, or any source with stale pages in an all-source sweep, cannot load its active schema pack, so no dispatch fails every cycle. `computeRecommendations(checks, opts)` returns `Remediation[]` with stable `id`, content-hash `idempotency_key`, `severity`, `est_seconds`, `est_usd_cost`, `depends_on` (references stable ids, not check names — so plan order is reproducible). `classifyChecks(report)` triages every doctor check three-state into `remediable | human_only | blocked` (`human_only` covers RLS warnings and other human-judgment gates; `blocked` covers dependency chains where a parent check failed). `maxReachableScore(checks)` computes the ceiling for empty/under-configured brains (no entity pages → graph_coverage caps at 70; no embedding key → embedding_coverage caps at 60). Cost estimates pull from `anthropic-pricing.ts` (synthesize/patterns/consolidate) and `embedding-pricing.ts` (embed jobs). Pinned by `test/brain-score-recommendations.test.ts` (~27 cases incl. determinism, content-hash idempotency, DB-backed checkpoint provenance, three-state triage).
- `src/core/orphan-policy.ts` — the shared orphan-reporting policy (`gbrain orphans`, doctor's orphan ratio, `get_health`): convention constants plus per-brain `orphans.exclude_prefixes` / `orphans.exclude_slugs` overrides. Two renderers over the same constants: `shouldExcludeFromOrphanReporting(slug, overrides, meta)` (TypeScript) and `orphanExclusionSql(alias, overrides)` (a never-NULL SQL predicate; every list value is a bound parameter, only the identifier-checked alias is spliced; regexes are spelled for Postgres's engine: ASCII digits, `.` stops at line terminators). Quarantine stays outside the SQL predicate. Parity pinned on a generated slug/type corpus by `test/orphan-policy-sql-parity.test.ts` and its Postgres arm in `test/e2e/engine-sql-health-parity.test.ts`.
-- `src/core/planner-stats.ts` + `src/core/planner-stats-schema.ts` — F4b row-delta ANALYZE for PGLite (no autovacuum; `n_mod_since_analyze` is never populated there). Migration f4_planner_stats (`sqlFor.pglite` only; a Postgres no-op) adds `planner_stats_deltas` / `planner_stats_state` and AFTER STATEMENT transition-table triggers on pages, links, facts, takes, content_chunks and timeline_entries, so modification counts commit or roll back with the data and survive restarts. `maybeRefreshPlannerStats(engine, reason)` ANALYZEs tables whose pending count exceeds max(500, 10% of reltuples) (or that have rows but no pg_stats) and publishes a watermark read before the ANALYZE, so a concurrent modification stays pending; checks are throttled to one per 2 s per engine. Call sites: PGLite planner-sensitive reads (`beforePlannerRead`, deferring a table whose last ANALYZE exceeded `planner.first_read_budget_ms`), import and managed sync every `import.analyze_every_pages`, stale link drains of at least `LINK_DRAIN_ANALYZE_MIN_STALE` (500) pages through `plannerStatsForLinkDrain` (before the first page, then on the same cadence; `link_transitions` and `link_relationships`, which carry no deltas, whenever `links` is analyzed), the cycle after extract_facts, the consumer idle tick, and `refreshProjectionStatistics` (full ANALYZE publishes every watermark). `planner.auto_analyze=false` / `GBRAIN_PLANNER_AUTO_ANALYZE=0` disables them all. Doctor `planner_stats_stale` (Postgres: `pg_stat_user_tables`) and repair kind `planner-stats` keep working. Guide: `docs/guides/planner-stats.md`. Tests: `test/planner-stats*.test.ts` (`planner-stats-link-drain.test.ts` EXPLAINs the drain's snapshot read), `test/e2e/planner-stats-postgres.test.ts`.
+- `src/core/planner-stats.ts` + `src/core/planner-stats-schema.ts` — F4b row-delta ANALYZE for PGLite (no autovacuum). Migration f4_planner_stats (`sqlFor.pglite` only; a Postgres no-op) adds `planner_stats_deltas` / `planner_stats_state` and AFTER STATEMENT transition-table triggers on pages, links, facts, takes, content_chunks and timeline_entries, so modification counts commit or roll back with the data and survive restarts. `maybeRefreshPlannerStats(engine, reason)` ANALYZEs tables whose pending count exceeds max(500, 10% of reltuples) (or that have rows but no pg_stats) and publishes a watermark read before the ANALYZE, so a concurrent modification stays pending; checks are throttled to one per 2 s per engine. Call sites: PGLite planner-sensitive reads (`beforePlannerRead`, deferring a table whose last ANALYZE exceeded `planner.first_read_budget_ms`), import and managed sync every `import.analyze_every_pages`, stale link drains of at least `LINK_DRAIN_ANALYZE_MIN_STALE` (500) pages through `plannerStatsForLinkDrain` (before the first page, then on the same cadence; `link_transitions` and `link_relationships`, which carry no deltas, whenever `links` is analyzed), the cycle after extract_facts, the consumer idle tick, and `refreshProjectionStatistics` (full ANALYZE publishes every watermark). `planner.auto_analyze=false` / `GBRAIN_PLANNER_AUTO_ANALYZE=0` disables them all. Doctor `planner_stats_stale` (Postgres: `pg_stat_user_tables` plus absent `missingSearchStatistics`) and repair kind `planner-stats` keep working. Guide: `docs/guides/planner-stats.md`. Tests: `test/planner-stats*.test.ts` (`planner-stats-link-drain.test.ts` EXPLAINs the drain's snapshot read), `test/e2e/planner-stats-postgres.test.ts`.
- `src/core/timeline-grading.ts` — `loadTimelineGradedPredicate(engine)`: which pages the 15-point brain_score timeline component grades (#5828). `engine-sql/health.ts` applies the predicate per page type to the linkable groups; `gradeTimelinePages` (re-exported by `orphan-policy.ts`) keeps the linkable (orphan-policy) pages whose active-pack primitive is `entity` or `temporal` (aliases resolve to the canonical type); undeclared and untyped types, and every page when no pack resolves, stay graded. Labelled "timeline density (entity and event pages)" in doctor and `get_health` output. Pinned by `test/brain-score-timeline-grading.test.ts`.
- `src/core/cjk.ts` — Single source of truth for CJK detection. Exports `CJK_RANGES_REGEX`, `CJK_SLUG_CHARS` (character-class fragment for embedding inside other regexes), `SLUG_WORD_CHARS` + `PAGE_SLUG_SEG` (the shared slug-grammar fragments) and `SLUG_VARIATION_SELECTORS_RE` (the Mn-invisible emoji-VS16 / ideographic-IVS strip that BOTH `sync.ts:slugifySegment` and its twin `link-extraction.ts:normalizeBasename` apply, so the two grammars cannot drift on selectors), `CJK_SENTENCE_DELIMITERS` (`。!?`), `CJK_CLAUSE_DELIMITERS` (`;:,、`), `CJK_DENSITY_THRESHOLD = 0.30`, `hasCJK(s)`, `isCJKDominant(s)` (the ONE density test: CJK chars ≥ 30% of non-whitespace chars), `countCJKAwareWords(s)` (routes through `isCJKDominant` — English docs with one Japanese term stay whitespace-tokenized; Chinese-dominant docs get char-counted), and `escapeLikePattern(s)` (escapes `%`, `_`, `\\` for `ILIKE ... ESCAPE '\\'`). BMP-only ranges (Han / Hiragana / Katakana / Hangul Syllables). Consumers: `expansion.ts`, `sync.ts:slugifySegment`, `operations.ts:validatePageSlug + validateFilename`, `chunkers/recursive.ts:countWords + DELIMITERS + extractTrailingContext` (the overlap extractor branches on `isCJKDominant` so it counts the same unit `countWords` does), `pglite-engine.ts:searchKeyword + searchKeywordChunks`.
diff --git a/docs/guides/planner-stats.md b/docs/guides/planner-stats.md
index 341ecb720d..e84f2b9220 100644
--- a/docs/guides/planner-stats.md
+++ b/docs/guides/planner-stats.md
@@ -47,6 +47,20 @@ when a table is over the same threshold and neither ANALYZE nor autoanalyze ran
in the last hour; the repair runs each ANALYZE with a 60 s statement and 2 s
lock timeout.
+Postgres can also lose the statistics outright: `pg_upgrade` carries none and
+resets the modification counters, so autovacuum never collects them again
+until 10% of a table changes. Without the page columns search filters read,
+search plans as nested loops over every page (50-60 s per search at 5,000
+pages instead of 0.5 s). gbrain guards this two ways, both through the same
+refresh as import and sync (`ANALYZE pages(...)` and
+`ANALYZE content_chunks(model, modality, page_id)`, 30 s bounded):
+
+- The first search of each process checks in the background and collects them
+ when the database role owns the tables. The search does not wait for it.
+- `planner_stats_stale` warns with the absent columns, and
+ `gbrain repair planner-stats --apply` collects them (run it as the table
+ owner when the brain's role is not).
+
## Settings and opt-out
| Setting | Default | Effect |
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index d4b256e89f..35da0cd366 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 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/postgres-engine.ts 2995 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)
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/commands/doctor/checks/planner-stats.ts b/src/commands/doctor/checks/planner-stats.ts
index bd82e4f3b5..42bf72e5ae 100644
--- a/src/commands/doctor/checks/planner-stats.ts
+++ b/src/commands/doctor/checks/planner-stats.ts
@@ -10,9 +10,18 @@
* warns only when neither ANALYZE nor autoanalyze ran in the last hour. Both
* name each table and the fix. Reports even when `planner.auto_analyze` is
* off.
+ *
+ * Postgres also reports the search statistics `missingSearchStatistics`
+ * finds absent (projection-statistics.ts, the test the write-pass skip and the
+ * search guard use): after pg_upgrade or a deleted pg_statistic autovacuum
+ * never collects them, and search plans as nested loops (50-60 s at 5,000
+ * pages). The fix runs the same refresh through `gbrain repair planner-stats
+ * --apply`; a role that may not ANALYZE gets it as a host-operator step.
*/
import { plannerAutoAnalyzeEnabled, PLANNER_STATS_REPAIR_COMMAND, readPlannerTableStates } from '../../../core/planner-stats.ts';
+import { canAnalyzePages, missingSearchStatistics } from '../../../core/search/projection-statistics.ts';
import type { Check } from '../../doctor.ts';
+import { doctorVerify } from '../check-fix.ts';
import { connectedEngine, type DoctorContext, type DoctorEntry } from '../context.ts';
async function runPlannerStats(ctx: DoctorContext): Promise<Check[]> {
@@ -28,11 +37,23 @@ async function runPlannerStats(ctx: DoctorContext): Promise<Check[]> {
}
const autoAnalyze = engine.kind === 'pglite' ? await plannerAutoAnalyzeEnabled(engine) : null;
const stale = tables.filter(t => t.stale);
- const details = { engine: engine.kind, auto_analyze: autoAnalyze, checked: tables.map(t => t.table), stale, fix: PLANNER_STATS_REPAIR_COMMAND };
- if (stale.length === 0) {
+ const missing = await missingSearchStatistics(engine);
+ const details = { engine: engine.kind, auto_analyze: autoAnalyze, checked: tables.map(t => t.table), stale, missing_search_statistics: missing, fix: PLANNER_STATS_REPAIR_COMMAND };
+ if (stale.length === 0 && missing.length === 0) {
checks.push({ name: 'planner_stats_stale', status: 'ok', message: `Planner statistics are fresh on ${tables.length} hot tables.`, details });
return checks;
}
+ if (missing.length > 0) {
+ const owner = await canAnalyzePages(engine);
+ const why = `Search's planner statistics are absent (${missing.join(', ')}), so search plans as nested loops over every page: `
+ + 'at 5,000 pages a search took 50-60 s instead of 0.5 s. Autovacuum does not restore them after pg_upgrade or a deleted pg_statistic.';
+ const listed = stale.map(t => `${t.table} (${t.pending} rows changed since ANALYZE, threshold ${Math.round(t.threshold)})`).join(', ');
+ checks.push({ name: 'planner_stats_stale', status: 'warn',
+ message: `${why}${listed ? ` Also stale: ${listed}.` : ''} Fix on the brain host: ${PLANNER_STATS_REPAIR_COMMAND}${owner ? '' : ' as the table owner'}.`, details,
+ fix: { argv: PLANNER_STATS_REPAIR_COMMAND.split(' '), consent: [], actor: owner ? 'agent' : 'host_admin', why,
+ verify: doctorVerify('planner_stats_stale'), requires_exclusive: false } });
+ return checks;
+ }
const listed = stale.map(t => `${t.table} (${t.pending} rows changed since ANALYZE, threshold ${Math.round(t.threshold)}${t.has_stats ? '' : ', no statistics'})`).join(', ');
const why = engine.kind === 'pglite'
? 'PGLite has no autovacuum, so search and graph reads may plan as slow nested loops until these tables are analyzed.'
diff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.ts
index 11b9964f31..175c9096ee 100644
--- a/src/core/postgres-engine.ts
+++ b/src/core/postgres-engine.ts
@@ -67,6 +67,7 @@ import { applyChunkEmbeddingIndexPolicy, dropZombieIndexes, supportsHnswIterativ
import { searchIndexWalk, searchVectorPool, readVectorPool, remainingVectorBudget, type VectorPoolAttempt, POOL_MAX_SCAN_TUPLES } from './search/vector-pool.ts';
import { buildVectorSearchStatement, PAGE_SOURCE_STATS_SQL, SCOPE_CHUNKS_SQL, SET_STATEMENT_TIMEOUT_SQL, VECTOR_EXTENSION_VERSION_SQL, vectorScopeLoader, type PageSourceStats, type ScopeChunkCount, type VectorSearchStatement } from './search/vector-statement.ts';
import { withVectorSettings } from './search/vector-settings.ts';
+import { guardSearchStatistics } from './search/projection-statistics.ts';
import {
vectorCastSuffix,
resolveActiveEmbeddingColumnFromEngine,
@@ -937,6 +938,7 @@ export class PostgresEngine implements BrainEngine {
// list_pages etc. see zero breaking changes. A2 two-pass (Layer 7)
// consumes searchKeywordChunks for the raw chunk-grain primitive.
async searchKeyword(query: string, opts?: SearchOpts): Promise<SearchResult[]> {
+ guardSearchStatistics(this, this._pageTransaction);
const limit = clampSearchLimit(opts?.limit, 20, searchLimitCap());
const offset = opts?.offset || 0;
const type = opts?.type;
@@ -1319,6 +1321,7 @@ export class PostgresEngine implements BrainEngine {
}
async searchVector(embedding: Float32Array, opts?: SearchOpts): Promise<SearchResult[]> {
+ guardSearchStatistics(this, this._pageTransaction);
const limit = clampSearchLimit(opts?.limit, 20, searchLimitCap());
if (opts?.limit && opts.limit > searchLimitCap()) {
console.warn(`[gbrain] Warning: search limit clamped from ${opts.limit} to ${searchLimitCap()}`);
diff --git a/src/core/repair/planner-stats.ts b/src/core/repair/planner-stats.ts
index 56853f2c67..67b27343a6 100644
--- a/src/core/repair/planner-stats.ts
+++ b/src/core/repair/planner-stats.ts
@@ -6,11 +6,18 @@
* publishes the table's row-delta watermark). Brain-wide; no journal
* admission and no user data changes, so `--all` and doctor remediation
* include it. Works when `planner.auto_analyze` is off.
+ *
+ * Postgres: when `missingSearchStatistics` finds search's statistics absent,
+ * the plan leads with one `search-statistics` item whose apply is
+ * `refreshProjectionStatistics` (the one refresh path for those columns).
*/
import { PLANNER_STATS_TABLES, type PlannerStatsTable } from '../planner-stats-schema.ts';
import { readPlannerTableStates, repairPlannerTable } from '../planner-stats.ts';
+import { missingSearchStatistics, refreshProjectionStatistics } from '../search/projection-statistics.ts';
import type { RepairHandler, RepairItem } from './core.ts';
+const SEARCH_STATISTICS_ITEM = 'search-statistics';
+
export const plannerStatsRepair: RepairHandler = {
kind: 'planner-stats',
publication: 'projection',
@@ -18,13 +25,17 @@ export const plannerStatsRepair: RepairHandler = {
// ANALYZE is idempotent, so every run plans what is stale now (the cursor never skips a table).
async plan(engine) {
const tables = await readPlannerTableStates(engine) ?? [];
- const items: RepairItem[] = tables.filter(t => t.stale).map(t => ({
+ const missing = await missingSearchStatistics(engine);
+ const search: RepairItem[] = missing.length === 0 ? [] : [{ cursor: { phase: 0, id: 0 }, source_id: '(brain)', slug: SEARCH_STATISTICS_ITEM,
+ chars: 0, action: `collect search statistics (${missing.length} absent: ${missing.join(', ')})` }];
+ const items: RepairItem[] = search.concat(tables.filter(t => t.stale).map(t => ({
cursor: { phase: 0, id: PLANNER_STATS_TABLES.indexOf(t.table) + 1 }, source_id: '(brain)', slug: t.table, chars: 0,
action: `analyze (${t.pending} rows changed since ANALYZE, threshold ${Math.round(t.threshold)}${t.has_stats ? '' : ', no statistics'})`,
- }));
+ })));
return { items, residuals: {} };
},
async apply(ctx, item) {
+ if (item.slug === SEARCH_STATISTICS_ITEM) return refreshProjectionStatistics(ctx.engine);
if (!PLANNER_STATS_TABLES.includes(item.slug as PlannerStatsTable)) return false;
await repairPlannerTable(ctx.engine, item.slug as PlannerStatsTable);
return true;
diff --git a/src/core/search/projection-statistics.ts b/src/core/search/projection-statistics.ts
index 6e62ae0cb5..6754b9c93f 100644
--- a/src/core/search/projection-statistics.ts
+++ b/src/core/search/projection-statistics.ts
@@ -9,7 +9,9 @@ CREATE STATISTICS IF NOT EXISTS ${PROJECTION_STATISTICS_NAME}
ANALYZE pages(text_projection_revision, knowledge_revision);
`;
-export async function verifyProjectionStatistics(engine: Pick<BrainEngine, 'executeRaw'>): Promise<void> {
+type ProjectionStatisticsState = 'collected' | 'undefined' | 'uninspectable' | 'uncollected';
+
+async function readProjectionStatistics(engine: Pick<BrainEngine, 'executeRaw'>): Promise<ProjectionStatisticsState> {
const rows = await engine.executeRaw<{
expression: string;
correct_table: boolean;
@@ -28,17 +30,35 @@ export async function verifyProjectionStatistics(engine: Pick<BrainEngine, 'exec
AND x.expr = pg_get_expr(e.stxexprs, e.stxrelid)
WHERE p.oid = 'pages'::regclass AND e.stxname = $1`, [PROJECTION_STATISTICS_NAME]);
const state = rows[0];
- if (!state || !state.correct_table || state.expression !== '(text_projection_revision = knowledge_revision)') {
+ if (!state || !state.correct_table || state.expression !== '(text_projection_revision = knowledge_revision)') return 'undefined';
+ if (!state.can_inspect) return 'uninspectable';
+ if (Number(state.sampled_rows) < 0 || (Number(state.sampled_rows) > 0 && !state.collected)) return 'uncollected';
+ return 'collected';
+}
+
+export async function verifyProjectionStatistics(engine: Pick<BrainEngine, 'executeRaw'>): Promise<void> {
+ const state = await readProjectionStatistics(engine);
+ if (state === 'undefined') {
throw new Error('Projection planner statistics are missing or have the wrong definition; the schema migration was not verified.');
}
- if (!state.can_inspect) {
+ if (state === 'uninspectable') {
throw new Error('Projection planner statistics cannot be inspected by this database role or its row-security policy; run schema maintenance with an authorized maintenance role.');
}
- if (Number(state.sampled_rows) < 0 || (Number(state.sampled_rows) > 0 && !state.collected)) {
+ if (state === 'uncollected') {
throw new Error('Projection planner statistics have not been collected; run ANALYZE pages(text_projection_revision, knowledge_revision) as the table owner.');
}
}
+/**
+ * The columns the Postgres refresh collects (SEARCH_PAGE_STATISTICS_SQL, CHUNK_STATISTICS_SQL) and the ones
+ * `missingSearchStatistics` requires. Without them search's visibility-filtered statements estimate one page per
+ * source scope and run as pages-by-pages nested loops: at 5,000 pages a search took 50-60 s instead of 0.5 s.
+ */
+export const SEARCH_STATISTICS_COLUMNS = {
+ pages: ['text_projection_revision', 'knowledge_revision', 'deleted_at', 'source_id', 'type', 'slug'],
+ content_chunks: ['model', 'modality', 'page_id'],
+} as const;
+
/**
* The content_chunks columns vector search's candidate statement is estimated
* from: its generation and modality filters (cc.model, cc.modality) and its
@@ -47,7 +67,7 @@ export async function verifyProjectionStatistics(engine: Pick<BrainEngine, 'exec
* walking the HNSW index: at 1M to 2M chunks that runs past the 8 s vector
* budget (docs/eval/hnsw-scale-bench.md, "Statistics states and EXPLAIN").
*/
-export const CHUNK_STATISTICS_SQL = 'ANALYZE content_chunks(model, modality, page_id)';
+export const CHUNK_STATISTICS_SQL = `ANALYZE content_chunks(${SEARCH_STATISTICS_COLUMNS.content_chunks.join(', ')})`;
/**
* The Postgres page refresh: the projection columns plus the page columns
@@ -57,7 +77,7 @@ export const CHUNK_STATISTICS_SQL = 'ANALYZE content_chunks(model, modality, pag
* chunks and a sort, even with content_chunks analyzed. Wide columns
* (frontmatter, compiled_truth) stay out, so the sample stays cheap.
*/
-export const SEARCH_PAGE_STATISTICS_SQL = 'ANALYZE pages(text_projection_revision, knowledge_revision, deleted_at, source_id, type, slug)';
+export const SEARCH_PAGE_STATISTICS_SQL = `ANALYZE pages(${SEARCH_STATISTICS_COLUMNS.pages.join(', ')})`;
const CHUNK_STATISTICS_WARNING = `[search] Chunk planner statistics could not be refreshed (a lock or the 30 s bound). Vector search may skip its index until autovacuum analyzes content_chunks; run ${CHUNK_STATISTICS_SQL} as the table owner to fix it now.`;
@@ -107,6 +127,42 @@ export async function withChunkStatisticsRefresh<T>(engine: BrainEngine, changed
return out;
}
+/** Each SEARCH_STATISTICS_COLUMNS column whose table holds rows but has no pg_stats row ($1 tables, $2 columns). */
+const MISSING_SEARCH_STATISTICS_SQL = `SELECT r.tablename || '.' || r.attname AS col
+ FROM unnest($1::text[], $2::text[]) WITH ORDINALITY AS r(tablename, attname, position)
+ JOIN pg_class t ON t.oid = to_regclass(quote_ident(current_schema()) || '.' || r.tablename)
+ WHERE (t.reltuples > 0 OR (t.reltuples < 0 AND pg_relation_size(t.oid) > 0))
+ AND has_table_privilege(t.oid, 'SELECT') AND NOT row_security_active(t.oid)
+ AND NOT EXISTS (SELECT 1 FROM pg_stats s WHERE s.schemaname = current_schema() AND s.tablename = r.tablename AND s.attname = r.attname)
+ ORDER BY r.position`;
+
+/**
+ * Postgres: the planner statistics search needs that are absent, as `table.column` (plus PROJECTION_STATISTICS_NAME
+ * when the projection statistics are not collected). Empty when every one exists, the tables are empty, or this role
+ * cannot see a table's statistics (pg_stats hides them under row security; that is not absence). Absent
+ * statistics outlive autovacuum after pg_upgrade (it carries no statistics and resets the modification counters) or
+ * a deleted pg_statistic; a restore regains them at autovacuum's next pass. The one test behind the write-pass skip
+ * (`statisticsStillCurrent`), the search guard (`ensureSearchStatistics`) and doctor `planner_stats_stale`.
+ */
+export async function missingSearchStatistics(engine: Pick<BrainEngine, 'executeRaw' | 'kind'>): Promise<string[]> {
+ if (engine.kind !== 'postgres') return [];
+ const pairs = Object.entries(SEARCH_STATISTICS_COLUMNS).flatMap(([table, columns]) => columns.map(column => [table, column] as const));
+ const rows = await engine.executeRaw<{ col: string }>(MISSING_SEARCH_STATISTICS_SQL, [pairs.map(p => p[0]), pairs.map(p => p[1])]);
+ const missing = rows.map(row => row.col);
+ if (await readProjectionStatistics(engine) === 'uncollected') missing.push(PROJECTION_STATISTICS_NAME);
+ return missing;
+}
+
+/** Whether this role may ANALYZE pages (owner or superuser), as the refresh requires. */
+export async function canAnalyzePages(engine: Pick<BrainEngine, 'executeRaw'>): Promise<boolean> {
+ const [role] = await engine.executeRaw<{ can_analyze: boolean }>(
+ `SELECT pg_has_role(current_user, p.relowner, 'USAGE') OR r.rolsuper AS can_analyze
+ FROM pg_class p CROSS JOIN pg_roles r
+ WHERE p.oid = 'pages'::regclass AND r.rolname = current_user`,
+ );
+ return !!role?.can_analyze;
+}
+
/**
* 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
@@ -121,16 +177,46 @@ async function statisticsStillCurrent(engine: BrainEngine, changedPages: number)
// past the size it last sampled, refreshes.
const [state] = await engine.executeRaw<{ reltuples: number; columns: boolean }>(
`SELECT c.reltuples::float8 AS reltuples,
- CASE WHEN $1::text = 'postgres' THEN (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
- ELSE NOT EXISTS (SELECT 1 FROM pg_class t WHERE t.relnamespace = c.relnamespace AND t.relkind = 'r' AND pg_relation_size(t.oid) > 0
- AND (t.reltuples < 0 OR pg_relation_size(t.oid) / current_setting('block_size')::int > t.relpages * 1.1 + 8)) END AS columns
+ $1::text = 'postgres' OR NOT EXISTS (SELECT 1 FROM pg_class t WHERE t.relnamespace = c.relnamespace AND t.relkind = 'r' AND pg_relation_size(t.oid) > 0
+ AND (t.reltuples < 0 OR pg_relation_size(t.oid) / current_setting('block_size')::int > t.relpages * 1.1 + 8)) AS columns
FROM pg_class c WHERE c.oid = 'pages'::regclass`, [engine.kind]);
const rows = Number(state?.reltuples ?? -1);
if (!state?.columns || rows <= (engine.kind === 'pglite' ? 500 : 0) || changedPages >= 50 + 0.1 * rows) return false;
+ if ((await missingSearchStatistics(engine)).length > 0) return false;
return verifyProjectionStatistics(engine).then(() => true, () => false);
}
+/**
+ * The Postgres search guard (`guardSearchStatistics` runs it once per engine, in the background): when
+ * `missingSearchStatistics` finds statistics absent and this role may ANALYZE, run the full refresh. Returns what
+ * was missing. Never throws; a role that may not ANALYZE is left to doctor `planner_stats_stale`.
+ */
+export async function ensureSearchStatistics(engine: BrainEngine): Promise<string[]> {
+ try {
+ const missing = await missingSearchStatistics(engine);
+ if (missing.length > 0 && await canAnalyzePages(engine)) await refreshProjectionStatistics(engine);
+ return missing;
+ } catch {
+ return [];
+ }
+}
+
+const searchStatisticsGuards = new WeakSet<object>();
+
+/**
+ * PostgresEngine's searchKeyword and searchVector: once per engine, on its first search outside a transaction,
+ * `ensureSearchStatistics` in the background. The search never waits on it (a caller's transaction may hold the
+ * pool's only connection); disconnect waits for it, bounded by the refresh's 30 s statement timeout.
+ */
+export function guardSearchStatistics(engine: BrainEngine & { registerBeforeDisconnect(stop: () => Promise<void>): () => void },
+ inTransaction: boolean): void {
+ if (inTransaction || searchStatisticsGuards.has(engine)) return;
+ searchStatisticsGuards.add(engine);
+ const run = ensureSearchStatistics(engine);
+ const unregister = engine.registerBeforeDisconnect(async () => { await run; });
+ void run.finally(unregister);
+}
+
/**
* Refreshes the planner statistics after a write pass that changed `changedPages` pages (omitted: always). A pass
* `statisticsStillCurrent` vouches for skips the ANALYZE; PGLite then analyzes only the hot tables its row deltas
@@ -142,12 +228,7 @@ export async function refreshProjectionStatistics(engine: BrainEngine, changedPa
await maybeRefreshPlannerStats(engine, 'import', { throttle: false });
return true;
}
- const [role] = await engine.executeRaw<{ can_analyze: boolean }>(
- `SELECT pg_has_role(current_user, p.relowner, 'USAGE') OR r.rolsuper AS can_analyze
- FROM pg_class p CROSS JOIN pg_roles r
- WHERE p.oid = 'pages'::regclass AND r.rolname = current_user`,
- );
- if (!role?.can_analyze) {
+ if (!await canAnalyzePages(engine)) {
console.warn('[search] Projection planner statistics were not refreshed: database-owner maintenance is required. Run ANALYZE pages(text_projection_revision, knowledge_revision) as the table owner.');
return false;
}
diff --git a/test/e2e/search-statistics-guard-postgres.test.ts b/test/e2e/search-statistics-guard-postgres.test.ts
new file mode 100644
index 0000000000..b133d3f9a9
--- /dev/null
+++ b/test/e2e/search-statistics-guard-postgres.test.ts
@@ -0,0 +1,44 @@
+/**
+ * GBRA-75 wave 7: PostgresEngine's search guard. A brain whose search planner
+ * statistics are absent (pg_upgrade, a deleted pg_statistic) gets them from the
+ * first pool search, in the background; a search inside a transaction never
+ * starts the guard (it may hold the pool's only connection).
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { getEngine, hasDatabase, importFixtures, setupDB, teardownDB } from './helpers.ts';
+import { missingSearchStatistics, SEARCH_STATISTICS_COLUMNS } from '../../src/core/search/projection-statistics.ts';
+
+const d = hasDatabase() ? describe : describe.skip;
+
+d('search planner statistics guard on Postgres', () => {
+ beforeAll(async () => {
+ await setupDB();
+ await importFixtures();
+ const engine = getEngine();
+ await engine.executeRaw('ANALYZE pages');
+ await engine.executeRaw('ANALYZE content_chunks');
+ await engine.executeRaw("DELETE FROM pg_statistic WHERE starelid = 'pages'::regclass");
+ }, 60_000);
+ afterAll(async () => { await teardownDB(); });
+
+ const pagesMissing = SEARCH_STATISTICS_COLUMNS.pages.map(c => `pages.${c}`);
+
+ test('a search inside a transaction does not start the guard', async () => {
+ const engine = getEngine();
+ expect(await missingSearchStatistics(engine)).toEqual(pagesMissing);
+ await engine.transaction(tx => tx.searchKeyword('fixture'));
+ await new Promise(resolve => setTimeout(resolve, 300));
+ expect(await missingSearchStatistics(engine)).toEqual(pagesMissing);
+ });
+
+ test('the first pool search collects the absent statistics without waiting for them', async () => {
+ const engine = getEngine();
+ await engine.searchKeyword('fixture');
+ let missing = await missingSearchStatistics(engine);
+ for (let i = 0; i < 50 && missing.length > 0; i++) {
+ await new Promise(resolve => setTimeout(resolve, 100));
+ missing = await missingSearchStatistics(engine);
+ }
+ expect(missing).toEqual([]);
+ }, 30_000);
+});
diff --git a/test/search-statistics-guard.test.ts b/test/search-statistics-guard.test.ts
new file mode 100644
index 0000000000..20546aa5ac
--- /dev/null
+++ b/test/search-statistics-guard.test.ts
@@ -0,0 +1,113 @@
+/**
+ * GBRA-75 wave 7: a Postgres brain whose search planner statistics are absent
+ * (pg_upgrade, a deleted pg_statistic) plans search as nested loops (50-60 s at
+ * 5,000 pages). One test, `missingSearchStatistics`, drives the write-pass skip,
+ * the search guard, doctor `planner_stats_stale` and `repair planner-stats`.
+ * PGLite stands in for Postgres here (the same catalogs), through an engine
+ * that reports kind 'postgres'; test/e2e/search-statistics-guard-postgres.test.ts
+ * runs the PostgresEngine guard itself.
+ */
+import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
+import { PGlite } from '@electric-sql/pglite';
+import type { BrainEngine } from '../src/core/engine.ts';
+import {
+ ensureSearchStatistics, missingSearchStatistics, PROJECTION_STATISTICS_NAME, PROJECTION_STATISTICS_SQL,
+ refreshProjectionStatistics, SEARCH_STATISTICS_COLUMNS,
+} from '../src/core/search/projection-statistics.ts';
+import { DOCTOR_CHECK_REGISTRY } from '../src/commands/doctor/registry.ts';
+import { plannerStatsRepair } from '../src/core/repair/planner-stats.ts';
+import type { DoctorContext } from '../src/commands/doctor/context.ts';
+import type { Check } from '../src/commands/doctor.ts';
+
+function postgresLike(db: Pick<PGlite, 'query'> & Partial<Pick<PGlite, 'transaction'>>): BrainEngine {
+ return {
+ kind: 'postgres',
+ executeRaw: async (sql: string, params?: unknown[]) => (await db.query(sql, params)).rows,
+ getConfig: async () => null,
+ transaction: async (fn: (tx: BrainEngine) => Promise<unknown>) => db.transaction
+ ? db.transaction(tx => fn(postgresLike(tx)))
+ : fn(postgresLike(db)),
+ } as unknown as BrainEngine;
+}
+
+const ALL = Object.entries(SEARCH_STATISTICS_COLUMNS).flatMap(([table, columns]) => columns.map(column => `${table}.${column}`));
+
+describe('missing search planner statistics on Postgres', () => {
+ let db: PGlite;
+ let engine: BrainEngine;
+ const dropStatistics = (table: string, column?: string) => db.query(
+ `DELETE FROM pg_statistic WHERE starelid = $1::regclass ${column ? `AND staattnum = (SELECT attnum FROM pg_attribute WHERE attrelid = $1::regclass AND attname = '${column}')` : ''}`,
+ [table]);
+
+ beforeEach(async () => {
+ db = new PGlite();
+ engine = postgresLike(db);
+ await db.exec(`CREATE TABLE pages (id integer PRIMARY KEY, source_id text, type text, slug text, deleted_at timestamptz,
+ text_projection_revision uuid, knowledge_revision uuid);
+ CREATE TABLE content_chunks (id integer PRIMARY KEY, page_id integer, model text, modality text);
+ CREATE TABLE planner_probe_unused (id integer);
+ INSERT INTO pages SELECT i, 'src-' || (i % 8), 'note', 'note-' || i, NULL,
+ '00000000-0000-0000-0000-000000000001', '00000000-0000-0000-0000-000000000001' FROM generate_series(1, 2000) i;
+ INSERT INTO content_chunks SELECT i, 1 + i % 2000, 'voyage:voyage-4', 'text' FROM generate_series(1, 6000) i;
+ ANALYZE content_chunks;`);
+ await db.exec(PROJECTION_STATISTICS_SQL);
+ await db.exec('ANALYZE pages');
+ }, 30_000);
+
+ afterEach(async () => { await db?.close(); });
+
+ test('collected statistics: nothing is missing; empty tables are never missing', async () => {
+ expect(await missingSearchStatistics(engine)).toEqual([]);
+ const empty = new PGlite();
+ try {
+ await empty.exec(`CREATE TABLE pages (id integer, source_id text, type text, slug text, deleted_at timestamptz,
+ text_projection_revision uuid, knowledge_revision uuid);
+ CREATE TABLE content_chunks (id integer, page_id integer, model text, modality text);`);
+ await empty.exec(PROJECTION_STATISTICS_SQL);
+ expect(await missingSearchStatistics(postgresLike(empty))).toEqual([]);
+ } finally { await empty.close(); }
+ });
+
+ test('deleted statistics are reported per column, and the projection statistics with them', async () => {
+ await dropStatistics('pages');
+ await db.query("DELETE FROM pg_statistic_ext_data WHERE stxoid = (SELECT oid FROM pg_statistic_ext WHERE stxname = $1)", [PROJECTION_STATISTICS_NAME]);
+ await dropStatistics('content_chunks');
+ expect(await missingSearchStatistics(engine)).toEqual([...ALL, PROJECTION_STATISTICS_NAME]);
+ });
+
+ test('a one-page write pass refreshes when any search column lost its statistics, not only deleted_at', async () => {
+ // Base skipped this refresh: its test read only pages.deleted_at and content_chunks.model.
+ await dropStatistics('pages', 'source_id');
+ expect(await missingSearchStatistics(engine)).toEqual(['pages.source_id']);
+ expect(await refreshProjectionStatistics(engine, 1)).toBe(true);
+ expect(await missingSearchStatistics(engine)).toEqual([]);
+ });
+
+ test('the search guard collects absent statistics through the refresh and reports what was missing', async () => {
+ await dropStatistics('pages');
+ expect(await ensureSearchStatistics(engine)).toEqual(SEARCH_STATISTICS_COLUMNS.pages.map(c => `pages.${c}`));
+ expect(await missingSearchStatistics(engine)).toEqual([]);
+ expect(await ensureSearchStatistics(engine)).toEqual([]);
+ const [unrelated] = (await db.query<{ n: number }>("SELECT count(*)::int AS n FROM pg_stats WHERE tablename = 'planner_probe_unused'")).rows;
+ expect(unrelated!.n).toBe(0);
+ });
+
+ test('doctor warns with a runnable fix; repair planner-stats --apply clears it', async () => {
+ const entry = DOCTOR_CHECK_REGISTRY.find(e => e.name === 'planner_stats_stale')!;
+ const ctx = { engine, progress: { heartbeat() {}, start() {}, tick() {}, finish() {} } } as unknown as DoctorContext;
+ const run = async () => ((await entry.run(ctx)) as Check[])[0]!;
+ expect((await run()).status).toBe('ok');
+
+ await dropStatistics('pages', 'deleted_at');
+ const warn = await run();
+ expect(warn.status).toBe('warn');
+ expect(warn.details?.missing_search_statistics).toEqual(['pages.deleted_at']);
+ expect(warn.fix).toMatchObject({ argv: ['gbrain', 'repair', 'planner-stats', '--apply'], actor: 'agent', consent: [],
+ verify: { argv: ['gbrain', 'doctor', '--only', 'planner_stats_stale', '--json'] } });
+
+ const plan = await plannerStatsRepair.plan(engine, { brain_id: 'host', source_ids: [] }, null);
+ expect(plan.items.map(i => i.slug)).toEqual(['search-statistics']);
+ expect(await plannerStatsRepair.apply({ engine, logger: { info() {}, warn() {}, error() {} } } as never, plan.items[0]!)).toBe(true);
+ expect((await run()).status).toBe('ok');
+ });
+});