Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(pglite): transactional planner-stats accounting, row-delta ANALYZE and ANALYZE during import (F4b, GBRA-40)

garrytanfd23e871575e
diff --git a/docs/architecture/key-files/core-utilities-1.md b/docs/architecture/key-files/core-utilities-1.md
index 8433cef5bc..a15dc02dae 100644
--- a/docs/architecture/key-files/core-utilities-1.md
+++ b/docs/architecture/key-files/core-utilities-1.md
@@ -11,6 +11,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/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`, 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`, `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). `gradeTimelinePages` (re-exported by `orphan-policy.ts`, which both engines' `getHealth` already import) 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
new file mode 100644
index 0000000000..964c0e4235
--- /dev/null
+++ b/docs/guides/planner-stats.md
@@ -0,0 +1,55 @@
+# Planner statistics on PGLite
+
+PGLite (the embedded engine) has no autovacuum, so nothing collects planner
+statistics on its own. Without them the query planner guesses row counts and
+runs search and graph reads as nested loops over every page: a search that
+takes 40 ms on an analyzed 10,000-page brain can take tens of seconds on an
+unanalyzed one. GBrain keeps these statistics fresh for you. This is on by
+default; Postgres brains are unaffected (autovacuum owns statistics there).
+
+## How it works
+
+- Every statement that changes `pages`, `links`, `facts`, `takes`,
+ `content_chunks` or `timeline_entries` records how many rows it touched in
+ `planner_stats_deltas`. The record commits or rolls back with the data and
+ survives crashes and restarts, so changes from remote `put_page`,
+ `remember`, raw SQL or a killed process all count.
+- A table is stale when the rows changed since its last ANALYZE exceed
+ `max(500, 10% of the table)`, or when it has rows but no statistics.
+- Stale tables are analyzed (`ANALYZE <table>`, bounded by sample size, not
+ table size) at these points:
+ - the first search, `get_health`, orphan, backlink, graph or page-list read
+ (at most one check every 2 seconds per process);
+ - every `import.analyze_every_pages` files (default 500) during
+ `gbrain import` and managed sync;
+ - after the dream cycle's freshness phases, and when the resident write
+ consumer is idle;
+ - the full ANALYZE that import and sync already run at the end resets every
+ table's pending count.
+- 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.
+
+## 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 repair planner-stats --apply # ANALYZE them now (works with auto-analyze off)
+```
+
+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
+lock timeout.
+
+## Settings and opt-out
+
+| Setting | Default | Effect |
+|---|---|---|
+| `planner.auto_analyze` (env `GBRAIN_PLANNER_AUTO_ANALYZE`, which wins) | `true` | `false` turns off every automatic ANALYZE, including the full ANALYZE at the end of import and sync (which falls back to the narrow `pages` refresh the search projection needs). Doctor still reports stale tables. |
+| `planner.first_read_budget_ms` | `2000` | A stale table whose last ANALYZE took longer is analyzed after the read instead of before it. |
+| `import.analyze_every_pages` | `500` | Import and managed sync check statistics every N files; `0` disables that cadence. |
+
+To opt out: `gbrain config set planner.auto_analyze false`. To turn it back on:
+`gbrain config set planner.auto_analyze true`.
diff --git a/scripts/function-size-baseline.tsv b/scripts/function-size-baseline.tsv
index 4329af93bc..abe3f79d48 100644
--- a/scripts/function-size-baseline.tsv
+++ b/scripts/function-size-baseline.tsv
@@ -19,7 +19,7 @@ src/commands/eval-longmemeval.ts runEvalLongMemEval 740 seed: W5 baseline, refac
src/commands/extract-conversation-facts.ts processPage 307 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
src/commands/extract-conversation-facts.ts runExtractConversationFactsCore 378 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +1 #5757: managed flag threaded into ExtractCoreState; +4 #5823: shared default-cap wiring and structured budget reason/model; decision logic is in facts/conversation-budget.ts; +2 #5330: strict-eligibility read and the enumeration filter through the shared predicate (rule lives in facts/conversation-types.ts)
src/commands/extract.ts runExtract 398 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
-src/commands/import.ts runImport 959 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
+src/commands/import.ts runImport 963 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +4 GBRA-40 F4b: planner-stats refresh every import.analyze_every_pages files (logic in planner-stats.ts)
src/commands/mcp-expose.ts runPublish 443 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
src/commands/migrate-embeddings.ts runMigrateEmbeddings 325 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
src/commands/migrate-engine.ts runMigrateEngine 405 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
@@ -33,7 +33,7 @@ src/core/check-resolvable.ts checkResolvable 419 seed: W5 baseline, refactor wav
src/core/config.ts loadConfigWithEngine 362 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +2 #5824: search.vector_legacy_guard DB-plane merge
src/core/context-engine.ts createGBrainContextEngine 519 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
src/core/context/retrieval-reflex.ts resolveEntitiesToPointers 355 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
-src/core/cycle.ts runCycle 1237 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +5 #5809: extract_atoms phase gets a real abort signal; +2 #5809: cycle_already_running names the lock holder; +1 #4578: a lock steal during the last selected phase reports lock_stolen (one phase per runCycle call)
+src/core/cycle.ts runCycle 1241 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +5 #5809: extract_atoms phase gets a real abort signal; +2 #5809: cycle_already_running names the lock holder; +1 #4578: a lock steal during the last selected phase reports lock_stolen (one phase per runCycle call); +4 GBRA-40 F4b: planner-stats refresh after the freshness phases
src/core/cycle/extract-atoms.ts runPhaseExtractAtoms 787 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +12 #5809/#5832: hard/soft stop checks, chat-call signal, abortable pacing, no post-stop writes; +1 #5856: one BudgetTracker per drain attempt (reuse the attempt's tracker)
src/core/cycle/extract-atoms.ts runPhaseExtractAtoms>withBudgetTracker(#1) 316 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +11 #5809/#5832: per-item and pre-commit abort checks, chat-call signal, abortable pacing, catch-side stop
src/core/cycle/extract-facts.ts runExtractFacts 505 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index 9d83f5a962..cf7f17eddd 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -13,14 +13,14 @@ src/commands/jobs.ts 658 ratchet refactor wave 1 split target (W4 jobs, cut line
src/commands/serve-http.ts 915 ratchet refactor wave 1 W4 split into serve-http-<area>.ts modules; ceiling rationale: docs/architecture/key-files/commands-5.md entry for src/commands/serve-http.ts
src/core/ai/gateway.ts 4393 ratchet +7 fix wave 5 (#5137): provider-key redactor on every upstream error path and the first embedding 401/403 report (logic in ai/key-redact.ts, ai/key-warnings.ts); +20 System One v1: decide() delegating export + transport seam, RerankInput.onMeta/RerankMeta, TypeSafe reranker delegation to ai/decide/rerank-adapter.ts; +3 #5585: reconfigureGatewayWithEngine records expansion/chat model provenance (ai/gateway-model-sources.ts) + clears it with gateway state; lowered #5585: tracker record sites collapsed onto ai/budget-record.ts (recordOnTracker + failedCallUsage) while adding ledger fields (requested model, purpose, failed, estimated, countsAsCall); +20: schema-rejection fallback in chat() (retry once schemaless on a json_schema 4xx, remember the recipe for the process — mirrors expand()); re-summed after merging master v0.50.0.0 with the wave (structured-output + pricing hunks); +48: #4863 ChatOpts.responseSchema → tolerant json_schema Output on the chat() generateText call for openai-compatible recipes that declare structured outputs (facts extraction on Ollama); +74: #3657 post-sunset rerank short-circuit (effective-model check, once-per-process audit row + stderr, injected-clock seam); grown v0.46.26.0 megawave: config-plane probes + halt telemetry (#3387 #4312); +21 lines (OpenAI Responses API reasoning-item echo: ChatBlock 'reasoning' variant, chat()/toModelMessages() round-trip); wave-k absorbs: OCR routing seam (#4107 class), config-snapshot reader block (#3980); +21: #4107 OCR-model routing (getImageOcrModel); +10: keyless OPENAI_BASE_URL embedding override (#4385); wave-k #3622 reimpl: GBRAIN_EMBED_MAX_BATCH_TOKENS env cap for no_batch_cap recipes; +9: DeepSeek judge thinking pin plumbed through chat opts (#4069); +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); ranker wave v0.48.4.0: ChatOpts.temperature threaded to the transport (+15); +24: #4172 recipe-declared thinking headroom on the chat()/toolLoop() default — shared isThinkingModel predicate (Claude-5 regex || recipe thinking_by_default, fail-closed), also consumed by the subagent handler; +20: #4861 claude-cli expansion routed to the schemaless viaText path (the CLI adapter ignores responseFormat, so the native generateObject branch had no fallback); retired provider integration removed; safety wave: migration reranker input ceilings; lowered by fix wave 3 #5680 (embed request planning peeled to ai/embed-batch-plan.ts); +5 #4616: empty inputs skip the provider and every text/multimodal result is screened for zero-norm/NaN/Inf vectors (logic lives in ai/embedding-guard.ts); fix wave 3 integration: #4616 empty-input filtering feeds the shared #5680 batch planner; +3 #5691: embedQuery takes a per-request queryPrefix (no gateway state); +26 fix wave 7 (#5642): embed spend records bank provider-reported usage.tokens (all sub-batches reported → measured; chars-per-token estimate stays the fallback and the failure charge); +2 #5892: import + load-time call of installAiSdkWarningWriter (writer lives in ai/sdk-warnings.ts)
src/commands/sync.ts 473 ratchet refactor wave 1 split target (W4 sync); ceiling rationale: docs/architecture/key-files/commands-6.md entry for src/commands/sync.ts; +2 for the #5751 SyncResult.legacySkips interface field (fix wave 4); +2 fix wave 4 lane B: SyncResult.connectorHolds interface field (held counts for the sync summary); +1 fix wave 5 (#5032): SyncResult.fileRefusals interface field (named per-file Windows colon refusals)
-src/core/cycle.ts 3200 ratchet +2 System One v1 S9: extract_facts phase tail runs the conflict sweep (ai/decide/sweep.ts) only when the slot is not off; +2 System One v1: purge phase prunes decision receipts (ai/decide/store.ts); grown v0.46.26.0 megawave (#4102 #2608) + master v0.46.26.0 cycle-start orphan recovery; +10 wave G #3974: cycle-sync uncommitted-drift warn; grown wave-g (#4416): synthesize_concepts source threading; grown wave-g (#4416): synthesize_concepts source threading (same fix absorbed as #4417 on wave-k); wave-k: ); +7: #4077 abort threading; +10: #4745 fullImplicitSourceCycle opt-in contract; +3: #4890 extract phase jsonMode/quiet + pages-not-links totals; +1: wave review — extract phase passes quiet:true + jsonMode:false; +1: extract_facts pagesFailed detail; +8 fix wave 3: one cycle date resolved in runCycle and threaded to synthesize/patterns/drift (C-15); +1 #5632: cycle sync resumes an unfinished managed cursor with its stored options; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; -41 #5809: anyAbortSignal peeled to abort-signals.ts; +5 #5809: extract_atoms phase gets a real abort signal; +4 #5809: cycle_already_running names the lock holder; +7 #5255: cycle sync runs a managed pull request as no-pull and reports upstream_refresh; +1 #4578: a lock steal during the last selected phase reports lock_stolen, not aborted; +3 #5536: keyless embed phase clean-skips when embedding_disabled is set
+src/core/cycle.ts 3205 ratchet +2 System One v1 S9: extract_facts phase tail runs the conflict sweep (ai/decide/sweep.ts) only when the slot is not off; +2 System One v1: purge phase prunes decision receipts (ai/decide/store.ts); grown v0.46.26.0 megawave (#4102 #2608) + master v0.46.26.0 cycle-start orphan recovery; +10 wave G #3974: cycle-sync uncommitted-drift warn; grown wave-g (#4416): synthesize_concepts source threading; grown wave-g (#4416): synthesize_concepts source threading (same fix absorbed as #4417 on wave-k); wave-k: ); +7: #4077 abort threading; +10: #4745 fullImplicitSourceCycle opt-in contract; +3: #4890 extract phase jsonMode/quiet + pages-not-links totals; +1: wave review — extract phase passes quiet:true + jsonMode:false; +1: extract_facts pagesFailed detail; +8 fix wave 3: one cycle date resolved in runCycle and threaded to synthesize/patterns/drift (C-15); +1 #5632: cycle sync resumes an unfinished managed cursor with its stored options; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; -41 #5809: anyAbortSignal peeled to abort-signals.ts; +5 #5809: extract_atoms phase gets a real abort signal; +4 #5809: cycle_already_running names the lock holder; +7 #5255: cycle sync runs a managed pull request as no-pull and reports upstream_refresh; +1 #4578: a lock steal during the last selected phase reports lock_stolen, not aborted; +3 #5536: keyless embed phase clean-skips when embedding_disabled is set; +5 F4b: planner-stats refresh after the freshness phases (logic in planner-stats.ts)
src/core/cycle/synthesize.ts 3297 ratchet +26 System One v1 S7/S8: triage and grounding decide delegation (triage-decide.ts, grounding-decide.ts); merged waves; grown v0.46.26.0 megawave + master rolling lease via shared throttled renewer; grown wave-g (#4506): cycle summaries can stay out of the source repo; +18: expired-verdict sweep + DeepSeek judge thinking pin (#4069); +47: #4077 cooperative-abort threading; +110: eval fix wave F6 spend surfacing (withChatPhase wrap, triage/child token telemetry, zero-page counter); +32: F1b quote-verify call site + kill switch; +2: F1a/F3/F4a OUTPUT POLICY rules; +59: F2 verified-segment rescue (gate at report construction, rescue knobs, telemetry); +19: rubric v2 peak-scoring + docblock rescue branch; +50: #4337 summary link-sample cap + dream_created_cycle_date preserve-on-rerun; +5: #4348 resolveCycleDate wiring (local-day summary bucketing); +3 round-3 rebase true-up; +55: #4805 synth-v2 completion skip (findSynthV2Completion + prefix-parameterized loadSuccessfulSynthesisKeys); +10: #4886 mode-aware buildSynthesisPrompt (oneshot children drop tool-use/final-prose guidance); #5105: small legacy writer/refusal and shared revision CAS delegates; +4: merge of #5666 durable synthesis completions with the v0.59.18.0 verify-epoch wiring; +7 #5413/#5471 discovery exclusions (self-capture session ids, dream output directories); +6 fix wave 2 (v0.60.5.0) integration: W7 paid-loop breaker check before submission and released-key daily-cap count on top of the W1b discovery exclusions; +6 v0.60.5.0 master-merge true-up: the wave-2 growth (+13 W1b, +6 W7) re-summed over master v0.59.18.0 at 3222 lines with no slack; +76 fix wave 3: per-run USD gate + fail-closed daily cap (C-13), child first-write ownership for stamp/reverse-write (C-8, #5685), cycle-date prompt hint (C-15), opt-in attribution rule (#5425); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +19 at the merge; +2 #5806 triageNow clock seam forwarded to triage (interface field + call-site option); +4 #5854: a postprocess or summary publish still pending after its wait is deferred (publish_pending warn, no cooldown stamp; helper in synthesize-postprocess.ts)
src/core/cycle/extract-atoms.ts 1808 ratchet crossed the 1500 unlisted cap in the atoms/extraction fix wave: +21 embed-aware cost gate (#4878), +65 atoms-array anchor scan (#4913); peel candidate: the parse block (parseAtomsOutcome / parseArrayAtOffset / atomsFromParsedArray) into extract-atoms-parse.ts; +35: #4853 transcript-origin atoms link to their conversation page; +130: #4916 transcript failure-count/tombstone (extract_atoms_transcript_state, TODOS P2(b)); wave composition: #4916 transcript-state skip + #4948 zero-atom prompt + #4943 meetings source-id summed; +3: wave review — a later `[]` is an honest zero-yield, a non-atom-shaped array is a counted failure; +13: wave review — explicit budget keeps the cap over an unpriced embed route ($0-priced); +14: wave review — transcript-state write errors surfaced, missing table warns once; merged reliability/shared-skills source integration; +37 fix wave 3: stable undated atom dates + stale-atom retirement (C-14); +3 #5525: effectiveVisibility stamped on non-managed atoms; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +3 at the merge; +6 fix wave 3 lane A (#5601): accepted-pending atom batches count as progress (helper in persistence/accepted-pending.ts); +4 fix wave 4: #5705 transcript-as-data system prompt lines and its message helper, #5627 response schema import (the atom-type list moved to extract-atoms-schema.ts); +30 #5809/#5832: drain hard/soft stop signals (ExtractAtomsOpts.signal/stopSignal, pre-commit abort checks, no strike or post-stop writes after a hard stop) and the cancellable backlog count; +1 #5812: transcript items are paste-stripped (corpusTextForExtraction import) before the input cut; +1 #5820: extract_atoms discovery passes selfCaptureSessionIds like synthesize; +10 #5856/#5854: drain attempt state (one BudgetTracker + one publish wait across batches) and the opt-in connector email/meeting exclusion (predicate in connector-atoms.ts)
src/core/engine.ts 2678 ratchet grown v0.46.26.0 megawave: relational/visibility/usage contract surface (#4352 #4218); grown wave-g (#4524 #4527): orphans-mode contract + removeLink deleted count; wave-k: +4 fail-closed TrajectoryOpts.remote contract doc (#3855), +2 FactListOpts.unconsolidatedOnly (#4070), +14 getAllConfig bulk-read contract (#3980); +1: getBacklinkCounts page-id contract doc (#4380); +9: FactListOpts.grep SQL pre-limit contract (#3851); +13: dream-verdict TTL contract (#4069); +33: softDeletePages batch soft-delete contract (#4587); +8: #4592 scoped getStats/getHealth contract doc; +5 read-time TTL validity contract docs (active vs history read semantics); +12: #4280 findOrphanPages type/quarantined metadata contract; +14: traversePathsDetailed row-cap contract (ship-review); +12: resolveSlugWithAliasDetailed owning-source contract (ship-review) | merged v0.48.1.0: master #4788 + wave traversePathsDetailed/resolveSlugWithAliasDetailed; master: | merged v0.48.1.0 true-up; corrective release: read-policy signatures and Chronicle scope; +7: #4882 listFactsSince entitySlug/sessionId composition doc; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: guarded derived projection preparation and read seals; #5105: resident-stop registration and direct transaction contract; #5105: +1 raw preservation contract for legacy engine migration; merged company ingestion/schema routing changes; safety wave: fact embedding model and text identity contract; +5 write-path wave: findDuplicatePage excludeSlug + id-first ranking contract; +2 fw3 A14: addTag tagSource provenance contract; evidence delivery: getChunkWindows interface member + type import (+3); #5761: +4 markPagesAttendanceBlocked member + countStalePagesForExtraction attendance option; +4 #5888: FactListOpts.fingerprint + FactRow.fact_fingerprint contract (hot-memory duplicate collapse)
src/core/import-file.ts 2232 ratchet +2: pre-publication withdrawal validation; grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); security: durable queued authority and confined filesystem dispatch; master integration: grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: withdrawal preservation after data-only frontmatter parsing; #5105: small legacy writer/refusal and shared revision CAS delegates; #5105: +8 prepared contextual retrieval policy and retry boundary wiring; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: shared provider-free Markdown and code preparation; merged company ingestion/schema routing changes; master retrieval/projection integration with company ingestion; shared content: prepare managed image imports without bypassing canonical publication; +29 write-path wave: identity move/collision wiring (logic in import-identity.ts), deferred embedding on provider failure, image index completeness, file-time date anchor; +22 fw3 A13: markdown re-import reuses unchanged chunk vectors under the seal/wrapper/signature/protected-fence gate; +2 fw3 A12: importFromFile firstCommitAt option; +3 fw3 A14: managed imports keep add-only tags; +4 #5675: record the file origin move inference binds to (logic in import-identity.ts); fw3 integration: A12/A13/A14 (+27) and #5675 (+4) compose; +17 wave-2 W4: safe-chunk re-seal of unchanged legacy markdown/code pages (#5050 #5247) and embedding-input provenance on inline imports (#5553); -1 fix wave 2 (v0.60.5.0) integration: W4 delta re-summed over the merged master line count; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +16 at the merge; +11 #4616: markdown and code imports keep the usable vectors of a partially refused batch and leave refused chunks for embed --stale; lowered to 2230: #5621 contextual-mode resolution peeled to core/import-contextual-mode.ts (shared with gbrain repair contextual-mode); +2 wave 8 lane D1 #5158: key-order fallback equality call (comparison lives in page-state/import-guard.ts)
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 332 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)
-src/core/pglite-engine.ts 3117 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); 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)
+src/core/pglite-engine.ts 3139 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); 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); +22 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts)
src/core/postgres-engine.ts 3130 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)
src/core/search/hybrid.ts 1584 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
src/core/types.ts 2112 ratchet +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)
@@ -36,7 +36,7 @@ src/core/embedding-migration.ts 1569 ratchet new row: crossed 1500 in v0.46.25.0
src/core/github-source.ts 1530 ratchet new row: crossed the 1500 unlisted cap in v0.46.23.0 review fix wave (scope-state gating, client hardening, symlink containment); merged reliability/shared-skills source integration; managed sweep lease wrapper; fix wave 3 lane A: config parser peeled to github-source-config.ts (-47), +account pin wiring and pinned-installation refresh
src/commands/hook.ts 1903 ratchet cathedral-5 heartbeat extraction offsets part of the BrainBench-seam growth; grown v0.46.26.0 megawave hooks-ipc (#4245); +108 monthly backup check: banner + gated session-start note + detached spawn (backup/status-file readers); +28 ship-review egress hardening: per-harness capture dispatch (capture-spec), memorable gate + receipt + relay block, fail-closed unscanned/newest-guess skips; +79 ambient-writeback WP4: hookStop bank step (gate -> bankWritebackTurn -> IPC flush; gate/bank logic live in core/facts + corpus-segments); +41 adversarial fix wave: wide-tail retry when the 128KB window misses the user turn, by-design heartbeat outcome classes, source-in-name banking; +11 #5413 session-end skips claude-cli self-transcripts; +11 #5701: hook lanes pass allowOversize so a long session reaches the bounded tail read
src/core/chunkers/code.ts 1588 ratchet new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (decorated-python defs #3821, version-gate + timeout chunker fixes); grown wave-g (#4511): named defs never folded into merged chunks; grown #4669: skip WASM parse for languages without TOP_LEVEL_TYPES; +6 N13-1: CodeChunkMetadata.definesFunction field + merge-guard stamp (predicate lives in def-types.ts)
-src/core/config.ts 1819 ratchet +1 System One v1: decide.* key prefix (validated by ai/decide/config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge); +8: loadConfig hook for ~/.gbrain/.env, loader lives in gbrain-env-file.ts (#3893); +17: litellm/together key-fold slots (#3904 reimpl: two GBrainConfig fields + KNOWN_CONFIG_KEYS rows); +1: link_resolution.cross_source key (#3908); +4 v0.47 gmail-loops: loops.extraction_enabled key; +1: pricing.overrides key (#4633 adoption); +7 #4667 adoption: sync.exclude key registration; +4: eval fix wave keys (quote_verify + 3 rescue knobs); +memorable file-plane key registration (integrations.memorable.enabled + consent-event doc); +33 ambient-writeback: memory.* + brain.audience key registration + GBrainConfig.memory mirror slot (resolvers live in facts/writeback-config.ts); +38 2026-08 wave: retrieval_reflex_volunteer key + env mapping (volunteer-arm kill switch) + E5a registration of the 10 adaptive_return*/autocut*/crag_* search (incl. adversarial batch isEnvDisabled dedup); ambient-writeback (master merge): facts/writeback-config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave; prior growth: sync/intent/chat-connectors/litellm/pricing/loops key folds; +34: #4702 content_sanity.disabled_patterns (type + DB-plane parse/merge + key registration); composition true-up (fix-wave multi-train) | merged v0.48.1.0: master #4788 writeback keys + wave #4702/#4748 keys; master: | merged v0.48.1.0 true-up; ranker wave v0.48.4.0: +4 KNOWN_CONFIG_KEYS rows (+8); +5 #4895: CWD_DOTENV_FILES gains the per-NODE_ENV .local variants Bun auto-loads; +2 #5003: sync.include_hidden key registration; +57 #4605: search.* registry reconciled to the keys mode.ts reads (+20 knob rows, +4 direct-read singletons) + GBrainConfig.search slot + adaptive_return* DB-plane merge; +2 pre-landing review: fts.reindex_in_progress key registration (#4795 marker escape hatch); +4 #4987: auto_timeline key registration (the documented off switch was rejected as unknown); lowered to 1793: GHSA wave v0.50.5.0 moved CWD_DOTENV_FILES + dotenvValuesForKey into core/env-trust.ts (-49, re-exported); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; evidence delivery: 5 registered config keys + comment (+7); +2 #5691: embedding_query_prefix key registration; evidence delivery auto v2: search.return_budget_conversation key row (+1); +1 #5836: facts.entity_inference key row; +6 #5824: search.vector_legacy_guard key row + GBrainConfig.search slot + DB-plane merge; +3 wave 8 lane D1 #5885: takes.auto_embed key row; +3 #5232: GBrainConfig.persistence.write_wait_ms file-plane slot + key row (resolver in persistence/write-wait.ts)
+src/core/config.ts 1821 ratchet +1 System One v1: decide.* key prefix (validated by ai/decide/config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge); +8: loadConfig hook for ~/.gbrain/.env, loader lives in gbrain-env-file.ts (#3893); +17: litellm/together key-fold slots (#3904 reimpl: two GBrainConfig fields + KNOWN_CONFIG_KEYS rows); +1: link_resolution.cross_source key (#3908); +4 v0.47 gmail-loops: loops.extraction_enabled key; +1: pricing.overrides key (#4633 adoption); +7 #4667 adoption: sync.exclude key registration; +4: eval fix wave keys (quote_verify + 3 rescue knobs); +memorable file-plane key registration (integrations.memorable.enabled + consent-event doc); +33 ambient-writeback: memory.* + brain.audience key registration + GBrainConfig.memory mirror slot (resolvers live in facts/writeback-config.ts); +38 2026-08 wave: retrieval_reflex_volunteer key + env mapping (volunteer-arm kill switch) + E5a registration of the 10 adaptive_return*/autocut*/crag_* search (incl. adversarial batch isEnvDisabled dedup); ambient-writeback (master merge): facts/writeback-config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave; prior growth: sync/intent/chat-connectors/litellm/pricing/loops key folds; +34: #4702 content_sanity.disabled_patterns (type + DB-plane parse/merge + key registration); composition true-up (fix-wave multi-train) | merged v0.48.1.0: master #4788 writeback keys + wave #4702/#4748 keys; master: | merged v0.48.1.0 true-up; ranker wave v0.48.4.0: +4 KNOWN_CONFIG_KEYS rows (+8); +5 #4895: CWD_DOTENV_FILES gains the per-NODE_ENV .local variants Bun auto-loads; +2 #5003: sync.include_hidden key registration; +57 #4605: search.* registry reconciled to the keys mode.ts reads (+20 knob rows, +4 direct-read singletons) + GBrainConfig.search slot + adaptive_return* DB-plane merge; +2 pre-landing review: fts.reindex_in_progress key registration (#4795 marker escape hatch); +4 #4987: auto_timeline key registration (the documented off switch was rejected as unknown); lowered to 1793: GHSA wave v0.50.5.0 moved CWD_DOTENV_FILES + dotenvValuesForKey into core/env-trust.ts (-49, re-exported); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; evidence delivery: 5 registered config keys + comment (+7); +2 #5691: embedding_query_prefix key registration; evidence delivery auto v2: search.return_budget_conversation key row (+1); +1 #5836: facts.entity_inference key row; +6 #5824: search.vector_legacy_guard key row + GBrainConfig.search slot + DB-plane merge; +3 wave 8 lane D1 #5885: takes.auto_embed key row; +3 #5232: GBrainConfig.persistence.write_wait_ms file-plane slot + key row (resolver in persistence/write-wait.ts); +2 F4b: planner.* and import.analyze_every_pages keys
src/core/bootstrap/harness.ts 2704 ratchet +29 live-PGLite-serve lane: LIVE_SERVE refusal ahead of source resolution + unpinned --token hooks (CI e2e fix); +46 wave review: resolveHookSource dep (serve-parity resolver + federated grant), --source shape validation, loud SOURCE_UNRESOLVED instead of a silent 'default'; +10: #4574 parseCodexBlockBearer http_headers shape + legacy bearer_token fallback; +4 at megawave/wave-k merge; +codex hooks lane: step-7 codex hooks.json + config.toml trust pair, removeHarness arm; +234 ambient-writeback WP3: kind:'instructions' targets (plan/apply/converge-off/remove/status probes, OV-A4 override pre-check) — splice/render mechanics live in instructions-block.ts; +59 adversarial fix wave: registrar-mode block suppression, converge-failure receipt tracking, MCP-confirmed guard before block install; +26 round-3 fixes: codex-lane MCP-confirmed guard + smoke-rollback block strip; master: | merged v0.48.1.0 true-up; +41 #4897 resolveImplicitSource dep + defaultResolveImplicitSource: hooks/token/receipt bind to the serve's implicit default source when --source is omitted; +23 #4586 statusHarness live claude-code mcp verdict (URL mismatch or same-scope non-HTTP registration reads failed, receipt untouched); shared-skills integration on company-ingestion base; +18 #5671: logAmbientPostureNotes helper (registrar note moved out of applyHarness + pre-consent warning when an explicit private facts default meets the HTTP harness; text shared with doctor in facts/writeback-config.ts); +24 #5893: rotation grant carry wiring and its rotationCarry/withheldOperationsNote helpers (carry rules live in token-mint.ts carryLegacyGrant); +6 #5878: --refresh-skills flag and status epoch line (refresh logic lives in harness-skills.ts)
src/core/oauth-provider.ts 1236 ratchet new row: crossed the 1500 unlisted cap absorbing #3819 (DCR 400 invalid_client_metadata + scope filtering + custom-scheme redirect_uris + pseudo-scheme guard); merged v0.49: transactional grant enforcement shared with hosted grant policies; +1 #5222 resourceUrl option
src/core/ops/pages.ts 644 ratchet crossed the unlisted 1500 cap in the fix wave: pack-vocabulary enforcement on capture (#4721) + get_page alias follow (#4275) landed together; next growth should peel a pages-ops submodule; +3: alias hop reads the canonical in the owning source (ship-review); +5: explicit source_id liveness check in get_page/list_pages (#4620); +3: #4857 total-order slug sort + list_pages source_id parse; +5: #4620 explicit removed-source id fails loudly; master integration: +4: authenticated delegated private-write boundary and auto-link suppression; #5105: canonical page mutations peeled into persistence modules; +2 v0.50.5.0 purge parameter and shared preflight call; preparation composes through the persistence modules; +7: source-qualified deep-research fetch authorization and ambiguity refusal (codec lives in deep-research-id.ts); +1 #5567: remote get_page keeps materialized markers; +1 #5622: trusted local capture file parameter; +5 #5709: get_page include_timeline_entries (rows via get_timeline's read policy); +8 GBRA-36 security wave: required outputRedaction policy on each pages op; +1 #5154: list_pages passes listColumnsOnly; +17 #5641: list_pages exposes the updated_after_slug keyset cursor and updated_at_iso
diff --git a/src/commands/doctor/checks/planner-stats.ts b/src/commands/doctor/checks/planner-stats.ts
new file mode 100644
index 0000000000..bd82e4f3b5
--- /dev/null
+++ b/src/commands/doctor/checks/planner-stats.ts
@@ -0,0 +1,52 @@
+/**
+ * planner_stats_stale (F4b, O-DX-9): hot tables whose planner statistics are
+ * stale enough to give the query planner the wrong shape (pages-by-pages
+ * nested loops in search and graph reads).
+ *
+ * PGLite reads the F4b row deltas (src/core/planner-stats.ts): stale when the
+ * rows modified since the table's last ANALYZE exceed max(500, 10% of its
+ * rows), or when it has rows but no statistics. Postgres reads
+ * `pg_stat_user_tables.n_mod_since_analyze` against the same threshold and
+ * 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.
+ */
+import { plannerAutoAnalyzeEnabled, PLANNER_STATS_REPAIR_COMMAND, readPlannerTableStates } from '../../../core/planner-stats.ts';
+import type { Check } from '../../doctor.ts';
+import { connectedEngine, type DoctorContext, type DoctorEntry } from '../context.ts';
+
+async function runPlannerStats(ctx: DoctorContext): Promise<Check[]> {
+ const engine = connectedEngine(ctx);
+ const checks: Check[] = [];
+ ctx.progress.heartbeat('planner_stats_stale');
+ try {
+ const tables = await readPlannerTableStates(engine);
+ if (!tables) {
+ checks.push({ name: 'planner_stats_stale', status: 'ok',
+ message: 'Planner statistics accounting is not installed yet (schema migration pending). Run: gbrain apply-migrations --yes' });
+ return checks;
+ }
+ 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) {
+ checks.push({ name: 'planner_stats_stale', status: 'ok', message: `Planner statistics are fresh on ${tables.length} hot tables.`, 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.'
+ : 'Autovacuum has not analyzed them in the last hour, so search and graph reads may plan against stale row counts.';
+ const off = autoAnalyze === false
+ ? ' 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 });
+ } 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` });
+ }
+ return checks;
+}
+
+export const plannerStatsEntry: DoctorEntry = { name: 'planner_stats_stale', emits: ['planner_stats_stale'], run: runPlannerStats };
diff --git a/src/commands/doctor/registry.ts b/src/commands/doctor/registry.ts
index e9a036053e..bb67b2099c 100644
--- a/src/commands/doctor/registry.ts
+++ b/src/commands/doctor/registry.ts
@@ -85,6 +85,7 @@ import { autoChronicleEntry } from './checks/auto-chronicle.ts';
import { factTakeVectorsEntry } from './checks/vector-coverage.ts';
import { decideHealthEntry } from './checks/decide.ts';
import { unlinkedFactsEntry } from './checks/unlinked-facts.ts';
+import { plannerStatsEntry } from './checks/planner-stats.ts';
import { STOP_DOCTOR, type DoctorContext, type DoctorEntry } from './context.ts';
import type { Check } from '../doctor.ts';
@@ -145,6 +146,7 @@ export const DOCTOR_CHECK_REGISTRY: readonly DoctorEntry[] = [
unlinkedFactsEntry,
autoChronicleEntry,
factTakeVectorsEntry,
+ plannerStatsEntry,
searchModeEntry,
];
diff --git a/src/commands/import.ts b/src/commands/import.ts
index d97926d194..daf622713c 100644
--- a/src/commands/import.ts
+++ b/src/commands/import.ts
@@ -33,6 +33,7 @@ import {
import { realpathOrResolve } from '../core/path-confine.ts';
import { slog } from '../core/console-prefix.ts';
import { refreshProjectionStatistics } from '../core/search/projection-statistics.ts';
+import { importAnalyzeEveryPages, maybeRefreshPlannerStats, PLANNER_STATS_REPAIR_COMMAND } from '../core/planner-stats.ts';
import { importManagedFile } from '../core/persistence/import-mutations.ts';
import { acceptedPendingReceipt } from '../core/persistence/accepted-pending.ts';
import { estimateCostFromChars, lookupEmbeddingPrice } from '../core/embedding-pricing.ts';
@@ -634,6 +635,10 @@ export async function runImport(
const firstCommits = !singleFile && await engine.getConfig('sync.git_first_commit_dates').catch(() => null) === 'true'
? gitFirstCommitDates(dir) : null;
+ // F4b: PGLite has no autovacuum; refresh stale planner statistics every N files so the import
+ // never plans against the empty tables it started with (O-CEO-17).
+ const analyzeEvery = await importAnalyzeEveryPages(engine);
+
async function processFile(eng: BrainEngine, filePath: string) {
if (signal?.aborted) return;
const relativePath = singleFile ? basename(filePath) : relative(dir, filePath);
@@ -719,6 +724,10 @@ export async function runImport(
}
processed++;
tickProgress();
+ if (analyzeEvery > 0 && processed % analyzeEvery === 0) {
+ await maybeRefreshPlannerStats(engine, 'import', { throttle: false }).catch((e: unknown) =>
+ console.error(` Warning: planner statistics refresh failed (${e instanceof Error ? e.message : String(e)}); the import continues. Afterwards run: ${PLANNER_STATS_REPAIR_COMMAND}`));
+ }
if (company) {
await engine.executeRaw("INSERT INTO op_checkpoints(op,fingerprint,completed_keys) VALUES('company-brain-content',$1,$2::text::jsonb) ON CONFLICT(op,fingerprint) DO UPDATE SET completed_keys=EXCLUDED.completed_keys,updated_at=now()",
[company.receiptId, JSON.stringify([...completed])]);
diff --git a/src/core/config.ts b/src/core/config.ts
index 7f0a01b5ba..81f2b6725a 100644
--- a/src/core/config.ts
+++ b/src/core/config.ts
@@ -1630,6 +1630,8 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = [
'persistence.limits.brain_recovery_bytes', 'persistence.limits.worktree_recovery_bytes',
'persistence.receipt_retention_days', 'persistence.unbound_write', // #5254: persistence/unbound-source.ts
'persistence.write_wait_ms', // #5232: file plane, persistence/write-wait.ts
+ // F4b: PGLite row-delta ANALYZE, read by src/core/planner-stats.ts (docs/guides/planner-stats.md).
+ 'planner.auto_analyze', 'planner.first_read_budget_ms', 'import.analyze_every_pages',
];
/**
diff --git a/src/core/cycle.ts b/src/core/cycle.ts
index 960d33edba..1acd691d63 100644
--- a/src/core/cycle.ts
+++ b/src/core/cycle.ts
@@ -57,6 +57,7 @@ import { assertValidSourceId } from './source-id.ts';
import { PHASE_SCOPE, SOURCE_FRESHNESS_PHASES, type PhaseScope } from './cycle/phase-scope.ts';
import { assertEmbedNotStalled } from './embed-stall.ts';
import { anyAbortSignal } from './abort-signals.ts';
+import { maybeRefreshPlannerStats } from './planner-stats.ts';
export { PHASE_SCOPE, SOURCE_FRESHNESS_PHASES, type PhaseScope } from './cycle/phase-scope.ts';
export { anyAbortSignal } from './abort-signals.ts';
@@ -2334,6 +2335,10 @@ export async function runCycle(
await safeYield(opts.yieldBetweenPhases);
}
+ // F4b: the freshness phases above write links, timeline and facts in bulk; on PGLite (no autovacuum)
+ // refresh the stale planner statistics before the heavier graph phases read them. Best-effort.
+ if (engine && !dryRun) await maybeRefreshPlannerStats(engine, 'cycle').catch(() => undefined);
+
// ── v0.41 T9: extract_atoms (per-source, pack-gated) ──────────
// Orchestrator-level pack gate: consults the active pack's `phases:`
// declaration. When the active pack does NOT declare extract_atoms
diff --git a/src/core/doctor-categories.ts b/src/core/doctor-categories.ts
index 42abaa19e4..7b20420ce7 100644
--- a/src/core/doctor-categories.ts
+++ b/src/core/doctor-categories.ts
@@ -184,6 +184,8 @@ export const SKILL_CHECK_NAMES: ReadonlySet<string> = new Set([
* Infrastructure liveness signals. DB, workers, OAuth, RLS, locks, providers.
*/
export const OPS_CHECK_NAMES: ReadonlySet<string> = new Set([
+ // F4b: PGLite row-delta planner statistics / Postgres autovacuum ANALYZE lag on the hot tables.
+ 'planner_stats_stale',
'alternative_providers',
'autopilot_fanout_concurrency',
'autopilot_lock_scope',
diff --git a/src/core/persistence/consumer.ts b/src/core/persistence/consumer.ts
index afdfd2d02f..189475eb9b 100644
--- a/src/core/persistence/consumer.ts
+++ b/src/core/persistence/consumer.ts
@@ -13,6 +13,7 @@ import { isWriteErrorCode } from './types.ts';
import { redactConnectionInfo } from '../audit/redact-connection-info.ts';
import { AsyncLocalStorage } from 'node:async_hooks';
import { monitorEventLoopDelay, type IntervalHistogram } from 'node:perf_hooks';
+import { maybeRefreshPlannerStats } from '../planner-stats.ts';
type PhaseObservation = { name: string; started_at: string; deadline_exceeded: boolean; attempt: number; first_conn_ms?: number };
/** #5801: the phase a connection checkout belongs to, carried through its async chain. */
@@ -251,8 +252,9 @@ export class PersistenceConsumer {
this.nextMaintenance = Date.now() + 300_000;
await this.phase('refresh_roots', signal => refreshManagedFilesystemRoots(this.engine,
this.engine.kind === 'pglite' ? this.config.database_path : undefined, signal));
- this.maintenanceWorker = compactWriteReceipts(this.engine).catch(error => this.report(error))
- .finally(() => { this.maintenanceWorker = undefined; });
+ // F4b: idle maintenance also refreshes stale PGLite planner statistics (a no-op on Postgres).
+ this.maintenanceWorker = compactWriteReceipts(this.engine).then(() => maybeRefreshPlannerStats(this.engine, 'idle'))
+ .catch(error => this.report(error)).finally(() => { this.maintenanceWorker = undefined; });
}
return;
}
diff --git a/src/core/persistence/sync-run.ts b/src/core/persistence/sync-run.ts
index 2533d32eb0..89911daebb 100644
--- a/src/core/persistence/sync-run.ts
+++ b/src/core/persistence/sync-run.ts
@@ -19,6 +19,7 @@ import { join, resolve } from 'node:path';
import { currentCompanyBrainSync, getCompanyBrainProfile, readCompanyBrainPlan } from '../company-brain/profile.ts';
import { readCommittedBlob } from '../company-brain/revision.ts';
import { refreshProjectionStatistics } from '../search/projection-statistics.ts';
+import { importAnalyzeEveryPages, maybeRefreshPlannerStats } from '../planner-stats.ts';
import { recordManagedSyncFailure, clearManagedSyncFailureAfterSuccess, formatManagedSyncFailure, type ManagedSyncFailure } from './sync-failures.ts';
import { writeFailureDiagnostic } from './verb-errors.ts';
import { extractManagedStaleLinks } from './links-maintenance.ts';
@@ -389,6 +390,7 @@ export async function performManagedSync(engine: BrainEngine, opts: SyncOpts, sl
}
if (opts.dryRun) return result(cursor, 'dry_run');
const config = loadConfig() ?? { engine: engine.kind };
+ const analyzeEvery = await importAnalyzeEveryPages(engine);
let batchStart = performance.now(), batchPages = 0, foregroundWaitStart = 0, foregroundBaseline = 0;
let creditedPages = 0, creditStarted = 0;
const sliceStarted = performance.now(), sliceFirstIndex = cursor.index;
@@ -490,6 +492,8 @@ export async function performManagedSync(engine: BrainEngine, opts: SyncOpts, sl
next.counts.chunks += Number(done.outcome?.chunks ?? 0);
cursor = await saveCursor(engine, key, cursor, next);
opts.onProgress?.({ phase: 'managed_sync.page_committed', bankedFiles: cursor.index });
+ // F4b: PGLite plans the rest of a large sync against fresh statistics (spec Addendum A item 2).
+ if (analyzeEvery > 0 && cursor.index % analyzeEvery === 0) await maybeRefreshPlannerStats(engine, 'managed_sync', { throttle: false }).catch(() => undefined);
assertActive();
if (slice && (cursor.index - sliceFirstIndex >= slice.maxPages || performance.now() - sliceStarted >= slice.maxMs)) return result(cursor, 'partial', 'writer_yield');
batchPages++;
diff --git a/src/core/pglite-engine.ts b/src/core/pglite-engine.ts
index 4661899cc8..e6e723d855 100644
--- a/src/core/pglite-engine.ts
+++ b/src/core/pglite-engine.ts
@@ -73,6 +73,7 @@ import { logBatchRetry as auditLogBatchRetry, logBatchExhausted as auditLogBatch
import { runMigrations } from './migrate.ts';
import { supportsHnswIterativeScan } from './vector-index.ts';
import { searchVectorPool, readVectorPool } from './search/vector-pool.ts';
+import { beforePlannerRead } from './planner-stats.ts';
import { buildVectorSearchStatement, VECTOR_EXTENSION_VERSION_SQL } from './search/vector-statement.ts';
import { withVectorSettings } from './search/vector-settings.ts';
import { PGLITE_SCHEMA_SQL, getPGLiteSchema } from './pglite-schema.ts';
@@ -1157,6 +1158,20 @@ export class PGLiteEngine implements BrainEngine {
private _pageTransaction = false;
+ /**
+ * F4b (O-ENG-12): planner-sensitive reads first refresh stale planner
+ * statistics (src/core/planner-stats.ts); call the returned function once the
+ * read has answered. Never inside a transaction.
+ */
+ private async beforePlannerRead(): Promise<() => void> {
+ return this._pageTransaction ? () => {} : beforePlannerRead(this);
+ }
+
+ private async plannerRead<T>(read: () => Promise<T>): Promise<T> {
+ const settle = await this.beforePlannerRead();
+ try { return await read(); } finally { settle(); }
+ }
+
async putPage(slug: string, page: PageInput, opts?: PageWriteOptions): Promise<Page> {
slug = validateSlug(slug);
return this.transaction(async tx => {
@@ -1272,7 +1287,7 @@ export class PGLiteEngine implements BrainEngine {
}
async listPages(filters?: PageFilters): Promise<Page[]> {
- return pagesImpl.listPages(scopedRead(this.engineSql), filters);
+ return this.plannerRead(() => pagesImpl.listPages(scopedRead(this.engineSql), filters));
}
async getAllSlugs(opts?: { sourceId?: string }): Promise<Set<string>> {
@@ -1322,6 +1337,7 @@ export class PGLiteEngine implements BrainEngine {
// than direct window function + GROUP BY. Fetch more chunks than the
// page limit (3x) to ensure N dedup'd pages survive; bounded and fast.
async searchKeyword(query: string, opts?: SearchOpts): Promise<SearchResult[]> {
+ const settle = await this.beforePlannerRead();
const limit = clampSearchLimit(opts?.limit, 20, searchLimitCap());
const offset = opts?.offset || 0;
const detailFilter = opts?.detail === 'low' ? `AND cc.chunk_source = 'compiled_truth'` : '';
@@ -1351,7 +1367,7 @@ export class PGLiteEngine implements BrainEngine {
limit, offset, innerLimit, sourceFactorCase,
hardExcludeClause, visibilityClause, detailFilter, opts,
dedup: true,
- });
+ }).finally(settle);
}
// v0.20.0 Cathedral II Layer 10 C1/C2: language + symbol-kind filters.
@@ -1448,6 +1464,7 @@ export class PGLiteEngine implements BrainEngine {
const fallbackParams = [...params];
fallbackParams[0] = orQuery;
({ rows } = await this.db.query(keywordSql, fallbackParams));
+ settle();
// 2026-09 (#3617 follow-up): relaxed rows are TAGGED so hybrid's
// fusion can demote them — an OR-of-common-terms match must not
// outvote a healthy vector arm (SearchResult.keyword_relaxed doc).
@@ -1455,6 +1472,7 @@ export class PGLiteEngine implements BrainEngine {
}
}
+ settle();
return (rows as Record<string, unknown>[]).map(rowToSearchResult);
}
@@ -1614,6 +1632,7 @@ export class PGLiteEngine implements BrainEngine {
}
async searchVector(embedding: Float32Array, opts?: SearchOpts): Promise<SearchResult[]> {
+ const settle = await this.beforePlannerRead();
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()}`);
@@ -1644,6 +1663,7 @@ export class PGLiteEngine implements BrainEngine {
},
opts?.onVectorPoolMeta,
);
+ settle();
return rows.map(rowToSearchResult);
}
@@ -1851,7 +1871,7 @@ export class PGLiteEngine implements BrainEngine {
}
async getBacklinks(slug: string, opts?: { sourceId?: string; sourceIds?: string[]; excludePrivate?: boolean }): Promise<Link[]> {
- return linksImpl.getBacklinks(scopedRead(this.engineSql), slug, opts);
+ return this.plannerRead(() => linksImpl.getBacklinks(scopedRead(this.engineSql), slug, opts));
}
async listLinkSources(
@@ -1874,7 +1894,7 @@ export class PGLiteEngine implements BrainEngine {
depth: number = 5,
opts?: import('./engine.ts').TraverseGraphOpts,
): Promise<GraphNode[]> {
- return linksImpl.traverseGraph(unscopedExecutor(this.engineSql, 'links: unscoped on master (EO4 inventory)'), slug, depth, opts);
+ return this.plannerRead(() => linksImpl.traverseGraph(unscopedExecutor(this.engineSql, 'links: unscoped on master (EO4 inventory)'), slug, depth, opts));
}
async traversePaths(
@@ -1888,7 +1908,7 @@ export class PGLiteEngine implements BrainEngine {
slug: string,
opts?: { depth?: number; linkType?: string; direction?: 'in' | 'out' | 'both'; sourceId?: string; sourceIds?: string[]; excludePrivate?: boolean },
): Promise<{ paths: GraphPath[]; truncated: boolean }> {
- return linksImpl.traversePathsDetailed(unscopedExecutor(this.engineSql, 'links: unscoped on master (EO4 inventory)'), slug, opts);
+ return this.plannerRead(() => linksImpl.traversePathsDetailed(unscopedExecutor(this.engineSql, 'links: unscoped on master (EO4 inventory)'), slug, opts));
}
async relationalFanout(
@@ -1932,7 +1952,7 @@ export class PGLiteEngine implements BrainEngine {
excludePrivate?: boolean;
mode?: 'inbound' | 'islanded';
}): Promise<Array<{ slug: string; title: string; domain: string | null; type?: string | null; quarantined?: boolean; source_id?: string }>> {
- return linksImpl.findOrphanPages(unscopedExecutor(this.engineSql, 'links: unscoped on master (EO4 inventory)'), opts);
+ return this.plannerRead(() => linksImpl.findOrphanPages(unscopedExecutor(this.engineSql, 'links: unscoped on master (EO4 inventory)'), opts));
}
// Tags
@@ -2601,6 +2621,7 @@ export class PGLiteEngine implements BrainEngine {
}
async getHealth(opts?: { sourceId?: string; sourceIds?: string[] }): Promise<BrainHealth> {
+ const settle = await this.beforePlannerRead();
// Combined metrics from master (brain_score components: dead_links, link_count,
// pages_with_timeline) and v0.10.3 graph layer (link_coverage, timeline_coverage,
// most_connected). Both coexist: master's brain_score is the composite
@@ -2781,6 +2802,7 @@ export class PGLiteEngine implements BrainEngine {
const noDeadLinksScore = pageCount === 0 ? 10 : Math.round(noDeadLinks * 10);
const brainScore = embedCoverageScore + linkDensityScore + timelineCoverageScore + noOrphansScore + noDeadLinksScore;
+ settle();
return {
page_count: pageCount,
linkable_page_count: linkablePageCount,
diff --git a/src/core/planner-stats-schema.ts b/src/core/planner-stats-schema.ts
new file mode 100644
index 0000000000..9d96c3a30d
--- /dev/null
+++ b/src/core/planner-stats-schema.ts
@@ -0,0 +1,51 @@
+/**
+ * F4b (O-ENG-12, O-CEO-9): transactional planner-statistics accounting, PGLite
+ * only. PGLite has no autovacuum and never populates
+ * `pg_stat_user_tables.n_mod_since_analyze`, so every statement that changes
+ * a hot table records how many rows it touched. The rows commit or roll back
+ * with the data, survive crashes and restarts, and cover raw SQL, bulk writes
+ * and delete/reinsert. Insert-only: no shared counter row.
+ * `src/core/planner-stats.ts` turns them into row-delta ANALYZE.
+ *
+ * Applied only through `sqlFor.pglite` in the f4_planner_stats migration:
+ * Postgres keeps autovacuum and its write paths gain no trigger.
+ */
+export const PLANNER_STATS_TABLES = ['pages', 'links', 'facts', 'takes', 'content_chunks', 'timeline_entries'] as const;
+export type PlannerStatsTable = typeof PLANNER_STATS_TABLES[number];
+
+const triggers = (table: PlannerStatsTable) => `
+CREATE OR REPLACE TRIGGER planner_stats_ins AFTER INSERT ON ${table} REFERENCING NEW TABLE AS new_rows
+ FOR EACH STATEMENT EXECUTE FUNCTION gbrain_count_modifications();
+CREATE OR REPLACE TRIGGER planner_stats_upd AFTER UPDATE ON ${table} REFERENCING NEW TABLE AS new_rows
+ FOR EACH STATEMENT EXECUTE FUNCTION gbrain_count_modifications();
+CREATE OR REPLACE TRIGGER planner_stats_del AFTER DELETE ON ${table} REFERENCING OLD TABLE AS old_rows
+ FOR EACH STATEMENT EXECUTE FUNCTION gbrain_count_modifications();`;
+
+export const PLANNER_STATS_SCHEMA_SQL = `
+CREATE TABLE IF NOT EXISTS planner_stats_deltas (
+ id BIGSERIAL PRIMARY KEY,
+ table_name TEXT NOT NULL,
+ n BIGINT NOT NULL
+);
+CREATE TABLE IF NOT EXISTS planner_stats_state (
+ table_name TEXT PRIMARY KEY,
+ analyzed_through BIGINT NOT NULL DEFAULT 0,
+ analyzed_at TIMESTAMPTZ,
+ last_analyze_ms INTEGER
+);
+CREATE OR REPLACE FUNCTION gbrain_count_modifications() RETURNS trigger LANGUAGE plpgsql AS $$
+DECLARE
+ modified BIGINT;
+BEGIN
+ IF TG_OP = 'DELETE' THEN
+ SELECT count(*) INTO modified FROM old_rows;
+ ELSE
+ SELECT count(*) INTO modified FROM new_rows;
+ END IF;
+ IF modified > 0 THEN
+ INSERT INTO planner_stats_deltas (table_name, n) VALUES (TG_TABLE_NAME, modified);
+ END IF;
+ RETURN NULL;
+END $$;
+${PLANNER_STATS_TABLES.map(triggers).join('\n')}
+`;
diff --git a/src/core/planner-stats.ts b/src/core/planner-stats.ts
new file mode 100644
index 0000000000..56085cb458
--- /dev/null
+++ b/src/core/planner-stats.ts
@@ -0,0 +1,292 @@
+/**
+ * F4b (O-ENG-12, O-CEO-9, O-CEO-17): row-delta ANALYZE for PGLite.
+ *
+ * PGLite has no autovacuum, so planner statistics are only as fresh as the
+ * last explicit ANALYZE; without them search and graph reads plan as
+ * pages-by-pages nested loops. The f4_planner_stats migration
+ * (`planner-stats-schema.ts`) records every statement's row count on the hot
+ * 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
+ * per-table watermark: the highest delta id it read before the ANALYZE, so a
+ * modification committed between that read and the publication stays pending.
+ *
+ * Call sites: the PGLite engine's planner-sensitive reads (first relevant
+ * read, `planner.first_read_budget_ms`), bulk import and managed sync every
+ * `import.analyze_every_pages` pages, the cycle after its freshness phases,
+ * the resident consumer's idle tick, and `refreshProjectionStatistics` (full
+ * 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).
+ */
+import type { BrainEngine } from './engine.ts';
+import { PLANNER_STATS_TABLES, type PlannerStatsTable } from './planner-stats-schema.ts';
+
+export const PLANNER_STATS_MIN_PENDING = 500;
+export const PLANNER_STATS_PENDING_RATIO = 0.1;
+export const PLANNER_STATS_THROTTLE_MS = 2000;
+export const DEFAULT_FIRST_READ_BUDGET_MS = 2000;
+export const DEFAULT_IMPORT_ANALYZE_EVERY_PAGES = 500;
+export const PLANNER_STATS_REPAIR_COMMAND = 'gbrain repair planner-stats --apply';
+
+export type PlannerRefreshReason = 'first_read' | 'import' | 'managed_sync' | 'cycle' | 'idle' | 'repair';
+
+export interface PlannerTableState {
+ table: PlannerStatsTable;
+ pending: number;
+ reltuples: number;
+ has_stats: boolean;
+ threshold: number;
+ stale: boolean;
+ analyzed_at: string | null;
+ last_analyze_ms: number | null;
+}
+
+export interface PlannerRefreshResult {
+ reason: PlannerRefreshReason;
+ skipped?: 'not_pglite' | 'disabled' | 'throttled' | 'in_flight' | 'unavailable';
+ analyzed: Array<{ table: PlannerStatsTable; pending: number; ms: number }>;
+ /** Stale tables whose last ANALYZE exceeded the first-read budget: refreshed after the read instead of before it. */
+ deferred: PlannerStatsTable[];
+}
+
+interface PlannerTestHooks {
+ /** Runs after a table's ANALYZE and before its watermark is published. */
+ beforePublish?: (engine: BrainEngine, table: PlannerStatsTable, watermark: number) => Promise<void>;
+ /** Runs after each published ANALYZE. */
+ onAnalyzed?: (engine: BrainEngine, event: { reason: PlannerRefreshReason; table: PlannerStatsTable; pending: number; ms: number }) => Promise<void>;
+}
+
+const hooks: PlannerTestHooks = {};
+const runtime = new WeakMap<BrainEngine, { lastCheck: number; inflight: Promise<unknown> | null }>();
+
+function runtimeFor(engine: BrainEngine) {
+ let state = runtime.get(engine);
+ if (!state) runtime.set(engine, state = { lastCheck: 0, inflight: null });
+ return state;
+}
+
+const OFF = ['0', 'false', 'off', 'no'];
+
+/** `planner.auto_analyze` (config) with GBRAIN_PLANNER_AUTO_ANALYZE (env) taking precedence; default on. */
+export async function plannerAutoAnalyzeEnabled(engine: Pick<BrainEngine, 'getConfig'>): Promise<boolean> {
+ let raw = process.env.GBRAIN_PLANNER_AUTO_ANALYZE ?? null;
+ if (raw === null) {
+ try { raw = await engine.getConfig('planner.auto_analyze'); } catch { raw = null; }
+ }
+ return raw == null || !OFF.includes(raw.trim().toLowerCase());
+}
+
+async function numericConfig(engine: Pick<BrainEngine, 'getConfig'>, key: string, fallback: number): Promise<number> {
+ const raw = await engine.getConfig(key);
+ const value = raw == null || raw.trim() === '' ? NaN : Number(raw);
+ return Number.isFinite(value) && value >= 0 ? value : fallback;
+}
+
+/** `import.analyze_every_pages`: bulk import and managed sync check planner statistics every N pages (0 disables). */
+export async function importAnalyzeEveryPages(engine: BrainEngine): Promise<number> {
+ if (engine.kind !== 'pglite') return 0;
+ return Math.floor(await numericConfig(engine, 'import.analyze_every_pages', DEFAULT_IMPORT_ANALYZE_EVERY_PAGES));
+}
+
+export const plannerStatsThreshold = (reltuples: number) =>
+ Math.max(PLANNER_STATS_MIN_PENDING, PLANNER_STATS_PENDING_RATIO * Math.max(0, reltuples));
+
+/** Per hot table: rows modified since its watermark, planner row estimate and whether pg_stats has rows. Null before the migration. */
+export async function readPlannerStatsState(engine: BrainEngine): Promise<PlannerTableState[] | null> {
+ const [present] = await engine.executeRaw<{ ok: boolean }>(
+ "SELECT to_regclass('planner_stats_deltas') IS NOT NULL AND to_regclass('planner_stats_state') IS NOT NULL AS ok");
+ if (!present?.ok) return null;
+ const rows = await engine.executeRaw<{ table_name: PlannerStatsTable; pending: string | number; reltuples: number | null;
+ has_stats: boolean; analyzed_at: string | Date | null; last_analyze_ms: number | null }>(
+ `WITH pending AS (
+ SELECT d.table_name, sum(d.n) AS n FROM planner_stats_deltas d
+ LEFT JOIN planner_stats_state s ON s.table_name = d.table_name
+ WHERE d.id > COALESCE(s.analyzed_through, 0)
+ GROUP BY d.table_name)
+ SELECT t.table_name, COALESCE(p.n, 0)::bigint AS pending, c.reltuples::float8 AS reltuples,
+ EXISTS (SELECT 1 FROM pg_stats ps WHERE ps.schemaname = 'public' AND ps.tablename = t.table_name) AS has_stats,
+ s.analyzed_at, s.last_analyze_ms
+ FROM unnest($1::text[]) WITH ORDINALITY AS t(table_name, position)
+ LEFT JOIN pending p ON p.table_name = t.table_name
+ LEFT JOIN planner_stats_state s ON s.table_name = t.table_name
+ LEFT JOIN pg_class c ON c.oid = to_regclass('public.' || t.table_name)
+ ORDER BY t.position`,
+ [[...PLANNER_STATS_TABLES]]);
+ return rows.map(row => {
+ const pending = Number(row.pending);
+ const reltuples = Number(row.reltuples ?? -1);
+ const threshold = plannerStatsThreshold(reltuples);
+ return {
+ table: row.table_name, pending, reltuples, has_stats: row.has_stats, threshold,
+ stale: pending > threshold || (reltuples > 0 && !row.has_stats),
+ analyzed_at: row.analyzed_at == null ? null : new Date(row.analyzed_at).toISOString(),
+ last_analyze_ms: row.last_analyze_ms,
+ };
+ });
+}
+
+/**
+ * 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
+ * ANALYZE nor autoanalyze ran in the last hour.
+ */
+export async function readPostgresPlannerStats(engine: BrainEngine): Promise<PlannerTableState[]> {
+ const rows = await engine.executeRaw<{ table_name: PlannerStatsTable; pending: string | number; reltuples: number | null;
+ analyzed_at: string | Date | null; recent: boolean }>(
+ `SELECT s.relname AS table_name, s.n_mod_since_analyze AS pending, c.reltuples::float8 AS reltuples,
+ GREATEST(s.last_analyze, s.last_autoanalyze) AS analyzed_at,
+ COALESCE(GREATEST(s.last_analyze, s.last_autoanalyze) > now() - interval '1 hour', false) AS recent
+ FROM pg_stat_user_tables s JOIN pg_class c ON c.oid = s.relid
+ WHERE s.schemaname = current_schema() AND s.relname = ANY($1::text[])
+ ORDER BY array_position($1::text[], s.relname::text)`,
+ [[...PLANNER_STATS_TABLES]]);
+ return rows.map(row => {
+ const pending = Number(row.pending);
+ const reltuples = Number(row.reltuples ?? -1);
+ const threshold = plannerStatsThreshold(reltuples);
+ return { table: row.table_name, pending, reltuples, has_stats: true, threshold, stale: pending > threshold && !row.recent,
+ analyzed_at: row.analyzed_at == null ? null : new Date(row.analyzed_at).toISOString(), last_analyze_ms: null };
+ });
+}
+
+/** The engine's table states: the F4b deltas on PGLite (null before the migration), autovacuum's counters on Postgres. */
+export async function readPlannerTableStates(engine: BrainEngine): Promise<PlannerTableState[] | null> {
+ return engine.kind === 'pglite' ? readPlannerStatsState(engine) : readPostgresPlannerStats(engine);
+}
+
+/** `gbrain repair planner-stats --apply`: one bounded ANALYZE on the brain host (Postgres: 60 s statement, 2 s lock timeout). */
+export async function repairPlannerTable(engine: BrainEngine, table: PlannerStatsTable): Promise<void> {
+ if (!PLANNER_STATS_TABLES.includes(table)) throw new Error(`Not a planner statistics table: ${table}`);
+ if (engine.kind === 'pglite') {
+ await analyzePlannerTables(engine, [table], 'repair');
+ return;
+ }
+ await engine.transaction(async tx => {
+ await tx.executeRaw("SET LOCAL statement_timeout = '60s'");
+ await tx.executeRaw("SET LOCAL lock_timeout = '2s'");
+ await tx.executeRaw(`ANALYZE ${table}`);
+ });
+}
+
+async function readWatermarks(engine: BrainEngine, tables: readonly PlannerStatsTable[]): Promise<Map<PlannerStatsTable, number>> {
+ const rows = await engine.executeRaw<{ table_name: PlannerStatsTable; watermark: string | number }>(
+ `SELECT t.table_name, COALESCE((SELECT max(d.id) FROM planner_stats_deltas d WHERE d.table_name = t.table_name), 0) AS watermark
+ FROM unnest($1::text[]) AS t(table_name)`, [[...tables]]);
+ return new Map(rows.map(row => [row.table_name, Number(row.watermark)]));
+}
+
+/** `ms` null (a full ANALYZE, not timed per table) keeps the table's last measured ANALYZE time. */
+async function publishWatermark(engine: BrainEngine, table: PlannerStatsTable, watermark: number, ms: number | null): Promise<void> {
+ await engine.executeRaw(
+ `INSERT INTO planner_stats_state (table_name, analyzed_through, analyzed_at, last_analyze_ms) VALUES ($1, $2, now(), $3)
+ ON CONFLICT (table_name) DO UPDATE SET analyzed_through = GREATEST(planner_stats_state.analyzed_through, EXCLUDED.analyzed_through),
+ analyzed_at = EXCLUDED.analyzed_at, last_analyze_ms = COALESCE(EXCLUDED.last_analyze_ms, planner_stats_state.last_analyze_ms)`,
+ [table, watermark, ms === null ? null : Math.round(ms)]);
+ await engine.executeRaw('DELETE FROM planner_stats_deltas WHERE table_name = $1 AND id <= $2', [table, watermark]);
+}
+
+/**
+ * ANALYZE each table, then publish its watermark (read before the ANALYZE) and
+ * drop the deltas it covers in one transaction. Table names come only from
+ * PLANNER_STATS_TABLES.
+ */
+export async function analyzePlannerTables(engine: BrainEngine, tables: readonly PlannerStatsTable[], reason: PlannerRefreshReason,
+ pending: ReadonlyMap<PlannerStatsTable, number> = new Map()): Promise<PlannerRefreshResult['analyzed']> {
+ const analyzed: PlannerRefreshResult['analyzed'] = [];
+ for (const table of tables) {
+ if (!PLANNER_STATS_TABLES.includes(table)) throw new Error(`Not a planner statistics table: ${table}`);
+ const watermark = (await readWatermarks(engine, [table])).get(table) ?? 0;
+ const started = performance.now();
+ await engine.executeRaw(`ANALYZE ${table}`);
+ const ms = performance.now() - started;
+ await hooks.beforePublish?.(engine, table, watermark);
+ await engine.transaction(tx => publishWatermark(tx, table, watermark, ms));
+ const event = { table, pending: pending.get(table) ?? 0, ms: Math.round(ms) };
+ analyzed.push(event);
+ await hooks.onAnalyzed?.(engine, { reason, ...event });
+ }
+ return analyzed;
+}
+
+/**
+ * After a full ANALYZE (GBRA-39's `refreshProjectionStatistics` on PGLite):
+ * read the watermarks first with `beginFullAnalyze`, ANALYZE, then call the
+ * returned function in the same transaction to publish them for every table.
+ * A no-op before the migration and on Postgres.
+ */
+export async function beginFullAnalyze(engine: BrainEngine): Promise<() => Promise<void>> {
+ const noop = async () => {};
+ if (engine.kind !== 'pglite') return noop;
+ const [present] = await engine.executeRaw<{ ok: boolean }>("SELECT to_regclass('planner_stats_state') IS NOT NULL AS ok");
+ if (!present?.ok) return noop;
+ const marks = await readWatermarks(engine, PLANNER_STATS_TABLES);
+ return async () => {
+ for (const table of PLANNER_STATS_TABLES) await publishWatermark(engine, table, marks.get(table) ?? 0, null);
+ };
+}
+
+/**
+ * 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
+ * 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.
+ */
+export async function maybeRefreshPlannerStats(engine: BrainEngine, reason: PlannerRefreshReason,
+ opts: { throttle?: boolean; budgetMs?: number } = {}): Promise<PlannerRefreshResult> {
+ const result: PlannerRefreshResult = { reason, analyzed: [], deferred: [] };
+ if (engine.kind !== 'pglite') return { ...result, skipped: 'not_pglite' };
+ const state = runtimeFor(engine);
+ if (state.inflight) {
+ await state.inflight.catch(() => {});
+ return { ...result, skipped: 'in_flight' };
+ }
+ if (opts.throttle !== false && Date.now() - state.lastCheck < PLANNER_STATS_THROTTLE_MS) return { ...result, skipped: 'throttled' };
+ state.lastCheck = Date.now();
+ if (!await plannerAutoAnalyzeEnabled(engine)) return { ...result, skipped: 'disabled' };
+ const run = (async (): Promise<PlannerRefreshResult> => {
+ const tables = await readPlannerStatsState(engine);
+ if (!tables) return { ...result, skipped: 'unavailable' };
+ const stale = tables.filter(t => t.stale);
+ 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])));
+ return result;
+ })();
+ state.inflight = run;
+ try { return await run; } finally { state.inflight = null; }
+}
+
+/**
+ * The first relevant read (O-ENG-12): refresh stale tables within
+ * `planner.first_read_budget_ms` before the read; the returned function, called
+ * once the read has answered, refreshes the tables whose last ANALYZE exceeded
+ * the budget. Never throws: planner upkeep must not fail a read.
+ */
+export async function beforePlannerRead(engine: BrainEngine): Promise<() => void> {
+ const noop = () => {};
+ const state = runtimeFor(engine);
+ if (!state.inflight && Date.now() - state.lastCheck < PLANNER_STATS_THROTTLE_MS) return noop;
+ try {
+ const budgetMs = await numericConfig(engine, 'planner.first_read_budget_ms', DEFAULT_FIRST_READ_BUDGET_MS);
+ const { deferred } = await maybeRefreshPlannerStats(engine, 'first_read', { budgetMs });
+ if (deferred.length === 0) return noop;
+ return () => {
+ if (state.inflight) return;
+ const run = analyzePlannerTables(engine, deferred, 'first_read').catch(() => []);
+ state.inflight = run.finally(() => { state.inflight = null; });
+ };
+ } catch {
+ return noop;
+ }
+}
+
+/** Exposed for tests. */
+export const __testing = {
+ hooks,
+ /** Forget an engine's throttle and in-flight state. */
+ reset(engine: BrainEngine) { runtime.delete(engine); },
+};
diff --git a/src/core/repair/core.ts b/src/core/repair/core.ts
index 273ff7d078..75596c5f28 100644
--- a/src/core/repair/core.ts
+++ b/src/core/repair/core.ts
@@ -23,7 +23,7 @@ import { getWriteRequest } from '../persistence/journal.ts';
import { initializeLocalPersistence, requestPrincipalForContext } from '../persistence/page-mutations.ts';
import { lookupEmbeddingPrice, estimateCostFromChars } from '../embedding-pricing.ts';
-export const REPAIR_KINDS = ['timeline', 'visibility', 'safe-chunks', 'contextual-mode', 'connector-checkpoints', 'request-indexes', 'connector-fences', 'orphan-bindings', 'embedding-effects', 'google-file-modes', 'stale-atoms', 'extractor-facts', 'captured-facts', 'loop-facts', 'orphan-children'] as const;
+export const REPAIR_KINDS = ['timeline', 'visibility', 'safe-chunks', 'contextual-mode', 'connector-checkpoints', 'request-indexes', 'connector-fences', 'orphan-bindings', 'embedding-effects', 'google-file-modes', 'stale-atoms', 'extractor-facts', 'captured-facts', 'loop-facts', 'orphan-children', 'planner-stats'] as const;
export type RepairKind = typeof REPAIR_KINDS[number];
export interface RepairScope { brain_id: string; source_ids: string[] }
diff --git a/src/core/repair/planner-stats.ts b/src/core/repair/planner-stats.ts
new file mode 100644
index 0000000000..56853f2c67
--- /dev/null
+++ b/src/core/repair/planner-stats.ts
@@ -0,0 +1,32 @@
+/**
+ * `gbrain repair planner-stats` (F4b, O-DX-9): ANALYZE the hot tables doctor
+ * `planner_stats_stale` reports. The preview lists each stale table with its
+ * pending row count; `--apply` runs one bounded ANALYZE per table on the brain
+ * host (Postgres: 60 s statement timeout, 2 s lock timeout; PGLite also
+ * 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.
+ */
+import { PLANNER_STATS_TABLES, type PlannerStatsTable } from '../planner-stats-schema.ts';
+import { readPlannerTableStates, repairPlannerTable } from '../planner-stats.ts';
+import type { RepairHandler, RepairItem } from './core.ts';
+
+export const plannerStatsRepair: RepairHandler = {
+ kind: 'planner-stats',
+ publication: 'projection',
+ embeds: false,
+ // 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 => ({
+ 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 (!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/repair/registry.ts b/src/core/repair/registry.ts
index 4c8d52ee03..d3fbb66475 100644
--- a/src/core/repair/registry.ts
+++ b/src/core/repair/registry.ts
@@ -37,6 +37,7 @@ import { extractorFactsRepair } from './extractor-facts.ts';
import { capturedFactsRepair } from './captured-facts.ts';
import { loopFactsRepair } from './loop-facts.ts';
import { orphanChildrenRepair } from './orphan-children.ts';
+import { plannerStatsRepair } from './planner-stats.ts';
import { ERROR_CATALOGUE, catalogueError } from '../error-catalogue.ts';
import type { OperationError } from '../ops/contract.ts';
@@ -138,6 +139,12 @@ const SPECS: Record<RepairKind, Omit<RepairKindSpec, 'kind'>> = {
+ 'links.origin_page_id and files.page_id references (#5216, #4738). The preview also probes every page body and reports torn TOAST rows '
+ '(SQLSTATE XX000) as torn_pages without changing them. Bookkeeping only; no journal admission. Brain-wide; runs only when named.',
},
+ 'planner-stats': {
+ handler: plannerStatsRepair, embeds: 'none', checks: ['planner_stats_stale'],
+ summary: 'ANALYZE the hot tables (pages, links, facts, takes, content_chunks, timeline_entries) whose planner statistics are stale (F4b), '
+ + 'so search and graph reads stop planning as slow nested loops. PGLite also resets each table\'s pending row count; Postgres runs each '
+ + 'ANALYZE with a 60 s statement and 2 s lock timeout. No journal admission and no user data changes. Brain-wide.',
+ },
};
export const REPAIR_REGISTRY: readonly RepairKindSpec[] = REPAIR_KINDS.map(kind => ({ kind, ...SPECS[kind] }));
diff --git a/src/core/schema-migrations/registry.generated.ts b/src/core/schema-migrations/registry.generated.ts
index a15abb5b68..173f0d3a1f 100644
--- a/src/core/schema-migrations/registry.generated.ts
+++ b/src/core/schema-migrations/registry.generated.ts
@@ -193,6 +193,7 @@ import { v189 } from './v189-pages-credential-projection-pending.ts';
import { v190 } from './v190-sources-upstream-observation.ts';
import { v191 } from './v191-alias-source-cascade.ts';
import { v192 } from './v192-take-embedding-identity.ts';
+import { v193 } from './v193-f4-planner-stats.ts';
// Array order is historical (see HISTORICAL_ARRAY_ORDER in the generator); the
// runner sorts by version before applying.
@@ -384,4 +385,5 @@ export const MIGRATIONS: Migration[] = [
v190,
v191,
v192,
+ v193,
];
diff --git a/src/core/schema-migrations/v193-f4-planner-stats.ts b/src/core/schema-migrations/v193-f4-planner-stats.ts
new file mode 100644
index 0000000000..59ec02ea9d
--- /dev/null
+++ b/src/core/schema-migrations/v193-f4-planner-stats.ts
@@ -0,0 +1,21 @@
+import type { Migration } from './types.ts';
+import { PLANNER_STATS_SCHEMA_SQL } from '../planner-stats-schema.ts';
+
+// Applied by src/core/migrate.ts on the next initSchema(); see docs/ENGINES.md
+// ("Canonical schema sources") for when schema.sql or a TS fragment also changes.
+//
+// Foundations 1 (F4b) planner-statistics accounting: the planner_stats_deltas /
+// planner_stats_state tables and the AFTER STATEMENT transition-table triggers
+// on the six hot tables (DDL in src/core/planner-stats-schema.ts). PGLite only:
+// Postgres has autovacuum, so this migration is a no-op there and Postgres write
+// paths gain no trigger. Not in schema.sql: facts and takes are created by
+// migrations, so the PGLite bootstrap blob cannot carry their triggers, and every
+// fresh PGLite brain runs this migration anyway.
+// Placeholder version: the Foundations integrator renumbers it.
+export const v193: Migration = {
+ version: 193,
+ name: 'f4_planner_stats',
+ idempotent: true,
+ sql: '',
+ sqlFor: { pglite: PLANNER_STATS_SCHEMA_SQL },
+};
diff --git a/src/core/search/projection-statistics.ts b/src/core/search/projection-statistics.ts
index 889cb4851d..899761980a 100644
--- a/src/core/search/projection-statistics.ts
+++ b/src/core/search/projection-statistics.ts
@@ -1,4 +1,5 @@
import type { BrainEngine } from '../engine.ts';
+import { beginFullAnalyze, plannerAutoAnalyzeEnabled } from '../planner-stats.ts';
export const PROJECTION_STATISTICS_NAME = 'pages_text_projection_current_stats';
@@ -49,6 +50,8 @@ export async function refreshProjectionStatistics(engine: BrainEngine): Promise<
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;
}
+ // F4b: `planner.auto_analyze=false` keeps PGLite on the narrow refresh the projection statistics need.
+ const full = engine.kind === 'pglite' && await plannerAutoAnalyzeEnabled(engine);
await engine.transaction(async tx => {
if (engine.kind === 'postgres') {
await tx.executeRaw("SET LOCAL statement_timeout = '30s'");
@@ -58,7 +61,10 @@ export async function refreshProjectionStatistics(engine: BrainEngine): Promise<
// planner sees empty tables and runs search's graph joins as pages-by-pages nested loops (about 50 s
// per search on a freshly imported 4,000-page brain; 6 ms after ANALYZE). Postgres keeps the narrow
// refresh and leaves the rest to autovacuum.
- await tx.executeRaw(engine.kind === 'pglite' ? 'ANALYZE' : 'ANALYZE pages(text_projection_revision, knowledge_revision)');
+ // F4b: the full ANALYZE covers every hot table, so it publishes their planner-stats watermarks too.
+ const publishWatermarks = full ? await beginFullAnalyze(tx) : async () => {};
+ await tx.executeRaw(full ? 'ANALYZE' : 'ANALYZE pages(text_projection_revision, knowledge_revision)');
+ await publishWatermarks();
await verifyProjectionStatistics(tx);
});
return true;
diff --git a/test/e2e/planner-stats-postgres.test.ts b/test/e2e/planner-stats-postgres.test.ts
new file mode 100644
index 0000000000..6d577c10b0
--- /dev/null
+++ b/test/e2e/planner-stats-postgres.test.ts
@@ -0,0 +1,73 @@
+/**
+ * F4b (spec 5.3 test 9, O-CEO-9): on Postgres the f4_planner_stats migration
+ * is a no-op (autovacuum owns statistics): no planner_stats_* table, no
+ * gbrain_count_modifications function, no planner_stats_* trigger, and
+ * 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.
+ */
+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 { 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';
+
+const RUN = hasDatabase();
+const d = RUN ? describe : describe.skip;
+
+d('planner stats on Postgres', () => {
+ beforeAll(async () => { await setupDB(); });
+ afterAll(async () => { await teardownDB(); });
+
+ async function doctor(): Promise<Check> {
+ const entry = DOCTOR_CHECK_REGISTRY.find(e => e.name === 'planner_stats_stale')!;
+ const ctx = { engine: getEngine(), progress: { heartbeat() {}, start() {}, tick() {}, finish() {} } } as unknown as DoctorContext;
+ return ((await entry.run(ctx)) as Check[])[0]!;
+ }
+
+ test('9. no planner_stats objects exist and the refresh is a no-op', async () => {
+ const engine = getEngine();
+ const [objects] = await engine.executeRaw<{ tables: number; functions: number; triggers: number }>(
+ `SELECT (SELECT count(*)::int FROM pg_class WHERE relname LIKE 'planner_stats%') AS tables,
+ (SELECT count(*)::int FROM pg_proc WHERE proname = 'gbrain_count_modifications') AS functions,
+ (SELECT count(*)::int FROM pg_trigger WHERE tgname LIKE 'planner_stats%') AS triggers`);
+ expect(objects).toEqual({ tables: 0, functions: 0, triggers: 0 });
+ expect((await maybeRefreshPlannerStats(engine, 'first_read', { throttle: false })).skipped).toBe('not_pglite');
+ });
+
+ test('9. doctor reads pg_stat_user_tables; repair planner-stats analyzes the stale table', async () => {
+ const engine = getEngine();
+ await engine.executeRaw(`INSERT INTO facts (fact, source) SELECT 'pg claim ' || g, 'test' FROM generate_series(1, 2000) g`);
+ // pg_stat counters are reported asynchronously by the backend; wait until the inserts are visible.
+ for (let i = 0; i < 50; i++) {
+ await engine.executeRaw('SELECT pg_stat_clear_snapshot()');
+ const facts = (await readPostgresPlannerStats(engine)).find(t => t.table === 'facts');
+ if (facts && facts.pending >= 2000) break;
+ await new Promise(resolve => setTimeout(resolve, 200));
+ }
+ const states = await readPostgresPlannerStats(engine);
+ const facts = states.find(t => t.table === 'facts')!;
+ expect(facts.pending).toBeGreaterThanOrEqual(2000);
+ expect(states.map(t => t.table)).toContain('pages');
+
+ const check = await doctor();
+ expect(check.details?.engine).toBe('postgres');
+ expect(check.details?.fix).toBe('gbrain repair planner-stats --apply');
+ if (facts.stale) {
+ expect(check.status).toBe('warn');
+ expect(check.message).toContain('facts (');
+ const plan = await plannerStatsRepair.plan(engine, { brain_id: 'host', source_ids: [] }, null);
+ expect(plan.items.map(i => i.slug)).toContain('facts');
+ const ctx = { engine, logger: { info() {}, warn() {}, error() {} } } as never;
+ expect(await plannerStatsRepair.apply(ctx, plan.items.find(i => i.slug === 'facts')!)).toBe(true);
+ } else {
+ // Autovacuum (or a prior ANALYZE) touched facts within the last hour: Postgres does not warn then.
+ expect(facts.analyzed_at).not.toBeNull();
+ }
+ await engine.executeRaw('SELECT pg_stat_clear_snapshot()');
+ const after = (await readPostgresPlannerStats(engine)).find(t => t.table === 'facts')!;
+ expect(after.stale).toBe(false);
+ });
+});
diff --git a/test/e2e/schema-catalog-golden.test.ts b/test/e2e/schema-catalog-golden.test.ts
index 4af10c6bb2..36be5cbca2 100644
--- a/test/e2e/schema-catalog-golden.test.ts
+++ b/test/e2e/schema-catalog-golden.test.ts
@@ -71,6 +71,8 @@ if (skip) console.log('Skipping E2E schema catalog goldens (DATABASE_URL not set
const CAPTURE_TIMEOUT = 240_000;
/** Same allowlist as test/e2e/schema-drift.test.ts (Postgres-only by design). */
const PG_ONLY_TABLES = ['file_migration_ledger'];
+/** F4b planner-stats accounting: PGLite-only by design (Postgres has autovacuum). */
+const PGLITE_ONLY_TABLES = ['planner_stats_deltas', 'planner_stats_state'];
function withDatabase(url: string, name: string): string {
const u = new URL(url);
@@ -189,7 +191,7 @@ describe.skipIf(skip)('Postgres catalog goldens (E4, E2E)', () => {
test('T-G13: PG <-> PGLite column parity stays name-based (existing drift contract)', async () => {
const pglite = await withCatalogConfig(CATALOG_CONFIGS[0], capturePgliteEngineCatalog);
const diff = diffSnapshots(toSchemaSnapshot(requireCaptured('engine:default')), toSchemaSnapshot(pglite), {
- allowlistPgOnlyTables: PG_ONLY_TABLES,
+ allowlistPgOnlyTables: PG_ONLY_TABLES, allowlistPgliteOnlyTables: PGLITE_ONLY_TABLES,
});
if (!isCleanDiff(diff)) throw new Error(`PG <-> PGLite column drift:\n${formatDiffForFailure(diff)}`);
expect(isCleanDiff(diff)).toBe(true);
diff --git a/test/e2e/schema-drift.test.ts b/test/e2e/schema-drift.test.ts
index 9b272521a3..ca04574226 100644
--- a/test/e2e/schema-drift.test.ts
+++ b/test/e2e/schema-drift.test.ts
@@ -176,7 +176,8 @@ describe.skipIf(skip)('schema drift: PGLite ↔ Postgres post-initSchema parity
}, 30_000);
test('post-initSchema schemas are equivalent (modulo allowlist)', () => {
- const diff = diffSnapshots(pgSnap, pgliteSnap, { allowlistPgOnlyTables: PG_ONLY_TABLES });
+ // F4b planner-stats accounting is PGLite-only by design (Postgres has autovacuum).
+ const diff = diffSnapshots(pgSnap, pgliteSnap, { allowlistPgOnlyTables: PG_ONLY_TABLES, allowlistPgliteOnlyTables: ['planner_stats_deltas', 'planner_stats_state'] });
if (!isCleanDiff(diff)) {
throw new Error(`Schema drift detected:\n${formatDiffForFailure(diff)}`);
}
diff --git a/test/fix-wave-3-integration.test.ts b/test/fix-wave-3-integration.test.ts
index 49c98ed9be..901d5ceb86 100644
--- a/test/fix-wave-3-integration.test.ts
+++ b/test/fix-wave-3-integration.test.ts
@@ -431,7 +431,7 @@ test('check 9: every registered repair kind reaches the remediation plan with it
await engine.executeRaw("UPDATE pages SET contextual_retrieval_mode=NULL,chunker_version=1,text_projection_revision=gen_random_uuid() WHERE source_id=$1 AND slug='people/second-example'", [f.id]);
await engine.executeRaw("INSERT INTO op_checkpoints(op,fingerprint,completed_keys,updated_at) VALUES('managed-connector',$1,'[]'::jsonb,now()-interval '9 days')", [`orphan-${randomUUID()}`]);
const kinds = AUTO_REPAIR_REGISTRY.map(spec => spec.kind);
- expect(kinds).toEqual(['timeline', 'visibility', 'safe-chunks', 'contextual-mode', 'connector-checkpoints', 'request-indexes', 'connector-fences', 'orphan-bindings', 'embedding-effects']);
+ expect(kinds).toEqual(['timeline', 'visibility', 'safe-chunks', 'contextual-mode', 'connector-checkpoints', 'request-indexes', 'connector-fences', 'orphan-bindings', 'embedding-effects', 'planner-stats']);
const planned = Object.fromEntries((await planRepairSteps(engine, { noEmbed: true })).map(step => [step.kind, step]));
expect(planned['contextual-mode']).toMatchObject({ paid: false, embeds: 'inline', command: 'gbrain repair contextual-mode --no-embed --apply' });
expect(planned['connector-checkpoints']).toMatchObject({ paid: false, embeds: 'none' });
diff --git a/test/fix-wave-4-integration.test.ts b/test/fix-wave-4-integration.test.ts
index 0c53d5db09..f0a6db6398 100644
--- a/test/fix-wave-4-integration.test.ts
+++ b/test/fix-wave-4-integration.test.ts
@@ -210,7 +210,7 @@ test('X6: deactivate carries a held connector item into classic state (wave 5):
test('X11: the remediation run reaches every new repair kind, runs the free ones under --max-usd 0 and clears their doctor findings', async () => withEnv(env, async () => {
for (const engine of engines) {
expect(AUTO_REPAIR_REGISTRY.map(spec => spec.kind)).toEqual(['timeline', 'visibility', 'safe-chunks', 'contextual-mode', 'connector-checkpoints',
- 'request-indexes', 'connector-fences', 'orphan-bindings', 'embedding-effects']);
+ 'request-indexes', 'connector-fences', 'orphan-bindings', 'embedding-effects', 'planner-stats']);
// Pending work for Lane A (a dropped index) and Lane D (an orphan binding of a removed source).
await engine.executeRaw('DROP INDEX IF EXISTS persistence_requests_sync_run_open');
await withPersistenceOff(engine, async () => {
diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-default.json b/test/fixtures/goldens/catalog/pglite-engine-init-default.json
index 7bb9733603..dcafb91cbb 100644
--- a/test/fixtures/goldens/catalog/pglite-engine-init-default.json
+++ b/test/fixtures/goldens/catalog/pglite-engine-init-default.json
@@ -195,6 +195,8 @@
"persistence_writer_protocols.persistence_writer_protocols_pkey": "p PRIMARY KEY (worktree_id, host_id)",
"persistence_writer_protocols.persistence_writer_protocols_protocol_version_check": "c CHECK ((protocol_version = 2))",
"persistence_writer_protocols.persistence_writer_protocols_worktree_id_fkey": "f FOREIGN KEY (worktree_id) REFERENCES persistence_worktrees(id)",
+ "planner_stats_deltas.planner_stats_deltas_pkey": "p PRIMARY KEY (id)",
+ "planner_stats_state.planner_stats_state_pkey": "p PRIMARY KEY (table_name)",
"query_cache.query_cache_pkey": "p PRIMARY KEY (id)",
"raw_data.raw_data_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",
"raw_data.raw_data_page_id_source_key": "u UNIQUE (page_id, source)",
@@ -294,6 +296,7 @@
"gbrain_advance_page_revision()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=ae793ff5263f7b76311e0c22593fb658db9f82e7b3781914421d9508b6da0e88",
"gbrain_advance_tag_revision()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=7807b26b4933148aa63c67fca824a60d3492396728205d04e16c48c81174cbd5",
"gbrain_clear_atom_page_state()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=7db0ef05d1220a579e64428b2dd7cf5183191da186fbe64b6496433a7a713d11",
+ "gbrain_count_modifications()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=9518c925621def19cafb2918da4d41e602ce94619af872eafa3c11b46c66296f",
"gbrain_fact_fingerprint(claim text)": "RETURNS text kind=f lang=sql volatility=i secdef=false config=[] body_sha256=666cc212d15431ede62a3d1e8932676a950705717852262f86df6d836d526ab4",
"gbrain_fact_fingerprint_v1(claim text)": "RETURNS text kind=f lang=sql volatility=i secdef=false config=[] body_sha256=38f7cfc0016f2b34d6f54652f4910cf1dd5240fbec5fd636c782e46fb70a6c7d",
"gbrain_fact_normalize(claim text)": "RETURNS text kind=f lang=sql volatility=i secdef=false config=[] body_sha256=5fff22c689f79bb28b4cc66254ca3a42c2fc809be193c6ceaf75c3200a353035",
@@ -526,6 +529,12 @@
"persistence_writer_protocols": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
+ "planner_stats_deltas": [
+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
+ ],
+ "planner_stats_state": [
+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
+ ],
"query_cache": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
@@ -871,6 +880,8 @@
"persistence_topology_recovering": "CREATE INDEX persistence_topology_recovering ON public.persistence_topology_changes USING btree (created_at) WHERE (state = 'recovering'::text)",
"persistence_worktrees_pkey": "CREATE UNIQUE INDEX persistence_worktrees_pkey ON public.persistence_worktrees USING btree (id)",
"persistence_writer_protocols_pkey": "CREATE UNIQUE INDEX persistence_writer_protocols_pkey ON public.persistence_writer_protocols USING btree (worktree_id, host_id)",
+ "planner_stats_deltas_pkey": "CREATE UNIQUE INDEX planner_stats_deltas_pkey ON public.planner_stats_deltas USING btree (id)",
+ "planner_stats_state_pkey": "CREATE UNIQUE INDEX planner_stats_state_pkey ON public.planner_stats_state USING btree (table_name)",
"query_cache_pkey": "CREATE UNIQUE INDEX query_cache_pkey ON public.query_cache USING btree (id)",
"raw_data_page_id_source_key": "CREATE UNIQUE INDEX raw_data_page_id_source_key ON public.raw_data USING btree (page_id, source)",
"raw_data_pkey": "CREATE UNIQUE INDEX raw_data_pkey ON public.raw_data USING btree (id)",
@@ -976,6 +987,7 @@
"pages_id_seq": "integer start=1 min=1 max=2147483647 increment=1 cycle=false cache=1 owned_by=pages.id",
"persistence_effects_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=persistence_effects.id",
"persistence_requests_sequence_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=persistence_requests.sequence",
+ "planner_stats_deltas_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=planner_stats_deltas.id",
"raw_data_id_seq": "integer start=1 min=1 max=2147483647 increment=1 cycle=false cache=1 owned_by=raw_data.id",
"slug_aliases_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=slug_aliases.id",
"subagent_messages_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=subagent_messages.id",
@@ -2157,6 +2169,23 @@
],
"flags": "relkind=r rls=true force_rls=false"
},
+ "planner_stats_deltas": {
+ "columns": [
+ "1 id bigint/int8 NOT NULL DEFAULT nextval('planner_stats_deltas_id_seq'::regclass)",
+ "2 table_name text/text NOT NULL",
+ "3 n bigint/int8 NOT NULL"
+ ],
+ "flags": "relkind=r rls=false force_rls=false"
+ },
+ "planner_stats_state": {
+ "columns": [
+ "1 table_name text/text NOT NULL",
+ "2 analyzed_through bigint/int8 NOT NULL DEFAULT 0",
+ "3 analyzed_at timestamp with time zone/timestamptz NULL",
+ "4 last_analyze_ms integer/int4 NULL"
+ ],
+ "flags": "relkind=r rls=false force_rls=false"
+ },
"query_cache": {
"columns": [
"1 id text/text NOT NULL",
@@ -2595,8 +2624,17 @@
},
"triggers": {
"content_chunks.chunk_search_vector_trigger": "CREATE TRIGGER chunk_search_vector_trigger BEFORE INSERT OR UPDATE OF chunk_text, doc_comment, symbol_name_qualified ON public.content_chunks FOR EACH ROW EXECUTE FUNCTION update_chunk_search_vector()",
+ "content_chunks.planner_stats_del": "CREATE TRIGGER planner_stats_del AFTER DELETE ON public.content_chunks REFERENCING OLD TABLE AS old_rows FOR EACH STATEMENT EXECUTE FUNCTION gbrain_count_modifications()",
+ "content_chunks.planner_stats_ins": "CREATE TRIGGER planner_stats_ins AFTER INSERT ON public.content_chunks REFERENCING NEW TABLE AS new_rows FOR EACH STATEMENT EXECUTE FUNCTION gbrain_count_modifications()",
+ "content_chunks.planner_stats_upd": "CREATE TRIGGER planner_stats_upd AFTER UPDATE ON public.content_chunks REFERENCING NEW TABLE AS new_rows FOR EACH STATEMENT EXECUTE FUNCTION gbrain_count_modifications()",
"facts.facts_preserve_withdrawal": "CREATE TRIGGER facts_preserve_withdrawal BEFORE INSERT OR UPDATE OF fact, source_id, visibility, entity_slug, expired_at ON public.facts FOR EACH ROW EXECUTE FUNCTION gbrain_preserve_fact_withdrawal()",
"facts.managed_writer_guard": "CREATE TRIGGER managed_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.facts FOR EACH ROW EXECUTE FUNCTION gbrain_require_managed_writer()",
+ "facts.planner_stats_del": "CREATE TRIGGER planner_stats_del AFTER DELETE ON public.facts REFERENCING OLD TABLE AS old_rows FOR EACH STATEMENT EXECUTE FUNCTION gbrain_count_modifications()",
+ "facts.planner_stats_ins": "CREATE TRIGGER planner_stats_ins AFTER INSERT ON public.facts REFERENCING NEW TABLE AS new_rows FOR EACH STATEMENT EXECUTE FUNCTION gbrain_count_modifications()",
+ "facts.planner_stats_upd": "CREATE TRIGGER planner_stats_upd AFTER UPDATE ON public.facts REFERENCING NEW TABLE AS new_rows FOR EACH STATEMENT EXECUTE FUNCTION gbrain_count_modifications()",
+ "links.planner_stats_del": "CREATE TRIGGER planner_stats_del AFTER DELETE ON public.links REFERENCING OLD TABLE AS old_rows FOR EACH STATEMENT EXECUTE FUNCTION gbrain_count_modifications()",
+ "links.planner_stats_ins": "CREATE TRIGGER planner_stats_ins AFTER INSERT ON public.links REFERENCING NEW TABLE AS new_rows FOR EACH STATEMENT EXECUTE FUNCTION gbrain_count_modifications()",
+ "links.planner_stats_upd": "CREATE TRIGGER planner_stats_upd AFTER UPDATE ON public.links REFERENCING NEW TABLE AS new_rows FOR EACH STATEMENT EXECUTE FUNCTION gbrain_count_modifications()",
"minion_jobs.minion_queue_protocol": "CREATE TRIGGER minion_queue_protocol BEFORE INSERT OR UPDATE ON public.minion_jobs FOR EACH ROW EXECUTE FUNCTION enforce_minion_queue_protocol()",
"page_aliases.managed_writer_guard": "CREATE TRIGGER managed_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.page_aliases FOR EACH ROW EXECUTE FUNCTION gbrain_require_managed_writer()",
"pages.bump_page_generation_clock_trg": "CREATE TRIGGER bump_page_generation_clock_trg AFTER INSERT OR DELETE OR UPDATE ON public.pages FOR EACH STATEMENT EXECUTE FUNCTION bump_page_generation_clock_fn()",
@@ -2605,6 +2643,9 @@
"pages.pages_clear_atom_scan_state": "CREATE TRIGGER pages_clear_atom_scan_state AFTER UPDATE ON public.pages FOR EACH ROW EXECUTE FUNCTION gbrain_clear_atom_page_state()",
"pages.pages_knowledge_revision": "CREATE TRIGGER pages_knowledge_revision BEFORE UPDATE ON public.pages FOR EACH ROW EXECUTE FUNCTION gbrain_advance_page_revision()",
"pages.pages_projection_queue": "CREATE TRIGGER pages_projection_queue AFTER INSERT OR DELETE OR UPDATE ON public.pages FOR EACH ROW EXECUTE FUNCTION gbrain_queue_page_projection()",
+ "pages.planner_stats_del": "CREATE TRIGGER planner_stats_del AFTER DELETE ON public.pages REFERENCING OLD TABLE AS old_rows FOR EACH STATEMENT EXECUTE FUNCTION gbrain_count_modifications()",
+ "pages.planner_stats_ins": "CREATE TRIGGER planner_stats_ins AFTER INSERT ON public.pages REFERENCING NEW TABLE AS new_rows FOR EACH STATEMENT EXECUTE FUNCTION gbrain_count_modifications()",
+ "pages.planner_stats_upd": "CREATE TRIGGER planner_stats_upd AFTER UPDATE ON public.pages REFERENCING NEW TABLE AS new_rows FOR EACH STATEMENT EXECUTE FUNCTION gbrain_count_modifications()",
"pages.trg_pages_search_vector": "CREATE TRIGGER trg_pages_search_vector BEFORE INSERT OR UPDATE OF title, timeline ON public.pages FOR EACH ROW EXECUTE FUNCTION update_page_search_vector()",
"persistence_brain.gbrain_protocol_activation": "CREATE TRIGGER gbrain_protocol_activation BEFORE UPDATE ON public.persistence_brain FOR EACH ROW EXECUTE FUNCTION gbrain_guard_protocol_activation()",
"persistence_effects.gbrain_effect_protocol": "CREATE TRIGGER gbrain_effect_protocol BEFORE INSERT OR DELETE OR UPDATE ON public.persistence_effects FOR EACH ROW EXECUTE FUNCTION gbrain_guard_effect_protocol()",
@@ -2618,7 +2659,13 @@
"tags.managed_writer_guard": "CREATE TRIGGER managed_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.tags FOR EACH ROW EXECUTE FUNCTION gbrain_require_managed_writer()",
"tags.tags_knowledge_revision": "CREATE TRIGGER tags_knowledge_revision AFTER INSERT OR DELETE OR UPDATE ON public.tags FOR EACH ROW EXECUTE FUNCTION gbrain_advance_tag_revision()",
"takes.managed_writer_guard": "CREATE TRIGGER managed_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.takes FOR EACH ROW EXECUTE FUNCTION gbrain_require_managed_writer()",
- "timeline_entries.managed_writer_guard": "CREATE TRIGGER managed_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.timeline_entries FOR EACH ROW EXECUTE FUNCTION gbrain_require_managed_writer()"
+ "takes.planner_stats_del": "CREATE TRIGGER planner_stats_del AFTER DELETE ON public.takes REFERENCING OLD TABLE AS old_rows FOR EACH STATEMENT EXECUTE FUNCTION gbrain_count_modifications()",
+ "takes.planner_stats_ins": "CREATE TRIGGER planner_stats_ins AFTER INSERT ON public.takes REFERENCING NEW TABLE AS new_rows FOR EACH STATEMENT EXECUTE FUNCTION gbrain_count_modifications()",
+ "takes.planner_stats_upd": "CREATE TRIGGER planner_stats_upd AFTER UPDATE ON public.takes REFERENCING NEW TABLE AS new_rows FOR EACH STATEMENT EXECUTE FUNCTION gbrain_count_modifications()",
+ "timeline_entries.managed_writer_guard": "CREATE TRIGGER managed_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.timeline_entries FOR EACH ROW EXECUTE FUNCTION gbrain_require_managed_writer()",
+ "timeline_entries.planner_stats_del": "CREATE TRIGGER planner_stats_del AFTER DELETE ON public.timeline_entries REFERENCING OLD TABLE AS old_rows FOR EACH STATEMENT EXECUTE FUNCTION gbrain_count_modifications()",
+ "timeline_entries.planner_stats_ins": "CREATE TRIGGER planner_stats_ins AFTER INSERT ON public.timeline_entries REFERENCING NEW TABLE AS new_rows FOR EACH STATEMENT EXECUTE FUNCTION gbrain_count_modifications()",
+ "timeline_entries.planner_stats_upd": "CREATE TRIGGER planner_stats_upd AFTER UPDATE ON public.timeline_entries REFERENCING NEW TABLE AS new_rows FOR EACH STATEMENT EXECUTE FUNCTION gbrain_count_modifications()"
},
"viewColumns": {
"page_links": [
diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json b/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json
index 7447ae5006..8ec9081b52 100644
--- a/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json
+++ b/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json
@@ -195,6 +195,8 @@
"persistence_writer_protocols.persistence_writer_protocols_pkey": "p PRIMARY KEY (worktree_id, host_id)",
"persistence_writer_protocols.persistence_writer_protocols_protocol_version_check": "c CHECK ((protocol_version = 2))",
"persistence_writer_protocols.persistence_writer_protocols_worktree_id_fkey": "f FOREIGN KEY (worktree_id) REFERENCES persistence_worktrees(id)",
+ "planner_stats_deltas.planner_stats_deltas_pkey": "p PRIMARY KEY (id)",
+ "planner_stats_state.planner_stats_state_pkey": "p PRIMARY KEY (table_name)",
"query_cache.query_cache_pkey": "p PRIMARY KEY (id)",
"raw_data.raw_data_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",
"raw_data.raw_data_page_id_source_key": "u UNIQUE (page_id, source)",
@@ -294,6 +296,7 @@
"gbrain_advance_page_revision()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=ae793ff5263f7b76311e0c22593fb658db9f82e7b3781914421d9508b6da0e88",
"gbrain_advance_tag_revision()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=7807b26b4933148aa63c67fca824a60d3492396728205d04e16c48c81174cbd5",
"gbrain_clear_atom_page_state()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=7db0ef05d1220a579e64428b2dd7cf5183191da186fbe64b6496433a7a713d11",
+ "gbrain_count_modifications()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=9518c925621def19cafb2918da4d41e602ce94619af872eafa3c11b46c66296f",
"gbrain_fact_fingerprint(claim text)": "RETURNS text kind=f lang=sql volatility=i secdef=false config=[] body_sha256=666cc212d15431ede62a3d1e8932676a950705717852262f86df6d836d526ab4",
"gbrain_fact_fingerprint_v1(claim text)": "RETURNS text kind=f lang=sql volatility=i secdef=false config=[] body_sha256=38f7cfc0016f2b34d6f54652f4910cf1dd5240fbec5fd636c782e46fb70a6c7d",
"gbrain_fact_normalize(claim text)": "RETURNS text kind=f lang=sql volatility=i secdef=false config=[] body_sha256=5fff22c689f79bb28b4cc66254ca3a42c2fc809be193c6ceaf75c3200a353035",
@@ -526,6 +529,12 @@
"persistence_writer_protocols": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
+ "planner_stats_deltas": [
+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
+ ],
+ "planner_stats_state": [
+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
+ ],
"query_cache": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
@@ -871,6 +880,8 @@
"persistence_topology_recovering": "CREATE INDEX persistence_topology_recovering ON public.persistence_topology_changes USING btree (created_at) WHERE (state = 'recovering'::text)",
"persistence_worktrees_pkey": "CREATE UNIQUE INDEX persistence_worktrees_pkey ON public.persistence_worktrees USING btree (id)",
"persistence_writer_protocols_pkey": "CREATE UNIQUE INDEX persistence_writer_protocols_pkey ON public.persistence_writer_protocols USING btree (worktree_id, host_id)",
+ "planner_stats_deltas_pkey": "CREATE UNIQUE INDEX planner_stats_deltas_pkey ON public.planner_stats_deltas USING btree (id)",
+ "planner_stats_state_pkey": "CREATE UNIQUE INDEX planner_stats_state_pkey ON public.planner_stats_state USING btree (table_name)",
"query_cache_pkey": "CREATE UNIQUE INDEX query_cache_pkey ON public.query_cache USING btree (id)",
"raw_data_page_id_source_key": "CREATE UNIQUE INDEX raw_data_page_id_source_key ON public.raw_data USING btree (page_id, source)",
"raw_data_pkey": "CREATE UNIQUE INDEX raw_data_pkey ON public.raw_data USING btree (id)",
@@ -976,6 +987,7 @@
"pages_id_seq": "integer start=1 min=1 max=2147483647 increment=1 cycle=false cache=1 owned_by=pages.id",
"persistence_effects_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=persistence_effects.id",
"persistence_requests_sequence_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=persistence_requests.sequence",
+ "planner_stats_deltas_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=planner_stats_deltas.id",
"raw_data_id_seq": "integer start=1 min=1 max=2147483647 increment=1 cycle=false cache=1 owned_by=raw_data.id",
"slug_aliases_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=slug_aliases.id",
"subagent_messages_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=subagent_messages.id",
@@ -2157,6 +2169,23 @@
],
"flags": "relkind=r rls=true force_rls=false"
},
+ "planner_stats_deltas": {
+ "columns": [
+ "1 id bigint/int8 NOT NULL DEFAULT nextval('planner_stats_deltas_id_seq'::regclass)",
+ "2 table_name text/text NOT NULL",
+ "3 n bigint/int8 NOT NULL"
+ ],
+ "flags": "relkind=r rls=false force_rls=false"
+ },
+ "planner_stats_state": {
+ "columns": [
+ "1 table_name text/text NOT NULL",
+ "2 analyzed_through bigint/int8 NOT NULL DEFAULT 0",
+ "3 analyzed_at timestamp with time zone/timestamptz NULL",
+ "4 last_analyze_ms integer/int4 NULL"
+ ],
+ "flags": "relkind=r rls=false force_rls=false"
+ },
"query_cache": {
"columns": [
"1 id text/text NOT NULL",
@@ -2595,8 +2624,17 @@
},
"triggers": {
"content_chunks.chunk_search_vector_trigger": "CREATE TRIGGER chunk_search_vector_trigger BEFORE INSERT OR UPDATE OF chunk_text, doc_comment, symbol_name_qualified ON public.content_chunks FOR EACH ROW EXECUTE FUNCTION update_chunk_search_vector()",
+ "content_chunks.planner_stats_del": "CREATE TRIGGER planner_stats_del AFTER DELETE ON public.content_chunks REFERENCING OLD TABLE AS old_rows FOR EACH STATEMENT EXECUTE FUNCTION gbrain_count_modifications()",
+ "content_chunks.planner_stats_ins": "CREATE TRIGGER planner_stats_ins AFTER INSERT ON public.content_chunks REFERENCING NEW TABLE AS new_rows FOR EACH STATEMENT EXECUTE FUNCTION gbrain_count_modifications()",
+ "content_chunks.planner_stats_upd": "CREATE TRIGGER planner_stats_upd AFTER UPDATE ON public.content_chunks REFERENCING NEW TABLE AS new_rows FOR EACH STATEMENT EXECUTE FUNCTION gbrain_count_modifications()",
"facts.facts_preserve_withdrawal": "CREATE TRIGGER facts_preserve_withdrawal BEFORE INSERT OR UPDATE OF fact, source_id, visibility, entity_slug, expired_at ON public.facts FOR EACH ROW EXECUTE FUNCTION gbrain_preserve_fact_withdrawal()",
"facts.managed_writer_guard": "CREATE TRIGGER managed_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.facts FOR EACH ROW EXECUTE FUNCTION gbrain_require_managed_writer()",
+ "facts.planner_stats_del": "CREATE TRIGGER planner_stats_del AFTER DELETE ON public.facts REFERENCING OLD TABLE AS old_rows FOR EACH STATEMENT EXECUTE FUNCTION gbrain_count_modifications()",
+ "facts.planner_stats_ins": "CREATE TRIGGER planner_stats_ins AFTER INSERT ON public.facts REFERENCING NEW TABLE AS new_rows FOR EACH STATEMENT EXECUTE FUNCTION gbrain_count_modifications()",
+ "facts.planner_stats_upd": "CREATE TRIGGER planner_stats_upd AFTER UPDATE ON public.facts REFERENCING NEW TABLE AS new_rows FOR EACH STATEMENT EXECUTE FUNCTION gbrain_count_modifications()",
+ "links.planner_stats_del": "CREATE TRIGGER planner_stats_del AFTER DELETE ON public.links REFERENCING OLD TABLE AS old_rows FOR EACH STATEMENT EXECUTE FUNCTION gbrain_count_modifications()",
+ "links.planner_stats_ins": "CREATE TRIGGER planner_stats_ins AFTER INSERT ON public.links REFERENCING NEW TABLE AS new_rows FOR EACH STATEMENT EXECUTE FUNCTION gbrain_count_modifications()",
+ "links.planner_stats_upd": "CREATE TRIGGER planner_stats_upd AFTER UPDATE ON public.links REFERENCING NEW TABLE AS new_rows FOR EACH STATEMENT EXECUTE FUNCTION gbrain_count_modifications()",
"minion_jobs.minion_queue_protocol": "CREATE TRIGGER minion_queue_protocol BEFORE INSERT OR UPDATE ON public.minion_jobs FOR EACH ROW EXECUTE FUNCTION enforce_minion_queue_protocol()",
"page_aliases.managed_writer_guard": "CREATE TRIGGER managed_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.page_aliases FOR EACH ROW EXECUTE FUNCTION gbrain_require_managed_writer()",
"pages.bump_page_generation_clock_trg": "CREATE TRIGGER bump_page_generation_clock_trg AFTER INSERT OR DELETE OR UPDATE ON public.pages FOR EACH STATEMENT EXECUTE FUNCTION bump_page_generation_clock_fn()",
@@ -2605,6 +2643,9 @@
"pages.pages_clear_atom_scan_state": "CREATE TRIGGER pages_clear_atom_scan_state AFTER UPDATE ON public.pages FOR EACH ROW EXECUTE FUNCTION gbrain_clear_atom_page_state()",
"pages.pages_knowledge_revision": "CREATE TRIGGER pages_knowledge_revision BEFORE UPDATE ON public.pages FOR EACH ROW EXECUTE FUNCTION gbrain_advance_page_revision()",
"pages.pages_projection_queue": "CREATE TRIGGER pages_projection_queue AFTER INSERT OR DELETE OR UPDATE ON public.pages FOR EACH ROW EXECUTE FUNCTION gbrain_queue_page_projection()",
+ "pages.planner_stats_del": "CREATE TRIGGER planner_stats_del AFTER DELETE ON public.pages REFERENCING OLD TABLE AS old_rows FOR EACH STATEMENT EXECUTE FUNCTION gbrain_count_modifications()",
+ "pages.planner_stats_ins": "CREATE TRIGGER planner_stats_ins AFTER INSERT ON public.pages REFERENCING NEW TABLE AS new_rows FOR EACH STATEMENT EXECUTE FUNCTION gbrain_count_modifications()",
+ "pages.planner_stats_upd": "CREATE TRIGGER planner_stats_upd AFTER UPDATE ON public.pages REFERENCING NEW TABLE AS new_rows FOR EACH STATEMENT EXECUTE FUNCTION gbrain_count_modifications()",
"pages.trg_pages_search_vector": "CREATE TRIGGER trg_pages_search_vector BEFORE INSERT OR UPDATE OF title, timeline ON public.pages FOR EACH ROW EXECUTE FUNCTION update_page_search_vector()",
"persistence_brain.gbrain_protocol_activation": "CREATE TRIGGER gbrain_protocol_activation BEFORE UPDATE ON public.persistence_brain FOR EACH ROW EXECUTE FUNCTION gbrain_guard_protocol_activation()",
"persistence_effects.gbrain_effect_protocol": "CREATE TRIGGER gbrain_effect_protocol BEFORE INSERT OR DELETE OR UPDATE ON public.persistence_effects FOR EACH ROW EXECUTE FUNCTION gbrain_guard_effect_protocol()",
@@ -2618,7 +2659,13 @@
"tags.managed_writer_guard": "CREATE TRIGGER managed_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.tags FOR EACH ROW EXECUTE FUNCTION gbrain_require_managed_writer()",
"tags.tags_knowledge_revision": "CREATE TRIGGER tags_knowledge_revision AFTER INSERT OR DELETE OR UPDATE ON public.tags FOR EACH ROW EXECUTE FUNCTION gbrain_advance_tag_revision()",
"takes.managed_writer_guard": "CREATE TRIGGER managed_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.takes FOR EACH ROW EXECUTE FUNCTION gbrain_require_managed_writer()",
- "timeline_entries.managed_writer_guard": "CREATE TRIGGER managed_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.timeline_entries FOR EACH ROW EXECUTE FUNCTION gbrain_require_managed_writer()"
+ "takes.planner_stats_del": "CREATE TRIGGER planner_stats_del AFTER DELETE ON public.takes REFERENCING OLD TABLE AS old_rows FOR EACH STATEMENT EXECUTE FUNCTION gbrain_count_modifications()",
+ "takes.planner_stats_ins": "CREATE TRIGGER planner_stats_ins AFTER INSERT ON public.takes REFERENCING NEW TABLE AS new_rows FOR EACH STATEMENT EXECUTE FUNCTION gbrain_count_modifications()",
+ "takes.planner_stats_upd": "CREATE TRIGGER planner_stats_upd AFTER UPDATE ON public.takes REFERENCING NEW TABLE AS new_rows FOR EACH STATEMENT EXECUTE FUNCTION gbrain_count_modifications()",
+ "timeline_entries.managed_writer_guard": "CREATE TRIGGER managed_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.timeline_entries FOR EACH ROW EXECUTE FUNCTION gbrain_require_managed_writer()",
+ "timeline_entries.planner_stats_del": "CREATE TRIGGER planner_stats_del AFTER DELETE ON public.timeline_entries REFERENCING OLD TABLE AS old_rows FOR EACH STATEMENT EXECUTE FUNCTION gbrain_count_modifications()",
+ "timeline_entries.planner_stats_ins": "CREATE TRIGGER planner_stats_ins AFTER INSERT ON public.timeline_entries REFERENCING NEW TABLE AS new_rows FOR EACH STATEMENT EXECUTE FUNCTION gbrain_count_modifications()",
+ "timeline_entries.planner_stats_upd": "CREATE TRIGGER planner_stats_upd AFTER UPDATE ON public.timeline_entries REFERENCING NEW TABLE AS new_rows FOR EACH STATEMENT EXECUTE FUNCTION gbrain_count_modifications()"
},
"viewColumns": {
"page_links": [
diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json b/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json
index c228f4da8d..f7e2b3bfce 100644
--- a/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json
+++ b/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json
@@ -195,6 +195,8 @@
"persistence_writer_protocols.persistence_writer_protocols_pkey": "p PRIMARY KEY (worktree_id, host_id)",
"persistence_writer_protocols.persistence_writer_protocols_protocol_version_check": "c CHECK ((protocol_version = 2))",
"persistence_writer_protocols.persistence_writer_protocols_worktree_id_fkey": "f FOREIGN KEY (worktree_id) REFERENCES persistence_worktrees(id)",
+ "planner_stats_deltas.planner_stats_deltas_pkey": "p PRIMARY KEY (id)",
+ "planner_stats_state.planner_stats_state_pkey": "p PRIMARY KEY (table_name)",
"query_cache.query_cache_pkey": "p PRIMARY KEY (id)",
"raw_data.raw_data_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",
"raw_data.raw_data_page_id_source_key": "u UNIQUE (page_id, source)",
@@ -294,6 +296,7 @@
"gbrain_advance_page_revision()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=ae793ff5263f7b76311e0c22593fb658db9f82e7b3781914421d9508b6da0e88",
"gbrain_advance_tag_revision()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=7807b26b4933148aa63c67fca824a60d3492396728205d04e16c48c81174cbd5",
"gbrain_clear_atom_page_state()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=7db0ef05d1220a579e64428b2dd7cf5183191da186fbe64b6496433a7a713d11",
+ "gbrain_count_modifications()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=9518c925621def19cafb2918da4d41e602ce94619af872eafa3c11b46c66296f",
"gbrain_fact_fingerprint(claim text)": "RETURNS text kind=f lang=sql volatility=i secdef=false config=[] body_sha256=666cc212d15431ede62a3d1e8932676a950705717852262f86df6d836d526ab4",
"gbrain_fact_fingerprint_v1(claim text)": "RETURNS text kind=f lang=sql volatility=i secdef=false config=[] body_sha256=38f7cfc0016f2b34d6f54652f4910cf1dd5240fbec5fd636c782e46fb70a6c7d",
"gbrain_fact_normalize(claim text)": "RETURNS text kind=f lang=sql volatility=i secdef=false config=[] body_sha256=5fff22c689f79bb28b4cc66254ca3a42c2fc809be193c6ceaf75c3200a353035",
@@ -526,6 +529,12 @@
"persistence_writer_protocols": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
+ "planner_stats_deltas": [
+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
+ ],
+ "planner_stats_state": [
+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
+ ],
"query_cache": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
@@ -867,6 +876,8 @@
"persistence_topology_recovering": "CREATE INDEX persistence_topology_recovering ON public.persistence_topology_changes USING btree (created_at) WHERE (state = 'recovering'::text)",
"persistence_worktrees_pkey": "CREATE UNIQUE INDEX persistence_worktrees_pkey ON public.persistence_worktrees USING btree (id)",
"persistence_writer_protocols_pkey": "CREATE UNIQUE INDEX persistence_writer_protocols_pkey ON public.persistence_writer_protocols USING btree (worktree_id, host_id)",
+ "planner_stats_deltas_pkey": "CREATE UNIQUE INDEX planner_stats_deltas_pkey ON public.planner_stats_deltas USING btree (id)",
+ "planner_stats_state_pkey": "CREATE UNIQUE INDEX planner_stats_state_pkey ON public.planner_stats_state USING btree (table_name)",
"query_cache_pkey": "CREATE UNIQUE INDEX query_cache_pkey ON public.query_cache USING btree (id)",
"raw_data_page_id_source_key": "CREATE UNIQUE INDEX raw_data_page_id_source_key ON public.raw_data USING btree (page_id, source)",
"raw_data_pkey": "CREATE UNIQUE INDEX raw_data_pkey ON public.raw_data USING btree (id)",
@@ -972,6 +983,7 @@
"pages_id_seq": "integer start=1 min=1 max=2147483647 increment=1 cycle=false cache=1 owned_by=pages.id",
"persistence_effects_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=persistence_effects.id",
"persistence_requests_sequence_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=persistence_requests.sequence",
+ "planner_stats_deltas_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=planner_stats_deltas.id",
"raw_data_id_seq": "integer start=1 min=1 max=2147483647 increment=1 cycle=false cache=1 owned_by=raw_data.id",
"slug_aliases_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=slug_aliases.id",
"subagent_messages_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=subagent_messages.id",
@@ -2153,6 +2165,23 @@
],
"flags": "relkind=r rls=true force_rls=false"
},
+ "planner_stats_deltas": {
+ "columns": [
+ "1 id bigint/int8 NOT NULL DEFAULT nextval('planner_stats_deltas_id_seq'::regclass)",
+ "2 table_name text/text NOT NULL",
+ "3 n bigint/int8 NOT NULL"
+ ],
+ "flags": "relkind=r rls=false force_rls=false"
+ },
+ "planner_stats_state": {
+ "columns": [
+ "1 table_name text/text NOT NULL",
+ "2 analyzed_through bigint/int8 NOT NULL DEFAULT 0",
+ "3 analyzed_at timestamp with time zone/timestamptz NULL",
+ "4 last_analyze_ms integer/int4 NULL"
+ ],
+ "flags": "relkind=r rls=false force_rls=false"
+ },
"query_cache": {
"columns": [
"1 id text/text NOT NULL",
@@ -2591,8 +2620,17 @@
},
"triggers": {
"content_chunks.chunk_search_vector_trigger": "CREATE TRIGGER chunk_search_vector_trigger BEFORE INSERT OR UPDATE OF chunk_text, doc_comment, symbol_name_qualified ON public.content_chunks FOR EACH ROW EXECUTE FUNCTION update_chunk_search_vector()",
+ "content_chunks.planner_stats_del": "CREATE TRIGGER planner_stats_del AFTER DELETE ON public.content_chunks REFERENCING OLD TABLE AS old_rows FOR EACH STATEMENT EXECUTE FUNCTION gbrain_count_modifications()",
+ "content_chunks.planner_stats_ins": "CREATE TRIGGER planner_stats_ins AFTER INSERT ON public.content_chunks REFERENCING NEW TABLE AS new_rows FOR EACH STATEMENT EXECUTE FUNCTION gbrain_count_modifications()",
+ "content_chunks.planner_stats_upd": "CREATE TRIGGER planner_stats_upd AFTER UPDATE ON public.content_chunks REFERENCING NEW TABLE AS new_rows FOR EACH STATEMENT EXECUTE FUNCTION gbrain_count_modifications()",
"facts.facts_preserve_withdrawal": "CREATE TRIGGER facts_preserve_withdrawal BEFORE INSERT OR UPDATE OF fact, source_id, visibility, entity_slug, expired_at ON public.facts FOR EACH ROW EXECUTE FUNCTION gbrain_preserve_fact_withdrawal()",
"facts.managed_writer_guard": "CREATE TRIGGER managed_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.facts FOR EACH ROW EXECUTE FUNCTION gbrain_require_managed_writer()",
+ "facts.planner_stats_del": "CREATE TRIGGER planner_stats_del AFTER DELETE ON public.facts REFERENCING OLD TABLE AS old_rows FOR EACH STATEMENT EXECUTE FUNCTION gbrain_count_modifications()",
+ "facts.planner_stats_ins": "CREATE TRIGGER planner_stats_ins AFTER INSERT ON public.facts REFERENCING NEW TABLE AS new_rows FOR EACH STATEMENT EXECUTE FUNCTION gbrain_count_modifications()",
+ "facts.planner_stats_upd": "CREATE TRIGGER planner_stats_upd AFTER UPDATE ON public.facts REFERENCING NEW TABLE AS new_rows FOR EACH STATEMENT EXECUTE FUNCTION gbrain_count_modifications()",
+ "links.planner_stats_del": "CREATE TRIGGER planner_stats_del AFTER DELETE ON public.links REFERENCING OLD TABLE AS old_rows FOR EACH STATEMENT EXECUTE FUNCTION gbrain_count_modifications()",
+ "links.planner_stats_ins": "CREATE TRIGGER planner_stats_ins AFTER INSERT ON public.links REFERENCING NEW TABLE AS new_rows FOR EACH STATEMENT EXECUTE FUNCTION gbrain_count_modifications()",
+ "links.planner_stats_upd": "CREATE TRIGGER planner_stats_upd AFTER UPDATE ON public.links REFERENCING NEW TABLE AS new_rows FOR EACH STATEMENT EXECUTE FUNCTION gbrain_count_modifications()",
"minion_jobs.minion_queue_protocol": "CREATE TRIGGER minion_queue_protocol BEFORE INSERT OR UPDATE ON public.minion_jobs FOR EACH ROW EXECUTE FUNCTION enforce_minion_queue_protocol()",
"page_aliases.managed_writer_guard": "CREATE TRIGGER managed_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.page_aliases FOR EACH ROW EXECUTE FUNCTION gbrain_require_managed_writer()",
"pages.bump_page_generation_clock_trg": "CREATE TRIGGER bump_page_generation_clock_trg AFTER INSERT OR DELETE OR UPDATE ON public.pages FOR EACH STATEMENT EXECUTE FUNCTION bump_page_generation_clock_fn()",
@@ -2601,6 +2639,9 @@
"pages.pages_clear_atom_scan_state": "CREATE TRIGGER pages_clear_atom_scan_state AFTER UPDATE ON public.pages FOR EACH ROW EXECUTE FUNCTION gbrain_clear_atom_page_state()",
"pages.pages_knowledge_revision": "CREATE TRIGGER pages_knowledge_revision BEFORE UPDATE ON public.pages FOR EACH ROW EXECUTE FUNCTION gbrain_advance_page_revision()",
"pages.pages_projection_queue": "CREATE TRIGGER pages_projection_queue AFTER INSERT OR DELETE OR UPDATE ON public.pages FOR EACH ROW EXECUTE FUNCTION gbrain_queue_page_projection()",
+ "pages.planner_stats_del": "CREATE TRIGGER planner_stats_del AFTER DELETE ON public.pages REFERENCING OLD TABLE AS old_rows FOR EACH STATEMENT EXECUTE FUNCTION gbrain_count_modifications()",
+ "pages.planner_stats_ins": "CREATE TRIGGER planner_stats_ins AFTER INSERT ON public.pages REFERENCING NEW TABLE AS new_rows FOR EACH STATEMENT EXECUTE FUNCTION gbrain_count_modifications()",
+ "pages.planner_stats_upd": "CREATE TRIGGER planner_stats_upd AFTER UPDATE ON public.pages REFERENCING NEW TABLE AS new_rows FOR EACH STATEMENT EXECUTE FUNCTION gbrain_count_modifications()",
"pages.trg_pages_search_vector": "CREATE TRIGGER trg_pages_search_vector BEFORE INSERT OR UPDATE OF title, timeline ON public.pages FOR EACH ROW EXECUTE FUNCTION update_page_search_vector()",
"persistence_brain.gbrain_protocol_activation": "CREATE TRIGGER gbrain_protocol_activation BEFORE UPDATE ON public.persistence_brain FOR EACH ROW EXECUTE FUNCTION gbrain_guard_protocol_activation()",
"persistence_effects.gbrain_effect_protocol": "CREATE TRIGGER gbrain_effect_protocol BEFORE INSERT OR DELETE OR UPDATE ON public.persistence_effects FOR EACH ROW EXECUTE FUNCTION gbrain_guard_effect_protocol()",
@@ -2614,7 +2655,13 @@
"tags.managed_writer_guard": "CREATE TRIGGER managed_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.tags FOR EACH ROW EXECUTE FUNCTION gbrain_require_managed_writer()",
"tags.tags_knowledge_revision": "CREATE TRIGGER tags_knowledge_revision AFTER INSERT OR DELETE OR UPDATE ON public.tags FOR EACH ROW EXECUTE FUNCTION gbrain_advance_tag_revision()",
"takes.managed_writer_guard": "CREATE TRIGGER managed_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.takes FOR EACH ROW EXECUTE FUNCTION gbrain_require_managed_writer()",
- "timeline_entries.managed_writer_guard": "CREATE TRIGGER managed_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.timeline_entries FOR EACH ROW EXECUTE FUNCTION gbrain_require_managed_writer()"
+ "takes.planner_stats_del": "CREATE TRIGGER planner_stats_del AFTER DELETE ON public.takes REFERENCING OLD TABLE AS old_rows FOR EACH STATEMENT EXECUTE FUNCTION gbrain_count_modifications()",
+ "takes.planner_stats_ins": "CREATE TRIGGER planner_stats_ins AFTER INSERT ON public.takes REFERENCING NEW TABLE AS new_rows FOR EACH STATEMENT EXECUTE FUNCTION gbrain_count_modifications()",
+ "takes.planner_stats_upd": "CREATE TRIGGER planner_stats_upd AFTER UPDATE ON public.takes REFERENCING NEW TABLE AS new_rows FOR EACH STATEMENT EXECUTE FUNCTION gbrain_count_modifications()",
+ "timeline_entries.managed_writer_guard": "CREATE TRIGGER managed_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.timeline_entries FOR EACH ROW EXECUTE FUNCTION gbrain_require_managed_writer()",
+ "timeline_entries.planner_stats_del": "CREATE TRIGGER planner_stats_del AFTER DELETE ON public.timeline_entries REFERENCING OLD TABLE AS old_rows FOR EACH STATEMENT EXECUTE FUNCTION gbrain_count_modifications()",
+ "timeline_entries.planner_stats_ins": "CREATE TRIGGER planner_stats_ins AFTER INSERT ON public.timeline_entries REFERENCING NEW TABLE AS new_rows FOR EACH STATEMENT EXECUTE FUNCTION gbrain_count_modifications()",
+ "timeline_entries.planner_stats_upd": "CREATE TRIGGER planner_stats_upd AFTER UPDATE ON public.timeline_entries REFERENCING NEW TABLE AS new_rows FOR EACH STATEMENT EXECUTE FUNCTION gbrain_count_modifications()"
},
"viewColumns": {
"page_links": [
diff --git a/test/fixtures/goldens/doctor/json-pglite-degraded.json b/test/fixtures/goldens/doctor/json-pglite-degraded.json
index 1e43169ad1..5ee1470497 100644
--- a/test/fixtures/goldens/doctor/json-pglite-degraded.json
+++ b/test/fixtures/goldens/doctor/json-pglite-degraded.json
@@ -383,7 +383,7 @@
},
{
"category": "meta",
- "message": "Version 192 (latest: 192)",
+ "message": "Version 193 (latest: 193)",
"name": "schema_version",
"status": "ok"
},
@@ -1089,6 +1089,26 @@
"name": "fact_take_vectors",
"status": "ok"
},
+ {
+ "category": "ops",
+ "details": {
+ "auto_analyze": true,
+ "checked": [
+ "pages",
+ "links",
+ "facts",
+ "takes",
+ "content_chunks",
+ "timeline_entries"
+ ],
+ "engine": "pglite",
+ "fix": "gbrain repair planner-stats --apply",
+ "stale": []
+ },
+ "message": "Planner statistics are fresh on 6 hot tables.",
+ "name": "planner_stats_stale",
+ "status": "ok"
+ },
{
"category": "ops",
"message": "Mode: conservative (no per-key overrides — mode bundle is canonical).",
diff --git a/test/fixtures/goldens/doctor/json-pglite-fresh.json b/test/fixtures/goldens/doctor/json-pglite-fresh.json
index 34d18106b9..6f3f073be7 100644
--- a/test/fixtures/goldens/doctor/json-pglite-fresh.json
+++ b/test/fixtures/goldens/doctor/json-pglite-fresh.json
@@ -383,7 +383,7 @@
},
{
"category": "meta",
- "message": "Version 192 (latest: 192)",
+ "message": "Version 193 (latest: 193)",
"name": "schema_version",
"status": "ok"
},
@@ -1076,6 +1076,26 @@
"name": "fact_take_vectors",
"status": "ok"
},
+ {
+ "category": "ops",
+ "details": {
+ "auto_analyze": true,
+ "checked": [
+ "pages",
+ "links",
+ "facts",
+ "takes",
+ "content_chunks",
+ "timeline_entries"
+ ],
+ "engine": "pglite",
+ "fix": "gbrain repair planner-stats --apply",
+ "stale": []
+ },
+ "message": "Planner statistics are fresh on 6 hot tables.",
+ "name": "planner_stats_stale",
+ "status": "ok"
+ },
{
"category": "ops",
"message": "Mode: conservative (no per-key overrides — mode bundle is canonical).",
diff --git a/test/fixtures/goldens/doctor/json-postgres-fresh.json b/test/fixtures/goldens/doctor/json-postgres-fresh.json
index 9a259010fd..6f084e801e 100644
--- a/test/fixtures/goldens/doctor/json-postgres-fresh.json
+++ b/test/fixtures/goldens/doctor/json-postgres-fresh.json
@@ -389,7 +389,7 @@
},
{
"category": "meta",
- "message": "Version 192 (latest: 192)",
+ "message": "Version 193 (latest: 193)",
"name": "schema_version",
"status": "ok"
},
@@ -1091,6 +1091,26 @@
"name": "fact_take_vectors",
"status": "ok"
},
+ {
+ "category": "ops",
+ "details": {
+ "auto_analyze": null,
+ "checked": [
+ "pages",
+ "links",
+ "facts",
+ "takes",
+ "content_chunks",
+ "timeline_entries"
+ ],
+ "engine": "postgres",
+ "fix": "gbrain repair planner-stats --apply",
+ "stale": []
+ },
+ "message": "Planner statistics are fresh on 6 hot tables.",
+ "name": "planner_stats_stale",
+ "status": "ok"
+ },
{
"category": "ops",
"message": "Mode: conservative (no per-key overrides — mode bundle is canonical).",
diff --git a/test/fixtures/goldens/doctor/registry-build-checks.json b/test/fixtures/goldens/doctor/registry-build-checks.json
index c759f9f9e5..0e5d2b447d 100644
--- a/test/fixtures/goldens/doctor/registry-build-checks.json
+++ b/test/fixtures/goldens/doctor/registry-build-checks.json
@@ -573,6 +573,10 @@
"category": "brain",
"name": "fact_take_vectors"
},
+ {
+ "category": "ops",
+ "name": "planner_stats_stale"
+ },
{
"category": "ops",
"name": "chat_fallback_chain_inert"
diff --git a/test/fixtures/goldens/migrations/records.json b/test/fixtures/goldens/migrations/records.json
index 62e8b3e37c..63dcccd2e0 100644
--- a/test/fixtures/goldens/migrations/records.json
+++ b/test/fixtures/goldens/migrations/records.json
@@ -1,6 +1,6 @@
{
"golden": {
- "count": 187,
+ "count": 188,
"gaps": [
17,
18,
@@ -28,7 +28,7 @@
"slugifyPath": "401dbca23580865d8b168dd8d84db4a6c708c6610d7cb61abafc7d0ee9809063",
"verifyProjectionStatistics": "59d9ccfea1c53384d8607874a51209a9c2dfd51b2b85a2cb6269fa4120faf1f3"
},
- "latest": 192,
+ "latest": 193,
"records": [
{
"handler": {
@@ -2852,6 +2852,25 @@
"transaction": "absent",
"verify": "absent",
"version": 192
+ },
+ {
+ "handler": "absent",
+ "idempotent": true,
+ "name": "f4_planner_stats",
+ "sql": {
+ "length": 0,
+ "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
+ },
+ "sqlFor": {
+ "pglite": {
+ "length": 3815,
+ "sha256": "665c078e7bb26f924eb846aa0a737fba16239519ab0237cd8f5d948ce3af062b"
+ },
+ "postgres": "absent"
+ },
+ "transaction": "absent",
+ "verify": "absent",
+ "version": 193
}
],
"versions": [
@@ -3041,7 +3060,8 @@
189,
190,
191,
- 192
+ 192,
+ 193
]
},
"normalizer": "migrations-record-v1"
diff --git a/test/helpers/planner-stats-child.ts b/test/helpers/planner-stats-child.ts
new file mode 100644
index 0000000000..a7c4316a2d
--- /dev/null
+++ b/test/helpers/planner-stats-child.ts
@@ -0,0 +1,36 @@
+/**
+ * Child process for test/planner-stats-restart.serial.test.ts (F4b, O-CEO-17).
+ *
+ * bun test/helpers/planner-stats-child.ts <data-dir> insert <n> insert n facts, disconnect
+ * bun test/helpers/planner-stats-child.ts <data-dir> insert-crash <n> insert n facts, SIGKILL itself right after the commit
+ * bun test/helpers/planner-stats-child.ts <data-dir> first-read print one JSON line about the first get_health
+ */
+import { writeSync } from 'node:fs';
+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';
+import { __testing, readPlannerStatsState } from '../../src/core/planner-stats.ts';
+
+const [dataDir, action, count] = process.argv.slice(2);
+const engine = new PGLiteEngine();
+await engine.connect({ database_path: dataDir });
+await engine.initSchema();
+const facts = async () => (await readPlannerStatsState(engine))!.find(t => t.table === 'facts')!;
+
+if (action === 'insert' || action === 'insert-crash') {
+ await engine.executeRaw(`INSERT INTO facts (fact, source) SELECT 'restart claim ' || g, 'test' FROM generate_series(1, $1::int) g`, [Number(count)]);
+ if (action === 'insert-crash') {
+ writeSync(1, 'COMMITTED\n');
+ process.kill(process.pid, 'SIGKILL');
+ await new Promise(() => {});
+ }
+} else if (action === 'first-read') {
+ const before = await facts();
+ const events: Array<{ table: string; ms: number; during_read: boolean }> = [];
+ let reading = true;
+ __testing.hooks.onAnalyzed = async (_engine, event) => { events.push({ table: event.table, ms: event.ms, during_read: reading }); };
+ const started = performance.now();
+ await engine.getHealth();
+ const readMs = performance.now() - started;
+ reading = false;
+ writeSync(1, `${JSON.stringify({ before, events, read_ms: readMs, after: await facts() })}\n`);
+}
+await engine.disconnect();
diff --git a/test/helpers/schema-diff.ts b/test/helpers/schema-diff.ts
index 0ec33f2c09..6bd64765ed 100644
--- a/test/helpers/schema-diff.ts
+++ b/test/helpers/schema-diff.ts
@@ -254,9 +254,10 @@ function normaliseDefault(d: string | null): string | null {
export function diffSnapshots(
pg: SchemaSnapshot,
pglite: SchemaSnapshot,
- opts: { allowlistPgOnlyTables: string[] },
+ opts: { allowlistPgOnlyTables: string[]; allowlistPgliteOnlyTables?: string[] },
): SchemaDiff {
const allowlist = new Set(opts.allowlistPgOnlyTables);
+ const pgliteOnly = new Set(opts.allowlistPgliteOnlyTables ?? []);
const diff: SchemaDiff = {
tablesMissingInPGLite: [],
tablesUnexpectedlyInPGLite: [],
@@ -302,7 +303,7 @@ export function diffSnapshots(
// reviewer can decide.
for (const [table, pgliteCols] of pglite) {
if (!pg.has(table)) {
- diff.tablesUnexpectedlyInPGLite.push(table);
+ if (!pgliteOnly.has(table)) diff.tablesUnexpectedlyInPGLite.push(table);
continue;
}
if (allowlist.has(table)) continue;
diff --git a/test/planner-stats-catalog.test.ts b/test/planner-stats-catalog.test.ts
new file mode 100644
index 0000000000..0a754d4aea
--- /dev/null
+++ b/test/planner-stats-catalog.test.ts
@@ -0,0 +1,43 @@
+/**
+ * F4b (spec 5.3 test 10, O-CEO-9): the planner-stats objects exist on PGLite
+ * only. The committed catalog goldens (regenerated by
+ * test/schema-catalog-golden.test.ts and its Postgres twin
+ * test/e2e/schema-catalog-golden.test.ts) carry the two tables, the function
+ * and the 18 statement triggers for every PGLite config, and none of them for
+ * any Postgres config. Postgres write paths gain no trigger.
+ */
+import { describe, test, expect } from 'bun:test';
+import { readdirSync, readFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { PLANNER_STATS_TABLES } from '../src/core/planner-stats-schema.ts';
+
+const DIR = join(import.meta.dir, 'fixtures', 'goldens', 'catalog');
+const goldens = readdirSync(DIR).filter(f => f.endsWith('.json'));
+const text = (file: string) => readFileSync(join(DIR, file), 'utf8');
+
+describe('planner-stats catalog goldens', () => {
+ test('every PGLite engine-init golden has the accounting tables, function and triggers', () => {
+ const pglite = goldens.filter(f => f.startsWith('pglite-engine-init-'));
+ expect(pglite.length).toBe(3);
+ for (const file of pglite) {
+ const golden = text(file);
+ expect(golden).toContain('"planner_stats_deltas": {');
+ expect(golden).toContain('"planner_stats_state": {');
+ expect(golden).toContain('"gbrain_count_modifications()"');
+ for (const table of PLANNER_STATS_TABLES) {
+ for (const [trigger, event, rows] of [['planner_stats_ins', 'INSERT', 'NEW'], ['planner_stats_upd', 'UPDATE', 'NEW'], ['planner_stats_del', 'DELETE', 'OLD']]) {
+ expect(golden).toContain(`"${table}.${trigger}": "CREATE TRIGGER ${trigger} AFTER ${event} ON public.${table} REFERENCING ${rows} TABLE AS ${rows.toLowerCase()}_rows FOR EACH STATEMENT EXECUTE FUNCTION gbrain_count_modifications()"`);
+ }
+ }
+ }
+ });
+
+ test('no Postgres golden has any planner-stats object', () => {
+ const postgres = goldens.filter(f => f.startsWith('postgres-'));
+ expect(postgres.length).toBeGreaterThan(0);
+ for (const file of postgres) {
+ expect(text(file)).not.toContain('planner_stats');
+ expect(text(file)).not.toContain('gbrain_count_modifications');
+ }
+ });
+});
diff --git a/test/planner-stats-import.slow.test.ts b/test/planner-stats-import.slow.test.ts
new file mode 100644
index 0000000000..4125c112f1
--- /dev/null
+++ b/test/planner-stats-import.slow.test.ts
@@ -0,0 +1,52 @@
+/**
+ * F4b (spec 5.3 test 8, O-CEO-17, Addendum A item 1): `gbrain import` of
+ * 2,000 pages into PGLite refreshes planner statistics during the import, at
+ * every `import.analyze_every_pages` (500) pages where the row-delta threshold
+ * says the hot tables are stale, instead of planning the whole import against
+ * the empty tables it started with. Slow: a real 2,000-file import.
+ */
+import { describe, test, expect, beforeAll, afterAll } from 'bun:test';
+import { mkdtempSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { runImport } from '../src/commands/import.ts';
+import { __testing } from '../src/core/planner-stats.ts';
+
+let engine: PGLiteEngine;
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+}, 60_000);
+
+afterAll(async () => {
+ __testing.hooks.onAnalyzed = undefined;
+ await engine.disconnect();
+});
+
+describe('8. ANALYZE during import', () => {
+ test('a 2,000-page import analyzes pages at 500, 1,000, 1,500 and 2,000 pages and chunks when over the threshold', async () => {
+ const dir = mkdtempSync(join(tmpdir(), 'planner-import-'));
+ for (let i = 0; i < 2000; i++) {
+ writeFileSync(join(dir, `note-${String(i).padStart(4, '0')}.md`),
+ `---\ntitle: Note ${i}\ntype: note\n---\nNote ${i} links to [[note-${String((i + 1) % 2000).padStart(4, '0')}]] about topic ${i % 37}.\n`);
+ }
+ await engine.setConfig('import.analyze_every_pages', '500');
+ const analyzed: Array<{ table: string; pages: number }> = [];
+ __testing.hooks.onAnalyzed = async (eng, event) => {
+ if (event.reason !== 'import') return;
+ const [{ n }] = await eng.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM pages');
+ analyzed.push({ table: event.table, pages: n });
+ };
+
+ await runImport(engine, [dir, '--no-embed']);
+
+ expect(analyzed.filter(a => a.table === 'pages').map(a => a.pages)).toEqual([500, 1000, 1500, 2000]);
+ // One chunk per page: 500 new chunks are not over the max(500, 10%) threshold, 1,000 are.
+ expect(analyzed.filter(a => a.table === 'content_chunks').map(a => a.pages)).toEqual([1000, 2000]);
+ const [{ n }] = await engine.executeRaw<{ n: number }>("SELECT count(*)::int AS n FROM pg_stats WHERE schemaname = 'public' AND tablename = 'pages'");
+ expect(n).toBeGreaterThan(0);
+ }, 600_000);
+});
diff --git a/test/planner-stats-restart.serial.test.ts b/test/planner-stats-restart.serial.test.ts
new file mode 100644
index 0000000000..09b89c62bf
--- /dev/null
+++ b/test/planner-stats-restart.serial.test.ts
@@ -0,0 +1,54 @@
+/**
+ * F4b (spec 5.3 tests 4 and 6, O-CEO-17): planner-stats deltas are durable
+ * across crashes and restarts. Real child processes on a persisted PGLite data
+ * dir (test/helpers/planner-stats-child.ts). Serial: each case spawns bun
+ * processes that open the same data dir one at a time.
+ */
+import { describe, test, expect } from 'bun:test';
+import { mkdtempSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+
+const CHILD = join(import.meta.dir, 'helpers', 'planner-stats-child.ts');
+
+function child(dataDir: string, ...args: string[]) {
+ const proc = Bun.spawnSync(['bun', CHILD, dataDir, ...args], {
+ env: { ...process.env, GBRAIN_HOME: mkdtempSync(join(tmpdir(), 'planner-home-')), GBRAIN_PGLITE_SNAPSHOT: '' },
+ stdout: 'pipe', stderr: 'pipe',
+ });
+ return { exitCode: proc.exitCode, signal: proc.signalCode, stdout: proc.stdout.toString(), stderr: proc.stderr.toString() };
+}
+
+function lastJson(stdout: string) {
+ return JSON.parse(stdout.trim().split('\n').filter(l => l.startsWith('{')).at(-1)!);
+}
+
+describe('planner-stats durability (O-CEO-17)', () => {
+ test('4. a crash right after commit keeps the committed modifications pending', () => {
+ const dataDir = join(mkdtempSync(join(tmpdir(), 'planner-crash-')), 'brain.pglite');
+ const crashed = child(dataDir, 'insert-crash', '700');
+ expect(crashed.stdout).toContain('COMMITTED');
+ expect(crashed.signal).toBe('SIGKILL');
+
+ const reopened = child(dataDir, 'first-read');
+ expect(reopened.exitCode).toBe(0);
+ const report = lastJson(reopened.stdout);
+ expect(report.before).toMatchObject({ table: 'facts', pending: 700, stale: true });
+ }, 120_000);
+
+ test('6. five restarts of 150 facts each: the first get_health in a sixth process analyzes facts within the budget', () => {
+ const dataDir = join(mkdtempSync(join(tmpdir(), 'planner-restart-')), 'brain.pglite');
+ for (let i = 0; i < 5; i++) {
+ const run = child(dataDir, 'insert', '150');
+ expect(run.exitCode).toBe(0);
+ }
+
+ const sixth = child(dataDir, 'first-read');
+ expect(sixth.exitCode).toBe(0);
+ const report = lastJson(sixth.stdout);
+ expect(report.before).toMatchObject({ pending: 750, stale: true });
+ expect(report.events).toContainEqual(expect.objectContaining({ table: 'facts', during_read: true }));
+ expect(report.events.find((e: { table: string }) => e.table === 'facts').ms).toBeLessThan(2000);
+ expect(report.after).toMatchObject({ pending: 0, stale: false, has_stats: true });
+ }, 180_000);
+});
diff --git a/test/planner-stats.test.ts b/test/planner-stats.test.ts
new file mode 100644
index 0000000000..8ca7885aa4
--- /dev/null
+++ b/test/planner-stats.test.ts
@@ -0,0 +1,228 @@
+/**
+ * F4b (spec 5.3, O-ENG-12): transactional planner-statistics accounting and
+ * row-delta ANALYZE on PGLite. In-memory PGLite ($0). Restart and crash cases
+ * live in test/planner-stats-restart.serial.test.ts, the 2,000-page import in
+ * test/planner-stats-import.slow.test.ts, Postgres in
+ * test/e2e/planner-stats-postgres.test.ts.
+ */
+import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';
+import { mkdtempSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { resetPgliteState } from './helpers/reset-pglite.ts';
+import { withEnv } from './helpers/with-env.ts';
+import {
+ __testing, analyzePlannerTables, maybeRefreshPlannerStats, readPlannerStatsState, type PlannerRefreshReason,
+} from '../src/core/planner-stats.ts';
+import { DOCTOR_CHECK_REGISTRY } from '../src/commands/doctor/registry.ts';
+import { categorizeCheck } from '../src/core/doctor-categories.ts';
+import { REPAIR_KINDS } from '../src/core/repair/core.ts';
+import { plannerStatsRepair } from '../src/core/repair/planner-stats.ts';
+import { runImport } from '../src/commands/import.ts';
+import type { DoctorContext } from '../src/commands/doctor/context.ts';
+import type { Check } from '../src/commands/doctor.ts';
+
+let engine: PGLiteEngine;
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+}, 60_000);
+
+afterAll(async () => {
+ await engine.disconnect();
+});
+
+beforeEach(async () => {
+ await resetPgliteState(engine);
+ 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'");
+ __testing.reset(engine);
+ __testing.hooks.beforePublish = undefined;
+ __testing.hooks.onAnalyzed = undefined;
+});
+
+async function table(name: string) {
+ const state = await readPlannerStatsState(engine);
+ return state!.find(t => t.table === name)!;
+}
+
+async function insertFacts(count: number) {
+ await engine.executeRaw(`INSERT INTO facts (fact, source) SELECT 'claim ' || g, 'test' FROM generate_series(1, $1::int) g`, [count]);
+}
+
+async function insertTakes(count: number) {
+ const page = await engine.putPage('notes/takes-host', { type: 'note', title: 'Takes host', compiled_truth: 'Host page.' });
+ await engine.executeRaw(
+ `INSERT INTO takes (page_id, row_num, claim, kind, holder) SELECT $1, g, 'take ' || g, 'take', 'garry' FROM generate_series(1, $2::int) g`,
+ [page.id, count]);
+ return page.id;
+}
+
+async function runDoctorCheck(): 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;
+ const result = await entry.run(ctx);
+ return (result as Check[])[0]!;
+}
+
+describe('transactional accounting (O-ENG-12)', () => {
+ test('1. a raw executeRaw UPDATE of 600 facts rows makes facts stale', async () => {
+ await insertFacts(600);
+ await maybeRefreshPlannerStats(engine, 'repair', { throttle: false });
+ expect(await table('facts')).toMatchObject({ pending: 0, stale: false, has_stats: true });
+
+ await engine.executeRaw("UPDATE facts SET fact = fact || ' (edited)'");
+
+ expect(await table('facts')).toMatchObject({ pending: 600, stale: true });
+ });
+
+ test('2. delete/reinsert of 300 takes counts 600', async () => {
+ const pageId = await insertTakes(300);
+ await analyzePlannerTables(engine, ['takes'], 'repair');
+ expect((await table('takes')).pending).toBe(0);
+
+ await engine.transaction(async tx => {
+ await tx.executeRaw('DELETE FROM takes WHERE page_id = $1', [pageId]);
+ await tx.executeRaw(
+ `INSERT INTO takes (page_id, row_num, claim, kind, holder) SELECT $1, g, 'take ' || g, 'take', 'garry' FROM generate_series(1, 300) g`, [pageId]);
+ });
+
+ expect((await table('takes')).pending).toBe(600);
+ });
+
+ test('3. a rolled-back transaction adds nothing', async () => {
+ await expect(engine.transaction(async tx => {
+ await tx.executeRaw(`INSERT INTO facts (fact, source) SELECT 'rolled back ' || g, 'test' FROM generate_series(1, 700) g`);
+ throw new Error('roll back');
+ })).rejects.toThrow('roll back');
+
+ expect(await table('facts')).toMatchObject({ pending: 0, stale: false });
+ const [{ n }] = await engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM planner_stats_deltas');
+ expect(n).toBe(0);
+ });
+
+ test('5. a modification committed between reading the watermark and publishing stays pending', async () => {
+ await insertFacts(700);
+ __testing.hooks.beforePublish = async (_engine, name) => {
+ if (name === 'facts') await engine.executeRaw(`INSERT INTO facts (fact, source) SELECT 'racer ' || g, 'test' FROM generate_series(1, 25) g`);
+ };
+
+ const result = await maybeRefreshPlannerStats(engine, 'repair', { throttle: false });
+
+ expect(result.analyzed.map(a => a.table)).toEqual(['facts']);
+ expect((await table('facts')).pending).toBe(25);
+ });
+
+ test('a stale table is analyzed once and its pending count resets; unchanged tables are left alone', async () => {
+ await insertFacts(700);
+ const first = await maybeRefreshPlannerStats(engine, 'repair', { throttle: false });
+ expect(first.analyzed).toEqual([expect.objectContaining({ table: 'facts', pending: 700 })]);
+ const second = await maybeRefreshPlannerStats(engine, 'repair', { throttle: false });
+ expect(second.analyzed).toEqual([]);
+ expect(await table('facts')).toMatchObject({ pending: 0, reltuples: 700, has_stats: true });
+ });
+
+ test('checks are throttled to one per 2 s per engine', async () => {
+ await maybeRefreshPlannerStats(engine, 'idle');
+ await insertFacts(700);
+ expect((await maybeRefreshPlannerStats(engine, 'idle')).skipped).toBe('throttled');
+ expect((await maybeRefreshPlannerStats(engine, 'import', { throttle: false })).analyzed.map(a => a.table)).toEqual(['facts']);
+ });
+});
+
+describe('first relevant read (O-ENG-12, decision 5)', () => {
+ test('get_health on stale tables analyzes them before answering', async () => {
+ await insertFacts(800);
+ await engine.getHealth();
+ expect(await table('facts')).toMatchObject({ pending: 0, has_stats: true });
+ });
+
+ test('a table whose last ANALYZE exceeded planner.first_read_budget_ms is analyzed after the read', async () => {
+ await insertFacts(800);
+ await engine.executeRaw("INSERT INTO planner_stats_state (table_name, analyzed_through, last_analyze_ms) VALUES ('facts', 0, 60000)");
+ await engine.setConfig('planner.first_read_budget_ms', '2000');
+ const order: string[] = [];
+ let analyzed!: () => void;
+ const done = new Promise<void>(resolve => { analyzed = resolve; });
+ __testing.hooks.onAnalyzed = async (_engine, event) => { order.push(`analyze:${event.table}`); analyzed(); };
+
+ await engine.findOrphanPages();
+ order.push('read answered');
+ await done;
+
+ expect(order).toEqual(['read answered', 'analyze:facts']);
+ expect((await table('facts')).pending).toBe(0);
+ });
+
+ test('reads inside a transaction never analyze', async () => {
+ await insertFacts(800);
+ await engine.transaction(async tx => { await tx.listPages({ limit: 5 }); });
+ expect((await table('facts')).pending).toBe(800);
+ });
+});
+
+describe('7. planner.auto_analyze=false', () => {
+ test('disables every call site; doctor still reports', async () => {
+ await withEnv({ GBRAIN_PLANNER_AUTO_ANALYZE: 'false' }, async () => {
+ await insertFacts(800);
+ for (const reason of ['first_read', 'import', 'managed_sync', 'cycle', 'idle'] as PlannerRefreshReason[]) {
+ __testing.reset(engine);
+ expect((await maybeRefreshPlannerStats(engine, reason, { throttle: false })).skipped).toBe('disabled');
+ }
+ __testing.reset(engine);
+ await engine.getHealth();
+ await engine.searchKeyword('claim');
+ await engine.findOrphanPages();
+ await engine.listPages({ limit: 5 });
+
+ const dir = mkdtempSync(join(tmpdir(), 'planner-off-'));
+ for (let i = 0; i < 3; i++) writeFileSync(join(dir, `note-${i}.md`), `---\ntitle: Note ${i}\n---\nBody ${i}.\n`);
+ await engine.setConfig('import.analyze_every_pages', '1');
+ await runImport(engine, [dir, '--no-embed']);
+
+ const facts = await table('facts');
+ expect(facts).toMatchObject({ pending: 800, stale: true });
+
+ const check = await runDoctorCheck();
+ expect(check.status).toBe('warn');
+ expect(check.message).toContain('facts (800 rows changed since ANALYZE');
+ expect(check.message).toContain('gbrain repair planner-stats --apply');
+ expect(check.message).toContain('gbrain config set planner.auto_analyze true');
+ });
+ });
+
+ test('config key planner.auto_analyze=false disables too; the env var wins over config', async () => {
+ await insertFacts(800);
+ await engine.setConfig('planner.auto_analyze', 'false');
+ expect((await maybeRefreshPlannerStats(engine, 'cycle', { throttle: false })).skipped).toBe('disabled');
+ await withEnv({ GBRAIN_PLANNER_AUTO_ANALYZE: '1' }, async () => {
+ expect((await maybeRefreshPlannerStats(engine, 'cycle', { throttle: false })).analyzed.map(a => a.table)).toEqual(['facts']);
+ });
+ });
+});
+
+describe('doctor planner_stats_stale and repair planner-stats', () => {
+ test('doctor is ok when fresh, warns naming each stale table and the exact fix; repair clears it', async () => {
+ expect((await runDoctorCheck()).status).toBe('ok');
+ expect(categorizeCheck('planner_stats_stale')).toBe('ops');
+
+ await insertFacts(900);
+ await withEnv({ GBRAIN_PLANNER_AUTO_ANALYZE: '0' }, async () => {
+ const check = await runDoctorCheck();
+ expect(check.status).toBe('warn');
+ expect(check.message).toContain('facts (900 rows changed since ANALYZE, threshold 500');
+ expect(check.details?.fix).toBe('gbrain repair planner-stats --apply');
+
+ expect(REPAIR_KINDS).toContain('planner-stats');
+ const plan = await plannerStatsRepair.plan(engine, { brain_id: 'host', source_ids: [] }, null);
+ expect(plan.items.map(i => i.slug)).toEqual(['facts']);
+ const ctx = { engine, logger: { info() {}, warn() {}, error() {} } } as never;
+ expect(await plannerStatsRepair.apply(ctx, plan.items[0]!)).toBe(true);
+ expect((await runDoctorCheck()).status).toBe('ok');
+ });
+ });
+});
diff --git a/test/repair-command.test.ts b/test/repair-command.test.ts
index 6a01e3aec2..96e025720a 100644
--- a/test/repair-command.test.ts
+++ b/test/repair-command.test.ts
@@ -174,7 +174,7 @@ describe('gbrain repair timeline', () => {
} finally { console.log = log; }
const json = JSON.parse(out[0]);
expect(json.scope.source_ids).toEqual([source]);
- expect(json.results.map((r: { kind: string }) => r.kind)).toEqual(['timeline', 'visibility', 'safe-chunks', 'contextual-mode', 'connector-checkpoints', 'request-indexes', 'connector-fences', 'orphan-bindings', 'embedding-effects']);
+ expect(json.results.map((r: { kind: string }) => r.kind)).toEqual(['timeline', 'visibility', 'safe-chunks', 'contextual-mode', 'connector-checkpoints', 'request-indexes', 'connector-fences', 'orphan-bindings', 'embedding-effects', 'planner-stats']);
expect(json.results[0]).toMatchObject({ mode: 'dry_run', affected: 1 });
expect(out[1]).toContain(`Scope: brain `);
expect(out[1]).toContain(`sources ${source}`);