Skip to content

bug: timed-out, cancelled and backend-failed runs record no cost — spend and loop budgets undercount #4823

Backlog

Description

@AndriiPasternak31

Summary

A run that fails part-way still spent tokens, but in most failure shapes the execution row is written with cost = NULL. Every spend surface adds costs up with COALESCE(cost, 0), so that spend shows as $0. A run that times out after 40 minutes of tool use, a run an operator cancels, and a run the backend gives up on all count as free in per-agent stats, schedule analytics, subscription spend, and the loop max_cost_usd budget.

Context

The backend already stores whatever cost the agent reports on a failed row (the failure branch of apply_result in src/backend/services/task_execution_service.py, from #678 and #1853). So the gap is in what the agent reports, and in terminals the backend writes without asking the agent.

Claude Code reports cost only in the final result stream line (total_cost_usd). A process that is killed never emits that line. Separately, per-message usage is overwritten with each new message rather than added up, so no running total exists to fall back on.

Terminal shape Cost on the row today Where
Success ✅ reported result line
error_during_execution, error_max_turns ✅ if Claude emitted a result line #1853 salvage
Previous attempt of a retried run ✅ rolled into the final attempt #678 R2
Agent-side timeout / stall-watchdog kill (504) ❌ NULL: the process is killed before the result line, so metadata.cost_usd is never set _timeout_504_detail in docker/base-image/agent_server/services/headless_executor.py, stream_parser.py
Operator cancel ❌ dropped on purpose: the relabel returns "metadata": {} with the comment "the cancel is non-billable". That premise is wrong, because every token used before the cancel was billed docker/base-image/agent_server/routers/chat.py, the #679 (F3) cancel branch
Backend-side timeout (httpx.TimeoutException) ❌ the terminal is written with an error only _handle_timeout in task_execution_service.py
Watchdog / cleanup-sweep failures ❌ unless a retained terminal is recovered src/backend/services/cleanup_service.py
Subprocess pipe closed / unexpected exception (500/502 string detail) ❌ no metadata in the body headless_executor.py outer handlers

Who sees the effect:

  • Operators reading spend (agent stats, get_agent_spending, schedule analytics cost_by_status) see failure-heavy agents as cheap. That is backwards: a timing-out schedule is often the most expensive thing on the fleet.
  • Loop budgets (feat(loops): per-loop cost budget enforced as a hard stop (max_cost_usd) #1155) treat a run with no cost as $0 (loop_service.py already logs this case as "reported no cost; counts as 0"). A loop whose runs keep timing out never reaches its max_cost_usd stop.
  • Subscription spend (SUB-004) undercounts in the same way.

Not measured yet: how much of the fleet's real spend falls into these shapes. The fix should report that number from a live instance (failed/cancelled rows with cost IS NULL, and their duration) so the priority can be checked.

Acceptance Criteria

  • A Claude run that is killed by the agent-side timeout or the stall watchdog records a non-null cost covering the API calls it made before the kill.
  • A cancelled run records the cost it used before the cancel. The cancel stays labelled cancelled, and the dispatch-breaker and failure-counter behaviour from feat(executions): plumb cancel signal into agent task-runner reply (#671 defense-in-depth) #679 does not change.
  • Each failure terminal in the table above either records a cost or is listed, with its reason, as a shape where no cost can be known (for example, the agent never started a model call).
  • A cost that is reconstructed rather than reported by the runtime is marked as such on the row or in its metadata, so spend surfaces never present an estimate as a billed figure. Where the runtime does report a cost, that figure wins.
  • Codex, Gemini and OpenCode runtimes are checked against the same criteria, and any gap there is fixed or recorded.
  • Each fixed shape has a test that is red before the fix: kill a run mid-stream, then assert the persisted row's cost is greater than 0.
  • A loop with max_cost_usd whose runs time out stops with budget_exhausted once the real spend crosses the budget.

Technical Notes

Activity

  1. added
    priority-p2
    type-bug
    theme-reliability
    status-ready
    on Nov 27, 2026
  2. pcbeingused333 commented on Nov 28, 2026

    @pcbeingused333
    Contributor

    A killed Claude run never emits the result line, so accumulating per-call usage would give token totals but no dollar figure: as far as I can see there is no Claude price table in the repo, and opencode_runtime.py deliberately avoids a hand-maintained one. Which would you prefer for these shapes: (a) a Claude rate table used only to produce a cost explicitly marked as estimated, or (b) persisting the accumulated token usage and leaving cost NULL, with spend surfaces showing it as unknown rather than $0? Also, should the "estimated" marker be a new column or a metadata field? Happy to open a PR against dev once that is settled.

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

    priority-p2status-readytheme-reliabilitytype-bug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions