Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

perf(search): readiness probe walks idx_pages_projection_pending instead of scanning pages (GBRA-156)

garrytan8b9787c8c0ab
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 0c8a0b7a11..a7af66d960 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,6 +10,21 @@ credits are retained; no result has been reassigned to another provider. Origina
identifiers and attribution are available in the pre-removal Git revision
`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).
+## [0.60.450.0] - 2026-10-24
+
+**Search and query answer `response.meta` about 560 ms faster on a large sealed brain when the process has no cached readiness answer (every `gbrain search` or `gbrain query` CLI call): the projection-readiness probe reads the small pending-projection index instead of every page.**
+
+### What changed
+
+| Situation | Before | Now |
+|---|---|---|
+| The readiness probe on a brain with no pending text projections | the planner, with no statistics for the revision comparison, expected most pages to be pending and scanned all of `pages` (199k buffers, ~600 ms at 600k pages) | each arm orders by `idx_pages_projection_pending`'s columns under `LIMIT 1`, so it reads only that partial index (under 1 ms) |
+
+### What to watch for after you upgrade
+
+- Answers are unchanged: the probe returns the same `ready`, `projection_pending`, `by_design` or `unknown` status, and output, defaults and notices are the same.
+- Nothing is rewritten on upgrade, and there is no schema migration (the index arrived with migration 161).
+
## [0.60.438.0] - 2026-10-24
**A source can now be marked git-canonical: each page write is committed to Git before the database records it, a write interrupted after its commit keeps the committed file, and its Git effect only pushes. The mode is off by default and nothing turns it on yet.**
diff --git a/docs/architecture/key-files/core-search-1.md b/docs/architecture/key-files/core-search-1.md
index ef57ca9199..a7c8384cf3 100644
--- a/docs/architecture/key-files/core-search-1.md
+++ b/docs/architecture/key-files/core-search-1.md
@@ -67,9 +67,9 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/search/private-visibility.ts` — shared page-visibility resolver and SQL predicates. Explicit local trust disables page filtering; operator env/config opt-outs keep their semantics; failed config reads enforce privacy. `privatePagesFilterFragment` authorizes concrete page rows and `isPrivatePage` is its row-side twin: explicit `private` hides a page, absent visibility is world for ordinary pages and private for extracted atoms (`type = 'atom'`) and synthesized concepts (`type = 'concept'` with `synthesized_by`), because their origin may be a private page or transcript. The page predicate also follows derived origins: an atom whose `source_slug` page is explicitly private, and a synthesized concept with a private input atom (or an input whose origin is private) over `concept-provenance` edges, are private whatever their own field says, so a later private flip of an origin reaches derived pages before any repair. Chronicle events follow `event.depth` (fail closed). Declared lineage matches `derived_from` slugs with `= ANY(ARRAY(...))`, not `IN (SELECT ... jsonb_array_elements_text(...))`: same rows, but the planner priced the IN form as a 100-row semi-join per page and pushed every read carrying the rule past `jit_above_cost` (`test/e2e/private-visibility-plan-postgres.test.ts`). `privateSnapshotFilterFragment` is the same rule on a row's own frontmatter for `page_versions`. `effectiveVisibility(origin)` (transcript or missing origin private, page origin per the read rule) and `strictestVisibility` are used by both `extract_atoms` paths, concept synthesis and `gbrain repair visibility`. Remote publication rechecks (`persistence/page-visibility.ts`) and the alias-inject recheck in `hybrid.ts` use the same rule. Tests: `test/private-visibility.test.ts`, `test/derived-page-visibility.test.ts` (PGLite and Postgres); link origins and timeline projections use independent ID-based predicates. `privateProvenanceFilterFragment` hides a fact whose provenance page (`source_markdown_slug`) is private; the fact-list reads in `engine-sql/facts.ts` (by entity, since, keyset, session, supersessions, trajectory) apply it behind `FactListOpts.excludePrivate` / `TrajectoryOpts.excludePrivate`, which every remote fact surface resolves with `resolveExcludePrivatePages` (`test/remote-fact-list-private-provenance.test.ts`, both engines). Remote fact writes apply the same predicate behind an `excludePrivate` option: `forget` (`guardRemoteForget`, the row lock in `persistence/memory-mutations.ts`, `recordFactWithdrawal`, `similarActiveAfterForget`) and `remember` (`decideSingleFact`'s exact and cosine arms, `decideReplacement`), so a fact remote reads hide is `not_found` to a remote write and never matched as its duplicate (`test/remote-fact-write-private-provenance.test.ts`, both engines). Legacy slug-set helpers only enumerate names; they never authorize another row's data. `ops/context.ts:readPolicyOpts` combines canonical source precedence, resolved privacy and holder permissions. Both engines filter content/history/graph/identity/analytics before limits or aggregation; current and historical visibility are checked independently while page privacy is enforced. Semantic response caching remains disabled, so visibility-key folding alone never authorizes reuse.
-- `src/core/search/projection-readiness.ts` — one statement probes visible unsealed pages: ready, projection_pending, by_design (protected/archived only) or unknown. 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-readiness.ts` — one statement probes visible unsealed pages: ready, projection_pending, by_design (protected/archived only) or unknown; LIMIT 1 arms walk the v161 pending index, not pages. 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`). 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 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/core/search/projection-readiness.ts b/src/core/search/projection-readiness.ts
index 7fe12d5513..842b363a08 100644
--- a/src/core/search/projection-readiness.ts
+++ b/src/core/search/projection-readiness.ts
@@ -86,14 +86,19 @@ async function probeUncached(
const filters = coverageScopeFilters(scope, params);
try {
// One bound statement: unsealed pages that need work, then those unsealed by design (the class fragment doctor counts).
- const unsealed = `SELECT 1 FROM pages p JOIN sources s ON s.id = p.source_id
+ // The planner has no statistics for a column-to-column comparison, so it believes most pages are unsealed and an
+ // EXISTS chose a sequential scan of pages that expected to stop at once; on a sealed brain it read every page
+ // (~600 ms at 600k pages, on every cold call). Ordering by idx_pages_projection_pending's columns under LIMIT 1
+ // makes that partial index the cheap first row, so the probe reads only the unsealed pages.
+ const unsealed = (cond: string) => `(SELECT true FROM pages p JOIN sources s ON s.id = p.source_id
WHERE p.deleted_at IS NULL
AND p.text_projection_revision IS DISTINCT FROM p.knowledge_revision
- AND ${filters.join(' AND ')}`;
+ AND ${filters.join(' AND ')} AND ${cond}
+ ORDER BY p.source_id, p.page_kind, p.slug LIMIT 1) IS NOT NULL`;
const cls = projectionClassSql('p', 's');
const rows = await engine.executeRaw<{ pending: boolean; by_design: boolean }>(
- `SELECT EXISTS (${unsealed} AND ${cls} NOT IN ('protected','archived')) AS pending,
- EXISTS (${unsealed} AND ${cls} IN ('protected','archived')) AS by_design`,
+ `SELECT ${unsealed(`${cls} NOT IN ('protected','archived')`)} AS pending,
+ ${unsealed(`${cls} IN ('protected','archived')`)} AS by_design`,
params,
);
if (typeof rows[0]?.pending !== 'boolean') throw new Error('Invalid readiness result');
diff --git a/test/e2e/projection-readiness-plan-postgres.test.ts b/test/e2e/projection-readiness-plan-postgres.test.ts
new file mode 100644
index 0000000000..c88799cfc9
--- /dev/null
+++ b/test/e2e/projection-readiness-plan-postgres.test.ts
@@ -0,0 +1,79 @@
+/**
+ * GBRA-156: the projection-readiness probe runs on every search and query and
+ * a cold CLI process cannot reuse a cached answer. The planner has no
+ * statistics for `text_projection_revision IS DISTINCT FROM knowledge_revision`,
+ * so an EXISTS over it chose a sequential scan of pages that expected to stop
+ * at the first row; on a sealed brain it read every page (~600 ms at 600k
+ * pages). Pins the plan on real Postgres with analyzed, fully sealed filler
+ * pages: the probe walks the partial idx_pages_projection_pending and no
+ * sequential scan of pages runs.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import type { BrainEngine } from '../../src/core/engine.ts';
+import { probeProjectionReadiness, type ProjectionReadinessScope } from '../../src/core/search/projection-readiness.ts';
+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';
+import { withEnv } from '../helpers/with-env.ts';
+import { hasDatabase } from './helpers.ts';
+
+const describePostgres = hasDatabase() ? describe : describe.skip;
+
+describePostgres('projection readiness probe plan on Postgres (GBRA-156)', () => {
+ let engine: BrainEngine;
+ let close: () => Promise<void>;
+
+ beforeAll(async () => {
+ ({ engine, close } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));
+ await engine.executeRaw("INSERT INTO sources(id,name) VALUES ('source-a','source-a'),('source-b','source-b') ON CONFLICT DO NOTHING");
+ await engine.executeRaw(`INSERT INTO pages(source_id,slug,title,type,page_kind,compiled_truth,chunker_version,frontmatter)
+ SELECT CASE WHEN i % 2 = 0 THEN 'source-a' ELSE 'source-b' END, 'filler-' || i, 'Filler ' || i, 'concept',
+ CASE WHEN i % 5 = 0 THEN 'code' ELSE 'markdown' END, 'filler body ' || i, 999, '{}'::jsonb
+ FROM generate_series(1, 20000) AS i`);
+ await engine.executeRaw('UPDATE pages SET text_projection_revision=knowledge_revision');
+ await engine.executeRaw('ANALYZE pages');
+ await engine.executeRaw('ANALYZE sources');
+ }, 120_000);
+
+ afterAll(async () => { await close?.(); });
+
+ async function probeStatement(scope: ProjectionReadinessScope) {
+ const captured: Array<{ sql: string; params?: unknown[] }> = [];
+ const recording = { executeRaw: (sql: string, params?: unknown[]) => {
+ captured.push({ sql, params });
+ return engine.executeRaw(sql, params);
+ } } as unknown as BrainEngine;
+ const result = await withEnv({ GBRAIN_PROJECTION_READINESS_CACHE: '0' }, () => probeProjectionReadiness(recording, scope));
+ const probe = captured.find(call => call.sql.includes('IS DISTINCT FROM'));
+ expect(probe).toBeDefined();
+ return { result, probe: probe! };
+ }
+
+ async function plan(sql: string, params?: unknown[]): Promise<string> {
+ return (await engine.executeRaw<Record<string, string>>(`EXPLAIN (ANALYZE, COSTS OFF) ${sql}`, params)).map(row => Object.values(row)[0]).join('\n');
+ }
+
+ for (const [name, scope] of [
+ ['every source', {}],
+ ['one source', { sourceId: 'source-a' }],
+ ['a source grant without private pages', { sourceIds: ['source-a', 'source-b'], excludePrivate: true }],
+ ] as Array<[string, ProjectionReadinessScope]>) {
+ test(`a sealed brain answers ready from the partial index without scanning pages (${name})`, async () => {
+ const { result, probe } = await probeStatement(scope);
+ expect(result).toEqual({ status: 'ready', ready: true });
+ const text = await plan(probe.sql, probe.params);
+ expect(text).toMatch(/Index Scan using idx_pages_projection_pending on pages p\b/);
+ // The private-visibility clause carries lazily evaluated subplans over pages; none may run.
+ expect(text.split('\n').filter(line => line.includes('Seq Scan on pages') && !line.includes('never executed'))).toEqual([]);
+ });
+ }
+
+ test('one unsealed page among the sealed filler is still found', async () => {
+ await engine.executeRaw("UPDATE pages SET text_projection_revision=NULL WHERE slug='filler-7'");
+ try {
+ expect((await probeStatement({ sourceId: 'source-b' })).result.status).toBe('projection_pending');
+ expect((await probeStatement({ sourceId: 'source-a' })).result.status).toBe('ready');
+ expect((await probeStatement({})).result.status).toBe('projection_pending');
+ } finally {
+ await engine.executeRaw("UPDATE pages SET text_projection_revision=knowledge_revision WHERE slug='filler-7'");
+ }
+ });
+});
diff --git a/test/projection-readiness.test.ts b/test/projection-readiness.test.ts
index 93bf53fa75..f1a963e173 100644
--- a/test/projection-readiness.test.ts
+++ b/test/projection-readiness.test.ts
@@ -115,7 +115,7 @@ describe('canonical projection readiness', () => {
} as any, { sourceId: "source-'quote", excludePrivate: true });
expect(result.status).toBe('projection_pending');
// Besides the probe, at most the cache's read-only generation read runs.
- const probes = calls.filter(call => call.sql.includes('SELECT EXISTS'));
+ const probes = calls.filter(call => call.sql.includes('ORDER BY p.source_id, p.page_kind, p.slug LIMIT 1'));
expect(probes).toHaveLength(1);
expect(calls.length).toBeLessThanOrEqual(2);
expect(probes[0].sql).toContain('IS DISTINCT FROM');
@@ -148,7 +148,7 @@ describe('projection readiness cache', () => {
const counted = () => {
let probes = 0;
const wrapped = { executeRaw: async (sql: string, params?: unknown[]) => {
- if (sql.includes('SELECT EXISTS')) probes++;
+ if (sql.includes('ORDER BY p.source_id, p.page_kind, p.slug LIMIT 1')) probes++;
return engine.executeRaw(sql, params);
} };
return { engine: wrapped as unknown as PGLiteEngine, probes: () => probes };
@@ -194,7 +194,7 @@ describe('projection readiness cache', () => {
test('an unknown answer is never reused, and GBRAIN_PROJECTION_READINESS_CACHE=0 always probes', async () => {
let fail = true;
const flaky = { executeRaw: async (sql: string, params?: unknown[]) => {
- if (sql.includes('SELECT EXISTS') && fail) throw new Error('transient');
+ if (sql.includes('ORDER BY p.source_id, p.page_kind, p.slug LIMIT 1') && fail) throw new Error('transient');
return engine.executeRaw(sql, params);
} } as unknown as PGLiteEngine;
expect((await probeProjectionReadiness(flaky)).status).toBe('unknown');
@@ -211,7 +211,7 @@ describe('projection readiness cache', () => {
test('nothing is cached while a transaction is in flight', async () => {
let probes = 0;
const busy = { executeRaw: async (sql: string, params?: unknown[]) => {
- if (sql.includes('SELECT EXISTS')) probes++;
+ if (sql.includes('ORDER BY p.source_id, p.page_kind, p.slug LIMIT 1')) probes++;
const rows = await engine.executeRaw<Record<string, unknown>>(sql, params);
return sql.includes('pg_current_snapshot') ? rows.map(row => ({ ...row, quiescent: false })) : rows;
} } as unknown as PGLiteEngine;