Skip to content

Where agent teams gather. Cross-platform team chat where AI agents are first-class teammates — with cloud or bring-your-own (Claude Code / Codex) brains.

TypeScript

fix(scheduler): wake-retry recovery must obey the same backpressure as live fan-out (#287)

OKNOTOKa4c7664e0475
diff --git a/server/src/__tests__/scheduler-low-pri-budget.test.ts b/server/src/__tests__/scheduler-low-pri-budget.test.ts
index 6b9d9a4..88b5258 100644
--- a/server/src/__tests__/scheduler-low-pri-budget.test.ts
+++ b/server/src/__tests__/scheduler-low-pri-budget.test.ts
@@ -70,12 +70,37 @@ test('many rejections in a window are absorbed, then the next window is fresh',
})
test('wake retry delay backs off and caps at 60s', () => {
- assert.equal(_wakeRetryDelayMs(0), 5_000)
- assert.equal(_wakeRetryDelayMs(1), 10_000)
- assert.equal(_wakeRetryDelayMs(2), 20_000)
- assert.equal(_wakeRetryDelayMs(3), 40_000)
- assert.equal(_wakeRetryDelayMs(4), 60_000)
- assert.equal(_wakeRetryDelayMs(50), 60_000)
+ // random() = 0.5 is the midpoint of the 0.5x–1.5x jitter band, i.e. the bare
+ // base curve.
+ const mid = (attempt: number): number => _wakeRetryDelayMs(attempt, () => 0.5)
+ assert.equal(mid(0), 5_000)
+ assert.equal(mid(1), 10_000)
+ assert.equal(mid(2), 20_000)
+ assert.equal(mid(3), 40_000)
+ assert.equal(mid(4), 60_000)
+ assert.equal(mid(50), 60_000)
+})
+
+test('wake retry delay is jittered, so a batch that failed together does not stay phase-locked', () => {
+ // Past attempt 4 the base delay is a flat 60s. Without jitter every job from
+ // the same outage gets exactly 60_000 ms on every one of its 60 attempts and
+ // the whole herd comes due in the same second, once a minute, for an hour.
+ assert.equal(_wakeRetryDelayMs(9, () => 0), 30_000)
+ assert.equal(_wakeRetryDelayMs(9, () => 0.999999), 89_999)
+
+ const spread = new Set<number>()
+ for (let i = 0; i < 200; i++) {
+ const delay = _wakeRetryDelayMs(9)
+ assert.ok(delay >= 30_000 && delay < 90_000, `delay ${delay} outside the 0.5x–1.5x band`)
+ spread.add(delay)
+ }
+ assert.ok(spread.size > 100, `expected the herd to spread out, saw ${spread.size} distinct delays in 200 draws`)
+
+ // Early attempts are jittered too, and never negative or zero.
+ for (let attempt = 0; attempt <= 4; attempt++) {
+ const low = _wakeRetryDelayMs(attempt, () => 0)
+ assert.ok(low > 0, `attempt ${attempt} floor must stay positive, got ${low}`)
+ }
})
test('ensurePod retry is only for manual wakes — message.new is durable via DB inbox', () => {
diff --git a/server/src/__tests__/scheduler-wake-retry.test.ts b/server/src/__tests__/scheduler-wake-retry.test.ts
new file mode 100644
index 0000000..6b193c2
--- /dev/null
+++ b/server/src/__tests__/scheduler-wake-retry.test.ts
@@ -0,0 +1,176 @@
+/**
+ * The wake-retry drain has to be backpressured by the same semaphore as live
+ * fan-out.
+ *
+ * `_drainWakeRetries` is the recovery path for wakes that failed on host
+ * resolution. Any database error in `resolveAgentHost` maps to `lookup_failed`,
+ * and `_shouldRetryWakeFailure` treats that as retryable for every wake reason,
+ * so a short database blip during a busy hour enqueues a retry for every
+ * recipient of every message sent during it. The burst that comes back is
+ * therefore the *most* correlated traffic the scheduler ever sees, and it
+ * arrives while the database is still recovering.
+ *
+ * It used to call `wakeOne(...)` without awaiting, up to `WAKE_RETRY_BATCH_SIZE`
+ * (25) per 5s tick, bypassing `wakeFanoutSem` entirely — each wake costing a
+ * host-resolution query plus, for a managed agent, persona + inbox + context
+ * loads and a model call. That is the triage fail-open amplification loop the
+ * semaphore was built for after the 2026-05-27 connection-exhaustion outage.
+ *
+ * Run: node --import tsx --test server/src/__tests__/scheduler-wake-retry.test.ts
+ */
+import { test, after } from 'node:test'
+import assert from 'node:assert/strict'
+import { pool } from '../db/pool.js'
+import { env } from '../env.js'
+import {
+ _drainWakeRetries,
+ _wakeFanoutSem,
+ type WakeRetryQueue,
+} from '../agents/scheduler.js'
+
+after(async () => {
+ // scheduler.ts transitively imports redis.ts which opens connections.
+ try { await pool.end() } catch { /* ignore */ }
+ try {
+ const { redis, sub } = await import('../redis.js')
+ redis.disconnect()
+ sub.disconnect()
+ } catch { /* ignore */ }
+})
+
+const tick = (): Promise<void> => new Promise((resolve) => setImmediate(resolve))
+
+interface Recorder {
+ queue: WakeRetryQueue
+ started: string[]
+ finished: string[]
+ rescheduled: Array<{ id: string; attempt: number; failure: string }>
+ peakConcurrency: number
+ release: () => void
+}
+
+/** A queue of `count` due jobs whose wakes block until `release()` is called,
+ * so the test can observe how many the drain lets run at once. */
+function recorder(count: number, opts: { fail?: Set<string>; hold?: boolean } = {}): Recorder {
+ const ids = Array.from({ length: count }, (_, i) => `agent-${i}:message.new:c-${i}`)
+ const started: string[] = []
+ const finished: string[] = []
+ const rescheduled: Array<{ id: string; attempt: number; failure: string }> = []
+ const gate: Array<() => void> = []
+ let inFlight = 0
+ // Latched: the batch is larger than the semaphore, so jobs keep arriving
+ // after release() — they must not re-block on a gate nobody will open again.
+ let released = false
+ const rec: Recorder = {
+ started, finished, rescheduled,
+ peakConcurrency: 0,
+ release: () => {
+ released = true
+ for (const open of gate.splice(0)) open()
+ },
+ queue: {
+ due: async () => ids,
+ claim: async (id) => ({
+ id,
+ agentId: id.split(':')[0],
+ reason: 'message.new',
+ conversationId: id.split(':')[2],
+ steerPayload: null,
+ options: {},
+ attempt: 7,
+ lastFailure: 'host lookup failed',
+ }),
+ run: async (job) => {
+ started.push(job.id)
+ inFlight += 1
+ rec.peakConcurrency = Math.max(rec.peakConcurrency, inFlight)
+ try {
+ if (opts.hold && !released) await new Promise<void>((resolve) => gate.push(resolve))
+ else await tick()
+ if (opts.fail?.has(job.id)) throw new Error(`pod apply failed for ${job.agentId}`)
+ finished.push(job.id)
+ } finally {
+ inFlight -= 1
+ }
+ },
+ reschedule: async (job, failure) => {
+ rescheduled.push({ id: job.id, attempt: job.attempt + 1, failure })
+ },
+ },
+ }
+ return rec
+}
+
+test('a full retry batch never exceeds the live fan-out concurrency', async () => {
+ const rec = recorder(25)
+
+ await _drainWakeRetries(rec.queue)
+
+ assert.equal(rec.started.length, 25, 'every due job must still run')
+ assert.equal(rec.finished.length, 25)
+ assert.ok(
+ rec.peakConcurrency <= env.WAKE_FANOUT_CONCURRENCY,
+ `peak concurrency ${rec.peakConcurrency} exceeded the fan-out bound ${env.WAKE_FANOUT_CONCURRENCY}`,
+ )
+ assert.ok(rec.peakConcurrency > 1, 'the drain should still overlap work, not serialize it')
+})
+
+test('the drain awaits its batch instead of firing and forgetting', async () => {
+ const rec = recorder(8, { hold: true })
+
+ let settled = false
+ const drained = _drainWakeRetries(rec.queue).then(() => { settled = true })
+
+ await tick()
+ assert.equal(settled, false, 'the drain resolved while wakes were still in flight')
+ assert.ok(rec.started.length > 0)
+
+ rec.release()
+ await drained
+ assert.equal(settled, true)
+ assert.equal(rec.finished.length, 8)
+})
+
+test('retry wakes queue behind the same permits as live fan-out', async () => {
+ // Hold every permit, the way a reply-storm fan-out would. Nothing in the
+ // retry batch may start until they come back — a private bound of its own
+ // would let 25 wakes run straight through a saturated pool.
+ const held: Array<Promise<void>> = []
+ const openGates: Array<() => void> = []
+ for (let i = 0; i < env.WAKE_FANOUT_CONCURRENCY; i++) {
+ held.push(_wakeFanoutSem.run(() => new Promise<void>((resolve) => openGates.push(resolve))))
+ }
+ await tick()
+
+ const rec = recorder(5)
+ const drained = _drainWakeRetries(rec.queue)
+ await tick()
+ await tick()
+ assert.equal(rec.started.length, 0, 'a retry wake started while live fan-out held every permit')
+
+ for (const open of openGates) open()
+ await Promise.all(held)
+ await drained
+ assert.equal(rec.finished.length, 5)
+})
+
+test('a wake that throws is rescheduled at the next attempt and does not sink the batch', async () => {
+ const rec = recorder(4, { fail: new Set(['agent-1:message.new:c-1']) })
+
+ await _drainWakeRetries(rec.queue)
+
+ assert.equal(rec.finished.length, 3, 'the three healthy wakes must still complete')
+ assert.deepEqual(rec.rescheduled.map((r) => r.id), ['agent-1:message.new:c-1'])
+ assert.equal(rec.rescheduled[0].attempt, 8, 'a retry has to advance the attempt counter')
+ assert.match(rec.rescheduled[0].failure, /pod apply failed/)
+})
+
+test('a job another replica already claimed is skipped', async () => {
+ const rec = recorder(3)
+ const queue: WakeRetryQueue = { ...rec.queue, claim: async () => null }
+
+ await _drainWakeRetries(queue)
+
+ assert.deepEqual(rec.started, [])
+ assert.deepEqual(rec.rescheduled, [])
+})
diff --git a/server/src/agents/scheduler.ts b/server/src/agents/scheduler.ts
index e57e90f..9fec6cd 100644
--- a/server/src/agents/scheduler.ts
+++ b/server/src/agents/scheduler.ts
@@ -46,6 +46,11 @@ import { Semaphore } from '../concurrency.js'
* pg pool and tripping the triage fail-open amplification loop. */
const wakeFanoutSem = new Semaphore(env.WAKE_FANOUT_CONCURRENCY)
+/** Test handle on the semaphore above. Exported so a test can prove the retry
+ * drain queues behind the SAME permits as live fan-out, not just behind some
+ * bound of its own. */
+export const _wakeFanoutSem = wakeFanoutSem
+
/** Optional payload attached to a wake that the busy-agent path should
* also publish as a `steer` event so the running turn can react
* mid-flight (instead of waiting until the next wake). Built by the
@@ -86,11 +91,29 @@ const WAKE_RETRY_JOB_KEY = 'cumora:wake-retry:jobs'
const WAKE_RETRY_MAX_ATTEMPTS = 60
const WAKE_RETRY_BATCH_SIZE = 25
-export function _wakeRetryDelayMs(attempt: number): number {
+/** 5s, 10s, 20s, 40s, then 60s for every attempt after that. */
+function wakeRetryBaseDelayMs(attempt: number): number {
const n = Math.max(0, Math.min(4, attempt))
return Math.min(60_000, 5_000 * 2 ** n)
}
+/**
+ * Backoff with decorrelating jitter (0.5x–1.5x of the base delay).
+ *
+ * The base curve flattens at 60s from attempt 4 on, so without jitter every job
+ * that failed in the same blip is handed the SAME delay forever: they come due
+ * in the same second, every minute, for all `WAKE_RETRY_MAX_ATTEMPTS`
+ * attempts — an hour-long synchronized herd hitting a database that is
+ * probably still recovering from whatever knocked them out. Jitter is what
+ * turns that into a spread-out trickle.
+ *
+ * `random` is injectable so the spread is testable rather than asserted by
+ * eyeball.
+ */
+export function _wakeRetryDelayMs(attempt: number, random: () => number = Math.random): number {
+ return Math.floor(wakeRetryBaseDelayMs(attempt) * (0.5 + random()))
+}
+
export function _shouldRetryEnsurePodFailure(reason: WakeReason, ensureReason: string): boolean {
// message.new wakes are DURABLE because the message itself is already
// committed to the messages table. Whenever the agent's pod next
@@ -160,47 +183,93 @@ async function scheduleWakeRetry(
console.warn(`[scheduler] ${agentId} ${reason} wake retry scheduled in ${Math.round((dueAt - Date.now()) / 1000)}s after ${failureClass}: ${failureReason}`)
}
-async function pollWakeRetriesOnce(): Promise<void> {
- const ids = await redis.zrangebyscore(WAKE_RETRY_DUE_KEY, 0, Date.now(), 'LIMIT', 0, WAKE_RETRY_BATCH_SIZE)
- for (const id of ids) {
- const claimed = await redis.zrem(WAKE_RETRY_DUE_KEY, id)
- if (claimed !== 1) continue
+/** The Redis side of the retry queue, behind an interface so the drain loop can
+ * be driven by a test without a live Redis or a live agent fleet. */
+export interface WakeRetryQueue {
+ /** Retry ids that are due, oldest first, capped at the batch size. */
+ due(now: number): Promise<string[]>
+ /** Atomically take ownership of one id. `null` means another replica won it,
+ * or the job body is gone or unreadable. */
+ claim(id: string): Promise<WakeRetryJob | null>
+ run(job: WakeRetryJob): Promise<void>
+ reschedule(job: WakeRetryJob, failure: string): Promise<void>
+}
+
+const redisWakeRetryQueue: WakeRetryQueue = {
+ due: (now) => redis.zrangebyscore(WAKE_RETRY_DUE_KEY, 0, now, 'LIMIT', 0, WAKE_RETRY_BATCH_SIZE),
+ claim: async (id) => {
+ // zrem is the claim: exactly one replica gets 1 back for a given id.
+ if (await redis.zrem(WAKE_RETRY_DUE_KEY, id) !== 1) return null
const raw = await redis.hget(WAKE_RETRY_JOB_KEY, id)
- if (!raw) continue
+ if (!raw) return null
await redis.hdel(WAKE_RETRY_JOB_KEY, id).catch(() => { /* ignore */ })
- let job: WakeRetryJob
try {
- job = JSON.parse(raw) as WakeRetryJob
+ return JSON.parse(raw) as WakeRetryJob
} catch {
- continue
+ return null
}
- wakeOne(
- job.agentId,
- job.reason,
- job.conversationId,
- job.steerPayload,
- job.options,
- job.attempt,
- ).catch((err) => {
- console.error(`[scheduler] wake retry ${job.id} failed:`, err instanceof Error ? err.message : err)
- scheduleWakeRetry(
- job.agentId,
- job.reason,
- job.conversationId,
- job.steerPayload,
- job.options,
- job.attempt + 1,
- err instanceof Error ? err.message : String(err),
- ).catch(() => { /* ignore */ })
- })
- }
+ },
+ // wakeOne's boolean says whether it woke anything; the retry loop has never
+ // branched on it (its own failure paths already re-enqueue through
+ // scheduleWakeRetry), so drop it rather than invent a new policy here.
+ run: async (job) => {
+ await wakeOne(job.agentId, job.reason, job.conversationId, job.steerPayload, job.options, job.attempt)
+ },
+ reschedule: (job, failure) => scheduleWakeRetry(
+ job.agentId, job.reason, job.conversationId, job.steerPayload, job.options, job.attempt + 1, failure,
+ ),
+}
+
+/**
+ * Drain one batch of due wake retries — through `wakeFanoutSem`, the same
+ * semaphore the live fan-out uses.
+ *
+ * This loop used to call `wakeOne(...)` without awaiting it, so a tick fired up
+ * to `WAKE_RETRY_BATCH_SIZE` (25) wakes fully in parallel, every 5 seconds, and
+ * none of them passed through the semaphore. Each wake costs a host-resolution
+ * query, and for a managed agent a triage pass on top: persona + inbox +
+ * context loads and a model call. Twenty-five of those at once is ~100
+ * concurrent queries against a 20-slot pool.
+ *
+ * That matters most in exactly the situation this queue exists for. Any DB
+ * error in `resolveAgentHost` maps to `lookup_failed`, which
+ * `_shouldRetryWakeFailure` treats as retryable for every wake reason, so a
+ * 30-second database blip enqueues a retry for every recipient of every message
+ * sent during it. The recovery burst then oversubscribes the pool that is still
+ * recovering, more wakes time out, and each timeout re-enqueues itself — the
+ * triage fail-open amplification loop the semaphore was introduced for after
+ * the 2026-05-27 connection-exhaustion outage. Recovery traffic has to obey the
+ * same backpressure as live traffic; it is the traffic most likely to arrive
+ * all at once.
+ */
+export async function _drainWakeRetries(queue: WakeRetryQueue = redisWakeRetryQueue): Promise<void> {
+ const ids = await queue.due(Date.now())
+ await Promise.all(ids.map((id) => wakeFanoutSem.run(async () => {
+ const job = await queue.claim(id)
+ if (!job) return
+ try {
+ await queue.run(job)
+ } catch (err) {
+ const failure = err instanceof Error ? err.message : String(err)
+ console.error(`[scheduler] wake retry ${job.id} failed:`, failure)
+ await queue.reschedule(job, failure).catch(() => { /* ignore */ })
+ }
+ })))
}
function startWakeRetryWorker(intervalMs: number = 5_000): NodeJS.Timeout {
+ // One batch at a time. The drain now awaits its wakes, so a slow recovery
+ // would otherwise stack a fresh 25-id batch on the semaphore queue every 5s
+ // — bounded work, but an ever-growing backlog of claims that mostly lose
+ // their zrem race and do nothing.
+ let inFlight: Promise<void> | null = null
const tick = (): void => {
- pollWakeRetriesOnce().catch((err) =>
- console.error('[scheduler] wake retry worker failed:', err instanceof Error ? err.message : err),
- )
+ if (inFlight) return
+ inFlight = _drainWakeRetries()
+ .catch((err) =>
+ console.error('[scheduler] wake retry worker failed:', err instanceof Error ? err.message : err),
+ )
+ .finally(() => { inFlight = null })
}
setImmediate(tick)
const t = setInterval(tick, intervalMs)