Skip to content

fix(run): -Q quality loop retries after an "Out of credits" exec instead of failing fast (billing cascades into "unparseable verdict") #799

Closed

Description

@admarble

Summary

When sequant run … -Q (quality loop) hits an "Out of credits" / billing failure during a phase, the outer quality loop does not fail fast — it spawns /loop and retries the phase for the remaining iterations, none of which can succeed (there are no credits). The retries then surface as misleading QA completed without a parseable verdict errors, so a billing stop is reported to the user as a QA problem.

This was observed on a real chain run (sequant run 109 111 112 113 --chain -Q): #111 passed cleanly, then #112 failed like this:

✘ #112 exec Out of credits
▸ #112 loop
✔ #112 loop 2m 23s
▸ #112 exec (attempt 2/3)      ✔ 52s
▸ #112 qa (attempt 2/3)        ✘ QA completed without a parseable verdict
▸ #112 loop
✔ #112 loop 2m 12s
▸ #112 exec (attempt 3/3)      ✔ 1m 45s
▸ #112 qa (attempt 3/3)        ✘ QA completed without a parseable verdict
SUMMARY · #112 ✘ failed · QA completed without a parseable verdict

The run's actual halt cause was Out of credits on the very first exec; everything after it is wasted wall-clock and a mislabeled failure.

Root cause

src/lib/workflow/batch-executor.ts:1051:

