Skip to content

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

Closed

Description

@admarble

⚠️ STATUS: ACs rewritten — read the clarification comment before implementing

The Acceptance Criteria below have been replaced (see § at the bottom). Corrections to the Context/Proposal sections, which are otherwise left as filed:

  • The forensic logs are gone. No f317530c / 058048af run log survives in .sequant/logs/. The original AC-1/AC-5 mandated validating signatures against them and were unsatisfiable. The log-scraping method is dropped entirely.
  • feat(driver): surface structured rate-limit/credits errors from SDK message stream (replaces #592 fallback noise) #732 superseded the method. Structured SDK rate-limit signals (RateLimitError / RateLimitMetadata) already exist; regex-scraping logs would re-introduce what feat(driver): surface structured rate-limit/credits errors from SDK message stream (replaces #592 fallback noise) #732 removed.
  • "Nothing classifies rate-limit signatures in the chain loop" — half true. Classification exists in the phase executor; what's missing is that the abort path discards it (drivers/claude-code.ts:287-294). That is the root cause.
  • The chain does NOT cascade across links — it already halts at the first failure (run-orchestrator.ts:1337-1345). The ~30+ min burn is real but happens inside a single phase via a retry ladder of up to 4 × 1800s.
  • Retry-with-backoff does NOT already exist. The retryable branch is a bare continue with no delay. Bounded retry ≠ backoff.

Retitle suggested: this is not "halt the chain" — the chain already halts. It is "stop burning ~2 hours of doomed retries inside one phase, and say why it stopped."

Context

2 of the 5 recorded chain failures in the #604 forensics were Claude Code 5-hour rate-limit hits mid-run (f317530c 2026-03-23, 058048af 2026-03-25). In both, the limit manifested as 1800s phase timeouts that cascaded — burning ~30+ minutes per timed-out phase before the chain died, with no indication that the root cause was a rate limit rather than a real failure. Chain mode is structurally the most exposed surface: wall clock scales with length (avg 78.9 min, observed up to 228 min), so a 4-issue chain has ~4× the rate-limit window of a single run. #452 (PR #455) added retry-with-backoff for transient spec-phase failures, but nothing classifies rate-limit signatures in the chain loop.

Proposal

Blocking for a 5-hour window is impractical, so the goal is fail fast and fail labeled, not wait-and-retry:

  • Detect the rate-limit signature in phase output/exit (the specific patterns should be pulled from the two forensic run logs in .sequant/logs/).
  • On detection mid-chain: skip the remaining 1800s timeout ladder, halt the chain immediately, and report "rate limited — chain halted after #N; resume when the window resets" with the exact resume command.
  • Short exponential backoff (à la Improve multi-issue reliability: default to parallel worktrees and add spec retry logic #452) is appropriate only for transient blips, not window exhaustion — classify the two cases rather than retrying blindly.

Pairs with #760: a labeled rate-limit halt plus chain resume turns this failure class from fatal into a pause.

Acceptance Criteria

Rewritten. Rationale + evidence in the clarification comment. The original log-signature ACs are dropped (logs gone; #732 supersedes the method). Ordered by dependency — AC-1 is load-bearing.

  • AC-1: The abort/timeout path at drivers/claude-code.ts:287-294 attaches structuredError via buildStructuredError(rateLimitInfo, assistantError, apiRetryError), matching the sibling catch path at :302. A rate limit that manifests as a hang must stay classifiable downstream. Without this, every AC below is unreachable.
  • AC-2: A rate limit whose resetsAt is beyond a short threshold does not consume cold-start retries. Model on the capped precedent (phase-executor.ts:906-908): explicit early return skipping all retries. A window resetting in hours cannot be retried into success.
  • AC-3: The MCP fallback gate (phase-executor.ts:972-978) additionally checks !failureIsRateLimited, alongside !failureIsBilling && !failureIsCapped. A throttle must not trigger "retrying without MCP".
  • AC-4: Transient rate-limit retries get real backoff — reuse the injected delayFn (phase-executor.ts:825) rather than inventing a mechanism. This does not exist today; the current branch is a bare continue. Bounded retry alone is not the AC.
  • AC-5: On chain halt, the run summary prints the resume affordance. Implement in run-display.ts:119 displaySummary, not at the orchestrator break — that is where feat: resume a partially-completed chain from its last good link #760 already restates checkpoint failures for the same reason ("the per-issue warning has long scrolled past by now on a multi-hour chain", run-display.ts:149-151), and RunResult there carries mergedOptions. Note: feat: resume a partially-completed chain from its last good link #760 added no resume flag — resume is re-running the identical command. The output must say so explicitly, or it reads as a bug. Use formatRateLimitMessage (errors.ts:313); include resetsAt when present.
  • AC-6: structuredError is threaded into batch-executor.ts:942 and :623 in preference to classifyError, and rate_limit / billing are added to ERROR_CATEGORIES (error-classifier.ts:19-27) and errorTypeToCategory (:34-49). Prerequisite for AC-7.
  • AC-7: .sequant/metrics.json records a bounded-enum failureCategory on MetricRunSchema, threaded from PhaseResult.structuredError → IssueResult → recordRun (run-orchestrator.ts:1545). Enum only — no message strings (privacy contract, metrics-schema.ts:69-77).
  • AC-8: Tests. phase-executor.test.ts:722 — "still retries a transient rate-limit failure (RateLimitError is retryable)" — pins the behavior AC-2 changes and must be inverted. Copy the shape of the BillingError non-retryable + MCP-skip tests at :651-692. Add an abort-path test asserting AC-1 (a hang carrying rateLimitInfo yields a classified failure, not a bare timeout).
  • AC-9: Before implementing AC-2's branch on rateLimitType, validate against a real captured rejection that window exhaustion actually arrives with rateLimitType populated. [UNRESOLVED] whether the SDK can emit a window rejection as assistant.error: "rate_limit" without a paired rate_limit_event — if it can, window detection degrades to indistinguishable, AC-2 needs a fallback rule, and the metadata-dropping map at claude-code.ts:363-376 needs fixing too. Validate against a real capture, not a mocked event.

Notes for the implementer

Out of scope

Scheduling runs around limit windows, token budgeting, resume itself (#760).

References

Activity

  1. added
    enhancement
    cli
    on Jul 14, 2026
  2. admarble commented on Jul 15, 2026

    @admarble
    ContributorAuthor

    Assessment

    → CLARIFY — Two independent problems: the mandated evidence is gone, and the proposed approach has been superseded.

    1. The cited forensic logs no longer exist

    AC-1 requires signatures "validated against the f317530c and 058048af run logs" and AC-5 requires unit tests using "verbatim log samples from the two forensic runs". Neither log is present:

    • 93 files in .sequant/logs/; no filename contains either run id.
    • A content grep across every run log finds neither id.
    • The only surviving trace is the summary table in docs/reference/chain-mode-analysis-2026-05.md:66-67 — two rows of prose, no raw output.

    As written, both ACs are unsatisfiable. Per the motivating-example rule this issue itself invokes, synthetic fixtures are not an acceptable substitute here — so this needs a real decision: locate the logs, or re-base the ACs on a different real corpus.

    2. The premise is stale — #732 shipped structured signals

    The Context says "nothing classifies rate-limit signatures in the chain loop", and the Proposal says patterns "should be pulled from the two forensic run logs". Since filing, #732 (closed) landed exactly the better version of this:

    • src/lib/workflow/drivers/claude-code.ts — createRateLimitError / RateLimitError built from the SDK's structured rate_limit_event and assistant.error signals.
    • src/lib/workflow/phase-executor.ts:915 — already prefers the driver's structuredError over stderr-regex classification, with the in-code comment that regex "only sees text and never the structured data."

    Log-scraped regex signatures would re-introduce precisely what #732 removed.

    AC-3 also already exists — bounded retry-with-backoff for transient errors is implemented at phase-executor.ts:912-925 (isRetryable + COLD_START_MAX_RETRIES).

    What's genuinely still unbuilt

    The chain-level behavior: halt the chain on a window-exhaustion classification without waiting out the 1800s timeout ladder, print the resume command (now that #760 has shipped resume), and record the failure category in .sequant/metrics.json (no failureCategory field exists today).

    Recommendation: rewrite the ACs around #732's structured RateLimitError — distinguishing window-exhaustion from transient — and drop the log-signature framing entirely. The valuable core survives; its stated method doesn't.

  3. admarble commented on Jul 15, 2026

    @admarble
    ContributorAuthor

    Clarification: premise verified, root cause found, ACs rewritten

    Fanned out two agents against the code and verified every load-bearing claim by hand. Result: the issue's core instinct is right, the assessment's correction to it was partly wrong, and the actual root cause is one line-range nobody had named.

    Labelling as in the earlier research comment: [VERIFIED] = reproduced against this checkout. [UNRESOLVED] = flagged, not guessed.


    1. The title premise holds — the cascade is real, but it's within one phase

    I initially concluded the opposite and was wrong. Correcting it explicitly, because the correction is the finding.

    The chain does already halt at the first failed link — run-orchestrator.ts:1337-1345 is an unconditional break, and the phase loop breaks at batch-executor.ts:1089-1090. So there is no march through remaining issues. That part of the Context is inaccurate.

    But "1800s phase timeouts that cascaded — burning ~30+ minutes per timed-out phase" is [VERIFIED] accurate — it just happens inside a single phase, via the retry ladder, before the break ever fires:

    • COLD_START_MAX_RETRIES = 2 (phase-executor.ts:56) → up to 3 attempts, and RateLimitError is explicitly allowed to consume them because it is constructed isRetryable: true (errors.ts:215).
    • The MCP fallback (phase-executor.ts:972-978) adds a fourth. Its gate is !failureIsBilling && !failureIsCapped — rate-limiting is not on that skip list, so a throttle still triggers the "retrying without MCP" re-spawn.

    Each attempt can hang to the full phaseTimeout (default 1800s, types.ts:188). Worst case ≈ 4 × 1800s ≈ 2 hours on one phase. (Reasoned from the ladder, not measured — flagging as such.)

    2. Root cause: the abort path drops the structured error

    This is the bug, and it is one line-range — drivers/claude-code.ts:287-294:

    if (error.includes("abort") || error.includes("AbortError")) {
      return {
        success: false,
        output: capturedOutput,
        error: `Timeout after ${config.phaseTimeout}s`,
        stderrTail: stderrBuffer.getLines(),
        stdoutTail: stdoutBuffer.getLines(),
      };
    }

    No structuredError. The sibling catch path at :302-318 does call buildStructuredError. The comment above it states the intent — "Abort/timeout is handled above first, so a genuine timeout is never masked by a stale rate-limit signal" — and that intent is sound, but the consequence runs the other way:

    • Rate limit arrives as a stream event → catch path → classified promptly. Fine today.
    • Rate limit manifests as a hang → abort fires → bare Timeout after 1800s, rateLimitInfo already captured at :152-157 is discarded → phase-executor.ts:918 falls back to classifyError(stderrTail), which sees no rate-limit text → SubprocessError → MCP fallback fires anyway.

    That second path is the forensic signature this issue was filed about. The missing logs would have shown exactly this.

    3. Correction to the assessment: AC-3 does not already exist

    The assessment states bounded retry-with-backoff is implemented at phase-executor.ts:912-925. [VERIFIED] false. The retryable branch ends in a bare continue — no delay:

    if (typedError.isRetryable && attempt < COLD_START_MAX_RETRIES) {
      ...
      continue;
    }

    The only delayFn (:825-826) is wired solely to the spec-extra retry at :1035 (SPEC_RETRY_BACKOFF_MS, 5000ms, phase === "spec" only). Retry is bounded; backoff does not exist on this path. A rate-limited phase re-spawns immediately, twice, into the same closed window. This is the sharpest finding here and the one AC that should not have been dropped as redundant.

    4. What #732 actually gives us

    Confirmed shipped (PR #735 / 27f8106, plus 0af8872, 1dc6e15; SDK 0.3.205 installed). Typed errors live in src/lib/errors.ts, not the driver: RateLimitError:207 (isRetryable: true), BillingError:227, RateLimitMetadata:186-200 carrying resetsAt / rateLimitType / errorCode.

    Window-vs-transient is only partially distinguishable, and it depends on which signal arrives:

    • Via rate_limit_event: yes. SDK exposes rateLimitType: 'five_hour' | 'seven_day' | ... | 'overage' and resetsAt (sdk.d.ts:4089-4105), copied verbatim into metadata at errors.ts:340. (There is no retryAfter; resetsAt is the only timing signal.)
    • Via assistant-level error: no. claude-code.ts:363-376 maps to new RateLimitError("Rate limited") with no metadata argument — rateLimitType and resetsAt are both undefined, and rate_limit vs overloaded collapse into the same shape.
    • Either way, nothing branches on it. Every RateLimitError is isRetryable: true.

    [UNRESOLVED] Whether the SDK ever emits a genuine window rejection as assistant.error: "rate_limit" without a paired rate_limit_event. If it does, window detection silently degrades to indistinguishable. Not verified against a real capture, and the existing tests don't settle it. Any AC written around rateLimitType must be validated against a real capture, not a mocked rate_limit_event — which is the same evidence discipline the original ACs were reaching for.

    5. Two more gaps

    structuredError never leaves phase-executor. Grep across src/ hits only errors.ts, types.ts:220, agent-driver.ts:87, claude-code.ts, phase-executor.ts. Zero references in batch-executor.ts or run-orchestrator.ts. So the run-log errorContext is built at batch-executor.ts:942 from classifyError(result.stderrTail, result.exitCode) — the very stderr-regex path #732 was meant to supersede — while the structured error sits ignored on the same object. Same defect at :623. And errorTypeToCategory (error-classifier.ts:34-49) has no rate-limit/billing case → default: "unknown".

    No failureCategory in metrics. MetricRunSchema (metrics-schema.ts:78-97) has outcome: success | partial | failed and no classification. An optional field does not force the version: z.literal(1) bump. Note the schema's stated privacy contract (:69-77) is "No error messages (could contain sensitive info)" — a bounded enum category is consistent with that; a message string is not.


    Rewritten Acceptance Criteria

    Replaces the original list. The log-signature framing (original AC-1/AC-5) is dropped: the f317530c / 058048af logs are gone, and #732 supersedes regex-scraping with structured SDK signals. Ordered by dependency — AC-1 is load-bearing for everything else.

    • AC-1: The abort/timeout path at drivers/claude-code.ts:287-294 attaches structuredError via buildStructuredError(rateLimitInfo, assistantError, apiRetryError), matching the sibling catch path at :302. A rate limit that manifests as a hang must remain classifiable downstream. Without this, every AC below is unreachable.
    • AC-2: A rate limit whose resetsAt is beyond a short threshold does not consume cold-start retries. Model it on the capped precedent (phase-executor.ts:906-908): an explicit early return skipping all retries. A window resetting in hours cannot be retried into success.
    • AC-3: The MCP fallback gate (phase-executor.ts:972-978) additionally checks !failureIsRateLimited, alongside the existing !failureIsBilling && !failureIsCapped. A throttle must not trigger "retrying without MCP".
    • AC-4: Transient rate-limit retries get real backoff — reuse the injected delayFn (phase-executor.ts:825) rather than inventing a mechanism. This does not exist today; the current branch is a bare continue. Bounded retry alone is not the AC.
    • AC-5: On chain halt, the run summary prints the resume affordance. Implement in run-display.ts:119 displaySummary, not at the orchestrator break — that is where feat: resume a partially-completed chain from its last good link #760 already restates checkpoint failures for the same reason ("the per-issue warning has long scrolled past by now on a multi-hour chain", run-display.ts:149-151), and RunResult there carries mergedOptions. Note: feat: resume a partially-completed chain from its last good link #760 added no resume flag — resume is re-running the identical command. The output must say so explicitly (e.g. "re-run the same command to resume from fix: /qa skill should handle 'no implementation' case gracefully #102"), or it reads as a bug. Use formatRateLimitMessage (errors.ts:313) for the label; include resetsAt when present.
    • AC-6: structuredError is threaded into batch-executor.ts:942 and :623 in preference to classifyError, and rate_limit / billing are added to ERROR_CATEGORIES (error-classifier.ts:19-27) and errorTypeToCategory (:34-49). Prerequisite for AC-7.
    • AC-7: .sequant/metrics.json records a bounded-enum failureCategory on MetricRunSchema, threaded from PhaseResult.structuredError → IssueResult → recordRun (run-orchestrator.ts:1545). Enum only — no message strings (privacy contract, metrics-schema.ts:69-77).
    • AC-8: Tests. phase-executor.test.ts:722 — "still retries a transient rate-limit failure (RateLimitError is retryable)" — pins the behavior AC-2 changes and must be inverted. Copy the shape of the BillingError non-retryable + MCP-skip tests at :651-692. Add an abort-path test asserting AC-1 (a hang carrying rateLimitInfo yields a classified failure, not a bare timeout).
    • AC-9: Before implementing AC-2's branch on rateLimitType, validate against a real captured rejection that window exhaustion actually arrives with rateLimitType populated (see §4 [UNRESOLVED]). If it can arrive bare via assistant.error, AC-2 needs a fallback rule and the metadata-dropping map at claude-code.ts:363-376 needs fixing too.

    Notes for the implementer

    Investigation: 2 agents + hand-verification of every quoted line. The assessment's "AC-3 already exists" and my own initial "the timeout isn't waited out" were both wrong — both came from trusting a code comment that described intent rather than effect.

  4. admarble commented on Jul 16, 2026

    @admarble
    ContributorAuthor

    Re-assessment: CLARIFY → PROCEED

    Supersedes my earlier CLARIFY. The rewritten ACs resolve both objections I raised — and correct a claim of mine that was simply wrong.

    My "AC-3 already exists" was wrong — verified

    I asserted bounded retry-with-backoff was implemented at phase-executor.ts:912-925. Re-read the code rather than the comment above it:

    • The retryable branch ends in a bare continue — no delay of any kind.
    • delayFn (:825) is referenced exactly once, at :1035, for the spec-extra retry (SPEC_RETRY_BACKOFF_MS, phase === "spec" only).

    Retry is bounded; backoff does not exist on this path. The clarification's correction stands, and AC-4 is real work.

    The tell is worth recording: I reasoned from the #732 comment at :915 ("Prefer the driver's structured cause… over stderr-regex classification") and inferred the structured path was wired through. It isn't. grep -rn structuredError src --include="*.ts" returns zero hits in batch-executor.ts and run-orchestrator.ts — the field stops at phase-executor. batch-executor.ts:942 still builds errorContext from classifyError(result.stderrTail, ...), the exact stderr-regex path #732 was meant to supersede, with the structured error sitting unused on the same object.

    So "#732 supersedes this issue" was wrong in the way that matters: #732 shipped the types, nothing branches on them. The premise held; I talked myself out of it from a comment. Also confirmed: the abort path at drivers/claude-code.ts:287-294 returns without structuredError while its sibling at :302 attaches it — AC-1's root cause, verified.

    Assessment

    Workflow: exec → qa with quality loop

    npx sequant run 761 -Q --phases exec,qa
    

    Spec is skipped deliberately — the rewritten ACs are already a spec, down to the test to invert (phase-executor.test.ts:722).

    Order: after #766, before #767. Real file overlap, from ACs naming line ranges: batch-executor.ts (this issue's AC-6 at :942/:623; #766 at :1055; #767 at :199) and run-orchestrator.ts (AC-7 at :1545; #766 at :416).

    ⚠ AC-9 gates AC-2 and is unresolved inside the issue — whether window exhaustion can arrive as a bare assistant.error without a paired rate_limit_event. If it can, AC-2 needs a fallback rule and the metadata-dropping map at claude-code.ts:363-376 needs fixing too. Resolve it before building AC-2's rateLimitType branch, and validate against a real capture rather than a mocked rate_limit_event.

    ⚠ Possible cross-link with #766, flagged as hypothesis not finding. #766's undiagnosed loose end — #762 displaying Timeout after 1800s when its last failure was an API drop — sits on the same abort path this issue's AC-1 rewrites, which returns exactly that bare string. I could not confirm they are the same bug: API Error: Connection closed mid-response should not match the abort/AbortError branch, so it ought to have taken the catch path and surfaced the API error. Either way AC-1 changes that path's error field, so whoever implements it should look at #766's loose end while in there.

  5. added a commit that references this issue on Jul 16, 2026
  6. admarble commented on Jul 16, 2026

    @admarble
    ContributorAuthor

    Pre-run verification (2026-07-16, main @ dbfbfee)

    Re-verified every anchor in the rewritten ACs after the #766 (PR #772) and #767 (PR #774) merges. All substantive claims hold; the issue is runnable. Corrections and one resolved gate below.

    AC-9 is no longer a hard gate on AC-2 — resolved by the SDK typings

    The unresolved question was whether window exhaustion can arrive as a bare assistant.error: "rate_limit" without a paired rate_limit_event. Three findings settle the design consequence without a live capture:

    1. SDKRateLimitInfo is documented subscription-only — the doc comment on the type (sdk.d.ts:4086-4088, SDK 0.3.205) reads "Rate limit information for claude.ai subscription users." API-key/console auth plausibly never receives the event at all; its rate limits would arrive only on the assistant-error channel (SDKAssistantMessageError at sdk.d.ts:2822, which carries no metadata).
    2. Even when the event fires, resetsAt and rateLimitType are both optional (sdk.d.ts:4091-4092). A status: 'rejected' event with no rateLimitType is legal per the contract.
    3. Emission cannot be verified statically — sdk.mjs contains zero references to rate_limit_event; the event is produced inside the closed CLI binary and merely typed by the SDK.

    Consequence: AC-2's metadata-absent fallback rule is mandatory unconditionally, not contingent on AC-9's answer. Write AC-2 with the fallback from the start (e.g. metadata present + resetsAt beyond threshold → skip retries; metadata absent → treat as transient, AC-4's backoff path). The claude-code.ts:363-376 metadata-dropping map fix is likewise unconditionally warranted. AC-9 downgrades to: capture a real rejection when one occurs and confirm the fallback fires as designed — validation, not a design gate.

    Also checked: no real captured rejection exists in .sequant/logs/ (97 files; the only "rate_limit" hit is #732's own implementation run log — mentions of the feature, not a limit event). AC-9 as originally written ("validate against a real capture" before implementing) is unsatisfiable from existing artifacts.

    #766's loose end is falsified as evidence for AC-1 — but AC-1 stands on its own

    The assessment hypothesized #762's "Timeout after 1800s"-vs-API-drop discrepancy sat on the abort path AC-1 rewrites. It didn't — PR #772 diagnosed and fixed it as a display bug in run-display.ts:toIssueSummary (first-failure-wins scan over accumulated quality-loop attempts; now reverse-scans for the last non-loop failure). Drop that cross-link from AC-1's rationale. AC-1's root cause is independently re-verified today: the abort early-return in drivers/claude-code.ts (~:287-294) still returns bare Timeout after ${config.phaseTimeout}s with no structuredError, while the sibling catch path attaches it via buildStructuredError (:340-344).

    Anchor corrections (post-#772/#774 drift)

    • Two file paths in the ACs are wrong:
      • AC-7's metrics-schema.ts is at src/lib/workflow/metrics-schema.ts (ACs imply src/lib/). Lines :69-77 / :78-97 are exact; failureCategory confirmed absent.
      • AC-5's run-display.ts is at src/commands/run-display.ts. displaySummary is now :132 (not :119 — that's inside toIssueSummary now). The feat: resume a partially-completed chain from its last good link #760 checkpoint restatement is :161-180; mergedOptions is destructured at :136.
    • Line drift, same code: AC-6's batch-executor.ts sites are now :939 and :620; AC-7's recordRun is run-orchestrator.ts:1553; the MCP fallback gate is phase-executor.ts:~958-968 (failureIsBilling/failureIsCapped at :966-977).
    • Exact and unchanged: phase-executor.test.ts:722 test to invert (verbatim name confirmed; the BillingError-shape tests to copy are :648-720); retryable branch :920 still ends in a bare continue (:933), COLD_START_MAX_RETRIES = 2 (:56); errorFromAssistantError map :363-376 still drops metadata; ERROR_CATEGORIES (error-classifier.ts:19-26) and errorTypeToCategory (:34-49) still lack rate_limit/billing; RateLimitError:207 / BillingError:227 / RateLimitMetadata:186-200 / formatRateLimitMessage:313 all exact; planChainResumeFromState at chain-resume.ts:231 with chain-resume.integration.test.ts present.
    • The "after fix: recovered phase failure still reports failed — live card, summary, and log disagree #766, before fix: parseDependencies matches prose mentions and silently reorders runs #767" ordering is moot — both merged with zero collisions on this issue's territory.

    Run command from the assessment stands: sequant run 761 -Q --phases exec,qa (ACs are already spec-grade).

  7. added a commit that references this issue on Jul 16, 2026
  8. admarble commented on Jul 16, 2026

    @admarble
    ContributorAuthor

    QA Review for Issue #761

    Full /fullsolve pass (exec → qa) against the rewritten ACs (clarification comment) as amended by the pre-run verification (2026-07-16). PR: #781.

    AC Coverage

    AC Description Status Evidence
    AC-1 Abort/timeout path attaches structuredError via buildStructuredError, matching sibling catch path MET drivers/claude-code.ts abort branch now builds and attaches the structured error, preferring its message. Tests: rate-limited hang → RateLimitError with resetsAt intact; billing hang → BillingError; regression guards: signal-less abort and allowed_warning-then-abort both stay a bare Timeout after Ns. The old #732 pin ("does NOT mask a genuine timeout") was inverted as the ACs required.
    AC-2 Window-exhausted rate limit (resetsAt beyond threshold) does not consume cold-start retries MET isWindowExhaustedRateLimit + explicit early return modeled on the capped precedent, placed before the duration branch (rate-limit rejections fail fast and would otherwise be mistaken for cold-start failures). Threshold RATE_LIMIT_WINDOW_SKIP_THRESHOLD_MS = 5 min. Metadata-absent fallback → transient (mandatory per pre-run verification). Tests: genuine-duration, cold-start-window, seconds-unit resetsAt, exact boundary.
    AC-3 MCP fallback gate additionally checks !failureIsRateLimited MET Gate now !failureIsBilling && !failureIsCapped && !failureIsRateLimited. Test: transient rate limit exhausts all attempts → no mcp: false call ever made.
    AC-4 Transient rate-limit retries get real backoff via injected delayFn MET Replaces the bare continue: RATE_LIMIT_RETRY_BACKOFF_MS * 2 ** attempt (5s → 10s) awaited through the existing delayFn injection point. Tests assert the exact delay sequence.
    AC-5 Run summary prints the rate-limit halt + resume affordance, in displaySummary MET buildRateLimitHaltNotice extracted for standalone testability (the #760 planChainResumeFromState treatment), consumed by displaySummary after the #760 checkpoint restatement. Label via formatRateLimitMessage with resetsAt when present; output says explicitly "Re-run the same command to resume from #N (no flag needed; completed links are skipped)" — phrasing verified against computeChainResumePlan semantics. Uses the same #766 reverse non-loop scan as toIssueSummary so the label describes the LAST attempt.
    AC-6 structuredError threaded into batch-executor errorContext; rate_limit/billing categories added MET Both sites (spec-path and main-loop) now result.structuredError ?? classifyError(...). ERROR_CATEGORIES, errorTypeToCategory, and the duplicated inline enum in run-log-schema.ts all extended (the schema enum would otherwise reject the new categories at validation).
    AC-7 Bounded-enum failureCategory on MetricRunSchema, threaded PhaseResult → IssueResult → recordRun MET FailureCategorySchema = z.enum(ERROR_CATEGORIES); IssueResult.failureCategory set at both failure returns via deriveFailureCategory (reverse non-loop scan, structured-cause-first); recordRun takes the first categorized failed issue. Additive/optional — no version bump; pre-#761 records still parse (test-pinned). Privacy pinned by test: a free-text failureCategory fails schema validation. Security agent traced the full path — no message string can reach metrics.json.
    AC-8 Tests: invert the :722 pin, copy BillingError shapes, abort-path test MET Both old-behavior pins inverted (phase-executor.test.ts:722 and the driver abort-path pin the ACs didn't name but which guarded the same behavior). Added: window-exhaustion (both duration regimes), backoff sequence, MCP-skip, near-reset-still-transient, abort-path classification (transient + billing + two negative guards), halt-notice suite, deriveFailureCategory unit tests, metrics schema/writer tests, errorTypeToCategory mappings. Full suite: 3999 passed. CI: 5/5 green.
    AC-9 Validate rateLimitType population against a real capture MET (as amended) Per the pre-run verification, AC-9 was downgraded from design gate to post-hoc validation (no capture exists in .sequant/logs/; emission is inside the closed CLI binary). The design consequence shipped unconditionally: metadata-absent fallback rule (AC-2) + the errorFromAssistantError metadata-dropping map now records the originating variant so rate_limit/overloaded stay distinguishable. Follow-up: when a real window rejection occurs, confirm it arrives with rateLimitType/resetsAt populated and the exhaustion skip fires (noted in PR #781 test plan).

    Coverage: 9/9 ACs met (AC-9 per its amended definition).

    Quality Checks

    Check Status Notes
    Type safety ✅ Pass 0 any/as any in added lines
    Deleted tests ✅ Pass 0 deleted test files
    Scope/size ✅ Pass 20 files, +1020/−40 total; ~68% of added lines are tests; no out-of-scope files
    Security ✅ Pass 0 critical/warning/info; metrics privacy contract verified end-to-end
    Build / Lint / Tests ✅ Pass tsc clean, eslint 0 warnings, full suite 3999 passed / 1 pre-existing expected-fail / 2 skipped
    CI (PR #781) ✅ 5/5 pass build (22.x), node-floor-guard, typecheck, validate-plugin, validate-skills
    CLI smoke ✅ Pass npx tsx bin/cli.ts run --help exits 0 with changed modules on the import path
    Behavior-rule survival ✅ Clean Old-rule sites (bare continue, ungated MCP fallback, bare-timeout abort return) all replaced in-diff; detector "survivors" were historical CHANGELOG prose, not code
    CHANGELOG ✅ Present [Unreleased] → Fixed entry for #761
    Precheck ✅ Pass fixtures/sibling-grep/AC-literal-diff all pass; PR body covers every AC

    Adversarial Re-Read

    Findings: One genuine defect surfaced and fixed in-PR (20c38cb): the AC-5 halt notice derived its label from formatRateLimitMessage(err.metadata), which mislabels a metadata-less BillingError (assistant-error channel) as "Rate limited" — isBillingFailure({}) is false. Fixed to fall back to the typed error's own message when metadata carries no signal; regression test added. Also audited: data-flow of structuredError from driver → displaySummary (survives every hop, instanceof safe — single module instance); phase-log status for a classified rate-limited hang changes from "timeout" to "failure" with category: rate_limit (more truthful, intentional); the skipColdStartRetry (loop-phase) path needs no window check since it never retries, and the AC-3 gate covers its MCP exposure; batch-executor.test.ts's module mock was widened to passthrough real errorTypeToCategory (the old mock omitted it, which would have broken every failure-path test once deriveFailureCategory ran on failure returns).

    Status: Clean (after in-PR fix)

    Risk Assessment

    • Likely failure mode: the 5-minute window threshold is a judgment call — a limit resetting in 4 minutes is retried with 5s/10s backoff into a still-closed window (bounded: at most 2 extra attempts). Conversely, a spurious far-future resetsAt on a genuinely transient throttle would skip retries that might have succeeded; the failure is labeled and resumable either way.
    • Not tested: live SDK emission shape for window exhaustion (AC-9 follow-up — unverifiable statically); recordMetrics' 3-line failureCategory pick in run-orchestrator.ts has no direct orchestrator test (the derivation itself is unit-tested in batch-executor).
    • Sibling sites considered: AiderDriver has no structured rate-limit signal channel (SDK-specific) — no cross-file sibling; the run.ts subprocess stderr-regex path is feat(driver): surface structured rate-limit/credits errors from SDK message stream (replaces #592 fallback noise) #732's documented fallback, unchanged by design.
    • Sibling-line audit: the sibling catch path at claude-code.ts already attached structuredError (it was the model for AC-1); the two classifyError sites in batch-executor were both converted (AC-6 named both).

    Verdict: READY_FOR_MERGE

    All 9 ACs met (AC-9 as amended by the pre-run verification), CI 5/5 green, the one adversarial-re-read finding fixed and regression-tested in-PR, and quality checks clean across the board.


    /fullsolve Complete

    Issue: #761 · PR: #781 · Status: READY_FOR_MERGE

    Phase Iterations Status
    Spec 0 (skipped per assessment — ACs were spec-grade) —
    Exec 1/3 ✅ Complete
    Test skipped (cli label, no UI) —
    QA 1/2 ✅ Complete (1 in-PR fix from adversarial re-read)

    Ready for human review and merge. Post-merge follow-up: when a real window rejection is captured in the wild, validate the AC-9 emission-shape assumption (see PR test plan).

  9. added
    ready-for-review
    on Jul 16, 2026
  10. added 2 commits that reference this issue on Jul 17, 2026
  11. added 6 commits that reference this issue on Jul 19, 2026
  12. added 2 commits that reference this issue on Sep 9, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    clienhancementready-for-review

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions