Skip to content

Five-hour window exhaustion is misclassified as terminal billing, so --auto-wait is inert on subscription plans #860

Closed

Description

@admarble

The defect

isBillingFailure (src/lib/errors.ts:260-265) classifies on the presence of a marker alone:

export function isBillingFailure(info: RateLimitInfoLike): boolean {
  return info.errorCode === "credits_required" ||
         info.overageDisabledReason === "out_of_credits";
}

It ignores rateLimitType and ignores whether a live resetsAt is present.

On a subscription plan, hitting the five-hour cap with overage disabled produces exactly this payload. All 26 real rate-limit failures captured across ad-motion and matcha-maps (five separate days) are structurally identical:

"errorMetadata": {
  "resetsAt": 1784478600,
  "rateLimitType": "five_hour",
  "overageDisabledReason": "out_of_credits"
}

That is a window that will reopen at a known time, not a wallet needing a top-up. But it becomes a BillingError, and:

  • BillingError and RateLimitError are sibling classes (errors.ts:207 and :227, both extending SequantError directly)
  • shouldAutoWaitForReset (phase-executor.ts:287) returns null unless error instanceof RateLimitError

So --auto-wait (#804) cannot fire on any real limit event this project has ever recorded, even though the payload carries the exact wake time it needs. #799 then fail-fasts the quality loop and the run halts.

Net effect: the feature built for unattended runs is inert for the plan most likely to want it.

Design critique — the obvious fix is wrong

Do not simply invert the classification. On a pay-as-you-go/API account, out_of_credits genuinely is terminal; waiting is useless and the current halt-immediately behavior is correct. A naive change strands those users in a silent multi-hour sleep instead of telling them to add credits. The change must narrow the billing class, not flip it.

The natural discriminator is not available in practice. RateLimitInfoLike (errors.ts:250-253) already declares canUserPurchaseCredits and hasChargeableSavedPaymentMethod — exactly the fields that would separate "subscription window" from "needs purchase". All 26 captured payloads omit both. So a correct implementation cannot depend on them; it must degrade to a proxy and treat their absence as unknown.

The proxy is an inference about someone else's billing semantics. rateLimitType: "five_hour" + a future resetsAt is good evidence of a subscription window, but it encodes an assumption about Anthropic's payload vocabulary that can drift silently. Whatever is built should fail closed — if the shape is unrecognized, keep today's terminal behavior.

The larger critique: in-process sleeping may be the wrong shape

Even with correct classification, --auto-wait holds a live process for up to five hours. That has costs the current design does not address:

Alternative worth costing before building: halt cleanly, record a machine-readable resumeAt in state, and exit. Re-entry is already cheap because #837 makes a resumed run skip completed issues. That design holds no lock, survives reboots and laptop sleep for free, is trivially observable, and needs no in-process timer. The scheduling then lives in ~20 lines of launchd/cron rather than inside a long-lived agent process.

The counter-argument for keeping the in-process wait is that it preserves worktree and chain state across the pause without re-deriving it, and avoids a cold start. That may well win — but it should be an argued choice, not a default.

Credit where due: waitForWindowReset (phase-executor.ts:321) is wall-clock tick-based, taking an injectable now() rather than a single setTimeout, so it already survives machine sleep. AUTO_WAIT_MAX_WAITS = 2 bounds runaway pause loops, and a registered AbortController lets Ctrl-C end a wait. The existing implementation is careful; the problem is that classification prevents it from ever running.

Real-world scenario

An overnight chain starts at 23:00 and exhausts the five-hour window at 02:00, with resetsAt at 07:00.

Today: BillingError → #799 fail-fasts → the run halts at 02:00. Seven hours of wall clock wasted; the user finds a dead run at breakfast.

With classification fixed, in-process wait: the run sleeps five hours holding the lock. If the laptop sleeps, the tick loop re-reads the clock and is fine. If it reboots, the run is gone and a stale lock remains. On wake the phase restarts from scratch anyway, because the claude subprocess died at 02:00 — so the wait bought resumption, not continuity.

With halt-and-resume: the run exits at 02:00 recording resumeAt: 07:00. A scheduled re-invocation at 07:05 skips the completed issues (#837) and continues. Survives reboot, holds no lock, and the state file says plainly what is happening.

Acceptance Criteria

  • AC-1: A rate-limit failure carrying rateLimitType: "five_hour" (or another window type) together with a future resetsAt is classified as a waitable window rather than a terminal billing failure, even when overageDisabledReason: "out_of_credits" is present.
  • AC-2: A failure with errorCode: "credits_required", or with no future resetsAt, remains terminal and halts immediately with the existing message.
  • AC-3: An unrecognized payload shape fails closed — treated as terminal, never as an indefinite wait.
  • AC-4: All 26 captured payloads are committed as fixtures and assert the waitable classification; the existing terminal-billing fixtures continue to assert terminal.
  • AC-5: --auto-wait fires end-to-end on a replayed five-hour-window payload, and does not fire on a replayed terminal-credits payload.
  • AC-6: A waiting run emits periodic progress to non-TTY stdout naming the wake time, so an unattended wait is distinguishable from a hang.
  • AC-7: The in-process-wait versus halt-and-resume tradeoff is decided explicitly and the rationale recorded, covering lock-holding and reboot survival.

Evidence

Captured payloads: docs/incidents/782/captures/ (the committed #782 sample from 2026-07-18) plus 26 further occurrences in the ad-motion and matcha-maps .sequant/logs/ from 2026-07-19, 07-24 and 07-26. Note .sequant/ is gitignored and rotates at ~100 files — copy before they age out.

Related: #804 (auto-wait), #799 (fail-fast on billing/window), #820 (infra-blocked CI), #856 (a silent run is indistinguishable from a hang).

Activity

  1. admarble commented on Jul 29, 2026

    @admarble
    ContributorAuthor

    #860 — Five-hour window exhaustion is misclassified as terminal billing, so --auto-wait is inert on subscription plans
    Open
    ────────────────────────────────────────────────────────────────

    → PROCEED — Verified against main — isBillingFailure (errors.ts:260-265) classifies on marker presence alone, checking neither rateLimitType nor resetsAt

    Commands:
    sequant run 860 -Q

    spec → exec → qa · 7 ACs

    Flags:
    -Q classification, wait plumbing and non-TTY observability span several files

    Considered:
    --testgen AC-4 pins specific captured payloads as fixtures — generated stubs would not match them
    ────────────────────────────────────────────────────────────────
    ⚠ AC-4 needs the 26 payloads copied out of ad-motion/matcha-maps .sequant/logs/ before the 100-file rotation ages them out — capture first or the AC becomes unmeetable
    ⚠ AC-7 is a design decision (in-process wait vs halt-and-resume), not implementation — expect spec to surface it for a call
    ────────────────────────────────────────────────────────────────

  2. admarble commented on Jul 29, 2026

    @admarble
    ContributorAuthor

    #860 — Five-hour window exhaustion is misclassified as terminal billing, so --auto-wait is inert on subscription plans
    Open
    ────────────────────────────────────────────────────────────────

    Supersedes prior assess from 2026-07-29 (PROCEED)

    → PROCEED — Re-verified against main — isBillingFailure (errors.ts:259-264) still classifies on marker presence alone, checking neither rateLimitType nor resetsAt

    Commands:
    sequant run 860 -Q # after PR #858 merges

    spec → exec → qa · 7 ACs

    Flags:
    -Q classification, wait plumbing and non-TTY observability span several files

    Considered:
    --testgen AC-4 pins 26 specific captured payloads as fixtures — generated stubs would not match them
    ────────────────────────────────────────────────────────────────
    ⚠ New since the last assess: open PR #858 (issue #853) rewrites src/lib/workflow/phase-executor.ts, the same file shouldAutoWaitForReset (:287) and waitForWindowReset (:321) live in — land #858 first or expect a conflict
    ⚠ AC-4 needs the 26 payloads copied out of ad-motion/matcha-maps .sequant/logs/ before the 100-file rotation ages them out — capture first or the AC becomes unmeetable
    ⚠ AC-7 is a design decision (in-process wait vs halt-and-resume), not implementation — expect spec to surface it for a call
    ────────────────────────────────────────────────────────────────

  3. admarble commented on Aug 4, 2026

    @admarble
    ContributorAuthor

    Plan (spec)

    Complexity: Standard (7 ACs, ~4 directories)

    Scope note

    Automated scope assessment says SCOPE_SPLIT_RECOMMENDED (feature-count heuristic counts classification + observability + decision-record as 3 features). Proceeding as one change: AC-1..5 are one cohesive classification fix with its evidence, AC-6 is a ~15-line heartbeat gap in the same feature, AC-7 is a document. Quality loop enabled to compensate.

    Evidence secured

    All 26 payloads (22 ad-motion + 4 matcha-maps, 6 distinct resetsAt values, all five_hour + out_of_credits, none carrying errorCode/canUserPurchaseCredits/hasChargeableSavedPaymentMethod) copied out of the rotating .sequant/logs before they age out. They will be committed under docs/incidents/860/captures/ plus a distilled test-fixture JSON.

    AC checklist & verification

    • AC-1 waitable-window classification — Unit (fixtures through createRateLimitError → RateLimitError)
    • AC-2 credits_required / no-future-resetsAt stays terminal — Unit
    • AC-3 unrecognized shape fails closed — Unit (property-style negative cases)
    • AC-4 all 26 payloads committed as fixtures asserting waitable; existing terminal fixtures still terminal — Unit, mutation-verified per repo testing rule
    • AC-5 --auto-wait fires end-to-end on replayed window payload, not on terminal payload — Integration (replay through buildStructuredError → shouldAutoWaitForReset/performAutoWait)
    • AC-6 periodic non-TTY stdout progress naming wake time — Unit (heartbeat tick with isTTY: false)
    • AC-7 in-process-wait vs halt-and-resume decision recorded — Manual (decision doc in docs/investigations/)

    Design

    Narrow isBillingFailure at the source (src/lib/errors.ts) — do not invert it:

    1. errorCode === "credits_required" → always terminal (explicit purchase signal wins).
    2. overageDisabledReason === "out_of_credits" → terminal unless the payload also carries a recognized window type (five_hour / seven_day* prefix allowlist) and a future resetsAt (via resetsAtToMs, injectable now). Then it is a waitable window → RateLimitError.
    3. Anything unrecognized (e.g. rateLimitType: "overage", missing/past resetsAt) → fails closed, terminal. canUserPurchaseCredits/hasChargeableSavedPaymentMethod stay out of classification (absent in all 26 real payloads); they continue to enrich messaging only.

    All consumers inherit the narrowing: createRateLimitError, formatRateLimitMessage (window payloads now say "Rate limited — resets at …" instead of the misleading "Out of credits"), isRateLimitFailureInfo, run-display.ts.

    Critical second touchpoint: claude-code.ts:366 downgrades RateLimitError → bare BillingError when the assistant separately reports billing_error. After narrowing, that guard would re-kill auto-wait for exactly the payloads we are fixing. The downgrade must not fire when the rate-limit event itself carries waitable-window evidence (richer signal wins — same precedence philosophy already documented there).

    AC-6: LivenessHeartbeat.tick() currently continues past non-TTY output while waiting (heartbeat.ts:223-228). Add a throttled non-TTY branch (~every 5 min, plain newline-terminated line naming wake time + remaining). TUI renderer path unaffected.

    AC-7 decision (to be recorded in docs/investigations/auto-wait-vs-halt-resume-860.md): keep the in-process wait now — classification is the actual defect; the wait machinery (#804) is tick-based, sleep-safe, abortable, and bounded (AUTO_WAIT_MAX_WAITS=2). Record lock-holding and reboot-survival costs honestly; file a follow-up issue for halt-and-resume + resumeAt state (builds on #837) rather than expanding this change.

    Implementation plan

    1. Commit captures to docs/incidents/860/captures/ + distilled __tests__/fixtures/rate-limit-payloads-860.json (26 entries with source refs).
    2. errors.ts: add isWaitableWindow(info, now?), narrow isBillingFailure(info, now?); unit tests incl. all 26 fixtures (AC-1..4).
    3. claude-code.ts: guard the billing_error downgrade with the waitable-window check; driver-level tests.
    4. heartbeat.ts: non-TTY throttled wait line (AC-6) + tests.
    5. Integration test replaying both payload classes through shouldAutoWaitForReset/auto-wait path (AC-5).
    6. Decision record + follow-up issue (AC-7).
    7. Mutation-verify the fixture gate test (delete fixture payload → exactly that test fails → restore; record in PR body).

    Open questions (proceeding with defaults)

    1. Window-type allowlist breadth — default: five_hour exact + seven_day prefix (matches documented SDK vocabulary). Impact if wrong: an unlisted future window type stays terminal (fail-closed, safe).
    2. Does seven_day + out_of_credits occur in practice? No captures show it; allowlisting is a judgment call consistent with AC-1 "(or another window type)".

    Phases: spec → exec → qa (no UI labels → no browser test; testgen skipped — tests are themselves ACs and written alongside implementation)

  4. added
    planned
    on Aug 4, 2026
  5. admarble commented on Aug 4, 2026

    @admarble
    ContributorAuthor

    Exec complete

    Commit a910520d on feature/860-waitable-window-classification (13 files, +1397/−21).

    AC status after implementation

    • AC-1 ✅ isBillingFailure narrowed via new isWaitableWindow (five_hour/seven_day* + future resetsAt, injectable now); live windows → retryable RateLimitError, metadata intact
    • AC-2 ✅ credits_required terminal even beside window evidence; past/missing resetsAt terminal; existing "Out of credits" messages unchanged
    • AC-3 ✅ allowlist + full-shape requirement fails closed (tested incl. rateLimitType: "overage")
    • AC-4 ✅ all 26 payloads committed with provenance (__tests__/fixtures/rate-limit-payloads-860.json + docs/incidents/860/captures/README.md); raw stdoutTail transcripts deliberately excluded (unrelated-project content — noted in the README)
    • AC-5 ✅ fixture replay: all 26 grant an auto-wait at their captured instant, terminal once aged; end-to-end executePhaseWithRetry replay waits-and-retries on the window payload, halts without waiting on credits_required
    • AC-6 ✅ -q heartbeat: append-only non-TTY line naming wake time every 5 min; default-mode NonTTYRenderer: announces wait once, 60s heartbeat names wake time — and two latent bugs fixed (waiting events printed a spurious ✘ per 15s tick and held the heartbeat idle clock fresh, silencing it for the whole wait)
    • AC-7 ✅ decision recorded in docs/investigations/auto-wait-vs-halt-resume-860.md (keep in-process wait; halt-and-resume filed as follow-up)

    Extra touchpoint found during implementation

    claude-code.ts buildStructuredError downgraded any RateLimitError to a metadata-less BillingError when the assistant separately reported billing_error — which would have re-inerted auto-wait for exactly the payloads being fixed. The downgrade now yields to waitable-window evidence in the rate_limit_event.

    Gates

    • Build ✅ · Lint ✅ · Full suite ✅ 4845 passed / 231 files (1 expected fail, 2 skipped — baseline)
    • Mutation verification (per repo testing rule):
      1. Fixture payload deleted → exactly the 2 count-gate tests fail ✅
      2. five_hour removed from allowlist → 10 tests fail across errors/auto-wait/driver suites ✅
      3. Non-TTY heartbeat notice branch disabled → exactly the 3 notice tests fail ✅
      4. NonTTYRenderer waiting handling reverted → exactly the 3 renderer tests fail (incl. the ✘-suppression guard) ✅
  6. admarble commented on Aug 4, 2026

    @admarble
    ContributorAuthor

    QA Review for Issue #860

    AC Coverage

    AC Description Status Notes
    AC-1 Live window (five_hour/other + future resetsAt) classified waitable despite out_of_credits MET isWaitableWindow + narrowed isBillingFailure (errors.ts); all 26 captured payloads → RateLimitError with metadata intact; message names the reset, not "Out of credits"
    AC-2 credits_required / no future resetsAt stays terminal with existing message MET credits_required short-circuits before the window check; past/missing resetsAt terminal; "Out of credits" message tests unchanged; end-to-end replay halts in 1 attempt, delayFn never called
    AC-3 Unrecognized shape fails closed MET Allowlist /^(five_hour|seven_day)/ + full-shape requirement; tested with rateLimitType: "overage", missing type, missing/past resetsAt — all terminal. Wait is additionally double-bounded (AUTO_WAIT_MAX_WAITS, minutes budget), so "indefinite wait" is impossible even on misclassification
    AC-4 All 26 payloads committed as fixtures asserting waitable; existing terminal fixtures still terminal MET __tests__/fixtures/rate-limit-payloads-860.json (26 entries, 22 ad-motion + 4 matcha-maps, with provenance); count + shape + classification gated by tests, mutation-verified. Untouched terminal fixtures (credits_required, markerless out_of_credits) still assert terminal. The #782 capture tests were retitled honestly: same payload class, terminal once aged, waitable at the captured instant
    AC-5 --auto-wait fires end-to-end on window replay, not on terminal-credits replay MET All 26 payloads grant a wait via shouldAutoWaitForReset at their captured instant; executePhaseWithRetry replay (payload shape verbatim, reset re-based) waits and retries to success; credits_required replay halts without waiting; driver test proves the rate_limit_event → RateLimitError link survives a concurrent billing_error enum
    AC-6 Periodic non-TTY stdout progress naming wake time MET Both non-TTY surfaces: -q LivenessHeartbeat (append-only line, 5-min throttle, wake + remaining) and default-mode NonTTYRenderer (announce-once + 60s heartbeat naming wake). Two latent bugs fixed on the way: waiting events printed a spurious ✘ per 15s tick and held lastEventAt fresh, silencing the heartbeat for the whole wait
    AC-7 In-process vs halt-and-resume decided and recorded, covering lock + reboot MET (manual: doc reviewed) docs/investigations/auto-wait-vs-halt-resume-860.md — argued table covering lock-holding and reboot loss explicitly; decision: keep in-process wait, file halt-and-resume follow-up

    Coverage: 7/7 ACs fully met

    Quality Metrics & Checks

    Check Result
    Type safety ✅ 0 issues (any/@ts-ignore: none added)
    Deleted tests ✅ 0 (4 test files modified, no removed cases, no .skip)
    Scope/size ✅ 13 files, +1397/−21 (source +196/−13; tests +596; fixtures/docs +605); no out-of-scope files; phase-executor.ts comment-only
    Security ✅ 0 critical/0 warnings; new regex linear-time (not ReDoS-prone); fixtures contain run metadata only, no secrets/emails
    Build / Lint ✅ clean
    Full suite ✅ 4845 passed / 231 files
    Mutation verification ✅ 4 mutations, each caught by exactly the intended tests (fixture count, allowlist, heartbeat notice, renderer waiting path)
    Stale branch ✅ 0 behind origin/main
    CI No PR yet at QA time — checks run post-PR

    Precheck Findings

    Section Status Surfaced
    Fixtures pass 2 verbatim issue-body fixtures — the pre-fix isBillingFailure snippet (now replaced) and the resetsAt: 1784478600 payload (present in the committed 26, asserted waitable)
    Sibling-grep pass 6 changed identifiers, 0 unaddressed sibling sites
    AC literal-diff not_applicable No PR body yet

    Test Coverage Analysis

    All behavioral source changes have direct tests: errors.ts → rate-limit-errors.test.ts (36), claude-code.ts → driver suite, heartbeat.ts/run-renderer.ts → auto-wait-display.test.ts (16), executor path → auto-wait.test.ts (46). phase-executor.ts change is comment-only.

    Risk Assessment

    • Likely failure mode: Anthropic changes the payload vocabulary (new window type name, or resetsAt semantics). By design this fails closed to today's terminal halt — inconvenient, never harmful. Second-order: a genuine billing outage that happens to carry a live five_hour window would now wait once (bounded ≤2 waits/budget) before halting instead of halting immediately — accepted, documented trade-off in the driver comment.
    • Not tested: A real 5-hour wall-clock wait (tick loop is clock-injected and tested at scale); MCP/orchestrator-mode wait visibility (out of scope — that channel deliberately suppresses renderer output, MCP runs are 30-min bounded, and sequant_status/run logs remain the liveness source there).
    • Sibling sites considered: All isBillingFailure consumers traced (createRateLimitError, formatRateLimitMessage, isRateLimitFailureInfo — deliberately kept on raw markers, run-display.ts label fallback — correct with default now). Precheck sibling-grep: 0 unaddressed.
    • Sibling-line audit: The driver's billing_error downgrade at claude-code.ts:366 was found and guarded during exec — the one adjacent site that would have re-inerted the fix.

    Trust-Boundary Check

    Finding: Clean — diff implements only product requirements; the issue body's process guidance ("copy captures before they age out") was followed as benign maintainer instruction; no agent-directed execute/fetch/exfiltrate content present or acted on.

    Status: Clean

    Behavior-Rule Survival Check

    Detector run on all 7 ACs: not triggered (AC-3's single "never" is below the 2-keyword threshold; no always X unless Y patterns). Status: N/A

    CHANGELOG Verification

    Check Status
    CHANGELOG.md exists ✅
    User-facing change ✅ (fix)
    [Unreleased] entry ✅ Present under ### Fixed, includes (#860)

    Adversarial Re-Read

    Findings: No gaps found because: (1) both verbatim issue-body fixtures were run — the quoted payload is entry #2 of the committed 26 and asserts waitable; (2) evidence claims are post-fix validations (fixture-driven classification tests + end-to-end replay), not pre-fix repros; (3) process state inspected — single clean commit, 0 behind origin/main, lockfile churn reverted before commit; (4) sibling sites cited above, including the driver downgrade that static AC reading would have missed; (5) the issue's explicit non-goal ("do not simply invert") honored — credits_required and aged windows remain terminal, asserted by tests; classification-time vs wait-decision-time drift traced (window expiring between error creation and wait decision degrades to transient backoff, not a hang).

    Status: Clean

    Verdict: READY_FOR_MERGE

    All 7 ACs met with fixture-backed, mutation-verified tests; full suite green; the change narrows rather than inverts the classification and fails closed on unknown shapes. One observation recorded (MCP-mode wait visibility) — pre-existing, by-design, out of scope.

    Documentation: CHANGELOG ✅ · incident captures README ✅ · decision record ✅ · README unchanged (no new flags — --auto-wait already documented by #804)

  7. admarble commented on Aug 4, 2026

    @admarble
    ContributorAuthor

    /fullsolve Complete

    Issue: #860
    Status: READY_FOR_MERGE
    PR: #893 (CI: 5/5 checks green — build, typecheck, node-floor-guard, validate-skills, validate-plugin)

    Summary

    • AC: 7/7 met — classification narrowed (not inverted), fail-closed on unknown shapes, all 26 captured payloads committed as gating fixtures, end-to-end auto-wait replay, non-TTY wait observability on both surfaces, AC-7 decision recorded
    • Tests: full suite 4845 passed / 231 files; 4 gate-test mutations verified (each caught by exactly the intended tests)
    • QA: READY_FOR_MERGE on first pass (see QA review above)
    • Extra findings fixed en route: driver billing_error downgrade would have re-inerted auto-wait; NonTTY renderer printed a spurious ✘ per 15s waiting tick and its heartbeat was silenced during waits
    • Follow-up filed: feat(run): durable halt-and-resume for waitable rate-limit windows — write resumeAt, release the lock, survive reboots #892 — durable halt-and-resume (resumeAt state, lock release at halt, reboot survival), per the AC-7 decision record

    Iterations

    Phase Iterations Status
    Spec 1/1 Complete
    Exec 1/3 Complete
    Test — Skipped (no UI labels)
    QA 1/2 Complete (READY_FOR_MERGE)

    Ready for human review and merge.

  8. added 2 commits that reference this issue on Aug 4, 2026
  9. added a commit that references this issue on Aug 4, 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

    planned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions