Skip to content

fix(#761): classify rate limits mid-phase — skip doomed retries, label the chain halt - #781

Merged
admarble merged 3 commits into
mainfrom
feature/761-feat-detect-rate-limit-failures-mid-chain-and-
Jul 17, 2026
Merged

admarble merged 3 commits into
mainfrom
feature/761-feat-detect-rate-limit-failures-mid-chain-and-

Conversation

@admarble

Copy link
Copy Markdown
Contributor

Summary

Implements the rewritten ACs from #761 (see the clarification + pre-run verification comments on the issue): stop burning ~2 hours of doomed retries inside one phase when a rate limit hits mid-chain, and say why the chain stopped.

  • AC-1 (root cause): the driver's abort/timeout path discarded the already-captured rateLimitInfo and returned a bare Timeout after Ns. It now attaches structuredError via buildStructuredError, matching the sibling catch path. Only failure-grade signals are ever captured, so a genuine timeout is never mislabeled (regression-guarded).
  • AC-2: a rate limit whose resetsAt lies beyond RATE_LIMIT_WINDOW_SKIP_THRESHOLD_MS (5 min) skips all cold-start retries via a capped-style early return. Metadata-absent rate limits fall back to transient handling — the mandatory AC-9 fallback (the rate_limit_event is documented subscription-only; the assistant-error channel carries no metadata).
  • AC-3: the MCP fallback gate adds !failureIsRateLimited alongside !failureIsBilling && !failureIsCapped.
  • AC-4: transient rate-limit retries now wait via the injected delayFn with exponential backoff (5s → 10s) instead of a bare continue.
  • AC-5: displaySummary restates a rate-limited chain halt using formatRateLimitMessage (with resetsAt when present) and spells out that resume is re-running the identical command. Extracted buildRateLimitHaltNotice for standalone testability (the feat: resume a partially-completed chain from its last good link #760 planChainResumeFromState treatment).
  • AC-6: batch-executor errorContext (both sites) prefers result.structuredError over classifyError; rate_limit/billing added to ERROR_CATEGORIES, errorTypeToCategory, and the run-log category enum.
  • AC-7: .sequant/metrics.json records an optional bounded-enum failureCategory, threaded PhaseResult.structuredError → IssueResult.failureCategory → recordRun. Enum only — a free-text category fails schema validation (test-pinned). Additive, no version bump.
  • AC-8: inverted both tests pinning the old behavior (phase-executor.test.ts:722 transient-retry pin, and the claude-code.test.ts "feat(driver): surface structured rate-limit/credits errors from SDK message stream (replaces #592 fallback noise) #732 does NOT mask a genuine timeout" pin on the abort path); added window-exhaustion, backoff, MCP-skip, abort-path classification, and halt-notice coverage.
  • AC-9: per the pre-run verification, downgraded from design gate to validation. The metadata-absent fallback is implemented unconditionally; the errorFromAssistantError map now records the originating variant so rate_limit/overloaded no longer collapse into one shape. Remaining follow-up: confirm against a real captured window rejection when one occurs.

AC Verification

AC Status Evidence
AC-1 ✅ Implemented drivers/claude-code.ts abort branch; tests: "classifies a hang after a rejected rate_limit_event…", billing variant, bare-timeout regression guard
AC-2 ✅ Implemented isWindowExhaustedRateLimit + early return in executePhaseWithRetry; tests incl. cold-start-window + seconds-unit resetsAt
AC-3 ✅ Implemented failureIsRateLimited at the MCP gate; test "does not trigger the MCP fallback for a rate-limited failure"
AC-4 ✅ Implemented delayFn-based backoff, RATE_LIMIT_RETRY_BACKOFF_MS * 2 ** attempt; tests assert exact delays
AC-5 ✅ Implemented buildRateLimitHaltNotice + summary print in run-display.ts; 6 tests incl. #766 reverse-scan semantics
AC-6 ✅ Implemented batch-executor.ts both errorContext sites; enum additions in error-classifier.ts + run-log-schema.ts
AC-7 ✅ Implemented metrics-schema.ts FailureCategorySchema; threading via deriveFailureCategory; privacy pinned by "rejects a free-text failureCategory" test
AC-8 ✅ Implemented Both pins inverted; 265 tests green across the 6 touched suites; full suite 3999 passed
AC-9 ⚠️ Partial by design Fallback rule + metadata preservation shipped unconditionally (per pre-run verification, the live-capture validation is a post-hoc check, unsatisfiable from existing artifacts — no capture exists in .sequant/logs/)

Test plan

  • npm run build — clean
  • npm run lint — clean (0 warnings)
  • Full npm test — 3999 passed, 1 expected fail (pre-existing), 2 skipped
  • Post-merge validation (AC-9): when a real window rejection is captured, confirm it arrives with rateLimitType/resetsAt populated and the window-exhaustion skip fires as designed

Closes #761

🤖 Generated with Claude Code

admarble added 2 commits July 16, 2026 18:01
…s; label the chain halt

AC-1: the driver's abort/timeout path now attaches structuredError via
buildStructuredError, matching the sibling catch path — a rate limit that
manifests as a hang stays classifiable instead of returning a bare
"Timeout after Ns". A signal-less abort still reports the bare timeout.

AC-2: a rate limit whose resetsAt lies >5min out is window exhaustion and
skips all cold-start retries (capped-style early return); metadata-absent
rate limits fall back to transient handling (AC-9 fallback rule).

AC-3: MCP fallback gate adds !failureIsRateLimited — a throttle never
triggers "retrying without MCP".

AC-4: transient rate-limit retries get real exponential backoff via the
injected delayFn (5s → 10s) instead of a bare `continue`.

AC-5: displaySummary restates a rate-limited chain halt with
formatRateLimitMessage (resetsAt included when present) and says resume is
re-running the identical command; extracted buildRateLimitHaltNotice for
testability.

AC-6: batch-executor errorContext prefers structuredError over
classifyError; rate_limit/billing added to ERROR_CATEGORIES,
errorTypeToCategory, and the run-log category enum.

AC-7: .sequant/metrics.json records a bounded-enum failureCategory,
threaded PhaseResult.structuredError → IssueResult → recordRun. Enum only.

AC-8: inverted the two tests pinning the old behavior
(phase-executor.test.ts "still retries a transient rate-limit failure",
claude-code.test.ts "does NOT mask a genuine timeout"); added abort-path,
window-exhaustion, backoff, and MCP-skip coverage.

AC-9: assistant-error map records the originating variant in metadata so
rate_limit/overloaded stay distinguishable; window detection degrades to
the transient fallback when metadata is absent.
QA catch on the AC-5 halt notice: a BillingError arriving via the
assistant-error channel carries empty metadata, and
formatRateLimitMessage(metadata) with no billing signal falls through to
"Rate limited". Use the metadata-derived label only when the metadata
actually carries a signal (resetsAt or a billing marker); otherwise fall
back to the typed error's own message.
…it chain halt in run-command.md

analytics.md: failureCategory added to the field table (privacy column
states the bounded-enum guarantee) and to the MetricRun TypeScript shape,
with the closed FailureCategory enum spelled out.

run-command.md: chain-mode section gains "Rate-limit halts fail fast and
are labeled" alongside the sibling #748/#760 behaviors — the summary
notice, the resume affordance, and the metrics pointer.

AC-9's post-hoc validation now tracked in #782 instead of only the PR body.
@admarble
admarble merged commit b1bedbc into main Jul 17, 2026
5 checks passed
@admarble
admarble deleted the feature/761-feat-detect-rate-limit-failures-mid-chain-and- branch July 17, 2026 14:39
admarble added a commit that referenced this pull request Jul 25, 2026
…itType/resetsAt (#805)

* test(#782): validate #761 AC-9 — real window rejections carry rateLimitType/resetsAt

Post-hoc validation #761 AC-9 asked for. Two real rate-limit rejections
captured 2026-07-18 (startCommit b1bedbc — the PR #781 merge commit itself,
so the structured errorContext persistence was live) settle the load-bearing
assumption: window exhaustion DOES arrive on the structured rate_limit_event
channel with rateLimitType and resetsAt populated.

AC-1: channel = rate_limit_event, not bare assistant.error (errorMetadata
      .assistantError absent — structurally decisive per buildStructuredError).
      rateLimitType "five_hour", resetsAt 1784392200 -> 16:30Z, matching the
      CLI's own "resets 11:30am" line.
AC-2: partial, and recorded as such. MCP fallback correctly skipped and the
      non-retryable classification held, but the "window exhausted" line did
      not print — credits were also exhausted, so isBillingFailure won and the
      error was a BillingError, which the predicate excludes by design. The
      counterfactual is decisive: the reset was 24.8 min out, well past the
      5-min threshold, so the same payload without the credits flag would have
      taken the branch. Cold-start retries were NOT skipped (known, intended —
      see the comment above the capped early return).
AC-3: not triggered. The AC is conditional on rejections arriving WITHOUT
      metadata; metadata was present, so no follow-up issue is filed.

Adds a production-sample regression test that replays the committed captures
through createRateLimitError and isWindowExhaustedRateLimit, including the
counterfactual. Existing coverage is entirely synthetic; this pins the real
field names and units so SDK drift breaks a test instead of silently disabling
the #761 branch. Verified non-tautological by mutation.

Docs + tests only — no behavior change, no threshold change (issue Non-Goals).

* test(#782): guard the #799 sibling site; correct an overclaimed MCP evidence row

Two QA findings on my own first commit.

1. Cross-file sibling site (QA §5). batch-executor's isBillingOrWindowHalt
   (#799) consumes the same classifier as the #761 window branch, and its
   coverage is also entirely synthetic. The captured payload is a valid input,
   so replay it there too: if SDK drift changed the shape, the predicate would
   silently stop halting the -Q loop and #799's "QA completed without a
   parseable verdict" mislabel would return. Also pins billingHaltReason.

2. Overclaim in validation.md. The "MCP fallback skipped" row cited "no
   retrying without MCP line" as if it were observed in the capture. It is not:
   stdoutTail/stderrTail carry the driver's stdoutBuffer (agent output), while
   that line comes from the executor's own bracketedConsoleLog — so it would
   not appear in these artifacts either way. The skip is a code-level guarantee
   via the failureIsBilling gate, not a log observation. The evidence table now
   carries a "kind of evidence" column separating observed from inferred from
   code-level across all four rows.

Still docs + tests only.

* docs(#782): commit the metrics corroboration; the cited source is gitignored and rotating

Second-look findings on the validation record.

1. Perishable, unverifiable evidence. validation.md cited
   ".sequant/metrics.json" as independent corroboration for AC-1, but
   .sequant/ is gitignored (.gitignore:52) — so no reader could check that
   claim. Worse, run-log rotation is capped at maxFiles: 100 and is actively
   evicting: the directory was observed dropping 100 -> 99 while this was being
   written, so the cited originals are on their way out. The two matching
   metrics entries are now excerpted verbatim into the captures directory, and
   the doc explains why the artifacts are copied rather than referenced. This
   also retroactively justifies committing the run logs — that was load-bearing
   preservation, not tidiness.

2. Understated the cold-start finding. It was labelled "arithmetic inference,
   not measurement". The attempt COUNT is in fact provable: cumulative phase
   time is 17.47s, so every attempt ran under 60s, and at sub-60s a
   BillingError can take no early exit from the ladder (not capped; not a
   RateLimitError, so both the window and transient-backoff branches are
   skipped; duration < threshold) — leaving only the cold-start fall-through.
   The loop therefore runs attempts 0-2 and exhausts: exactly 3 agent spawns
   against an account with no credits. Only the per-attempt split (~5.8s each)
   is arithmetic; the doc now separates the two.

No test or behavior change; 201 tests still pass.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat: detect rate-limit failures mid-chain and halt cleanly instead of timeout-cascading

1 participant