Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(jobs): smoke removes the jobs it created on every exit path (#5977)
time-attackcfdd80a25ef8
diff --git a/TODOS.md b/TODOS.mdindex f2faee36b5..0feb10772d 100644--- a/TODOS.md+++ b/TODOS.md@@ -1,5 +1,9 @@# TODOS+## Fix wave 10 lane H follow-ups (filed 2026-10-06, GBRA-51)++- [ ] **P2 — `gbrain jobs smoke --sigkill-rescue` and `--wedge-rescue` always throw.** **What:** both cases forge a claimed job with a raw `UPDATE minion_jobs SET status='active', lock_token=…`, which the `enforce_minion_queue_protocol` trigger refuses ("Minion queue protocol 1 required: old workers cannot claim upgraded queue jobs"), so neither regression check (#219 stall rescue, wall-clock eviction) runs at all; the command exits through the thrown error. `test/jobs-smoke-cleanup.test.ts` pins the refusal and that no smoke job is left behind. **Fix:** put the forged job into `active` through the queue's own claim path (claim it with a short-lived lock token, then age `lock_until`/`started_at`), or a test-only protocol-conformant transition, so both cases reach their assertions again; then flip the cleanup test's sigkill case to assert the rescue verdict. **Effort:** S. **Priority:** P2.+## Fix wave 9 follow-ups (filed 2026-10-05, follow-up from v0.60.74.0)- [ ] **P2 — Receipted publication for managed conversation facts.** **What:** `extract-conversation-facts` replaces a page's derived fact batch through `replaceDerivedFactsForPage` (`src/core/persistence/derived-facts.ts`), a coordinated transaction with no persistence request. On a managed brain a multi-message email thread is therefore skipped without writing and retried every run (`src/core/facts/conversation-skip.ts`), as are the single-email and prose outcomes; `test/helpers/managed-connector-job-contract.ts` case `extract_conversation_facts_thread` pins it. **Fix:** admit a persistence request for the derived batch (delete-by-prefix plus insert, page revision as the CAS) in the same transaction, so the write carries a receipt; then drop the managed gate and record the single-email/prose outcomes durably there too. **Effort:** M. **Priority:** P2.diff --git a/src/commands/jobs/smoke.ts b/src/commands/jobs/smoke.tsindex e759c5e5e2..4b32b7a5b9 100644--- a/src/commands/jobs/smoke.ts+++ b/src/commands/jobs/smoke.ts@@ -1,15 +1,50 @@/** `gbrain jobs smoke` (dispatched by runJobs in src/commands/jobs.ts). */import { hasFlag, type JobsCommandContext } from './shared.ts';import { MinionWorker } from '../../core/minions/worker.ts';+import type { MinionQueue } from '../../core/minions/queue.ts';import type { MinionJob } from '../../core/minions/types.ts';import { reportInlineWorkerConfiguration } from '../jobs-readiness.ts';-export async function runJobsSmoke({ args, engine, queue }: JobsCommandContext): Promise<void> {+const TERMINAL_STATUSES = ['completed', 'failed', 'dead', 'cancelled'];++/**+ * Cancel a smoke job that is still live, then delete it. Production workers+ * never serve the `smoke` queue, so a job left behind waits forever and trips+ * oldest-waiting-job health checks. Best-effort: never changes the verdict.+ */+export async function discardSmokeJob(queue: MinionQueue, id: number): Promise<void> {+ try {+ const job = await queue.getJob(id);+ if (!job) return;+ if (!TERMINAL_STATUSES.includes(job.status)) await queue.cancelJob(id);+ await queue.removeJob(id);+ } catch (e) {+ console.error(` (could not remove smoke job #${id}: ${e instanceof Error ? e.message : String(e)})`);+ }+}++/**+ * `opts.timeoutMs` is a test seam (the CLI never passes it). Every job the run+ * adds is tracked and discarded in one `finally`, on pass, failure, timeout+ * and throw alike; only then does the process exit.+ */+export async function runJobsSmoke(ctx: JobsCommandContext, opts: { timeoutMs?: number } = {}): Promise<void> {+ const owned: number[] = [];+ let code: number;+ try {+ code = await runSmokeChecks(ctx, owned, opts.timeoutMs ?? 15000);+ } finally {+ for (const id of owned) await discardSmokeJob(ctx.queue, id);+ }+ process.exit(code);+}++async function runSmokeChecks({ args, engine, queue }: JobsCommandContext, owned: number[], timeoutMs: number): Promise<0 | 1> {const startTime = Date.now();try { await queue.ensureSchema(); }catch (e) {console.error(`SMOKE FAIL — schema init: ${e instanceof Error ? e.message : String(e)}`);- process.exit(1);+ return 1;}const sigkillRescue = hasFlag(args, '--sigkill-rescue');@@ -23,14 +58,14 @@ export async function runJobsSmoke({ args, engine, queue }: JobsCommandContext):worker.register('noop', async () => ({ ok: true, at: new Date().toISOString() }));const job = await queue.add('noop', {}, { queue: 'smoke', max_attempts: 1 });+ owned.push(job.id);const workerPromise = worker.start();- const timeoutMs = 15000;let final: MinionJob | null = null;for (let elapsed = 0; elapsed < timeoutMs; elapsed += 100) {await new Promise(r => setTimeout(r, 100));final = await queue.getJob(job.id);- if (final && ['completed', 'failed', 'dead', 'cancelled'].includes(final.status)) break;+ if (final && TERMINAL_STATUSES.includes(final.status)) break;}worker.stop();await workerPromise;@@ -40,7 +75,7 @@ export async function runJobsSmoke({ args, engine, queue }: JobsCommandContext):console.error(`SMOKE FAIL — job #${job.id} status: ${final?.status ?? 'timeout'} (${elapsedSec}s elapsed)`);if (final?.error_text) console.error(` Error: ${final.error_text}`);if (worker.configurationError) reportInlineWorkerConfiguration(worker.configurationError);- process.exit(1);+ return 1;}// --sigkill-rescue: regression case for #219. Simulates a SIGKILL@@ -50,6 +85,7 @@ export async function runJobsSmoke({ args, engine, queue }: JobsCommandContext):// Full subprocess-level SIGKILL lives in test/e2e/minions.test.ts.if (sigkillRescue) {const rescueJob = await queue.add('noop', {}, { queue: 'smoke' });+ owned.push(rescueJob.id);// Transition to active with a past lock_until, mimicking a worker// that claimed and then got SIGKILL'd mid-run.@@ -73,16 +109,15 @@ export async function runJobsSmoke({ args, engine, queue }: JobsCommandContext):`This is the #219 regression: schema default max_stalled should rescue, not dead-letter. ` +`handleStalled: ${JSON.stringify(result)}`);- process.exit(1);+ return 1;}if (afterStall?.status !== 'waiting') {console.error(`SMOKE FAIL (--sigkill-rescue) — unexpected status after stall: ${afterStall?.status}. ` +`Expected 'waiting' (rescued). handleStalled: ${JSON.stringify(result)}`);- process.exit(1);+ return 1;}- try { await queue.removeJob(rescueJob.id); } catch { /* non-fatal cleanup */ }}// --wedge-rescue: regression case for the v0.19.1 production incident.@@ -104,6 +139,7 @@ export async function runJobsSmoke({ args, engine, queue }: JobsCommandContext):queue: 'smoke',timeout_ms: 1000,});+ owned.push(wedgedJob.id);await engine.executeRaw(`UPDATE minion_jobsSET status='active',@@ -131,16 +167,15 @@ export async function runJobsSmoke({ args, engine, queue }: JobsCommandContext):`handleTimeouts: ${timeoutResult.length}, after: ${timedStatus?.status}; ` +`handleWallClockTimeouts: ${wallResult.length}, final: ${finalStatus?.status}.`);- process.exit(1);+ return 1;}if (finalStatus.error_text !== 'wall-clock timeout exceeded') {console.error(`SMOKE FAIL (--wedge-rescue) — dead, but error_text='${finalStatus.error_text}' ` +`(expected 'wall-clock timeout exceeded').`);- process.exit(1);+ return 1;}- try { await queue.removeJob(wedgedJob.id); } catch { /* non-fatal cleanup */ }}const cfg = (await import('../../core/config.ts')).loadConfig();@@ -154,6 +189,5 @@ export async function runJobsSmoke({ args, engine, queue }: JobsCommandContext):console.log('Note: the `gbrain jobs work` daemon requires Postgres. PGLite');console.log('supports inline execution only (`submit --follow`).');}- try { await queue.removeJob(job.id); } catch { /* non-fatal cleanup */ }- process.exit(0);+ return 0;}diff --git a/test/jobs-smoke-cleanup.test.ts b/test/jobs-smoke-cleanup.test.tsnew file mode 100644index 0000000000..de085263eb--- /dev/null+++ b/test/jobs-smoke-cleanup.test.ts@@ -0,0 +1,114 @@+/**+ * `gbrain jobs smoke` must not leave a job it created on the private `smoke`+ * queue. Production workers never serve that queue, so a leftover job waits+ * forever and trips oldest-waiting-job health checks. Each case also seeds+ * jobs the run did not create and pins that they survive: cleanup owns+ * exactly the run's job ids, never the queue.+ */+import { afterAll, beforeAll, beforeEach, describe, expect, spyOn, test } from 'bun:test';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { MinionQueue } from '../src/core/minions/queue.ts';+import { MinionWorker } from '../src/core/minions/worker.ts';+import { runJobsSmoke } from '../src/commands/jobs/smoke.ts';++let engine: PGLiteEngine;+let queue: MinionQueue;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ queue = new MinionQueue(engine);+});++afterAll(async () => {+ await engine.disconnect();+});++beforeEach(async () => {+ await engine.executeRaw('DELETE FROM minion_jobs');+});++async function jobRows(): Promise<Array<{ id: number; queue: string; status: string }>> {+ return engine.executeRaw<{ id: number; queue: string; status: string }>(+ 'SELECT id, queue, status FROM minion_jobs ORDER BY id',+ );+}++/**+ * Jobs the smoke run did not create: a delayed `smoke` job (the run's own+ * worker cannot claim it, so only cleanup could remove it) and a default-queue job.+ */+async function seedUnrelated(): Promise<Array<{ id: number; queue: string; status: string }>> {+ await queue.add('noop', {}, { queue: 'smoke', max_attempts: 1, delay: 3_600_000 });+ await queue.add('noop', {}, { queue: 'default', max_attempts: 1 });+ return jobRows();+}++/** Run the smoke with process.exit and console captured; resolves to the exit code. */+async function runSmoke(args: string[], opts: { timeoutMs?: number } = {}): Promise<{ code: number; stderr: string }> {+ const stderr: string[] = [];+ const exitSpy = spyOn(process, 'exit').mockImplementation(((code?: number) => {+ throw new Error(`EXIT:${code}`);+ }) as never);+ const errSpy = spyOn(console, 'error').mockImplementation((...a: unknown[]) => { stderr.push(a.join(' ')); });+ const logSpy = spyOn(console, 'log').mockImplementation(() => {});+ try {+ await runJobsSmoke({ args, engine, engineOrNull: engine, queue }, opts);+ throw new Error('expected process.exit');+ } catch (e) {+ const m = /^EXIT:(\d+)$/.exec((e as Error).message);+ if (!m) throw e;+ return { code: Number(m[1]), stderr: stderr.join('\n') };+ } finally {+ exitSpy.mockRestore();+ errSpy.mockRestore();+ logSpy.mockRestore();+ }+}++describe('gbrain jobs smoke cleanup', () => {+ test('timeout: a probe no worker claims is cancelled and removed before exit 1', async () => {+ const unrelated = await seedUnrelated();+ const startSpy = spyOn(MinionWorker.prototype, 'start').mockImplementation(async () => {});+ let result: { code: number; stderr: string };+ try {+ result = await runSmoke([], { timeoutMs: 300 });+ } finally {+ startSpy.mockRestore();+ }+ expect(result.code).toBe(1);+ expect(result.stderr).toContain('status: waiting');+ expect(await jobRows()).toEqual(unrelated);+ }, 30_000);++ test('pass: exit 0 and the run leaves no job of its own', async () => {+ const unrelated = await seedUnrelated();+ expect((await runSmoke([])).code).toBe(0);+ expect(await jobRows()).toEqual(unrelated);+ }, 30_000);++ test('throw mid-run: the error propagates and the live probe is still discarded', async () => {+ const unrelated = await seedUnrelated();+ const startSpy = spyOn(MinionWorker.prototype, 'start').mockImplementation(async () => {});+ const getJobSpy = spyOn(queue, 'getJob').mockImplementationOnce(async () => {+ throw new Error('getJob unavailable');+ });+ try {+ await expect(runSmoke([], { timeoutMs: 300 })).rejects.toThrow('getJob unavailable');+ } finally {+ getJobSpy.mockRestore();+ startSpy.mockRestore();+ }+ expect(await jobRows()).toEqual(unrelated);+ }, 30_000);++ test('--sigkill-rescue: the forged active transition is refused today, and neither probe nor rescue job is left', async () => {+ const unrelated = await seedUnrelated();+ // The rescue case forges status='active' with raw SQL, which the queue+ // protocol trigger refuses (tracked separately). Pin that refusal so the+ // cleanup assertion below is about a real throw, not a skipped case.+ await expect(runSmoke(['--sigkill-rescue'])).rejects.toThrow(/Minion queue protocol/);+ expect(await jobRows()).toEqual(unrelated);+ }, 30_000);+});