Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(purge): tolerate a missing rebuildable cache; doctor schema_missing_tables; repair missing-tables (#6911)

garrytan12d4a5e5c2ad
diff --git a/docs/guides/repair.md b/docs/guides/repair.md
index 99ac68e2e9..fc9062e40b 100644
--- a/docs/guides/repair.md
+++ b/docs/guides/repair.md
@@ -149,6 +149,7 @@ work behind exits 0, so scripts should also check `results[].complete`.
| `aliases` | `dangling_aliases` (orphaned rows) | Explicit-only. Deletes free-text page aliases and slug redirects whose target page has no row at all (a page purged before purge removed its aliases, #6619, or a hard-deleted page), each target rechecked under its page lock; a coordinated maintenance write on a managed brain. A redirect from an old name of a page that still exists is never touched. See [aliases](#aliases). | `soft_deleted_target`: aliases of a soft-deleted page, kept for `gbrain restore` and removed when the page is purged. |
| `rename-identity` | `rename_identity_downgrades` | Explicit-only, preview-bound, destructive consent. For an inexact Git rename that sync split into a delete plus an add (#6729): carries the old page's identity (id, version history, timeline, links, facts, aliases) onto the new slug, imports the new file onto it as an edit and retires the provisional page; or, with `--close`, settles the pair and moves nothing. `--slug <new-slug>` (and `--from <old-slug>`) names one pair; `--apply --expect <hash> --yes`. See [rename identity](#rename-identity). | `fact_rows_collide` (a fence row of the old page the new file does not keep with the same claim); `managed_remedy_unavailable` (a carry on a managed source; `--close` is the remedy there); pages changed after the preview (`changed_since_preview`). |
| `overwritten-edits` | `sync_overwritten_db_edits` | Explicit-only, preview-bound. Restores database edits that an incremental managed sync replaced with a committed file edit and no `file_drift` hold (#6712, fixed by #6887). It restores only what the records prove: a database-only revision (its receipt published no file) archived by a managed-sync import that wrote different content, with no later revision holding the edit again. The preview diffs the live page against the edit; `--apply --expect <hash>` reverts each page to that version through a revision-bound, database-only `revert_version` and holds the committed file `file_drift` when it differs. See [overwritten edits](#overwritten-edits). | `unknown_*` findings (no persistence outcome on the writer's receipt, the import's content no longer readable, a segmented version), listed but not restored; pages that moved after the preview (`changed_since_preview`). |
+| `missing-tables` | `schema_missing_tables` | Explicit-only, preview-bound. Recreates, empty, a rebuildable cache table (`query_cache`, `code_traversal_cache`) that the applied migrations created but the brain no longer has, on a brain whose schema version is already current, so `apply-migrations` never recreates it (#6911). DDL only (`IF NOT EXISTS`), no journal admission, brain-wide. See [missing tables](#missing-tables). | `user_data_tables`: a missing table that holds user data; it is never recreated empty. |
Timeline rows that an earlier version of a page produced and its current text
no longer has are removals, not history, so `timeline` neither counts nor
@@ -248,6 +249,43 @@ missing or INVALID; otherwise compare the elapsed time with
**Say to your agent:** *"Dream keeps saying postprocessing deferred. What's wrong?"*
+<a id="missing-tables"></a>
+### Missing tables
+
+The schema version records which migrations ran, not which tables still
+exist. A table dropped after its migration ran (by hand, by a restore that
+skipped it, or by a pooler that swallowed the DDL) stays missing:
+`gbrain apply-migrations` sees nothing to do and `gbrain db-repair` checks the
+connection, not the tables. When that table is `query_cache`, every
+coordinated page purge used to fail with `42P01`, so the dream cycle's purge
+phase failed every night with `managed_purge_failed` (#6911).
+
+The purge now skips a missing rebuildable cache (`query_cache`,
+`code_traversal_cache`): there is nothing in it a rebuild cannot regenerate.
+The purge receipt lists it under `purge.missing_caches`, and the store report
+shows `query_cache` as `not_present` with reason `table_missing`. A missing
+table that holds user data (facts, takes, notices and the like) still fails the
+purge, because the purge cannot honestly say it removed rows from it.
+
+`gbrain doctor` reports `schema_missing_tables` when the schema is at head and
+a table it should have is missing: a warning for a rebuildable cache, a failure
+for a table that holds user data. The expected set is every table a fully
+migrated brain has on this engine.
+
+**Say to your agent:** *"Doctor says query_cache is missing. Fix it."*
+
+```bash
+gbrain repair missing-tables # read-only: the tables it would recreate empty, and a hash
+gbrain repair missing-tables --apply --expect <preview-hash>
+```
+
+The apply recreates each previewed cache table empty, in the shape a fully
+migrated brain has, then checks it exists. A table created since the preview
+is skipped as `already_present`. The cache refills as searches run. Missing
+user-data tables are listed under `user_data_tables` and never recreated:
+restore them from a backup. The repair runs only when named and never on
+upgrade, `apply-migrations`, `db-repair` or the maintenance cycle.
+
<a id="request-growth"></a>
### Request-table growth
@@ -2553,7 +2591,7 @@ Each heading below is the `docs` anchor a refusal carries.
### Explicit-only repair kinds
`google-file-modes`, `stale-atoms`, `extractor-facts`, `captured-facts`,
-`loop-facts`, `ontology-facts` and `file-drift` run only when named: `gbrain repair <kind>` previews, and
+`loop-facts`, `ontology-facts`, `file-drift` and `missing-tables` run only when named: `gbrain repair <kind>` previews, and
`gbrain repair <kind> --apply` applies (every kind but `google-file-modes`
also needs `--expect <hash>`, so it applies exactly the previewed set; `google-file-modes` re-checks each file's owner,
type and mode at apply time). They are excluded everywhere else:
diff --git a/src/commands/doctor/checks/schema-health.ts b/src/commands/doctor/checks/schema-health.ts
index c27ba2d1c6..4dcdd1addd 100644
--- a/src/commands/doctor/checks/schema-health.ts
+++ b/src/commands/doctor/checks/schema-health.ts
@@ -26,7 +26,10 @@ import type { BrainEngine } from '../../../core/engine.ts';
import { connectedEngine, type DoctorContext, type DoctorEntry, doctorHealth } from '../context.ts';
import { embeddingsDisabled } from '../../../core/embedding-disabled.ts';
import { quoteIdentifier, resolveActiveEmbeddingColumnFromEngine } from '../../../core/search/embedding-column.ts';
-import { checkError, infoCheck, keylessEnablementFix } from '../check-fix.ts';
+import { agentFix, checkError, infoCheck, keylessEnablementFix } from '../check-fix.ts';
+import type { MissingTable, MissingTablesReport } from '../../../core/schema-missing-tables.ts';
+
+const MISSING_TABLES_DOCS = 'docs/guides/repair.md#missing-tables';
async function runPgvector(ctx: DoctorContext): Promise<Check[]> {
const { progress } = ctx;
@@ -251,6 +254,14 @@ async function runSchemaVersion(ctx: DoctorContext): Promise<Check[]> {
} catch {
checks.push(checkError('schema_columns', 'verify live schema columns'));
}
+ // 6c. #6911: tables the applied migrations created that the brain no longer has (the ledger cannot see a drop).
+ progress.heartbeat('schema_missing_tables');
+ try {
+ const { readMissingTables } = await import('../../../core/schema-missing-tables.ts');
+ checks.push({ name: 'schema_missing_tables', ...missingTablesFields(await readMissingTables(engine)) });
+ } catch (error) {
+ checks.push(checkError('schema_missing_tables', 'check for tables the applied migrations created', error));
+ }
}
} catch {
checks.push(checkError('schema_version', 'check schema version'));
@@ -259,9 +270,26 @@ async function runSchemaVersion(ctx: DoctorContext): Promise<Check[]> {
return checks;
}
+/** #6911: the schema_missing_tables verdict; a missing user-data table fails, a missing rebuildable cache warns. */
+function missingTablesFields(report: MissingTablesReport): Omit<Check, 'name'> {
+ if (report.status === 'skipped') return { status: 'ok', message: `Skipped: schema v${report.version} is not at head v${report.latest} (schema_version covers it).` };
+ if (!report.missing.length) return { status: 'ok', message: `All ${report.checked} table(s) the applied migrations create exist.` };
+ const recreatable = report.missing.filter(m => m.recreatable), kept = report.missing.filter(m => !m.recreatable);
+ const details = { missing: report.missing, checked: report.checked, docs: MISSING_TABLES_DOCS };
+ const names = (list: MissingTable[]) => list.map(m => m.table).join(', ');
+ const message = `${report.missing.length} table(s) the applied migrations create are missing although schema_version is at head, so apply-migrations will not recreate them`
+ + (recreatable.length ? `. Rebuildable cache(s) ${names(recreatable)}: preview recreating them empty with gbrain repair missing-tables, then apply the printed command after the user agrees.` : '')
+ + (kept.length ? `. ${names(kept)} hold user data and are never recreated empty: restore them from a backup (see ${MISSING_TABLES_DOCS}).` : '.');
+ return { status: kept.length ? 'fail' : 'warn', message, details,
+ ...(recreatable.length
+ ? { fix: agentFix(['gbrain', 'repair', 'missing-tables', '--json'], 'Read-only preview: lists each rebuildable cache table it would recreate empty and prints the apply command with its hash. Apply only after the user agrees.',
+ 'schema_missing_tables', { docs: MISSING_TABLES_DOCS }) }
+ : { fix_unavailable_reason: 'operator_judgement' as const }) };
+}
+
export const schemaVersionEntry: DoctorEntry = {
name: 'schema_version',
- emits: ['schema_version', 'schema_columns'],
+ emits: ['schema_version', 'schema_columns', 'schema_missing_tables'],
run: runSchemaVersion,
};
diff --git a/src/core/doctor-categories.ts b/src/core/doctor-categories.ts
index ee146ca92a..378e35ebce 100644
--- a/src/core/doctor-categories.ts
+++ b/src/core/doctor-categories.ts
@@ -390,6 +390,8 @@ export const META_CHECK_NAMES: ReadonlySet<string> = new Set([
// #5216: the resumable pages.knowledge_revision backfill (resumed by apply-migrations --force-schema).
'revision_backfill',
'schema_columns',
+ // #6911: tables the applied migrations created that are missing (repair missing-tables recreates rebuildable caches).
+ 'schema_missing_tables',
'schema_pack_active',
'schema_pack_consistency',
'schema_pack_source_drift',
diff --git a/src/core/facts/purge-verify.ts b/src/core/facts/purge-verify.ts
index a20d62f598..988be110d1 100644
--- a/src/core/facts/purge-verify.ts
+++ b/src/core/facts/purge-verify.ts
@@ -28,6 +28,7 @@ import type { PurgePlan, PurgeTarget } from './purge.ts';
import { gitChildEnv } from '../git-env.ts';
import { claimForms, quotes, type LedgerPurgeReport } from '../belief/purge.ts';
import { CARRYING_FIELDS } from '../belief/keys.ts';
+import { isRebuildableCache, relationExists } from '../persistence/rebuildable-cache.ts';
export type StoreCount = Record<string, number>;
export type StoreStatus = 'deleted' | 'would_remove' | 'retained_inactive' | 'unverified' | 'out_of_reach' | 'out_of_scope' | 'not_present' | 'incomplete';
@@ -80,6 +81,10 @@ async function unprobedSegmentedPages(engine: BrainEngine, sourceId: string, rep
type ProbeResult = { count: number } | { unverified: string };
+/** #6911: a rebuildable cache table that does not exist holds nothing to verify. */
+const missingCache = (store: string): StoreReport => ({ store, status: 'not_present', removed: 0, reason: 'table_missing',
+ detail: `The ${store} table does not exist on this brain; it is a rebuildable cache, so there was nothing to clear. gbrain doctor reports it under schema_missing_tables.` });
+
/** One bounded probe: `sql` selects matching rows (no LIMIT); the adapter caps rows and the statement time. */
async function boundedCount(engine: BrainEngine, sql: string, params: unknown[], deadline: number): Promise<ProbeResult> {
if (performance.now() > deadline) return { unverified: 'verification_deadline' };
@@ -257,6 +262,7 @@ async function sweptInventoryReports(engine: BrainEngine, reported: ReadonlySet<
if (entry.class !== 'swept' || reported.has(entry.table)) continue;
const planned = removed[entry.table] ?? 0;
if (dryRun) { reports.push({ store: entry.table, status: planned ? 'would_remove' : 'not_present', removed: planned }); continue; }
+ if (isRebuildableCache(entry.table) && !await relationExists(engine, entry.table)) { reports.push(missingCache(entry.table)); continue; }
const result = await probeTable(engine, entry, sourceId, needles, deadline);
if ('unverified' in result) reports.push({ store: entry.table, status: 'unverified', reason: result.unverified, removed: planned });
else if (result.count) reports.push({ store: entry.table, status: 'incomplete', remaining: result.count, removed: planned });
@@ -378,7 +384,8 @@ export async function verifyFactPurge(engine: BrainEngine, input: { target: Purg
await swept('persistence_requests', `SELECT 1 FROM persistence_requests WHERE source_id=$1 AND (${['intent', 'outcome', 'error_detail', 'error_message']
.map(c => `strpos(lower(COALESCE(${c}::text,'')),$2)>0 OR strpos(lower(COALESCE(${c}::text,'')),$3)>0`).join(' OR ')})`,
[src, needle, JSON.stringify(claim).slice(1, -1).toLowerCase()], plan.requests.length, removed.persistence_requests);
- await swept('query_cache', 'SELECT 1 FROM query_cache WHERE $1::text IS NOT NULL', [src], 0, removed.query_cache);
+ if (!dryRun && !await relationExists(engine, 'query_cache')) stores.push(missingCache('query_cache'));
+ else await swept('query_cache', 'SELECT 1 FROM query_cache WHERE $1::text IS NOT NULL', [src], 0, removed.query_cache);
const refs = plan.factIds.map(String);
for (const table of ['decide_review_queue', 'decide_review_proposals'] as const) {
await swept(table, `SELECT 1 FROM ${table} WHERE source_id=$1 AND (a_ref=ANY($2::text[]) OR b_ref=ANY($2::text[]))`, [src, refs], plan.review[table], plan.review[table]);
@@ -465,7 +472,8 @@ export async function verifyPagePurge(engine: BrainEngine, input: { sourceId: st
await keyed('slug_aliases', 'SELECT 1 FROM slug_aliases WHERE source_id=$1 AND canonical_slug=$2', [src, slug]);
await keyed('files', 'SELECT 1 FROM files WHERE page_slug=$2 AND (source_id=$1 OR source_id IS NULL)', [src, slug]);
await keyed('write_gate_holds', 'SELECT 1 FROM write_gate_holds WHERE source_id=$1 AND slug=$2', [src, slug]);
- await keyed('query_cache', 'SELECT 1 FROM query_cache WHERE $1::text IS NOT NULL', [src]);
+ if (!await relationExists(engine, 'query_cache')) stores.push(missingCache('query_cache'));
+ else await keyed('query_cache', 'SELECT 1 FROM query_cache WHERE $1::text IS NOT NULL', [src]);
if (context) {
const refs = context.factIds.map(String);
for (const table of ['decide_review_queue', 'decide_review_proposals']) await keyed(table, `SELECT 1 FROM ${table} WHERE source_id=$1 AND (a_ref=ANY($2::text[]) OR b_ref=ANY($2::text[]))`, [src, refs]);
diff --git a/src/core/facts/purge.ts b/src/core/facts/purge.ts
index 12762e33e0..e90a156e88 100644
--- a/src/core/facts/purge.ts
+++ b/src/core/facts/purge.ts
@@ -48,6 +48,7 @@ import { noteBelief, withBeliefBatch } from '../belief/ledger.ts';
import { markBeliefCommits } from '../belief/append.ts';
import { appendPurgeCommitted, appendPurgeIntent } from '../belief/purge-mirror.ts';
import { createPageVersion } from '../page-state/versions.ts';
+import { clearRebuildableCache } from '../persistence/rebuildable-cache.ts';
import { appendDerivedHidden, bumpPurgeEpoch, derivedBeliefTargets, derivedStreamSlugs, redactCarryingFields, redactPurgedKeys, registerLiveCarriers, registerVersionCarriers, sourceHasBeliefEvents,
type LedgerPurgeReport } from '../belief/purge.ts';
@@ -379,7 +380,7 @@ export async function submitPurgeFactMutation(ctx: OperationContext, params: Rec
const chunks = pageIds.length ? (await tx.executeRaw('DELETE FROM content_chunks WHERE page_id=ANY($1::integer[]) RETURNING 1', [pageIds])).length : 0;
const versions = await redactPageVersions(tx, p.sourceId, current.fact, pageIds);
prose = versions.prose;
- const cache = (await tx.executeRaw('DELETE FROM query_cache RETURNING 1')).length;
+ const cache = await clearRebuildableCache(tx, 'query_cache', 'DELETE FROM query_cache RETURNING 1', [], []);
const pages = pageIds.length ? await tx.executeRaw<{ id: number; slug: string; knowledge_revision: string }>(
'SELECT id,slug,knowledge_revision::text AS knowledge_revision FROM pages WHERE source_id=$1 AND id=ANY($2::int[]) ORDER BY slug', [p.sourceId, pageIds]) : [];
await tx.executeRaw(`INSERT INTO persistence_effects(request_id,kind,data,source_id,source_incarnation,worktree_id)
diff --git a/src/core/persistence/page-purge.ts b/src/core/persistence/page-purge.ts
index 97d7863051..f7c75b73a5 100644
--- a/src/core/persistence/page-purge.ts
+++ b/src/core/persistence/page-purge.ts
@@ -42,6 +42,7 @@ import { enterClaimStep, type ClaimPhaseClock } from './claim-phase.ts';
import { PERSISTENCE_REQUEST_SLUG_INTENT_INDEX } from './schema.ts';
import { readRequestIndexStates, REQUEST_INDEXES_REPAIR_COMMAND, type RequestIndexState } from './checkpoint-validation.ts';
import { faultPoint } from './fault-points.ts';
+import { clearRebuildableCache } from './rebuildable-cache.ts';
import { carryingNeedles, findRequestsForSlugs, JOURNAL_SWEEP_MATCH_CAP, recheckRequestsCarrying, redactRequestIntents, sweepRequestsCarrying, sweepRequestsForGroups,
type JournalSweep } from './intent-redaction.ts';
import { dropPurgedFenceRows } from '../facts/purge-overlay.ts';
@@ -280,7 +281,8 @@ export async function purgePageInTransaction(tx: BrainEngine, row: WriteRequest,
removed.write_gate_receipts = await count(`DELETE FROM write_gate_receipts WHERE (target_table='pages' AND target_id=$1) OR (target_table='facts' AND target_id=ANY($2::text[]))
OR (target_table='takes' AND target_id=ANY($3::text[])) OR (target_table='write_gate_holds' AND target_id=ANY($4::text[])) RETURNING 1`,
[String(page.id), refs, takeIds.map(String), holds]);
- removed.query_cache = await count('DELETE FROM query_cache RETURNING 1', []);
+ const missingCaches: string[] = [];
+ removed.query_cache = await clearRebuildableCache(tx, 'query_cache', 'DELETE FROM query_cache RETURNING 1', [], missingCaches);
removed.facts = await count('DELETE FROM facts WHERE source_id=$1 AND source_markdown_slug=$2 RETURNING 1', [sourceId, slug]);
removed.take_proposals = await count('DELETE FROM take_proposals WHERE source_id=$1 AND page_slug=$2 RETURNING 1', [sourceId, slug]);
removed.open_loops = await count('DELETE FROM open_loops WHERE source_id=$1 AND page_slug=$2 RETURNING 1', [sourceId, slug]);
@@ -321,6 +323,7 @@ export async function purgePageInTransaction(tx: BrainEngine, row: WriteRequest,
while (purgeContext.size > PURGE_CONTEXT_LIMIT) purgeContext.delete(purgeContext.keys().next().value!);
return { status: 'purged', slug, source_id: sourceId, residuals: PURGE_RESIDUALS, journal_sweep: journalSweep, ...(retention ? { retention: true } : {}),
purge: { content_hash8: storedHash?.slice(0, 8) ?? null, tombstoned: hashes.size > 0, content_hashes_tombstoned: hashes.size, removed,
+ ...(missingCaches.length ? { missing_caches: missingCaches } : {}),
...(ledger ? { ledger: { purged_events: ledger.purged_events, redacted_fields: ledger.redacted_fields.length, live_carriers: ledger.live_carriers.length, derived_hidden: ledger.derived_hidden, derived_walk: ledger.derived_walk } } : {}),
derived: { ...derived, truncated: derivedFrom.truncated },
blobs: files.map(f => f.storage_path).filter(Boolean) } };
diff --git a/src/core/persistence/preview-approval.ts b/src/core/persistence/preview-approval.ts
index 78d44c4d22..b75339bd10 100644
--- a/src/core/persistence/preview-approval.ts
+++ b/src/core/persistence/preview-approval.ts
@@ -40,7 +40,7 @@ export const PREVIEW_APPROVAL_OP = 'repair-approval';
/** The default `purgeStaleCheckpoints` TTL; an older approved set may already be gone. */
export const APPROVAL_MAX_AGE_DAYS = 7;
-export type PreviewApprovalCommand = 'authorize-legacy' | 'jobs-cancel' | 'stale-atoms' | 'extractor-facts' | 'conversation-labels' | 'captured-facts' | 'loop-facts' | 'ontology-facts' | 'failed-writes' | 'split-facts' | 'frontmatter' | 'fences' | 'slug-conflicts' | 'managed-sync-orphans' | 'frontmatter-keys' | 'file-drift' | 'stuck-recovery' | 'ghost-pages' | 'receipt-compaction' | 'accepted-takes' | 'rename-identity' | 'overwritten-edits';
+export type PreviewApprovalCommand = 'authorize-legacy' | 'jobs-cancel' | 'stale-atoms' | 'extractor-facts' | 'conversation-labels' | 'captured-facts' | 'loop-facts' | 'ontology-facts' | 'failed-writes' | 'split-facts' | 'frontmatter' | 'fences' | 'slug-conflicts' | 'managed-sync-orphans' | 'frontmatter-keys' | 'file-drift' | 'stuck-recovery' | 'ghost-pages' | 'receipt-compaction' | 'accepted-takes' | 'rename-identity' | 'overwritten-edits' | 'missing-tables';
export interface ApprovedSetKey {
command: PreviewApprovalCommand;
diff --git a/src/core/persistence/rebuildable-cache.ts b/src/core/persistence/rebuildable-cache.ts
new file mode 100644
index 0000000000..2f48218601
--- /dev/null
+++ b/src/core/persistence/rebuildable-cache.ts
@@ -0,0 +1,31 @@
+/**
+ * #6911: purge-path writes to rebuildable caches. A cache the graduation inventory classifies `rebuild`
+ * (query_cache, code_traversal_cache) holds nothing a rebuild cannot regenerate, so a brain where the table is
+ * absent purges correctly by skipping it. The existence check runs before the statement because a 42P01 inside a
+ * Postgres transaction aborts the whole transaction even when caught. A missing table that holds user data is never
+ * skipped: the purge fails loudly rather than claim it cleared rows it could not reach.
+ */
+import type { BrainEngine } from '../engine.ts';
+import { GRADUATION_INVENTORY } from './graduation-inventory.ts';
+
+let rebuildable: ReadonlySet<string> | null = null;
+export function isRebuildableCache(table: string): boolean {
+ rebuildable ??= new Set(GRADUATION_INVENTORY.entries.filter(e => e.class === 'rebuild' && e.kind === 'table').map(e => e.relation));
+ return rebuildable.has(table);
+}
+
+/** Whether `table` resolves on the connection's search path, the same resolution the statement that uses it gets. */
+export async function relationExists(engine: Pick<BrainEngine, 'executeRaw'>, table: string): Promise<boolean> {
+ const [row] = await engine.executeRaw<{ present: boolean }>('SELECT to_regclass($1) IS NOT NULL AS present', [table]);
+ return row?.present === true;
+}
+
+/**
+ * Run `sql` (a DELETE ... RETURNING) against a rebuildable cache and return the row count, or 0 with the table
+ * appended to `missing` when the cache table does not exist.
+ */
+export async function clearRebuildableCache(tx: Pick<BrainEngine, 'executeRaw'>, table: string, sql: string, params: unknown[], missing: string[]): Promise<number> {
+ if (!isRebuildableCache(table)) throw new Error(`clearRebuildableCache: ${table} is not a rebuildable cache in the graduation inventory`);
+ if (!await relationExists(tx, table)) { missing.push(table); return 0; }
+ return (await tx.executeRaw(sql, params)).length;
+}
diff --git a/src/core/repair/core.ts b/src/core/repair/core.ts
index fdfad3c642..6e69573f43 100644
--- a/src/core/repair/core.ts
+++ b/src/core/repair/core.ts
@@ -37,7 +37,7 @@ import { acceptedPendingReceipt } from '../persistence/accepted-pending.ts';
import { repairAdmissionWindow, repairPublicationOwner, settleRepairReceipts, type PendingRepair } from './settle.ts';
import { RECEIPT_RESERVATION_FLOOR } from '../persistence/receipt-bytes.ts';
-export const REPAIR_KINDS = ['timeline', 'visibility', 'safe-chunks', 'contextual-mode', 'connector-checkpoints', 'request-indexes', 'connector-fences', 'take-supersession', 'accepted-takes', 'orphan-bindings', 'embedding-effects', 'attribution-backfill', 'planner-stats', 'google-file-modes', 'stale-atoms', 'extractor-facts', 'conversation-labels', 'captured-facts', 'loop-facts', 'ontology-facts', 'orphan-children', 'failed-writes', 'split-facts', 'frontmatter', 'fences', 'slug-conflicts', 'timeline-comments', 'managed-sync-orphans', 'frontmatter-keys', 'file-drift', 'stuck-recovery', 'ghost-pages', 'receipt-compaction', 'aliases', 'rename-identity', 'overwritten-edits'] as const;
+export const REPAIR_KINDS = ['timeline', 'visibility', 'safe-chunks', 'contextual-mode', 'connector-checkpoints', 'request-indexes', 'connector-fences', 'take-supersession', 'accepted-takes', 'orphan-bindings', 'embedding-effects', 'attribution-backfill', 'planner-stats', 'google-file-modes', 'stale-atoms', 'extractor-facts', 'conversation-labels', 'captured-facts', 'loop-facts', 'ontology-facts', 'orphan-children', 'failed-writes', 'split-facts', 'frontmatter', 'fences', 'slug-conflicts', 'timeline-comments', 'managed-sync-orphans', 'frontmatter-keys', 'file-drift', 'stuck-recovery', 'ghost-pages', 'receipt-compaction', 'aliases', 'rename-identity', 'overwritten-edits', 'missing-tables'] as const;
export type RepairKind = typeof REPAIR_KINDS[number];
export interface RepairScope { brain_id: string; source_ids: string[] }
diff --git a/src/core/repair/missing-tables.ts b/src/core/repair/missing-tables.ts
new file mode 100644
index 0000000000..a8b129c4a0
--- /dev/null
+++ b/src/core/repair/missing-tables.ts
@@ -0,0 +1,65 @@
+/**
+ * `gbrain repair missing-tables` (#6911): recreate, empty, a rebuildable cache table that the applied migrations
+ * created but the brain no longer has (`doctor` check schema_missing_tables). The schema version is already at head,
+ * so `apply-migrations` never runs the creating migration again. Only tables the graduation inventory classifies
+ * `rebuild` and that have a recreate step qualify; any other missing table holds user data and is listed for the
+ * operator (restore it from a backup), never recreated empty.
+ *
+ * Explicit-only and preview-bound: the preview prints the tables and a hash, and `--apply --expect <hash>` recreates
+ * exactly that set. It never runs on upgrade, apply-migrations, db-repair or the maintenance cycle. DDL only (IF NOT
+ * EXISTS); no journal admission and no user data changes. Brain-wide.
+ */
+import { OperationError } from '../ops/contract.ts';
+import { clearApprovedSet, loadApprovedSet, previewHash, saveApprovedSet } from '../persistence/preview-approval.ts';
+import { relationExists } from '../persistence/rebuildable-cache.ts';
+import { readMissingTables, RECREATE } from '../schema-missing-tables.ts';
+import { afterCursor, type RepairHandler, type RepairItem, type RepairPlan } from './core.ts';
+
+const PREVIEW = 'gbrain repair missing-tables';
+const toItem = (table: string, position: number): RepairItem => ({ cursor: { phase: 0, id: position + 1 }, source_id: '(brain)', slug: table, chars: 0,
+ action: 'recreate_empty' });
+
+export const missingTablesRepair: RepairHandler = {
+ kind: 'missing-tables',
+ publication: 'projection',
+ embeds: false,
+ async plan(engine, scope, after, opts = { apply: false }): Promise<RepairPlan> {
+ if (opts.apply) {
+ if (!opts.expect) throw new OperationError('invalid_params', 'gbrain repair missing-tables --apply needs the preview hash.',
+ `Preview first: ${PREVIEW} — then run the apply command it prints: ${PREVIEW} --apply --expect <preview-hash>`, 'docs/guides/repair.md#missing-tables');
+ const { items: tables } = await loadApprovedSet<string>(engine, { command: 'missing-tables', hash: opts.expect, previewCommand: PREVIEW });
+ const items = tables.map(toItem).filter(item => afterCursor(item.cursor, after));
+ if (!items.length) await clearApprovedSet(engine, { command: 'missing-tables', hash: opts.expect });
+ return { items, preview_hash: opts.expect, residuals: {} };
+ }
+ const report = await readMissingTables(engine);
+ if (report.status === 'skipped') {
+ return { items: [], residuals: {}, warnings: [`The schema is at v${report.version}, not v${report.latest}; run gbrain apply-migrations --yes first, then preview again.`] };
+ }
+ const tables = report.missing.filter(m => m.recreatable).map(m => m.table);
+ const kept = report.missing.filter(m => !m.recreatable);
+ const hash = previewHash({ kind: 'missing-tables-v1', brain_id: scope.brain_id, tables });
+ if (tables.length) await saveApprovedSet<string>(engine, { command: 'missing-tables', hash }, tables);
+ return { items: tables.map(toItem), ...(tables.length ? { preview_hash: hash } : {}), residuals: kept.length ? { user_data_tables: kept.length } : {},
+ details: { checked: report.checked, recreate: tables, user_data_tables: kept.map(m => m.table) } };
+ },
+ 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);
+ 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' };
+ },
+ render(details) {
+ const d = details as { checked?: number; recreate?: string[]; user_data_tables?: string[] };
+ return [
+ ` ${d.checked ?? 0} expected table(s) checked`,
+ ...(d.recreate ?? []).map(t => ` recreate empty: ${t} (rebuildable cache; it refills on use)`),
+ ...(d.user_data_tables ?? []).map(t => ` kept: ${t} holds user data; restore it from a backup, it is never recreated empty`),
+ ];
+ },
+};
diff --git a/src/core/repair/registry.ts b/src/core/repair/registry.ts
index 11c94cba73..62c7e76789 100644
--- a/src/core/repair/registry.ts
+++ b/src/core/repair/registry.ts
@@ -70,6 +70,7 @@ import { receiptCompactionRepair } from './receipt-compaction.ts';
import { aliasesRepair } from './aliases.ts';
import { renameIdentityRepair, RENAME_IDENTITY_CONSENT_TEXT } from './rename-identity.ts';
import { overwrittenEditsRepair } from './overwritten-edits.ts';
+import { missingTablesRepair } from './missing-tables.ts';
import { ERROR_CATALOGUE, catalogueError } from '../error-catalogue.ts';
import type { OperationError } from '../ops/contract.ts';
@@ -374,6 +375,13 @@ const SPECS: Record<RepairKind, Omit<RepairKindSpec, 'kind'>> = {
+ 'reverts each page to that version through a revision-bound, database-only revert_version, then holds the committed file file_drift when it '
+ 'differs, so sync never publishes it over the edit. Narrow with --slug. Runs only when named.',
},
+ 'missing-tables': {
+ handler: missingTablesRepair, embeds: 'none', checks: ['schema_missing_tables'], explicit_only: true, preview_bound: true,
+ summary: 'Recreate, empty, a rebuildable cache table (query_cache, code_traversal_cache) that the applied migrations created but the brain no longer '
+ + 'has (#6911), so the coordinated purge and search caching work again. A missing table that holds user data is listed for a restore, never '
+ + 'recreated. DDL only (IF NOT EXISTS), no journal admission. The preview prints a hash; --apply --expect <hash> recreates exactly that set. '
+ + 'Runs only when named; never on upgrade. Brain-wide.',
+ },
};
export const REPAIR_REGISTRY: readonly RepairKindSpec[] = REPAIR_KINDS.map(kind => ({ kind, ...SPECS[kind] }));
diff --git a/src/core/schema-missing-tables.ts b/src/core/schema-missing-tables.ts
new file mode 100644
index 0000000000..4089eb01bd
--- /dev/null
+++ b/src/core/schema-missing-tables.ts
@@ -0,0 +1,53 @@
+/**
+ * #6911: tables an applied migration should have created but the live brain lacks. The schema version only says
+ * which migrations ran, so a table dropped afterwards (or swallowed by a pooler) stays invisible to
+ * `apply-migrations` and `db-repair`. The expected set is the graduation inventory, which
+ * test/graduation-inventory.test.ts pins to a fully migrated brain on each engine, so it covers tables that only a
+ * migration creates (query_cache is not in schema.sql). Read-only; `gbrain repair missing-tables` recreates the
+ * rebuildable ones after a preview.
+ */
+import type { BrainEngine } from './engine.ts';
+import { LATEST_VERSION } from './migrate.ts';
+import { GRADUATION_INVENTORY } from './persistence/graduation-inventory.ts';
+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';
+
+export interface MissingTable {
+ table: string;
+ /** The graduation inventory class: `rebuild` tables hold only regenerable cache rows. */
+ inventory_class: string;
+ /** `gbrain repair missing-tables` can recreate it empty in its head shape. */
+ recreatable: boolean;
+}
+
+export type MissingTablesReport = { status: 'checked'; checked: number; missing: MissingTable[] } | { status: 'skipped'; reason: 'schema_not_at_head'; version: number; latest: number };
+
+/**
+ * Recreate a rebuildable cache table empty, in the shape a fully migrated brain has: its creating migration, then
+ * every later column and index statement that targets it (v090 and v091 add one column each to query_cache inside
+ * migrations that also rewrite pages, so only those statements run here). Every statement is IF NOT EXISTS.
+ * test/schema-missing-tables.test.ts compares the recreated catalog with a fresh brain's, so a later migration that
+ * changes one of these tables without a line here fails that test.
+ */
+export const RECREATE: Readonly<Record<string, (engine: BrainEngine) => Promise<void>>> = {
+ query_cache: async engine => {
+ 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;');
+ },
+ code_traversal_cache: async engine => { await engine.runMigration(59, v059.sql); },
+};
+
+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 };
+ const expected = GRADUATION_INVENTORY.entries.filter(e => e.kind === 'table' && e.engines[engine.kind]);
+ const rows = await engine.executeRaw<{ relation: string }>('SELECT r AS relation FROM unnest($1::text[]) AS r WHERE to_regclass(r) IS NULL ORDER BY r',
+ [expected.map(e => e.relation)]);
+ const byName = new Map(expected.map(e => [e.relation, e]));
+ return { status: 'checked', checked: expected.length, missing: rows.map(({ relation }) => ({ table: relation, inventory_class: byName.get(relation)!.class,
+ recreatable: isRebuildableCache(relation) && relation in RECREATE })) };
+}
diff --git a/test/fix-wave-5-integration.test.ts b/test/fix-wave-5-integration.test.ts
index adad04540a..cdf6030c35 100644
--- a/test/fix-wave-5-integration.test.ts
+++ b/test/fix-wave-5-integration.test.ts
@@ -197,7 +197,7 @@ for (const backend of testBackends()) {
'conversation-labels': 'gbrain repair conversation-labels', 'captured-facts': 'gbrain repair captured-facts', 'loop-facts': 'gbrain repair loop-facts', 'ontology-facts': 'gbrain repair ontology-facts', 'orphan-children': 'gbrain repair orphan-children', 'failed-writes': 'gbrain repair failed-writes', 'split-facts': 'gbrain repair split-facts',
frontmatter: 'gbrain repair frontmatter', 'timeline-comments': 'gbrain repair timeline-comments', 'managed-sync-orphans': 'gbrain repair managed-sync-orphans', 'frontmatter-keys': 'gbrain repair frontmatter-keys', 'file-drift': 'gbrain repair file-drift',
'stuck-recovery': 'gbrain repair stuck-recovery', 'ghost-pages': 'gbrain repair ghost-pages', 'receipt-compaction': 'gbrain repair receipt-compaction', aliases: 'gbrain repair aliases', 'rename-identity': 'gbrain repair rename-identity',
- 'overwritten-edits': 'gbrain repair overwritten-edits' };
+ 'overwritten-edits': 'gbrain repair overwritten-edits', 'missing-tables': 'gbrain repair missing-tables' };
// The post-upgrade banner names both findings with the kind's read-only preview.
const banner = await postUpgradeRecoveryBanner(engine, 'host');
diff --git a/test/fixtures/goldens/doctor/json-pglite-degraded.json b/test/fixtures/goldens/doctor/json-pglite-degraded.json
index c87992545b..31aa3d5ed4 100644
--- a/test/fixtures/goldens/doctor/json-pglite-degraded.json
+++ b/test/fixtures/goldens/doctor/json-pglite-degraded.json
@@ -902,6 +902,13 @@
"name": "schema_columns",
"status": "ok"
},
+ {
+ "category": "meta",
+ "elapsed_ms": "<volatile>",
+ "message": "All 147 table(s) the applied migrations create exist.",
+ "name": "schema_missing_tables",
+ "status": "ok"
+ },
{
"category": "ops",
"elapsed_ms": "<volatile>",
diff --git a/test/fixtures/goldens/doctor/json-pglite-fresh.json b/test/fixtures/goldens/doctor/json-pglite-fresh.json
index be53467c11..5d49d09108 100644
--- a/test/fixtures/goldens/doctor/json-pglite-fresh.json
+++ b/test/fixtures/goldens/doctor/json-pglite-fresh.json
@@ -949,6 +949,13 @@
"name": "schema_columns",
"status": "ok"
},
+ {
+ "category": "meta",
+ "elapsed_ms": "<volatile>",
+ "message": "All 147 table(s) the applied migrations create exist.",
+ "name": "schema_missing_tables",
+ "status": "ok"
+ },
{
"category": "ops",
"elapsed_ms": "<volatile>",
diff --git a/test/fixtures/goldens/doctor/registry-build-checks.json b/test/fixtures/goldens/doctor/registry-build-checks.json
index f44c035b0a..58baf705a6 100644
--- a/test/fixtures/goldens/doctor/registry-build-checks.json
+++ b/test/fixtures/goldens/doctor/registry-build-checks.json
@@ -349,6 +349,10 @@
"category": "meta",
"name": "schema_columns"
},
+ {
+ "category": "meta",
+ "name": "schema_missing_tables"
+ },
{
"category": "ops",
"name": "rls_event_trigger"
diff --git a/test/purge-missing-cache-6911.test.ts b/test/purge-missing-cache-6911.test.ts
new file mode 100644
index 0000000000..dbd24e4f41
--- /dev/null
+++ b/test/purge-missing-cache-6911.test.ts
@@ -0,0 +1,139 @@
+/**
+ * #6911: a brain whose query_cache table is missing although its schema is at head. The coordinated purge must
+ * still purge (query_cache is a rebuildable cache), its receipt must say the cache was absent, a missing user-data
+ * table must still fail the purge loudly, doctor must report the missing table, and the preview-first
+ * `gbrain repair missing-tables` must recreate the cache in the shape a fully migrated brain has.
+ * Real PGLite, plus Postgres when DATABASE_URL is set.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type { BrainEngine } from '../src/core/engine.ts';
+import type { OperationContext } from '../src/core/ops/contract.ts';
+import { OperationError } from '../src/core/ops/contract.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { importFromContent } from '../src/core/import-file.ts';
+import { runExtractFacts } from '../src/core/cycle/extract-facts.ts';
+import { registerLocalWriter } from '../src/core/persistence/identity.ts';
+import { operations } from '../src/core/operations.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { readMissingTables } from '../src/core/schema-missing-tables.ts';
+import { runRepair, resolveRepairScope } from '../src/core/repair/core.ts';
+import { missingTablesRepair } from '../src/core/repair/missing-tables.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const home = mkdtempSync(join(tmpdir(), 'gbrain-6911-'));
+const engines: BrainEngine[] = [];
+let fresh: PGLiteEngine;
+let closePostgres: (() => Promise<void>) | undefined;
+const CLAIM = 'Keeps the deploy runbook in vault-a';
+const body = (title: string) => `---\ntitle: ${title}\ntype: person\n---\n# ${title}\n\nProse.\n\n## Facts\n\n<!--- gbrain:facts:begin -->
+| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |
+|---|-------|------|------------|------------|------------|------------|-------------|--------|---------|
+| 1 | ${CLAIM} | fact | 1.0 | world | medium | 2026-01-01 | | chat | |
+<!--- gbrain:facts:end -->\n`;
+const ctx = (engine: BrainEngine): OperationContext => ({ engine, sourceId: 'default', remote: false, dryRun: false,
+ config: { engine: engine.kind, embedding_disabled: true }, logger: { info() {}, warn() {}, error() {} } } as unknown as OperationContext);
+const op = (name: string) => operations.find(o => o.name === name)!;
+const call = (engine: BrainEngine, name: string, params: Record<string, unknown>) => op(name).handler(ctx(engine), params) as Promise<Record<string, any>>;
+
+async function seed(engine: BrainEngine, slug: string): Promise<void> {
+ await importFromContent(engine, slug, body(slug.split('/')[1]!), { noEmbed: true, sourceId: 'default' });
+ await runExtractFacts(engine, { slugs: [slug] });
+}
+async function purgePage(engine: BrainEngine, slug: string) {
+ const snapshot = await engine.readPageSnapshot(slug, { sourceId: 'default', includeDeleted: true });
+ return call(engine, 'delete_page', { slug, purge: true, request_id: randomUUID(), expected_revision: snapshot!.revision });
+}
+async function errorCode(p: Promise<unknown>): Promise<string> {
+ try { await p; return 'ok'; } catch (e) { return e instanceof OperationError ? `${e.canonical ?? e.code}: ${e.message}` : String((e as Error).message); }
+}
+/** Columns and indexes of a table, comparable across two brains. */
+async function shape(engine: BrainEngine, table: string) {
+ const columns = await engine.executeRaw<Record<string, string>>(`SELECT column_name, data_type, udt_name, is_nullable, column_default FROM information_schema.columns
+ WHERE table_schema=current_schema() AND table_name=$1 ORDER BY column_name`, [table]);
+ const indexes = await engine.executeRaw<{ indexdef: string }>('SELECT indexdef FROM pg_indexes WHERE schemaname=current_schema() AND tablename=$1 ORDER BY indexname', [table]);
+ return { columns, indexes: indexes.map(i => i.indexdef) };
+}
+
+beforeAll(async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ const lite = new PGLiteEngine(); await lite.connect({}); await lite.initSchema(); engines.push(lite);
+ fresh = new PGLiteEngine(); await fresh.connect({}); await fresh.initSchema();
+ if (process.env.DATABASE_URL) {
+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL);
+ engines.push(pg.engine); closePostgres = pg.close;
+ }
+ for (const engine of engines) await registerLocalWriter(engine, 'cli');
+}), 180_000);
+afterAll(async () => {
+ for (const engine of engines) await disposePersistenceConsumer(engine).catch(() => undefined);
+ await engines[0]?.disconnect(); await fresh?.disconnect(); await closePostgres?.();
+ rmSync(home, { recursive: true, force: true });
+}, 60_000);
+
+describe('#6911 missing query_cache', () => {
+ test('the coordinated page purge commits and its receipt names the absent cache', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ for (const engine of engines) {
+ await seed(engine, 'people/purge-example');
+ await engine.executeRaw('DROP TABLE query_cache');
+ const result = await purgePage(engine, 'people/purge-example');
+ expect(result.status).toBe('purged');
+ expect(result.purge.removed.query_cache).toBe(0);
+ expect(result.purge.missing_caches).toEqual(['query_cache']);
+ expect(result.receipt.stores.find((s: any) => s.store === 'query_cache')).toMatchObject({ status: 'not_present', reason: 'table_missing' });
+ expect(await engine.executeRaw("SELECT 1 FROM pages WHERE slug='people/purge-example'")).toHaveLength(0);
+ expect((await engine.executeRaw("SELECT 1 FROM page_purges WHERE slug='people/purge-example'")).length).toBeGreaterThan(0);
+ }
+ }), 120_000);
+
+ test('a fact purge commits and verifies with the cache absent', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ for (const engine of engines) {
+ await seed(engine, 'people/fact-example');
+ const [row] = await engine.executeRaw<{ id: number }>("SELECT id FROM facts WHERE fact=$1 AND entity_slug='people/fact-example'", [CLAIM]);
+ const dry = await call(engine, 'purge_fact', { id: Number(row!.id), dry_run: true });
+ const done = await call(engine, 'purge_fact', { id: Number(row!.id), confirm: dry.confirm_token, expected_revision: dry.expected_revision, request_id: randomUUID() });
+ expect(done.state).toBe('committed');
+ expect(done.stores.find((s: any) => s.store === 'query_cache')).toMatchObject({ status: 'not_present', reason: 'table_missing' });
+ }
+ }), 120_000);
+
+ test('doctor reports the missing cache; the repair previews, then recreates it in the head shape', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ const expected = await shape(fresh, 'query_cache');
+ expect(expected.columns.length).toBeGreaterThan(0);
+ for (const engine of engines) {
+ const report = await readMissingTables(engine);
+ expect(report).toMatchObject({ status: 'checked', missing: [{ table: 'query_cache', inventory_class: 'rebuild', recreatable: true }] });
+ const scope = await resolveRepairScope(engine);
+ expect(await errorCode(runRepair(ctx(engine), missingTablesRepair, scope, { apply: true, explicit: true }))).toStartWith('invalid_params');
+ const preview = await runRepair(ctx(engine), missingTablesRepair, scope, { apply: false, explicit: true });
+ expect(preview.affected).toBe(1);
+ expect(preview.preview_hash).toBeTruthy();
+ expect(await engine.executeRaw("SELECT to_regclass('query_cache') IS NULL AS absent")).toEqual([{ absent: true }]);
+ const applied = await runRepair(ctx(engine), missingTablesRepair, scope, { apply: true, explicit: true, expect: preview.preview_hash });
+ expect(applied.applied).toBe(1);
+ expect(applied.outcomes).toMatchObject({ recreated: 1 });
+ if (engine.kind === 'pglite') expect(await shape(engine, 'query_cache')).toEqual(expected);
+ else expect((await shape(engine, 'query_cache')).columns.map(c => c.column_name)).toEqual(expected.columns.map(c => c.column_name));
+ expect(await readMissingTables(engine)).toMatchObject({ status: 'checked', missing: [] });
+ }
+ }), 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);
+ expect(await errorCode(runRepair(ctx(engine), missingTablesRepair, scope, { apply: false }))).toContain('explicit');
+ await seed(engine, 'people/loud-example');
+ await engine.executeRaw('DROP TABLE core_edit_notices');
+ const report = await readMissingTables(engine);
+ expect(report).toMatchObject({ status: 'checked', missing: [{ table: 'core_edit_notices', recreatable: false }] });
+ const preview = await runRepair(ctx(engine), missingTablesRepair, scope, { apply: false, explicit: true });
+ expect(preview.affected).toBe(0);
+ expect(preview.residuals).toEqual({ user_data_tables: 1 });
+ expect(await errorCode(purgePage(engine, 'people/loud-example'))).not.toBe('ok');
+ expect(await engine.executeRaw("SELECT 1 FROM pages WHERE slug='people/loud-example' AND deleted_at IS NULL")).toHaveLength(1);
+ }
+ }), 120_000);
+});
diff --git a/test/repair-explicit-only.test.ts b/test/repair-explicit-only.test.ts
index 71bda489a9..9e94276321 100644
--- a/test/repair-explicit-only.test.ts
+++ b/test/repair-explicit-only.test.ts
@@ -24,7 +24,7 @@ import { REPAIR_HELP, parseRepairArgs, runRepairCommand } from '../src/commands/
import { _resetCliExitVerdictForTests, currentExitCode } from '../src/core/cli-force-exit.ts';
import { withEnv } from './helpers/with-env.ts';
-const EXPLICIT: RepairKind[] = ['accepted-takes', 'google-file-modes', 'stale-atoms', 'extractor-facts', 'conversation-labels', 'captured-facts', 'loop-facts', 'ontology-facts', 'orphan-children', 'failed-writes', 'split-facts', 'frontmatter', 'timeline-comments', 'managed-sync-orphans', 'frontmatter-keys', 'file-drift', 'stuck-recovery', 'ghost-pages', 'receipt-compaction', 'aliases', 'rename-identity', 'overwritten-edits'];
+const EXPLICIT: RepairKind[] = ['accepted-takes', 'google-file-modes', 'stale-atoms', 'extractor-facts', 'conversation-labels', 'captured-facts', 'loop-facts', 'ontology-facts', 'orphan-children', 'failed-writes', 'split-facts', 'frontmatter', 'timeline-comments', 'managed-sync-orphans', 'frontmatter-keys', 'file-drift', 'stuck-recovery', 'ghost-pages', 'receipt-compaction', 'aliases', 'rename-identity', 'overwritten-edits', 'missing-tables'];
let engine: PGLiteEngine;
const home = mkdtempSync(join(tmpdir(), 'gbrain-repair-explicit-'));