Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(doctor): extract_health tolerates only the named missing schema object (#6599)

time-attack74c395de2a01
diff --git a/src/commands/doctor/checks/extraction-sync.ts b/src/commands/doctor/checks/extraction-sync.ts
index 05c2fda03d..f096db3b3f 100644
--- a/src/commands/doctor/checks/extraction-sync.ts
+++ b/src/commands/doctor/checks/extraction-sync.ts
@@ -15,7 +15,7 @@ import { resolveEnvNumber, resolveHoursEnv, warnOnceForEnv } from '../../../core
import { chunkerStamp } from '../../../core/chunkers/code.ts';
import { effectiveLinkExtractorWatermark, smallBrainBacklogNote } from '../../../core/link-extraction-watermark.ts';
import { previewMentionPass } from '../../../core/mentions/stale.ts';
-import { isUndefinedColumnError } from '../../../core/utils.ts';
+import { isMissingSchemaObject, isUndefinedColumnError } from '../../../core/utils.ts';
import {
loadStorageConfig,
effectiveDbOnlyDirs,
@@ -36,6 +36,13 @@ import { parseSourceConfig } from '../../../core/sources-load.ts';
import { checkError } from '../check-fix.ts';
import { haltReasonsWithUnknown, readRecordedHaltReasons7d, topHaltReason } from '../../../core/extract/rollup-writer.ts';
+/** Objects ownedContentFreshness reads that an older schema may lack; any other SQL error surfaces (#6599). */
+const OWNED_CONTENT_TABLES = [
+ 'persistence_brain', 'persistence_source_bindings', 'persistence_worktrees', 'persistence_host_bindings',
+ 'persistence_requests', 'persistence_effects', 'source_ingestion_receipts',
+] as const;
+const OWNED_CONTENT_COLUMNS = ['incarnation', 'source_incarnation', 'recovery', 'owner_host_id'] as const;
+
/** Local aliases; the shared warn-once memo lives in core so it can't fork per module. */
const _resolveEnvNumber = resolveEnvNumber;
const _resolveSyncFreshnessHours = resolveHoursEnv;
@@ -1047,8 +1054,7 @@ export async function computeExtractHealthCheck(
try {
rows = await engine.executeRaw<RollupRow>(rollupQuery(true), []);
} catch (err) {
- const msg = (err as Error).message || String(err);
- if (!/expected_limit_count/i.test(msg)) throw err;
+ if (!isMissingSchemaObject(err, 'column', 'expected_limit_count')) throw err;
rows = await engine.executeRaw<RollupRow>(rollupQuery(false), []);
}
// #5495: recorded halt reasons per kind over the same 7 days (migration v239).
@@ -1191,7 +1197,7 @@ export async function computeExtractHealthCheck(
// bootstrap-coverage / migration framework brings the schema forward
// and the next run resolves naturally. Stay quiet.
const msg = (err as Error).message || String(err);
- if (/extract_rollup_7d.*does not exist|no such table/i.test(msg)) {
+ if (isMissingSchemaObject(err, 'table', 'extract_rollup_7d')) {
return {
name,
status: 'ok',
@@ -1252,7 +1258,7 @@ export async function checkSyncFreshness(
const issues: string[] = [];
let ownedContent = new Set<string>();
try { ownedContent = new Set((await ownedContentFreshness(engine)).map(source => source.sourceId)); }
- catch (error) { if (!/does not exist|no such table/i.test(String(error))) throw error; }
+ catch (error) { if (!isMissingSchemaObject(error, 'table', OWNED_CONTENT_TABLES) && !isMissingSchemaObject(error, 'column', OWNED_CONTENT_COLUMNS)) throw error; }
let writer_owned_count = 0;
// v0.41.27.0: D6 count math. Every source falls into
// EXACTLY ONE bucket per iteration. Invariant pinned by unit test:
diff --git a/src/core/extract/rollup-writer.ts b/src/core/extract/rollup-writer.ts
index c1c0cb918c..fbaf0eb8bb 100644
--- a/src/core/extract/rollup-writer.ts
+++ b/src/core/extract/rollup-writer.ts
@@ -28,6 +28,7 @@
*/
import type { BrainEngine } from '../engine.ts';
+import { isMissingSchemaObject } from '../utils.ts';
/**
* #5495: why a round halted, as a closed vocabulary stored per reason in
@@ -95,7 +96,7 @@ export async function readRecordedHaltReasons7d(engine: Pick<BrainEngine, 'execu
recorded.set(row.kind, perKind);
}
} catch (err) {
- if (!/halt_reasons/i.test((err as Error).message || String(err))) throw err;
+ if (!isMissingSchemaObject(err, 'column', 'halt_reasons')) throw err;
}
return recorded;
}
@@ -227,7 +228,7 @@ export async function upsertExtractRollup(
// #5495 (no fallback by design): a brain whose schema is behind v239 has no
// halt_reasons column. The rollup is a best-effort cache, so the row is
// lost until the migration runs; say which fix restores it.
- if (/halt_reasons/i.test(msg)) {
+ if (isMissingSchemaObject(err, 'column', 'halt_reasons')) {
rollupErrorLogOnce(input.kind, day, `${msg} (the schema is behind: doctor reports migrations_pending; run gbrain apply-migrations --yes --no-autopilot-install)`);
return { ok: false, error: msg };
}
@@ -236,7 +237,7 @@ export async function upsertExtractRollup(
// write (best-effort would swallow it), retry the pre-v141 statement —
// the cap stop degrades to the old conflated halt accounting until the
// migration runs.
- if (/expected_limit_count/i.test(msg)) {
+ if (isMissingSchemaObject(err, 'column', 'expected_limit_count')) {
try {
await engine.executeRaw(
`INSERT INTO extract_rollup_7d (
diff --git a/src/core/utils.ts b/src/core/utils.ts
index 4dd5edddc2..5068ef0f12 100644
--- a/src/core/utils.ts
+++ b/src/core/utils.ts
@@ -381,6 +381,34 @@ export function isUndefinedTableError(error: unknown): boolean {
return /relation .* does not exist|no such table|undefined table/i.test(message);
}
+/**
+ * #6599: strict old-schema predicate. True only when the error names exactly
+ * one of `names` as a missing table (42P01) or column (42703). With a SQLSTATE
+ * present, the code must match and the named object must too (driver metadata
+ * `table_name`/`column_name` wins over message text); a driver that drops the
+ * code is accepted only on the exact PostgreSQL/PGLite diagnostic. Unlike
+ * `isUndefinedColumnError`, a different missing object, a permission error or
+ * a data error that merely mentions the name never reads as "not migrated yet".
+ */
+export function isMissingSchemaObject(error: unknown, kind: 'table' | 'column', names: string | readonly string[]): boolean {
+ if (typeof error !== 'object' || error === null) return false;
+ const wanted = new Set(typeof names === 'string' ? [names] : names);
+ const err = error as Record<string, unknown>;
+ const code = err.code === undefined || err.code === null ? '' : String(err.code);
+ if (code && code !== (kind === 'table' ? '42P01' : '42703')) return false;
+ if (code) {
+ const identifiers = (kind === 'table' ? ['table_name', 'table'] : ['column_name', 'column'])
+ .map(field => err[field]).filter((value): value is string => typeof value === 'string');
+ if (identifiers.length) return identifiers.every(identifier => wanted.has(identifier));
+ }
+ const message = typeof err.message === 'string' ? err.message.trim() : '';
+ const match = kind === 'table'
+ ? /^relation "([^"]+)" does not exist$/.exec(message)
+ : /^column (?:"([^"]+)"|([A-Za-z_][\w$]*(?:\.[A-Za-z_][\w$]*)?))(?: of relation "[^"]+")? does not exist$/.exec(message);
+ const identifier = match?.[1] ?? match?.[2];
+ return identifier !== undefined && wanted.has(identifier.split('.').pop()!);
+}
+
/**
* SQLSTATE 22007 / 22008: a date or timestamp the database could not parse.
* On a read path that is the caller's input, never a degraded result or a
diff --git a/test/e2e/extract-rollup-schema-errors-postgres.test.ts b/test/e2e/extract-rollup-schema-errors-postgres.test.ts
new file mode 100644
index 0000000000..ff56cf0eeb
--- /dev/null
+++ b/test/e2e/extract-rollup-schema-errors-postgres.test.ts
@@ -0,0 +1,3 @@
+import { registerPostgresTests } from '../helpers/test-backends.ts';
+
+await registerPostgresTests(() => import('../extract-rollup-schema-errors.test.ts'));
diff --git a/test/extract-rollup-schema-diagnostics.test.ts b/test/extract-rollup-schema-diagnostics.test.ts
new file mode 100644
index 0000000000..7cabd53a80
--- /dev/null
+++ b/test/extract-rollup-schema-diagnostics.test.ts
@@ -0,0 +1,118 @@
+/** Protects SQLSTATE + exact object compatibility and non-retrying failure diagnostics.
+ * Driver-shaped errors cover metadata variants unavailable from one local backend; a
+ * wrapped error without a SQLSTATE is accepted only on the exact PostgreSQL diagnostic.
+ * Real SQL errors/old schemas are exercised in extract-rollup-schema-errors.test.ts.
+ */
+import { expect, test } from 'bun:test';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { checkSyncFreshness, computeExtractHealthCheck } from '../src/commands/doctor/checks/extraction-sync.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { readRecordedHaltReasons7d, upsertExtractRollup } from '../src/core/extract/rollup-writer.ts';
+import { isMissingSchemaObject } from '../src/core/utils.ts';
+
+function throwingEngine(error: unknown): BrainEngine {
+ return { executeRaw: async () => { throw error; } } as unknown as BrainEngine;
+}
+
+test('reader propagates non-schema errors and contradictory missing-column identities', async () => {
+ for (const fields of [
+ { code: '42501', message: 'permission denied for halt_reasons diagnostic' },
+ { code: '22P02', message: 'invalid input syntax for integer: "halt_reasons"' },
+ { code: '42703', message: 'column r.other_halt_reasons does not exist' },
+ { code: '42703', message: 'column r.halt_reasons does not exist', column_name: 'other' },
+ { code: '42703', message: 'column r.halt_reasons does not exist', column: 'other' },
+ { code: '42703', message: 'column r.halt_reasons does not exist', column_name: 'halt_reasons', column: 'other' },
+ { message: 'permission denied for column halt_reasons' },
+ { code: '08006', message: 'column r.halt_reasons does not exist' },
+ ]) {
+ const error = Object.assign(new Error(fields.message), fields);
+ await expect(readRecordedHaltReasons7d(throwingEngine(error))).rejects.toBe(error);
+ expect((await computeExtractHealthCheck(throwingEngine(error))).status).toBe('warn');
+ }
+});
+
+test('reader accepts exact driver metadata and PostgreSQL/PGLite missing-column messages', async () => {
+ for (const fields of [
+ { code: '42703', message: 'column r.halt_reasons does not exist' },
+ { code: '42703', message: 'column "halt_reasons" does not exist', column: 42 },
+ { code: '42703', message: 'localized diagnostic', column_name: 'halt_reasons' },
+ { code: '42703', message: 'localized diagnostic', column: 'halt_reasons' },
+ { message: 'column r.halt_reasons does not exist' },
+ { message: 'column "halt_reasons" of relation "extract_rollup_7d" does not exist' },
+ ]) {
+ expect((await readRecordedHaltReasons7d(throwingEngine(Object.assign(new Error(fields.message), fields)))).size).toBe(0);
+ }
+});
+
+test('doctor only treats the exact missing rollup relation as old schema', async () => {
+ for (const fields of [
+ { code: '42P01', message: 'relation "extract_rollup_7d" does not exist', expected: 'ok' },
+ { code: '42P01', message: 'localized diagnostic', table_name: 'extract_rollup_7d', expected: 'ok' },
+ { code: '42P01', message: 'relation "other_extract_rollup_7d" does not exist', expected: 'warn' },
+ { code: '42P01', message: 'relation "extract_rollup_7d" does not exist', table_name: 'other', expected: 'warn' },
+ { code: '42P01', message: 'relation "extract_rollup_7d" does not exist', table: 'other', expected: 'warn' },
+ { code: '22P02', message: 'invalid input syntax for integer: "no such table"', expected: 'warn' },
+ { code: '42501', message: 'relation "extract_rollup_7d" does not exist', expected: 'warn' },
+ ] as const) {
+ expect((await computeExtractHealthCheck(throwingEngine(Object.assign(new Error(fields.message), fields)))).status).toBe(fields.expected);
+ }
+});
+
+test('writer does not downgrade or retry a real error mentioning an old column', async () => {
+ for (const column of ['expected_limit_count', 'halt_reasons']) {
+ let calls = 0;
+ const error = Object.assign(new Error(`permission denied for ${column} diagnostic`), { code: '42501' });
+ const engine = { executeRaw: async () => { if (++calls === 1) throw error; return []; } } as unknown as BrainEngine;
+ expect(await upsertExtractRollup(engine, { kind: `denied-${column}`, source_id: 'default', halt_delta: 1 })).toEqual({ ok: false, error: error.message });
+ expect(calls).toBe(1);
+ }
+});
+
+test('doctor does not retry an aggregate failure that only mentions expected_limit_count', async () => {
+ let calls = 0;
+ const engine = { executeRaw: async () => {
+ calls++;
+ if (calls === 1) throw Object.assign(new Error('permission denied for expected_limit_count'), { code: '42501' });
+ return [];
+ } } as unknown as BrainEngine;
+ expect((await computeExtractHealthCheck(engine)).status).toBe('warn');
+ expect(calls).toBe(1);
+});
+
+test('isMissingSchemaObject needs the named object and the matching SQLSTATE', () => {
+ const err = (fields: Record<string, unknown>) => Object.assign(new Error(String(fields.message)), fields);
+ expect(isMissingSchemaObject(err({ code: '42P01', message: 'relation "persistence_worktrees" does not exist' }), 'table', ['persistence_brain', 'persistence_worktrees'])).toBe(true);
+ expect(isMissingSchemaObject(err({ code: '42P01', message: 'relation "public.extract_rollup_7d" does not exist' }), 'table', 'extract_rollup_7d')).toBe(true);
+ expect(isMissingSchemaObject(err({ message: 'relation "extract_rollup_7d" does not exist' }), 'table', 'extract_rollup_7d')).toBe(true);
+ expect(isMissingSchemaObject(err({ code: '42P01', message: 'relation "pages" does not exist' }), 'table', 'extract_rollup_7d')).toBe(false);
+ expect(isMissingSchemaObject(err({ code: '42703', message: 'relation "extract_rollup_7d" does not exist' }), 'table', 'extract_rollup_7d')).toBe(false);
+ expect(isMissingSchemaObject(err({ code: '42P01', message: 'relation "extract_rollup_7d" does not exist' }), 'column', 'extract_rollup_7d')).toBe(false);
+ expect(isMissingSchemaObject(err({ message: 'something about extract_rollup_7d does not exist yet' }), 'table', 'extract_rollup_7d')).toBe(false);
+ expect(isMissingSchemaObject('relation "extract_rollup_7d" does not exist', 'table', 'extract_rollup_7d')).toBe(false);
+});
+
+test('sync freshness surfaces real errors from the owned-content probe instead of skipping it', async () => {
+ const real = new PGLiteEngine();
+ await real.connect({});
+ await real.initSchema();
+ try {
+ await real.executeRaw(`INSERT INTO sources (id, name, local_path, last_sync_at) VALUES ('w17-fresh', 'w17-fresh', '/tmp/w17-fresh', now())`);
+ const failing = (error: Error) => new Proxy(real, {
+ get(target, prop, receiver) {
+ if (prop !== 'executeRaw') return Reflect.get(target, prop, receiver);
+ return async (sql: string, params?: unknown[]) => {
+ if (sql.includes('persistence_source_bindings')) throw error;
+ return target.executeRaw(sql, params as never);
+ };
+ },
+ }) as BrainEngine;
+ const denied = Object.assign(new Error('role "gbrain_reader" does not exist'), { code: '42704' });
+ const deniedCheck = await checkSyncFreshness(failing(denied));
+ expect(deniedCheck.message).toContain('role "gbrain_reader" does not exist');
+ const missing = Object.assign(new Error('relation "persistence_worktrees" does not exist'), { code: '42P01' });
+ const oldCheck = await checkSyncFreshness(failing(missing));
+ expect(oldCheck.message).not.toContain('Could not');
+ } finally {
+ await real.disconnect();
+ }
+});
diff --git a/test/extract-rollup-schema-errors.test.ts b/test/extract-rollup-schema-errors.test.ts
new file mode 100644
index 0000000000..9c579de6c4
--- /dev/null
+++ b/test/extract-rollup-schema-errors.test.ts
@@ -0,0 +1,94 @@
+/**
+ * Protects: SQL failures must not masquerade as old extraction schemas.
+ * A real invalid integer in halt_reasons must warn without losing its row;
+ * genuine missing columns retain unknown historical halts. Runs on PGLite
+ * and in the PostgreSQL E2E wrapper with isolated tables/schema.
+ */
+import { afterAll, beforeAll, expect, test } from 'bun:test';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { computeExtractHealthCheck } from '../src/commands/doctor/checks/extraction-sync.ts';
+import { readRecordedHaltReasons7d, upsertExtractRollup } from '../src/core/extract/rollup-writer.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { testBackends } from './helpers/test-backends.ts';
+
+const backends = testBackends();
+const engines: BrainEngine[] = [];
+let closePostgres: (() => Promise<void>) | undefined;
+beforeAll(async () => {
+ if (backends.includes('pglite')) {
+ const engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ engines.push(engine);
+ }
+ if (backends.includes('postgres')) {
+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!);
+ engines.push(pg.engine);
+ closePostgres = pg.close;
+ }
+}, 120_000);
+afterAll(async () => {
+ for (const engine of engines) if (engine.kind === 'pglite') await engine.disconnect();
+ await closePostgres?.();
+});
+
+test('corrupt numeric reasons containing schema-like text warn and preserve the evidence', async () => {
+ for (const engine of engines) {
+ await engine.executeRaw(`INSERT INTO extract_rollup_7d
+ (kind, source_id, day, halt_count, halt_reasons)
+ VALUES ('schema-error', 'default', CURRENT_DATE, 3,
+ jsonb_build_object('item_error', 'no such table halt_reasons'))`);
+ try {
+ await expect(readRecordedHaltReasons7d(engine)).rejects.toMatchObject({ code: '22P02' });
+ const check = await computeExtractHealthCheck(engine);
+ expect(check.status).toBe('warn');
+ expect(check.message).toContain('invalid input syntax');
+ expect(check.message).not.toContain('not yet present');
+ const [row] = await engine.executeRaw<{ halt_count: number; reason: string }>(
+ `SELECT halt_count, halt_reasons->>'item_error' AS reason
+ FROM extract_rollup_7d WHERE kind = 'schema-error'`);
+ expect(row).toEqual({ halt_count: 3, reason: 'no such table halt_reasons' });
+ } finally {
+ await engine.executeRaw("DELETE FROM extract_rollup_7d WHERE kind = 'schema-error'");
+ }
+ }
+}, 120_000);
+
+test('genuine old schemas retain unknown halts, cap fallback and absent-table compatibility', async () => {
+ for (const engine of engines) {
+ await engine.executeRaw(`INSERT INTO extract_rollup_7d
+ (kind, source_id, day, halt_count, round_completed_count)
+ VALUES ('old-schema', 'default', CURRENT_DATE, 3, 1)`);
+ await engine.executeRaw('ALTER TABLE extract_rollup_7d DROP COLUMN halt_reasons');
+ try {
+ const check = await computeExtractHealthCheck(engine);
+ expect(check.status).toBe('warn');
+ expect((check.details as { kinds: unknown[] }).kinds).toEqual([
+ expect.objectContaining({ kind: 'old-schema', halt_count: 3, halt_reasons: { unknown: 3 }, halt_rate: 0.75 }),
+ ]);
+ await engine.executeRaw('ALTER TABLE extract_rollup_7d DROP COLUMN expected_limit_count');
+ try {
+ expect(await upsertExtractRollup(engine, { kind: 'old-schema', source_id: 'default', expected_limit_delta: 1 })).toEqual({ ok: true });
+ const old = await computeExtractHealthCheck(engine);
+ expect(old.status).toBe('warn');
+ expect((old.details as { kinds: unknown[] }).kinds).toEqual([
+ expect.objectContaining({ halt_count: 4, halt_reasons: { unknown: 4 }, expected_limit_count: 0 }),
+ ]);
+ } finally {
+ await engine.executeRaw('ALTER TABLE extract_rollup_7d ADD COLUMN expected_limit_count INTEGER NOT NULL DEFAULT 0');
+ }
+ } finally {
+ await engine.executeRaw("ALTER TABLE extract_rollup_7d ADD COLUMN halt_reasons JSONB NOT NULL DEFAULT '{}'::jsonb");
+ await engine.executeRaw("DELETE FROM extract_rollup_7d WHERE kind = 'old-schema'");
+ }
+ await engine.executeRaw('ALTER TABLE extract_rollup_7d RENAME TO held_rollup');
+ try {
+ const check = await computeExtractHealthCheck(engine);
+ expect(check.status).toBe('ok');
+ expect(check.message).toContain('not yet present');
+ } finally {
+ await engine.executeRaw('ALTER TABLE held_rollup RENAME TO extract_rollup_7d');
+ }
+ }
+}, 120_000);