Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(brainstorm): keep the slug-prefix cache out of the config table (#7838)
garrytan018e3baba19c
diff --git a/src/core/brainstorm/domain-bank.ts b/src/core/brainstorm/domain-bank.tsindex 3579038b55..e487c3dbe1 100644--- a/src/core/brainstorm/domain-bank.ts+++ b/src/core/brainstorm/domain-bank.ts@@ -23,10 +23,10 @@* fall back to LLM-invented domains — that undercuts the brain-native* thesis.*- * Prefix enumeration cached in the `config` table with 1h TTL (D3 +- * codex round 2 #7 — source-scoped). Cache miss does a full- * `SELECT DISTINCT substring(slug from '^[^/]+/[^/]+') FROM pages` (~100-500ms- * on 30K-page brains); 99%+ of brainstorm calls hit the cache.+ * Prefix enumeration cached in the process with 1h TTL (D3 + codex round 2+ * #7 — source-scoped; #7838 moved it out of the `config` table). Cache miss+ * does a full `SELECT DISTINCT substring(slug from '^[^/]+/[^/]+') FROM pages`+ * (~100-500ms on 30K-page brains), once per process and scope.** Far-page content sanitized via INJECTION_PATTERNS from `think/sanitize.ts`* — same trust boundary as takes content (v0.28.8).@@ -135,64 +135,41 @@ interface PrefixCacheEntry {cached_at: number;}-function prefixCacheKey(sourceId: string | undefined): string {- // Source-scoped per codex round 2 #7. Federated/mounted brains MUST use- // the per-source key to avoid serving prefixes from a foreign source.- return `brainstorm.domain_bank.prefixes:${sourceId ?? 'default'}`;+/**+ * Per engine and source scope, in this process (#7838). Not the `config`+ * table: every command reads that table whole, so a large brain's prefix list+ * there travelled with every call. The scope is every field enumeration+ * honors, so a federated `sourceIds` call never shares the unscoped entry.+ */+let prefixCache = new WeakMap<BrainEngine, Map<string, PrefixCacheEntry>>();++/** Test-only: forget every cached prefix list. */+export function _resetPrefixCacheForTests(): void {+ prefixCache = new WeakMap();}/**- * Read + validate the cached prefix list for `sourceId`. Returns null on- * cache miss, expired entry, parse failure, or invalid shape.+ * The prefix list for this scope, from the process cache or enumerated. A+ * miss also removes the row versions before #7838 cached in `config`.*/-async function readPrefixCache(+async function cachedPrefixes(engine: BrainEngine,- sourceId: string | undefined,+ opts: { sourceId?: string; sourceIds?: string[] },ttlMs: number-): Promise<string[] | null> {- let raw: string | null;- try {- raw = await engine.getConfig(prefixCacheKey(sourceId));- } catch {- return null;- }- if (!raw) return null;- let parsed: unknown;+): Promise<string[]> {+ const scope = JSON.stringify([opts.sourceIds ? [...opts.sourceIds].sort() : null, opts.sourceId ?? null]);+ let entries = prefixCache.get(engine);+ if (!entries) prefixCache.set(engine, entries = new Map());+ const hit = entries.get(scope);+ if (hit && Date.now() - hit.cached_at <= ttlMs) return hit.prefixes;+ const prefixes = await enumeratePrefixes(engine, opts);+ entries.set(scope, { prefixes, cached_at: Date.now() });try {- parsed = JSON.parse(raw);+ await engine.unsetConfig(`brainstorm.domain_bank.prefixes:${opts.sourceId ?? 'default'}`);} catch {- return null;- }- if (- typeof parsed !== 'object'- || parsed === null- || !Array.isArray((parsed as PrefixCacheEntry).prefixes)- || typeof (parsed as PrefixCacheEntry).cached_at !== 'number'- ) {- return null;- }- const entry = parsed as PrefixCacheEntry;- if (Date.now() - entry.cached_at > ttlMs) return null;- // Type-narrow: every entry must be a string.- for (const p of entry.prefixes) {- if (typeof p !== 'string') return null;- }- return entry.prefixes;-}--async function writePrefixCache(- engine: BrainEngine,- sourceId: string | undefined,- prefixes: string[]-): Promise<void> {- const entry: PrefixCacheEntry = { prefixes, cached_at: Date.now() };- try {- await engine.setConfig(prefixCacheKey(sourceId), JSON.stringify(entry));- } catch (err) {- // Cache-write failures are non-fatal — next call re-enumerates.- const msg = err instanceof Error ? err.message : String(err);- console.warn(`[domain-bank] prefix-cache write failed (non-fatal): ${msg}`);+ // Best effort: the old row is only dead weight in the config table.}+ return prefixes;}/**@@ -344,16 +321,7 @@ export async function fetchFar(if (opts.prefixListOverride) {allPrefixes = opts.prefixListOverride;} else {- const cached = await readPrefixCache(engine, opts.sourceId, ttlMs);- if (cached) {- allPrefixes = cached;- } else {- allPrefixes = await enumeratePrefixes(engine, {- sourceId: opts.sourceId,- sourceIds: opts.sourceIds,- });- void writePrefixCache(engine, opts.sourceId, allPrefixes);- }+ allPrefixes = await cachedPrefixes(engine, { sourceId: opts.sourceId, sourceIds: opts.sourceIds }, ttlMs);}const totalPrefixes = allPrefixes.length;diff --git a/test/brainstorm/prefix-cache-7838.test.ts b/test/brainstorm/prefix-cache-7838.test.tsnew file mode 100644index 0000000000..534d687d17--- /dev/null+++ b/test/brainstorm/prefix-cache-7838.test.ts@@ -0,0 +1,70 @@+/**+ * #7838: brainstorm's slug-prefix cache stays out of the `config` table.+ *+ * Every command reads the whole config table (loadConfigSnapshot), so a cached+ * prefix list there travelled with every `gbrain` call on a large brain. The+ * cache now lives in the process, keyed by the whole source scope (a federated+ * `sourceIds` call no longer shares the unscoped entry), and the next run+ * removes the row an older version wrote.+ */+import { afterAll, beforeAll, beforeEach, describe, expect, mock, spyOn, test } from 'bun:test';+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';+import { _resetPrefixCacheForTests, fetchFar } from '../../src/core/brainstorm/domain-bank.ts';++let engine: PGLiteEngine;+const LEGACY_KEY = 'brainstorm.domain_bank.prefixes:default';++async function seed(slug: string, sourceId = 'default'): Promise<void> {+ await engine.executeRaw(+ `INSERT INTO pages (slug, source_id, type, title, compiled_truth, timeline)+ VALUES ($1, $2, 'note', $1, 'body', '')`, [slug, sourceId]);+}++const far = (scope: { sourceId?: string; sourceIds?: string[] } = {}) =>+ fetchFar(engine, { m: 1, closeSet: [], questionEmbedding: null, ...scope });++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ await engine.executeRaw("INSERT INTO sources (id, name) VALUES ('source-a', 'source-a') ON CONFLICT DO NOTHING");+}, 60_000);+afterAll(async () => { await engine.disconnect(); });+beforeEach(async () => {+ mock.restore();+ _resetPrefixCacheForTests();+ await engine.executeRaw('DELETE FROM pages');+ await engine.executeRaw("DELETE FROM config WHERE key LIKE 'brainstorm.%'");+});++describe('brainstorm prefix cache (#7838)', () => {+ test('the prefix list is never written to the config table every command reads', async () => {+ for (let i = 0; i < 40; i++) await seed(`topic-${i}/page-example`);+ const setConfig = spyOn(engine, 'setConfig');+ expect((await far()).total_prefixes).toBe(40);+ expect(setConfig.mock.calls.map(([key]) => key).filter(key => key.startsWith('brainstorm.'))).toEqual([]);+ expect(Object.keys(await engine.getAllConfig()).filter(key => key.startsWith('brainstorm.'))).toEqual([]);+ });++ test('a second call in the same process reuses the enumeration', async () => {+ await seed('alpha/page-example');+ const executeRaw = spyOn(engine, 'executeRaw');+ await far();+ await far();+ expect(executeRaw.mock.calls.filter(([sql]) => String(sql).includes('SELECT DISTINCT substring(slug')).length).toBe(1);+ });++ test('a federated sourceIds call and an unscoped call keep separate entries', async () => {+ await seed('alpha/page-example');+ await seed('beta/page-example', 'source-a');+ expect((await far({ sourceIds: ['source-a'] })).total_prefixes).toBe(1);+ expect((await far()).total_prefixes).toBe(2);+ });++ test('the next run removes the row an older version cached in config', async () => {+ await seed('alpha/page-example');+ await engine.setConfig(LEGACY_KEY, JSON.stringify({ prefixes: ['stale/page-example'], cached_at: Date.now() }));+ expect((await far()).total_prefixes).toBe(1);+ expect(await engine.getConfig(LEGACY_KEY)).toBeNull();+ });+});diff --git a/test/helpers/config-reader-registry.ts b/test/helpers/config-reader-registry.tsindex 54eab4555f..bc2727ada7 100644--- a/test/helpers/config-reader-registry.ts+++ b/test/helpers/config-reader-registry.ts@@ -50,7 +50,6 @@ export const INTERNAL_CONFIG_STATE: readonly InternalConfigState[] = [{ key: 'trust.backfill_completed_at', reason: 'memory-trust backfill completion marker' },{ key: 'trust.kill_switch', reason: 'receipt written by gbrain trust disable/enable --all' },{ key: 'schema_pack.source.', prefix: true, reason: 'per-source schema pack binding written by gbrain schema commands' },- { key: 'brainstorm.domain_bank.prefixes:', prefix: true, reason: 'brainstorm domain-bank prefix cache' },{ key: 'backfill.', prefix: true, reason: 'resumable backfill checkpoints (backfill-base.ts checkpointKey)' },{ key: 'shared_skills.export.v1.', prefix: true, reason: 'shared-skills migration export receipts' },{ key: 'shared_skills.content.v1.', prefix: true, reason: 'shared-skills content setup state per source incarnation' },