Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(minions): reconnect the stall timer, stop failJob masking job errors, unify retry matchers (#1720) (#3555)
Garry Tan69be8bb707b8
diff --git a/src/core/db.ts b/src/core/db.tsindex 99dae2136a..45aec00a46 100644--- a/src/core/db.ts+++ b/src/core/db.ts@@ -3,6 +3,7 @@ import { GBrainError, type EngineConfig } from './types.ts';import { SCHEMA_SQL } from './schema-embedded.ts';import type { BrainEngine } from './engine.ts';import { verifySchema } from './schema-verify.ts';+import { isRetryableConnError } from './retry-matcher.ts';let sql: ReturnType<typeof postgres> | null = null;let connectedUrl: string | null = null;@@ -322,19 +323,14 @@ export async function withTransaction<T>(fn: (tx: ReturnType<typeof postgres>) =}) as Promise<T>;}-const RETRYABLE_DB_CONNECT_PATTERNS = [- /password authentication failed/i,- /connection refused/i,- /the database system is starting up/i,- /Connection terminated unexpectedly/i,- /ECONNRESET/i,-];--export function isRetryableDbConnectError(err: unknown): boolean {- const msg = err instanceof Error ? err.message : String(err);- if (!msg) return false;- return RETRYABLE_DB_CONNECT_PATTERNS.some(p => p.test(msg));-}+// issue #1720 (proposal 4): the startup connect matcher and the runtime+// matcher drifted — this used to be a private 5-pattern list that predated+// /connection.*closed/i and the CONNECTION_ENDED/CONNECTION_CLOSED codes, so+// a pooler close hitting connectWithRetry was treated as permanent. One+// canonical source now: retry-matcher.ts's isRetryableConnError (a strict+// superset of the old list). Do NOT reintroduce a local pattern list here;+// the agreement guard in test/worker-conn-resilience-1720.test.ts pins it.+export const isRetryableDbConnectError = isRetryableConnError;export interface ConnectWithRetryOpts {attempts?: number;diff --git a/src/core/minions/worker.ts b/src/core/minions/worker.tsindex 3117eed34c..06fe7062e8 100644--- a/src/core/minions/worker.ts+++ b/src/core/minions/worker.ts@@ -295,18 +295,32 @@ export class MinionWorker extends EventEmitter {// so a stalled job (lock_until expired) gets requeued before handleTimeouts'// `lock_until > now()` guard would skip it. Stall → retry, timeout → dead.const stalledTimer = setInterval(async () => {+ // issue #1720: a dead pool used to spray "Stall detection error: write+ // CONNECTION_CLOSED ..." every tick forever — this interval was the only+ // background loop without the #1491-style reconnect. Rebuild the+ // worker-owned pool AT MOST ONCE per tick, shared across the three+ // sweeps: a dead pool fails all three, and one rebuild is enough (three+ // back-to-back connect attempts would just add pooler pressure).+ let reconnectedThisTick = false;+ const recoverConnection = async (site: string, e: unknown): Promise<void> => {+ if (reconnectedThisTick || !isRetryableConnError(e)) return;+ reconnectedThisTick = true;+ await this.reconnectAfterConnectionError(site, e);+ };try {const { requeued, dead } = await this.queue.handleStalled();if (requeued.length > 0) console.log(`Stall detector: requeued ${requeued.length} jobs`);if (dead.length > 0) console.log(`Stall detector: dead-lettered ${dead.length} jobs`);} catch (e) {console.error('Stall detection error:', e instanceof Error ? e.message : String(e));+ await recoverConnection('handleStalled', e);}try {const timedOut = await this.queue.handleTimeouts();if (timedOut.length > 0) console.log(`Timeout detector: dead-lettered ${timedOut.length} jobs (timeout exceeded)`);} catch (e) {console.error('Timeout detection error:', e instanceof Error ? e.message : String(e));+ await recoverConnection('handleTimeouts', e);}try {const wallClockTimedOut = await this.queue.handleWallClockTimeouts(this.opts.lockDuration);@@ -315,6 +329,7 @@ export class MinionWorker extends EventEmitter {}} catch (e) {console.error('Wall-clock timeout detection error:', e instanceof Error ? e.message : String(e));+ await recoverConnection('handleWallClockTimeouts', e);}}, this.opts.stalledInterval);@@ -1125,7 +1140,34 @@ export class MinionWorker extends EventEmitter {attempts_made: job.attempts_made + 1,}) : 0;- const failed = await this.queue.failJob(job.id, lockToken, errorText, newStatus, backoffMs);+ // issue #1720: failJob can itself throw during the same DB outage that+ // failed the job. Pre-fix the rejection escaped to launchJob's .catch+ // and the ORIGINAL job error was never logged anywhere — the recording+ // error masked it. Log the original FIRST (it must survive no matter+ // what), then reconnect + retry the recording once. If it still fails,+ // leave the row to the stall detector: the lock has stopped renewing,+ // so handleStalled requeues it cleanly on a live pool (the D8a path).+ let failed: MinionJob | null;+ try {+ failed = await this.queue.failJob(job.id, lockToken, errorText, newStatus, backoffMs);+ } catch (recordErr) {+ const recordMsg = recordErr instanceof Error ? recordErr.message : String(recordErr);+ console.error(+ `Job ${job.id} (${job.name}) failed with: ${errorText} — and recording the failure threw: ${recordMsg}`,+ );+ if (!isRetryableConnError(recordErr)) throw recordErr;+ await this.reconnectAfterConnectionError('failJob', recordErr);+ try {+ failed = await this.queue.failJob(job.id, lockToken, errorText, newStatus, backoffMs);+ } catch (retryErr) {+ console.error(+ `Job ${job.id} (${job.name}) failure-recording retry also failed ` ++ `(${retryErr instanceof Error ? retryErr.message : String(retryErr)}); ` ++ `leaving the row for the stall detector to requeue after lock expiry`,+ );+ return;+ }+ }if (!failed) {console.warn(`Job ${job.id} failure dropped (lock token mismatch)`);return;diff --git a/src/core/retry-matcher.ts b/src/core/retry-matcher.tsindex c25605e8d8..29816f10bb 100644--- a/src/core/retry-matcher.ts+++ b/src/core/retry-matcher.ts@@ -112,6 +112,11 @@ export function isRetryableConnError(err: unknown): boolean {// v0.42.5.0 (issue #1678): postgres.js's library-level connection-ended// code. Not an 08xxx SQLSTATE, so the /^08/ test above misses it.if (code === 'CONNECTION_ENDED') return true;+ // issue #1720: postgres.js also throws code 'CONNECTION_CLOSED' when the+ // pooler closes the socket mid-query ("write CONNECTION_CLOSED host:port").+ // The message form is already caught by /connection.*closed/i below; match+ // the code too for wrappers that rethrow with the code but a new message.+ if (code === 'CONNECTION_CLOSED') return true;// v0.42.x (#1794): SQLSTATE 53300 too_many_connections — pool/pooler// exhaustion. Starts with 53 not 08, so the /^08/ test above misses it.// Transient: the spike clears as in-flight queries release connections.diff --git a/test/worker-conn-resilience-1720.test.ts b/test/worker-conn-resilience-1720.test.tsnew file mode 100644index 0000000000..594ef35418--- /dev/null+++ b/test/worker-conn-resilience-1720.test.ts@@ -0,0 +1,212 @@+/**+ * issue #1720 — autopilot worker crash-loops on pooler CONNECTION_CLOSED.+ *+ * PRs #2025 (#1491) and #1824 (#1801) fixed the promoteDelayed/claim loops and+ * added the supervised db-liveness probe, but three gaps remained:+ *+ * 1. The stall-detection interval had NO reconnect — a dead pool sprayed+ * "Stall detection error: write CONNECTION_CLOSED ..." every tick until+ * the ~3-minute db_dead exit (the reporter's 20k-line log spray).+ * 2. `failJob` was unwrapped — when recording a failure threw on the same+ * dead pool, the ORIGINAL job error was never logged anywhere (masked),+ * and no reconnect happened.+ * 3. The startup connect matcher (db.ts isRetryableDbConnectError) and the+ * runtime matcher (retry-matcher.ts isRetryableConnError) had drifted:+ * the startup list lacked /connection.*closed/ + CONNECTION_CLOSED.+ *+ * These tests inject the postgres.js error SHAPES (message + code) — a real+ * Supavisor pooler close is not reproducible in CI (UNVERIFIED-ON-ENVIRONMENT).+ */++import { describe, expect, test } from 'bun:test';+import { MinionWorker } from '../src/core/minions/worker.ts';+import type { BrainEngine } from '../src/core/engine.ts';+import type { MinionJob } from '../src/core/minions/types.ts';+import { isRetryableConnError } from '../src/core/retry-matcher.ts';++/** The exact shape postgres.js throws when a pooler closes the socket. */+function connClosed(): Error {+ return Object.assign(+ new Error('write CONNECTION_CLOSED db.pooler.example:5432'),+ { code: 'CONNECTION_CLOSED' },+ );+}++function makeEngine(counter: { reconnects: number }): BrainEngine {+ return {+ kind: 'postgres',+ reconnect: async () => { counter.reconnects += 1; },+ } as unknown as BrainEngine;+}++/** Swap the worker's private queue for a fake (same pattern as worker-promote-reconnect.test.ts). */+function setQueue(worker: MinionWorker, queue: Record<string, unknown>): void {+ (worker as unknown as { queue: Record<string, unknown> }).queue = queue;+}++async function withCapturedConsoleError<T>(fn: () => Promise<T>): Promise<{ result: T; lines: string[] }> {+ const lines: string[] = [];+ const orig = console.error;+ console.error = (...args: unknown[]) => { lines.push(args.map(String).join(' ')); };+ try {+ const result = await fn();+ return { result, lines };+ } finally {+ console.error = orig;+ }+}++describe('stall-detection interval reconnect (#1720 gap 1)', () => {+ test('a retryable connection error in the stall sweep rebuilds the pool — once per tick across all three sweeps', async () => {+ const counter = { reconnects: 0 };+ const worker = new MinionWorker(makeEngine(counter), {+ pollInterval: 1,+ stalledInterval: 10,+ healthCheckInterval: 0,+ });+ worker.register('noop', async () => ({}));++ let tickDone = false;+ let claims = 0;+ const threw = { stalled: false, timeouts: false, wallClock: false };+ setQueue(worker, {+ ensureSchema: async () => {},+ promoteDelayed: async () => [],+ claim: async () => {+ claims += 1;+ // Stop once the first stall tick fully ran (or bail out after a bound+ // so an unfixed build terminates and FAILS the assertion, not hangs).+ if (tickDone || claims > 2000) worker.stop();+ return null;+ },+ handleStalled: async () => {+ if (!threw.stalled) { threw.stalled = true; throw connClosed(); }+ return { requeued: [], dead: [] };+ },+ handleTimeouts: async () => {+ if (!threw.timeouts) { threw.timeouts = true; throw connClosed(); }+ return [];+ },+ handleWallClockTimeouts: async () => {+ if (!threw.wallClock) { threw.wallClock = true; tickDone = true; throw connClosed(); }+ tickDone = true;+ return [];+ },+ });++ const { lines } = await withCapturedConsoleError(() => worker.start());++ // The tick actually exercised the failing sweeps...+ expect(lines.some(l => l.startsWith('Stall detection error:'))).toBe(true);+ // ...and the worker repaired its pool in-process: exactly ONE reconnect+ // for the tick even though all three sweeps failed (no pooler hammering).+ expect(counter.reconnects).toBe(1);+ });+});++describe('failJob failure-recording resilience (#1720 gap 2)', () => {+ test('when failJob throws a conn error: original job error is surfaced, pool reconnects, recording is retried once', async () => {+ const counter = { reconnects: 0 };+ const worker = new MinionWorker(makeEngine(counter), {+ pollInterval: 1,+ stalledInterval: 60_000,+ healthCheckInterval: 0,+ lockDuration: 60_000,+ concurrency: 1,+ });+ worker.register('explode', async () => { throw new Error('boom: the real job defect'); });++ const job = {+ id: 42,+ name: 'explode',+ queue: 'default',+ data: {},+ status: 'active',+ attempts_made: 2,+ attempts_started: 3,+ max_attempts: 3, // attempts exhausted → newStatus 'dead', no backoff math+ backoff_type: 'exponential',+ backoff_delay: 1000,+ backoff_jitter: false,+ timeout_ms: null,+ timeout_at: null,+ parent_job_id: null,+ } as unknown as MinionJob;++ let failJobCalls = 0;+ let handedOut = false;+ let done = false;+ let claims = 0;+ setQueue(worker, {+ ensureSchema: async () => {},+ promoteDelayed: async () => [],+ handleStalled: async () => ({ requeued: [], dead: [] }),+ handleTimeouts: async () => [],+ handleWallClockTimeouts: async () => [],+ renewLock: async () => true,+ claim: async () => {+ claims += 1;+ if (!handedOut) { handedOut = true; return job; }+ if (done || claims > 2000) worker.stop();+ return null;+ },+ failJob: async (_id: number, _tok: string, errorText: string, newStatus: string) => {+ failJobCalls += 1;+ if (failJobCalls === 1) throw connClosed(); // same outage that failed the job+ done = true;+ return { ...job, status: newStatus, error_text: errorText };+ },+ });++ const { lines } = await withCapturedConsoleError(() => worker.start());++ // Recording was retried after an in-process reconnect (not abandoned).+ expect(failJobCalls).toBe(2);+ expect(counter.reconnects).toBe(1);+ // The ORIGINAL job error must be logged even though recording it threw —+ // pre-fix only "executeJob unhandled error ... CONNECTION_CLOSED" survived+ // and the real defect was masked.+ expect(+ lines.some(l => l.includes('boom: the real job defect') && l.includes('CONNECTION_CLOSED')),+ ).toBe(true);+ });+});++describe('retry-matcher unification (#1720 gap 4)', () => {+ test('startup connect matcher recognizes a pooler CONNECTION_CLOSED', async () => {+ const { isRetryableDbConnectError } = await import('../src/core/db.ts');+ expect(isRetryableDbConnectError(new Error('write CONNECTION_CLOSED db.pooler.example:5432'))).toBe(true);+ expect(isRetryableDbConnectError(new Error('server closed the connection unexpectedly'))).toBe(true);+ });++ test('code-only CONNECTION_CLOSED (message rewritten by a wrapper) is retryable', () => {+ expect(isRetryableConnError(Object.assign(new Error('socket hang up'), { code: 'CONNECTION_CLOSED' }))).toBe(true);+ });++ test('drift guard: startup and runtime matchers agree on the full shape corpus', async () => {+ const { isRetryableDbConnectError } = await import('../src/core/db.ts');+ const shapes: unknown[] = [+ // transient / retryable+ connClosed(),+ new Error('write CONNECTION_CLOSED db.pooler.example:5432'),+ new Error('connection closed by server'),+ Object.assign(new Error(''), { code: 'CONNECTION_ENDED' }),+ new Error('password authentication failed for user "app"'),+ new Error('connection refused'),+ new Error('the database system is starting up'),+ new Error('Connection terminated unexpectedly'),+ new Error('read ECONNRESET'),+ new Error('No database connection: connect() has not been called'),+ new Error('EMAXCONNSESSION'),+ new Error('sorry, too many clients already'),+ // permanent / non-retryable+ new Error('extension "vector" does not exist'),+ new Error('relation "pages" does not exist'),+ new Error('syntax error at end of input'),+ new Error('duplicate key value violates unique constraint "pages_pkey"'),+ ];+ for (const shape of shapes) {+ expect(isRetryableDbConnectError(shape)).toBe(isRetryableConnError(shape));+ }+ });+});