Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(search): a role that does not own pages stops warning on every import

garrytan26f70b9a1d65
diff --git a/docs/architecture/key-files/core-search-1.md b/docs/architecture/key-files/core-search-1.md
index 198dd347ac..192e04ba79 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` — one statement probes visible unsealed pages: ready, projection_pending, by_design (protected/archived only, if none pending) or unknown; LIMIT 1 arms use the v161 pending index. Cached per scope by DB generation (page clock, pages filenode, archive flags, no open tx); `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 it also samples the page columns search filters read (`SEARCH_PAGE_STATISTICS_SQL`) and the chunk `SEARCH_STATISTICS_COLUMNS`; a vacuum holding a table defers it (analyze-lock.ts). `refreshChunkStatistics` runs the chunk step after a drain that changed 50 + 10% of chunks (any sans statistics): 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`).
+- `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 from statistics this role cannot see. 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 it also samples the page columns search filters read (`SEARCH_PAGE_STATISTICS_SQL`) and the chunk `SEARCH_STATISTICS_COLUMNS`; a vacuum holding a table defers it (analyze-lock.ts). `refreshChunkStatistics` runs the chunk step after a drain that changed 50 + 10% of chunks (any sans statistics): 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`).
- `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/src/commands/doctor/checks/planner-stats.ts b/src/commands/doctor/checks/planner-stats.ts
index 53f41b7cfe..11f01dc9a4 100644
--- a/src/commands/doctor/checks/planner-stats.ts
+++ b/src/commands/doctor/checks/planner-stats.ts
@@ -16,7 +16,8 @@
* search guard use): after pg_upgrade or a deleted pg_statistic autovacuum
* never collects them, and search plans as nested loops (50-60 s at 5,000
* pages). The fix runs the same refresh through `gbrain repair planner-stats
- * --apply`; a role that may not ANALYZE gets it as a host-operator step.
+ * --apply`; a role that may not ANALYZE gets it as a host-operator step. A role that cannot inspect the projection
+ * statistic (Postgres shows expression statistics only to the owner) is told so instead of hearing it is fresh.
*
* Both engines also report each expression index on a hot table that has no
* statistics under its own name (`readExpressionIndexesWithoutStats`, lhf wave 2
@@ -31,7 +32,7 @@
*/
import { plannerAutoAnalyzeEnabled, PLANNER_STATS_REPAIR_COMMAND, readExpressionIndexesWithoutStats, readPlannerTableStates,
readVacuumStarvation, VACUUM_STARVATION_HOURS, type ExpressionIndexGap, type VacuumStarvation } from '../../../core/planner-stats.ts';
-import { canAnalyzePages, missingSearchStatistics } from '../../../core/search/projection-statistics.ts';
+import { canAnalyzePages, missingSearchStatistics, readProjectionStatistics } from '../../../core/search/projection-statistics.ts';
import type { Check } from '../../doctor.ts';
import { doctorVerify } from '../check-fix.ts';
import { connectedEngine, type DoctorContext, type DoctorEntry } from '../context.ts';
@@ -52,11 +53,14 @@ async function runPlannerStats(ctx: DoctorContext): Promise<Check[]> {
const missing = await missingSearchStatistics(engine);
const gaps = await readExpressionIndexesWithoutStats(engine);
const starved = await readVacuumStarvation(engine);
+ const hidden = engine.kind === 'postgres' && await readProjectionStatistics(engine) === 'uninspectable';
const details = { engine: engine.kind, auto_analyze: autoAnalyze, checked: tables.map(t => t.table), stale, missing_search_statistics: missing,
- expression_indexes_without_statistics: gaps, ...(starved.length ? { vacuum_starved: starved } : {}), fix: PLANNER_STATS_REPAIR_COMMAND };
+ expression_indexes_without_statistics: gaps, ...(starved.length ? { vacuum_starved: starved } : {}), ...(hidden ? { projection_statistics: 'uninspectable' } : {}),
+ fix: PLANNER_STATS_REPAIR_COMMAND };
const expression = [expressionIndexText(gaps, engine.kind, autoAnalyze), starvationText(starved)].filter(Boolean).join(' ');
if (stale.length === 0 && missing.length === 0 && gaps.length === 0 && starved.length === 0) {
- checks.push({ name: 'planner_stats_stale', status: 'ok', message: `Planner statistics are fresh on ${tables.length} hot tables.`, details });
+ checks.push({ name: 'planner_stats_stale', status: 'ok', message: `Planner statistics are fresh on ${tables.length} hot tables.${hidden
+ ? ' This role cannot inspect the projection statistic; run gbrain doctor as the owner of pages to check it.' : ''}`, details });
return checks;
}
if (missing.length > 0) {
diff --git a/src/core/search/projection-statistics.ts b/src/core/search/projection-statistics.ts
index 5b3fbb8960..a185f4a6f7 100644
--- a/src/core/search/projection-statistics.ts
+++ b/src/core/search/projection-statistics.ts
@@ -20,11 +20,14 @@ interface ProjectionStatisticsRow {
collected: boolean | null;
}
-/** The projection statistics' definition and collection state; `$${n}` binds PROJECTION_STATISTICS_NAME. */
+/**
+ * The projection statistics' definition and collection state; `$${n}` binds PROJECTION_STATISTICS_NAME. can_inspect
+ * mirrors pg_stats_ext_exprs, which shows expression statistics only to the table owner's roles outside row security.
+ */
const projectionStatisticsSql = (n: number) => `SELECT pg_get_expr(e.stxexprs, e.stxrelid) AS expression,
e.stxrelid = 'pages'::regclass AS correct_table,
p.reltuples AS sampled_rows,
- has_table_privilege(p.oid, 'SELECT') AND NOT row_security_active(p.oid) AS can_inspect,
+ has_table_privilege(p.oid, 'SELECT') AND pg_has_role(p.relowner, 'USAGE') AND NOT row_security_active(p.oid) AS can_inspect,
x.null_frac IS NOT NULL AS collected
FROM pg_class p JOIN pg_statistic_ext e ON e.stxnamespace = p.relnamespace
LEFT JOIN pg_stats_ext_exprs x
@@ -33,7 +36,7 @@ const projectionStatisticsSql = (n: number) => `SELECT pg_get_expr(e.stxexprs, e
AND x.expr = pg_get_expr(e.stxexprs, e.stxrelid)
WHERE p.oid = 'pages'::regclass AND e.stxname = $${n}`;
-async function readProjectionStatistics(engine: Pick<BrainEngine, 'executeRaw'>): Promise<ProjectionStatisticsState> {
+export async function readProjectionStatistics(engine: Pick<BrainEngine, 'executeRaw'>): Promise<ProjectionStatisticsState> {
const rows = await engine.executeRaw<ProjectionStatisticsRow>(projectionStatisticsSql(1), [PROJECTION_STATISTICS_NAME]);
return projectionStatisticsState(rows[0]);
}
@@ -228,7 +231,8 @@ export async function canAnalyzePages(engine: Pick<BrainEngine, 'executeRaw'>):
* with rows, the statistics this refresh collects exist, and the pass changed fewer than 50 + 10% of the sampled
* pages (autovacuum's analyze threshold, as the projection-recovery debt in page-state/projections.ts). Such a pass
* barely moves them, and the refresh cost ~650 ms per one-page sync at 50k pages on Postgres and a full ANALYZE of
- * every table on PGLite.
+ * every table on PGLite. Projection statistics this role cannot inspect are no evidence of staleness, so such a pass
+ * leaves them to the owner and autovacuum.
*/
async function statisticsStillCurrent(engine: BrainEngine, changedPages: number): Promise<boolean> {
if (!Number.isFinite(changedPages)) return false;
@@ -245,7 +249,8 @@ async function statisticsStillCurrent(engine: BrainEngine, changedPages: number)
const rows = Number(state?.reltuples ?? -1);
if (!state?.columns || rows <= (engine.kind === 'pglite' ? 500 : 0) || changedPages >= 50 + 0.1 * rows) return false;
if ((await missingSearchStatistics(engine)).length > 0) return false;
- return verifyProjectionStatistics(engine).then(() => true, () => false);
+ const projection = await readProjectionStatistics(engine).catch(() => null);
+ return projection === 'collected' || projection === 'uninspectable';
}
/**
diff --git a/test/e2e/planner-stats-postgres.test.ts b/test/e2e/planner-stats-postgres.test.ts
index 829ab6fb05..23bde4f221 100644
--- a/test/e2e/planner-stats-postgres.test.ts
+++ b/test/e2e/planner-stats-postgres.test.ts
@@ -164,6 +164,28 @@ d('planner stats on Postgres', () => {
}
});
+ test('a role that does not own pages is told it cannot inspect the projection statistic, not that it is fresh (#8530)', async () => {
+ const engine = getEngine();
+ await engine.executeRaw("DO $$ BEGIN IF NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'gbrain_8530_reader') THEN CREATE ROLE gbrain_8530_reader; END IF; END $$");
+ await engine.executeRaw('GRANT USAGE ON SCHEMA public TO gbrain_8530_reader');
+ await engine.executeRaw('GRANT SELECT ON ALL TABLES IN SCHEMA public TO gbrain_8530_reader');
+ try {
+ expect((await doctor()).details?.projection_statistics).toBeUndefined();
+ const entry = DOCTOR_CHECK_REGISTRY.find(e => e.name === 'planner_stats_stale')!;
+ const check = await engine.transaction(async tx => {
+ await tx.executeRaw('SET LOCAL ROLE gbrain_8530_reader');
+ const ctx = { engine: tx, progress: { heartbeat() {}, start() {}, tick() {}, finish() {} } } as unknown as DoctorContext;
+ return ((await entry.run(ctx)) as Check[])[0]!;
+ });
+ expect(check.details?.projection_statistics).toBe('uninspectable');
+ if (check.status === 'ok') expect(check.message).toContain('cannot inspect the projection statistic');
+ } finally {
+ await engine.executeRaw('REVOKE ALL ON ALL TABLES IN SCHEMA public FROM gbrain_8530_reader');
+ await engine.executeRaw('REVOKE ALL ON SCHEMA public FROM gbrain_8530_reader');
+ await engine.executeRaw('DROP ROLE gbrain_8530_reader');
+ }
+ });
+
test('buildIndexOnline builds concurrently, prints the notice and analyzes the table', async () => {
await getEngine().executeRaw(`DROP INDEX IF EXISTS ${TITLE_INDEX.name}`);
const notices: string[] = [];
diff --git a/test/projection-statistics.test.ts b/test/projection-statistics.test.ts
index e1e8e83da8..e51c598d2e 100644
--- a/test/projection-statistics.test.ts
+++ b/test/projection-statistics.test.ts
@@ -1,8 +1,8 @@
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { afterAll, beforeAll, describe, expect, spyOn, test } from 'bun:test';
import { PGlite } from '@electric-sql/pglite';
import { currentTextProjectionFilter } from '../src/core/search/safe-chunks.ts';
import type { BrainEngine } from '../src/core/engine.ts';
-import { PROJECTION_STATISTICS_SQL, refreshProjectionStatistics, verifyProjectionStatistics } from '../src/core/search/projection-statistics.ts';
+import { missingSearchStatistics, PROJECTION_STATISTICS_SQL, refreshProjectionStatistics, verifyProjectionStatistics } from '../src/core/search/projection-statistics.ts';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
import { LATEST_VERSION, runMigrations } from '../src/core/migrate.ts';
@@ -124,6 +124,37 @@ describe('projection statistics refresh after a write pass', () => {
}, 30_000);
});
+describe('projection statistics read by a role that does not own pages (#8530)', () => {
+ test('owner-collected statistics hidden from a SELECT-only role are uninspectable, not uncollected, and a small pass stays quiet', async () => {
+ const db = new PGlite();
+ const warn = spyOn(console, 'warn').mockImplementation(() => {});
+ try {
+ const engine = { ...fixtureEngine(db), kind: 'postgres' } as BrainEngine;
+ await db.exec(`CREATE TABLE pages (id integer PRIMARY KEY, text_projection_revision uuid, knowledge_revision uuid,
+ deleted_at timestamptz, source_id text, type text, slug text, body_generation bigint);
+ INSERT INTO pages SELECT i, '00000000-0000-0000-0000-000000000001', '00000000-0000-0000-0000-000000000001',
+ NULL, 'source-a', 'note', 'page-' || i, 1 FROM generate_series(1, 1000) i;
+ CREATE STATISTICS pages_text_projection_current_stats ON ((text_projection_revision = knowledge_revision)) FROM pages;
+ ANALYZE pages;
+ CREATE ROLE app_reader;
+ GRANT SELECT ON pages TO app_reader;`);
+ await verifyProjectionStatistics(engine);
+ await db.exec('SET ROLE app_reader');
+ expect(await missingSearchStatistics(engine)).toEqual([]);
+ await expect(verifyProjectionStatistics(engine)).rejects.toThrow('cannot be inspected');
+ expect(await refreshProjectionStatistics(engine, 1)).toBe(true);
+ expect(await refreshProjectionStatistics(engine, 1)).toBe(true);
+ expect(warn).not.toHaveBeenCalled();
+ expect(await refreshProjectionStatistics(engine, 1000)).toBe(false);
+ expect(warn).toHaveBeenCalledTimes(1);
+ expect(String(warn.mock.calls[0]?.[0])).toContain('database-owner maintenance is required');
+ } finally {
+ warn.mockRestore();
+ await db.close();
+ }
+ }, 30_000);
+});
+
describe('projection statistics migration postconditions', () => {
test('empty initialization and later population both collect valid statistics', async () => {
const db = new PGlite();