Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(planner-stats): analyze after index builds; give present expression indexes statistics (lhf wave 2 item 6)

garrytan70521d88f626
diff --git a/docs/architecture/key-files/core-utilities-1.md b/docs/architecture/key-files/core-utilities-1.md
index f63ea62911..0533571bfb 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). 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 and the `extract --source db` links walk of at least `LINK_DRAIN_ANALYZE_MIN_STALE` (500) pages through `plannerStatsForLinkDrain` (first page, then the same cadence; `link_transitions`/`link_relationships`, no deltas, with `links`), 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/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 and the `extract --source db` links walk of at least `LINK_DRAIN_ANALYZE_MIN_STALE` (500) pages through `plannerStatsForLinkDrain` (first page, then the same cadence; `link_transitions`/`link_relationships`, no deltas, with `links`), 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. `readExpressionIndexesWithoutStats` (both engines; lhf wave 2 item 6) lists expression indexes on the hot tables with entries (index `reltuples > 0`) but no `pg_stats` row under their own name, skipping indexes whose statistics the role cannot see; every `maybeRefreshPlannerStats` reason except `first_read` analyzes their tables (a search never pays the probe), doctor names each with its own reason, and the repair plans their tables (on Postgres the operator-run recovery). 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), `escapeLikePattern(s)` (escapes `%`, `_`, `\\` for `ILIKE ... ESCAPE '\\'`), and `cjkMatchTerms(query)` (whitespace terms with a trailing Korean particle stripped by `stripKoreanParticle`, longest particle first, stem kept only at 2+ characters; the one term list every CJK keyword builder matches, so the count, the keyword pages and the chunk search agree). 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/architecture/key-files/engines-1.md b/docs/architecture/key-files/engines-1.md
index ff9058cc7a..087942425f 100644
--- a/docs/architecture/key-files/engines-1.md
+++ b/docs/architecture/key-files/engines-1.md
@@ -29,7 +29,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/engine.ts` — Pluggable engine interface (BrainEngine). `clampSearchLimit(limit, default, cap)` takes an explicit cap so per-operation caps can be tighter than `MAX_SEARCH_LIMIT`. Exports `LinkBatchInput`/`TimelineBatchInput` for the bulk-insert API (`addLinksBatch`/`addTimelineEntriesBatch`). `readonly kind: 'postgres' | 'pglite'` discriminator lets `src/core/migrate.ts` and others branch without `instanceof` + dynamic imports. Methods: `batchLoadEmotionalInputs(slugs?)` (CTE-shaped read with per-table aggregates so page × N tags × M takes never produces N×M rows), `setEmotionalWeightBatch(rows)` (`UPDATE FROM unnest($1::text[],$2::text[],$3::real[])` composite-keyed on `(slug, source_id)`), `getRecentSalience(opts)`, `findAnomalies(opts)`. `PageFilters` has `sort?: 'updated_desc'|'updated_asc'|'created_desc'|'slug'` + `PAGE_SORT_SQL` whitelist consumed by both engines. `listAllPageRefs(): Promise<Array<{slug, source_id}>>` ordered by `(source_id, slug)` — cheap cross-source enumeration instead of a `getAllSlugs()→getPage(slug)` N+1 (which would silently default to `source_id='default'`); parity across postgres-engine.ts + pglite-engine.ts; Pinned by `test/e2e/multi-source-bug-class.test.ts`. `SearchOpts`+`PageFilters` add `sourceIds?: string[]` (federated read axis; both engines apply `WHERE source_id = ANY($N::text[])` when set, preserve scalar `sourceId` fast path when unset); `traverseGraph(slug, depth, opts?)` and `traversePaths(slug, opts?)` accept `opts.sourceId`/`opts.sourceIds`. `traversePathsDetailed(slug, opts?)` returns `{ paths: GraphPath[], truncated }` — the final SELECT of the path-enumerating recursive CTE is bounded at `TRAVERSE_PATH_ROW_CAP + 1` rows on both engines (the probe row signals overflow; `ORDER BY depth` means the deepest edges are dropped, so a truncated result is still the complete shallow neighbourhood; the cap counts raw rows before the in-memory edge dedup, so `paths.length` alone cannot reveal truncation) and `traversePaths` is its `.paths` projection. Each `GraphPath` carries `from_source_id`/`to_source_id` and the edge dedup keys on page ids; each `traverseGraph` `GraphNode` carries `source_id` (DISTINCT per page), so the same slug in two sources stays two edges or nodes. `resolveSlugWithAliasDetailed(slug, sourceOrSources)` returns `{ canonical_slug, source_id } | null` — the winning alias row AND its owning source under the same scope/precedence rules (`ORDER BY array_position(scope, source_id), id`; null when nothing matches or the `slug_aliases` table does not exist yet); `resolveSlugWithAlias` is its canonical-slug projection (falls back to the input slug). A consumer that goes on to read the canonical page must scope that read to `source_id`. The by-slug read methods carry the same federated axis: `getTags`/`getLinks`/`getBacklinks`/`getChunks` opts and `TimelineOpts` (consumed by `getTimeline`) accept `sourceIds?: string[]` taking precedence over the scalar `sourceId` (`source_id = ANY($::text[])` scoping the slug→page-id lookup); `getChunkPage(slug, {fromIndex, limit, ...scope})` is get_chunks' paged read: the same predicate as `getChunks`, one count/max query plus the chunk_index range [fromIndex, fromIndex + limit) (a range, so a slug matching a page in two federated sources never splits an index across calls); `getChunks` falls back to the `'default'` source when neither is set (importCodeFile's incremental-embedding reuse relies on it) and SELECTs an explicit non-vector column list — embedding vectors never ride the payload since rowToChunk discards them (`getChunksWithEmbeddings` stays scalar-only by design: engine-internal, zero remote-reachable callers); the link reads (`getLinks`/`getBacklinks`) scope ALL THREE endpoints (from/to/origin) on the federated branch while the scalar branch scopes only the near endpoint for trusted internal cross-source callers. `traverseGraph` opts has `frontierCap?: number` (per-iteration recursive-CTE cap, approx per-BFS-layer); return type `Promise<GraphNode[]>` for MCP wire stability; export `TraverseGraphOpts`; Postgres uses parenthesized `LIMIT N ORDER BY (slug, id)` inside the recursive term, PGLite mirrors with positional params; Pinned by `test/regressions/v0_36_frontier_cap.test.ts`. Phantom-redirect methods: `refreshPageBody(slug, sourceId, compiled_truth, timeline, content_hash)` narrow-UPDATEs three columns + updated_at, skipping soft-deleted rows (content_hash refresh required so `gbrain sync` sees the canonical as unchanged after fence merge); `migrateFactsToCanonical(phantomSlug, canonicalSlug, sourceId)` UPDATEs `entity_slug`+`source_markdown_slug` on every active fact row keyed on the phantom, preserving embedding/validUntil/kind/status/source_session/confidence and offsetting `row_num` past the canonical page's current MAX(row_num) (all rows incl. expired — the partial `idx_facts_fence_key` only excludes NULL; NULL stays NULL) so overlapping fence rows never collide; parity at `test/phantom-redirect-engine-parity.test.ts`. `getAdjacencyBoosts(pageIds): Promise<Map<number, AdjacencyRow>>` powers the per-query graph-signals stage — one SQL query returning inbound-link counts among top-K plus a cross-source count (links from differing `source_id`); `COALESCE(p.source_id,'default')` null safety, `HAVING >= 1`, cross-source CASE-WHEN excludes the target's own source; parity SQL across both engines; `SearchResult` gains optional `base_score`, `backlink_boost`, `salience_boost`, `recency_boost`, `exact_match_boost`, `graph_adjacency_boost`, `graph_cross_source_boost`, `session_demote_factor`, `reranker_delta` + internal staging fields; Pinned by `test/e2e/graph-signals-engine.test.ts`. Two REQUIRED methods: `deletePages(slugs, {sourceId}): Promise<string[]>` (single-batch primitive returning slugs actually deleted) and `resolveSlugsByPaths(paths, {sourceId}): Promise<Map<path,slug>>` (batch path→slug lookup); `sourceId` REQUIRED on both at the type level (asymmetric with single-row `deletePage` which keeps optional/'default'); both short-circuit on empty input and throw when `> DELETE_BATCH_SIZE`. `softDeletePages(slugs, {sourceId}): Promise<string[]>` is the batch soft-delete twin, mirroring `deletePages`' contract exactly (required `sourceId`, `> DELETE_BATCH_SIZE` throws, empty input short-circuits, caller owns chunking + decompose-to-one-element-batches on failure): one `UPDATE … SET deleted_at = now() … AND deleted_at IS NULL … RETURNING slug` round-trip returning only the slugs that actually flipped active→soft-deleted — the `deleted_at IS NULL` predicate is load-bearing so a re-run never refreshes an already-soft-deleted row's 72h purge clock — and NOTHING cascades (chunks/links/timeline stay behind the read-side `deleted_at` filters; the autopilot purge phase hard-deletes after 72h; a re-import within the window revives via `putPage`'s upsert; `deletePage`/`deletePages` remain the purge/teardown primitives). `getStats(opts?)` / `getHealth(opts?)` take an optional `{sourceId?, sourceIds?}` scope (same shape as `sourceScopeOpts` output): omitted = brain-wide; scoped = EVERY counter/coverage/degree confines to the grant, including derived-table counts via their page joins, and link-derived numbers count only edges with BOTH endpoints in scope — so an excluded source's numbers can't be recovered by subtraction. Consumer is the remote-caller ladder in `src/core/ops/admin.ts`; `getHealth` is a one-line delegation to `src/core/engine-sql/health.ts`. Embedding-signature stale-detection quartet: `countStaleChunks(opts?)` gains optional `signature?: string` widening the stale predicate from `embedding IS NULL` to ALSO include chunks whose JOINed page `embedding_signature IS NOT NULL AND <> $signature` (NULL signature is GRANDFATHERED, never counted; omit `signature` for the legacy NULL-only count); `sumStaleChunkChars(opts?: {sourceId?, signature?}): Promise<number>` = `SUM(LENGTH(chunk_text))` over stale chunks (same predicate + embed_skip filter + optional sourceId scope), used by `gbrain sync --all` cost preview via `estimateCostFromChars`; `setPageEmbeddingSignature(slug, {sourceId?, signature})` stamps `pages.embedding_signature` after a page's chunks (re)embed, idempotent no-op when page absent; `invalidateStaleSignatureEmbeddings({signature, sourceId?}): Promise<number>` NULLs `embedding`+`embedded_at` on every chunk whose page signature is set AND differs, returning the count, called BEFORE `listStaleChunks` so signature-drift pages flow through the NULL-embedding keyset cursor unchanged (NULL never invalidated). Widens `findOrphanPages(opts?: {sourceId?, sourceIds?})` (candidate-side scoping only; inbound links counted from any source). Pinned by `test/sum-stale-chunk-chars.test.ts`, `test/embedding-signature-stale.test.ts`, `test/e2e/engine-parity.test.ts`. Free-text alias layer: `resolveAliases(aliasNorms, opts?): Promise<Map<string, Array<{slug, source_id}>>>` (READ; maps each normalized alias to declaring `(slug, source_id)` pairs, source-scoped) and `setPageAliases(slug, sourceId, aliasNorms)` (WRITE; replaces the full alias set, delete-then-insert, empty clears, idempotent on the unique triple), called by the `importFromContent` ingest projection and the `reindex --aliases` backfill; parity across both engines, Pinned by `test/search/page-aliases-engine.test.ts`. `searchVector` in both engines injects the shared `buildBestPerPagePoolCte` per-page max-pool so a page surfaces on its strongest chunk. `executeRawDirect(sql, params?, opts?)` is the lock-hot-path sibling of `executeRaw`: same single-statement contract, but routes to the direct session-mode pool when dual-pool is active (Postgres/Supabase port 5432) so a long-held lock heartbeat survives the transaction pooler's per-transaction connection recycling; PGLite delegates straight to `executeRaw` (no pooler). Both engines implement it; the Minion lock path (`claim`/`renewLock`) is the consumer. `reconnect(ctx?: {error?})` is a REQUIRED lifecycle method on BOTH engines: it recovers a dropped connection using the config captured at the last `connect()`, so callers (autopilot health probe, `batchRetry`) never `disconnect()` + bare `connect()` (which loses the config and throws `database_url undefined` forever, and opens a null-connection window). PostgresEngine rebuilds its pool with a `_reconnecting` reentrancy guard and emits pool-recovery audit; PGLite is single-writer in-process so it just restores the saved data dir for parity. Plus two interface members: (1) optional `findDuplicatePage?(sourceId, {hash, frontmatterId?}): Promise<{slug, id} | null>` (identity precedence is content_hash OR frontmatter->>'id', both with `deleted_at IS NULL`); (2) `resolveSlugs(partial, opts?)` extended with `{sourceId?, sourceIds?}` so the MCP fuzzy `get_page` path scopes by source (field names match `sourceScopeOpts(ctx)` output so handlers spread directly; no opts gives the unscoped behavior). Plus a stable tiebreaker `ORDER BY score DESC, page_id ASC, chunk_id ASC` in `searchVector` in both engines: on a score tie (basis-vector eval fixtures) older `page_id` wins, so a new index on `pages` cannot flip ranking on tied scores.
- `src/core/migrate-pending.ts` — `hasPendingMigrations` (re-exported by `migrate.ts`): one `version` read against the generated `schema-migrations/latest.generated.ts`, so a connect never loads the migration registry.
-- `src/core/migrate.ts` — schema-migration runner. Re-exports `MIGRATIONS` from the generated registry `src/core/schema-migrations/registry.generated.ts`; each migration is one file `src/core/schema-migrations/v<NNN>-<name>.ts` (the source of truth for schema DDL history), with the `Migration` type in `schema-migrations/types.ts` and shared handler helpers (`migrationNotice`, `dropInvalidConcurrentIndex`, the fresh-install quiet flag) in `schema-migrations/helpers.ts`, a leaf that never imports `migrate.ts`. `Migration` carries `sqlFor?: { postgres?, pglite? }` (engine-specific SQL overrides `sql`) and `transaction?: boolean` (false for `CREATE INDEX CONCURRENTLY`, which Postgres refuses in a transaction; ignored on PGLite). Key migrations: v14 (handler branches on `engine.kind` for CONCURRENTLY-on-Postgres with invalid-remnant pre-drop via `pg_index.indisvalid`, plain `CREATE INDEX` on PGLite); v15 (`minion_jobs.max_stalled` default 1→5 + backfill non-terminal rows); v24 `rls_backfill_missing_tables` (`sqlFor: { pglite: '' }` no-op — PGLite has no RLS engine, targets subagent tables absent from pglite-schema.ts); v30 `dream_verdicts (file_path TEXT, content_hash TEXT, worth_processing BOOL, reasons JSONB, judged_at TIMESTAMPTZ, PK(file_path, content_hash))` (RLS-enabled under BYPASSRLS; synthesize reads/writes to avoid re-judging); v35 auto-RLS event trigger `auto_rls_on_create_table` fires on `ddl_command_end` for `WHEN TAG IN ('CREATE TABLE','CREATE TABLE AS','SELECT INTO')` running `ALTER TABLE … ENABLE ROW LEVEL SECURITY` on new `public.*` tables (no FORCE) + one-time backfill on every existing `public.*` base table whose comment doesn't match `^GBRAIN:RLS_EXEMPT\s+reason=\S.{3,}` (per-table failure aborts the offending CREATE TABLE; no EXCEPTION wrap; PGLite no-op via `sqlFor.pglite: ''`; breaking change: intentionally-RLS-off public tables need the GBRAIN:RLS_EXEMPT comment before upgrade); v40 `pages_emotional_weight` (`pages.emotional_weight REAL NOT NULL DEFAULT 0.0`, column-only metadata-only); v46 `mcp_request_log_params_jsonb_normalize` (`UPDATE ... SET params = params::text::jsonb WHERE jsonb_typeof(params) = 'string'`, idempotent); v60-v65 six-migration chain wiring source-scoping into `oauth_clients` — v60 (`oauth_clients_source_id_fk`: `source_id TEXT` NULL→`'default'` backfill + FK to `sources(id) ON DELETE SET NULL`), v61 (`federated_read TEXT[] NOT NULL DEFAULT '{}'`), v62 (explicit-CASE backfill so `source_id IS NULL` → `'{}'`), v63 (fail-loud check every row's source_id is in its federated_read array), v64 (FK flipped to `ON DELETE RESTRICT`), v65 (GIN index for array-containment); v68 `eval_candidates_embedding_column` (`eval_candidates.embedding_column TEXT NULL` per-row provenance for `gbrain eval replay` to reproduce the same retrieval space; NULL-tolerant); v108 `pages_embedding_signature` (`pages.embedding_signature TEXT NULL` = `<provider:model>:<dims>` stamped via `setPageEmbeddingSignature`; GRANDFATHER — stale predicate is `embedding_signature IS NOT NULL AND embedding_signature <> $current` so NULL is NEVER stale and upgrade never re-embeds the whole corpus; no index; metadata-only); v109 `sources_newest_content_at` (`sources.newest_content_at TIMESTAMPTZ` durable newest-COMMIT HEAD committer time written by `writeSyncAnchor`, read by the REMOTE staleness path instead of shelling to git; fresh-install column in `src/schema.sql`, generated into both blobs, plus a bootstrap probe); v110 `page_aliases` (`(id, source_id, alias_norm, slug, ...)` with `UNIQUE (source_id, alias_norm, slug)` + lookup indexes on `(source_id, alias_norm)` and `(source_id, slug)`; `alias_norm` is `normalizeAlias()` output so WRITE/READ key on the same form; also in `src/core/pglite-schema.ts`); v111 `search_telemetry_rank1_columns` (`ADD COLUMN IF NOT EXISTS` on both engines: `sum_rank1_score`, `count_rank1`, three buckets `rank1_lt_solid`/`rank1_solid`/`rank1_high` on `search_telemetry` — aggregate not per-query rows so rank-1 median drift is bounded-growth; ALTERs right after v57 which created the table); v114 `links_link_source_check_kebab_regex` (opens `link_source` from the closed allowlist to a kebab-case format gate `^[a-z][a-z0-9]*(-[a-z0-9]+)*$` + `char_length<=64`; Postgres branch uses `NOT VALID` + `VALIDATE CONSTRAINT` with `transaction:false`, PGLite plain DROP+ADD; existing built-ins all satisfy the regex so VALIDATE never fails on existing data); v116 `code_edges_source_backfill_and_callee_index` (idempotent: backfills NULL `code_edges_symbol`/`code_edges_chunk` `source_id` from each edge's `from_chunk` page — a NULL never matches a scoped `AND source_id = …` filter, so scoped `code-callers`/`code-callees` would return 0 rows on multi-source brains — plus plain `CREATE INDEX` on `from_symbol_qualified` for both edge tables, which had no index and seq-scanned per BFS node); v129 `dream_verdicts_triage_v1_columns` (additive `ADD COLUMN IF NOT EXISTS` widening `dream_verdicts` into a scored triage record — `score`, `content_type`, `segments`, `entities`, `model`, `triage_version`; legacy rows keep `score` NULL and read as cache misses, re-judged once; no backfill, no index; same SQL on both engines since `dream_verdicts` is migration-created on PGLite too, so the columns take the COLUMN_EXEMPTIONS route in `test/schema-bootstrap-coverage.test.ts` rather than bootstrap probes); v143 `dream_verdicts_ttl` (30-day `expires_at` TTL: nullable `ADD COLUMN` + `SET DEFAULT` run BEFORE the `judged_at`-derived backfill — statement order is load-bearing so a legacy writer racing the upgrade window picks up the default instead of inserting a NULL that would fail `SET NOT NULL` on every retry; on Postgres the schema blob's `dream_verdicts_expires_idx` forward-references the column, so `forward-reference-bootstrap.ts` probes + ALTERs it before the blob replays, and both engines' `getDreamVerdict` read predicate is NULL-tolerant — `expires_at IS NULL OR expires_at > now()` — so a pre-backfill row reads as a hit instead of silently re-judging the corpus). Three shape-keyed self-heals run on EVERY `runMigrations` pass, including the no-pending early-return path, because a merge-renumbered migration or a drifted restore can leave the version counter past a schema change while the live shape stays old: `repairTimelineDedupIndex` (`timeline_dedup_index`, see `timeline-dedup-repair.ts`) and `repairPagesUpsertArbiter` (`pages_source_slug_key`, see `pages-upsert-arbiter.ts`) are not version-gated at all; `repairLinkSourceCheck` (`links_link_source_check`, see `link-source-check-repair.ts`) runs only when the ledger is already >= `LINK_SOURCE_GATE_MIGRATION_VERSION` (114), because below it the pending loop replays v114 itself (running the repair first would rewrite the constraint twice, and a pre-v11 brain has no `link_source` column). All three are best-effort + idempotent; `doctor` surfaces each drift independently. `retry-matcher.ts` and `timeline-dedup-repair.ts` are static dependencies because `runMigrations()` executes from live engine initialization; the engine dynamic-import guard scans this file with both engine implementations. v95: `pages_dedup_partial_index` adds `CREATE INDEX pages_dedup_idx ON pages (source_id, content_hash) WHERE deleted_at IS NULL`. Postgres uses `CREATE INDEX CONCURRENTLY` with `transaction: false` + pre-drops any invalid remnant; PGLite uses plain `CREATE INDEX`. Powers `findDuplicatePage` hot path (O(log n) instead of O(n)). v74 `mcp_spend_log` uses BTREE on `(client_id, created_at)` + `(token_name, created_at)` — `date_trunc('day', TIMESTAMPTZ)` is NOT IMMUTABLE so can't appear in index expressions; a `created_at` range scan covers the per-day rollup. v75 `embedding_multimodal_column` is column-only (no HNSW index — deferred to post-reindex per pgvector best practice). Every pass (including one with nothing pending) ends with `page-state/revision-backfill-schema.ts:resumePageRevisionBackfill` while `pages.knowledge_revision` is nullable (#5216): the page-state schema adds `sources.incarnation` and `pages.knowledge_revision` nullable with a separate default (no volatile-default table rewrite on replay; an empty `pages` is constrained at once), rows are backfilled in committed id batches with a config cursor (`page_state.revision_backfill`), a failing row is isolated and retried at most three passes, each update grants only its rows' sources to the managed writer guard (`gbrain.write_sources`, transaction-local), and the column becomes NOT NULL via CHECK NOT VALID → VALIDATE → SET NOT NULL. With the schema version current no ordinary command runs a pass, so `gbrain apply-migrations --force-schema` (`REVISION_BACKFILL_RESUME_COMMAND`) resumes it; `readRevisionBackfillStatus` feeds doctor `revision_backfill` (`src/commands/doctor/checks/revision-backfill.ts`: ok when NOT NULL, warn with the pending count, the failed rows by page and the resume command, or the `repair orphan-children` preview when only spent rows remain). The revision trigger handles a NULL old revision without reading bodies; snapshots report such a row's revision as `backfill_pending` and `assertPageRevision` refuses revision-bound writes with `revision_backfill_pending` (`page-revision-backfill-5216.test.ts`).
+- `src/core/migrate.ts` — schema-migration runner. Re-exports `MIGRATIONS` from the generated registry `src/core/schema-migrations/registry.generated.ts`; each migration is one file `src/core/schema-migrations/v<NNN>-<name>.ts` (the source of truth for schema DDL history), with the `Migration` type in `schema-migrations/types.ts` and shared handler helpers (`migrationNotice`, `dropInvalidConcurrentIndex`, `buildIndexOnline` with its best-effort `analyzeAfterIndexBuild` (a failed ANALYZE warns with the repair command and never fails the build of a valid index), the fresh-install quiet flag) in `schema-migrations/helpers.ts`, a leaf that never imports `migrate.ts`. `Migration` carries `sqlFor?: { postgres?, pglite? }` (engine-specific SQL overrides `sql`) and `transaction?: boolean` (false for `CREATE INDEX CONCURRENTLY`, which Postgres refuses in a transaction; ignored on PGLite). Key migrations: v14 (handler branches on `engine.kind` for CONCURRENTLY-on-Postgres with invalid-remnant pre-drop via `pg_index.indisvalid`, plain `CREATE INDEX` on PGLite); v15 (`minion_jobs.max_stalled` default 1→5 + backfill non-terminal rows); v24 `rls_backfill_missing_tables` (`sqlFor: { pglite: '' }` no-op — PGLite has no RLS engine, targets subagent tables absent from pglite-schema.ts); v30 `dream_verdicts (file_path TEXT, content_hash TEXT, worth_processing BOOL, reasons JSONB, judged_at TIMESTAMPTZ, PK(file_path, content_hash))` (RLS-enabled under BYPASSRLS; synthesize reads/writes to avoid re-judging); v35 auto-RLS event trigger `auto_rls_on_create_table` fires on `ddl_command_end` for `WHEN TAG IN ('CREATE TABLE','CREATE TABLE AS','SELECT INTO')` running `ALTER TABLE … ENABLE ROW LEVEL SECURITY` on new `public.*` tables (no FORCE) + one-time backfill on every existing `public.*` base table whose comment doesn't match `^GBRAIN:RLS_EXEMPT\s+reason=\S.{3,}` (per-table failure aborts the offending CREATE TABLE; no EXCEPTION wrap; PGLite no-op via `sqlFor.pglite: ''`; breaking change: intentionally-RLS-off public tables need the GBRAIN:RLS_EXEMPT comment before upgrade); v40 `pages_emotional_weight` (`pages.emotional_weight REAL NOT NULL DEFAULT 0.0`, column-only metadata-only); v46 `mcp_request_log_params_jsonb_normalize` (`UPDATE ... SET params = params::text::jsonb WHERE jsonb_typeof(params) = 'string'`, idempotent); v60-v65 six-migration chain wiring source-scoping into `oauth_clients` — v60 (`oauth_clients_source_id_fk`: `source_id TEXT` NULL→`'default'` backfill + FK to `sources(id) ON DELETE SET NULL`), v61 (`federated_read TEXT[] NOT NULL DEFAULT '{}'`), v62 (explicit-CASE backfill so `source_id IS NULL` → `'{}'`), v63 (fail-loud check every row's source_id is in its federated_read array), v64 (FK flipped to `ON DELETE RESTRICT`), v65 (GIN index for array-containment); v68 `eval_candidates_embedding_column` (`eval_candidates.embedding_column TEXT NULL` per-row provenance for `gbrain eval replay` to reproduce the same retrieval space; NULL-tolerant); v108 `pages_embedding_signature` (`pages.embedding_signature TEXT NULL` = `<provider:model>:<dims>` stamped via `setPageEmbeddingSignature`; GRANDFATHER — stale predicate is `embedding_signature IS NOT NULL AND embedding_signature <> $current` so NULL is NEVER stale and upgrade never re-embeds the whole corpus; no index; metadata-only); v109 `sources_newest_content_at` (`sources.newest_content_at TIMESTAMPTZ` durable newest-COMMIT HEAD committer time written by `writeSyncAnchor`, read by the REMOTE staleness path instead of shelling to git; fresh-install column in `src/schema.sql`, generated into both blobs, plus a bootstrap probe); v110 `page_aliases` (`(id, source_id, alias_norm, slug, ...)` with `UNIQUE (source_id, alias_norm, slug)` + lookup indexes on `(source_id, alias_norm)` and `(source_id, slug)`; `alias_norm` is `normalizeAlias()` output so WRITE/READ key on the same form; also in `src/core/pglite-schema.ts`); v111 `search_telemetry_rank1_columns` (`ADD COLUMN IF NOT EXISTS` on both engines: `sum_rank1_score`, `count_rank1`, three buckets `rank1_lt_solid`/`rank1_solid`/`rank1_high` on `search_telemetry` — aggregate not per-query rows so rank-1 median drift is bounded-growth; ALTERs right after v57 which created the table); v114 `links_link_source_check_kebab_regex` (opens `link_source` from the closed allowlist to a kebab-case format gate `^[a-z][a-z0-9]*(-[a-z0-9]+)*$` + `char_length<=64`; Postgres branch uses `NOT VALID` + `VALIDATE CONSTRAINT` with `transaction:false`, PGLite plain DROP+ADD; existing built-ins all satisfy the regex so VALIDATE never fails on existing data); v116 `code_edges_source_backfill_and_callee_index` (idempotent: backfills NULL `code_edges_symbol`/`code_edges_chunk` `source_id` from each edge's `from_chunk` page — a NULL never matches a scoped `AND source_id = …` filter, so scoped `code-callers`/`code-callees` would return 0 rows on multi-source brains — plus plain `CREATE INDEX` on `from_symbol_qualified` for both edge tables, which had no index and seq-scanned per BFS node); v129 `dream_verdicts_triage_v1_columns` (additive `ADD COLUMN IF NOT EXISTS` widening `dream_verdicts` into a scored triage record — `score`, `content_type`, `segments`, `entities`, `model`, `triage_version`; legacy rows keep `score` NULL and read as cache misses, re-judged once; no backfill, no index; same SQL on both engines since `dream_verdicts` is migration-created on PGLite too, so the columns take the COLUMN_EXEMPTIONS route in `test/schema-bootstrap-coverage.test.ts` rather than bootstrap probes); v143 `dream_verdicts_ttl` (30-day `expires_at` TTL: nullable `ADD COLUMN` + `SET DEFAULT` run BEFORE the `judged_at`-derived backfill — statement order is load-bearing so a legacy writer racing the upgrade window picks up the default instead of inserting a NULL that would fail `SET NOT NULL` on every retry; on Postgres the schema blob's `dream_verdicts_expires_idx` forward-references the column, so `forward-reference-bootstrap.ts` probes + ALTERs it before the blob replays, and both engines' `getDreamVerdict` read predicate is NULL-tolerant — `expires_at IS NULL OR expires_at > now()` — so a pre-backfill row reads as a hit instead of silently re-judging the corpus). Three shape-keyed self-heals run on EVERY `runMigrations` pass, including the no-pending early-return path, because a merge-renumbered migration or a drifted restore can leave the version counter past a schema change while the live shape stays old: `repairTimelineDedupIndex` (`timeline_dedup_index`, see `timeline-dedup-repair.ts`) and `repairPagesUpsertArbiter` (`pages_source_slug_key`, see `pages-upsert-arbiter.ts`) are not version-gated at all; `repairLinkSourceCheck` (`links_link_source_check`, see `link-source-check-repair.ts`) runs only when the ledger is already >= `LINK_SOURCE_GATE_MIGRATION_VERSION` (114), because below it the pending loop replays v114 itself (running the repair first would rewrite the constraint twice, and a pre-v11 brain has no `link_source` column). All three are best-effort + idempotent; `doctor` surfaces each drift independently. `retry-matcher.ts` and `timeline-dedup-repair.ts` are static dependencies because `runMigrations()` executes from live engine initialization; the engine dynamic-import guard scans this file with both engine implementations. v95: `pages_dedup_partial_index` adds `CREATE INDEX pages_dedup_idx ON pages (source_id, content_hash) WHERE deleted_at IS NULL`. Postgres uses `CREATE INDEX CONCURRENTLY` with `transaction: false` + pre-drops any invalid remnant; PGLite uses plain `CREATE INDEX`. Powers `findDuplicatePage` hot path (O(log n) instead of O(n)). v74 `mcp_spend_log` uses BTREE on `(client_id, created_at)` + `(token_name, created_at)` — `date_trunc('day', TIMESTAMPTZ)` is NOT IMMUTABLE so can't appear in index expressions; a `created_at` range scan covers the per-day rollup. v75 `embedding_multimodal_column` is column-only (no HNSW index — deferred to post-reindex per pgvector best practice). Every pass (including one with nothing pending) ends with `page-state/revision-backfill-schema.ts:resumePageRevisionBackfill` while `pages.knowledge_revision` is nullable (#5216): the page-state schema adds `sources.incarnation` and `pages.knowledge_revision` nullable with a separate default (no volatile-default table rewrite on replay; an empty `pages` is constrained at once), rows are backfilled in committed id batches with a config cursor (`page_state.revision_backfill`), a failing row is isolated and retried at most three passes, each update grants only its rows' sources to the managed writer guard (`gbrain.write_sources`, transaction-local), and the column becomes NOT NULL via CHECK NOT VALID → VALIDATE → SET NOT NULL. With the schema version current no ordinary command runs a pass, so `gbrain apply-migrations --force-schema` (`REVISION_BACKFILL_RESUME_COMMAND`) resumes it; `readRevisionBackfillStatus` feeds doctor `revision_backfill` (`src/commands/doctor/checks/revision-backfill.ts`: ok when NOT NULL, warn with the pending count, the failed rows by page and the resume command, or the `repair orphan-children` preview when only spent rows remain). The revision trigger handles a NULL old revision without reading bodies; snapshots report such a row's revision as `backfill_pending` and `assertPageRevision` refuses revision-bound writes with `revision_backfill_pending` (`page-revision-backfill-5216.test.ts`).
Size ceiling: `scripts/module-size-limits.tsv` (per-change raise history: `git log -p` on that file). The runner (ordering, retry, verify, repair-handler hooks and the static helper imports engine-live paths require) has a plain ratchet ceiling; migrations no longer live in this file.
- `src/core/pglite-embedded-assets.ts` + `src/core/pglite-embedded-asset-paths.ts` — PGLite runtime-asset supply for every run mode (compiled binary, source checkout, bun-global install). `pglite-embedded-asset-paths.ts` is the bundler ANCHOR: five literal `with { type: 'file' }` imports of the wasm/data/extension-tarball assets via repo-relative node_modules paths (the package's `exports` map hides `./dist/*`) — keep the specifiers literal and byte-stable, an expression or indirection silently stops the bytes embedding and the compiled binary falls into the Bun-vfs ENOENT failure. `resolvePgliteAssetPaths()` in `pglite-embedded-assets.ts` is the tiered resolver: tier 1 dynamically `import()`s the anchor (the rejection under a hoisted install — bun-global upgrades dedupe `@electric-sql/pglite` to the global root, making the anchor's specifiers unresolvable — is EXPECTED and routes to tier 2, which is why the anchor is not a static import); tier 2 derives the dist dir via module resolution of `@electric-sql/pglite` (`import.meta.resolve` then `createRequire` — the SAME specifier the engine imports, so assets can never come from a different pglite copy than the loaded JS); tier 3 throws one actionable error naming everything tried, with the canonical GitHub reinstall command (never the squatted npm name; README install warning). `getEmbeddedPgliteOptions()` memoizes one build per process and hands PGLite compiled `WebAssembly.Module`s + fs-bundle Blob + `vector`/`pg_trgm` extensions via `PGliteOptions` (the tarballs are gunzipped and untarred in memory, and `lazyExtension` writes their files into PGLite's filesystem in the extension's `init`, after the backend starts, so postgres loads each `.so` on first use instead of PGLite preloading both on every open, about 30 ms; `readExtensionFiles` refuses any entry that is not a file or directory), plus `startParams` = PGLite's defaults then `PGLITE_START_PARAM_OVERRIDES` (no parallel maintenance workers, `max_wal_size=8GB`: an HNSW build fits the WASM heap, its WAL under the checkpoint trigger). `withSharedBuffers` appends `-c shared_buffers=<size>` when `EngineConfig.pglite_shared_buffers` is set: `connectEngineForServe` sets `ONE_SHOT_READ_SHARED_BUFFERS` (32MB) for a one-shot read-scope CLI process (shared op path, `gbrain call <read op>`, `search`, `sources list`), because the backend zero-fills the whole pool at start (about 55 ms for the 128MB default) and one read never fills it; serve and writes keep the default. The package itself is a type-only import plus one lazy `await import('@electric-sql/pglite')` inside `build()` after the resolver ran: the module must load without the package, or a missing install dies with the raw "Cannot find module" before the tier-3 sentence (#6512). Pinned by `test/pglite-embedded-assets.test.ts` + `test/pglite-hoisted-install.test.ts` (`bun add -g`-shaped hoisted layout, spawned with `bun --no-install` so script auto-install cannot mask a missing package).
diff --git a/docs/guides/planner-stats.md b/docs/guides/planner-stats.md
index a4d5b8d04d..b146f9bc4c 100644
--- a/docs/guides/planner-stats.md
+++ b/docs/guides/planner-stats.md
@@ -30,6 +30,19 @@ default; Postgres brains are unaffected (autovacuum owns statistics there).
consumer is idle;
- the full ANALYZE that import and sync already run at the end resets every
table's pending count.
+- A new index on an expression (for example `lower(title)`) has no statistics
+ of its own until its whole table is analyzed; a column-list ANALYZE skips it.
+ Schema migrations analyze the table right after they build an index
+ (`building <index> on ~N rows, then analyzing <table>`). If that ANALYZE
+ fails, the migration still completes with the valid index and prints a
+ warning naming `gbrain repair planner-stats --apply`. A brain whose index
+ was built before this (an upgraded brain with the v240 name-lookup indexes:
+ a 50-name `entity names` batch on a 55k-page brain took 5.4 s instead of
+ 1.2 s) gets the statistics at the next maintenance point above (import,
+ managed sync, link drain, dream cycle, idle consumer); a search's first read
+ never runs this check. An expression whose values are all null still gets
+ statistics, and an empty table or a partial index matching no rows is not
+ flagged.
- If a table's last ANALYZE took longer than `planner.first_read_budget_ms`
(default 2000), a read does not wait for it: the table is analyzed right after
the read answers.
@@ -37,11 +50,23 @@ default; Postgres brains are unaffected (autovacuum owns statistics there).
## Check and repair
```bash
-gbrain doctor # planner_stats_stale names each stale table
-gbrain repair planner-stats # preview: stale tables and pending row counts
+gbrain doctor # planner_stats_stale names each stale table and expression index
+gbrain repair planner-stats # preview: stale tables, pending row counts, indexes without statistics
gbrain repair planner-stats --apply # ANALYZE them now (works with auto-analyze off)
```
+Doctor reports an expression index without statistics on its own line,
+`expression index <name> (on <table>) has no statistics`, separate from the
+row-delta count. On both engines the check covers the hot tables above and
+skips an index whose statistics the database role cannot see (unknown, not
+absent).
+
+On Postgres nothing collects an existing index's statistics automatically:
+autovacuum analyzes a table only after 10% of its rows change, so a quiet
+brain keeps the gap. Doctor warns, and an operator runs
+`gbrain repair planner-stats --apply` on the brain host (one whole-table
+ANALYZE per table, 60 s statement and 2 s lock timeout).
+
On Postgres, `planner_stats_stale` reads `pg_stat_user_tables` and warns only
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
diff --git a/src/commands/doctor/checks/planner-stats.ts b/src/commands/doctor/checks/planner-stats.ts
index 42bf72e5ae..b8974420e7 100644
--- a/src/commands/doctor/checks/planner-stats.ts
+++ b/src/commands/doctor/checks/planner-stats.ts
@@ -17,8 +17,16 @@
* 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.
+ *
+ * Both engines also report each expression index on a hot table that has no
+ * statistics under its own name (`readExpressionIndexesWithoutStats`, lhf wave 2
+ * item 6), with its own reason: no whole-table ANALYZE since the index was
+ * built. PGLite's next maintenance pass analyzes the table; on Postgres
+ * autovacuum waits for 10% of the rows to change, so the operator runs the
+ * repair.
*/
-import { plannerAutoAnalyzeEnabled, PLANNER_STATS_REPAIR_COMMAND, readPlannerTableStates } from '../../../core/planner-stats.ts';
+import { plannerAutoAnalyzeEnabled, PLANNER_STATS_REPAIR_COMMAND, readExpressionIndexesWithoutStats, readPlannerTableStates,
+ type ExpressionIndexGap } 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';
@@ -38,8 +46,11 @@ async function runPlannerStats(ctx: DoctorContext): Promise<Check[]> {
const autoAnalyze = engine.kind === 'pglite' ? await plannerAutoAnalyzeEnabled(engine) : null;
const stale = tables.filter(t => t.stale);
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) {
+ const gaps = await readExpressionIndexesWithoutStats(engine);
+ const details = { engine: engine.kind, auto_analyze: autoAnalyze, checked: tables.map(t => t.table), stale, missing_search_statistics: missing,
+ expression_indexes_without_statistics: gaps, fix: PLANNER_STATS_REPAIR_COMMAND };
+ const expression = expressionIndexText(gaps, engine.kind, autoAnalyze);
+ if (stale.length === 0 && missing.length === 0 && gaps.length === 0) {
checks.push({ name: 'planner_stats_stale', status: 'ok', message: `Planner statistics are fresh on ${tables.length} hot tables.`, details });
return checks;
}
@@ -49,11 +60,15 @@ async function runPlannerStats(ctx: DoctorContext): Promise<Check[]> {
+ '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,
+ message: `${why}${listed ? ` Also stale: ${listed}.` : ''}${expression ? ` Also: ${expression}` : ''} 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;
}
+ if (stale.length === 0) {
+ checks.push({ name: 'planner_stats_stale', status: 'warn', message: `${expression} Fix on the brain host: ${PLANNER_STATS_REPAIR_COMMAND}.`, details });
+ 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.'
@@ -62,7 +77,7 @@ async function runPlannerStats(ctx: DoctorContext): Promise<Check[]> {
? ' Automatic ANALYZE is off (planner.auto_analyze=false or GBRAIN_PLANNER_AUTO_ANALYZE=0); to turn it back on: gbrain config set planner.auto_analyze true.'
: '';
checks.push({ name: 'planner_stats_stale', status: 'warn',
- message: `Stale planner statistics: ${listed}. ${why} Fix on the brain host: ${PLANNER_STATS_REPAIR_COMMAND}.${off}`, details });
+ message: `Stale planner statistics: ${listed}. ${why}${expression ? ` Also: ${expression}` : ''} Fix on the brain host: ${PLANNER_STATS_REPAIR_COMMAND}.${off}`, details });
} catch (err) {
checks.push({ name: 'planner_stats_stale', status: 'warn',
message: `Planner statistics could not be read: ${err instanceof Error ? err.message : String(err)}. Freshness is unknown; preview the repair with: gbrain repair planner-stats` });
@@ -70,4 +85,17 @@ async function runPlannerStats(ctx: DoctorContext): Promise<Check[]> {
return checks;
}
+/** The expression-index sentence: its own reason, never a row delta, and who runs the ANALYZE on this engine. */
+function expressionIndexText(gaps: ExpressionIndexGap[], kind: string, autoAnalyze: boolean | null): string {
+ if (gaps.length === 0) return '';
+ const names = gaps.map(g => `expression index ${g.index} (on ${g.table}) has no statistics`).join('; ');
+ const who = kind === 'pglite'
+ ? autoAnalyze === false
+ ? 'Automatic ANALYZE is off (planner.auto_analyze=false), so it stays this way until the repair runs.'
+ : 'The next maintenance pass (cycle, idle tick or import) analyzes the table; the repair does it now.'
+ : 'Autovacuum does not analyze the table until 10% of its rows change, so an operator runs the repair.';
+ return `${names}. No whole-table ANALYZE has run since the index was built (a column-list ANALYZE skips index expressions), so the planner estimates its lookups `
+ + `with default selectivity (a 50-name entity names batch on a 55k-page brain: 5.4 s instead of 1.2 s). ${who}`;
+}
+
export const plannerStatsEntry: DoctorEntry = { name: 'planner_stats_stale', emits: ['planner_stats_stale'], run: runPlannerStats };
diff --git a/src/core/planner-stats.ts b/src/core/planner-stats.ts
index d16da7707e..a8de4a871b 100644
--- a/src/core/planner-stats.ts
+++ b/src/core/planner-stats.ts
@@ -8,7 +8,9 @@
* tables in `planner_stats_deltas`, transactionally and durably. A table is
* stale when the rows modified since its last ANALYZE exceed
* max(500, 10% of pg_class.reltuples), or when it has rows but no pg_stats
- * row. `maybeRefreshPlannerStats` ANALYZEs the stale tables and publishes a
+ * row. Maintenance passes (every reason but a search's first read) also
+ * analyze a table with an expression index that has no statistics.
+ * `maybeRefreshPlannerStats` ANALYZEs the stale tables and publishes a
* per-table watermark: the highest delta id it read before the ANALYZE, so a
* modification committed between that read and the publication stays pending.
*
@@ -20,7 +22,9 @@
* ANALYZE, then watermarks for every table). `planner.auto_analyze=false`
* (env GBRAIN_PLANNER_AUTO_ANALYZE) disables all of them; doctor
* `planner_stats_stale` and `gbrain repair planner-stats` keep working.
- * Postgres: every function here is a no-op (autovacuum owns statistics).
+ * Postgres: every refresh here is a no-op (autovacuum owns statistics);
+ * doctor and repair read autovacuum's counters and the expression-index probe,
+ * and an operator runs `gbrain repair planner-stats --apply`.
*/
import type { BrainEngine } from './engine.ts';
import { PLANNER_STATS_TABLES, type PlannerStatsTable } from './planner-stats-schema.ts';
@@ -129,6 +133,36 @@ export async function readPlannerStatsState(engine: BrainEngine): Promise<Planne
});
}
+/** An index on an expression of a hot table whose expression has no pg_stats row (lhf wave 2 item 6). */
+export interface ExpressionIndexGap { index: string; table: PlannerStatsTable }
+
+/**
+ * Expression indexes on the hot tables with entries (pg_class.reltuples > 0)
+ * but no pg_stats row under the index's own name: built after the table's last
+ * whole-table ANALYZE (the v240 name-lookup indexes on an upgraded brain; a
+ * column-list ANALYZE skips index expressions), so the planner
+ * prices their lookups with default selectivity. ANALYZE of the whole table
+ * clears it; an all-null expression still gets a row (null_frac 1), and an
+ * empty table or a partial index matching no rows has reltuples 0, so neither
+ * stays flagged. Statistics this role cannot see (another owner's index) are
+ * unknown, not absent, and are left out. Both engines; maintenance, doctor and
+ * repair only, never a search's first read.
+ */
+export async function readExpressionIndexesWithoutStats(engine: BrainEngine): Promise<ExpressionIndexGap[]> {
+ const rows = await engine.executeRaw<{ index_name: string; table_name: PlannerStatsTable }>(
+ `SELECT ix.relname AS index_name, t.relname AS table_name
+ FROM pg_index i
+ JOIN pg_class t ON t.oid = i.indrelid
+ JOIN pg_class ix ON ix.oid = i.indexrelid
+ WHERE t.relnamespace = to_regnamespace(current_schema()) AND t.relname = ANY($1::text[])
+ AND i.indexprs IS NOT NULL AND i.indisvalid AND ix.reltuples > 0
+ AND has_table_privilege(ix.oid, 'SELECT')
+ AND NOT EXISTS (SELECT 1 FROM pg_stats s WHERE s.schemaname = current_schema() AND s.tablename = ix.relname)
+ ORDER BY array_position($1::text[], t.relname::text), ix.relname`,
+ [[...PLANNER_STATS_TABLES]]);
+ return rows.map(row => ({ index: row.index_name, table: row.table_name }));
+}
+
/**
* Postgres variant for doctor and repair: autovacuum's own counters. A table
* is stale when `n_mod_since_analyze` exceeds the same threshold and neither
@@ -234,7 +268,9 @@ export async function beginFullAnalyze(engine: BrainEngine): Promise<() => Promi
/**
* Check the hot tables and ANALYZE the stale ones (PGLite, when
- * `planner.auto_analyze` is on). Checks are throttled to one per 2 s per
+ * `planner.auto_analyze` is on). Every reason but `first_read` also analyzes a
+ * table carrying an expression index without statistics
+ * (`readExpressionIndexesWithoutStats`), so a search never pays that probe. Checks are throttled to one per 2 s per
* engine unless `throttle: false` (the page-count cadence of import and
* managed sync). With `budgetMs`, a stale table whose last ANALYZE took longer
* is returned in `deferred` instead of being analyzed now.
@@ -254,7 +290,8 @@ export async function maybeRefreshPlannerStats(engine: BrainEngine, reason: Plan
const run = (async (): Promise<PlannerRefreshResult> => {
const tables = await readPlannerStatsState(engine);
if (!tables) return { ...result, skipped: 'unavailable' };
- const stale = tables.filter(t => t.stale);
+ const gaps = reason === 'first_read' ? [] : await readExpressionIndexesWithoutStats(engine);
+ const stale = tables.filter(t => t.stale || gaps.some(g => g.table === t.table));
const now = stale.filter(t => opts.budgetMs === undefined || (t.last_analyze_ms ?? 0) <= opts.budgetMs);
result.deferred = stale.filter(t => !now.includes(t)).map(t => t.table);
result.analyzed = await analyzePlannerTables(engine, now.map(t => t.table), reason, new Map(stale.map(t => [t.table, t.pending])));
diff --git a/src/core/repair/planner-stats.ts b/src/core/repair/planner-stats.ts
index 67b27343a6..b7ac310216 100644
--- a/src/core/repair/planner-stats.ts
+++ b/src/core/repair/planner-stats.ts
@@ -10,9 +10,15 @@
* 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).
+ *
+ * Both engines: a hot table carrying an expression index without statistics
+ * (`readExpressionIndexesWithoutStats`, lhf wave 2 item 6) is planned too,
+ * with the index named in its action; the same whole-table ANALYZE collects
+ * it. On Postgres this repair is the recovery (autovacuum waits for 10% of the
+ * rows to change), run by an operator.
*/
import { PLANNER_STATS_TABLES, type PlannerStatsTable } from '../planner-stats-schema.ts';
-import { readPlannerTableStates, repairPlannerTable } from '../planner-stats.ts';
+import { readExpressionIndexesWithoutStats, readPlannerTableStates, repairPlannerTable } from '../planner-stats.ts';
import { missingSearchStatistics, refreshProjectionStatistics } from '../search/projection-statistics.ts';
import type { RepairHandler, RepairItem } from './core.ts';
@@ -28,9 +34,15 @@ export const plannerStatsRepair: RepairHandler = {
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'})`,
+ const gaps = await readExpressionIndexesWithoutStats(engine);
+ const reasons = (table: PlannerStatsTable) => {
+ const t = tables.find(state => state.table === table);
+ const stale = t?.stale ? [`${t.pending} rows changed since ANALYZE, threshold ${Math.round(t.threshold)}${t.has_stats ? '' : ', no statistics'}`] : [];
+ return stale.concat(gaps.filter(g => g.table === table).map(g => `expression index ${g.index} has no statistics`));
+ };
+ const items: RepairItem[] = search.concat(PLANNER_STATS_TABLES.filter(table => reasons(table).length > 0).map(table => ({
+ cursor: { phase: 0, id: PLANNER_STATS_TABLES.indexOf(table) + 1 }, source_id: '(brain)', slug: table, chars: 0,
+ action: `analyze (${reasons(table).join('; ')})`,
})));
return { items, residuals: {} };
},
diff --git a/src/core/schema-migrations/helpers.ts b/src/core/schema-migrations/helpers.ts
index c01509d2c9..56562fae8e 100644
--- a/src/core/schema-migrations/helpers.ts
+++ b/src/core/schema-migrations/helpers.ts
@@ -79,17 +79,21 @@ export type OnlineIndexOutcome = 'present' | 'created' | 'rebuilt' | 'building';
* EXISTS` on a dedicated connection under the session's startup timeouts, then
* confirms the index is valid. Callers build one index at a time;
* a lock timeout leaves an INVALID index that the next call drops and rebuilds.
+ * After a create or rebuild, `analyzeAfterIndexBuild` refreshes the table's
+ * planner statistics (lhf wave 2 item 6).
*/
export async function buildIndexOnline(
engine: BrainEngine,
version: number,
index: { name: string; table: string; sql: string },
- opts: { notice?: (line: string) => void } = {},
+ opts: { notice?: (line: string) => void; rebuild?: string } = {},
): Promise<OnlineIndexOutcome> {
if (engine.kind !== 'postgres') {
const [row] = await engine.executeRaw<{ present: boolean }>('SELECT to_regclass($1) IS NOT NULL AS present', [index.name]);
if (row?.present) return 'present';
+ opts.notice?.(` building ${index.name} on ~${await tableRows(engine, index.table)} rows, then analyzing ${index.table}\n`);
await engine.runMigration(version, index.sql);
+ await analyzeAfterIndexBuild(engine, index);
return 'created';
}
const [row] = await engine.executeRaw<{ valid: boolean; building: boolean }>(
@@ -101,16 +105,54 @@ export async function buildIndexOnline(
if (row?.valid) return 'present';
if (row?.building) return 'building';
if (row) await dropInvalidConcurrentIndex(engine, version, index.name);
- const [size] = await engine.executeRaw<{ rows: number }>(
- 'SELECT GREATEST(reltuples, 0)::bigint AS rows FROM pg_class WHERE oid = to_regclass($1)', [index.table]);
- opts.notice?.(` building ${index.name} on ~${Number(size?.rows ?? 0)} rows; this can take minutes; it is safe to leave running; `
- + 'if interrupted, gbrain doctor names the rebuild command\n');
+ opts.notice?.(` building ${index.name} on ~${await tableRows(engine, index.table)} rows, then analyzing ${index.table}; `
+ + 'this can take minutes; it is safe to leave running; if interrupted, gbrain doctor names the rebuild command\n');
// No session SET: a reservation can fall back to a transaction-pooled connection, where a SET or RESET
// reaches another client's backend. The build runs under the session's startup timeouts; one that times
// out leaves an INVALID index, which the next call drops and rebuilds.
await engine.withReservedConnection(conn => conn.executeRaw(index.sql.replace('CREATE INDEX', 'CREATE INDEX CONCURRENTLY')), { selfContained: true });
// IF NOT EXISTS also skips an INVALID index a concurrent caller's failed build left behind.
const [built] = await engine.executeRaw<{ valid: boolean }>('SELECT indisvalid AS valid FROM pg_index WHERE indexrelid = to_regclass($1)', [index.name]);
- if (!built?.valid) throw new Error(`Index ${index.name} is not valid after its concurrent build; rerun: gbrain repair request-indexes --apply`);
+ if (!built?.valid) {
+ const rebuild = opts.rebuild ?? (index.table === 'persistence_requests' ? 'gbrain repair request-indexes --apply' : 'gbrain apply-migrations --yes');
+ throw new Error(`Index ${index.name} is not valid after its concurrent build; rerun: ${rebuild}`);
+ }
+ await analyzeAfterIndexBuild(engine, index);
return row ? 'rebuilt' : 'created';
}
+
+async function tableRows(engine: BrainEngine, table: string): Promise<number> {
+ const [size] = await engine.executeRaw<{ rows: number }>(
+ 'SELECT GREATEST(reltuples, 0)::bigint AS rows FROM pg_class WHERE oid = to_regclass($1)', [table]);
+ return Number(size?.rows ?? 0);
+}
+
+/** The hot tables `gbrain repair planner-stats` analyzes (PLANNER_STATS_TABLES; this leaf does not import planner-stats). */
+const PLANNER_REPAIR_TABLES = new Set(['pages', 'links', 'facts', 'takes', 'content_chunks', 'timeline_entries']);
+
+/**
+ * lhf wave 2 item 6: a new index on an expression has no planner statistics until
+ * its table is analyzed, and PGLite runs no autovacuum (a 50-name `entity names`
+ * batch after v240 on a 55k-page PGLite brain: 5.4 s, 1.2 s after ANALYZE pages).
+ * Best effort: one whole-table ANALYZE (a column list collects no index
+ * statistics), Postgres bounded by a 60 s statement and 2 s lock timeout. A
+ * failure prints the command that finishes the job and never fails the build of
+ * a valid index; doctor `planner_stats_stale` keeps reporting the index.
+ */
+export async function analyzeAfterIndexBuild(engine: BrainEngine, index: { name: string; table: string }): Promise<boolean> {
+ try {
+ await engine.transaction(async tx => {
+ if (engine.kind === 'postgres') {
+ await tx.executeRaw("SET LOCAL statement_timeout = '60s'");
+ await tx.executeRaw("SET LOCAL lock_timeout = '2s'");
+ }
+ await tx.executeRaw(`ANALYZE ${index.table}`);
+ });
+ return true;
+ } catch (err) {
+ const fix = PLANNER_REPAIR_TABLES.has(index.table) ? 'gbrain repair planner-stats --apply' : `ANALYZE ${index.table} as the table owner`;
+ console.warn(` [warn] ${index.name} is built and valid, but ANALYZE ${index.table} failed `
+ + `(${err instanceof Error ? err.message : String(err)}); the planner has no statistics for it yet. Run on the brain host: ${fix}`);
+ return false;
+ }
+}
diff --git a/test/e2e/planner-stats-postgres.test.ts b/test/e2e/planner-stats-postgres.test.ts
index 1d6e2db51b..5c23dc2b13 100644
--- a/test/e2e/planner-stats-postgres.test.ts
+++ b/test/e2e/planner-stats-postgres.test.ts
@@ -5,10 +5,18 @@
* maybeRefreshPlannerStats never runs. Doctor planner_stats_stale reads
* pg_stat_user_tables.n_mod_since_analyze, and repair planner-stats ANALYZEs
* the stale table with bounded timeouts.
+ *
+ * lhf wave 2 item 6: doctor names an expression index without statistics with
+ * its own reason, the repair (operator-driven on Postgres) clears it, a role
+ * that cannot see the index's statistics gets no warning, and buildIndexOnline
+ * analyzes after a build; a failed ANALYZE warns and keeps the valid index.
*/
import { describe, test, expect, beforeAll, afterAll } from 'bun:test';
import { setupDB, teardownDB, hasDatabase, getEngine } from './helpers.ts';
-import { maybeRefreshPlannerStats, readPostgresPlannerStats } from '../../src/core/planner-stats.ts';
+import { maybeRefreshPlannerStats, readExpressionIndexesWithoutStats, readPostgresPlannerStats } from '../../src/core/planner-stats.ts';
+import { buildIndexOnline } from '../../src/core/schema-migrations/helpers.ts';
+import { PAGES_NAME_LOOKUP_INDEXES } from '../../src/core/schema-migrations/v240-pages-name-lookup-indexes.ts';
+import type { BrainEngine } from '../../src/core/engine.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';
@@ -79,4 +87,110 @@ d('planner stats on Postgres', () => {
await engine.executeRaw('ALTER TABLE facts RESET (autovacuum_enabled)');
}
});
+
+ describe('item 6: expression index statistics', () => {
+ const TITLE_INDEX = PAGES_NAME_LOOKUP_INDEXES[0];
+ const repairCtx = () => ({ engine: getEngine(), logger: { info() {}, warn() {}, error() {} } }) as never;
+ const hasIndexStats = async () => (await getEngine().executeRaw<{ has: boolean }>(
+ 'SELECT EXISTS (SELECT 1 FROM pg_stats WHERE schemaname = current_schema() AND tablename = $1) AS has', [TITLE_INDEX.name]))[0]!.has;
+ /** The pre-item-6 upgrade: pages analyzed, then the index built with no ANALYZE after it. */
+ async function unanalyzedIndex() {
+ const engine = getEngine();
+ await engine.executeRaw(`DROP INDEX IF EXISTS ${TITLE_INDEX.name}`);
+ await engine.executeRaw('ANALYZE pages');
+ await engine.executeRaw(TITLE_INDEX.sql);
+ }
+ async function captureWarnings<T>(fn: () => Promise<T>): Promise<{ out: T; text: string }> {
+ const lines: string[] = [];
+ const warn = console.warn;
+ console.warn = (...args: unknown[]) => { lines.push(args.map(String).join(' ')); };
+ try { return { out: await fn(), text: lines.join('\n') }; } finally { console.warn = warn; }
+ }
+
+ beforeAll(async () => {
+ const engine = getEngine();
+ await engine.executeRaw('ALTER TABLE pages SET (autovacuum_enabled = false)');
+ await engine.executeRaw(
+ `INSERT INTO pages (source_id, slug, type, title) SELECT 'default', 'people/item6-' || g, 'person', 'Person Example ' || g FROM generate_series(1, 600) g`);
+ });
+ afterAll(async () => {
+ const engine = getEngine();
+ await engine.executeRaw("DELETE FROM pages WHERE slug LIKE 'people/item6-%'");
+ await engine.executeRaw('ALTER TABLE pages RESET (autovacuum_enabled)');
+ await engine.executeRaw('ANALYZE pages');
+ });
+
+ test('doctor names the index with its own reason; the operator repair clears it', async () => {
+ await unanalyzedIndex();
+ expect(await readExpressionIndexesWithoutStats(getEngine())).toEqual([{ index: TITLE_INDEX.name, table: 'pages' }]);
+ const check = await doctor();
+ expect(check.status).toBe('warn');
+ expect(check.message).toContain(`expression index ${TITLE_INDEX.name} (on pages) has no statistics`);
+ expect(check.message).toContain('an operator runs the repair');
+ expect(check.message).toContain('gbrain repair planner-stats --apply');
+ expect(check.message).not.toContain('pages (0 rows changed');
+
+ const plan = await plannerStatsRepair.plan(getEngine(), { brain_id: 'host', source_ids: [] }, null);
+ const item = plan.items.find(i => i.slug === 'pages')!;
+ expect(item.action).toContain(`expression index ${TITLE_INDEX.name} has no statistics`);
+ expect(await plannerStatsRepair.apply(repairCtx(), item)).toBe(true);
+ expect(await hasIndexStats()).toBe(true);
+ expect(await readExpressionIndexesWithoutStats(getEngine())).toEqual([]);
+ expect((await doctor()).message).not.toContain('expression index');
+ });
+
+ test('a role that cannot see the index statistics reads them as unknown, not absent', async () => {
+ await unanalyzedIndex();
+ const engine = getEngine();
+ await engine.executeRaw("DO $$ BEGIN IF NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'gbrain_item6_reader') THEN CREATE ROLE gbrain_item6_reader; END IF; END $$");
+ await engine.executeRaw('GRANT USAGE ON SCHEMA public TO gbrain_item6_reader');
+ await engine.executeRaw('GRANT SELECT ON pages TO gbrain_item6_reader');
+ try {
+ const seen = await engine.transaction(async tx => {
+ await tx.executeRaw('SET LOCAL ROLE gbrain_item6_reader');
+ return readExpressionIndexesWithoutStats(tx);
+ });
+ expect(seen).toEqual([]);
+ expect(await readExpressionIndexesWithoutStats(engine)).toEqual([{ index: TITLE_INDEX.name, table: 'pages' }]);
+ } finally {
+ await engine.executeRaw('REVOKE ALL ON pages FROM gbrain_item6_reader');
+ await engine.executeRaw('REVOKE ALL ON SCHEMA public FROM gbrain_item6_reader');
+ await engine.executeRaw('DROP ROLE gbrain_item6_reader');
+ }
+ });
+
+ test('buildIndexOnline builds concurrently, prints the notice and analyzes the table', async () => {
+ await getEngine().executeRaw(`DROP INDEX IF EXISTS ${TITLE_INDEX.name}`);
+ const notices: string[] = [];
+ expect(await buildIndexOnline(getEngine(), 240, TITLE_INDEX, { notice: line => notices.push(line) })).toBe('created');
+ expect(notices.join('')).toContain(`building ${TITLE_INDEX.name} on ~`);
+ expect(notices.join('')).toContain('then analyzing pages');
+ expect(await hasIndexStats()).toBe(true);
+ });
+
+ test('a failed ANALYZE warns with the repair command and keeps the valid index', async () => {
+ await getEngine().executeRaw(`DROP INDEX IF EXISTS ${TITLE_INDEX.name}`);
+ await getEngine().executeRaw('ANALYZE pages');
+ const base = getEngine();
+ const failing = Object.create(base) as BrainEngine;
+ failing.transaction = (async (fn: (tx: BrainEngine) => Promise<unknown>) => base.transaction(async tx => {
+ const wrapped = Object.create(tx) as BrainEngine;
+ wrapped.executeRaw = (async (sql: string, params?: unknown[]) => {
+ if (/^ANALYZE\b/.test(sql)) throw Object.assign(new Error('canceling statement due to lock timeout'), { code: '55P03' });
+ return tx.executeRaw(sql, params as never);
+ }) as BrainEngine['executeRaw'];
+ return fn(wrapped);
+ })) as BrainEngine['transaction'];
+ const { out, text } = await captureWarnings(() => buildIndexOnline(failing, 240, TITLE_INDEX));
+ expect(out).toBe('created');
+ expect(text).toContain(`${TITLE_INDEX.name} is built and valid, but ANALYZE pages failed`);
+ expect(text).toContain('gbrain repair planner-stats --apply');
+ const [valid] = await base.executeRaw<{ valid: boolean }>('SELECT indisvalid AS valid FROM pg_index WHERE indexrelid = to_regclass($1)', [TITLE_INDEX.name]);
+ expect(valid!.valid).toBe(true);
+ expect(await readExpressionIndexesWithoutStats(base)).toEqual([{ index: TITLE_INDEX.name, table: 'pages' }]);
+ const plan = await plannerStatsRepair.plan(base, { brain_id: 'host', source_ids: [] }, null);
+ expect(await plannerStatsRepair.apply(repairCtx(), plan.items.find(i => i.slug === 'pages')!)).toBe(true);
+ expect(await readExpressionIndexesWithoutStats(base)).toEqual([]);
+ });
+ });
});
diff --git a/test/planner-stats-expression-index.test.ts b/test/planner-stats-expression-index.test.ts
new file mode 100644
index 0000000000..824edcfe1f
--- /dev/null
+++ b/test/planner-stats-expression-index.test.ts
@@ -0,0 +1,183 @@
+/**
+ * lhf wave 2 item 6: planner statistics after index builds. `buildIndexOnline`
+ * analyzes the table after it creates an index (best effort: a failed ANALYZE
+ * warns with the command and never fails the migration), and the F4b
+ * maintenance passes give an already-present expression index its statistics
+ * (`readExpressionIndexesWithoutStats`), never on a search's first read.
+ * In-memory PGLite ($0); Postgres doctor and repair are in
+ * test/e2e/planner-stats-postgres.test.ts.
+ */
+import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { __testing, analyzePlannerTables, maybeRefreshPlannerStats, readExpressionIndexesWithoutStats, readPlannerStatsState } from '../src/core/planner-stats.ts';
+import { DOCTOR_CHECK_REGISTRY } from '../src/commands/doctor/registry.ts';
+import { plannerStatsRepair } from '../src/core/repair/planner-stats.ts';
+import { runMigrations } from '../src/core/migrate.ts';
+import { LATEST_SCHEMA_VERSION } from '../src/core/schema-migrations/latest.generated.ts';
+import { PAGES_NAME_LOOKUP_INDEXES, v240 } from '../src/core/schema-migrations/v240-pages-name-lookup-indexes.ts';
+import type { DoctorContext } from '../src/commands/doctor/context.ts';
+import type { Check } from '../src/commands/doctor.ts';
+
+const TITLE_INDEX = PAGES_NAME_LOOKUP_INDEXES[0];
+const PAGES = 600;
+let engine: PGLiteEngine;
+
+async function hasIndexStats(name: string): Promise<boolean> {
+ const [row] = await engine.executeRaw<{ has: boolean }>('SELECT EXISTS (SELECT 1 FROM pg_stats WHERE tablename = $1) AS has', [name]);
+ return row!.has;
+}
+
+async function doctor(): Promise<Check> {
+ const entry = DOCTOR_CHECK_REGISTRY.find(e => e.name === 'planner_stats_stale')!;
+ const ctx = { engine, progress: { heartbeat() {}, start() {}, tick() {}, finish() {} } } as unknown as DoctorContext;
+ return ((await entry.run(ctx)) as Check[])[0]!;
+}
+
+/** The pre-item-6 upgrade: pages analyzed, then v240's index built with no ANALYZE after it. */
+async function upgradedBrainWithUnanalyzedIndex() {
+ await engine.executeRaw(`DROP INDEX IF EXISTS ${TITLE_INDEX.name}`);
+ await analyzePlannerTables(engine, ['pages'], 'repair');
+ await engine.executeRaw(TITLE_INDEX.sql);
+}
+
+async function captureStderr<T>(fn: () => Promise<T>): Promise<{ out: T; text: string }> {
+ const lines: string[] = [];
+ const write = process.stderr.write.bind(process.stderr);
+ const warn = console.warn;
+ process.stderr.write = ((chunk: string | Uint8Array) => { lines.push(String(chunk)); return true; }) as typeof process.stderr.write;
+ console.warn = (...args: unknown[]) => { lines.push(args.map(String).join(' ')); };
+ try {
+ return { out: await fn(), text: lines.join('') };
+ } finally {
+ process.stderr.write = write;
+ console.warn = warn;
+ }
+}
+
+/** The engine with every ANALYZE failing as a held lock would. */
+function failingAnalyze(base: PGLiteEngine): BrainEngine {
+ const fail = (sql: string) => { if (/^\s*ANALYZE\b/i.test(sql)) throw new Error('canceling statement due to lock timeout'); };
+ const wrap = (target: BrainEngine): BrainEngine => {
+ const wrapped = Object.create(target) as BrainEngine;
+ wrapped.executeRaw = (async (sql: string, ...rest: unknown[]) => { fail(sql); return (target.executeRaw as (...a: unknown[]) => unknown)(sql, ...rest); }) as BrainEngine['executeRaw'];
+ wrapped.transaction = (async (fn: (tx: BrainEngine) => Promise<unknown>, opts?: unknown) =>
+ (target.transaction as (f: unknown, o?: unknown) => Promise<unknown>)((tx: BrainEngine) => fn(wrap(tx)), opts)) as BrainEngine['transaction'];
+ return wrapped;
+ };
+ return wrap(base);
+}
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ await engine.executeRaw(
+ `INSERT INTO pages (source_id, slug, type, title) SELECT 'default', 'people/person-' || g, 'person', 'Person Example ' || g FROM generate_series(1, $1::int) g`,
+ [PAGES]);
+}, 60_000);
+
+afterAll(async () => {
+ await engine.disconnect();
+});
+
+beforeEach(async () => {
+ await engine.executeRaw("DELETE FROM config WHERE key LIKE 'planner.%'");
+ __testing.reset(engine);
+});
+
+describe('expression index statistics on an upgraded PGLite brain', () => {
+ test('a pre-existing v240 index with no statistics is flagged with its own reason, never as a row delta', async () => {
+ await upgradedBrainWithUnanalyzedIndex();
+ expect(await hasIndexStats(TITLE_INDEX.name)).toBe(false);
+ const pages = (await readPlannerStatsState(engine))!.find(t => t.table === 'pages')!;
+ expect(pages.stale).toBe(false);
+ expect(await readExpressionIndexesWithoutStats(engine)).toEqual([{ index: TITLE_INDEX.name, table: 'pages' }]);
+
+ const check = await doctor();
+ expect(check.status).toBe('warn');
+ expect(check.message).toContain(`expression index ${TITLE_INDEX.name} (on pages) has no statistics`);
+ expect(check.message).toContain('The next maintenance pass');
+ expect(check.message).toContain('gbrain repair planner-stats --apply');
+ expect(check.message).not.toContain('rows changed since ANALYZE');
+ });
+
+ test("a search's first read never runs the probe; the next maintenance pass gives the index statistics", async () => {
+ await upgradedBrainWithUnanalyzedIndex();
+ const statements: string[] = [];
+ const spy = Object.create(engine) as PGLiteEngine;
+ spy.executeRaw = (async (sql: string, params?: unknown[]) => { statements.push(sql); return engine.executeRaw(sql, params as never); }) as PGLiteEngine['executeRaw'];
+ const first = await maybeRefreshPlannerStats(spy, 'first_read', { throttle: false });
+ expect(first.analyzed).toEqual([]);
+ expect(statements.some(sql => sql.includes('indexprs'))).toBe(false);
+ expect(await hasIndexStats(TITLE_INDEX.name)).toBe(false);
+
+ const cycle = await maybeRefreshPlannerStats(engine, 'cycle');
+ expect(cycle.analyzed.map(a => a.table)).toEqual(['pages']);
+ expect(await hasIndexStats(TITLE_INDEX.name)).toBe(true);
+ expect(await readExpressionIndexesWithoutStats(engine)).toEqual([]);
+ expect((await doctor()).status).toBe('ok');
+ __testing.reset(engine);
+ expect((await maybeRefreshPlannerStats(engine, 'cycle')).analyzed).toEqual([]);
+ });
+
+ test('planner.auto_analyze=false leaves it to the repair, which names the index and clears it', async () => {
+ await upgradedBrainWithUnanalyzedIndex();
+ await engine.setConfig('planner.auto_analyze', 'false');
+ expect((await maybeRefreshPlannerStats(engine, 'cycle')).skipped).toBe('disabled');
+ expect((await doctor()).message).toContain('Automatic ANALYZE is off');
+
+ const plan = await plannerStatsRepair.plan(engine, { brain_id: 'host', source_ids: [] }, null);
+ const item = plan.items.find(i => i.slug === 'pages')!;
+ expect(item.action).toBe(`analyze (expression index ${TITLE_INDEX.name} has no statistics)`);
+ const ctx = { engine, logger: { info() {}, warn() {}, error() {} } } as never;
+ expect(await plannerStatsRepair.apply(ctx, item)).toBe(true);
+ expect(await hasIndexStats(TITLE_INDEX.name)).toBe(true);
+ expect((await plannerStatsRepair.plan(engine, { brain_id: 'host', source_ids: [] }, null)).items.map(i => i.slug)).not.toContain('pages');
+ });
+
+ test('all-null and empty expressions do not stay flagged', async () => {
+ await engine.executeRaw(`INSERT INTO facts (fact, source) SELECT 'claim ' || g, 'test' FROM generate_series(1, 50) g`);
+ await analyzePlannerTables(engine, ['facts'], 'repair');
+ await engine.executeRaw('CREATE INDEX test_facts_null_expr ON facts (lower(entity_slug))');
+ await engine.executeRaw("CREATE INDEX test_facts_empty_expr ON facts (lower(fact)) WHERE fact = 'no fact matches this'");
+ try {
+ expect(await readExpressionIndexesWithoutStats(engine)).toEqual([{ index: 'test_facts_null_expr', table: 'facts' }]);
+ await maybeRefreshPlannerStats(engine, 'idle');
+ const [nulls] = await engine.executeRaw<{ null_frac: number }>("SELECT null_frac FROM pg_stats WHERE tablename = 'test_facts_null_expr'");
+ expect(nulls!.null_frac).toBe(1);
+ expect(await hasIndexStats('test_facts_empty_expr')).toBe(false);
+ expect(await readExpressionIndexesWithoutStats(engine)).toEqual([]);
+ } finally {
+ for (const sql of ['DROP INDEX test_facts_null_expr', 'DROP INDEX test_facts_empty_expr', 'DELETE FROM facts']) await engine.executeRaw(sql);
+ }
+ });
+});
+
+describe('buildIndexOnline analyzes after it builds', () => {
+ test('the v240 handler prints the build notice and leaves the index with statistics', async () => {
+ await engine.executeRaw(`DROP INDEX IF EXISTS ${TITLE_INDEX.name}`);
+ const { text } = await captureStderr(() => v240.handler!(engine));
+ expect(text).toContain(`building ${TITLE_INDEX.name} on ~${PAGES} rows, then analyzing pages`);
+ expect(text).not.toContain('[warn]');
+ expect(await hasIndexStats(TITLE_INDEX.name)).toBe(true);
+ expect(await readExpressionIndexesWithoutStats(engine)).toEqual([]);
+ });
+
+ test('a forced ANALYZE failure leaves the migration applied, the index valid and the warning printed', async () => {
+ await engine.executeRaw(`DROP INDEX IF EXISTS ${TITLE_INDEX.name}`);
+ await engine.setConfig('version', String(v240.version - 1));
+ const { out, text } = await captureStderr(() => runMigrations(failingAnalyze(engine)));
+ expect(out.current).toBe(LATEST_SCHEMA_VERSION);
+ expect(await engine.getConfig('version')).toBe(String(LATEST_SCHEMA_VERSION));
+ expect(text).toContain(`[${v240.version}] ✓ ${v240.name}`);
+ expect(text).toContain(`${TITLE_INDEX.name} is built and valid, but ANALYZE pages failed (canceling statement due to lock timeout)`);
+ expect(text).toContain('Run on the brain host: gbrain repair planner-stats --apply');
+ const [valid] = await engine.executeRaw<{ valid: boolean }>('SELECT indisvalid AS valid FROM pg_index WHERE indexrelid = to_regclass($1)', [TITLE_INDEX.name]);
+ expect(valid!.valid).toBe(true);
+ expect(await readExpressionIndexesWithoutStats(engine)).toEqual([{ index: TITLE_INDEX.name, table: 'pages' }]);
+
+ await maybeRefreshPlannerStats(engine, 'cycle');
+ expect(await readExpressionIndexesWithoutStats(engine)).toEqual([]);
+ }, 60_000);
+});
diff --git a/test/planner-stats.test.ts b/test/planner-stats.test.ts
index 2531409dbb..63b98a0443 100644
--- a/test/planner-stats.test.ts
+++ b/test/planner-stats.test.ts
@@ -40,6 +40,9 @@ beforeEach(async () => {
await engine.executeRaw('DELETE FROM planner_stats_deltas');
await engine.executeRaw('DELETE FROM planner_stats_state');
await engine.executeRaw("DELETE FROM config WHERE key LIKE 'planner.%' OR key = 'import.analyze_every_pages'");
+ // The reset deletes rows but keeps catalog row counts; re-sample the emptied pages table so an index
+ // count left by an earlier test's narrow ANALYZE is not read as an expression index without statistics.
+ await engine.executeRaw('ANALYZE pages');
__testing.reset(engine);
__testing.hooks.afterWatermark = undefined;
__testing.hooks.onAnalyzed = undefined;