Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(repair): missing-tables review fixes (#6911): honest user-data advice, loss-kind verdicts, below-head cache check, one-shot approval, lock-bounded DDL, shape drift test

garrytan5d280ea16d25
diff --git a/CHANGELOG.md b/CHANGELOG.md
index b85af374c7..0311e864cc 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -18,15 +18,20 @@ identifiers and attribution are available in the pre-removal Git revision
| 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` |
+| Page 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` |
+| Fact purge with `query_cache` missing | failed with `42P01` | commits; the store report 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 |
+| `gbrain doctor` with a missing table | nothing flagged it | `schema_missing_tables`: warn for a rebuildable cache or a table without user data, fail for a user-data table; below head it checks the rebuildable caches, whose absence would wedge `apply-migrations` |
| 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 |
+| `gbrain forget --purge --vacuum` on PGLite with the cache missing | the VACUUM failed silently, so nothing was vacuumed | the other tables are vacuumed, and the receipt says whether VACUUM ran or failed |
### 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.
+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.
+
+If your nightly purge failed on the missing cache for a while, some deleted pages were parked after five failures and stay unpurged. Doctor `purge_parked_pages` lists them; preview with `gbrain pages purge-deleted --retry-parked --dry-run`, then run it without `--dry-run` after you agree.
+
+If doctor fails `schema_missing_tables` on a table that holds user data, restore that table's rows from a backup **before** you run `gbrain upgrade`, `apply-migrations` or `init --migrate-only`: they recreate a base-schema table empty, which clears the check while the rows stay lost.
## [0.60.289.0] - 2026-10-17
diff --git a/docs/architecture/key-files/core-persistence-graduation.md b/docs/architecture/key-files/core-persistence-graduation.md
index dd3d9b755d..f0b01b41c9 100644
--- a/docs/architecture/key-files/core-persistence-graduation.md
+++ b/docs/architecture/key-files/core-persistence-graduation.md
@@ -16,3 +16,6 @@ Verified engine graduation, PGLite to Postgres ([operator guide](../../guides/mo
- `src/core/persistence/graduation-losses.ts` — rollback write detection: per carried table, the target digest against the verified receipt (`persistence_brain.enabled` through its transform), requests after the cutover sequence, and the security tables plus `fact_withdrawals` against the retained PGLite copy by identity and content (`last_used_at` ignored, expired OAuth tokens may disappear). Missing or changed security rows and new withdrawals are final.
- `src/commands/migrate-graduation.ts` — the `gbrain migrate` graduation CLI, routed before connect from `routeEngineFreeSubcommands` in `src/cli.ts` when `routesToGraduation` holds (run-scoped verbs and `--plan` always; a bare `--to postgres|supabase` on a durable PGLite config unless `migrate.graduation` is false or the host is Windows). Without `--yes --expect` it plans and returns the `confirmation_required` payload (effects egress and destructive, what moves and what stays, `plan_hash`, the `--plan` preview; no stdin prompt); `--plan`/`--dry-run` prints the plan; the run reports the receipt, retained copy, target doctor, `gbrain mcp expose` and the MCP restart note. Exit codes 0/1/2/3, 11 for a progressing drain stop (1 when a blocker needs a person), 75 for `graduation_in_progress`, 130 after SIGINT (stops at the next batch boundary). `--json` prints one document; progress goes to stderr per table and batch. Test: `test/migrate-graduation-cli.serial.test.ts`.
- `src/commands/doctor/checks/engine-graduation.ts` — `graduationStateCheck`, emitted from the filesystem lane of `local-audits.ts`: `graduation_interrupted` fails when a manifest or marker is non-terminal with no live owner (fix `gbrain migrate --resume`, rollback named) or a stray brain sits at the old path, is `ok` while a live run owns it, exempts the run named by `GBRAIN_GRADUATION_RUN`, and emits nothing on a brain that never graduated. The retained `.graduated-*` copy is reported by `pglite_leftovers` (`src/core/pglite-leftovers-check.ts`), silent while a manifest is non-terminal.
+- `src/core/repair/missing-tables.ts` — `gbrain repair missing-tables` (#6911), explicit-only and preview-bound (`--apply --expect <hash>`), brain-wide, DDL only. The preview lists the missing rebuildable caches `readMissingTables` reports (`recreate`), plus `user_data_tables` and `other_tables` residuals it never recreates; the hash covers the brain id, `LATEST_VERSION` and the tables. Apply refuses when the brain schema is newer than the client, leaves a table that already exists alone (`already_present`, no DDL), runs `recreateStep` in one transaction per table under the migration statement and lock timeouts (`schemaLockBlockedError` on a lock timeout), maps 42501 to `schema_owner_required` (approval kept) and 23505/42P07 races to `already_present`, and retires the approved set with the last item. Tests: `test/purge-missing-cache-6911.test.ts`, `test/schema-missing-tables.test.ts`.
+- `src/core/schema-missing-tables.ts` — #6911 expected-table check. `readMissingTables`: at head every graduation-inventory table for the engine, below head only the recreatable caches whose creating migration (`CREATED_BY`) already ran, `skipped` (`client_behind`) when the brain is newer; each missing table carries its inventory class and `loss_kind`. `recreateStep` (own-key lookup, rebuild class only) rebuilds `query_cache` (v055 DDL sized from the live `facts.embedding` shape, then the v056/v090/v091 statements) and `code_traversal_cache` (v059). `test/schema-missing-tables.test.ts` pins each recreated table's columns and indexes to the migrated brain's on both engines and `RECREATABLE_TABLES` to the inventory's rebuild tables. Doctor `schema_missing_tables` (`src/commands/doctor/checks/schema-health.ts`) renders it: warn for caches (repair preview fix) and tables without user data, fail for `user_data` tables.
+- `src/core/persistence/rebuildable-cache.ts` — #6911 purge-side skip: `isRebuildableCache` (inventory class `rebuild`), `relationExists` (`to_regclass` on the connection's search path), and `clearRebuildableCache(tx, table)`, which returns the rows deleted or null when the cache table is absent; the existence check runs first because a 42P01 aborts a Postgres transaction. Callers: page purge (`purge.missing_caches`) and fact purge.
diff --git a/docs/guides/repair.md b/docs/guides/repair.md
index 72b0298704..27997f9332 100644
--- a/docs/guides/repair.md
+++ b/docs/guides/repair.md
@@ -149,7 +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. |
+| `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 already covers its creating migration, 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; this repair never recreates it, so restore its rows from a backup first. `other_tables`: a missing table that holds no user data; `gbrain init --migrate-only` recreates it if the base schema defines it. |
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
@@ -253,24 +253,30 @@ missing or INVALID; otherwise compare the elapsed time with
### 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:
+exist. A table dropped after its migration ran 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
+connection, not the tables. How the #6911 brain lost its `query_cache` is not
+known; a manual drop, a restore that skipped the table, or a pooler that
+swallowed the DDL are possibilities. 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`,
+The page 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.
+shows `query_cache` as `not_present` with reason `table_missing`. The fact
+purge skips it the same way. 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`. At head it checks every table
+a fully migrated brain has on this engine; below head it checks the rebuildable
+caches whose creating migration already ran, because a pending migration that
+alters a missing cache fails with `42P01` and `apply-migrations` cannot finish.
+A missing rebuildable cache warns with the repair below. A missing table that
+holds user data fails. Any other missing table (locks, leases, operational
+state) warns: `gbrain init --migrate-only` recreates the ones the base schema
+defines.
**Say to your agent:** *"Doctor says query_cache is missing. Fix it."*
@@ -280,19 +286,31 @@ 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 completed in place (`completed`); every statement is `IF NOT EXISTS` and the
-whole table is built in one transaction. The cache refills as searches run.
-If the database role gbrain connects as may not create tables (an owner/app
-role split), the apply refuses with `schema_owner_required` and creates nothing:
-run it again connected as the role that owns the schema.
-
-A missing table that holds user data is listed under `user_data_tables` and is
-never recreated empty, because an empty table would hide that its rows are
-gone. Restore that table's rows from your own database backup (a `pg_dump`
-of the brain, or your host's point-in-time recovery). `gbrain backup restore`
-restores a whole brain into a new root, not one table. Until the table is
-back, writes that touch it keep failing, and doctor keeps reporting it.
+migrated brain has, in one transaction per table, then checks it exists. Every
+statement is `IF NOT EXISTS` and waits for locks only as long as a migration
+does. A table that exists by the time the apply reaches it is left alone
+(`already_present`). The approval is used once: the last table retires it, so
+a later drop needs a fresh preview. The cache refills as searches run. If the
+database role gbrain connects as may not create tables (an owner/app role
+split), the apply refuses with `schema_owner_required`, creates nothing and
+keeps the approval: run the same apply command connected as the role that owns
+the schema. If the brain schema is newer than this gbrain client, upgrade
+gbrain first; the repair refuses rather than build an older table shape.
+
+Purges that failed on the missing cache before this fix may have been parked
+after five failures, and the nightly purge skips parked pages. After the
+upgrade, preview them with `gbrain pages purge-deleted --retry-parked
+--dry-run` and run it without `--dry-run` after the user agrees; doctor
+`purge_parked_pages` lists them.
+
+A missing table that holds user data is listed under `user_data_tables`; this
+repair never recreates it, because an empty table would hide that its rows are
+gone. Restore its rows from your own database backup (a `pg_dump` of the brain,
+or your host's point-in-time recovery) **before** you run `gbrain upgrade`,
+`gbrain apply-migrations` or `gbrain init --migrate-only`: those replay the base
+schema, recreate a base-schema table empty and clear this check while the rows
+stay lost. `gbrain backup restore` restores a whole brain into a new root, not
+one table.
The repair runs only when named and never on upgrade, `apply-migrations`,
`db-repair` or the maintenance cycle.
diff --git a/docs/guides/troubleshooting.md b/docs/guides/troubleshooting.md
index a29f751325..3efcadbf8d 100644
--- a/docs/guides/troubleshooting.md
+++ b/docs/guides/troubleshooting.md
@@ -12,7 +12,7 @@
| Symptom | Next step | Who acts | Consent | Verify |
|---|---|---|---|---|
-| The dream cycle's purge phase fails every night with `managed_purge_failed` (`42P01`, relation `query_cache` does not exist), or doctor `schema_missing_tables` warns | upgrade (#6911: the purge skips a missing rebuildable cache), then preview recreating it: `gbrain repair missing-tables` ([missing tables](repair.md#missing-tables)); apply the printed `--apply --expect <hash>` command | agent, after the user agrees | none | `gbrain doctor --only schema_missing_tables --json` reports ok |
+| The dream cycle's purge phase fails every night with `managed_purge_failed` (`42P01`, relation `query_cache` does not exist), or doctor `schema_missing_tables` warns | upgrade (#6911: the purge skips a missing rebuildable cache), then preview recreating it: `gbrain repair missing-tables` ([missing tables](repair.md#missing-tables)); apply the printed `--apply --expect <hash>` command. Pages parked by the earlier failures: `gbrain pages purge-deleted --retry-parked --dry-run`, then without `--dry-run` | agent, after the user agrees | `destructive` (the parked-page retry purges them) | `gbrain doctor --only schema_missing_tables --json` reports ok |
| A managed source's autopilot freshness `sync` jobs each land about one page, or `sources status` says `parked` while a sync job runs | upgrade (#6706: sync jobs drain to their deadline and count as the source's live drain), then restart `gbrain jobs work` / the supervisor so the worker loads the handler; a job result with `incomplete: true` names its follow-up (`continuation_job_id`) or the next step in `next` | agent | none | `gbrain sync status --source <id> --json` shows `live_job_id` or a cursor at `done`; `gbrain jobs get <id> --json` shows `outcome` |
| Doctor `sync_freshness` says a source has "no successful sync recorded" or "first sync running" | follow the check's `fix`: `first sync running` (code `sync_first_run_in_progress`, warn) means wait; `no successful sync recorded` (code `sync_no_successful_sync`, fail) names the last attempt and its `reason`: wait for a queued job, inspect holds (`gbrain sync status --source <id> --json`), or retry (`gbrain sync --source <id>`) ([details](#sync-freshness-no-successful-sync)) | agent | none | `gbrain doctor --only sync_freshness --json` |
| Recall returns conversation facts like "Date said …", "Attendees said …" or "Summary said …" | `gbrain repair conversation-labels` previews them ([conversation labels](repair.md#conversation-labels)); apply the printed command with `--yes` | agent, after the user agrees | `destructive` | `gbrain doctor --only conversation_label_facts --json` is ok |
diff --git a/llms-full.txt b/llms-full.txt
index 180d540aef..67a01be6b1 100644
--- a/llms-full.txt
+++ b/llms-full.txt
@@ -10723,7 +10723,7 @@ Source: https://raw.githubusercontent.com/garrytan/gbrain/master/docs/guides/tro
| Symptom | Next step | Who acts | Consent | Verify |
|---|---|---|---|---|
-| The dream cycle's purge phase fails every night with `managed_purge_failed` (`42P01`, relation `query_cache` does not exist), or doctor `schema_missing_tables` warns | upgrade (#6911: the purge skips a missing rebuildable cache), then preview recreating it: `gbrain repair missing-tables` ([missing tables](repair.md#missing-tables)); apply the printed `--apply --expect <hash>` command | agent, after the user agrees | none | `gbrain doctor --only schema_missing_tables --json` reports ok |
+| The dream cycle's purge phase fails every night with `managed_purge_failed` (`42P01`, relation `query_cache` does not exist), or doctor `schema_missing_tables` warns | upgrade (#6911: the purge skips a missing rebuildable cache), then preview recreating it: `gbrain repair missing-tables` ([missing tables](repair.md#missing-tables)); apply the printed `--apply --expect <hash>` command. Pages parked by the earlier failures: `gbrain pages purge-deleted --retry-parked --dry-run`, then without `--dry-run` | agent, after the user agrees | `destructive` (the parked-page retry purges them) | `gbrain doctor --only schema_missing_tables --json` reports ok |
| A managed source's autopilot freshness `sync` jobs each land about one page, or `sources status` says `parked` while a sync job runs | upgrade (#6706: sync jobs drain to their deadline and count as the source's live drain), then restart `gbrain jobs work` / the supervisor so the worker loads the handler; a job result with `incomplete: true` names its follow-up (`continuation_job_id`) or the next step in `next` | agent | none | `gbrain sync status --source <id> --json` shows `live_job_id` or a cursor at `done`; `gbrain jobs get <id> --json` shows `outcome` |
| Doctor `sync_freshness` says a source has "no successful sync recorded" or "first sync running" | follow the check's `fix`: `first sync running` (code `sync_first_run_in_progress`, warn) means wait; `no successful sync recorded` (code `sync_no_successful_sync`, fail) names the last attempt and its `reason`: wait for a queued job, inspect holds (`gbrain sync status --source <id> --json`), or retry (`gbrain sync --source <id>`) ([details](#sync-freshness-no-successful-sync)) | agent | none | `gbrain doctor --only sync_freshness --json` |
| Recall returns conversation facts like "Date said …", "Attendees said …" or "Summary said …" | `gbrain repair conversation-labels` previews them ([conversation labels](repair.md#conversation-labels)); apply the printed command with `--yes` | agent, after the user agrees | `destructive` | `gbrain doctor --only conversation_label_facts --json` is ok |
diff --git a/src/commands/doctor/checks/schema-health.ts b/src/commands/doctor/checks/schema-health.ts
index 4dcdd1addd..a869eec95a 100644
--- a/src/commands/doctor/checks/schema-health.ts
+++ b/src/commands/doctor/checks/schema-health.ts
@@ -254,14 +254,15 @@ 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));
- }
+ }
+ // 6c. #6911: tables the applied migrations created that the brain no longer has (the ledger cannot see a drop).
+ // Below head too: a missing cache that a pending migration alters wedges apply-migrations with 42P01.
+ 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'));
@@ -270,18 +271,30 @@ 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. */
+/**
+ * #6911: the schema_missing_tables verdict. A missing rebuildable cache warns with the repair preview; a missing
+ * user-data table fails, because base-schema replays (init --migrate-only, upgrade, apply-migrations) recreate it
+ * empty and clear this check while the rows stay lost; any other missing table 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 };
+ if (report.status === 'skipped') {
+ return { status: 'ok', message: `Skipped: the brain schema is v${report.version}, newer than this client (v${report.latest}); upgrade gbrain to check it.` };
+ }
+ if (!report.missing.length) {
+ return { status: 'ok', message: report.scope === 'all_tables' ? `All ${report.checked} table(s) the applied migrations create exist.`
+ : `All ${report.checked} rebuildable cache table(s) the applied migrations create exist.` };
+ }
+ const caches = report.missing.filter(m => m.recreatable);
+ const userData = report.missing.filter(m => !m.recreatable && m.loss_kind === 'user_data');
+ const other = report.missing.filter(m => !m.recreatable && m.loss_kind !== 'user_data');
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
+ const sentences = [`${report.missing.length} table(s) the applied migrations create are missing, and apply-migrations will not recreate them from the migrations that already ran`];
+ if (caches.length) sentences.push(`Rebuildable cache(s) ${names(caches)}: preview recreating them empty with gbrain repair missing-tables, then apply the printed command after the user agrees`);
+ if (userData.length) sentences.push(`${names(userData)} hold user data: restore their rows from a backup before running gbrain init --migrate-only, gbrain upgrade or apply-migrations, which recreate a base-schema table empty and clear this check while the rows stay lost (see ${MISSING_TABLES_DOCS})`);
+ if (other.length) sentences.push(`${names(other)} hold no user data: gbrain init --migrate-only recreates the ones the base schema defines; report any it does not (see ${MISSING_TABLES_DOCS})`);
+ return { status: userData.length ? 'fail' : 'warn', message: `${sentences.join('. ')}.`,
+ details: { missing: report.missing, checked: report.checked, scope: report.scope, docs: MISSING_TABLES_DOCS },
+ ...(caches.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 }) };
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 508aeeac65..f3a8e297ef 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -848,7 +848,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }
{ since: '0.60.287.0', text: 'A batch of page purges no longer reads the whole write journal once per page: the first queued purge of a source sweeps once for its own claims and those of the purges queued behind it, and each of those scans only the journal rows added since. Purge receipts\' `journal_sweep` gains `batch` (how many purges that sweep covered) and `watermark` (the sequence a purge started past; null when it swept from the start). A purge whose claims changed since the batch sweep sweeps on its own as before.' },
{ since: '0.60.287.0', text: 'The managed purge (autopilot purge phase, the purge job and `gbrain pages purge-deleted`) submits only while the writer has outstanding-request room (a background run stops at `persistence.capacity.background_pause_pct` of the cap). The rest is reported as `write_capacity_deferred` and counted in `capacity_deferred` (cycle: `purged_pages_capacity_deferred`, phase status warn) and is submitted by the next run, where it used to fail each page with `queue_capacity` (`managed_purge_failed`) and count each failure toward parking it.' },
{ since: '0.60.288.0', text: 'On a managed brain `gbrain sync --dry-run --json` adds a `convergence` object: a read-only shadow of the level-triggered sync (#6712 PR 4a) that classifies every path of the source the way the coming pass will (matched, import, held, drift and the other classes, each tagged with who acts: none, owner or repair), with predicted file_drift decisions after a read-only screen, `legacy_unverified` counts, deletes with the mass-delete valve verdict and up to 20 sample paths per class. `--redact-paths` turns the sample paths into sha256 prefixes and drops slugs, so the counts can be shared. `gbrain sync status --detail --json` adds the same object (`convergence`, `dry_run: true`) and `convergence_read`; a plain `sync status` skips that heavy read. Nothing is written or admitted, existing keys keep their meaning, and sync behaves exactly as before.' },
- { since: '0.60.289.0', text: 'A coordinated page purge or fact purge on a brain whose `query_cache` table is missing (schema at head) no longer fails with 42P01 (`managed_purge_failed` every night): the missing rebuildable cache is skipped, the page purge receipt lists it in `purge.missing_caches` and the store report shows `query_cache` `not_present` with reason `table_missing`. A missing table that holds user data still fails the purge. `gbrain doctor` adds `schema_missing_tables` (warn for a missing rebuildable cache, fail for a missing user-data table), and the explicit-only, preview-bound `gbrain repair missing-tables` recreates a missing rebuildable cache empty in its head shape after `--apply --expect <hash>`. The PGLite `--vacuum` receipt now says whether the VACUUM ran.' },
+ { since: '0.60.289.0', text: 'A coordinated page purge or fact purge on a brain whose `query_cache` table is missing (schema at head) no longer fails with 42P01 (`managed_purge_failed` every night): the missing rebuildable cache is skipped, the page purge receipt lists it in `purge.missing_caches` and the store report shows `query_cache` `not_present` with reason `table_missing`. A missing table that holds user data still fails the purge. `gbrain doctor` adds `schema_missing_tables` (warn for a missing rebuildable cache or a table without user data, fail for a missing user-data table; below head it checks the rebuildable caches, whose absence wedges apply-migrations), and the explicit-only, preview-bound `gbrain repair missing-tables` recreates a missing rebuildable cache empty in its head shape after `--apply --expect <hash>`, once per preview. The PGLite `--vacuum` receipt now says whether the VACUUM ran.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/facts/purge-verify.ts b/src/core/facts/purge-verify.ts
index 42dac650df..03d132c304 100644
--- a/src/core/facts/purge-verify.ts
+++ b/src/core/facts/purge-verify.ts
@@ -28,7 +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';
+import { 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';
@@ -262,7 +262,6 @@ 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 });
diff --git a/src/core/facts/purge.ts b/src/core/facts/purge.ts
index e90a156e88..3d38f59877 100644
--- a/src/core/facts/purge.ts
+++ b/src/core/facts/purge.ts
@@ -380,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 clearRebuildableCache(tx, 'query_cache', 'DELETE FROM query_cache RETURNING 1', [], []);
+ const cache = (await clearRebuildableCache(tx, 'query_cache')) ?? 0;
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 f7c75b73a5..cbe9b06e40 100644
--- a/src/core/persistence/page-purge.ts
+++ b/src/core/persistence/page-purge.ts
@@ -282,7 +282,9 @@ export async function purgePageInTransaction(tx: BrainEngine, row: WriteRequest,
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]);
const missingCaches: string[] = [];
- removed.query_cache = await clearRebuildableCache(tx, 'query_cache', 'DELETE FROM query_cache RETURNING 1', [], missingCaches);
+ const cleared = await clearRebuildableCache(tx, 'query_cache');
+ if (cleared === null) missingCaches.push('query_cache');
+ removed.query_cache = cleared ?? 0;
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]);
diff --git a/src/core/persistence/rebuildable-cache.ts b/src/core/persistence/rebuildable-cache.ts
index 2f48218601..236e04ce87 100644
--- a/src/core/persistence/rebuildable-cache.ts
+++ b/src/core/persistence/rebuildable-cache.ts
@@ -20,12 +20,9 @@ export async function relationExists(engine: Pick<BrainEngine, 'executeRaw'>, ta
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> {
+/** Empty a rebuildable cache and return the rows removed, or null when the cache table does not exist. */
+export async function clearRebuildableCache(tx: Pick<BrainEngine, 'executeRaw'>, table: string): Promise<number | null> {
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;
+ if (!await relationExists(tx, table)) return null;
+ return (await tx.executeRaw(`DELETE FROM ${table} RETURNING 1`)).length;
}
diff --git a/src/core/repair/missing-tables.ts b/src/core/repair/missing-tables.ts
index 35f260ea87..87fb897ef5 100644
--- a/src/core/repair/missing-tables.ts
+++ b/src/core/repair/missing-tables.ts
@@ -1,72 +1,98 @@
/**
* `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.
+ * created but the brain no longer has (`doctor` check schema_missing_tables). The schema version already covers its
+ * creating migration, so `apply-migrations` never runs it again, and a later migration that touches the cache fails
+ * with 42P01. Only tables the graduation inventory classifies `rebuild` and that have a recreate step qualify; any
+ * other missing table is listed for the operator, never recreated here.
*
* 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.
+ * exactly that set once; the approval is retired with the last table. It never runs on upgrade, apply-migrations,
+ * db-repair or the maintenance cycle. DDL only (IF NOT EXISTS) under the migration lock timeout; no journal admission
+ * and no user data changes. Brain-wide.
*/
+import { LATEST_VERSION } from '../migrate.ts';
import { OperationError } from '../ops/contract.ts';
+import { resolveSchemaLockTimeoutMs, schemaLockBlockedError } from '../postgres-engine/schema-lock-timeout.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 { isLockTimeoutError } from '../retry-matcher.ts';
+import { readMissingTables, recreateStep } 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' });
+const DOCS = 'docs/guides/repair.md#missing-tables';
+type TableItem = RepairItem & { hash?: string; last?: boolean };
+const toItem = (table: string, position: number, hash?: string, last?: boolean): TableItem => ({ cursor: { phase: 0, id: position + 1 }, source_id: '(brain)',
+ slug: table, chars: 0, action: 'recreate_empty', ...(hash ? { hash, last } : {}) });
+const CLIENT_BEHIND = (version: number) => `The brain schema is at v${version}, newer than this gbrain client (v${LATEST_VERSION}); upgrade gbrain, then preview again.`;
export const missingTablesRepair: RepairHandler = {
kind: 'missing-tables',
publication: 'projection',
embeds: false,
async plan(engine, scope, after, opts = { apply: false }): Promise<RepairPlan> {
+ const report = await readMissingTables(engine);
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');
+ `Preview first: ${PREVIEW} — then run the apply command it prints: ${PREVIEW} --apply --expect <preview-hash>`, DOCS);
+ if (report.status === 'skipped') throw new OperationError('invalid_params', CLIENT_BEHIND(report.version), `Upgrade gbrain, then run ${PREVIEW} again.`, DOCS);
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));
+ const items = tables.map((table, index) => toItem(table, index, opts.expect, index === tables.length - 1)).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.`] };
- }
+ if (report.status === 'skipped') return { items: [], residuals: {}, warnings: [CLIENT_BEHIND(report.version)] };
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 });
+ const userData = report.missing.filter(m => !m.recreatable && m.loss_kind === 'user_data').map(m => m.table);
+ const other = report.missing.filter(m => !m.recreatable && m.loss_kind !== 'user_data').map(m => m.table);
+ const hash = previewHash({ kind: 'missing-tables-v1', brain_id: scope.brain_id, latest: LATEST_VERSION, 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) } };
+ return { items: tables.map((table, index) => toItem(table, index)), ...(tables.length ? { preview_hash: hash } : {}),
+ residuals: { ...(userData.length ? { user_data_tables: userData.length } : {}), ...(other.length ? { other_tables: other.length } : {}) },
+ details: { checked: report.checked, scope: report.scope, recreate: tables, user_data_tables: userData, other_tables: other } };
},
- async apply(ctx, item, opts) {
- const recreate = RECREATE[item.slug];
- if (!recreate) return { applied: false, outcome: 'refused', reason: 'not_rebuildable' };
- 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.
- try {
- await ctx.engine.transaction(tx => recreate(tx));
- } catch (error) {
- if ((error as { code?: string }).code !== '42501') throw error;
- throw new OperationError('schema_owner_required', `This database role may not create ${item.slug}, so nothing was recreated.`,
- `Connect as the role that owns the brain tables (the one apply-migrations uses) and run: ${PREVIEW} --apply --expect ${opts?.expect ?? '<preview-hash>'}`, 'docs/guides/repair.md#missing-tables');
- }
- 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: existed ? 'completed' : 'recreated' };
+ async apply(ctx, entry, opts) {
+ const item = entry as TableItem;
+ const outcome = await (async () => {
+ const recreate = recreateStep(item.slug);
+ if (!recreate) return { applied: false, outcome: 'refused', reason: 'not_rebuildable' } as const;
+ if (await relationExists(ctx.engine, item.slug)) return { applied: false, outcome: 'already_present' } as const;
+ try {
+ await ctx.engine.transaction(async tx => {
+ if (ctx.engine.kind === 'postgres') {
+ await tx.executeRaw("SET LOCAL statement_timeout = '600000'");
+ await tx.executeRaw(`SET LOCAL lock_timeout = '${resolveSchemaLockTimeoutMs()}ms'`);
+ }
+ await recreate(tx);
+ });
+ } catch (error) {
+ const code = (error as { code?: string }).code;
+ if (code === '42501') {
+ throw new OperationError('schema_owner_required', `This database role may not create ${item.slug}, so nothing was recreated.`,
+ `Connect as the role that owns the brain tables (the one apply-migrations uses) and run: ${PREVIEW} --apply --expect ${opts?.expect ?? '<preview-hash>'}`, DOCS);
+ }
+ if ((code === '23505' || code === '42P07') && await relationExists(ctx.engine, item.slug)) return { applied: false, outcome: 'already_present' };
+ if (ctx.engine.kind === 'postgres' && isLockTimeoutError(error)) {
+ throw schemaLockBlockedError({ step: `repair missing-tables (${item.slug})`, timeoutMs: resolveSchemaLockTimeoutMs(), sessions: null, sampledDuringWait: false });
+ }
+ throw error;
+ }
+ 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' };
+ })();
+ if (item.last && item.hash) await clearApprovedSet(ctx.engine, { command: 'missing-tables', hash: item.hash });
+ return outcome;
},
render(details) {
- const d = details as { checked?: number; recreate?: string[]; user_data_tables?: string[] };
+ const d = details as { checked?: number; recreate?: string[]; user_data_tables?: string[]; other_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`),
+ ...(d.user_data_tables ?? []).map(t => ` not recreated: ${t} holds user data; restore its rows from a backup before any upgrade or migrate run (${DOCS})`),
+ ...(d.other_tables ?? []).map(t => ` not recreated: ${t} holds no user data; gbrain init --migrate-only recreates it if the base schema defines it`),
];
},
};
diff --git a/src/core/schema-missing-tables.ts b/src/core/schema-missing-tables.ts
index 665b4d66eb..6ce39a126c 100644
--- a/src/core/schema-missing-tables.ts
+++ b/src/core/schema-missing-tables.ts
@@ -14,25 +14,34 @@ 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';
+import type { LossKind } from './persistence/engine-graduation.types.ts';
export interface MissingTable {
table: string;
/** The graduation inventory class: `rebuild` tables hold only regenerable cache rows. */
inventory_class: string;
+ /** The graduation inventory loss kind: only `user_data` tables hold rows nothing can regenerate. */
+ loss_kind: LossKind;
/** `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 };
+/**
+ * `checked`: at head every table a fully migrated brain has; below head only the rebuildable caches whose creating
+ * migration already ran (a later migration that touches the cache would otherwise fail with 42P01 and wedge the
+ * upgrade). `skipped`: the brain was migrated by a newer client, whose tables this one does not know.
+ */
+export type MissingTablesReport = { status: 'checked'; scope: 'all_tables' | 'rebuildable_caches'; checked: number; missing: MissingTable[] }
+ | { status: 'skipped'; reason: 'client_behind'; 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.
+ * test/schema-missing-tables.test.ts compares each recreated table's columns and indexes with the migrated brain's on
+ * both engines, 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>>> = {
+const RECREATE: Readonly<Record<string, (engine: BrainEngine) => Promise<void>>> = {
query_cache: async 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.
@@ -46,6 +55,17 @@ export const RECREATE: Readonly<Record<string, (engine: BrainEngine) => Promise<
code_traversal_cache: async engine => { await engine.runMigration(59, v059.sql); },
};
+/** The migration that first creates each recreatable cache; below it the table is not expected yet. */
+const CREATED_BY: Readonly<Record<string, number>> = { query_cache: 55, code_traversal_cache: 59 };
+
+/** The recreate step for a rebuildable cache, or undefined for any other name. */
+export function recreateStep(table: string): ((engine: BrainEngine) => Promise<void>) | undefined {
+ return Object.hasOwn(RECREATE, table) && isRebuildableCache(table) ? RECREATE[table] : undefined;
+}
+
+/** The tables `gbrain repair missing-tables` can recreate. */
+export const RECREATABLE_TABLES: readonly string[] = Object.keys(RECREATE);
+
/** 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)
@@ -61,11 +81,15 @@ function queryCacheDdl(type: 'vector' | 'halfvec', dims: number): string {
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]);
+ if (version > LATEST_VERSION) return { status: 'skipped', reason: 'client_behind', version, latest: LATEST_VERSION };
+ const atHead = version === LATEST_VERSION;
+ const expected = GRADUATION_INVENTORY.entries.filter(e => e.kind === 'table' && e.engines[engine.kind]
+ && (atHead || (recreateStep(e.relation) !== undefined && version >= CREATED_BY[e.relation]!)));
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 })) };
+ return { status: 'checked', scope: atHead ? 'all_tables' : 'rebuildable_caches', checked: expected.length, missing: rows.map(({ relation }) => {
+ const entry = byName.get(relation)!;
+ return { table: relation, inventory_class: entry.class, loss_kind: entry.lossKind, recreatable: recreateStep(relation) !== undefined };
+ }) };
}
diff --git a/test/fixtures/goldens/exports/types.json b/test/fixtures/goldens/exports/types.json
index c11172609e..057238ccb2 100644
--- a/test/fixtures/goldens/exports/types.json
+++ b/test/fixtures/goldens/exports/types.json
@@ -6334,7 +6334,7 @@
{
"kind": "class",
"members": [
- "canonical?: \"unknown\" | \"keyword_candidates_incomplete\" | \"projection_pending\" | \"timeout\" | \"rate_limited\" | \"embedding_disabled\" | \"writer_lock_unavailable\" | \"writer_pool_capacity\" | \"owner_unavailable\" | \"recovery_required\" | \"queue_capacity\" | \"write_quota_exhausted\" | \"write_quota_insufficient\" | \"write_capacity_backpressure\" | \"revision_required\" | \"revision_conflict\" | \"idempotency_conflict\" | \"source_changed\" | \"write_pending\" | \"storage_error\" | \"cancelled\" | \"permission_denied\" | \"scope_denied\" | \"invalid_params\" | \"not_found\" | \"page_not_found\" | \"page_identity_changed\" | \"write_claim_lost\" | \"request_too_large\" | \"response_too_large\" | \"writer_registration_required\" | \"writer_identity_invalid\" | \"writer_not_initialized\" | \"writer_coordinator_required\" | \"fact_already_expired\" | \"source_writeback_required\" | \"unsupported_mutation_protocol\" | \"writer_upgrade_required\" | \"writer_not_quiesced\" | \"skill_bundle_required\" | \"take_row_collision\" | \"invalid_source_uri\" | \"writer_admin_locked\" | \"connector_account_changed\" | \"connector_intent_outdated\" | \"checkpoint_validation_timeout\" | \"invalid_connector_text\" | \"connector_holds_exhausted\" | \"connector_fence_below_timeline\" | \"core_budget_exceeded\" | \"core_mark_owner_only\" | \"core_remote_edit_refused\" | \"core_delete_owner_only\" | \"timeline_rows_would_be_removed\" | \"purged_content\" | \"preparation_stalled\" | \"fence_unrenderable\" | \"write_outcome_unknown\" | \"embedding_failed\" | \"bucket_not_found\" | \"database_error\" | \"unknown_transport\" | \"extraction_failed\" | \"fact_not_found\" | \"provenance_required\" | \"unavailable\" | \"budget_unsatisfiable\" | \"embedding_budget_below_worst_case\" | \"access_command_failed\" | \"access_denied_test_user\" | \"access_env_missing\" | \"acknowledgment_unavailable\" | \"admin_policy_enforced\" | \"ambient_capture_off\" | \"ambiguous_id\" | \"ambiguous_ref\" | \"ambiguous_skill\" | \"answer_not_yours\" | \"answer_pending\" | \"answer_unavailable\" | \"api_not_enabled\" | \"approval_required\" | \"autopilot_job_owned_by_other_brain\" | \"body_staging_expired\" | \"budget_below_recent_runtime\" | \"backup_dump_failed\" | \"backup_too_large\" | \"belief_coverage_required\" | \"belief_stale_preparation\" | \"benchmark_duplicate_task_id\" | \"benchmark_empty\" | \"benchmark_exists\" | \"benchmark_judge_llm_no_rubric\" | \"benchmark_judge_qrels_no_expected\" | \"benchmark_judge_rule_no_checks\" | \"benchmark_judge_unknown_kind\" | \"benchmark_malformed\" | \"benchmark_missing_judge\" | \"benchmark_missing_task\" | \"benchmark_missing_task_id\" | \"benchmark_not_found\" | \"benchmark_rule_check_bad_arg\" | \"benchmark_rule_check_malformed\" | \"benchmark_rule_check_unknown_op\" | \"bootstrap_cleanup_pending\" | \"bootstrap_empty\" | \"bootstrap_pending_review\" | \"bridge_ownership_conflict\" | \"coverage_from\" | \"coverage_gap\" | \"clock_mismatch\" | \"known_as_of_unproven\" | \"cache_quota_exceeded\" | \"calendar_unreadable\" | \"capacity_paused\" | \"catalog_capacity_exceeded\" | \"catalog_unavailable\" | \"changed_since_preview\" | \"chronicle_skipped\" | \"page_body_segmented\" | \"no_pricing\" | \"checkpoint_missing\" | \"claim_already_used\" | \"client_json_unreadable\" | \"client_json_wrong_type\" | \"client_shape_invalid\" | \"code_callees_requires_symbol\" | \"code_callers_requires_symbol\" | \"code_def_requires_symbol\" | \"code_refs_requires_symbol\" | \"code_reused\" | \"colon_slug_windows_write_through\" | \"command_failed\" | \"commit_lock_busy\" | \"commit_paths_invalid\" | \"concurrent_write\" | \"config_error\" | \"confirmation_required\" | \"conflicting_source_scope\" | \"connection_lost\" | \"chunkless_pages_healable\" | \"consent_required\" | \"consent_timeout\" | \"consumers_without_heartbeat\" | \"content_repair_needs_human\" | \"content_rejected\" | \"continuation_unproven\" | \"corpus_chat_unavailable\" | \"corpus_window_backoff\" | \"corpus_window_dead_lettered\" | \"convergence_read_failed\" | \"cost_cap_exceeded\" | \"cost_preview_requires_yes\" | \"cursor_incarnation_retired\" | \"cycle_failed\" | \"d_sel_too_small\" | \"delta_cursor_upgrade_required\" | \"deleted_page_chunks_overdue\" | \"demo_graph_failed\" | \"demo_import_failed\" | \"demo_verification_failed\" | \"derived_cap_exhausted\" | \"destination_not_ready\" | \"drain_stalled\" | \"managed_sync_not_moving\" | \"dream_breaker_tripped\" | \"dirty_tree\" | \"doctor_tier_unavailable\" | \"effect_not_failed\" | \"embed_backfill_stalled\" | \"embedding_auth_failed\" | \"embedding_configuration\" | \"embedding_identity_unqualified\" | \"embedding_model_mismatch\" | \"embedding_plane_split\" | \"embedding_state_unknown\" | \"embedding_storage_unavailable\" | \"embedding_unavailable\" | \"embedding_unconfigured\" | \"embedding_width_mismatch\" | \"engine_graduated\" | \"entity_types_unavailable\" | \"eval_suite_unwired\" | \"export_limit\" | \"extractor_identity_mismatch\" | \"fact_withdrawn\" | \"fact_rows_collide\" | \"facts_absorb_write_refused\" | \"facts_backstop_skipped\" | \"facts_drain_deferred\" | \"facts_drain_job_failed\" | \"facts_payload_expired\" | \"feedback_disabled\" | \"feedback_not_authorized\" | \"fetch_failed\" | \"fix_not_writable\" | \"file_drift\" | \"file_removed_during_scan\" | \"file_too_large\" | \"follow_approval_required\" | \"forget_requires_owner\" | \"frontmatter_slug_conflict\" | \"full_resync_required\" | \"gate_failed\" | \"ghost_mass_delete_refused\" | \"ghost_storage_unknown\" | \"git_branch_unborn\" | \"git_durability_not_enabled\" | \"git_checkout_required\" | \"git_detached_head\" | \"git_index_locked\" | \"git_index_stale\" | \"git_target_pending\" | \"git_operation_in_progress\" | \"git_push_unavailable\" | \"git_target_unsafe\" | \"git_unavailable\" | \"graduation_drain_timeout\" | \"graduation_embedding_dimension_mismatch\" | \"graduation_foreign_host_binding\" | \"graduation_in_progress\" | \"graduation_interrupted\" | \"graduation_rollback_writes_lost\" | \"graduation_source_writer_held\" | \"graduation_split_brain\" | \"graduation_target_auth_failed\" | \"graduation_target_ddl_unreachable\" | \"graduation_target_not_empty\" | \"graduation_target_unsupported\" | \"graduation_unclassified_table\" | \"graduation_unsupported_platform\" | \"graduation_verify_failed\" | \"graph_incomplete\" | \"host_identity_mismatch\" | \"harness_hook_duplicates\" | \"harness_hook_unowned\" | \"head_blocked\" | \"held_failed\" | \"held_out_overlaps_benchmark\" | \"held_out_required_for_bundled\" | \"independent_principal_required\" | \"insufficient_scope\" | \"integrate_conflict\" | \"internal\" | \"internal_error\" | \"interrupted\" | \"invalid_acknowledgment\" | \"invalid_client\" | \"invalid_fence\" | \"unclosed_ambiguous_tail\" | \"tail_exposure_approval\" | \"sync_in_progress\" | \"invalid_frontmatter\" | \"invalid_grant_clock_skew\" | \"invalid_grant_revoked\" | \"invalid_grant_testing_expiry\" | \"invalid_rating\" | \"invalid_receipt\" | \"invalid_receipt_transition\" | \"invalid_request\" | \"invalid_source\" | \"invalid_source_pin\" | \"invalid_token\" | \"invalid_write_wait\" | \"ipc_path_too_long\" | \"legacy_job_selection_invalid\" | \"legacy_jobs_active\" | \"local_conflict\" | \"lock_busy\" | \"loops_extraction_skipped\" | \"maintenance_backpressure\" | \"maintenance_lock_busy\" | \"managed_failure_unsettled\" | \"managed_remedy_unavailable\" | \"merge_recommended\" | \"movement_unknown\" | \"managed_sync_flag_refused\" | \"managed_pull_skipped\" | \"manual_only_skipped\" | \"membership_inactive\" | \"membership_not_found\" | \"method_not_allowed\" | \"migration_lease_lost\" | \"migration_declined\" | \"migration_failed\" | \"migrations_pending\" | \"migrations_running\" | \"missing_source_scope\" | \"missing_source_value\" | \"models_strict_violation\" | \"no_refresh_token\" | \"no_routing_eval\" | \"no_skill_md\" | \"no_worker\" | \"no_worker_surface\" | \"not_a_git_repo\" | \"not_owner_host\" | \"not_connected\" | \"no_brain\" | \"overlapping_path\" | \"page_projection_conflict\" | \"page_shrink_refused\" | \"page_too_large_for_inline\" | \"parse_error\" | \"parser_regression\" | \"pasted_wrong_url\" | \"payload_too_large\" | \"pattern_claims_pending\" | \"patterns_min_interval\" | \"pending_verify\" | \"pending_writes\" | \"persistence_restart_required\" | \"pool_inflight_over_budget\" | \"deep_health_probe_failed\" | \"serve_self_exit_suppressed\" | \"serve_unhealthy_exit\" | \"persistence_write_stall\" | \"push_unconfirmed\" | \"schema_lock_blocked\" | \"pg_connection_recovery_failed\" | \"pg_connection_stuck\" | \"pg_pool_stalled\" | \"pg_statement_build_failed\" | \"pglite_busy\" | \"pglite_vector_index_too_large\" | \"plan_output_failed\" | \"plan_stale\" | \"port_in_use\" | \"preview_changed\" | \"profile_incompatible\" | \"projection_owner_resident\" | \"knock_on_exhausted\" | \"keyword_skipped_after_timeout\" | \"publication_pending\" | \"purge_blocked_pending_recovery\" | \"purge_lookup_timeout\" | \"purge_mirror_unwritable\" | \"question_not_found\" | \"question_owner_only\" | \"read_budget_exhausted\" | \"receipt_conflict\" | \"receipt_fence_changed\" | \"receipt_fence_required\" | \"receipt_identity_mismatch\" | \"pat_file_unreadable\" | \"reconcile_read_incomplete\" | \"redirect_uri_mismatch\" | \"ref_not_in_answer\" | \"refresh_dirty\" | \"refresh_diverged\" | \"refresh_drain_timeout\" | \"refresh_no_upstream\" | \"refresh_not_managed\" | \"refresh_not_owner\" | \"refresh_source_changed\" | \"relay_disabled\" | \"relay_session_expired\" | \"relay_unreachable\" | \"rename_held\" | \"request_already_submitted\" | \"requirements_changed\" | \"requires_local_engine\" | \"resume_spec_mismatch\" | \"result_too_large\" | \"revision_changed\" | \"revision_unavailable\" | \"scope_missing\" | \"search_cursor_requires_keyword\" | \"search_mode_local_only\" | \"scorecard_group_by_local_only\" | \"search_offset_over_cap\" | \"serve_build_drift\" | \"serve_port_in_use\" | \"serve_status_only\" | \"setup_harness_unsupported\" | \"setup_hosted_connection\" | \"setup_owner_conflict\" | \"shared_skills_unavailable\" | \"shared_skills_unsupported\" | \"skill_asset_not_found\" | \"skill_candidate_invalid\" | \"skill_not_found\" | \"skill_retention_capacity\" | \"skill_unavailable\" | \"slug_page_mismatch\" | \"slug_root_mode_mismatch\" | \"source_binding_required\" | \"source_id_taken\" | \"source_mismatch\" | \"source_not_ready\" | \"source_profile_no_backfill\" | \"source_referenced\" | \"source_root_conflict\" | \"split_bad_ratio\" | \"split_unparseable\" | \"stale_unavailable\" | \"state_mismatch\" | \"sync_not_applicable\" | \"sync_drain_lease_held\" | \"sync_first_run_in_progress\" | \"sync_no_successful_sync\" | \"sync_cursor_replaced\" | \"sync_parser_regression\" | \"target_escape\" | \"timeline_comment_markup\" | \"topology_change_required\" | \"transcript_secret_exposure\" | \"triage_unreliable_backoff\" | \"trust_raise_refused\" | \"two_consumers_on_host\" | \"trusted_local_only\" | \"unexpected_file_bytes\" | \"unexpected_staging_bytes\" | \"unknown_command\" | \"unknown_flag\" | \"unknown_method\" | \"unknown_source\" | \"unknown_tool\" | \"unpriced_model\" | \"unmanaged_database_path\" | \"unmanaged_path\" | \"unsupported_export_data\" | \"upstream\" | \"verification_failed\" | \"withdrawal_capacity\" | \"withdrawal_provenance\" | \"write_capacity_low\" | \"write_gate_rejected\" | \"write_held\" | \"worktree_dirty\" | \"writer_admin_intent_required\" | \"writer_admin_state_changed\" | \"writer_busy\" | \"writer_identity_publish_failed\" | \"writer_manifest_mismatch\" | \"writer_manifest_rescope_required\" | \"writer_manifest_unsafe\" | \"writer_regrant_required\" | \"writer_transfer_conflict\" | \"writer_transfer_required\" | \"wrong_account_consented\" | \"schema_pack_too_large\" | \"schema_pack_emit_mismatch\" | undefined",
+ "canonical?: \"unknown\" | \"keyword_candidates_incomplete\" | \"projection_pending\" | \"timeout\" | \"rate_limited\" | \"embedding_disabled\" | \"writer_lock_unavailable\" | \"writer_pool_capacity\" | \"owner_unavailable\" | \"recovery_required\" | \"queue_capacity\" | \"write_quota_exhausted\" | \"write_quota_insufficient\" | \"write_capacity_backpressure\" | \"revision_required\" | \"revision_conflict\" | \"idempotency_conflict\" | \"source_changed\" | \"write_pending\" | \"storage_error\" | \"cancelled\" | \"permission_denied\" | \"scope_denied\" | \"invalid_params\" | \"not_found\" | \"page_not_found\" | \"page_identity_changed\" | \"write_claim_lost\" | \"request_too_large\" | \"response_too_large\" | \"writer_registration_required\" | \"writer_identity_invalid\" | \"writer_not_initialized\" | \"writer_coordinator_required\" | \"fact_already_expired\" | \"source_writeback_required\" | \"unsupported_mutation_protocol\" | \"writer_upgrade_required\" | \"writer_not_quiesced\" | \"skill_bundle_required\" | \"take_row_collision\" | \"invalid_source_uri\" | \"writer_admin_locked\" | \"connector_account_changed\" | \"connector_intent_outdated\" | \"checkpoint_validation_timeout\" | \"invalid_connector_text\" | \"connector_holds_exhausted\" | \"connector_fence_below_timeline\" | \"core_budget_exceeded\" | \"core_mark_owner_only\" | \"core_remote_edit_refused\" | \"core_delete_owner_only\" | \"timeline_rows_would_be_removed\" | \"purged_content\" | \"preparation_stalled\" | \"fence_unrenderable\" | \"write_outcome_unknown\" | \"embedding_failed\" | \"bucket_not_found\" | \"database_error\" | \"unknown_transport\" | \"extraction_failed\" | \"fact_not_found\" | \"provenance_required\" | \"unavailable\" | \"budget_unsatisfiable\" | \"embedding_budget_below_worst_case\" | \"access_command_failed\" | \"access_denied_test_user\" | \"access_env_missing\" | \"acknowledgment_unavailable\" | \"admin_policy_enforced\" | \"ambient_capture_off\" | \"ambiguous_id\" | \"ambiguous_ref\" | \"ambiguous_skill\" | \"answer_not_yours\" | \"answer_pending\" | \"answer_unavailable\" | \"api_not_enabled\" | \"approval_required\" | \"autopilot_job_owned_by_other_brain\" | \"body_staging_expired\" | \"budget_below_recent_runtime\" | \"backup_dump_failed\" | \"backup_too_large\" | \"belief_coverage_required\" | \"belief_stale_preparation\" | \"benchmark_duplicate_task_id\" | \"benchmark_empty\" | \"benchmark_exists\" | \"benchmark_judge_llm_no_rubric\" | \"benchmark_judge_qrels_no_expected\" | \"benchmark_judge_rule_no_checks\" | \"benchmark_judge_unknown_kind\" | \"benchmark_malformed\" | \"benchmark_missing_judge\" | \"benchmark_missing_task\" | \"benchmark_missing_task_id\" | \"benchmark_not_found\" | \"benchmark_rule_check_bad_arg\" | \"benchmark_rule_check_malformed\" | \"benchmark_rule_check_unknown_op\" | \"bootstrap_cleanup_pending\" | \"bootstrap_empty\" | \"bootstrap_pending_review\" | \"bridge_ownership_conflict\" | \"coverage_from\" | \"coverage_gap\" | \"clock_mismatch\" | \"known_as_of_unproven\" | \"cache_quota_exceeded\" | \"calendar_unreadable\" | \"capacity_paused\" | \"catalog_capacity_exceeded\" | \"catalog_unavailable\" | \"changed_since_preview\" | \"chronicle_skipped\" | \"page_body_segmented\" | \"no_pricing\" | \"checkpoint_missing\" | \"claim_already_used\" | \"client_json_unreadable\" | \"client_json_wrong_type\" | \"client_shape_invalid\" | \"code_callees_requires_symbol\" | \"code_callers_requires_symbol\" | \"code_def_requires_symbol\" | \"code_refs_requires_symbol\" | \"code_reused\" | \"colon_slug_windows_write_through\" | \"command_failed\" | \"commit_lock_busy\" | \"commit_paths_invalid\" | \"concurrent_write\" | \"config_error\" | \"confirmation_required\" | \"conflicting_source_scope\" | \"connection_lost\" | \"chunkless_pages_healable\" | \"consent_required\" | \"consent_timeout\" | \"consumers_without_heartbeat\" | \"content_repair_needs_human\" | \"content_rejected\" | \"continuation_unproven\" | \"corpus_chat_unavailable\" | \"corpus_window_backoff\" | \"corpus_window_dead_lettered\" | \"convergence_read_failed\" | \"cost_cap_exceeded\" | \"cost_preview_requires_yes\" | \"cursor_incarnation_retired\" | \"cycle_failed\" | \"d_sel_too_small\" | \"delta_cursor_upgrade_required\" | \"deleted_page_chunks_overdue\" | \"demo_graph_failed\" | \"demo_import_failed\" | \"demo_verification_failed\" | \"derived_cap_exhausted\" | \"destination_not_ready\" | \"drain_stalled\" | \"managed_sync_not_moving\" | \"dream_breaker_tripped\" | \"dirty_tree\" | \"doctor_tier_unavailable\" | \"effect_not_failed\" | \"embed_backfill_stalled\" | \"embedding_auth_failed\" | \"embedding_configuration\" | \"embedding_identity_unqualified\" | \"embedding_model_mismatch\" | \"embedding_plane_split\" | \"embedding_state_unknown\" | \"embedding_storage_unavailable\" | \"embedding_unavailable\" | \"embedding_unconfigured\" | \"embedding_width_mismatch\" | \"engine_graduated\" | \"entity_types_unavailable\" | \"eval_suite_unwired\" | \"export_limit\" | \"extractor_identity_mismatch\" | \"fact_withdrawn\" | \"fact_rows_collide\" | \"facts_absorb_write_refused\" | \"facts_backstop_skipped\" | \"facts_drain_deferred\" | \"facts_drain_job_failed\" | \"facts_payload_expired\" | \"feedback_disabled\" | \"feedback_not_authorized\" | \"fetch_failed\" | \"fix_not_writable\" | \"file_drift\" | \"file_removed_during_scan\" | \"file_too_large\" | \"follow_approval_required\" | \"forget_requires_owner\" | \"frontmatter_slug_conflict\" | \"full_resync_required\" | \"gate_failed\" | \"ghost_mass_delete_refused\" | \"ghost_storage_unknown\" | \"git_branch_unborn\" | \"git_durability_not_enabled\" | \"git_checkout_required\" | \"git_detached_head\" | \"git_index_locked\" | \"git_index_stale\" | \"git_target_pending\" | \"git_operation_in_progress\" | \"git_push_unavailable\" | \"git_target_unsafe\" | \"git_unavailable\" | \"graduation_drain_timeout\" | \"graduation_embedding_dimension_mismatch\" | \"graduation_foreign_host_binding\" | \"graduation_in_progress\" | \"graduation_interrupted\" | \"graduation_rollback_writes_lost\" | \"graduation_source_writer_held\" | \"graduation_split_brain\" | \"graduation_target_auth_failed\" | \"graduation_target_ddl_unreachable\" | \"graduation_target_not_empty\" | \"graduation_target_unsupported\" | \"graduation_unclassified_table\" | \"graduation_unsupported_platform\" | \"graduation_verify_failed\" | \"graph_incomplete\" | \"host_identity_mismatch\" | \"harness_hook_duplicates\" | \"harness_hook_unowned\" | \"head_blocked\" | \"held_failed\" | \"held_out_overlaps_benchmark\" | \"held_out_required_for_bundled\" | \"independent_principal_required\" | \"insufficient_scope\" | \"integrate_conflict\" | \"internal\" | \"internal_error\" | \"interrupted\" | \"invalid_acknowledgment\" | \"invalid_client\" | \"invalid_fence\" | \"unclosed_ambiguous_tail\" | \"tail_exposure_approval\" | \"sync_in_progress\" | \"invalid_frontmatter\" | \"invalid_grant_clock_skew\" | \"invalid_grant_revoked\" | \"invalid_grant_testing_expiry\" | \"invalid_rating\" | \"invalid_receipt\" | \"invalid_receipt_transition\" | \"invalid_request\" | \"invalid_source\" | \"invalid_source_pin\" | \"invalid_token\" | \"invalid_write_wait\" | \"ipc_path_too_long\" | \"legacy_job_selection_invalid\" | \"legacy_jobs_active\" | \"local_conflict\" | \"lock_busy\" | \"loops_extraction_skipped\" | \"maintenance_backpressure\" | \"maintenance_lock_busy\" | \"managed_failure_unsettled\" | \"managed_remedy_unavailable\" | \"merge_recommended\" | \"movement_unknown\" | \"managed_sync_flag_refused\" | \"managed_pull_skipped\" | \"manual_only_skipped\" | \"membership_inactive\" | \"membership_not_found\" | \"method_not_allowed\" | \"migration_lease_lost\" | \"migration_declined\" | \"migration_failed\" | \"migrations_pending\" | \"migrations_running\" | \"missing_source_scope\" | \"missing_source_value\" | \"models_strict_violation\" | \"no_refresh_token\" | \"no_routing_eval\" | \"no_skill_md\" | \"no_worker\" | \"no_worker_surface\" | \"not_a_git_repo\" | \"not_owner_host\" | \"not_connected\" | \"no_brain\" | \"overlapping_path\" | \"page_projection_conflict\" | \"page_shrink_refused\" | \"page_too_large_for_inline\" | \"parse_error\" | \"parser_regression\" | \"pasted_wrong_url\" | \"payload_too_large\" | \"pattern_claims_pending\" | \"patterns_min_interval\" | \"pending_verify\" | \"pending_writes\" | \"persistence_restart_required\" | \"pool_inflight_over_budget\" | \"deep_health_probe_failed\" | \"serve_self_exit_suppressed\" | \"serve_unhealthy_exit\" | \"persistence_write_stall\" | \"push_unconfirmed\" | \"schema_lock_blocked\" | \"pg_connection_recovery_failed\" | \"pg_connection_stuck\" | \"pg_pool_stalled\" | \"pg_statement_build_failed\" | \"pglite_busy\" | \"pglite_vector_index_too_large\" | \"plan_output_failed\" | \"plan_stale\" | \"port_in_use\" | \"preview_changed\" | \"profile_incompatible\" | \"projection_owner_resident\" | \"knock_on_exhausted\" | \"keyword_skipped_after_timeout\" | \"publication_pending\" | \"purge_blocked_pending_recovery\" | \"purge_lookup_timeout\" | \"purge_mirror_unwritable\" | \"question_not_found\" | \"question_owner_only\" | \"read_budget_exhausted\" | \"receipt_conflict\" | \"receipt_fence_changed\" | \"receipt_fence_required\" | \"receipt_identity_mismatch\" | \"pat_file_unreadable\" | \"reconcile_read_incomplete\" | \"redirect_uri_mismatch\" | \"ref_not_in_answer\" | \"refresh_dirty\" | \"refresh_diverged\" | \"refresh_drain_timeout\" | \"refresh_no_upstream\" | \"refresh_not_managed\" | \"refresh_not_owner\" | \"refresh_source_changed\" | \"relay_disabled\" | \"relay_session_expired\" | \"relay_unreachable\" | \"rename_held\" | \"request_already_submitted\" | \"requirements_changed\" | \"requires_local_engine\" | \"resume_spec_mismatch\" | \"result_too_large\" | \"revision_changed\" | \"revision_unavailable\" | \"schema_owner_required\" | \"scope_missing\" | \"search_cursor_requires_keyword\" | \"search_mode_local_only\" | \"scorecard_group_by_local_only\" | \"search_offset_over_cap\" | \"serve_build_drift\" | \"serve_port_in_use\" | \"serve_status_only\" | \"setup_harness_unsupported\" | \"setup_hosted_connection\" | \"setup_owner_conflict\" | \"shared_skills_unavailable\" | \"shared_skills_unsupported\" | \"skill_asset_not_found\" | \"skill_candidate_invalid\" | \"skill_not_found\" | \"skill_retention_capacity\" | \"skill_unavailable\" | \"slug_page_mismatch\" | \"slug_root_mode_mismatch\" | \"source_binding_required\" | \"source_id_taken\" | \"source_mismatch\" | \"source_not_ready\" | \"source_profile_no_backfill\" | \"source_referenced\" | \"source_root_conflict\" | \"split_bad_ratio\" | \"split_unparseable\" | \"stale_unavailable\" | \"state_mismatch\" | \"sync_not_applicable\" | \"sync_drain_lease_held\" | \"sync_first_run_in_progress\" | \"sync_no_successful_sync\" | \"sync_cursor_replaced\" | \"sync_parser_regression\" | \"target_escape\" | \"timeline_comment_markup\" | \"topology_change_required\" | \"transcript_secret_exposure\" | \"triage_unreliable_backoff\" | \"trust_raise_refused\" | \"two_consumers_on_host\" | \"trusted_local_only\" | \"unexpected_file_bytes\" | \"unexpected_staging_bytes\" | \"unknown_command\" | \"unknown_flag\" | \"unknown_method\" | \"unknown_source\" | \"unknown_tool\" | \"unpriced_model\" | \"unmanaged_database_path\" | \"unmanaged_path\" | \"unsupported_export_data\" | \"upstream\" | \"verification_failed\" | \"withdrawal_capacity\" | \"withdrawal_provenance\" | \"write_capacity_low\" | \"write_gate_rejected\" | \"write_held\" | \"worktree_dirty\" | \"writer_admin_intent_required\" | \"writer_admin_state_changed\" | \"writer_busy\" | \"writer_identity_publish_failed\" | \"writer_manifest_mismatch\" | \"writer_manifest_rescope_required\" | \"writer_manifest_unsafe\" | \"writer_regrant_required\" | \"writer_transfer_conflict\" | \"writer_transfer_required\" | \"wrong_account_consented\" | \"schema_pack_too_large\" | \"schema_pack_emit_mismatch\" | undefined",
"canonicalCode: string",
"cause?: unknown",
"code: ErrorCode",
diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txt
index 23041cc3f6..6eafacdf0d 100644
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@ -191,6 +191,7 @@ test/repair-frontmatter-keys-sweep-6454.test.ts
test/repair-frontmatter.test.ts
test/repair-receipt-compaction.test.ts
test/repair-rename-identity-6729.test.ts
+test/schema-missing-tables.test.ts
test/scripts/test-stress-postgres.test.ts
test/search/page-rank-cut.test.ts
test/search/rerank-gate-hybrid.test.ts
diff --git a/test/purge-missing-cache-6911.test.ts b/test/purge-missing-cache-6911.test.ts
index a723a81cbb..bb786b8292 100644
--- a/test/purge-missing-cache-6911.test.ts
+++ b/test/purge-missing-cache-6911.test.ts
@@ -22,6 +22,9 @@ 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 { schemaVersionEntry } from '../src/commands/doctor/checks/schema-health.ts';
+import type { DoctorContext } from '../src/commands/doctor/context.ts';
+import type { Check } from '../src/commands/doctor.ts';
import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
import { withEnv } from './helpers/with-env.ts';
@@ -48,6 +51,10 @@ 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 missingTablesCheck(engine: BrainEngine) {
+ const checks = await schemaVersionEntry.run({ engine, progress: { heartbeat() {} } } as unknown as DoctorContext) as Check[];
+ return checks.find(c => c.name === 'schema_missing_tables')!;
+}
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); }
}
@@ -120,6 +127,20 @@ describe('#6911 missing query_cache', () => {
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: [] });
+ expect(await errorCode(runRepair(ctx(engine), missingTablesRepair, scope, { apply: true, explicit: true, expect: preview.preview_hash }))).not.toBe('ok');
+ }
+ }), 120_000);
+
+ test('an apply leaves a table that reappeared after the preview alone', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ for (const engine of engines) {
+ await engine.executeRaw('DROP TABLE IF EXISTS query_cache');
+ const scope = await resolveRepairScope(engine);
+ const preview = await runRepair(ctx(engine), missingTablesRepair, scope, { apply: false, explicit: true });
+ await engine.executeRaw('CREATE TABLE query_cache (id TEXT PRIMARY KEY)');
+ const applied = await runRepair(ctx(engine), missingTablesRepair, scope, { apply: true, explicit: true, expect: preview.preview_hash });
+ expect(applied.outcomes).toEqual({ already_present: 1 });
+ expect((await shape(engine, 'query_cache')).columns.map(c => c.column_name)).toEqual(['id']);
+ await engine.executeRaw('DROP TABLE query_cache');
}
}), 120_000);
@@ -181,8 +202,32 @@ describe('#6911 missing query_cache', () => {
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 errorCode(purgePage(engine, 'people/loud-example'))).toStartWith('storage_error');
expect(await engine.executeRaw("SELECT 1 FROM pages WHERE slug='people/loud-example' AND deleted_at IS NULL")).toHaveLength(1);
}
}), 120_000);
+
+ test('doctor fails only a missing user-data table, warns for the rest, and says the base-schema replay hides a lost user-data table', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ for (const engine of engines) {
+ await engine.initSchema();
+ await engine.executeRaw('DROP TABLE IF EXISTS query_cache');
+ await engine.executeRaw('DROP TABLE IF EXISTS gbrain_cycle_locks');
+ const warned = await missingTablesCheck(engine);
+ expect(warned.status).toBe('warn');
+ expect(warned.message).toBe('2 table(s) the applied migrations create are missing, and apply-migrations will not recreate them from the migrations that already ran. '
+ + 'Rebuildable cache(s) query_cache: preview recreating them empty with gbrain repair missing-tables, then apply the printed command after the user agrees. '
+ + 'gbrain_cycle_locks hold no user data: gbrain init --migrate-only recreates the ones the base schema defines; report any it does not (see docs/guides/repair.md#missing-tables).');
+ expect(warned.fix?.argv).toEqual(['gbrain', 'repair', 'missing-tables', '--json']);
+ expect((await readMissingTables(engine) as { missing: unknown[] }).missing).toEqual([
+ { table: 'gbrain_cycle_locks', inventory_class: 'discard', loss_kind: 'operational', recreatable: false },
+ { table: 'query_cache', inventory_class: 'rebuild', loss_kind: 'operational', recreatable: true }]);
+ await engine.executeRaw('DROP TABLE IF EXISTS core_edit_notices');
+ const failed = await missingTablesCheck(engine);
+ expect(failed.status).toBe('fail');
+ expect(failed.message).toContain('core_edit_notices hold user data: restore their rows from a backup before running gbrain init --migrate-only, gbrain upgrade or apply-migrations');
+ await engine.initSchema();
+ expect(await readMissingTables(engine)).toMatchObject({ status: 'checked', missing: [{ table: 'query_cache' }] });
+ expect(await engine.executeRaw('SELECT count(*)::int AS n FROM core_edit_notices')).toEqual([{ n: 0 }]);
+ }
+ }), 180_000);
});
diff --git a/test/schema-missing-tables.test.ts b/test/schema-missing-tables.test.ts
new file mode 100644
index 0000000000..bee3924ad8
--- /dev/null
+++ b/test/schema-missing-tables.test.ts
@@ -0,0 +1,76 @@
+/**
+ * #6911: the recreate steps behind `gbrain repair missing-tables` rebuild each rebuildable cache in exactly the shape
+ * a fully migrated brain has (columns, types, defaults and indexes), and the expected-table check scopes itself to the
+ * brain's schema version. A later migration that changes one of these tables without a matching recreate line fails
+ * here. Real PGLite, plus Postgres when DATABASE_URL is set.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { LATEST_VERSION } from '../src/core/migrate.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { GRADUATION_INVENTORY } from '../src/core/persistence/graduation-inventory.ts';
+import { readMissingTables, RECREATABLE_TABLES, recreateStep } from '../src/core/schema-missing-tables.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+
+const engines: BrainEngine[] = [];
+let closePostgres: (() => Promise<void>) | undefined;
+
+async function shape(engine: BrainEngine, table: string) {
+ const columns = await engine.executeRaw<Record<string, unknown>>(`SELECT a.attname AS name, format_type(a.atttypid, a.atttypmod) AS type, a.attnotnull AS not_null,
+ pg_get_expr(d.adbin, d.adrelid) AS default_expr
+ FROM pg_attribute a LEFT JOIN pg_attrdef d ON d.adrelid=a.attrelid AND d.adnum=a.attnum
+ WHERE a.attrelid=to_regclass($1) AND a.attnum > 0 AND NOT a.attisdropped ORDER BY a.attname`, [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) };
+}
+async function setVersion(engine: BrainEngine, version: number) { await engine.setConfig('version', String(version)); }
+
+beforeAll(async () => {
+ const lite = new PGLiteEngine(); await lite.connect({}); await lite.initSchema(); engines.push(lite);
+ if (process.env.DATABASE_URL) {
+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL);
+ engines.push(pg.engine); closePostgres = pg.close;
+ }
+}, 180_000);
+afterAll(async () => { await engines[0]?.disconnect(); await closePostgres?.(); }, 60_000);
+
+describe('#6911 recreatable caches', () => {
+ test('the recreatable tables are exactly the inventory rebuild tables, and nothing else resolves to a step', () => {
+ const rebuild = GRADUATION_INVENTORY.entries.filter(e => e.class === 'rebuild' && e.kind === 'table').map(e => e.relation).sort();
+ expect([...RECREATABLE_TABLES].sort()).toEqual(rebuild);
+ for (const name of ['facts', 'core_edit_notices', 'constructor', 'toString', '__proto__', 'hasOwnProperty']) expect(recreateStep(name)).toBeUndefined();
+ });
+
+ test('each recreated table has the columns, types, defaults and indexes of the migrated brain', async () => {
+ for (const engine of engines) {
+ for (const table of RECREATABLE_TABLES) {
+ const expected = await shape(engine, table);
+ expect(expected.columns.length).toBeGreaterThan(0);
+ await engine.executeRaw(`DROP TABLE ${table}`);
+ await engine.transaction(tx => recreateStep(table)!(tx));
+ expect({ engine: engine.kind, table, ...await shape(engine, table) }).toEqual({ engine: engine.kind, table, ...expected });
+ }
+ }
+ }, 120_000);
+
+ test('below head only caches whose creating migration ran are expected; a newer brain is skipped', async () => {
+ for (const engine of engines) {
+ await engine.executeRaw('DROP TABLE query_cache');
+ try {
+ await setVersion(engine, 100);
+ expect(await readMissingTables(engine)).toMatchObject({ status: 'checked', scope: 'rebuildable_caches', checked: 2,
+ missing: [{ table: 'query_cache', recreatable: true }] });
+ await setVersion(engine, 57);
+ expect(await readMissingTables(engine)).toMatchObject({ status: 'checked', scope: 'rebuildable_caches', checked: 1, missing: [{ table: 'query_cache' }] });
+ await setVersion(engine, 54);
+ expect(await readMissingTables(engine)).toEqual({ status: 'checked', scope: 'rebuildable_caches', checked: 0, missing: [] });
+ await setVersion(engine, LATEST_VERSION + 1);
+ expect(await readMissingTables(engine)).toEqual({ status: 'skipped', reason: 'client_behind', version: LATEST_VERSION + 1, latest: LATEST_VERSION });
+ } finally {
+ await setVersion(engine, LATEST_VERSION);
+ await engine.transaction(tx => recreateStep('query_cache')!(tx));
+ }
+ expect(await readMissingTables(engine)).toMatchObject({ status: 'checked', scope: 'all_tables', missing: [] });
+ }
+ }, 120_000);
+});