fix(orchestrator): respect the advertised Retry-After and stop discarding a sweep on one 429 (#297)

Merged
KH
3mo ago
+1280-52

Fixes #297.

relayfile answers an overloaded workspace DO with a 429 in milliseconds carrying Retry-After: 5. Factory answered by sleeping up to 300 seconds, latching on the first 429 raised anywhere in the sweep, discarding the entire sweep including work that had already succeeded, and clearing the ratchet only after a fully clean sweep. Root-caused during the 2026-08-20 cloud outage, where /healthz still read degraded seven minutes after the upstream fix (relayfile-cloud#166) went live purely because of this.

1. Respect the advertised Retry-After

discoveryOverloadBackoffMs treated the advertised delay as a floor under an independent 5/10/20/40/80/160/300s ladder — so a request to wait 5s produced a 300s sleep. It is now authoritative in both directions:

  • first rung — we never retry sooner than the dependency allows;
  • ceiling — DISCOVERY_OVERLOAD_ADVERTISED_BACKOFF_MAX_MS (30s), or the advertised value itself when that is larger, so a dependency asking for longer still gets what it asked for.

With no advertised delay there is nothing to respect and the original five-minute ladder governs unchanged. Retry-After: 0 is floored at DISCOVERY_OVERLOAD_BACKOFF_MIN_MS, or 0 * 2**n would pin the whole ladder at zero and turn "respect the dependency" into "hammer it".

Retry-After: 5beforeafter
rungs 1–75s → 10 → 20 → 40 → 80 → 160 → 300s5s → 10 → 20 → 30 → 30 → 30 → 30

2. Do not discard a whole sweep for one latched 429

Same shape #292/#293 fixed for dispatch errors, and the per-item catch is inverted the same way rather than by inventing a second pattern. A 429 on one work unit — its ready-issue read or its dispatch — skips that unit and the sweep continues, recorded as a skip with a sanitized reason. #isPassFatalFailure no longer treats the sweep-wide latch as fatal.

Two controls keep that from becoming "grind a shedding dependency through the whole backlog one 429 at a time":

  • DISCOVERY_OVERLOAD_PER_SWEEP_LIMIT shed operations in one sweep aborts the pass and takes the deferral path, mirroring UNCLASSIFIED_DISPATCH_FAILURE_LIMIT.
  • A sweep that was shed and got NO unit through still fails. There is no progress to preserve, and committing it would leave readinessReconcile green over a dependency that served none of it — the #292 wedge wearing the other costume.

3. Decay the ratchet on partial progress

consecutiveOverloads reset only inside completeDiscoverySweep, so requiring a perfect sweep meant the ratchet rarely cleared under sustained mild load. The signal is now whether relayfile served any of this sweep's work units: a shedding DO rejects all background traffic (oldest_inflight_age does this regardless of how few requests are in flight), so a genuinely overloaded workspace gets not one unit through and still escalates to the cap, while a sweep that got units through decays one rung. Decay, not reset — surviving shedding is not evidence the overload is over. A committed-but-shed sweep keeps a decayed ratchet and a backoff instead of clearing both, via an optional completeDiscoverySweepWithOverload on the state port (see review round 1 below).

4. Log the 429 reason, not just its message

relayfile's four reason codes — inflight_limit, oldest_inflight_age, router_inflight_limit, durable_object_overloaded — share one message string and mean four different things (a DO-local admission cap, one stuck op poisoning every background caller, a Worker-global isolate cap, the Cloudflare runtime shedding the object). relayfileOverload() always parsed the reason; nothing on this path printed it, and during the incident that ambiguity was the single biggest obstacle to diagnosis.

Now: every shed operation warns with { operation, status, reason, retryAfterSeconds, sweepOverloads }; discoveryOverloadReason:<code> counters appear in status().counters; and readinessReconcile.lastError carries [relayfile 429 <reason>; retry-after=Ns]. The reason is allowlisted wherever it reaches stdout or a counter key — the same public-surface rule #293 applied to error class names.

Tests

Five must-fire regressions, each verified failing against unmodified source before the fix (full output below), and three must-not-fire controls.

Must-not-fire:

  • still climbs the five-minute ladder when the 429 advertises no Retry-After — proves the ceiling still applies with nothing advertised. Passes before and after.
  • still escalates from the decayed counter when the next sweep gets nothing done — partial-progress decay does not make the ratchet meaningless; escalation resumes from the decayed value, not from zero.
  • still fails a sweep in which relayfile shed every work unit — deliberately below the fuse limit, so "no unit got through" is what saves it.

Pre-fix failures (final tests, unmodified src/orchestrator/factory.ts)

 ❯ src/orchestrator/factory.test.ts (526 tests | 5 failed | 518 skipped)

 FAIL  Relayfile discovery overload (#297) > caps the ladder near the advertised Retry-After instead of climbing to five minutes
AssertionError: expected [ 5000, 10000, 20000, 40000, …(3) ] to deeply equal [ 5000, 10000, 20000, 30000, …(3) ]

- Expected
+ Received

  [
    5000,
    10000,
    20000,
-   30000,
-   30000,
-   30000,
-   30000,
+   40000,
+   80000,
+   160000,
+   300000,
  ]

 FAIL  Relayfile discovery overload (#297) > skips the work unit relayfile shed and dispatches the rest of the sweep
 FAIL  Relayfile discovery overload (#297) > logs the 429 reason code, not just its message
 FAIL  Relayfile discovery overload (#297) > decays the ratchet when a sweep makes progress despite an overload
 FAIL  Relayfile discovery overload (#297) > still escalates from the decayed counter when the next sweep gets nothing done
Error: workspace durable object is busy; retry after the advertised delay
 ❯ ShedSomeIssueReadsMount.readFile     src/orchestrator/factory.test.ts:4244:50
 ❯ FactoryLoop.#withRelayfileOperation  src/orchestrator/factory.ts:3635:28
 ❯ FactoryLoop.#readRelayfileFile       src/orchestrator/factory.ts:3599:17
 ❯ FactoryLoop.#readGithubIssue         src/orchestrator/factory.ts:6468:42
 ❯ FactoryLoop.#readIssue               src/orchestrator/factory.ts:7145:29
 ❯ FactoryLoop.#performRunOnce          src/orchestrator/factory.ts:2460:23
 ❯ FactoryLoop.#runOnceWithDiscoveryFence src/orchestrator/factory.ts:2335:22

      Tests  5 failed | 3 passed | 518 skipped (526)

Four of the five fail by aborting the whole sweep on the latched 429 — the trace above is deliverable 2 reproduced exactly: one issue's readFile is shed, and #performRunOnce throws instead of skipping that unit.

Post-fix

 Tests  15 passed          # the #297 suite, including 3 must-not-fire controls
 Tests  1827 passed | 1 failed   # full suite

The single full-suite failure is dist-entrypoints, which needs npm run build first and fails identically on unmodified origin/main.

Review rounds

Nine bot threads across two rounds, six distinct findings, all fixed. Each fix has its own test verified failing against the unmodified source first; the failures are pasted in the thread replies.

Round 1 — on cb1f34f:

FindingReviewersFix
P1 A 429 raised after #dispatchUnlocked spawned left the agents unreaped, so skip-and-continue leaked them where the old abort did notcodex + cubicReap on every per-item skip except the two lifecycle refusals decided before any spawn (mayHaveSpawnedBeforeFailing, a denylist on purpose)
P2 readinessReconcile.lastError embedded the raw overload.reasoncubic + coderabbitRouted through relayfileOverloadReasonLabel, like every other surface here
P2 Only the first 429's Retry-After was honouredcodexSweep tracks the maximum advertised delay
P2 A read returning undefined was credited as progresscubicRequires issue to be present
P2 An optional residual argument was silently dropped by stores compiled against the old signaturecubicOptional completeDiscoverySweepWithOverload instead, following this port's own renewDiscoverySweepWithDetails precedent; absent + residual pending now warns and counts

Round 2 — cubic re-reviewed the round-1 fixes on 430f2c1 and found two real follow-ons, both in the P1 fix itself:

FindingFix
P1 The reap ran after #isPassFatalFailure, so the 429 tripping the overload fuse threw past it — and a direct runOnce() (the CLI, #reconcileReadyIssues) has no runLoop catch behind itMoved to the top of the catch, covering the abort and the skip in one call
P2 listFailureHandoffs sat outside the reap's own try, so a store failure replaced the error in flight — and a replaced 429 is not overload at the fence, silently dropping the backoffFixed at the source, so runLoop's catch (same exposure, during teardown) is covered too

Two of the round-2 test harnesses initially produced red results for the wrong reason and had to be corrected — one tripped the fuse on a unit that had spawned nothing, the other replaced the 429 inside dispatch before the reap ran. Both would have gone green after a fix that changed nothing about the defect. Noted here because "fails first" only counts if it fails for the reason under test.

Not in scope

The upstream trigger (relayfile-cloud#166, unbounded provider-generation alarm work) is already fixed and deployed. UPSTREAM-FINDINGS.md's remaining recommendation — telemetry for alarm(), which takes no admission slot and so is invisible in inflight/oldestInflightAgeMs — belongs in AgentWorkforce/relayfile-cloud, not here.

🤖 Generated with Claude Code