Skip to content

bug(codex): usage-limit turn failures classified 'unknown' — quality loop re-runs into the same quota, --auto-wait can't engage #1087

Closed

Description

@admarble

Problem

CodexDriver wraps every turn.failed as a generic SequantError (src/lib/workflow/drivers/codex.ts:323), so quota exhaustion is indistinguishable from any other turn failure. #1060 gate run 2 hit the ChatGPT free-plan limit mid-exec:

codex turn failed: You've hit your usage limit. Upgrade to Plus to continue using Codex (…), or try again at Oct 16th, 2026 1:04 AM.

The run log recorded errorContext: {category: "unknown", errorType: "SequantError", isRetryable: false, errorMetadata: {code: "turn-failed"}}. The spec-requested quality loop then ran loop, which failed on the same message 4.7s later. --auto-wait (#804) and the #592 billing skip key off RateLimitError/BillingError, so neither can engage for a Codex phase either.

The Claude driver already maps these signals to typed errors (claude-code.ts, createRateLimitError); this is the Codex counterpart.

Signal available

  • The turn.failed message text (You've hit your usage limit, with a reset time).
  • The rollout JSONL's token_count.rate_limits carries used_percent, window_minutes, resets_at (reached 99% just before the failure in run 2). Whether the same object reaches the codex exec --json stream the driver parses is unverified — check before relying on it.

Acceptance criteria

  • AC-1: a turn.failed whose message is the usage-limit text yields structuredError of class BillingError when the reset is beyond the run's wait horizon, carrying the reset time in metadata
  • AC-2: a transient throttle (429-style) turn.failed yields RateLimitError (retryable)
  • AC-3: any other turn.failed still yields the generic SequantError with code turn-failed
  • AC-4: with the phase failing on a BillingError, the batch executor does not start a quality-loop iteration (fixture from run 2's message)
  • AC-5: fixtures use the verbatim run-2 message; AC-1 and AC-4 are mutation-verified per CLAUDE.md §Testing

Release-graph plan — guard-2026-09 (2026-09-20)

Graph: guard-2026-09 Tier: mechanical Wave: 3
May touch: src/lib/workflow/drivers/codex.ts (turn.failed mapping), src/lib/workflow/drivers/codex.test.ts, src/lib/workflow/drivers/__fixtures__/ (the run-2 message lands there under #1096 AC-3; reuse it), src/lib/workflow/batch-executor.test.ts (AC-4 case only), CHANGELOG.md

The npm run build && npm test AC is verified by the runner from a clean shell after the PR opens (PLAN I-1); the agent runs only the test files its ACs name. Mutation markers use failedTest starting with the test file path (I-4). #1096 AC-3 is the failing test for AC-1/AC-2; this issue makes it pass. OQ-3 (does codex exec --json carry rate_limits?) is answered in the PR body; the message-text mapping does not depend on it.

Related

#1060 (run 2 record) · #497 · #804 · #592 · #799

Activity

  1. added
    bug
    on Sep 18, 2026
  2. admarble commented on Sep 20, 2026

    @admarble
    ContributorAuthor

    Runner context — guard-2026-09 wave 2 launch, 2026-09-20. Base: origin/main at bef0ac98 (all seven wave-1 PRs merged: #1086 scrub, #1104 marker docs, #1053, #1106 ownership gate, #1095 parsers, #1096 conformance suite, #1070 failing verdicts post). These rules override the exec AND qa skills' defaults for this run:

    • No full npm test in the worktree — this applies to the qa phase too. Under concurrent phase agents that one call exceeds the 30-minute no-progress wall and the phase is killed (three wave-1 phases died this way). Verify each AC by its own command; run only the test files the ACs name. The runner runs the full suite once per PR from a clean shell and records it on the PR.
    • A named test file red before your change: the suite is now hermetic (bug(test): suite isn't hermetic against the SEQUANT_* env phases inject — exec sees red tests it didn't cause and opens no PR #1086), so a red file is real. Name the issue number and the base-vs-head result in the PR body.
    • Mutation marker (gate-test ACs): <!-- SEQUANT_MUTATION: {"ac":"AC-N","mutation":"<what you deleted>","failedTest":"<test file path> > <describe> > <case>"} --> in the PR body. failedTest MUST start with the test file path. Run parseMutationMarkers on your body before opening the PR. Commit before mutating.
    • 30-minute no-progress wall per phase. Commit a WIP checkpoint before any long command; every command foreground, with timeout.
    • Commits: single-line git commit -m "...", no Co-Authored-By. Push the branch and open the PR yourself (one wave-1 exec forgot). Never rebase or force-push after pushing. One AC per line in the PR body, ids AC-N only.
    • Stop at the PR. Do not merge.

    Issue-specific: Pulled forward from wave 3: #1096 is merged. Its conformance suite marks the codex usage-limit and throttle cases it.fails — flip them to it in src/lib/workflow/drivers/__tests__/driver-conformance.test.ts (that file is in scope for that one change) and record the AC-1 mutation against it; reuse the fixtures in drivers/__fixtures__/ (verbatim run-2 message already there). batch-executor.test.ts is shared with #1069: add your AC-4 case in ONE new describe("#1087 …") block appended at the end and touch nothing else there.

  3. admarble commented on Sep 20, 2026

    @admarble
    ContributorAuthor

    Complexity: Standard (5 ACs, 3 directories)

    AC Quality Check

    • AC-1 — "the run's wait horizon" is undefined, and the Codex driver cannot see the run's autoWaitMinutes (evaluateCodexRun(parsed, outcome) and AgentExecutionConfig carry no wait budget). Resolved in Open Question 1: a fixed driver-side horizon. ⚠️ needs the owner's confirmation.
    • AC-2 — "429-style" has no enumerated wording. The only fixture (codex-turn-failed-rate-limit.jsonl) is reconstructed, not captured (PROVENANCE.md). The plan enumerates the patterns in Phase 1.
    • AC-3, AC-4, AC-5 — measurable.

    Scope Assessment

    Non-Goals: ⚠️ No Non-Goals section. Inferred from the graph plan's "May touch" list: no opencode classification, no rate_limits plumbing, no change to batch-executor logic (AC-4 is a test only).

    Metric Value Status
    Feature count 1 (Codex turn.failed classification) ✅
    AC items 5 ✅
    Directory spread 3 (drivers/, drivers/__tests__/, workflow/) ✅

    Verdict: ✅ SCOPE_OK


    Acceptance Criteria

    AC-1: usage-limit turn.failed → BillingError (reset beyond horizon), reset time in metadata

    Verification: Unit Test
    Scenario: Given the verbatim run-2 stream (codex-turn-failed-usage-limit.jsonl) → When evaluateCodexRun runs → Then structuredError is a BillingError, isRetryable === false, and metadata.resetsAtText = Oct 16th, 2026 1:04 AM (plus metadata.resetsAt in epoch ms when parseable).
    Assumptions: The reset text is local-time and human-formatted; only one capture exists. An unparseable or absent reset must still yield BillingError (fail closed) with resetsAtText only.

    AC-2: transient throttle → retryable RateLimitError

    Verification: Unit Test
    Scenario: Given codex-turn-failed-rate-limit.jsonl → When evaluateCodexRun runs → Then structuredError is a RateLimitError, isRetryable === true.
    Assumptions: The wording after rate limit exceeded: is reconstructed. Match the prefix codex itself emits, plus 429 / too many requests, not the invented detail.

    AC-3: other turn.failed → generic SequantError, code turn-failed

    Verification: Unit Test
    Scenario: Given codex-turn-failed-unrecognized.jsonl → Then the error is neither BillingError nor RateLimitError and metadata.code === "turn-failed". Already green in the conformance suite; it must stay green (regression guard for over-broad regexes).

    AC-4: no quality-loop iteration after a BillingError phase failure

    Verification: Integration Test
    Scenario: Given -Q with maxIterations > 1 and an exec phase whose result is evaluateCodexRun(<run-2 fixture>) (the real mapping, not a hand-built BillingError) → When runIssueWithLogging runs → Then exec is dispatched once and loop is never dispatched.
    Assumptions: The executor half (isBillingHalt → haltedByBilling, batch-executor.ts:1910) already exists (#799) and is tested with synthetic errors at batch-executor.test.ts:776. AC-4's new value is pinning the composition: the real Codex-mapped error reaches that guard.

    AC-5: verbatim fixtures; AC-1 and AC-4 mutation-verified

    Verification: Unit Test + Manual (PR body marker)
    Scenario: Reuse __fixtures__/codex-turn-failed-usage-limit.jsonl (byte-identical to run-2 stdoutTail[48..49]). Mutation records use the SEQUANT_MUTATION format with failedTest starting with the test file path.


    Implementation Plan

    Phase 1: Classifier in the driver (src/lib/workflow/drivers/codex.ts)

    1. Add an exported pure classifyCodexTurnFailure(message, now = Date.now()): SequantError, called from the parsed.turnFailure branch of evaluateCodexRun (codex.ts:323).
    2. Keep metadata.code = "turn-failed" on every branch, so anything keyed on the code keeps working.
    3. The error.message / fail() string is unchanged: codex turn failed: <message>.

    Phase 2: Tests (parallel-safe after Phase 1)

    1. drivers/__tests__/driver-conformance.test.ts: delete pending: "#1087" from the two codex cases (only that change in the file).
    2. drivers/codex.test.ts: unit tests for classifyCodexTurnFailure covering the horizon boundary (6d23h vs 7d1h, with injected now), the past reset, no reset, an unparseable reset, the ordinal suffix, both AC-2 wordings, and the AC-3 fall-through.
    3. batch-executor.test.ts: append ONE describe("#1087 …") at the end (shared with bug(qa): the qa phase rebases an already-pushed branch onto main, forcing a force-push to land it #1069, touch nothing else). Drive runIssueWithLogging with an exec result built from the run-2 fixture. Assert one exec dispatch, zero loop dispatches, haltedByBilling surfaced.

    Phase 3: Verify and record

    1. Run only the named files (driver-conformance, codex.test.ts, batch-executor.test.ts). No full npm test (runner context). Add a CHANGELOG.md entry.
    2. Mutations (commit first):
      • AC-1: make the usage-limit branch fall through to the generic SequantError. The conformance case errors map the verbatim #1087 usage-limit … must fail.
      • AC-4: same mutation. The new #1087 batch-executor case must fail, because it loops into loop. This confirms the test exercises the real mapping and not a stub.
      • Record both as SEQUANT_MUTATION markers with the full test file path first.
    3. Answer OQ-3 in the PR body (see below).

    Design Review

    1. Where does this logic belong? In the Codex driver (evaluateCodexRun), the counterpart of ClaudeCodeDriver.buildStructuredError. The executor already keys on the typed classes (isBillingHalt, isWindowHalt), so no executor change is needed.
    2. Simplest correct approach? A message-text classifier with a fixed horizon constant. Rejected: threading autoWaitMinutes into AgentExecutionConfig. It would touch the driver interface for every driver and is outside "May touch". autoWaitMinutes stays the final dial in shouldAutoWaitForReset.
    3. Existing pattern? createRateLimitError / isBillingFailure (Five-hour window exhaustion is misclassified as terminal billing, so --auto-wait is inert on subscription plans #860): recognized window allowlist, everything else fails closed to BillingError.
    4. Reviewer challenge: "Why can a usage-limit be a RateLimitError when AC-1 only names BillingError?" Because the issue title says auto-wait must be able to engage, and a within-horizon reset is a pause, not a wallet failure. Both halt the quality loop (isWindowHalt for reset > 5 min), so AC-4 holds either way. See OQ-1.

    Feature Quality Planning

    All standard checks pass. Notable items:

    • Sibling site: the same usage-limit text also arrives as a top-level error event (codex-turn-failed-usage-limit.jsonl line 3). The parsed.errors branch (codex.ts:331, code stream-error) is generic. With a turn.failed present the first branch wins, so the fixture is covered. A run that emits only the error event and exits non-zero would still be classified generic. Proposed as OQ-2; not silently widened.
    • opencode has no throttle/billing classification; the conformance suite already carries a typed skip for it. Out of scope.
    • Timezone: the reset text has no zone. A local-time parse can be off by hours, which affects only the 7-day boundary and the wake time. Auto-wait is capped at AUTO_WAIT_MAX_WAITS = 2, so an early wake costs one more rejection at worst.

    OQ-3 (rate_limits in the exec JSON stream)

    Partial evidence only: the run-2 log's 50-line stdoutTail has no rate_limits or token_count. That tail is only the last lines and is not conclusive for earlier events. Resolve in the PR by scanning a full live codex exec --json stream with the existing codex.live.integration.test.ts harness, if credentials allow; otherwise state "not observed in the tail; unverified". The message-text mapping does not depend on it.


    Open Questions

    1. What does a usage-limit within the horizon map to? AC-1 covers only "beyond the horizon". Recommendation: RateLimitError with resetsAt for ≤ 7 days, so --auto-wait can engage; the issue title names that as a goal. Impact if wrong: a within-horizon reset halts instead of waiting. Simpler fallback: always BillingError with reset metadata, since resetsAt still lands in metadata.
    2. Also classify the top-level error event (no turn.failed)? Recommendation: yes, by routing parsed.errors through the same classifier. It is a few lines in the same function, but it widens AC-3's "any other" surface. Impact if skipped: a stream that dies after the error event without a turn.failed stays "unknown".
    3. Horizon value: 7 days (mirrors seven_day). Run 2's Oct 16 reset is ~26 days out, so it is BillingError. Impact if wrong: only the boundary cases move.

    Recommended Workflow

    Phases: exec → qa
    Quality Loop: disabled
    Reasoning: Bug fix with the failing tests already stubbed by #1096 (pending), so testgen adds nothing. Mechanical tier, one driver file, three test files. No UI, no security surface. Runner rules apply: no full npm test, mutation markers with the file path first, stop at the PR.


    Label Review

    Current: bug
    Recommended: bug, planned
    Reason: Confirms scope; no complexity labels warranted.
    Quality Loop: Won't auto-enable (SCOPE_OK, 5 ACs).

  4. added
    planned
    on Sep 20, 2026
  5. admarble commented on Sep 20, 2026

    @admarble
    ContributorAuthor

    QA Verdict: AC_MET_BUT_NOT_A_PLUS

    AC coverage: 5/11 met

    Gaps:

    • The AC-1 and AC-4 mutation-gated tests are wall-clock dependent and will fail for a seven-day window in October because the fixture reset date crosses the driver's fixed 7-day horizon.
    • AC-1's 'the run's wait horizon' is implemented as a driver-side fixed 7-day constant rather than the run's configured autoWaitMinutes; behavior is contained but the contract wording and the code diverge.
    • A Codex run emitting only a top-level error event with usage-limit text and no turn.failed still classifies generic; documented as OQ-2 and deliberately not widened, and no such shape has been observed.
    • The AC-1 and AC-4 gate tests are wall-clock dependent and will fail for a seven-day window in October. Detail under Adversarial Re-Read.

    Suggestions:

    • Thread an optional now through evaluateCodexRun (it already exists on classifyCodexTurnFailure) and have codexOutcome / the batch-executor case pass a frozen timestamp. That removes the clock dependency without touching the fixture.
  6. added 2 commits that reference this issue on Sep 20, 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

    bugplanned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions