Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

graduation(g2a): G0 findings — source doctor in process (read-only), target doctor --scope=brain with wedged_queue exemption recorded in the receipt, timeline_history read-only under GBRAIN_GRADUATION_RUN, reconciliation re-enables triggers left disabled, plan blockers with DBA SQL for non-superuser targets, pooler startup-parameter refusal

garrytandaee30066e16
diff --git a/src/commands/doctor/checks/queue-jobs.ts b/src/commands/doctor/checks/queue-jobs.ts
index 92ec14157b..ae7edb4c20 100644
--- a/src/commands/doctor/checks/queue-jobs.ts
+++ b/src/commands/doctor/checks/queue-jobs.ts
@@ -375,6 +375,12 @@ export async function computeWedgedQueueCheck(
if (wedged.length === 0) {
return { name: 'wedged_queue', status: 'ok', message: 'No wedged queues' };
}
+ // The verify-step doctor of an engine graduation runs on the fenced target before any worker may
+ // start, so waiting jobs carried from the quiesced source cannot have progressed yet.
+ if (process.env.GBRAIN_GRADUATION_RUN) {
+ return { name: 'wedged_queue', status: 'warn', message: `Graduation exemption: ${wedged.map(w => w.label).join(', ')} carried from the quiesced source; workers start after cutover.`,
+ details: { graduation_exempt: true, run_id: process.env.GBRAIN_GRADUATION_RUN, queues: wedged.map(w => w.queue) } };
+ }
// #3063: "worker alive but not claiming work" would be a false claim
// for a queue no worker process was ever subscribed to. Split the
// wedged set by whether a registered live worker actually exists for
diff --git a/src/commands/doctor/checks/timeline-history.ts b/src/commands/doctor/checks/timeline-history.ts
index b3229dee3d..3cc7d64c72 100644
--- a/src/commands/doctor/checks/timeline-history.ts
+++ b/src/commands/doctor/checks/timeline-history.ts
@@ -43,6 +43,8 @@ async function loadState(engine: BrainEngine, key: string): Promise<ScanState |
}
async function saveState(engine: BrainEngine, key: string, state: ScanState): Promise<void> {
+ // Engine graduation runs doctor as a read-only gate (source at plan/run start, target under the fence): no scan-state write.
+ if (process.env.GBRAIN_GRADUATION_RUN) return;
try { await engine.setConfig(key, JSON.stringify(state)); } catch { /* best effort: the next run rescans from the start */ }
}
diff --git a/src/core/persistence/engine-graduation.ts b/src/core/persistence/engine-graduation.ts
index 58d21984ef..723ed86abf 100644
--- a/src/core/persistence/engine-graduation.ts
+++ b/src/core/persistence/engine-graduation.ts
@@ -113,7 +113,7 @@ export interface GraduationDeps {
initTargetSchema(target: BrainEngine, source: BrainEngine): Promise<void>;
claimAutopilotPause(): Promise<(() => void) | null>;
/** Failing check names of `gbrain doctor --no-migrate --json` against the fenced target. */
- runTargetDoctor(runId: string, mainUrl: string): Promise<readonly string[]>;
+ runTargetDoctor(runId: string, mainUrl: string): Promise<{ failing: readonly string[]; exempted: readonly string[] }>;
/** Failing source checks, measured with the source open under the run's lock. */
runSourceDoctor(source: BrainEngine): Promise<readonly string[]>;
hostId(): string;
@@ -156,7 +156,18 @@ export function defaultGraduationDeps(): GraduationDeps {
},
claimAutopilotPause: () => withStdoutOnStderr(() => quiesceAutopilot()),
async runTargetDoctor(runId, mainUrl) { return spawnTargetDoctor(runId, mainUrl); },
- async runSourceDoctor() { return []; },
+ async runSourceDoctor(source) {
+ // In process, on the engine this run (or plan) already opened; GBRAIN_GRADUATION_RUN keeps doctor read-only.
+ const { buildChecks } = await import('../../commands/doctor.ts');
+ const prior = process.env.GBRAIN_GRADUATION_RUN;
+ process.env.GBRAIN_GRADUATION_RUN = prior || 'source-doctor';
+ try {
+ const checks = await buildChecks(source, ['--json', '--scope=brain']);
+ return checks.filter(c => c.status === 'fail').map(c => c.name);
+ } finally {
+ if (prior === undefined) delete process.env.GBRAIN_GRADUATION_RUN; else process.env.GBRAIN_GRADUATION_RUN = prior;
+ }
+ },
hostId: () => localHostId(),
mountsPath: () => process.env.GBRAIN_MOUNTS_PATH || join(homedir(), '.gbrain', 'mounts.json'),
};
@@ -168,17 +179,18 @@ async function withStdoutOnStderr<T>(fn: () => Promise<T>): Promise<T> {
try { return await fn(); } finally { console.log = log; }
}
-function spawnTargetDoctor(runId: string, mainUrl: string): readonly string[] {
+function spawnTargetDoctor(runId: string, mainUrl: string): { failing: readonly string[]; exempted: readonly string[] } {
const script = process.argv[1] && /\.(ts|js|mjs)$/.test(process.argv[1]) ? [process.argv[1]] : [];
- const child = spawnSync(process.execPath, [...script, 'doctor', '--no-migrate', '--json'], {
+ const child = spawnSync(process.execPath, [...script, 'doctor', '--no-migrate', '--json', '--scope=brain'], {
env: { ...process.env, GBRAIN_DATABASE_URL: mainUrl, GBRAIN_GRADUATION_RUN: runId },
encoding: 'utf8', timeout: 600_000, maxBuffer: 64 * 1024 * 1024,
});
try {
- const doc = JSON.parse(child.stdout) as { checks?: Array<{ name?: string; status?: string }> };
- if (!Array.isArray(doc.checks)) return ['doctor_output_unreadable'];
- return doc.checks.filter(c => c.status === 'fail').map(c => String(c.name ?? 'unnamed'));
- } catch { return ['doctor_unavailable']; }
+ const doc = JSON.parse(child.stdout) as { checks?: Array<{ name?: string; status?: string; details?: { graduation_exempt?: boolean } }> };
+ if (!Array.isArray(doc.checks)) return { failing: ['doctor_output_unreadable'], exempted: [] };
+ return { failing: doc.checks.filter(c => c.status === 'fail').map(c => String(c.name ?? 'unnamed')),
+ exempted: doc.checks.filter(c => c.details?.graduation_exempt === true).map(c => String(c.name ?? 'unnamed')) };
+ } catch { return { failing: ['doctor_unavailable'], exempted: [] }; }
}
function mapTargetConnectError(error: unknown, routes: Routes): unknown {
@@ -186,6 +198,11 @@ function mapTargetConnectError(error: unknown, routes: Routes): unknown {
if (e?.code === '28P01' || /password authentication failed/i.test(e?.message ?? '')) {
return targetAuthFailedError({ host: routes.main, ...(routes.urlEnv ? { urlEnv: routes.urlEnv } : {}) });
}
+ if (/unsupported startup parameter/i.test(e?.message ?? '')) {
+ return targetUnsupportedError({ requirement: 'pooler_startup_parameters', host: routes.main,
+ detail: 'the connection pooler refuses the statement_timeout and idle_in_transaction_session_timeout startup parameters gbrain sends; add both to ignore_startup_parameters in pgbouncer.ini, or point --url-env (and GBRAIN_DIRECT_DATABASE_URL) at a direct or session-mode connection',
+ ...(routes.urlEnv ? { spelling: { urlEnv: routes.urlEnv } } : {}) });
+ }
return error;
}
@@ -848,19 +865,25 @@ async function stepVerify(run: Run): Promise<void> {
const started = Date.now();
await run.deps.assertRelationSet(run.main!, 'postgres', run.deps.inventory);
phase(run, 'verify');
+ let exempted: readonly string[] = [];
const result = await run.deps.verifyGraduation({ source: run.source!, target: run.main! }, {
inventory: run.deps.inventory, sourceReceipts: run.m.sourceReceipts ?? [], replayRequestId: run.m.replayRequestId ?? undefined,
runId: run.m.runId, expectFence: true,
- runDoctor: () => { phase(run, 'doctor'); return run.deps.runTargetDoctor(run.m.runId, run.m.targetUrls!.main); },
+ runDoctor: async () => {
+ phase(run, 'doctor');
+ const doctor = await run.deps.runTargetDoctor(run.m.runId, run.m.targetUrls!.main);
+ exempted = doctor.exempted;
+ return doctor.failing;
+ },
});
const timings = { ...run.m.timings, verify_ms: Date.now() - started };
if (!result.ok) {
- await withGraduationRun(run.main!, run.m.runId, tx => setTargetState(tx, run.m.runId, 'verify_failed', { tableReceipts: result.tables, replayProbe: result.replay, timings, doctor: { target: result.doctorFailingChecks } }));
+ await withGraduationRun(run.main!, run.m.runId, tx => setTargetState(tx, run.m.runId, 'verify_failed', { tableReceipts: result.tables, replayProbe: result.replay, timings, doctor: { source: [], target: result.doctorFailingChecks, exempted } }));
advance(run, 'verify_failed', { verifyFailures: result.failures, timings });
const repeated = result.failures.some(f => prior.some(p => p.relation === f.relation && p.kind === f.kind));
throw verifyFailedError({ failures: result.failures, repeated });
}
- await withGraduationRun(run.main!, run.m.runId, tx => setTargetState(tx, run.m.runId, 'verified', { tableReceipts: result.tables, replayProbe: result.replay, timings, triggerBypass: run.m.triggerBypass, doctor: { target: result.doctorFailingChecks } }));
+ await withGraduationRun(run.main!, run.m.runId, tx => setTargetState(tx, run.m.runId, 'verified', { tableReceipts: result.tables, replayProbe: result.replay, timings, triggerBypass: run.m.triggerBypass, doctor: { source: [], target: result.doctorFailingChecks, exempted } }));
run.m.tables = run.m.tables.map(t => ({ ...t, state: 'verified' as const }));
advance(run, 'verified', { verifyFailures: [], timings });
await boundary(run, 'verified');
@@ -949,11 +972,11 @@ function rewriteMounts(path: string, match: (m: MountRecord) => boolean, rewrite
async function receiptOf(run: Run): Promise<GraduationReceipt> {
if (!run.main) await openTargets(run);
const row = await readGraduationRow(run.main!);
- const doctor = (row?.doctor ?? {}) as { source?: readonly string[]; target?: readonly string[] };
+ const doctor = (row?.doctor ?? {}) as { source?: readonly string[]; target?: readonly string[]; exempted?: readonly string[] };
return { runId: run.m.runId, state: (row?.state ?? 'authoritative') as GraduationReceipt['state'], tables: row?.table_receipts ?? [],
triggerBypass: run.m.triggerBypass, replay: row?.replay_probe ?? { status: 'not_available', reason: 'no_uncompacted_request' }, timings: run.m.timings,
targetDisplayUrl: run.m.routes.main, retainedPath: graduatedPath(run.dataDir, run.m.runId), serveHandoff: run.serveHandoff,
- doctor: { source: doctor.source ?? [], target: doctor.target ?? [] } };
+ doctor: { source: doctor.source ?? [], target: doctor.target ?? [], exempted: doctor.exempted ?? [] } };
}
async function takeKernelLock(run: Run): Promise<void> {
@@ -1109,6 +1132,17 @@ export async function resumeGraduation(opts: RunOptions = {}): Promise<Graduatio
// ── reconciliation ─────────────────────────────────────────────────────────
+/** A crash under the DISABLE TRIGGER fallback can leave user triggers off: re-enable every table the manifest recorded. */
+async function repairDisabledTriggers(run: Run): Promise<boolean> {
+ const disabled = run.m.tables.filter(t => t.disabledTriggers).map(t => t.relation);
+ if (!disabled.length) return false;
+ await openTargets(run);
+ await run.deps.reenableTriggers(run.main!, disabled, { runId: run.m.runId });
+ run.m.tables = run.m.tables.map(t => ({ ...t, disabledTriggers: false }));
+ save(run);
+ return true;
+}
+
export interface ReconcileResult { state: ManifestState | 'none'; actions: readonly string[]; detail: string }
async function reconcileRun(run: Run): Promise<ReconcileResult> {
@@ -1128,6 +1162,7 @@ async function reconcileRun(run: Run): Promise<ReconcileResult> {
await installGraduationFence(run.ddl!, run.m.runId);
actions.push('re-installed target fence');
}
+ if (await repairDisabledTriggers(run)) actions.push('re-enabled user triggers left disabled');
}
return { state: run.m.state, actions, detail: actions.join('; ') };
}
@@ -1186,6 +1221,7 @@ async function rollbackBeforeCutover(run: Run): Promise<GraduationRollbackResult
await withGraduationRun(run.main!, run.m.runId, tx => setTargetState(tx, run.m.runId, 'abandoned'));
await installGraduationFence(run.ddl!, run.m.runId);
}
+ if (row?.role === 'target' && row.run_id === run.m.runId) await repairDisabledTriggers(run);
}
advance(run, 'abandoned');
return { state: 'abandoned', restoredPath: null, dropped: [] };
diff --git a/src/core/persistence/engine-graduation.types.ts b/src/core/persistence/engine-graduation.types.ts
index 74db18ff47..de227fa976 100644
--- a/src/core/persistence/engine-graduation.types.ts
+++ b/src/core/persistence/engine-graduation.types.ts
@@ -169,6 +169,10 @@ export interface TargetProbe {
embeddingColumns: readonly EmbeddingColumn[];
/** Other sessions on the target database (informational). */
otherSessions: number;
+ /** The connecting role: initSchema needs superuser, or BYPASSRLS plus a pre-created auto-RLS event trigger it owns the function of. */
+ role?: { name: string; superuser: boolean; bypassRls: boolean };
+ /** The v35 `auto_rls_on_create_table` event trigger and the owner of `public.auto_enable_rls()` (null when absent). */
+ autoRls?: { eventTrigger: boolean; functionOwner: string | null };
}
export interface SourceIdentity {
@@ -333,7 +337,7 @@ export interface GraduationReceipt {
/** True when a live serve handed the source over through the intent marker. */
serveHandoff?: boolean;
/** Failing doctor check names on each side; the cutover gate is `target` empty. */
- doctor?: { source: readonly string[]; target: readonly string[] };
+ doctor?: { source: readonly string[]; target: readonly string[]; /** Checks the verify-step doctor exempted, with the run's reason. */ exempted?: readonly string[] };
}
// ── CLI <-> orchestrator (src/commands/migrate-graduation.ts consumes; engine-graduation.ts implements) ──
diff --git a/src/core/persistence/graduation-target.ts b/src/core/persistence/graduation-target.ts
index 1a97274f4a..e41bb2ce1a 100644
--- a/src/core/persistence/graduation-target.ts
+++ b/src/core/persistence/graduation-target.ts
@@ -207,6 +207,14 @@ export async function probeTarget(routes: ResolvedTargetRoutes, opts: { timeoutS
const [owned] = await query<{ ok: boolean }>(`SELECT COALESCE(bool_and(pg_has_role(current_user, c.relowner, 'USAGE')), true) AS ok
FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = 'public' AND c.relkind IN ('r', 'p')`);
probe.ownsTables = owned?.ok === true;
+ const [role] = await query<{ name: string; superuser: boolean; bypass: boolean; trigger: boolean; owner: string | null }>(`SELECT current_user AS name,
+ (SELECT rolsuper FROM pg_roles WHERE rolname = current_user) AS superuser,
+ EXISTS (SELECT 1 FROM pg_roles pr WHERE pg_has_role(current_user, pr.oid, 'USAGE') AND (pr.rolbypassrls OR pr.rolsuper)) AS bypass,
+ EXISTS (SELECT 1 FROM pg_event_trigger WHERE evtname = 'auto_rls_on_create_table') AS trigger,
+ (SELECT pg_get_userbyid(p.proowner) FROM pg_proc p JOIN pg_namespace n ON n.oid = p.pronamespace
+ WHERE n.nspname = 'public' AND p.proname = 'auto_enable_rls' LIMIT 1) AS owner`);
+ probe.role = { name: role!.name, superuser: role!.superuser === true, bypassRls: role!.bypass === true };
+ probe.autoRls = { eventTrigger: role!.trigger === true, functionOwner: role!.owner ?? null };
Object.assign(probe, await targetEmptiness(query));
probe.embeddingColumns = await embeddingColumns(query);
await query('SAVEPOINT gbrain_replica_probe');
@@ -253,7 +261,19 @@ export function targetProbeBlockers(probe: TargetProbe, routes: Pick<TargetRoute
if (!probe.vector.installed && !probe.vector.available) blockers.push(unsupported('vector_extension', 'the vector extension is neither installed nor available'));
else if (!probe.vector.halfvec) blockers.push(unsupported('vector_halfvec', `vector ${probe.vector.installed ?? probe.vector.available} predates halfvec (needs ${MIN_VECTOR_HALFVEC_VERSION} or newer)`));
if (!probe.createPrivilege.schema) blockers.push(unsupported('create_privilege', `role cannot CREATE in schema public on ${routes.main}`));
- if (!probe.vector.installed && !probe.createPrivilege.database) blockers.push(unsupported('create_extension', 'vector is not installed and the role lacks CREATE on the database to install it'));
+ const superuser = probe.role?.superuser === true;
+ const role = probe.role ? `"${probe.role.name.replace(/"/g, '""')}"` : 'CURRENT_USER';
+ if (!probe.vector.installed && (!superuser || !probe.createPrivilege.database)) {
+ blockers.push(unsupported('vector_extension', 'the vector extension is not installed and only a superuser can install it; a DBA runs in the target database: CREATE EXTENSION IF NOT EXISTS vector;'));
+ }
+ if (probe.role && !superuser && !probe.role.bypassRls) {
+ blockers.push(unsupported('bypassrls', `role ${probe.role.name} lacks BYPASSRLS, which the schema's RLS backfill needs; a DBA runs: ALTER ROLE ${role} BYPASSRLS;`));
+ }
+ if (probe.autoRls && !superuser && !probe.autoRls.eventTrigger) {
+ blockers.push(unsupported('auto_rls_event_trigger', `the auto-RLS event trigger is missing and only a superuser can create it; a DBA runs in the target database: ${AUTO_RLS_DBA_SQL(role)}`));
+ } else if (probe.autoRls && !superuser && probe.autoRls.functionOwner && probe.role && probe.autoRls.functionOwner !== probe.role.name) {
+ blockers.push(unsupported('auto_rls_owner', `public.auto_enable_rls() is owned by ${probe.autoRls.functionOwner}, so schema setup fails with "must be owner of function"; a DBA runs: ALTER FUNCTION public.auto_enable_rls() OWNER TO ${role};`));
+ }
if (!probe.triggerBypass) blockers.push(unsupported('trigger_bypass', 'the role may neither set session_replication_role = replica nor owns the existing tables (needed for DISABLE TRIGGER)'));
if (!probe.empty) blockers.push({ kind: 'target_not_empty', id: 'target', detail: `target already holds rows in ${probe.nonEmptyTables.slice(0, 10).join(', ')}`, argv, needsUser: true });
for (const m of embeddingLayoutMismatches(sourceColumns, probe.embeddingColumns)) {
@@ -262,6 +282,13 @@ export function targetProbeBlockers(probe: TargetProbe, routes: Pick<TargetRoute
return blockers;
}
+/** What a DBA runs once on a target whose gbrain role is not a superuser (the v35 objects, owned by that role). */
+function AUTO_RLS_DBA_SQL(role: string): string {
+ return `CREATE OR REPLACE FUNCTION public.auto_enable_rls() RETURNS event_trigger LANGUAGE plpgsql AS $f$ DECLARE obj record; BEGIN FOR obj IN SELECT * FROM pg_event_trigger_ddl_commands() WHERE object_type = 'table' AND schema_name = 'public' LOOP EXECUTE format('ALTER TABLE %s ENABLE ROW LEVEL SECURITY', obj.object_identity); END LOOP; END; $f$; `
+ + `ALTER FUNCTION public.auto_enable_rls() OWNER TO ${role}; `
+ + `CREATE EVENT TRIGGER auto_rls_on_create_table ON ddl_command_end WHEN TAG IN ('CREATE TABLE', 'CREATE TABLE AS', 'SELECT INTO') EXECUTE FUNCTION public.auto_enable_rls();`;
+}
+
/** Throws the typed refusal when either route is unreachable or refuses authentication. */
export function assertTargetReachable(probe: TargetProbe, routes: Pick<TargetRoutes, 'urlEnv' | 'main' | 'ddl'>): void {
const spelling = routes.urlEnv ? { urlEnv: routes.urlEnv } : {};
diff --git a/test/helpers/graduation-harness.ts b/test/helpers/graduation-harness.ts
index f9a1225ce9..b9d8fe9b43 100644
--- a/test/helpers/graduation-harness.ts
+++ b/test/helpers/graduation-harness.ts
@@ -175,7 +175,7 @@ export async function makeHarness(opts: HarnessOptions = {}): Promise<Harness> {
connectTargets: async () => ({ main: borrowed(target), ddl: borrowed(target), close: async () => {} }),
initTargetSchema: async t => { await t.initSchema(); await t.executeRaw(PROBE_DDL); },
claimAutopilotPause: async () => () => { count('pause_released'); },
- runTargetDoctor: async () => [],
+ runTargetDoctor: async () => ({ failing: [], exempted: [] }),
runSourceDoctor: async () => [],
hostId: () => '00000000-0000-4000-8000-00000000beef',
mountsPath: () => mountsPath,