Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(minions): the stall, timeout and wall-clock sweeps skip the drain-lease holder record (#7261)

garrytan907ca718cdb0
diff --git a/src/core/minions/protected-names.ts b/src/core/minions/protected-names.ts
index 174e8057e8..d0022cab3f 100644
--- a/src/core/minions/protected-names.ts
+++ b/src/core/minions/protected-names.ts
@@ -12,6 +12,13 @@
* pay them at module load.
*/
+/**
+ * The queue of drain-lease holder records (persistence/sync-lease.ts): an active row per held sync lease that no worker
+ * claims and that the lease renews and deletes itself. It is not a job, so the stall, timeout and wall-clock sweeps
+ * skip it (#7261): dead-lettering it counted an attempt it never started and broke chk_attempts_order.
+ */
+export const LEASE_BEACON_QUEUE = 'gbrain-drain-lease';
+
export const PROTECTED_JOB_NAMES: ReadonlySet<string> = new Set([
'shell',
// v0.15: subagent + aggregator are protected because they call the
diff --git a/src/core/minions/queue.ts b/src/core/minions/queue.ts
index 277981dbe7..50f9497aad 100644
--- a/src/core/minions/queue.ts
+++ b/src/core/minions/queue.ts
@@ -20,7 +20,7 @@ export { WATCHDOG_SUSPECT_MARK } from './watchdog-attribution.ts';
import { coalesceOnIdempotencyKey, decideCoalesce, insertOrCoalesce } from './idempotency-coalesce.ts';
import { adoptSpendAuthorization, legacyDefaultClaimSetSql, legacyDefaultClaimParams, type SpendAuthorization } from './spend-authorization.ts';
import { validateAttachment } from './attachments.ts';
-import { isProtectedJobName } from './protected-names.ts';
+import { isProtectedJobName, LEASE_BEACON_QUEUE } from './protected-names.ts';
import { jsonbSafeJson } from '../text-safe.ts';
import { assertEmbedBackfillQueueAdmission } from './embed-backfill-admission.ts';
import { lockDelegatedSubmission, checkDelegatedCapacity, prepareDelegatedReplay, admitDelegatedRetry } from './delegated-admission.ts';
@@ -1526,7 +1526,7 @@ export class MinionQueue {
// SKIP LOCKED subselect — see killJobs() for the shared tail.
const candidates = await tx.executeRaw<{ id: number; parent_job_id: number | null }>(
`SELECT id, parent_job_id FROM minion_jobs
- WHERE status = 'active'
+ WHERE status = 'active' AND queue <> '${LEASE_BEACON_QUEUE}'
AND timeout_at IS NOT NULL
AND timeout_at < now()
AND lock_until > now()`
@@ -1658,7 +1658,7 @@ export class MinionQueue {
// handleTimeouts; shared tail in killJobs().
const candidates = await tx.executeRaw<{ id: number; parent_job_id: number | null }>(
`SELECT id, parent_job_id FROM minion_jobs
- WHERE status = 'active'
+ WHERE status = 'active' AND queue <> '${LEASE_BEACON_QUEUE}'
AND started_at IS NOT NULL
AND EXTRACT(EPOCH FROM (now() - started_at)) * 1000 > ${WALL_CLOCK_THRESHOLD_MS_SQL}`,
[lockDurationMs]
@@ -2147,7 +2147,7 @@ export class MinionQueue {
const candidates = await tx.executeRaw<{ id: number; parent_job_id: number | null; stalled_counter: number; max_stalled: number }>(
`SELECT id, parent_job_id, stalled_counter, max_stalled
FROM minion_jobs
- WHERE status = 'active'
+ WHERE status = 'active' AND queue <> '${LEASE_BEACON_QUEUE}'
AND lock_until < now() - ($1::double precision * interval '1 millisecond')`,
[graceMs]
);
diff --git a/src/core/persistence/sync-lease.ts b/src/core/persistence/sync-lease.ts
index 97e85401e3..3f4d4191fa 100644
--- a/src/core/persistence/sync-lease.ts
+++ b/src/core/persistence/sync-lease.ts
@@ -40,6 +40,7 @@ import { currentRunDeadline, lastForwardProgressAt, noteForwardProgress } from '
import { faultPoint } from './fault-points.ts';
import { MANAGED_SYNC_PASS_OP } from './sync-pass-row.ts';
import { VERSION } from '../../version.ts';
+import { LEASE_BEACON_QUEUE } from '../minions/protected-names.ts';
export const DRAIN_LEASE_TTL_MINUTES = 2;
export const DRAIN_LEASE_REFRESH_MS = 20_000;
@@ -49,7 +50,7 @@ export const LEASE_RETRY_AFTER_MS = 60_000;
/** A follower stops this long before its watchdog would (or half its window, when the window is shorter). */
const FOLLOW_MARGIN_MS = 30_000;
/** The minion queue of the holder records (also the beacon older binaries' `liveSyncJob` sees); no worker serves it. */
-export const LEASE_BEACON_QUEUE = 'gbrain-drain-lease';
+export { LEASE_BEACON_QUEUE };
/** A holder with no commit and no cursor save for this long is wedged (the in-pass governor's no-progress window). */
export const HOLDER_STALL_MS = 5 * 60_000;
/** How often a following run prints the holder's progress: on a terminal, and otherwise. */
diff --git a/test/minions-lease-beacon-sweeps-7261.test.ts b/test/minions-lease-beacon-sweeps-7261.test.ts
new file mode 100644
index 0000000000..a7bf103df4
--- /dev/null
+++ b/test/minions-lease-beacon-sweeps-7261.test.ts
@@ -0,0 +1,72 @@
+/**
+ * #7261: the drain-lease holder record (queue gbrain-drain-lease, written by a sync that holds the source's drain
+ * lease) is an active row no worker claims, with attempts_started 0. The stall, timeout and wall-clock sweeps
+ * matched it once its sync ran past two lock durations (or once its holder died), counted an attempt it never
+ * started, and broke chk_attempts_order. The exception rolled back the whole sweep, so every other stalled job
+ * stayed stalled, and the dream inline drain's housekeeping failed the synthesize phase after its children finished.
+ * The sweeps now skip the beacon queue; the lease renews and deletes its own row.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { MinionQueue } from '../src/core/minions/queue.ts';
+import { LEASE_BEACON_QUEUE, withDrainLease } from '../src/core/persistence/sync-lease.ts';
+import { runSubagentsInline } from '../src/core/cycle/inline-drain.ts';
+import type { SyncResult } from '../src/commands/sync.ts';
+
+describe('#7261 the job sweeps never touch the drain-lease holder record', () => {
+ let engine: PGLiteEngine;
+ let queue: MinionQueue;
+
+ beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({ database_url: '' });
+ await engine.initSchema();
+ queue = new MinionQueue(engine);
+ });
+ afterAll(async () => { await engine.disconnect(); });
+
+ const beacon = async () => (await engine.executeRaw<{ id: number; status: string; attempts_made: number }>(
+ 'SELECT id, status, attempts_made FROM minion_jobs WHERE queue = $1', [LEASE_BEACON_QUEUE]))[0];
+
+ /** Runs `body` while a real sync drain lease on source-a holds its holder record. */
+ const underLease = (body: () => Promise<void>) => withDrainLease(engine, 'source-a', { holder: { kind: 'cli' } }, async () => {
+ await body();
+ return { status: 'up_to_date' } as unknown as SyncResult;
+ });
+
+ test('a long-held lease: the wall-clock sweep leaves the record, and a stuck job in the same sweep still dies', async () => {
+ const stuck = await queue.add('noop', {}, { queue: 'default' });
+ await underLease(async () => {
+ await engine.executeRaw(`UPDATE minion_jobs SET started_at = now() - interval '1 hour' WHERE queue = $1`, [LEASE_BEACON_QUEUE]);
+ expect((await queue.claim('tok-7261', 600_000, 'default', ['noop']))?.id).toBe(stuck.id);
+ await engine.executeRaw(`UPDATE minion_jobs SET started_at = now() - interval '1 hour' WHERE id = $1`, [stuck.id]);
+ const killed = await queue.handleWallClockTimeouts(1000);
+ expect(killed.map(j => j.id)).toEqual([stuck.id]);
+ expect(await beacon()).toMatchObject({ status: 'active', attempts_made: 0 });
+ });
+ expect(await beacon()).toBeUndefined();
+ });
+
+ test("a dead holder's expired record: the stall sweep leaves it and still requeues a stalled job", async () => {
+ const stalled = await queue.add('noop', {}, { queue: 'default', max_stalled: 3 });
+ await underLease(async () => {
+ await engine.executeRaw(`UPDATE minion_jobs SET lock_until = now() - interval '1 hour' WHERE queue = $1`, [LEASE_BEACON_QUEUE]);
+ expect((await queue.claim('tok-7261b', 600_000, 'default', ['noop']))?.id).toBe(stalled.id);
+ await engine.executeRaw(`UPDATE minion_jobs SET lock_until = now() - interval '1 hour' WHERE id = $1`, [stalled.id]);
+ const { requeued, dead } = await queue.handleStalled(0);
+ expect(requeued.map(j => j.id)).toEqual([stalled.id]);
+ expect(dead).toEqual([]);
+ expect(await queue.handleTimeouts()).toEqual([]);
+ expect(await beacon()).toMatchObject({ status: 'active', attempts_made: 0 });
+ });
+ });
+
+ test('the dream inline drain finishes its children while a long sync holds the lease', async () => {
+ const child = await queue.add('subagent', { prompt: 'p' }, { queue: 'dream-inline-7261' }, { allowProtectedSubmit: true });
+ await underLease(async () => {
+ await engine.executeRaw(`UPDATE minion_jobs SET started_at = now() - interval '1 hour' WHERE queue = $1`, [LEASE_BEACON_QUEUE]);
+ await runSubagentsInline(engine, queue, 'dream-inline-7261', undefined, async () => ({ ok: true }), 1000);
+ });
+ expect((await queue.getJob(child.id))!.status).toBe('completed');
+ });
+});