Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(repair): schema_owner_required for a role without CREATE; tests for the refusal and a failed VACUUM; self-contained cases (#6911)
garrytane659f751bcaa
diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.mdindex a954be9787..4067ce61a1 100644--- a/docs/guides/error-codes.md+++ b/docs/guides/error-codes.md@@ -3106,6 +3106,16 @@ More: [docs/guides/windowed-reads.md#revision_changed](../../docs/guides/windoweMore: [docs/ENGINES.md#schema-lock-blocked](../../docs/ENGINES.md#schema-lock-blocked)+### schema_owner_required++<a id="schema_owner_required"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| The database role this command connects as may not create schema objects (Postgres 42501), so the schema repair created nothing. | On a brain whose tables belong to a separate owner role, the application role cannot run DDL; only the owner can recreate a missing table. | Run the same apply connected as the role that owns the brain tables (the one apply-migrations uses). | agent | `repeat the read that failed` | 1 | no |++More: [docs/guides/repair.md#missing-tables](../../docs/guides/repair.md#missing-tables)+### schema_pack_emit_mismatch<a id="schema_pack_emit_mismatch"></a>diff --git a/docs/guides/repair.md b/docs/guides/repair.mdindex a18f808ead..72b0298704 100644--- a/docs/guides/repair.md+++ b/docs/guides/repair.md@@ -284,7 +284,7 @@ migrated brain has, then checks it exists. A table created since the previewis completed in place (`completed`); every statement is `IF NOT EXISTS` and thewhole 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:+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 isdiff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex 7dd9107551..a75873ca38 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -523,6 +523,7 @@ export const CODES = {revision_conflict: { class: 'caller', summary: "The target changed since it was read; the expected revision no longer matches.", fix: { argv: ['gbrain', 'get', '--source', '{source_id}', '--', '{slug}'], mcp: { tool: 'get_page', arguments: { slug: '{slug}', source_id: '{source_id}' } }, consent: [], actor: 'agent', why: "Reads the current page and revision; resubmit against that revision with a new request_id.", requires_exclusive: false } },revision_required: { class: 'caller', summary: "The target already exists and the write named no revision: supply the expected revision read from the page (or the policy epoch) before replacing it.", why: "Without the revision the write cannot tell an intentional replacement from an overwrite of an edit it never saw; nothing was changed.", fix: { argv: ['gbrain', 'get', '--source', '{source_id}', '--', '{slug}'], mcp: { tool: 'get_page', arguments: { slug: '{slug}', source_id: '{source_id}' } }, consent: [], actor: 'agent', why: "Reads the current page and its revision; resubmit with that expected_revision (or force: true for an intentional overwrite).", requires_exclusive: false } },revision_unavailable: { class: 'unavailable', summary: "The exact authorized revision is unavailable." },+ schema_owner_required: { class: 'caller', summary: "The database role this command connects as may not create schema objects (Postgres 42501), so the schema repair created nothing.", why: "On a brain whose tables belong to a separate owner role, the application role cannot run DDL; only the owner can recreate a missing table.", docs: 'docs/guides/repair.md#missing-tables', suggestion: 'Run the same apply connected as the role that owns the brain tables (the one apply-migrations uses).' },scope_denied: { class: 'host_only', summary: "The connection lacks the scope this memory verb requires." },scope_missing: { class: 'caller', summary: "Google connect credential error: scope missing.", docs: 'docs/guides/google-connect.md#troubleshooting' },search_cursor_requires_keyword: { class: 'caller', summary: "A search cursor was sent without match: \"keyword\"; cursors continue keyword listings only (hybrid rows are a ranked top-K with no next page).", suggestion: 'Send the next object from the previous search response unchanged; it carries match: "keyword".' },diff --git a/src/core/repair/missing-tables.ts b/src/core/repair/missing-tables.tsindex 0ed871911e..35f260ea87 100644--- a/src/core/repair/missing-tables.ts+++ b/src/core/repair/missing-tables.ts@@ -43,7 +43,7 @@ export const missingTablesRepair: RepairHandler = {return { items: tables.map(toItem), ...(tables.length ? { preview_hash: hash } : {}), residuals: kept.length ? { user_data_tables: kept.length } : {},details: { checked: report.checked, recreate: tables, user_data_tables: kept.map(m => m.table) } };},- async apply(ctx, item) {+ 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);@@ -52,8 +52,8 @@ export const missingTablesRepair: RepairHandler = {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');+ 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.`,diff --git a/test/purge-missing-cache-6911.test.ts b/test/purge-missing-cache-6911.test.tsindex ba0ef6441f..a723a81cbb 100644--- a/test/purge-missing-cache-6911.test.ts+++ b/test/purge-missing-cache-6911.test.ts@@ -92,6 +92,7 @@ describe('#6911 missing query_cache', () => {test('a fact purge commits and verifies with the cache absent', async () => withEnv({ GBRAIN_HOME: home }, async () => {for (const engine of engines) {await seed(engine, 'people/fact-example');+ await engine.executeRaw('DROP TABLE IF EXISTS query_cache');const [row] = await engine.executeRaw<{ id: number }>("SELECT id FROM facts WHERE fact=$1 AND entity_slug='people/fact-example'", [CLAIM]);const dry = await call(engine, 'purge_fact', { id: Number(row!.id), dry_run: true });const done = await call(engine, 'purge_fact', { id: Number(row!.id), confirm: dry.confirm_token, expected_revision: dry.expected_revision, request_id: randomUUID() });@@ -104,6 +105,7 @@ describe('#6911 missing query_cache', () => {const expected = await shape(fresh, 'query_cache');expect(expected.columns.length).toBeGreaterThan(0);for (const engine of engines) {+ await engine.executeRaw('DROP TABLE IF EXISTS query_cache');const report = await readMissingTables(engine);expect(report).toMatchObject({ status: 'checked', missing: [{ table: 'query_cache', inventory_class: 'rebuild', recreatable: true }] });const scope = await resolveRepairScope(engine);@@ -123,7 +125,7 @@ describe('#6911 missing query_cache', () => {test('a recreated query_cache takes the live facts vector shape, not the config default', async () => withEnv({ GBRAIN_HOME: home }, async () => {for (const engine of engines) {- await engine.executeRaw('DROP TABLE query_cache');+ await engine.executeRaw('DROP TABLE IF EXISTS query_cache');await engine.executeRaw('DROP INDEX IF EXISTS idx_facts_embedding_hnsw');await engine.executeRaw('ALTER TABLE facts ALTER COLUMN embedding TYPE halfvec(768) USING NULL');const scope = await resolveRepairScope(engine);@@ -135,6 +137,39 @@ describe('#6911 missing query_cache', () => {}}), 120_000);+ test('a role that may not create the table gets schema_owner_required and nothing changes', 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 });+ const denied = Object.create(engine) as BrainEngine;+ denied.transaction = async () => { throw Object.assign(new Error('permission denied for schema public'), { code: '42501' }); };+ const message = await errorCode(runRepair(ctx(denied), missingTablesRepair, scope, { apply: true, explicit: true, expect: preview.preview_hash }));+ expect(message).toStartWith('schema_owner_required');+ expect(await engine.executeRaw("SELECT to_regclass('query_cache') IS NULL AS absent")).toEqual([{ absent: true }]);+ const applied = await runRepair(ctx(engine), missingTablesRepair, scope, { apply: true, explicit: true, expect: preview.preview_hash });+ expect(applied.outcomes).toMatchObject({ recreated: 1 });+ }+ }), 120_000);++ test('a failed PGLite VACUUM is reported as failed, never as ran', async () => withEnv({ GBRAIN_HOME: home }, async () => {+ const engine = engines[0]!;+ await seed(engine, 'people/vacuum-example');+ const [row] = await engine.executeRaw<{ id: number }>("SELECT id FROM facts WHERE fact=$1 AND entity_slug='people/vacuum-example'", [CLAIM]);+ const dry = await call(engine, 'purge_fact', { id: Number(row!.id), dry_run: true });+ const original = Object.getPrototypeOf(engine).executeRaw as typeof engine.executeRaw;+ engine.executeRaw = (async function (this: BrainEngine, sql: string, params?: unknown[], opts?: { signal?: AbortSignal }) {+ if (/^\s*VACUUM\b/i.test(sql)) throw new Error('forced vacuum failure');+ return original.call(this, sql, params, opts);+ }) as typeof engine.executeRaw;+ try {+ const done = await call(engine, 'purge_fact', { id: Number(row!.id), confirm: dry.confirm_token, expected_revision: dry.expected_revision, request_id: randomUUID(), vacuum: true });+ const physical = done.residuals.find((r: any) => r.store === 'database_physical');+ expect(physical.detail).toContain('VACUUM of the touched tables failed (forced vacuum failure)');+ expect(physical.detail).not.toContain('VACUUM ran');+ } finally { delete (engine as { executeRaw?: unknown }).executeRaw; }+ }), 120_000);+test('the repair is explicit-only and a missing user-data table still fails the purge loudly', async () => withEnv({ GBRAIN_HOME: home }, async () => {for (const engine of engines) {const scope = await resolveRepairScope(engine);