fix(orchestrator): reap a lifecycle that took a batch slot and never placed an agent (#303)
Fixes #303.
The defect
A dispatch lifecycle that reached a slot-occupying phase and never had an agent placed — spawn failed, fleet fault, or the process died between promote and spawn — was unreapable. Both halves of the only reaper keyed on heldSinceAtMs, which is stamped only by a successful placement:
#scheduleHeldAgentDeadlinereturned early, so no timer was ever armed.#sweepHeldAgentDeadlinescontinued, so it was never collected.
With dispatch.batchSize defaulting to 1, that one row held the only slot forever. Every other issue was claimed as queued and re-armed at 1 Hz with no iteration or wall-clock ceiling (#298 bounded only the relayfile 429 path). It was silent because the capacity wait logged once per key and never again, and it survived container restarts because the lifecycle lives in the Durable Object document.
One correction to the issue's proposed fix. It suggests using updatedAtMs as the clock for these rows. That cannot work: renewDispatchLifecycle writes lifecycle.updatedAtMs = nowMs every DISPATCH_LIFECYCLE_RENEW_MS (60 s), which is precisely the 12,836-byte PATCH storm measured on production — so a wedged row looks freshly touched forever and a deadline anchored on it would never fire. A new durable anchor was required.
One widening. The predicate is not agents.size === 0. BatchTracker#recordPlanned writes the spec before the spawn returns, so a process that died mid-spawn leaves an agent entry with no tracked.result — and no heldSinceAtMs. That row was equally unreapable, via the heldSinceAtMs === undefined clause rather than the agents.size === 0 one. The fix keys on no successful placement, which covers both. There is a test for each.
What changed
1. Reap a never-placed in-flight lifecycle. New durable field DispatchLifecycle.slotHeldSinceAtMs records when a row took its batch slot, stamped by the state stores on claim / promote / save and cleared when the row stops occupying a slot. Claim also stamps rows written before this change, so a lifecycle already wedged in production starts its clock at the next adoption rather than never. A new #holdDeadline(record) returns exactly one of two clocks — heldSinceAtMs + agentHoldTimeoutMs for a team that ran, or slotHeldSinceAtMs + agentlessHoldTimeoutMs (new, 30 min default) for one that never existed — and both halves of the reaper now use it.
The sweep re-derives the deadline against the durable row immediately before teardown, so an in-memory record that is a beat behind a placement that just succeeded here or a takeover elsewhere cannot trigger a release.
A never-placed agent is excluded from the release. A real broker rejects a release for a name it never issued; that failure sets cleanupComplete = false and re-arms the abandon retry forever, trading the wedge for a quieter one. This is load-bearing and tested — with the guard removed, the planned-agent test leaves the row stuck in abandoning.
2. Bound the capacity retry. #scheduleDispatchLifecycleRetry now backs off 1s → 2s → 4s … capped at 30s for DispatchLifecycleCapacityError, and escalates on every backoff step (then once a minute after the cap) with waitedMs, attempts and the issue keys holding the slots. Only the capacity path backs off — an ownership wait is already bounded by DISPATCH_LIFECYCLE_LEASE_MS, and every other failure is a real error whose fast retry is the recovery.
Deliberately not a hard abandon deadline: a legitimate multi-hour implementation run holds the slot honestly, and with batchSize: 1 every other issue's wait is legitimately that long. Abandoning a queued issue on a wall-clock ceiling would lose real work. What was harmful was the rate and the silence, and both are now bounded. With (1) in place, a wait that never ends is no longer reachable.
3. Make batch occupancy observable.
status().dispatchCapacityand the loop heartbeat carrybatchSize,active,waiting,longestWaitMs, the occupying issue keys and their phase/agent counts./healthzcarries the redacted projection (counts and durations only — issue keys carry customer project names and stay behind/evidence), includingagentlessOccupants, the wedge signature.dispatchCapacityjoinsDISPATCH_GATING_SUBSYSTEMS, so a wait pastdispatch.capacityWaitWarnMs(30 min default) setsstatus: degraded.okdeliberately does not move: recycling the container destroys the evidence and carries the durable lock into the replacement, exactly as production saw across three restarts.factory diagnose --deployednames a wedged batch instead of reporting green.
Also extracts the batch-slot predicate that FileStateStore and InMemoryStateStore had each copy-pasted into src/state/dispatch-lifecycle-slot.ts, now that a third reader depends on it.
Must-not-fire control
The window between promoteDispatchLifecycle and the first placement legitimately has no agents. does not reap a lifecycle still inside its promote-to-spawn window (#303) blocks the fleet's spawn on a gate, asserts the durable row is dispatching with heldSinceAtMs undefined and an agent carrying no result, waits 2.5 s — past the 1 s agentHoldTimeoutMs, far short of the 60 s agentlessHoldTimeoutMs — then asserts the row is untouched, nothing was released, and no counter moved. It then releases the gate and asserts the dispatch completes normally into running. Two independent guards back this: the 30 min default (a promote-to-spawn window includes clone, worktree prep and fleet spawn) and the durable re-derivation in the sweep.
Fail-first
Written before the fix and run against the unmodified orchestrator:
❯ src/orchestrator/factory.test.ts (552 tests | 3 failed | 548 skipped) 31183ms
× reaps a slot-holding lifecycle that never recorded an agent so a queued issue can dispatch (#303) 8139ms
× reaps a slot-holding lifecycle that recorded a planned agent that never spawned so a queued issue can dispatch (#303) 8093ms
× backs off and keeps reporting a dispatch capacity wait instead of spinning silently (#303) 12245ms
FAIL src/orchestrator/factory.test.ts > FactoryLoop > reaps a slot-holding lifecycle that never recorded an agent so a queued issue can dispatch (#303)
FAIL src/orchestrator/factory.test.ts > FactoryLoop > reaps a slot-holding lifecycle that recorded a planned agent that never spawned so a queued issue can dispatch (#303)
AssertionError: expected { runId: 'wedged-run', …(8) } to match object { phase: 'abandoned', …(1) }
- Expected
+ Received
{
- "phase": "abandoned",
- "releaseReason": "agentless-slot-past-deadline",
+ "phase": "dispatching",
}
❯ vi.waitFor.timeout src/orchestrator/factory.test.ts:10920:12
FAIL src/orchestrator/factory.test.ts > FactoryLoop > backs off and keeps reporting a dispatch capacity wait instead of spinning silently (#303)
AssertionError: expected 1 to be greater than or equal to 3
❯ vi.waitFor.timeout src/orchestrator/factory.test.ts:11033:59
11031| // Deliverable 2: the wait escalates instead of going silent aft…
11032| // log, and each re-arm is longer than the last.
11033| await vi.waitFor(() => expect(capacityWaits.length).toBeGreaterT…
The first two are the reap: the wedged row stays dispatching forever and the queued issue never spawns. The third is the retry: exactly one capacity log ever fires, with no waitedMs, no attempts and no escalation — the silence that made a 14-hour outage look like an idle Factory.
The must-not-fire control passes both before and after, by construction. Its value is as a regression guard on the new deadline; the load-bearing proof that the guard is real is the deleted-guard run above, where the planned-agent row sticks in abandoning.
Post-fix: 1909 passed | 1 skipped, npm run build and npm run featuremap:check clean.
Not done here
batchSizestill defaults to 1. Raising it is an operational change and not mine to make unilaterally, as #303 notes. With this fix a wedged row no longer leaks a slot permanently, so the default is no longer an outage multiplier — but one long-running issue still blocks everything behind it, which is a separate decision.#scheduleAbandonedDispatchRetryand#scheduleReleaseRetryare still flat 1 Hz. Neither is reachable from a wedge now (the never-placed release guard removes the only path that looped forever), so bounding them is cleanup rather than an outage fix.
🤖 Generated with Claude Code
Summary by cubic
Reaps slot-holding lifecycles that never placed an agent, bounds capacity retries, surfaces batch occupancy, and classifies late placements so readiness doesn’t abort (Linear #303). Old behavior: agent-less rows never reaped and capacity waits went silent; new behavior: they reap on a dispatch-armed deadline, capacity retries back off and reset on real slot release, capacity shows up in status/health/CLI, and late placements are released and classified.
-
Adds durable
slotHeldSinceAtMsanddispatch.agentlessHoldTimeoutMs(30m default). One clock per lifecycle: placed usesheldSinceAtMs + agentHoldTimeoutMs; never-placed usesslotHeldSinceAtMs + agentlessHoldTimeoutMs. Deadline arms at initial dispatch, is re-derived from the durable row before teardown, and pre-existing rows start their clock on next claim. -
Strengthens late-placement safety: after a spawn returns, ownership is revalidated against what
saveaccepts (same owner, same epoch, unexpired lease). If not owned or terminal, the worker is torn down without persisting placement and classified asLatePlacementReleasedError; classification uses the durable deadline so live workers are not leaked. -
Excludes never-issued agents from broker release and releases placements that land after their dispatch was reaped.
-
Capacity waits back off 1s → 2s … → 30s with escalating logs and
occupiedBy, and reset only when a write transitions a lifecycle from occupying to not occupying a slot. -
Observability: status/heartbeat add
dispatchCapacitywithbatchSize,active,waiting,longestWaitMs, occupants (includingplacedAgents, slot/placement hold times), and waiting issues./healthzincludes a redacted block, degrades oncedispatch.capacityWaitWarnMs(30m default) is exceeded, and wedges count only occupants with zero placed agents at or past the reap deadline. CLI diagnose names a wedged batch, treatslongestWaitMsas queue wait, and avoids “free batch” when a live daemon predates this field. -
Slot occupancy matches admission via a shared predicate and counts only lifecycles that still block promotion; it excludes teams fully handed off to unreleased babysitters.
-
New config:
dispatch.agentlessHoldTimeoutMs,dispatch.capacityWaitWarnMs(both default 30m). New counters:agentlessSlotPastDeadlineReleases,dispatchLifecycleCapacityWaits,dispatchCapacityBackoffResets. No data migration required.