Repository navigation
fix(#761): classify rate limits mid-phase — skip doomed retries, label the chain halt - #781
Merged
admarble merged 3 commits intoJul 17, 2026
Conversation
…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
deleted the
feature/761-feat-detect-rate-limit-failures-mid-chain-and-
branch
July 17, 2026 14:39
This was referenced Jul 18, 2026
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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.
rateLimitInfoand returned a bareTimeout after Ns. It now attachesstructuredErrorviabuildStructuredError, matching the sibling catch path. Only failure-grade signals are ever captured, so a genuine timeout is never mislabeled (regression-guarded).resetsAtlies beyondRATE_LIMIT_WINDOW_SKIP_THRESHOLD_MS(5 min) skips all cold-start retries via acapped-style early return. Metadata-absent rate limits fall back to transient handling — the mandatory AC-9 fallback (therate_limit_eventis documented subscription-only; the assistant-error channel carries no metadata).!failureIsRateLimitedalongside!failureIsBilling && !failureIsCapped.delayFnwith exponential backoff (5s → 10s) instead of a barecontinue.displaySummaryrestates a rate-limited chain halt usingformatRateLimitMessage(withresetsAtwhen present) and spells out that resume is re-running the identical command. ExtractedbuildRateLimitHaltNoticefor standalone testability (the feat: resume a partially-completed chain from its last good link #760planChainResumeFromStatetreatment).batch-executorerrorContext (both sites) prefersresult.structuredErroroverclassifyError;rate_limit/billingadded toERROR_CATEGORIES,errorTypeToCategory, and the run-log category enum..sequant/metrics.jsonrecords an optional bounded-enumfailureCategory, threadedPhaseResult.structuredError→IssueResult.failureCategory→recordRun. Enum only — a free-text category fails schema validation (test-pinned). Additive, no version bump.phase-executor.test.ts:722transient-retry pin, and theclaude-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.errorFromAssistantErrormap now records the originating variant sorate_limit/overloadedno longer collapse into one shape. Remaining follow-up: confirm against a real captured window rejection when one occurs.AC Verification
drivers/claude-code.tsabort branch; tests: "classifies a hang after a rejected rate_limit_event…", billing variant, bare-timeout regression guardisWindowExhaustedRateLimit+ early return inexecutePhaseWithRetry; tests incl. cold-start-window + seconds-unitresetsAtfailureIsRateLimitedat the MCP gate; test "does not trigger the MCP fallback for a rate-limited failure"delayFn-based backoff,RATE_LIMIT_RETRY_BACKOFF_MS * 2 ** attempt; tests assert exact delaysbuildRateLimitHaltNotice+ summary print inrun-display.ts; 6 tests incl. #766 reverse-scan semanticsbatch-executor.tsboth errorContext sites; enum additions inerror-classifier.ts+run-log-schema.tsmetrics-schema.tsFailureCategorySchema; threading viaderiveFailureCategory; privacy pinned by "rejects a free-text failureCategory" test.sequant/logs/)Test plan
npm run build— cleannpm run lint— clean (0 warnings)npm test— 3999 passed, 1 expected fail (pre-existing), 2 skippedrateLimitType/resetsAtpopulated and the window-exhaustion skip fires as designedCloses #761
🤖 Generated with Claude Code