Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

search: cache projection readiness per scope under a database-visible generation

garrytan61b2b1bd6926
diff --git a/docs/architecture/key-files/core-search-1.md b/docs/architecture/key-files/core-search-1.md
index 50ddb8753c..161f2150f9 100644
--- a/docs/architecture/key-files/core-search-1.md
+++ b/docs/architecture/key-files/core-search-1.md
@@ -56,7 +56,7 @@ 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). `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. 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 scoped EXISTS probe for NULL/mismatched text revisions. Excludes hidden, archived, deleted and quarantined rows; returns ready, projection_pending or unknown without identifiers or counts. Shared by search metadata, doctor and code readiness.
+- `src/core/search/projection-readiness.ts` — one scoped EXISTS probe for NULL/mismatched text revisions. Excludes hidden, archived, deleted and quarantined rows; returns ready, projection_pending or unknown without identifiers or counts. Shared by search metadata, doctor and code readiness. A per-engine cache reuses an answer for the same normalized scope (sources, privacy, page kind, types, excluded prefixes) while the database-visible generation holds: `page_generation_clock_seq`, the `pages` relation file and every source's archived flag, read in one statement that also requires no in-flight transaction (an uncommitted page write that already advanced the clock is never cached as ready). An `unknown` answer is never cached; `GBRAIN_PROJECTION_READINESS_CACHE=0` always probes. Tests: `test/projection-readiness.test.ts`, Postgres `test/e2e/projection-readiness-currency.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 and row-security-hidden statistics. Import, sync, reindex and drained recovery refresh outside page locks; failures preserve completed writes and give a maintenance hint. Migration 161 adds the scoped pending-projection index.
diff --git a/src/core/search/projection-readiness.ts b/src/core/search/projection-readiness.ts
index d025b5a252..73cc496a38 100644
--- a/src/core/search/projection-readiness.ts
+++ b/src/core/search/projection-readiness.ts
@@ -14,9 +14,68 @@ export interface ProjectionReadiness {
hint?: string;
}
+export const PROJECTION_READINESS_CACHE_ENV = 'GBRAIN_PROJECTION_READINESS_CACHE';
+const MAX_ENTRIES_PER_ENGINE = 256;
+let readinessCache = new WeakMap<object, Map<string, { generation: string; value: ProjectionReadiness }>>();
+
+/** Test seam: forget every cached answer. */
+export function __resetProjectionReadinessCacheForTests(): void { readinessCache = new WeakMap(); }
+
+/** Every input the probe's SQL reads from the caller, normalized so equal scopes share one key. */
+function scopeKey(scope: ProjectionReadinessScope): string {
+ const sorted = (values?: string[]) => values === undefined ? null : [...new Set(values)].sort();
+ return JSON.stringify([scope.sourceId ?? null, sorted(scope.sourceIds), scope.excludePrivate === true, scope.requireSafeChunks === true,
+ scope.pageKind ?? null, sorted(scope.types), sorted(scope.excludeSlugPrefixes)]);
+}
+
+/**
+ * The database-visible generation the probe's answer depends on: the page
+ * clock (every page insert, update or delete advances it), the pages relation
+ * file (TRUNCATE replaces it) and the archived flag of every source. Null
+ * when a transaction is in flight: a page write that already advanced the
+ * clock but has not committed would otherwise be cached as ready under the
+ * clock it moved.
+ */
+async function readinessGeneration(engine: Pick<BrainEngine, 'executeRaw'>): Promise<string | null> {
+ try {
+ const [row] = await engine.executeRaw<{ generation: string | null; quiescent: boolean }>(
+ `SELECT (SELECT last_value FROM page_generation_clock_seq)::text || '/' || pg_relation_filenode('pages')::text || '/'
+ || md5(COALESCE((SELECT string_agg(id || ':' || archived::text, ',' ORDER BY id) FROM sources), '')) AS generation,
+ pg_snapshot_xmin(pg_current_snapshot()) = pg_snapshot_xmax(pg_current_snapshot()) AS quiescent`);
+ return row?.quiescent === true && typeof row.generation === 'string' ? row.generation : null;
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * Whether the current text projections cover the visible scope. A repeat
+ * call for the same scope reuses the last answer while the generation it was
+ * computed under still holds; `GBRAIN_PROJECTION_READINESS_CACHE=0` always
+ * probes. An `unknown` answer (the probe failed) is never reused.
+ */
export async function probeProjectionReadiness(
engine: Pick<BrainEngine, 'executeRaw'>,
scope: ProjectionReadinessScope = {},
+): Promise<ProjectionReadiness> {
+ if (process.env[PROJECTION_READINESS_CACHE_ENV] === '0') return probeUncached(engine, scope);
+ const generation = await readinessGeneration(engine);
+ if (generation === null) return probeUncached(engine, scope);
+ const key = scopeKey(scope);
+ let entries = readinessCache.get(engine);
+ const hit = entries?.get(key);
+ if (hit?.generation === generation) return hit.value;
+ const value = await probeUncached(engine, scope);
+ if (value.status === 'unknown') return value;
+ if (!entries) readinessCache.set(engine, entries = new Map());
+ if (entries.size >= MAX_ENTRIES_PER_ENGINE) entries.clear();
+ entries.set(key, { generation, value });
+ return value;
+}
+
+async function probeUncached(
+ engine: Pick<BrainEngine, 'executeRaw'>,
+ scope: ProjectionReadinessScope,
): Promise<ProjectionReadiness> {
const params: unknown[] = [];
const filters = [pageReadFilter('p', scope, params, true)];
diff --git a/test/projection-readiness.test.ts b/test/projection-readiness.test.ts
index 75115beaa9..7023e4d009 100644
--- a/test/projection-readiness.test.ts
+++ b/test/projection-readiness.test.ts
@@ -1,6 +1,7 @@
import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
-import { probeProjectionReadiness } from '../src/core/search/projection-readiness.ts';
+import { __resetProjectionReadinessCacheForTests, probeProjectionReadiness } from '../src/core/search/projection-readiness.ts';
+import { withEnv } from './helpers/with-env.ts';
import { checkProjectionReadiness } from '../src/commands/doctor/checks/projection-readiness.ts';
import { resetPgliteState } from './helpers/reset-pglite.ts';
@@ -113,12 +114,14 @@ describe('canonical projection readiness', () => {
},
} as any, { sourceId: "source-'quote", excludePrivate: true });
expect(result.status).toBe('projection_pending');
- expect(calls).toHaveLength(1);
- expect(calls[0].sql).toContain('SELECT EXISTS');
- expect(calls[0].sql).toContain('IS DISTINCT FROM');
- expect(calls[0].sql).not.toMatch(/COUNT\(|UPDATE |INSERT |DELETE /);
- expect(calls[0].sql).not.toContain("source-'quote");
- expect(calls[0].params).toEqual(["source-'quote"]);
+ // Besides the probe, at most the cache's read-only generation read runs.
+ const probes = calls.filter(call => call.sql.includes('SELECT EXISTS'));
+ expect(probes).toHaveLength(1);
+ expect(calls.length).toBeLessThanOrEqual(2);
+ expect(probes[0].sql).toContain('IS DISTINCT FROM');
+ for (const call of calls) expect(call.sql).not.toMatch(/COUNT\(|UPDATE |INSERT |DELETE /);
+ expect(probes[0].sql).not.toContain("source-'quote");
+ expect(probes[0].params).toEqual(["source-'quote"]);
});
test('doctor distinguishes ready, pending and unknown without returning identifiers', async () => {
@@ -134,3 +137,85 @@ describe('canonical projection readiness', () => {
expect(JSON.stringify(unknown)).not.toContain('private connection');
});
});
+
+/**
+ * The readiness cache (Foundations 2, Lane F): a repeat search reuses the
+ * last answer for the same normalized scope while the database-visible
+ * generation (page clock, pages relation file, source archive flags) holds.
+ */
+describe('projection readiness cache', () => {
+ const counted = () => {
+ let probes = 0;
+ const wrapped = { executeRaw: async (sql: string, params?: unknown[]) => {
+ if (sql.includes('SELECT EXISTS')) probes++;
+ return engine.executeRaw(sql, params);
+ } };
+ return { engine: wrapped as unknown as PGLiteEngine, probes: () => probes };
+ };
+ beforeEach(() => { __resetProjectionReadinessCacheForTests(); });
+
+ test('a repeat call for an equal scope reuses the answer; a page write invalidates it', async () => {
+ await seed('markdown', 'source-a', 'current');
+ await engine.executeRaw('UPDATE pages SET text_projection_revision=knowledge_revision');
+ const c = counted();
+ expect((await probeProjectionReadiness(c.engine, { sourceIds: ['source-b', 'source-a'], types: ['concept'] })).status).toBe('ready');
+ expect((await probeProjectionReadiness(c.engine, { sourceIds: ['source-a', 'source-b', 'source-a'], types: ['concept'] })).status).toBe('ready');
+ expect(c.probes()).toBe(1);
+ await seed('markdown', 'source-a', 'pending');
+ expect((await probeProjectionReadiness(c.engine, { sourceIds: ['source-a', 'source-b'], types: ['concept'] })).status).toBe('projection_pending');
+ expect(c.probes()).toBe(2);
+ await engine.executeRaw('UPDATE pages SET text_projection_revision=knowledge_revision');
+ expect((await probeProjectionReadiness(c.engine, { sourceIds: ['source-a', 'source-b'], types: ['concept'] })).status).toBe('ready');
+ expect(c.probes()).toBe(3);
+ });
+
+ test('every scope input is part of the key', async () => {
+ await seed('code', 'source-a', 'excluded/pending', { visibility: 'private' });
+ const c = counted();
+ const scopes = [{}, { sourceId: 'source-a' }, { sourceIds: ['source-b'] }, { excludePrivate: true }, { pageKind: 'markdown' },
+ { types: ['person'] }, { excludeSlugPrefixes: ['excluded/'] }];
+ const statuses = [];
+ for (const scope of scopes) statuses.push((await probeProjectionReadiness(c.engine, scope)).status);
+ expect(statuses).toEqual(['projection_pending', 'projection_pending', 'ready', 'ready', 'ready', 'ready', 'ready']);
+ expect(c.probes()).toBe(scopes.length);
+ });
+
+ test('restoring an archived source with pending pages invalidates a cached ready', async () => {
+ await seed('markdown', 'source-b', 'pending');
+ await engine.executeRaw("UPDATE sources SET archived=true WHERE id='source-b'");
+ const c = counted();
+ expect((await probeProjectionReadiness(c.engine)).status).toBe('ready');
+ await engine.executeRaw("UPDATE sources SET archived=false WHERE id='source-b'");
+ expect((await probeProjectionReadiness(c.engine)).status).toBe('projection_pending');
+ expect(c.probes()).toBe(2);
+ });
+
+ 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');
+ return engine.executeRaw(sql, params);
+ } } as unknown as PGLiteEngine;
+ expect((await probeProjectionReadiness(flaky)).status).toBe('unknown');
+ fail = false;
+ expect((await probeProjectionReadiness(flaky)).status).toBe('ready');
+ const c = counted();
+ await withEnv({ GBRAIN_PROJECTION_READINESS_CACHE: '0' }, async () => {
+ await probeProjectionReadiness(c.engine);
+ await probeProjectionReadiness(c.engine);
+ });
+ expect(c.probes()).toBe(2);
+ });
+
+ 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++;
+ 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;
+ await probeProjectionReadiness(busy);
+ await probeProjectionReadiness(busy);
+ expect(probes).toBe(2);
+ });
+});