Repository navigation
Description
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 analyticscost_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.pyalready logs this case as "reported no cost; counts as 0"). A loop whose runs keep timing out never reaches itsmax_cost_usdstop. - 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_usdwhose runs time out stops withbudget_exhaustedonce the real spend crosses the budget.
Technical Notes
- Related, closed: bug: error_during_execution runs store zero telemetry (no execution_log/session_id/cost) and the JSONL is reaped in 1-7h — failure class is undiagnosable #1853 (zero telemetry on
error_during_execution), Async chat_with_agent: long execution silently fails with null response (reader-thread) #678 (salvaging the cost of a failed retry attempt), feat(loops): per-loop cost budget enforced as a hard stop (max_cost_usd) #1155 (loop cost budget), bug: scheduler-created executions (cron, reminders) never record subscription_id — SUB-004 spend misses them #4085 (scheduler runs missingsubscription_idfor SUB-004). - Cache-read tokens per call are large on tool-heavy turns (see the token-accounting notes in
stream_parser.py). Any reconstruction has to add up per-call usage without counting cache reads twice. The cumulativeresult.usagefigure is not available on these paths.
Activity
pcbeingused333 commentedon Nov 28, 2026
A killed Claude run never emits the
resultline, so accumulating per-callusagewould give token totals but no dollar figure: as far as I can see there is no Claude price table in the repo, andopencode_runtime.pydeliberately 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 leavingcostNULL, 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 againstdevonce that is settled.