Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
perf(extract): the --source db links walk refreshes planner stats on PGLite
time-attackefa10c24ff32
diff --git a/docs/architecture/key-files/core-utilities-1.md b/docs/architecture/key-files/core-utilities-1.mdindex 2637bae08f..ad0d289c2d 100644--- a/docs/architecture/key-files/core-utilities-1.md+++ b/docs/architecture/key-files/core-utilities-1.md@@ -12,7 +12,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/brain-score-recommendations.ts` — pure data layer consumed by both `gbrain doctor --remediation-plan` / `--remediate` and `gbrain features`. Extraction-watermark staleness produces source-scoped `extract.stale` against database pages, including DB-only pages without a checkout; it does not imply a filesystem sync or block embedding on one. `RecommendationContext.staleExtractionBlocked` (probed by `staleExtractionBlocked()` in `remediation/context.ts`, shared with autopilot) withholds `extract.stale` and classifies `links_extraction_lag` as blocked while the remediated source, or any source with stale pages in an all-source sweep, cannot load its active schema pack, so no dispatch fails every cycle. `computeRecommendations(checks, opts)` returns `Remediation[]` with stable `id`, content-hash `idempotency_key`, `severity`, `est_seconds`, `est_usd_cost`, `depends_on` (references stable ids, not check names — so plan order is reproducible). `classifyChecks(report)` triages every doctor check three-state into `remediable | human_only | blocked` (`human_only` covers RLS warnings and other human-judgment gates; `blocked` covers dependency chains where a parent check failed). `maxReachableScore(checks)` computes the ceiling for empty/under-configured brains (no entity pages → graph_coverage caps at 70; no embedding key → embedding_coverage caps at 60). Cost estimates pull from `anthropic-pricing.ts` (synthesize/patterns/consolidate) and `embedding-pricing.ts` (embed jobs). Pinned by `test/brain-score-recommendations.test.ts` (~27 cases incl. determinism, content-hash idempotency, DB-backed checkpoint provenance, three-state triage).- `src/core/orphan-policy.ts` — the shared orphan-reporting policy (`gbrain orphans`, doctor's orphan ratio, `get_health`): convention constants plus per-brain `orphans.exclude_prefixes` / `orphans.exclude_slugs` overrides. Two renderers over the same constants: `shouldExcludeFromOrphanReporting(slug, overrides, meta)` (TypeScript) and `orphanExclusionSql(alias, overrides)` (a never-NULL SQL predicate; every list value is a bound parameter, only the identifier-checked alias is spliced; regexes are spelled for Postgres's engine: ASCII digits, `.` stops at line terminators). Quarantine stays outside the SQL predicate. Parity pinned on a generated slug/type corpus by `test/orphan-policy-sql-parity.test.ts` and its Postgres arm in `test/e2e/engine-sql-health-parity.test.ts`.-- `src/core/planner-stats.ts` + `src/core/planner-stats-schema.ts` — F4b row-delta ANALYZE for PGLite (no autovacuum; `n_mod_since_analyze` is never populated there). Migration f4_planner_stats (`sqlFor.pglite` only; a Postgres no-op) adds `planner_stats_deltas` / `planner_stats_state` and AFTER STATEMENT transition-table triggers on pages, links, facts, takes, content_chunks and timeline_entries, so modification counts commit or roll back with the data and survive restarts. `maybeRefreshPlannerStats(engine, reason)` ANALYZEs tables whose pending count exceeds max(500, 10% of reltuples) (or that have rows but no pg_stats) and publishes a watermark read before the ANALYZE, so a concurrent modification stays pending; checks are throttled to one per 2 s per engine. Call sites: PGLite planner-sensitive reads (`beforePlannerRead`, deferring a table whose last ANALYZE exceeded `planner.first_read_budget_ms`), import and managed sync every `import.analyze_every_pages`, stale link drains of at least `LINK_DRAIN_ANALYZE_MIN_STALE` (500) pages through `plannerStatsForLinkDrain` (before the first page, then on the same cadence; `link_transitions` and `link_relationships`, which carry no deltas, whenever `links` is analyzed), the cycle after extract_facts, the consumer idle tick, and `refreshProjectionStatistics` (full ANALYZE publishes every watermark). `planner.auto_analyze=false` / `GBRAIN_PLANNER_AUTO_ANALYZE=0` disables them all. Doctor `planner_stats_stale` (Postgres: `pg_stat_user_tables`) and repair kind `planner-stats` keep working. Guide: `docs/guides/planner-stats.md`. Tests: `test/planner-stats*.test.ts` (`planner-stats-link-drain.test.ts` EXPLAINs the drain's snapshot read), `test/e2e/planner-stats-postgres.test.ts`.+- `src/core/planner-stats.ts` + `src/core/planner-stats-schema.ts` — F4b row-delta ANALYZE for PGLite (no autovacuum; `n_mod_since_analyze` is never populated there). Migration f4_planner_stats (`sqlFor.pglite` only; a Postgres no-op) adds `planner_stats_deltas` / `planner_stats_state` and AFTER STATEMENT transition-table triggers on pages, links, facts, takes, content_chunks and timeline_entries, so modification counts commit or roll back with the data and survive restarts. `maybeRefreshPlannerStats(engine, reason)` ANALYZEs tables whose pending count exceeds max(500, 10% of reltuples) (or that have rows but no pg_stats) and publishes a watermark read before the ANALYZE, so a concurrent modification stays pending; checks are throttled to one per 2 s per engine. Call sites: PGLite planner-sensitive reads (`beforePlannerRead`, deferring a table whose last ANALYZE exceeded `planner.first_read_budget_ms`), import and managed sync every `import.analyze_every_pages`, stale link drains and the `extract --source db` links walk of at least `LINK_DRAIN_ANALYZE_MIN_STALE` (500) pages through `plannerStatsForLinkDrain` (first page, then the same cadence; `link_transitions`/`link_relationships`, no deltas, with `links`), the cycle after extract_facts, the consumer idle tick, and `refreshProjectionStatistics` (full ANALYZE publishes every watermark). `planner.auto_analyze=false` / `GBRAIN_PLANNER_AUTO_ANALYZE=0` disables them all. Doctor `planner_stats_stale` (Postgres: `pg_stat_user_tables`) and repair kind `planner-stats` keep working. Guide: `docs/guides/planner-stats.md`. Tests: `test/planner-stats*.test.ts` (`planner-stats-link-drain.test.ts` EXPLAINs the drain's snapshot read), `test/e2e/planner-stats-postgres.test.ts`.- `src/core/timeline-grading.ts` — `loadTimelineGradedPredicate(engine)`: which pages the 15-point brain_score timeline component grades (#5828). `engine-sql/health.ts` applies the predicate per page type to the linkable groups; `gradeTimelinePages` (re-exported by `orphan-policy.ts`) keeps the linkable (orphan-policy) pages whose active-pack primitive is `entity` or `temporal` (aliases resolve to the canonical type); undeclared and untyped types, and every page when no pack resolves, stay graded. Labelled "timeline density (entity and event pages)" in doctor and `get_health` output. Pinned by `test/brain-score-timeline-grading.test.ts`.- `src/core/cjk.ts` — Single source of truth for CJK detection. Exports `CJK_RANGES_REGEX`, `CJK_SLUG_CHARS` (character-class fragment for embedding inside other regexes), `SLUG_WORD_CHARS` + `PAGE_SLUG_SEG` (the shared slug-grammar fragments) and `SLUG_VARIATION_SELECTORS_RE` (the Mn-invisible emoji-VS16 / ideographic-IVS strip that BOTH `sync.ts:slugifySegment` and its twin `link-extraction.ts:normalizeBasename` apply, so the two grammars cannot drift on selectors), `CJK_SENTENCE_DELIMITERS` (`。!?`), `CJK_CLAUSE_DELIMITERS` (`;:,、`), `CJK_DENSITY_THRESHOLD = 0.30`, `hasCJK(s)`, `isCJKDominant(s)` (the ONE density test: CJK chars ≥ 30% of non-whitespace chars), `countCJKAwareWords(s)` (routes through `isCJKDominant` — English docs with one Japanese term stay whitespace-tokenized; Chinese-dominant docs get char-counted), and `escapeLikePattern(s)` (escapes `%`, `_`, `\\` for `ILIKE ... ESCAPE '\\'`). BMP-only ranges (Han / Hiragana / Katakana / Hangul Syllables). Consumers: `expansion.ts`, `sync.ts:slugifySegment`, `operations.ts:validatePageSlug + validateFilename`, `chunkers/recursive.ts:countWords + DELIMITERS + extractTrailingContext` (the overlap extractor branches on `isCJKDominant` so it counts the same unit `countWords` does), `pglite-engine.ts:searchKeyword + searchKeywordChunks`.diff --git a/src/commands/extract.ts b/src/commands/extract.tsindex c98a65d926..c1a483d7d0 100644--- a/src/commands/extract.ts+++ b/src/commands/extract.ts@@ -1889,6 +1889,11 @@ async function extractLinksFromDB(const grammar = await readLineGrammarSettings(engine), lineGrammar = { enabled: grammar.enabled, allowUndeclaredTypes: grammar.allowUndeclaredTypes };let skippedSettingsChanged = 0;progress.start('extract.links_db', walkRefs.length);+ // The walk rewrites every page's links; on PGLite (no autovacuum) `links` keeps+ // its pre-walk statistics, so the per-page link statements plan as scans and+ // slow down as the table fills. Same upkeep as the stale drain, every+ // `import.analyze_every_pages` walked pages.+ const plannerTick = dryRun ? async () => {} : await plannerStatsForLinkDrain(engine, async () => walkRefs.length);// Dedup in dry-run only — DB enforces uniqueness via ON CONFLICT in batch writes.const dryRunSeen = dryRun ? new Set<string>() : null;@@ -1914,6 +1919,7 @@ async function extractLinksFromDB(for (const [index, { slug, source_id }] of walkRefs.entries()) {if (index >= snapshotBatch.start + snapshotBatch.covered) {await flushLinkWrites();+ await plannerTick(index);snapshotBatch = { start: index, ...await readPageSnapshotsBatch(engine, walkRefs.slice(index, index + BATCH_SIZE).map(ref => ({ slug: ref.slug, sourceId: ref.source_id }))) };wantedPages = !dryRun && await isWantedPagesEnabled(engine);diff --git a/test/extract-links-db-planner-stats.test.ts b/test/extract-links-db-planner-stats.test.tsnew file mode 100644index 0000000000..d54e867406--- /dev/null+++ b/test/extract-links-db-planner-stats.test.ts@@ -0,0 +1,76 @@+/**+ * `extract links|all --source db` (extractLinksFromDB) refreshes planner+ * statistics during its walk on PGLite (GBRA-75 wave 7). The walk rewrites+ * every page's links; without a refresh `links` keeps its pre-walk statistics+ * (none on a fresh brain), and the per-page link statements slowed from+ * 3.6 ms/page to about 180 ms/page on a 50k brain whose `links` table had+ * filled. The walk reuses the stale-drain upkeep (plannerStatsForLinkDrain):+ * a check before the first page, then every `import.analyze_every_pages`+ * walked pages, analyzing only tables past the F4b threshold.+ * Seam: planner-stats __testing.hooks.onAnalyzed (observes, changes nothing).+ * In-memory PGLite ($0).+ */+import { afterAll, beforeAll, expect, test } from 'bun:test';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { runExtract } from '../src/commands/extract.ts';+import { configureGateway, resetGateway } from '../src/core/ai/gateway.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { __testing, LINK_DRAIN_ANALYZE_MIN_STALE, type PlannerRefreshReason } from '../src/core/planner-stats.ts';+import { withEnv } from './helpers/with-env.ts';++const PAGES = LINK_DRAIN_ANALYZE_MIN_STALE + 300;+const engines: PGLiteEngine[] = [];++beforeAll(() => {+ configureGateway({ embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: 1536, env: {} });+});+afterAll(async () => {+ for (const engine of engines) { await disposePersistenceConsumer(engine); await engine.disconnect(); }+ resetGateway();+ __testing.hooks.onAnalyzed = undefined;+});++async function brainWithoutLinks(): Promise<PGLiteEngine> {+ const engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ engines.push(engine);+ for (let i = 0; i < PAGES; i++) {+ await engine.putPage(`notes/page-${i}`, { type: 'note', title: `Page ${i}`,+ compiled_truth: `Page ${i}. Related: [[notes/page-${(i + 1) % PAGES}]] and [[notes/page-${(i + 7) % PAGES}]].` });+ }+ return engine;+}++async function walk(engine: PGLiteEngine, events: Array<{ reason: PlannerRefreshReason; table: string }>, args: string[] = []) {+ __testing.hooks.onAnalyzed = async (_engine, event) => { events.push({ reason: event.reason, table: event.table }); };+ try { await runExtract(engine, ['links', '--source', 'db', '--json', ...args]); }+ finally { __testing.hooks.onAnalyzed = undefined; }+}++test('the links walk analyzes `links` once it fills, and the same links land', async () => {+ const engine = await brainWithoutLinks();+ const events: Array<{ reason: PlannerRefreshReason; table: string }> = [];+ await walk(engine, events);+ expect(events.filter(e => e.reason === 'extract').map(e => e.table)).toContain('links');+ const [stats] = await engine.executeRaw<{ n: number }>("SELECT count(*)::int AS n FROM pg_stats WHERE schemaname = 'public' AND tablename = 'links'");+ expect(stats!.n).toBeGreaterThan(0);+ const [links] = await engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM links');+ expect(links!.n).toBe(PAGES * 2);+}, 180_000);++test('planner.auto_analyze=false: the links walk runs no ANALYZE', async () => {+ const engine = await brainWithoutLinks();+ const events: Array<{ reason: PlannerRefreshReason; table: string }> = [];+ await withEnv({ GBRAIN_PLANNER_AUTO_ANALYZE: 'false' }, () => walk(engine, events));+ expect(events).toEqual([]);+ const [links] = await engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM links');+ expect(links!.n).toBe(PAGES * 2);+}, 180_000);++test('--dry-run walks without analyzing', async () => {+ const engine = await brainWithoutLinks();+ const events: Array<{ reason: PlannerRefreshReason; table: string }> = [];+ await walk(engine, events, ['--dry-run']);+ expect(events).toEqual([]);+}, 180_000);