fix(orchestrator): skip per-item dispatch failures instead of aborting the run-once pass (#292)
Fixes #292.
What was broken
The per-item catch in the run-once iteration loop whitelisted exactly one error type:
catch (error) {
if (!(error instanceof LiveDispatchStateChangedError)) throw error // everything else is fatal
...
}
Everything else escaped the for loop over issues, reached the outer handler that logs
[factory] run-once failed, and killed the pass — so every issue behind the failing one was
never processed. Production Cloud Factory sat wedged this way with
readinessReconcile.state = degraded, consecutiveFailures: 7, and
lastError: "Refusing to dispatch 1531: dispatch lifecycle is already terminal".
The blocked unit was not special. It was merely the first item to throw something not on the
whitelist.
1. Narrow fix
#claimDispatchLifecycle now throws a typed DispatchLifecycleClaimRefusedError (message text
unchanged) instead of a plain Error, carrying refusal: 'terminal' | 'owned-elsewhere'. The loop
records it as a skip with a clear reason — dispatch lifecycle already terminal — exactly like its
sibling conditions (not factory-e2e scope, parked on dependencies, live state is not ready-for-agent). Typed rather than message-matched so the classification is by construction, not
by parsing Refusing to dispatch ….
2. The class fix — and the fatal-vs-per-item reasoning
The catch is inverted: a failure raised while processing one work unit skips that unit by
default. Only conditions named in the FactoryLoop#isPassFatalFailure predicate abort the sweep.
The full reasoning lives in the doc comment on that method; the summary:
Fatal — continuing the pass is meaningless or actively harmful, because the failure is about the
pass, not the item:
- The discovery sweep lease is gone (
#discoverySweepLeaseLost). Another process now owns this
workspace's sweep. Every remaining read throws the same way, and each one would land in the report
as an ordinary per-issue skip — so the run report would claim a clean pass over work this process
no longer has the right to touch. - Relayfile signalled overload for this sweep (
#discoveryOverloadError). The backend is
shedding load; grinding through the remaining units makes it worse, and
#runOnceWithDiscoveryFencerethrows this at the fence anyway. - The factory is stopping (
#stopping). Teardown is in progress; dispatching more agents now
leaks them past the shutdown deadline. - The fleet control-plane circuit is no longer closed — on a live pass. Dispatch is globally
paused, the same condition#assertFleetControlPlaneAvailablerefuses to start a live pass on,
so it must also stop one already in flight. Checked both by type and by reading circuit state
— see "Circuit-open transitions are now self-describing" below for why both are needed.
A dry run is exempt, because this rule is fleet-scoped and a dry run never calls fleet
admission and never spawns: an open circuit is irrelevant to it, not fatal to it. Without the
exemption, one live pass that trips the circuit poisons every dry run for the whole reset window —
including the container boot gate'srun-once --dry-runprobe, turning a recoverable
circuit-open condition into a failed boot. The sweep-scoped rules above (lease lost, overload,
shutdown) are not exempt: they are about this process's right to run the pass at all, which a
dry run needs just as much.#isPassFatalFailuretakes the effectivedryRunand splits on
exactly that line.
Per-item — the failure costs that unit and nothing else: a refused or terminal lifecycle claim,
a live-state race, a transient provider/network fault on one issue's writeback or roster lookup.
The line a reviewer should push on. The obvious next rule is "treat programmer faults
(TypeError, ReferenceError, SyntaxError) as fatal — the code is wrong, so skipping past our own
bugs is the same silent wedge in reverse." I deliberately did not do that, and this is the call
most worth disagreeing with. Node reports a failed fetch as TypeError: fetch failed — which is
precisely the transient, single-issue roster lookup that wedged the second instance
(Dispatch roster lookup failed for <key>: fetch failed, filed as #291, not fixed here). A rule
keyed on builtin error types would have preserved that outage verbatim. SyntaxError is worse
still: JSON.parse of one malformed issue record is per-item by definition. Any type-shaped rule
over builtins is a trap, so the fatal set is domain conditions only.
What stops this from swallowing everything. A dispatcher that never fails is as broken as one
that always does, so the skip-by-default path is bounded three ways:
- An unclassified-failure fuse (
UNCLASSIFIED_DISPATCH_FAILURE_LIMIT = 5). A pass-wide fault
can arrive disguised as a run of per-item faults — a dead state store, an expired credential.
Five unclassified failures with no successful dispatch in between abort the pass with a wrapped
error, soreadinessReconcile.lastErrorcarries the cause instead of the report handing back a
green pass full of skips. Named per-item conditions (a lifecycle claim refusal, a live-state
race) neither count toward the fuse nor reset it: they legitimately affect many units at once —
the benign case #292 asks the loop to survive — and a claim refused by the state store before
anything reaches the fleet is no evidence that dispatch works. A completed dispatch is the only
reset, which is why the counter is namedunclassifiedFailuresSinceDispatchrather than
"consecutive". - Every skip is visible, not silent — but the two kinds of skip are counted separately, because
they mean different things:- An unclassified failure (something went wrong on this unit) lands in
report.skipped, logs
atwarnwith the full error, incrementsdispatchItemFailuresSkipped, and goes through
#errorso it reachescounters.errorsand telemetry. - A classified skip (this unit cannot be dispatched right now: lifecycle claim refused,
live-state race) lands inreport.skipped, logs atinfo, and increments
dispatchItemsSkippedUndispatchable— so a growing terminal-lifecycle backlog is visible to
counters, not only to a report line. It deliberately stays out ofcounters.errors: an
undispatchable unit is a state, not a fault, and routing it there would make a healthy factory
look like a failing one exactly when that signal needs to mean something. The test pins both
halves (dispatchItemsSkippedUndispatchable === 1andcounters.errors === 0).
- An unclassified failure (something went wrong on this unit) lands in
- Classification follows the
causechain (bounded depth 4), becausecontextualErrorand the
fleet control-plane guard both rethrow wrapped — a fatal condition cannot be hidden behind a
wrapper.
Circuit-open transitions are now self-describing (src/fleet/control-plane-circuit.ts)
Raised in review, and it is the mirror image of the builtin-type trap above. probe() recorded the
failure that crossed the threshold and rethrew the original transport error — an ordinary
timeout, or TypeError: fetch failed. So a globally fatal transition arrived dressed as a per-item
fault, and a dispatcher classifying by error type would skip the very work unit whose roster request
paused all dispatch. If that unit was the last ready issue, the pass returned successfully while the
circuit was already open, leaving readiness green.
probe() now rejects that failure as FleetControlPlaneCircuitOpenError with the transport error
kept on cause. This is the third case of a rule probe() already applied twice — it throws
circuit-open when the state is open at entry, and when a mutation opened the circuit while a read was
pending; the transition itself was the one that stayed silent.
This is a deliberate contract change. Two existing circuit tests asserted the old behavior
(rejects.toMatchObject({ name: 'TimeoutError' }) on the threshold-crossing probe) and now assert
the transition plus cause: expect.objectContaining({ name: 'TimeoutError' }).
#isPassFatalFailure still reads circuit state as well, and not merely as belt-and-braces:
guardedMutation records a mutation's own transport failure and rethrows the original error, so
that path can still open the circuit without saying so. Converting the error there would be wrong —
a mutation may already have reached the broker, and callers key spawn-failure handling off the
original error. So: named at the source for probes, state-checked for the mutation path.
Report reasons are sanitized (perItemDispatchSkipReason)
Also from review. factory run-once serializes the whole IterationReport to stdout, so
skipped[].reason is a public surface — and it was embedding describeError(error).errorMessage
verbatim, which can carry provider text or filesystem paths out of a public repo. The reason is now
a fixed classification plus an allowlisted class name via telemetryErrorClass, which only passes
/^[A-Za-z][A-Za-z0-9]{0,63}(?:Error|Exception)$/ and otherwise falls back to Error. The full
message still goes to the operator log. This is the same split the file already makes for circuit
state in describeControlPlaneError.
Keeping the class rather than dropping it entirely: dispatch failed (TypeError) versus
dispatch failed (DispatchLifecycleClaimRefusedError) is the difference between "a transient fault
hit this unit" and "this unit is structurally undispatchable", which is what an operator reading a
skipped list needs. The vocabulary is closed and pattern-checked, so it carries the signal without
the payload.
Handoff-reaper regression, fixed in the same change
#reapDispatchFailureHandoffsNow previously ran only from runLoop's catch — i.e. only because a
per-item dispatch failure aborted the pass. With the pass now surviving, a failure that left
half-spawned agents behind would leak them until some later iteration happened to fail. The skip
path therefore reaps inline. runLoop records the registry/heartbeat paths it would use so the
inline reap writes to the same place.
Tests — both directions
Must-fire. Both fail against unfixed code:
- "skips a work unit whose dispatch lifecycle is already terminal and dispatches the rest of the
pass" — issue 59's lifecycle claim is refused as terminal; issue 60 in the same pass must
still dispatch. - "skips a work unit whose per-item failure is unclassified and dispatches the rest of the pass" —
issue 59 fails withTypeError: fetch failed(#291's shape); issue 60 must still dispatch.
Pre-fix failure, verbatim:
FAIL src/orchestrator/factory.test.ts > FactoryLoop > per-item dispatch failures do not abort the
readiness pass (#292) > skips a work unit whose dispatch lifecycle is already terminal and
dispatches the rest of the pass
Error: Refusing to dispatch 59: dispatch lifecycle is already terminal
❯ FactoryLoop.#claimDispatchLifecycle src/orchestrator/factory.ts:4685:13
4683| ? 'dispatch lifecycle is already terminal'
4684| : `dispatch lifecycle is owned by ${claim.lifecycle.lease?.own…
4685| throw new Error(`Refusing to dispatch ${decision.issue.key}: ${r…
| ^
❯ FactoryLoop.#dispatchUnlocked src/orchestrator/factory.ts:3785:30
❯ FactoryLoop.dispatch src/orchestrator/factory.ts:3641:22
❯ FactoryLoop.#performRunOnce src/orchestrator/factory.ts:2536:22
❯ FactoryLoop.#runOnceWithDiscoveryFence src/orchestrator/factory.ts:2310:22
❯ FactoryLoop.runOnce src/orchestrator/factory.ts:2216:14
FAIL … > skips a work unit whose per-item failure is unclassified and dispatches the rest of the pass
TypeError: fetch failed
❯ FailingTriage.triage src/orchestrator/factory.test.ts:4501:30
❯ FactoryLoop.triageIssue src/orchestrator/factory.ts:3622:25
❯ FactoryLoop.#performRunOnce src/orchestrator/factory.ts:2532:39
❯ FactoryLoop.#runOnceWithDiscoveryFence src/orchestrator/factory.ts:2310:22
❯ FactoryLoop.runOnce src/orchestrator/factory.ts:2216:14
That is the production error, reproduced.
Must-not-fire. Two controls, each verified by mutation to actually detect over-swallowing:
- "still aborts the pass when the fleet control plane is globally unavailable" — emptying
PASS_FATAL_DISPATCH_ERRORSmakes this test fail. - "still aborts the pass once a per-item roster failure opens the circuit" — removing the circuit
state read makes this test fail withpromise resolved … instead of rejecting. It uses a
single ready issue on purpose: with more work behind it the pass aborts one item later on the
now-open circuit and the test passes either way. - "MUST NOT FIRE: a failure below the threshold still rejects with the original error"
(control-plane-circuit.test.ts) — the control for the source fix, so a transient single fault is
never misreported as a global pause. - "still treats the same open circuit as fatal on a live pass" — the live half of the dry-run
exemption pair. Replacing the fleet rule withreturn falsemakes it fail with
promise resolved … instead of rejecting.
The dry-run exemption pair. Both halves share one openTheCircuit() fixture so they cannot
drift apart: a live pass trips the circuit, then the broker recovers while the circuit stays open.
"skips per-item failures in a dry run while the fleet circuit is open" fails first as
Error: unrelated per-item fault — an unrelated per-item fault killing a dry-run pass purely
because an earlier live pass opened the circuit — while its live sibling still aborts.
Plus, for the circuit source fix, a must-fire unit test — "MUST FIRE: the failure that trips the
threshold rejects as circuit-open, keeping the cause" — which fails first as
expected TypeError: fetch failed … to be an instance of FleetControlPlaneCircuitOpenError.
- "still aborts the pass once unclassified per-item failures repeat" — raising
UNCLASSIFIED_DISPATCH_FAILURE_LIMITto 1000 makes this test fail.
Skip visibility is asserted directly: each must-fire test checks the exact report.skipped
entry, and the unclassified case also asserts counters.dispatchItemFailuresSkipped.
Existing test updated
consumes an orphan-recovery readiness exemption after a failed dispatch transition asserted
rejects.toThrow('transient triage failure') — i.e. it encoded the bug: one transient triage
failure aborting the pass. It now asserts the failure is recorded as a skip and the pass completes;
the orphan-recovery exemption it actually tests is still consumed and the next pass recovers the
issue.
Not in scope
#291 (Dispatch roster lookup failed …: fetch failed) is a separate cause and is not fixed here.
This change stops that cause — and any other per-item fault — from taking down the whole pass.
Full suite: npx vitest run → 1814 tests, all passing (dist-entrypoints requires npm run build
first, as CI does; two agent-worktree git-shelling tests flake on a 5s timeout under parallel load
locally and pass in isolation and on CI). npm run featuremap:check clean.
🤖 Generated with Claude Code