Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Wave B PR 1: search statistics cover the generation columns
garrytandc02a5f7f48f
diff --git a/docs/ENGINES.md b/docs/ENGINES.mdindex e302400cd2..823fff6205 100644--- a/docs/ENGINES.md+++ b/docs/ENGINES.md@@ -173,14 +173,14 @@ describes bounded candidate recovery and incomplete-result metadata.On Postgres the same refresh also analyzes the page columns every searchfilter reads (`deleted_at`, `source_id`, `type`, `slug`) and-`content_chunks(model, modality, page_id)`, and an embed drain that embedded+`content_chunks(model, modality, page_id, body_generation, retired_generation)`, and an embed drain that embeddedanything analyzes those chunk columns once at its end (each ANALYZE bounded bya 30 s statement and 2 s lock timeout). Without those statistics the vectorcandidate statement sorts every eligible chunk instead of walking the HNSWindex, and at 1M chunks and above that sort runs past the 8 s vector budget,so hybrid search falls back to keyword-only results until autovacuumanalyzes the tables. If a refresh is skipped (a lock, or a role that does not-own the tables), run `ANALYZE content_chunks(model, modality, page_id)` and+own the tables), run `ANALYZE content_chunks(model, modality, page_id, body_generation, retired_generation)` and`ANALYZE pages` as the table owner.### Vector index sizingdiff --git a/docs/architecture/key-files/core-search-1.md b/docs/architecture/key-files/core-search-1.mdindex 67dcfe4a39..9d466d6f84 100644--- a/docs/architecture/key-files/core-search-1.md+++ b/docs/architecture/key-files/core-search-1.md@@ -69,7 +69,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/search/projection-readiness.ts` — EXISTS probe for unsealed text revisions in the visible scope: ready, projection_pending or unknown. Cached per scope by DB generation (page clock, `pages` filenode, archive flags, no open transaction); `GBRAIN_PROJECTION_READINESS_CACHE=0` disables.-- `src/core/search/projection-statistics.ts` — current-projection expression statistics, strict migration postconditions and owner-authorized batch refresh. Migration 160 verifies object identity and populated samples before advancing the ledger, distinguishing empty tables and row-security-hidden statistics. Import, sync, reindex and drained recovery refresh outside page locks; failures preserve completed writes and give a maintenance hint. A pass that changed fewer than 50 + 10% of the sampled pages leaves the statistics alone once they exist (the projection statistic and, on Postgres, every `SEARCH_STATISTICS_COLUMNS` column: `missingSearchStatistics`), and PGLite then analyzes only the hot tables its row deltas mark stale. On Postgres the refresh also samples the page columns search filters read (`SEARCH_PAGE_STATISTICS_SQL`) and, behind a savepoint so a held lock skips only that step, `content_chunks(model, modality, page_id)`; `refreshChunkStatistics` runs the chunk step alone once at the end of an embed drain that embedded: without them the vector candidate statement sorts every eligible chunk instead of walking the HNSW index (`test/e2e/vector-chunk-statistics-postgres.test.ts`). Absent search statistics (pg_upgrade, a deleted pg_statistic; 50-60 s searches at 5k pages) get `ensureSearchStatistics`: PostgresEngine runs it once per engine in the background on its first pool search (never awaited; disconnect waits), and doctor `planner_stats_stale` plus `repair planner-stats` report and apply the same refresh (`test/search-statistics-guard.test.ts`). Migration 161 adds the scoped pending-projection index.+- `src/core/search/projection-statistics.ts` — current-projection expression statistics, strict migration postconditions and owner-authorized batch refresh. Migration 160 verifies object identity and populated samples before advancing the ledger, distinguishing empty tables and row-security-hidden statistics. Import, sync, reindex and drained recovery refresh outside page locks; failures preserve completed writes and give a maintenance hint. A pass that changed fewer than 50 + 10% of the sampled pages leaves the statistics alone once they exist (the projection statistic and, on Postgres, every `SEARCH_STATISTICS_COLUMNS` column: `missingSearchStatistics`), and PGLite then analyzes only the hot tables its row deltas mark stale. On Postgres the refresh also samples the page columns search filters read (`SEARCH_PAGE_STATISTICS_SQL`) and, behind a savepoint so a held lock skips only that step, `content_chunks(model, modality, page_id, body_generation, retired_generation)`; `refreshChunkStatistics` runs the chunk step alone once at the end of an embed drain that embedded: without them the vector candidate statement sorts every eligible chunk instead of walking the HNSW index (`test/e2e/vector-chunk-statistics-postgres.test.ts`). Absent search statistics (pg_upgrade, a deleted pg_statistic; 50-60 s searches at 5k pages) get `ensureSearchStatistics`: PostgresEngine runs it once per engine in the background on its first pool search (never awaited; disconnect waits), and doctor `planner_stats_stale` plus `repair planner-stats` report and apply the same refresh (`test/search-statistics-guard.test.ts`). Migration 161 adds the scoped pending-projection index.- `src/core/search/query-cache.ts` — stored semantic-cache data and maintenance remain, but `semanticResultCacheAvailable()` is false. `hybridSearchCached` bypasses both result lookup and writes regardless of configuration or `useCache`, and skips the key/config setup (merged config, cache config, intent-pattern state) so the wrapper adds no engine round-trips; request-local query embeddings still work. Search metadata, cache_stats and the mode dashboard report effective caching as disabled. Historical hit counts and search_telemetry remain intact. Restoration requires complete response-dependency provenance.diff --git a/docs/eval/hnsw-scale-bench.md b/docs/eval/hnsw-scale-bench.mdindex c27ca98d14..17bf13ae9d 100644--- a/docs/eval/hnsw-scale-bench.md+++ b/docs/eval/hnsw-scale-bench.md@@ -15,7 +15,7 @@ neighbours. The deeper scan has these effects:- **Unscoped searches** return identical results.**Fix 2: statistics follow bulk writes.** Import, sync, reindex and embed drains now analyze-`content_chunks(model, modality, page_id)` and the page columns search filters read. Without those+`content_chunks(model, modality, page_id, body_generation, retired_generation)` and the page columns search filters read. Without thosestatistics, the pooled statement sorted every eligible chunk instead of walking the index. At 1M to 2Mchunks that ran past the 8 s budget on 44% to 100% of 50%-scoped searches. In the post-import statisticsstate, 1M and 2M chunks now plan on HNSW with no incomplete results.@@ -189,8 +189,8 @@ decimals in every cell. The topic-coherent gap is not a scan budget.`refreshProjectionStatistics` (`src/core/search/projection-statistics.ts`) used to run`ANALYZE pages(text_projection_revision, knowledge_revision)` only. That is what import, sync, reindex andprojection recovery end with. On Postgres it now runs two steps:-1. `ANALYZE pages(text_projection_revision, knowledge_revision, deleted_at, source_id, type, slug)`.-2. `ANALYZE content_chunks(model, modality, page_id)`, in the same transaction (30 s statement and 2 s lock+1. `ANALYZE pages(text_projection_revision, knowledge_revision, deleted_at, source_id, type, slug, body_generation)`.+2. `ANALYZE content_chunks(model, modality, page_id, body_generation, retired_generation)`, in the same transaction (30 s statement and 2 s locktimeouts) behind a savepoint, so a concurrent index build only skips this step, with a warning thatnames the command.diff --git a/docs/guides/planner-stats.md b/docs/guides/planner-stats.mdindex e84f2b9220..a4d5b8d04d 100644--- a/docs/guides/planner-stats.md+++ b/docs/guides/planner-stats.md@@ -53,7 +53,7 @@ until 10% of a table changes. Without the page columns search filters read,search plans as nested loops over every page (50-60 s per search at 5,000pages instead of 0.5 s). gbrain guards this two ways, both through the samerefresh as import and sync (`ANALYZE pages(...)` and-`ANALYZE content_chunks(model, modality, page_id)`, 30 s bounded):+`ANALYZE content_chunks(model, modality, page_id, body_generation, retired_generation)`, 30 s bounded):- The first search of each process checks in the background and collects themwhen the database role owns the tables. The search does not wait for it.diff --git a/llms-full.txt b/llms-full.txtindex 4fcef43e8f..13195fe3f6 100644--- a/llms-full.txt+++ b/llms-full.txt@@ -5412,14 +5412,14 @@ describes bounded candidate recovery and incomplete-result metadata.On Postgres the same refresh also analyzes the page columns every searchfilter reads (`deleted_at`, `source_id`, `type`, `slug`) and-`content_chunks(model, modality, page_id)`, and an embed drain that embedded+`content_chunks(model, modality, page_id, body_generation, retired_generation)`, and an embed drain that embeddedanything analyzes those chunk columns once at its end (each ANALYZE bounded bya 30 s statement and 2 s lock timeout). Without those statistics the vectorcandidate statement sorts every eligible chunk instead of walking the HNSWindex, and at 1M chunks and above that sort runs past the 8 s vector budget,so hybrid search falls back to keyword-only results until autovacuumanalyzes the tables. If a refresh is skipped (a lock, or a role that does not-own the tables), run `ANALYZE content_chunks(model, modality, page_id)` and+own the tables), run `ANALYZE content_chunks(model, modality, page_id, body_generation, retired_generation)` and`ANALYZE pages` as the table owner.### Vector index sizingdiff --git a/src/core/schema-migrations/v248-segmented-page-storage.ts b/src/core/schema-migrations/v248-segmented-page-storage.tsindex 67395ed3c8..381d3604a3 100644--- a/src/core/schema-migrations/v248-segmented-page-storage.ts+++ b/src/core/schema-migrations/v248-segmented-page-storage.ts@@ -107,5 +107,10 @@ export const v248: Migration = {await engine.runMigration(248, 'ALTER TABLE pages VALIDATE CONSTRAINT pages_body_storage_chk;');await engine.runMigration(248, 'ALTER TABLE page_versions VALIDATE CONSTRAINT page_versions_body_chk;');await buildIndexOnline(engine, 248, CONTENT_CHUNKS_OCCURRENCE_INDEX, { notice: migrationNotice });+ // Search's visibility predicate reads the generation columns; without their statistics Postgres prices it at 0.5%+ // and vector search sorts every candidate instead of walking its HNSW index (projection-statistics.ts).+ if (engine.kind === 'postgres') {+ await engine.runMigration(248, 'ANALYZE pages(body_generation); ANALYZE content_chunks(body_generation, retired_generation);');+ }},};diff --git a/src/core/search/projection-statistics.ts b/src/core/search/projection-statistics.tsindex 041d9b4d09..02a8df7e62 100644--- a/src/core/search/projection-statistics.ts+++ b/src/core/search/projection-statistics.ts@@ -55,8 +55,8 @@ export async function verifyProjectionStatistics(engine: Pick<BrainEngine, 'exec* source scope and run as pages-by-pages nested loops: at 5,000 pages a search took 50-60 s instead of 0.5 s.*/export const SEARCH_STATISTICS_COLUMNS = {- pages: ['text_projection_revision', 'knowledge_revision', 'deleted_at', 'source_id', 'type', 'slug'],- content_chunks: ['model', 'modality', 'page_id'],+ pages: ['text_projection_revision', 'knowledge_revision', 'deleted_at', 'source_id', 'type', 'slug', 'body_generation'],+ content_chunks: ['model', 'modality', 'page_id', 'body_generation', 'retired_generation'],} as const;/**diff --git a/test/e2e/keyword-arm-ranking-postgres.test.ts b/test/e2e/keyword-arm-ranking-postgres.test.tsindex 6882018ad6..e143171395 100644--- a/test/e2e/keyword-arm-ranking-postgres.test.ts+++ b/test/e2e/keyword-arm-ranking-postgres.test.ts@@ -64,7 +64,7 @@ describe('keyword arm plan (postgres)', () => {test(`\`${query}\` with excludePrivate runs the full-text match inside the OFFSET 0 subquery`, async () => {const { sql, params, rows } = await capturedKeywordStatement(query, true);expect(rows).toBeGreaterThan(0);- expect(sql).toMatch(/FROM \(\s*SELECT id, page_id, chunk_index, chunk_text, chunk_source, search_vector, language, symbol_type\s+FROM content_chunks\s+WHERE search_vector @@ websearch_to_tsquery\('[a-z_]+', \$1\) AND modality = 'text'\s+OFFSET 0\s*\) cc\s+JOIN pages p/);+ expect(sql).toMatch(/FROM \(\s*SELECT id, page_id, chunk_index, chunk_text, chunk_source, search_vector, language, symbol_type, body_generation, retired_generation\s+FROM content_chunks\s+WHERE search_vector @@ websearch_to_tsquery\('[a-z_]+', \$1\) AND modality = 'text'\s+OFFSET 0\s*\) cc\s+JOIN pages p/);expect(sql).not.toMatch(/cc\.search_vector @@/);const plan = (await engine.executeRaw<{ 'QUERY PLAN': string }>(`EXPLAIN ${sql}`, params)).map((r) => r['QUERY PLAN']).join('\n');expect(plan).toContain('content_chunks');diff --git a/test/e2e/segmented-storage-statistics-postgres.test.ts b/test/e2e/segmented-storage-statistics-postgres.test.tsnew file mode 100644index 0000000000..511dd0415e--- /dev/null+++ b/test/e2e/segmented-storage-statistics-postgres.test.ts@@ -0,0 +1,43 @@+/**+ * Wave B: migration v248 leaves the search statistics complete on an upgraded+ * Postgres brain. Search's chunk visibility predicate reads+ * pages.body_generation and content_chunks.body_generation/retired_generation;+ * columns added by ALTER TABLE have no pg_stats rows until ANALYZE, and+ * without them vector search drops its HNSW plan+ * (test/e2e/vector-chunk-statistics-postgres.test.ts).+ *+ * Fails when: v248 stops collecting statistics for the generation columns, or+ * SEARCH_STATISTICS_COLUMNS stops naming them.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { getEngine, hasDatabase, importFixtures, setupDB, teardownDB } from './helpers.ts';+import { missingSearchStatistics } from '../../src/core/search/projection-statistics.ts';+import { v248 } from '../../src/core/schema-migrations/v248-segmented-page-storage.ts';++const d = hasDatabase() ? describe : describe.skip;+const GENERATION_COLUMNS = ['pages.body_generation', 'content_chunks.body_generation', 'content_chunks.retired_generation'];++d('v248 search statistics on Postgres', () => {+ beforeAll(async () => {+ await setupDB();+ await importFixtures();+ const engine = getEngine();+ await engine.executeRaw('ANALYZE pages');+ await engine.executeRaw('ANALYZE content_chunks');+ // An upgraded brain: the pre-v248 columns are sampled, the columns v248 adds are not. The fixture stands in for a+ // large brain (missingSearchStatistics acts on tables sampled at 500 rows or more).+ await engine.executeRaw(`DELETE FROM pg_statistic s USING pg_attribute a+ WHERE a.attrelid = s.starelid AND a.attnum = s.staattnum+ AND ((a.attrelid = 'pages'::regclass AND a.attname = 'body_generation')+ OR (a.attrelid = 'content_chunks'::regclass AND a.attname IN ('body_generation', 'retired_generation')))`);+ await engine.executeRaw("UPDATE pg_class SET reltuples = 5000 WHERE oid IN ('pages'::regclass, 'content_chunks'::regclass)");+ }, 60_000);+ afterAll(async () => { await teardownDB(); });++ test('the generation columns are search statistics, and v248 collects them', async () => {+ const engine = getEngine();+ expect(await missingSearchStatistics(engine)).toEqual(GENERATION_COLUMNS);+ await v248.handler!(engine);+ expect(await missingSearchStatistics(engine)).toEqual([]);+ });+});