fix(factory): arm the never-placed reaper independently of startup fleet health (#315)

Merged
KH
3mo ago
+603-14

Closes #315.

The mechanism

#rescheduleHeldAgentDeadlineSweep() is the only thing that arms a hold deadline for a row that survived a restart, and it was the last statement of the try in #adoptInFlightAgents, whose catch only logs. Two fleet awaits sit above it:

  • await this.#fleet.reconcileTrackedAgents?.() — not circuit-proxied (guardFleetControlPlane wraps only roster, spawn, resume), so with the broker down it reaches the transport and rejects on its own.
  • await this.#fleet.roster() — the guarded one, which throws FleetControlPlaneCircuitOpenError outright once the circuit is open, without touching the transport.

The enclosing try/finally has a finally but no catch, so either throw propagates to the outer catch, skipping the arming. No hold deadline is armed for that boot: the #304 reaper is present in the build and was never scheduled — disabled by exactly the fault it exists to clear. That matches the reported environment, where fleetControlPlane was open for the whole window while the process restarted under the broker outage.

Arming now runs in a finally, so it survives every throw site above it — including ones added later.

Why a running row

Every other slot-occupying phase is additionally armed by #scheduleDispatchLifecycleRetry, called earlier in the same loop; running is the one phase that call skips. So the aggregate arming is a running row's only route.

An agent-less running row is not contrived — it is what the GitHub orphaned-PR adoption path produces: it saves running from records whose agents may carry no spawn result (t.result?.name ?? t.spec.name) and never stamps heldSinceAtMs.

I originally expected this on a dispatching row and wrote a probe that passed against unfixed main before finding that the per-row retry driver rescues that phase. The fixture phase is load-bearing here, not incidental.

A second, non-fleet route into the same state

#readIssue swallows every read failure except a relayfile 429, which it rethrows so callers can back off. On the adoption path that rethrow aborted the whole loop from inside one row's iteration — before that row was restored into the batch and before its retry was scheduled — stranding it and every later row with no armed deadline. Startup already degrades safely when an issue is merely unreadable; a shed read now degrades the same way instead of stranding the batch.

The abandoning second path — named so the next reader does not rediscover it

Not fixed here, and deliberately so. dispatchPhaseOccupiesSlot excludes queued, waiting-for-human, releasing, complete, abandoned — it does not exclude abandoning. #abandonStuckDispatch sets #abandonedDispatchReasons and saves abandoning; any later cleanup failure returns early leaving the row at abandoning: still slot-occupying, still placedAgents: 0, still past its deadline, so still counted as a wedge. And the sweep will not look at it again — if (this.#abandonedDispatchReasons.has(key)) continue. Recovery then rests entirely on #scheduleAbandonedDispatchRetry.

The consequence worth writing down: a reap that fired and half-completed produces a health signature identical to one that never fired. The occupant identity added below is what now lets an operator tell those apart from outside the process. Fixing the phase accounting is a separate change with its own admission-semantics blast radius, and it should not ride along with a reaper-arming fix.

Observability — part of this fix, not a follow-up

state: "healthy" through the wedge. deriveDispatchCapacityState returned healthy whenever waiting === 0. agentlessOccupants was computed one line above and never passed in. The reported payload had waiting: 0, so it read healthy while half a two-slot batch was held by a row past its own reap deadline — a monitor staying green through the exact condition it exists to catch. Nothing is queued because dispatch is down; the moment it resumes, that is a halved batch running into the backlog. It now reports stalled, and the reader path will not launder a stale healthy over a record whose own occupants carry the wedge.

A count with no identity. agentlessOccupants is a count, and a count cannot separate one stuck occupant from reap-and-reacquire churn — both read 1 on every sample, forever. That is why stating this took 34 samples over 40 minutes rather than one request. Each occupant now carries slotHeldForMs (grows monotonically for a stuck row, resets for a churning one) and a stable id.

The id is a per-process salted digest, not a bare hash: issue keys carry project and repository names, which is why this surface redacts them (#303), and a bare digest of a low-entropy key like AR-315 is recoverable from a word list. Salting makes the id meaningful only by comparison — which is all the reading requires — and uncorrelatable to an issue. It is deliberately not stable across restarts.

Tests

Three must-fire, each verified to fail against unfixed source for the right reason, not merely to be red:

testfailure on unfixed source
startup reconcileTrackedAgents rejectsexpected { … } to match object { phase: 'abandoned', … } → received "phase": "running"
startup roster rejectssame — row never moved, reap warn never emitted
startup issue read shed with a 429first warn is [factory] failed to re-adopt durable in-flight agents carrying status: 429; the next is AR-335 waiting on capacity with occupiedBy: [] — a full batch whose occupant list is empty, because nothing was ever adopted

Both fleet tests assert [factory] failed to re-adopt durable in-flight agents actually fired, so they cannot pass vacuously on a boot where nothing threw.

One must-not-fire: a dispatching row is armed by both routes once this lands, so it pins that it is still released exactly once — the fix must not trade a wedged slot for a double teardown.

Plus three on the public-health surface, all failing before (expected 'healthy' not to be 'healthy', expected 'healthy' to be 'stalled', occupants absent).

Verification

  • Full suite: 1961 passed. Two failures, both confirmed pre-existing on unmodified main in this same worktree: dist-entrypoints (needs dist/ built — passes after npm run build) and fleet.test.ts > keeps relay dispatch ownership…, which flakes at the same rate on clean main (2 fail / 1 pass in three isolated runs, identical with and without this change).
  • tsc -p tsconfig.build.json clean; npm run build clean; featuremap:check ok.
  • Touches no file in #317 (src/fleet/relay-fleet-client.ts). The 45s node-delivery guard and the #292 fuse are untouched.

🤖 Generated with Claude Code


Summary by cubic

Arms the never-placed reaper during startup even when the fleet control-plane is down, and fixes public dispatch-capacity health so wedged capacity is surfaced and identifiable. Previously, startup throws (reconcileTrackedAgents/roster) or a shed 429 issue read could skip arming/adoption, leaving a slot stuck past agentlessHoldTimeoutMs while health reported healthy. Addresses Linear AR-315.

  • Move #rescheduleHeldAgentDeadlineSweep() into finally in #adoptInFlightAgents; arming is idempotent and still releases exactly once.
  • Startup adoption: treat relayfile 429 as non-fatal; warn, adopt without the read, and schedule retries.
  • Public health:
    • Derive stalled when any occupant is past agentlessHoldTimeoutMs even if waiting === 0, and refuse to re-publish healthy over a wedged record.
    • Publish per-occupant redacted fields: boot-scoped salted id, optional placedAgents (omit when unreported), slotHeldForMs, pastReapDeadline; when the issue key is missing, fall back to a position-based id.
    • Reader normalization re-derives the wedge from occupants, recomputes the count when absent, and propagates it to top-level status: 'degraded' and degradedSubsystems.
  • Tests pin the two fleet-failure paths, the shed-read path, the must-not-fire double-release case, and the public-health state/occupants/top-level propagation.