Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Merge origin/master into capy/gbra75-efficiency-wave6
time-attackc642e9a47dc9
diff --cc docs/architecture/key-files/core-search-1.mdindex fe96fb8d94,d0e09aa5a5..0628dab45f--- a/docs/architecture/key-files/core-search-1.md+++ b/docs/architecture/key-files/core-search-1.md@@@ -58,7 -58,7 +58,7 @@@ Current behavior and load-bearing invar- `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 pages than `plannerStatsThreshold` (max(500, 10% of pages)) leaves collected statistics alone, and PGLite then analyzes only the hot tables its row deltas mark stale. 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. On Postgres the refresh also samples the page columns search filters read (`SEARCH_PAGE_STATISTICS_SQL`) and, behind a savepoint so a held lock skips only that step, `content_chunks(model, modality, page_id)`; `refreshChunkStatistics` runs the chunk step alone once at the end of an embed drain that embedded: without them the vector candidate statement sorts every eligible chunk instead of walking the HNSW index (`test/e2e/vector-chunk-statistics-postgres.test.ts`). Migration 161 adds the scoped pending-projection index.++- `src/core/search/projection-statistics.ts` — current-projection expression statistics, strict migration postconditions and owner-authorized batch refresh. Migration 160 verifies object identity and populated samples before advancing the ledger, distinguishing empty tables and row-security-hidden statistics. Import, sync, reindex and drained recovery refresh outside page locks; failures preserve completed writes and give a maintenance hint. A pass that changed fewer pages than `plannerStatsThreshold` (max(500, 10% of pages)) leaves the statistics alone once they exist (the projection statistic, and on Postgres `pages.deleted_at` and `content_chunks.model`), and PGLite then analyzes only the hot tables its row deltas mark stale. On Postgres the refresh also samples the page columns search filters read (`SEARCH_PAGE_STATISTICS_SQL`) and, behind a savepoint so a held lock skips only that step, `content_chunks(model, modality, page_id)`; `refreshChunkStatistics` runs the chunk step alone once at the end of an embed drain that embedded: without them the vector candidate statement sorts every eligible chunk instead of walking the HNSW index (`test/e2e/vector-chunk-statistics-postgres.test.ts`). Migration 161 adds the scoped pending-projection index.- `src/core/search/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 --cc src/core/search/projection-statistics.tsindex bf964da70c,4bcb769067..0dc886969d--- a/src/core/search/projection-statistics.ts+++ b/src/core/search/projection-statistics.ts@@@ -40,21 -40,75 +40,101 @@@ export async function verifyProjectionS}/**- * Refreshes the projection statistics after a write pass that changed `changedPages` pages (omitted: always).- * A pass that changed fewer pages than the planner-statistics threshold (max(500, 10% of pages), autovacuum's- * scale) leaves collected statistics alone: the current-page fraction barely moves, and the narrow ANALYZE cost- * 170 ms per one-page sync at 50k pages on Postgres and a full ANALYZE of every table on PGLite. PGLite still- * analyzes any hot table its row deltas mark stale.+ * The content_chunks columns vector search's candidate statement is estimated+ * from: its generation and modality filters (cc.model, cc.modality) and its+ * page join (cc.page_id). Without them Postgres prices each equality at 0.5%,+ * expects a handful of eligible chunks, and sorts every candidate instead of+ * walking the HNSW index: at 1M to 2M chunks that runs past the 8 s vector+ * budget (docs/eval/hnsw-scale-bench.md, "Statistics states and EXPLAIN").+ */+ export const CHUNK_STATISTICS_SQL = 'ANALYZE content_chunks(model, modality, page_id)';++ /**+ * The Postgres page refresh: the projection columns plus the page columns+ * every search filter reads (`p.deleted_at IS NULL`, source, type and slug+ * scopes). Without `deleted_at` statistics Postgres prices `IS NULL` at 0.5%+ * and drives the vector candidate statement from a few pages into their+ * chunks and a sort, even with content_chunks analyzed. Wide columns+ * (frontmatter, compiled_truth) stay out, so the sample stays cheap.+ */+ export const SEARCH_PAGE_STATISTICS_SQL = 'ANALYZE pages(text_projection_revision, knowledge_revision, deleted_at, source_id, type, slug)';++ const CHUNK_STATISTICS_WARNING = `[search] Chunk planner statistics could not be refreshed (a lock or the 30 s bound). Vector search may skip its index until autovacuum analyzes content_chunks; run ${CHUNK_STATISTICS_SQL} as the table owner to fix it now.`;++ /**+ * The chunk ANALYZE inside a caller's bounded Postgres transaction, behind a+ * savepoint: a concurrent index build holding the table's lock (2 s lock+ * timeout) costs this step alone, never the caller's page statistics. A role+ * that does not own the table gets Postgres's skip warning, not an error.+ */+ async function analyzeChunkColumns(tx: BrainEngine): Promise<boolean> {+ await tx.executeRaw('SAVEPOINT chunk_statistics');+ try {+ await tx.executeRaw(CHUNK_STATISTICS_SQL);+ await tx.executeRaw('RELEASE SAVEPOINT chunk_statistics');+ return true;+ } catch {+ await tx.executeRaw('ROLLBACK TO SAVEPOINT chunk_statistics');+ console.warn(CHUNK_STATISTICS_WARNING);+ return false;+ }+ }++ /**+ * Postgres only (PGLite's planner-stats deltas own its chunk statistics): one+ * bounded narrow ANALYZE of content_chunks after an embed drain, which moves+ * content_chunks.model on every row it embeds. Import, sync and reindex get+ * the same step inside refreshProjectionStatistics.+ */+ export async function refreshChunkStatistics(engine: BrainEngine): Promise<boolean> {+ if (engine.kind !== 'postgres') return false;+ try {+ return await engine.transaction(async tx => {+ await tx.executeRaw("SET LOCAL statement_timeout = '30s'");+ await tx.executeRaw("SET LOCAL lock_timeout = '2s'");+ return analyzeChunkColumns(tx);+ });+ } catch {+ console.warn(CHUNK_STATISTICS_WARNING);+ return false;+ }+ }++ /** Runs an embed drain, then refreshes the chunk statistics once when `changed()` says it embedded something (a drain moves content_chunks.model on every row it embeds). */+ export async function withChunkStatisticsRefresh<T>(engine: BrainEngine, changed: () => boolean, drain: () => Promise<T>): Promise<T> {+ const out = await drain();+ if (changed()) await refreshChunkStatistics(engine);+ return out;+ }+-export async function refreshProjectionStatistics(engine: BrainEngine): Promise<boolean> {++/**++ * Whether a write pass that changed `changedPages` pages can leave the planner statistics alone: it changed fewer++ * pages than the planner-statistics threshold (max(500, 10% of pages), autovacuum's scale) and the statistics this++ * refresh collects already exist. Such a pass barely moves them, and the refresh cost 170 ms per one-page sync at++ * 50k pages on Postgres and a full ANALYZE of every table on PGLite.++ */++async function statisticsStillCurrent(engine: BrainEngine, changedPages: number): Promise<boolean> {++ if (!Number.isFinite(changedPages)) return false;++ const [state] = await engine.executeRaw<{ reltuples: number; columns: boolean }>(++ `SELECT c.reltuples::float8 AS reltuples,++ $1::text <> 'postgres' OR (SELECT count(*) FROM pg_stats s WHERE s.schemaname = current_schema()++ AND ((s.tablename = 'pages' AND s.attname = 'deleted_at') OR (s.tablename = 'content_chunks' AND s.attname = 'model'))) = 2 AS columns++ FROM pg_class c WHERE c.oid = 'pages'::regclass`, [engine.kind]);++ if (!state?.columns || changedPages >= plannerStatsThreshold(Number(state.reltuples))) return false;++ return verifyProjectionStatistics(engine).then(() => true, () => false);++}++++/**++ * Refreshes the planner statistics after a write pass that changed `changedPages` pages (omitted: always). A pass++ * `statisticsStillCurrent` vouches for skips the ANALYZE; PGLite then analyzes only the hot tables its row deltas++ * mark stale.+ */+export async function refreshProjectionStatistics(engine: BrainEngine, changedPages = Infinity): Promise<boolean> {try {- if (Number.isFinite(changedPages)) {- const [pages] = await engine.executeRaw<{ reltuples: number }>("SELECT reltuples::float8 AS reltuples FROM pg_class WHERE oid = 'pages'::regclass");- if (changedPages < plannerStatsThreshold(Number(pages?.reltuples ?? -1)) && await verifyProjectionStatistics(engine).then(() => true, () => false)) {- await maybeRefreshPlannerStats(engine, 'import', { throttle: false });- return true;- }++ if (await statisticsStillCurrent(engine, changedPages)) {++ await maybeRefreshPlannerStats(engine, 'import', { throttle: false });++ return true;+ }const [role] = await engine.executeRaw<{ can_analyze: boolean }>(`SELECT pg_has_role(current_user, p.relowner, 'USAGE') OR r.rolsuper AS can_analyzeFROM pg_class p CROSS JOIN pg_roles r