Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(purge): follow the facts vector shape, recreate atomically, vacuum only present tables; Postgres arm; docs and CHANGELOG (#6911)
garrytan7984b5963a46
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 40de796552..b85af374c7 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,6 +10,24 @@ credits are retained; no result has been reassigned to another provider. Originaidentifiers and attribution are available in the pre-removal Git revision`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).+## [Unreleased] - 2026-10-17++**A brain that lost its `query_cache` table can finish its nightly purge again.** On a brain where `query_cache` was missing although the schema was at head, every coordinated page purge failed with `42P01`, so the dream cycle's purge phase failed every night with `managed_purge_failed` and the tombstone was never purged (#6911). `apply-migrations` and `db-repair` both reported healthy, because the schema version said the table's migration had run.++### What changed++| Situation | Before | Now |+|---|---|---|+| Page purge or fact purge with `query_cache` missing | failed with `42P01` every time (`managed_purge_failed`) | commits; the receipt lists `purge.missing_caches` and shows `query_cache` as `not_present` with reason `table_missing` |+| Purge with a missing table that holds user data | failed | still fails, because the purge cannot say it removed rows it could not reach |+| `gbrain doctor` on a brain at head with a missing table | nothing flagged it | `schema_missing_tables`: warn for a rebuildable cache, fail for a user-data table |+| Getting the cache back | run the old migration handler by hand | `gbrain repair missing-tables` previews, then `--apply --expect <hash>` recreates it empty in the shape a fully migrated brain has |+| `gbrain forget --purge --vacuum` on PGLite with the cache missing | the VACUUM failed silently, so nothing was vacuumed | the other tables are vacuumed |++### What you need to do++Nothing, unless doctor reports `schema_missing_tables`. Then ask your agent: *"Doctor says query_cache is missing. Fix it."* It runs `gbrain repair missing-tables`, shows you the preview, and applies it after you agree. The repair runs only when named; nothing changes on upgrade. A missing table that holds user data is never recreated empty: restore it from a backup.+## [0.60.289.0] - 2026-10-17**The unit test matrix runs 10 shards instead of 8, so one slow CI runner no longer turns master red.** Master run 39030803745 lost `test (2)` to the 22-minute job timeout. The tests were fine: CPU steal on that runner was 2–3x the usual and every file ran about 1.5x slower. At 8 shards each shard carried about 908s of measured test time, so a normal job took about 16.5 minutes and a 1.5x slower runner overran the timeout. At 10 shards each carries about 727s.diff --git a/src/core/facts/purge-verify.ts b/src/core/facts/purge-verify.tsindex 988be110d1..1490d08b2f 100644--- a/src/core/facts/purge-verify.ts+++ b/src/core/facts/purge-verify.ts@@ -425,7 +425,10 @@ export async function verifyFactPurge(engine: BrainEngine, input: { target: Purgif (Number(other?.n ?? 0)) residuals.push({ store: 'facts_other_scope', status: 'out_of_scope', reason: plan.subject === '*' ? 'other_visibility' : 'other_subject', remaining: Number(other.n),detail: `${other.n} fact row(s) state the same claim about another entity or at another visibility; rerun with --all-subjects to purge every entity's copy.` });residuals.push(...stores.filter(s => s.reason === 'source_prose' || s.reason === 'probed_reported' || s.store === 'canonical_markdown' && s.status === 'out_of_scope'));- if (input.vacuum && !dryRun && engine.kind === 'pglite') await engine.executeRaw('VACUUM facts, takes, pages, content_chunks, page_versions, persistence_requests, query_cache').catch(() => undefined);+ if (input.vacuum && !dryRun && engine.kind === 'pglite') {+ const tables = ['facts', 'takes', 'pages', 'content_chunks', 'page_versions', 'persistence_requests', ...(await relationExists(engine, 'query_cache') ? ['query_cache'] : [])];+ await engine.executeRaw(`VACUUM ${tables.join(', ')}`).catch(() => undefined);+ }const next = dryRun? ['Review the residuals with the user, then confirm with the token printed above (gbrain forget <id> --purge asks for it on a terminal).']: ['Poll completion with gbrain forget --purge --status --request-id <request_id> until it reports complete.'];diff --git a/src/core/repair/missing-tables.ts b/src/core/repair/missing-tables.tsindex a8b129c4a0..82a90cfda6 100644--- a/src/core/repair/missing-tables.ts+++ b/src/core/repair/missing-tables.ts@@ -46,13 +46,14 @@ export const missingTablesRepair: RepairHandler = {async apply(ctx, item) {const recreate = RECREATE[item.slug];if (!recreate) return { applied: false, outcome: 'refused', reason: 'not_rebuildable' };- if (await relationExists(ctx.engine, item.slug)) return { applied: false, outcome: 'already_present' };- await recreate(ctx.engine);+ const existed = await relationExists(ctx.engine, item.slug);+ // Every statement is IF NOT EXISTS and runs in one transaction, so a rerun finishes a table an interrupted run left without its later columns.+ await ctx.engine.transaction(tx => recreate(tx));if (!await relationExists(ctx.engine, item.slug)) {throw new OperationError('storage_error', `Recreating ${item.slug} ran, but the table still does not exist.`,'Run gbrain doctor --json and report the schema_missing_tables entry.');}- return { applied: true, outcome: 'recreated' };+ return { applied: true, outcome: existed ? 'completed' : 'recreated' };},render(details) {const d = details as { checked?: number; recreate?: string[]; user_data_tables?: string[] };diff --git a/src/core/schema-missing-tables.ts b/src/core/schema-missing-tables.tsindex 4089eb01bd..665b4d66eb 100644--- a/src/core/schema-missing-tables.ts+++ b/src/core/schema-missing-tables.ts@@ -13,6 +13,7 @@ import { isRebuildableCache } from './persistence/rebuildable-cache.ts';import { v055 } from './schema-migrations/v055-query-cache-search-lite.ts';import { v056 } from './schema-migrations/v056-query-cache-knobs-hash.ts';import { v059 } from './schema-migrations/v059-code-traversal-cache-v0-34.ts';+import { hnswIndexExpected, readExistingEmbeddingShape } from './vector-index.ts';export interface MissingTable {table: string;@@ -33,7 +34,11 @@ export type MissingTablesReport = { status: 'checked'; checked: number; missing:*/export const RECREATE: Readonly<Record<string, (engine: BrainEngine) => Promise<void>>> = {query_cache: async engine => {- await v055.handler!(engine);+ // v055 sizes the column from config; an embedding migration since then resized facts and query_cache together, so+ // the live facts column is the shape a never-dropped query_cache would have.+ const shape = await readExistingEmbeddingShape(engine, 'facts');+ if (shape) await engine.runMigration(55, queryCacheDdl(shape.type, shape.dimensions));+ else await v055.handler!(engine);await engine.runMigration(56, v056.sql);await engine.runMigration(90, "ALTER TABLE query_cache ADD COLUMN IF NOT EXISTS page_generations JSONB NOT NULL DEFAULT '{}'::jsonb;");await engine.runMigration(91, 'ALTER TABLE query_cache ADD COLUMN IF NOT EXISTS max_generation_at_store BIGINT NOT NULL DEFAULT 0;');@@ -41,6 +46,19 @@ export const RECREATE: Readonly<Record<string, (engine: BrainEngine) => Promise<code_traversal_cache: async engine => { await engine.runMigration(59, v059.sql); },};+/** v055's DDL for a known vector shape (the table, its source index and, when pgvector can build one, its HNSW index). */+function queryCacheDdl(type: 'vector' | 'halfvec', dims: number): string {+ const hnsw = hnswIndexExpected(type, dims)+ ? `CREATE INDEX IF NOT EXISTS idx_query_cache_embedding_hnsw ON query_cache USING hnsw (embedding ${type === 'halfvec' ? 'halfvec_cosine_ops' : 'vector_cosine_ops'}) WHERE embedding IS NOT NULL;`+ : '';+ return `CREATE TABLE IF NOT EXISTS query_cache (+ id TEXT PRIMARY KEY, query_text TEXT NOT NULL, source_id TEXT NOT NULL DEFAULT 'default', embedding ${type.toUpperCase()}(${dims}),+ results JSONB NOT NULL DEFAULT '[]'::jsonb, meta JSONB NOT NULL DEFAULT '{}'::jsonb, ttl_seconds INTEGER NOT NULL DEFAULT 3600,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(), hit_count INTEGER NOT NULL DEFAULT 0, last_hit_at TIMESTAMPTZ);+ CREATE INDEX IF NOT EXISTS idx_query_cache_source_created ON query_cache(source_id, created_at DESC);+ ${hnsw}`;+}+export async function readMissingTables(engine: BrainEngine): Promise<MissingTablesReport> {const version = parseInt((await engine.getConfig('version')) || '0', 10);if (version !== LATEST_VERSION) return { status: 'skipped', reason: 'schema_not_at_head', version, latest: LATEST_VERSION };diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txtindex 03c60ad72f..23041cc3f6 100644--- a/test/postgres-unit-arms.txt+++ b/test/postgres-unit-arms.txt@@ -177,6 +177,7 @@ test/persistence-writer-fences.test.tstest/physical-root-birth-tolerance-6501.test.tstest/purge-fact.test.tstest/purge-global-marker.test.ts+test/purge-missing-cache-6911.test.tstest/purge-read-surfaces.test.tstest/recall-page-fill.test.tstest/remediation-manual-only.test.tsdiff --git a/test/purge-missing-cache-6911.test.ts b/test/purge-missing-cache-6911.test.tsindex dbd24e4f41..ba0ef6441f 100644--- a/test/purge-missing-cache-6911.test.ts+++ b/test/purge-missing-cache-6911.test.ts@@ -121,6 +121,20 @@ describe('#6911 missing query_cache', () => {}}), 120_000);+ test('a recreated query_cache takes the live facts vector shape, not the config default', async () => withEnv({ GBRAIN_HOME: home }, async () => {+ for (const engine of engines) {+ await engine.executeRaw('DROP TABLE query_cache');+ await engine.executeRaw('DROP INDEX IF EXISTS idx_facts_embedding_hnsw');+ await engine.executeRaw('ALTER TABLE facts ALTER COLUMN embedding TYPE halfvec(768) USING NULL');+ const scope = await resolveRepairScope(engine);+ const preview = await runRepair(ctx(engine), missingTablesRepair, scope, { apply: false, explicit: true });+ await runRepair(ctx(engine), missingTablesRepair, scope, { apply: true, explicit: true, expect: preview.preview_hash });+ const [column] = await engine.executeRaw<{ type: string; dims: number }>(`SELECT t.typname AS type, a.atttypmod AS dims FROM pg_attribute a+ JOIN pg_type t ON t.oid=a.atttypid WHERE a.attrelid=to_regclass('query_cache') AND a.attname='embedding'`);+ expect(column).toEqual({ type: 'halfvec', dims: 768 });+ }+ }), 120_000);+test('the repair is explicit-only and a missing user-data table still fails the purge loudly', async () => withEnv({ GBRAIN_HOME: home }, async () => {for (const engine of engines) {const scope = await resolveRepairScope(engine);