Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(persistence): classify 42703/42P01 at publication as schema_missing with a migrate-or-repair verdict (#6904)

garrytan593a8e0ed4be
diff --git a/docs/guides/sync-unblock-runbook.md b/docs/guides/sync-unblock-runbook.md
index 8193a644f7..cb3aed9e37 100644
--- a/docs/guides/sync-unblock-runbook.md
+++ b/docs/guides/sync-unblock-runbook.md
@@ -80,7 +80,9 @@ Every hold and error has three fields, from one table
reruns the same sync; `retry_when_clean` re-screens a held file once its edit
is committed; `repair` previews and applies a hash-bound file repair;
`reconcile` previews two diverged versions; `upgrade` installs a newer gbrain;
- `none` waits for a person.
+ `migrate` applies the pending schema migrations (`gbrain apply-migrations
+ --yes`, as the database role that owns the gbrain tables) before the write is
+ resubmitted; `none` waits for a person.
- `needs_human`: a person has to choose or act before it clears;
`human_reason` says what. A page whose safe action failed three times with
the same code (`attempts`: a re-hold, or a failed `unblock --apply` or
diff --git a/docs/guides/troubleshooting.md b/docs/guides/troubleshooting.md
index 3efcadbf8d..81e4b88d7b 100644
--- a/docs/guides/troubleshooting.md
+++ b/docs/guides/troubleshooting.md
@@ -220,7 +220,7 @@ Two calls, no SQL: the doctor or `sources status` row names the command, and `wr
<a id="terminal-write-failures"></a>**Doctor warns `persistence_terminal_failures`, or `gbrain sync status` reports terminal write failures?** Every write leaves a receipt, and a receipt that ended `failed`, `conflict` or `cancelled` stays in `persistence_requests` until compaction. gbrain reads them at query time and sorts each one into a category with a class, safe actions, whether a person decides, and a structured fix (nothing new is stored). Most rows need no action, so the check separates three things:
- **Active blockers** hold work now: a receipt still holding a publication recovery record (it blocks every queued write on its root), or a receipt that blocks a managed sync's checkpoint. Doctor warns whenever one exists, whatever the trend, and its `fix.command` is the next step (for a recovery record, `gbrain sync --source <id> --no-pull`, which runs the owner pass that clears it; a `recovery_blocked` record names the file to inspect instead).
-- **Unresolved rows** are terminal receipts in the window (`persistence.terminal_failures.window_days`, default 7, never longer than `persistence.receipt_retention_days`) that no later write superseded. Doctor warns when any of them is a gbrain-defect class (`owner_exception`, `database_refusal`, `writer_guard`, `outside_fence`, `gbrain_defect`): report those with the receipt ids. The rest are ordinary refusals the caller already received (`caller_conflict`, `caller_refusal`, `operator_cancelled`) or sync faults a rerun retries.
+- **Unresolved rows** are terminal receipts in the window (`persistence.terminal_failures.window_days`, default 7, never longer than `persistence.receipt_retention_days`) that no later write superseded. Doctor warns when any of them is a gbrain-defect class (`owner_exception`, `database_refusal`, `writer_guard`, `outside_fence`, `gbrain_defect`): report those with the receipt ids. The rest are ordinary refusals the caller already received (`caller_conflict`, `caller_refusal`, `operator_cancelled`) or sync faults a rerun retries. A `schema_missing` row (#6904) is a write that met a missing table or column: when the schema is behind, its fix is `gbrain apply-migrations --yes` as the database role that owns the gbrain tables, then resubmit; at head, it asks the user and points at doctor's `schema_missing_tables` check and the `gbrain repair missing-tables` preview.
- **Historical rows** do not block: a later write superseded them (`superseded`, `already_written`, `duplicate`), or they came from a build older than the release that fixed their cause (sync knock-on cancels before 0.60.216.0, the `Publication failed (P0001)` refusal before 0.60.40.0). Doctor counts them and never warns on them.
A spike warns only on its own: when at least `persistence.terminal_failures.spike_min` (default 25) receipts ended in the last 24 h and that is more than `persistence.terminal_failures.spike_factor` (default 3) times the median of the 7 days before. When most of those receipts were written by a gbrain build older than the release that fixed their class, the warning says an older write owner is still producing them and names the build; its fix is the read-only `gbrain sources writer status --source <id> --json` that names the owner, so upgrade or restart that process. A `file_database_drift` row is the page-drift class: [file drift](repair.md#file-drift) resolves it with `gbrain repair file-drift`. A read that does not finish within its deadline (5 s per statement, 2 s to get a connection) reports `unknown`, never a clean pile; rerun it.
diff --git a/src/core/ops/persistence.ts b/src/core/ops/persistence.ts
index e48beb1300..df56e4f499 100644
--- a/src/core/ops/persistence.ts
+++ b/src/core/ops/persistence.ts
@@ -118,7 +118,8 @@ async function publicReceipt(ctx: OperationContext, row: WriteRequest, facts?: W
const terminal = isTerminalOrRecovering(row) ? (await import('../persistence/terminal-classify.ts')).classifyTerminal({ request_id: row.request_id, source_id: row.source_id,
slug: row.slug, operation: row.operation, state: row.state, error_code: row.error_code, error_detail: row.error_detail ?? null, recovery: row.recovery,
blocked_reason: row.blocked_reason, compacted: row.compacted, publication_started: row.publication_started, error_message: row.error_message,
- intent_kind: typeof row.intent?.kind === 'string' ? row.intent.kind : null, build: (row as { admitter_version?: string | null }).admitter_version ?? null }) : null;
+ intent_kind: typeof row.intent?.kind === 'string' ? row.intent.kind : null, build: (row as { admitter_version?: string | null }).admitter_version ?? null,
+ schema_behind: await (await import('../persistence/schema-admission.ts')).readSchemaBehind(ctx.engine) }) : null;
const { cliRenderContext, renderAction } = await import('../agent-output.ts');
const render = ctx.remote === false ? cliRenderContext() : { transport: 'stdio' as const, isCallable: () => false, preapproved: () => false };
return {
diff --git a/src/core/persistence/public-category.ts b/src/core/persistence/public-category.ts
index 2a187e817d..727bcb8595 100644
--- a/src/core/persistence/public-category.ts
+++ b/src/core/persistence/public-category.ts
@@ -28,6 +28,7 @@ export const PUBLIC_BY_TERMINAL: Readonly<Record<TerminalCategory, PublicCategor
operator_cancelled: 'superseded', caller_conflict: 'conflict', file_conflict: 'drift', canonical_file_missing: 'file_missing', fence_unrenderable: 'defect',
writer_guard: 'defect', database_refusal: 'config', owner_exception: 'defect', legacy_publication_refusal: 'superseded',
sync_fault: 'defect', transport: 'transient', caller_refusal: 'content_refused', gbrain_defect: 'defect', diagnosis_required: 'defect',
+ schema_missing: 'storage',
};
/** Fault codes (holds, run stops, receipts) by name; a test pins that every `SYNC_FAULT_TABLE` code is here. */
diff --git a/src/core/persistence/publication-failure.ts b/src/core/persistence/publication-failure.ts
index 573dc47e7d..7289a54438 100644
--- a/src/core/persistence/publication-failure.ts
+++ b/src/core/persistence/publication-failure.ts
@@ -4,6 +4,7 @@ import { cursorFenceCause } from './sync-knock-on.ts';
import type { FenceFailureDetail } from '../fence-repair/refusal.ts';
import type { WithdrawalFailureDetail } from '../facts/withdrawal.ts';
import type { Action } from '../agent-output.ts';
+import { classifyPgAccessError } from '../pg-access-classify.ts';
/**
* #5974: a database refusal during preparation or publication becomes a
@@ -13,11 +14,12 @@ import type { Action } from '../agent-output.ts';
*/
export type PublicationStage = 'preparation' | 'publication' | 'after_file_publication';
/**
- * #6513 (wave 16 G3.5): the public `reason` of a refusal gbrain classifies by its raiser and SQLSTATE. A CLOSED enum:
+ * #6513 (wave 16 G3.5): the public `reason` of a refusal gbrain classifies by its raiser and SQLSTATE (#6904: `schema_missing`,
+ * a 42P01/42703 missing relation or column, per `pg-access-classify.ts`). A CLOSED enum:
* an operator trigger can interpolate a row value at its message prefix, so nothing derived from the message is kept,
* publicly or owner-side (#5974's rule: fixed identifiers only).
*/
-export const PUBLICATION_REASONS = ['attribution_unclassified_table', 'trust_unclassified_table', 'graduation_in_progress', 'unknown'] as const;
+export const PUBLICATION_REASONS = ['attribution_unclassified_table', 'trust_unclassified_table', 'graduation_in_progress', 'schema_missing', 'unknown'] as const;
export type PublicationReason = typeof PUBLICATION_REASONS[number];
export interface PublicationFailureDetail {
origin: 'database_guard' | 'database_trigger' | 'database';
@@ -29,6 +31,8 @@ export interface PublicationFailureDetail {
relationship?: string;
/** Closed enum (`PUBLICATION_REASONS`) for a refusal without a typed code; absent on the typed guard/trigger refusals. */
reason?: PublicationReason;
+ /** Owner-only, #6904: the relation or column a `schema_missing` refusal names (an identifier, never a value). */
+ missing?: string;
/** Owner-only: source identifiers can name private sources. */
sources?: { target: string | null; old: string | null; allowed: string[] };
stage?: PublicationStage;
@@ -94,11 +98,28 @@ function publicationReason(sqlstate: string, raiser: string | undefined, message
return unclassified && message.startsWith(`${raiser} is not classified for table`) ? unclassified : 'unknown';
}
+/**
+ * #6904: a relation or column the write path needs is missing (42P01 / 42703, `schema_missing` in `pg-access-classify.ts`):
+ * the brain schema is behind this build or lost a table, never a gbrain defect. Names the missing identifier from the error.
+ */
+const SCHEMA_MISSING_SQLSTATES = new Set(['42P01', '42703']);
+const MISSING_NAME = /(column|relation)\s+"?([A-Za-z_][A-Za-z0-9_.]*)"?(?:\s+of relation\s+"?([A-Za-z_][A-Za-z0-9_.]*)"?)?\s+does not exist/i;
+function schemaMissing(sqlstate: string, message: string): PublicationFailure {
+ const match = MISSING_NAME.exec(message);
+ const missing = match ? ident(match[3] ? `${match[3]}.${match[2]}` : match[2]) : undefined;
+ const what = match ? `${match[1]!.toLowerCase()} ${missing ?? 'unnamed'}` : 'a relation or column';
+ return { code: 'storage_error', message: `Publication failed: the database has no ${what} (${sqlstate}), which this gbrain build needs, so the brain schema is missing a migration or a table. Nothing was committed.`,
+ detail: { origin: 'database', sqlstate, reason: 'schema_missing', ...(missing ? { missing } : {}) } };
+}
+
/** Null when the error is not a database refusal this module recognizes. */
export function databaseRefusal(error: unknown): PublicationFailure | null {
if (error instanceof OperationError || !error || typeof error !== 'object') return null;
const e = error as Record<string, unknown>;
const sqlstate = typeof e.code === 'string' && /^[0-9A-Z]{5}$/.test(e.code) ? e.code : null;
+ if (sqlstate && SCHEMA_MISSING_SQLSTATES.has(sqlstate) && classifyPgAccessError(error).reason === 'schema_missing') {
+ return schemaMissing(sqlstate, typeof e.message === 'string' ? e.message : '');
+ }
if (sqlstate !== 'P0001' && sqlstate !== GRADUATION_SQLSTATE) return null;
const where = typeof e.where === 'string' ? e.where : '';
const raiser = ident(/PL\/pgSQL function (?:[A-Za-z_][A-Za-z0-9_]*\.)?([A-Za-z_][A-Za-z0-9_]*)[( ]/.exec(where)?.[1]);
diff --git a/src/core/persistence/sync-fault-class.ts b/src/core/persistence/sync-fault-class.ts
index 369c6efe8e..d3f71d733c 100644
--- a/src/core/persistence/sync-fault-class.ts
+++ b/src/core/persistence/sync-fault-class.ts
@@ -26,7 +26,8 @@
* model prose; the table row stays the lane's default for every other state.
*/
export type SyncFaultClass = 'page' | 'connection' | 'systemic';
-export type SyncSafeAction = 'retry' | 'retry_when_clean' | 'repair' | 'reconcile' | 'upgrade' | 'none';
+/** #6904: `migrate` applies the pending schema migrations (as the schema owner) before the write is resubmitted. */
+export type SyncSafeAction = 'retry' | 'retry_when_clean' | 'repair' | 'reconcile' | 'upgrade' | 'migrate' | 'none';
export interface SyncFaultRule {
code: string;
diff --git a/src/core/persistence/terminal-classify.ts b/src/core/persistence/terminal-classify.ts
index e0c030b413..9602dcd357 100644
--- a/src/core/persistence/terminal-classify.ts
+++ b/src/core/persistence/terminal-classify.ts
@@ -31,7 +31,9 @@ export type TerminalCategory =
| 'knock_on' | 'run_replaced' | 'outside_fence'
| 'operator_cancelled' | 'caller_conflict' | 'file_conflict' | 'canonical_file_missing' | 'fence_unrenderable'
| 'writer_guard' | 'database_refusal' | 'owner_exception' | 'legacy_publication_refusal'
- | 'sync_fault' | 'transport' | 'caller_refusal' | 'gbrain_defect' | 'diagnosis_required';
+ | 'sync_fault' | 'transport' | 'caller_refusal' | 'gbrain_defect' | 'diagnosis_required'
+ // #6904: the write met a missing relation or column (42P01 / 42703); the schema is behind this build or lost a table.
+ | 'schema_missing';
/** The receipt columns the classifier reads; every one but `intent_kind` and `error_message` survives compaction. */
export interface TerminalInput {
@@ -53,6 +55,11 @@ export interface TerminalInput {
error_message?: string | null;
/** A reader that computed `terminalKnockOnSql` passes its answer, so the SQL twin and this verdict cannot disagree. */
knock_on?: boolean;
+ /**
+ * #6904: whether the brain's schema is behind this build now (`readSchemaBehind`), which picks a `schema_missing` verdict's
+ * fix: apply-migrations when behind, the missing-tables check when at head. Absent or null: unknown, the fix is a doctor read.
+ */
+ schema_behind?: boolean | null;
}
export interface TerminalVerdict {
@@ -211,6 +218,10 @@ function route(input: TerminalInput): Partial_ {
'Read recent_failures[].error_detail from gbrain sources writer status --probe --json on the brain host, check doctor managed_guard_schema_drift, then retry the write with a new request id (gbrain repair failed-writes replays caller writes).'),
argv: ['gbrain', 'sources', 'writer', 'status', '--source', source, '--probe', '--json'] } };
}
+ // #6904: a missing relation or column, classified at publication, or recorded as an owner exception by an older build (its errno).
+ if (reason === 'schema_missing' || (origin === 'owner_exception' && ['42P01', '42703'].includes(stringField(detail, 'errno') ?? ''))) {
+ return schemaMissingVerdict(input, code, origin, stringField(detail, 'missing'));
+ }
if (origin === 'owner_exception') {
return { category: 'owner_exception', code, origin, class: 'systemic', safe_actions: ['upgrade'], needs_human: true,
human_reason: 'The owner raised an unexpected exception while running this write: a gbrain defect.',
@@ -305,6 +316,28 @@ function route(input: TerminalInput): Partial_ {
why: `The caller's write was refused ${code} and the caller saw why; the receipt carries the diagnosis, read-only.`, verify: { argv: failuresArgv(source) } } };
}
+/** #6904: the schema-missing verdict; the fix depends on whether the schema is behind this build right now. */
+function schemaMissingVerdict(input: TerminalInput, code: string, origin: string | null, missing: string | null): Partial_ {
+ const what = missing ? `the ${missing} relation or column` : 'a relation or column';
+ const verify = { argv: ['gbrain', 'doctor', '--json'] };
+ const base = { category: 'schema_missing' as const, code, origin, class: 'systemic' as const };
+ if (input.schema_behind === true) {
+ return { ...base, safe_actions: ['migrate'], needs_human: false, escalate: 'the schema is still behind after gbrain apply-migrations --yes (doctor schema_version names the failing migration)',
+ action: { argv: ['gbrain', 'apply-migrations', '--yes'], consent: [], actor: 'agent', requires_exclusive: true,
+ why: `The write needed ${what}, which a pending migration adds: the brain schema is behind this gbrain build. Apply the migrations as the database role that owns the gbrain tables, then resubmit the write with a new request id.`,
+ verify, docs: 'docs/guides/write-refusals.md#schema_behind' } };
+ }
+ if (input.schema_behind === false) {
+ const human = `The write needed ${what}, but the schema version is at head: a table or column is missing outside a migration (an older backup restored, a table dropped by hand, or a migration recorded without its change). Doctor's schema_missing_tables check names what is missing and gbrain repair missing-tables previews recreating it; decide with the user before applying.`;
+ return { ...base, safe_actions: ['repair'], needs_human: true, human_reason: human, escalate: 'always: the schema is at head and still lacks what the write needs',
+ action: { argv: ['gbrain', 'doctor', '--json'], consent: [], actor: 'agent', requires_exclusive: false, ask_user: true, user_message: human,
+ why: "Read-only: doctor's schema_missing_tables check lists the missing tables and columns and names the gbrain repair missing-tables preview.", verify } };
+ }
+ return { ...base, safe_actions: ['none'], needs_human: false, escalate: 'doctor reports the schema at head and the write still fails on a missing relation or column',
+ action: { argv: ['gbrain', 'doctor', '--json'], consent: [], actor: 'agent', requires_exclusive: false, verify,
+ why: `The write needed ${what}. Read-only: when doctor's schema_version reports the schema behind, run gbrain apply-migrations --yes as the database role that owns the gbrain tables and resubmit; when it is at head, its schema_missing_tables check names what is missing (gbrain repair missing-tables previews it).` } };
+}
+
function faultAction(code: string, input: TerminalInput): Action {
const v = classifySyncFault({ code });
if (v.safe_actions[0] === 'retry') return syncRetry(input.source_id, `The sync recorded ${code} (${v.class}); a rerun holds or retries it.`);
diff --git a/src/core/persistence/terminal-failures.ts b/src/core/persistence/terminal-failures.ts
index aff17521c0..14a986a34a 100644
--- a/src/core/persistence/terminal-failures.ts
+++ b/src/core/persistence/terminal-failures.ts
@@ -23,6 +23,7 @@
import type { BrainEngine } from '../engine.ts';
import type { Action } from '../agent-output.ts';
import { isStatementTimeout } from './bounded-reads.ts';
+import { readSchemaBehind } from './schema-admission.ts';
import { readReceiptRetentionDays, DEFAULT_RECEIPT_RETENTION_DAYS } from './limits.ts';
import type { PublicCategory } from './public-category.ts';
import { classifyTerminal, dispositionOf, driftSinceAction, TERMINAL_FIXED_IN, supersessionOrderSql, supersessionSql, terminalInspectArgv, terminalKnockOnSql, type TerminalCategory,
@@ -80,17 +81,19 @@ const BUILD = (r: string) => `COALESCE(${r}.error_detail->'attempt'->>'consumer_
const ENDED = (r: string) => `COALESCE(${r}.completed_at, ${r}.updated_at)`;
const TERMINAL = (r: string) => `${r}.state IN ('failed','conflict','cancelled')`;
/** A request holding a publication recovery record outside an in-flight claim: it blocks its root. `recovering` is the durable parked state (a blocked restore). */
+/** #6904: the grouped `reason`, with an older build's owner exception on a missing relation or column (its errno) read as `schema_missing`, as `classifyTerminal` reads the full detail. */
+const SCHEMA_AWARE_REASON = (r: string) => `COALESCE(${r}.error_detail->>'reason', CASE WHEN ${r}.error_detail->>'origin'='owner_exception' AND ${r}.error_detail->>'errno' IN ('42P01','42703') THEN 'schema_missing' END)`;
const RECOVERY = (r: string) => `(${r}.recovery IS NOT NULL AND ${r}.state IN ('committed','recovering','failed','conflict','cancelled'))`;
interface KeyColumns { source_id: string; state: string; error_code: string | null; origin: string | null; reason: string | null; cause: string | null; operation: string; intent_kind?: string | null;
has_recovery: boolean; blocked_reason: string | null; compacted: boolean; knock_on: boolean; routed_message: string | null; build: string | null }
-function verdictOf(row: KeyColumns & { request_id?: string; slug?: string; error_detail?: Record<string, unknown> | null }): TerminalVerdict {
+function verdictOf(row: KeyColumns & { request_id?: string; slug?: string; error_detail?: Record<string, unknown> | null }, schemaBehind: boolean | null = null): TerminalVerdict {
const detail = row.error_detail ?? (row.origin || row.reason || row.cause ? { ...(row.origin ? { origin: row.origin } : {}), ...(row.reason ? { reason: row.reason } : {}),
...(row.cause ? { cause: row.cause } : {}) } : null);
return classifyTerminal({ request_id: row.request_id, source_id: row.source_id, slug: row.slug ?? '<slug>', operation: row.operation, state: row.state, error_code: row.error_code,
error_detail: detail, recovery: row.has_recovery || null, blocked_reason: row.blocked_reason, compacted: row.compacted, knock_on: row.knock_on,
- error_message: row.routed_message, build: row.build, intent_kind: row.intent_kind ?? null })!;
+ error_message: row.routed_message, build: row.build, intent_kind: row.intent_kind ?? null, schema_behind: schemaBehind })!;
}
async function bounded<T>(engine: BrainEngine, sql: string, params: unknown[]): Promise<T[] | 'unknown'> {
@@ -125,13 +128,14 @@ export type TerminalSummary = { status: 'ok'; window_days: number; window_clampe
export async function readTerminalFailureSummary(engine: BrainEngine, opts: { sourceIds?: string[]; thresholds?: TerminalThresholds;
checkpointBlockers?: Map<string, Array<{ request_id: string; slug: string; knock_on: boolean; recovery: boolean }>> } = {}): Promise<TerminalSummary> {
const t = opts.thresholds ?? await readTerminalThresholds(engine);
+ const schemaBehind = await readSchemaBehind(engine);
const span = Math.max(t.windowDays, 8);
const days = Array.from({ length: 7 }, (_, i) => `count(*) FILTER (WHERE state IN ('failed','conflict','cancelled') AND ended_at <= now()-interval '${i + 1} day' AND ended_at > now()-interval '${i + 2} day')::int AS d${i + 2}`).join(',\n ');
const rows = await bounded<KeyColumns & { set: number; resolved: boolean | null; rows: number; in_window: number; n_24h: number; oldest: string | null; oldest_age: number | null;
distinct_slugs: number; distinct_intents: number; recovery_ids: string[] | null; recovery_slugs: string[] | null } & Record<string, number>>(engine,
`WITH base AS (
SELECT r.id, r.request_id::text AS request_id, r.source_id, r.slug, r.digest, r.sequence, r.operation, r.intent->>'kind' AS intent_kind, r.state, r.error_code,
- r.error_detail->>'origin' AS origin, r.error_detail->>'reason' AS reason, r.error_detail->>'cause' AS cause,
+ r.error_detail->>'origin' AS origin, ${SCHEMA_AWARE_REASON('r')} AS reason, r.error_detail->>'cause' AS cause,
r.recovery IS NOT NULL AS has_recovery, r.blocked_reason, r.compacted, ${terminalKnockOnSql('r')} AS knock_on,
${ROUTED_MESSAGE('r')} AS routed_message, ${BUILD('r')} AS build, ${ENDED('r')} AS ended_at
FROM persistence_requests r JOIN sources s ON s.id=r.source_id AND s.archived IS NOT TRUE
@@ -173,7 +177,7 @@ export async function readTerminalFailureSummary(engine: BrainEngine, opts: { so
s.daily_7d = Array.from({ length: 7 }, (_, i) => Number(row[`d${i + 2}`] ?? 0));
continue;
}
- const verdict = verdictOf(row);
+ const verdict = verdictOf(row, schemaBehind);
const n = Number(row.rows);
if (verdict.historical && Number(row.n_24h) > 0) {
s.new_last_24h_older_builds.rows += Number(row.n_24h);
@@ -181,7 +185,7 @@ export async function readTerminalFailureSummary(engine: BrainEngine, opts: { so
}
if (row.has_recovery) {
(row.recovery_ids ?? []).forEach((id, i) => {
- const v = verdictOf({ ...row, request_id: id, slug: row.recovery_slugs?.[i] });
+ const v = verdictOf({ ...row, request_id: id, slug: row.recovery_slugs?.[i] }, schemaBehind);
s.active_blockers.push({ kind: 'recovery', source_id: row.source_id, request_id: id, slug: row.recovery_slugs?.[i], category: v.category, action: v.action,
needs_human: v.needs_human, ...(v.human_reason ? { human_reason: v.human_reason } : {}) });
});
@@ -288,6 +292,7 @@ export function terminalFailuresArgv(q: TerminalFailureQuery, extra: Record<stri
*/
export async function readTerminalFailures(engine: BrainEngine, q: TerminalFailureQuery): Promise<TerminalFailureListing> {
const t = await readTerminalThresholds(engine, q.sinceDays);
+ const schemaBehind = await readSchemaBehind(engine);
const limit = Math.min(100, Math.max(1, q.limit ?? 20));
const state = q.state ?? 'unresolved';
const out: TerminalFailureRow[] = [];
@@ -313,7 +318,7 @@ export async function readTerminalFailures(engine: BrainEngine, q: TerminalFailu
for (const row of batch) {
scanned++;
cursor = row.sequence;
- const v = verdictOf(row);
+ const v = verdictOf(row, schemaBehind);
const disposition = dispositionOf(row.later_state ? { state: row.later_state, same_intent: row.same_intent === true } : null);
const historical = !row.has_recovery && (disposition !== 'unknown' || v.historical);
const matches = (!q.category || v.category === q.category) && (!q.code || v.code === q.code)
diff --git a/test/publication-failure-reason-6513.test.ts b/test/publication-failure-reason-6513.test.ts
index b3902fb45a..e9aafeb564 100644
--- a/test/publication-failure-reason-6513.test.ts
+++ b/test/publication-failure-reason-6513.test.ts
@@ -25,7 +25,7 @@ const raise = (raiser: string, message: string, extra: Record<string, unknown> =
const leak = (value: unknown) => JSON.stringify(value).includes(PRIVATE);
test('the reason enum is closed and covers the three known raisers; everything else is unknown', () => {
- expect([...PUBLICATION_REASONS].sort()).toEqual(['attribution_unclassified_table', 'graduation_in_progress', 'trust_unclassified_table', 'unknown']);
+ expect([...PUBLICATION_REASONS].sort()).toEqual(['attribution_unclassified_table', 'graduation_in_progress', 'schema_missing', 'trust_unclassified_table', 'unknown']);
const attribution = databaseRefusal(raise('gbrain_stamp_write_attribution', 'gbrain_stamp_write_attribution is not classified for table pages'))!;
expect(attribution).toMatchObject({ code: 'storage_error', detail: { origin: 'database_trigger', sqlstate: 'P0001', raiser: 'gbrain_stamp_write_attribution', table: 'pages', reason: 'attribution_unclassified_table' } });
expect(attribution.message).toBe('Publication failed (P0001 in gbrain_stamp_write_attribution: attribution_unclassified_table). Inspect owner diagnostics.');
diff --git a/test/terminal-schema-missing-6904.test.ts b/test/terminal-schema-missing-6904.test.ts
new file mode 100644
index 0000000000..88fbccaefe
--- /dev/null
+++ b/test/terminal-schema-missing-6904.test.ts
@@ -0,0 +1,123 @@
+/**
+ * #6904: a write that meets a missing relation or column (Postgres 42703 / 42P01) at publication is classified
+ * `schema_missing`, never an owner exception `defect` with `upgrade` as its safe action.
+ *
+ * Protects: on a real PGLite brain whose `sources.purge_epoch` column is missing (the column the issue hit), a put_page
+ * fails with `storage_error` whose detail records `reason: schema_missing`, the SQLSTATE and the missing column; the
+ * write-request diagnosis is `schema_missing` / `storage` with the fix for the schema state now (at head: ask the user,
+ * doctor's missing-tables check; behind: `gbrain apply-migrations --yes`); `gbrain sources writer failures` groups it under
+ * the same category; and a receipt an older build recorded as an owner exception with errno 42703 reads the same way.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { execFileSync } from 'node:child_process';
+import { randomUUID } from 'node:crypto';
+import { mkdirSync, mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type { BrainEngine } from '../src/core/engine.ts';
+import type { OperationContext } from '../src/core/operations.ts';
+import { OperationError } from '../src/core/ops/contract.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { claimWorktree } from '../src/core/persistence/ownership.ts';
+import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { databaseRefusal, publicFailureDetail } from '../src/core/persistence/publication-failure.ts';
+import { classifyTerminal } from '../src/core/persistence/terminal-classify.ts';
+import { readTerminalFailures, readTerminalFailureSummary } from '../src/core/persistence/terminal-failures.ts';
+import { LATEST_SCHEMA_VERSION } from '../src/core/schema-migrations/latest.generated.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const logger = { info() {}, warn() {}, error() {} };
+const SOURCE = 'schema-missing';
+let engine: BrainEngine;
+let dir: string;
+let ctx: OperationContext;
+let requestId: string;
+
+const inHome = <T>(fn: () => Promise<T>) => withEnv({ GBRAIN_HOME: join(dir, 'home') }, fn);
+const page = (title: string) => `---\ntype: note\ntitle: ${title}\n---\n\n${title} body.\n`;
+async function diagnosis(): Promise<Record<string, any>> {
+ const { operations } = await import('../src/core/operations.ts');
+ const receipt = await operations.find(op => op.name === 'get_write_request')!.handler(ctx, { request_id: requestId }) as Record<string, any>;
+ return receipt.diagnosis;
+}
+
+describe('#6904 a missing relation or column at publication is schema_missing', () => {
+ beforeAll(async () => {
+ dir = mkdtempSync(join(tmpdir(), 'gbrain-schema-missing-'));
+ const root = join(dir, 'brain'); mkdirSync(root);
+ execFileSync('git', ['init', '-q'], { cwd: root });
+ const pglite = new PGLiteEngine();
+ await pglite.connect({}); await pglite.initSchema(); engine = pglite;
+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', [SOURCE, root]);
+ await engine.setConfig('sync.write_through', 'true');
+ await inHome(() => claimWorktree(engine, SOURCE, root));
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ ctx = { engine, sourceId: SOURCE, remote: false, config: { engine: engine.kind, embedding_disabled: true } as never, dryRun: false, logger } as OperationContext;
+ await inHome(async () => {
+ await submitPageMutation(ctx, { operation: 'put_page', params: { slug: 'notes/before', content: page('before'), request_id: randomUUID() } });
+ await engine.executeRaw('ALTER TABLE sources DROP COLUMN purge_epoch');
+ requestId = randomUUID();
+ const error = await submitPageMutation(ctx, { operation: 'put_page', params: { slug: 'notes/after', content: page('after'), request_id: requestId } })
+ .then(() => null, (e: unknown) => e);
+ expect(error).toBeInstanceOf(OperationError);
+ });
+ }, 120_000);
+ afterAll(async () => {
+ await disposePersistenceConsumer(engine);
+ await engine.disconnect();
+ rmSync(dir, { recursive: true, force: true });
+ });
+
+ test('the receipt records storage_error with reason schema_missing, the SQLSTATE and the missing column', async () => {
+ const [row] = await engine.executeRaw<{ state: string; error_code: string; error_message: string; error_detail: Record<string, unknown> }>(
+ 'SELECT state,error_code,error_message,error_detail FROM persistence_requests WHERE request_id=$1', [requestId]);
+ expect(row).toMatchObject({ state: 'failed', error_code: 'storage_error', error_detail: { origin: 'database', reason: 'schema_missing', sqlstate: '42703', missing: 's.purge_epoch' } });
+ expect(row!.error_message).toContain('s.purge_epoch');
+ expect(publicFailureDetail(row!.error_detail)).toMatchObject({ origin: 'database', reason: 'schema_missing', sqlstate: '42703' });
+ });
+
+ test('at head the diagnosis is schema_missing / storage and asks the user, with the missing-tables check', () => inHome(async () => {
+ await engine.setConfig('version', String(LATEST_SCHEMA_VERSION));
+ const d = await diagnosis();
+ expect(d).toMatchObject({ category: 'schema_missing', public_category: 'storage', class: 'systemic', safe_actions: ['repair'], needs_human: true });
+ expect(d.human_reason).toContain('s.purge_epoch');
+ expect(d.human_reason).toContain('schema_missing_tables');
+ expect(d.human_reason).toContain('gbrain repair missing-tables');
+ expect(d.fix).toMatchObject({ argv: ['gbrain', 'doctor', '--json'], next: 'ask_user' });
+ }), 60_000);
+
+ test('behind, the diagnosis fix is apply-migrations as the schema owner, then resubmit', () => inHome(async () => {
+ await engine.setConfig('version', String(LATEST_SCHEMA_VERSION - 1));
+ try {
+ const d = await diagnosis();
+ expect(d).toMatchObject({ category: 'schema_missing', public_category: 'storage', safe_actions: ['migrate'], needs_human: false });
+ expect(d.fix).toMatchObject({ argv: ['gbrain', 'apply-migrations', '--yes'], next: 'run', verify: { argv: ['gbrain', 'doctor', '--json'] } });
+ expect(d.fix.why).toContain('owns the gbrain tables');
+ } finally { await engine.setConfig('version', String(LATEST_SCHEMA_VERSION)); }
+ }), 60_000);
+
+ test('sources writer failures groups the receipt under schema_missing, never as a defect', () => inHome(async () => {
+ const listing = await readTerminalFailures(engine, { sourceId: SOURCE });
+ expect(listing.status).not.toBe('unknown');
+ const rows = (listing as { rows: Array<{ request_id: string; category: string }> }).rows;
+ expect(rows.find(row => row.request_id === requestId)?.category).toBe('schema_missing');
+ const summary = await readTerminalFailureSummary(engine, { sourceIds: [SOURCE] }) as { sources: Array<{ categories: Array<{ category: string }>; defects: unknown[] }> };
+ expect(summary.sources[0]!.categories.map(entry => entry.category)).toContain('schema_missing');
+ expect(summary.sources[0]!.defects).toEqual([]);
+ }), 60_000);
+
+ test('a 42P01 is schema_missing with the relation, and an older build\'s owner-exception receipt with errno 42703 reads the same way', () => {
+ expect(databaseRefusal(Object.assign(new Error('relation "belief_ledger" does not exist'), { code: '42P01' })))
+ .toMatchObject({ code: 'storage_error', detail: { origin: 'database', reason: 'schema_missing', sqlstate: '42P01', missing: 'belief_ledger' } });
+ expect(databaseRefusal(Object.assign(new Error('syntax error at or near "x"'), { code: '42601' }))).toBeNull();
+ const legacy = classifyTerminal({ source_id: SOURCE, slug: 'notes/after', operation: 'put_page', state: 'failed', error_code: 'storage_error',
+ error_detail: { origin: 'owner_exception', error_class: 'PostgresError', errno: '42703' }, recovery: null, blocked_reason: null, compacted: false, schema_behind: true })!;
+ expect(legacy).toMatchObject({ category: 'schema_missing', public_category: 'storage', safe_actions: ['migrate'], defect: false });
+ expect(legacy.action.argv).toEqual(['gbrain', 'apply-migrations', '--yes']);
+ const unknown = classifyTerminal({ source_id: SOURCE, slug: 'notes/after', operation: 'put_page', state: 'failed', error_code: 'storage_error',
+ error_detail: { origin: 'database', sqlstate: '42703', reason: 'schema_missing' }, recovery: null, blocked_reason: null, compacted: false })!;
+ expect(unknown).toMatchObject({ category: 'schema_missing', safe_actions: ['none'], defect: false });
+ expect(unknown.action.argv).toEqual(['gbrain', 'doctor', '--json']);
+ });
+});