if (useQualityLoop && iteration < maxIterations && !result.capped) {
  // spawn /loop, then continue to the next outer iteration

The outer quality loop only fails-fast on the #739 turn-cap case (!result.capped). It has no equivalent halt for a billing / window-exhausted-rate-limit failure, even though the signal is already present in scope: the failure branch at batch-executor.ts:1040 has result.structuredError, which is a BillingError for out-of-credits (see error-classifier.ts:53-58, errorTypeToCategory → "billing"). deriveFailureCategory(phaseResults) (batch-executor.ts:440) already computes exactly this category elsewhere in the file.

Why #761/#732 didn't cover this: #732 surfaced the structured billing/credits signal from the driver, and #761 added billing/rate-limit skips inside a single phase's retry ladder (phase-executor.ts:~923 "the billing skip (#732)") plus the MCP-fallback gate. But the outer -Q quality loop in batch-executor.ts was never taught to consult that signal — so a billing failure that halts the inner retries still triggers an outer /loop + phase re-run.

Expected behavior

A billing / out-of-credits failure (and a window-exhausted rate limit, i.e. isWindowExhaustedRateLimit) should halt the outer quality loop immediately — the same "surface + halt, user resumes" treatment the turn-cap path (#739) already gets — and the run summary / phase-failed line should state the real cause (Out of credits / rate-limited, with resetsAt when present) instead of cascading into QA completed without a parseable verdict.

Acceptance Criteria

  • AC-1 In batch-executor.ts, when a phase fails with a billing structured error (result.structuredError instanceof BillingError, or deriveFailureCategory = "billing"), the outer quality loop halts immediately — no /loop spawn, no further iterations — mirroring the existing haltedByCap (feat(orchestrator): preserve partial output for turn-capped phases in phase-executor #739) pattern (e.g. a haltedByBilling flag / shared "halt, don't loop" predicate).
  • AC-2 Same fail-fast for a window-exhausted rate limit (reuse isWindowExhaustedRateLimit from phase-executor.ts) so a closed-window throttle doesn't burn iterations either. A metadata-absent / transient rate limit keeps today's behavior.
  • AC-3 The phase-failed event and run summary state the real cause (Out of credits / rate-limited + resetsAt when available) rather than a downstream QA completed without a parseable verdict. The failureCategory recorded in metrics is billing/rate_limit accordingly (already wired via deriveFailureCategory).
  • AC-4 The issue's state ends resumable (not a spurious hard AC_NOT_MET), so re-running the same command resumes the link once credits/window are restored — consistent with the feat: resume a partially-completed chain from its last good link #760 resume contract.
  • AC-5 Regression test: a mocked exec phase returning a BillingError under -Q halts after the first attempt (assert: no second exec/loop attempt, halt reason names billing). Add the rate-limit-window variant.

Notes

Activity

  1. admarble commented on Jul 24, 2026

    @admarble
    ContributorAuthor

    Plan Complete — #799

    Complexity: Standard (5 ACs, 1 primary directory: src/lib/workflow/)

    AC Checklist

    • AC-1: Billing structured error (BillingError / deriveFailureCategory === "billing") halts the outer -Q quality loop immediately — no /loop spawn, no further iterations — mirroring haltedByCap (feat(orchestrator): preserve partial output for turn-capped phases in phase-executor #739).
    • AC-2: Same fail-fast for a window-exhausted rate limit (reuse isWindowExhaustedRateLimit). Metadata-absent/transient rate limit keeps today's behavior.
    • AC-3: Phase-failed event + run summary state the real cause (Out of credits / rate-limited + resetsAt), not a downstream QA completed without a parseable verdict. failureCategory = billing/rate_limit (already via deriveFailureCategory).
    • AC-4: Issue ends resumable (not spurious hard AC_NOT_MET); re-run resumes the link once credits/window restored (feat: resume a partially-completed chain from its last good link #760 contract).
    • AC-5: Regression test — mocked exec BillingError under -Q halts after first attempt (no 2nd exec/loop; halt reason names billing). Add rate-limit-window variant.

    Implementation Plan

    File: src/lib/workflow/batch-executor.ts (mirror the haltedByCap #739 machinery)

    1. Imports: add BillingError from ../errors.js and isWindowExhaustedRateLimit from ./phase-executor.js.
    2. Halt predicate: add a small helper isHaltNotLoopFailure(result) (billing OR window-exhausted rate limit) or a haltedByBilling flag declared next to haltedByCap (line ~843).
    3. Failure branch (~1040): when the predicate matches, set haltedByBilling = true (alongside if (result.capped) haltedByCap = true).
    4. Loop-spawn guard (~1051): extend !result.capped → also && !haltedByBilling so no /loop spawns.
    5. Break guard (~1155): if (haltedByCap || haltedByBilling) break;.
    6. Failed-event message (~936): for billing/rate-limit, surface result.error ?? "Out of credits" (append resetsAt for rate limit) instead of the generic reason. deriveFailureCategory already yields the correct metrics category — no metrics change needed.
    7. State (AC-4): non-success already writes in_progress finalStatus (resumable); halting before /loop avoids the spurious AC_NOT_MET verdict. No extra state flag required.

    Design Review

    1. Where: the outer quality-loop retry in batch-executor.ts — the one place feat(orchestrator): preserve partial output for turn-capped phases in phase-executor #739's cap-halt lives and where the feat(driver): surface structured rate-limit/credits errors from SDK message stream (replaces #592 fallback noise) #732 billing signal was never consulted.
    2. Simplest correct: reuse existing structured signals (structuredError, isWindowExhaustedRateLimit); no new classification. Mirror haltedByCap exactly rather than inventing a new halt mechanism.
    3. Pattern: feat(orchestrator): preserve partial output for turn-capped phases in phase-executor #739 "surface + halt, user resumes."
    4. Senior challenge: "why not skip inside phase-executor?" — feat: detect rate-limit failures mid-chain and halt cleanly instead of timeout-cascading #761 already fail-fasts the inner retry ladder; this closes the outer -Q loop gap those left open.

    Verification

    • AC-1/2/5: Unit test (mock exec returning BillingError / window-exhausted RateLimitError under -Q).
    • AC-3/4: Assert emitted failed-event message + final state/failureCategory in the same test.

    Recommended Workflow

    Phases: exec → qa (no test — backend/CLI, no UI labels). Quality Loop: enabled.

  2. admarble commented on Jul 24, 2026

    @admarble
    ContributorAuthor

    /fullsolve Complete — #799

    Status: READY_FOR_MERGE

    Summary

    The outer -Q quality loop now fails fast on a billing / out-of-credits failure or a window-exhausted rate limit — mirroring the #739 turn-cap halt — instead of spawning /loop for doomed retries that mislabeled the cause as QA completed without a parseable verdict.

    AC Coverage — 5/5 MET

    • AC-1: Billing halts the outer loop before /loop.
    • AC-2: Window-exhausted rate limit halts too; transient/metadata-absent unchanged.
    • AC-3: Failed event + summary state the real cause + resetsAt; failureCategory = billing/rate_limit.
    • AC-4: Ends resumable (in_progress, no spurious AC_NOT_MET).
    • AC-5: Regression tests added (billing, rate-limit-window, transient fallback).

    Quality

    • Tests: batch-executor.test.ts 55 ✓ (4 new), phase-executor.test.ts 138 ✓
    • tsc --noEmit, eslint, npm run build: clean

    Iterations

    • Exec: 1 (1 mock-mismatch fix — partial-mock phase-executor.js)
    • QA: 1 (inline adversarial review; data-flow traced source→summary)

    PR: #800

  3. added a commit that references this issue on Jul 24, 2026
  4. admarble commented on Jul 24, 2026

    @admarble
    ContributorAuthor

    QA second-look — one real gap fixed

    Adversarial re-read after the first PASS found a defect the structured pass missed:

    billingHaltReason doubled the reset time. For a window-exhausted rate limit, the driver already formats the reset time into result.error ("Rate limited — resets at 07-24 14:32", local time, via formatRateLimitMessage). The helper then re-appended a second, timezone-inconsistent copy from structuredError.metadata (" — resets at 2026-…Z"). The first test only matched /resets at/i, so it passed despite the duplication.

    Fixed in 9005620: surface result.error verbatim (already the canonical "cause + reset time"); dropped the redundant resetsAtToMs append. Regression tests tightened to assert the exact message + exactly one resets at, and AC-4 now asserts the real state write (in_progress, never ready_for_merge).

    Noted non-gap (no fix): the early spec-phase block handles capped as a #739 sibling but not billing. It's outside the outer -Q quality loop and can't cascade (no /loop retry there), so it's out of AC scope — a spec-phase "Out of credits" already surfaces result.error correctly. Flagging for visibility only.

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

    @admarble
    ContributorAuthor

    All gaps closed

    Following the QA second-look, every identified gap is now fixed (PR #800, all CI green):

    1. Doubled reset time (real bug) — billingHaltReason re-appended a reset time the driver already formats into result.error. Now surfaces result.error verbatim; test asserts the exact message + exactly one resets at.
    2. Thin AC-4 test — now drives a spy StateManager and asserts final status in_progress, never ready_for_merge.
    3. Spec-phase sibling symmetry — the early spec block now routes billing/window failures through billingHaltReason (mirroring the feat(orchestrator): preserve partial output for turn-capped phases in phase-executor #739 capped message it already had). Behavior was already correct (early-returns, no cascade); this is message/fallback symmetry + a spec-phase billing regression test.
    4. Doc accuracy — docs/reference/run-command.md described the rate-limit fail-fast as skipping "all phase retries" (true for the inner feat: detect rate-limit failures mid-chain and halt cleanly instead of timeout-cascading #761 ladder, not the outer -Q loop pre-fix). Now notes billing explicitly and that the -Q loop honors the halt.

    Final: 194 tests pass · tsc/eslint/build clean · 5/5 CI checks SUCCESS.

  7. added a commit that references this issue on Jul 24, 2026
  8. added 3 commits that reference this issue on Jul 25, 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

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions