Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(purge): vacuum receipt reports what ran, typed permission refusal, behavior row, troubleshooting row (#6911)

garrytan6ae3b34acf5a
diff --git a/docs/guides/repair.md b/docs/guides/repair.md
index fc9062e40b..a18f808ead 100644
--- a/docs/guides/repair.md
+++ b/docs/guides/repair.md
@@ -281,10 +281,21 @@ 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.
+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 `permission_denied` 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.
+
+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
diff --git a/docs/guides/troubleshooting.md b/docs/guides/troubleshooting.md
index 12738616ce..a29f751325 100644
--- a/docs/guides/troubleshooting.md
+++ b/docs/guides/troubleshooting.md
@@ -12,6 +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 |
| 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/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 3a4befbb4e..508aeeac65 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -848,6 +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.' },
];
/** 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 1490d08b2f..42dac650df 100644
--- a/src/core/facts/purge-verify.ts
+++ b/src/core/facts/purge-verify.ts
@@ -415,20 +415,21 @@ export async function verifyFactPurge(engine: BrainEngine, input: { target: Purg
AND NOT (visibility=$3 AND ($4='*' OR entity_slug=$4))`, [src, target.fact_hash, target.visibility, plan.subject]);
const files = await pageFilePaths(engine, src, plan.pages.map(page => page.page_id));
stores.push(...onDiskReports(files.files, claim, dryRun));
+ let vacuumed: string | null = null;
+ if (input.vacuum && !dryRun && engine.kind === 'pglite') {
+ const tables = ['facts', 'takes', 'pages', 'content_chunks', 'page_versions', 'persistence_requests', ...(await relationExists(engine, 'query_cache') ? ['query_cache'] : [])];
+ vacuumed = await engine.executeRaw(`VACUUM ${tables.join(', ')}`).then(() => 'ran', (error: unknown) => `failed (${(error as Error).message})`);
+ }
const residuals: StoreReport[] = [];
if (files.root && files.paths.length) residuals.push(await gitResidualCommits(files.root, files.paths, claim));
for (const r of OUT_OF_REACH_RESIDUALS) {
if (r.store === 'git_history' && residuals.length) continue;
- const detail = r.store === 'database_physical' ? `${r.detail}${engine.kind === 'pglite' ? (input.vacuum ? ' VACUUM ran on the touched tables; filesystem blocks and snapshots may still hold old pages.' : ' PGLite has no autovacuum; rerun with --vacuum to compact the touched tables.') : ' On Postgres the operator runs VACUUM; WAL archives, replicas and PITR windows are outside gbrain.'}` : r.detail;
+ const detail = r.store === 'database_physical' ? `${r.detail}${engine.kind === 'pglite' ? (vacuumed === 'ran' ? ' VACUUM ran on the touched tables; filesystem blocks and snapshots may still hold old pages.' : vacuumed ? ` VACUUM of the touched tables ${vacuumed}; rerun with --vacuum.` : ' PGLite has no autovacuum; rerun with --vacuum to compact the touched tables.') : ' On Postgres the operator runs VACUUM; WAL archives, replicas and PITR windows are outside gbrain.'}` : r.detail;
residuals.push({ store: r.store, status: 'out_of_reach', detail });
}
if (Number(other?.n ?? 0)) residuals.push({ store: 'facts_other_scope', status: 'out_of_scope', reason: plan.subject === '*' ? 'other_visibility' : 'other_subject', remaining: Number(other.n),
detail: `${other.n} fact row(s) state the same claim about another entity or at another visibility; rerun with --all-subjects to purge every entity's copy.` });
residuals.push(...stores.filter(s => s.reason === 'source_prose' || s.reason === 'probed_reported' || s.store === 'canonical_markdown' && s.status === 'out_of_scope'));
- if (input.vacuum && !dryRun && engine.kind === 'pglite') {
- const tables = ['facts', 'takes', 'pages', 'content_chunks', 'page_versions', 'persistence_requests', ...(await relationExists(engine, 'query_cache') ? ['query_cache'] : [])];
- await engine.executeRaw(`VACUUM ${tables.join(', ')}`).catch(() => undefined);
- }
const next = dryRun
? ['Review the residuals with the user, then confirm with the token printed above (gbrain forget <id> --purge asks for it on a terminal).']
: ['Poll completion with gbrain forget --purge --status --request-id <request_id> until it reports complete.'];
diff --git a/src/core/repair/missing-tables.ts b/src/core/repair/missing-tables.ts
index 82a90cfda6..0ed871911e 100644
--- a/src/core/repair/missing-tables.ts
+++ b/src/core/repair/missing-tables.ts
@@ -48,7 +48,13 @@ export const missingTablesRepair: RepairHandler = {
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.
- await ctx.engine.transaction(tx => recreate(tx));
+ try {
+ await ctx.engine.transaction(tx => recreate(tx));
+ } catch (error) {
+ if ((error as { code?: string }).code !== '42501') throw error;
+ throw new OperationError('permission_denied', `This database role may not create ${item.slug}, so nothing was recreated.`,
+ `Run the apply again connected as the role that owns the gbrain schema (the one apply-migrations uses): ${PREVIEW} --apply --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.');