aiinfra-tools 0.2.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (160) hide show
  1. package/CHANGELOG.md +268 -0
  2. package/README.md +27 -3
  3. package/bin/aiinfra.mjs +5 -2
  4. package/bin/report.mjs +177 -0
  5. package/fleetops/README.md +33 -1
  6. package/fleetops/deploy/shadow-gate/argo-analysistemplate.yaml +34 -0
  7. package/fleetops/deploy/shadow-gate/argo-rollout-example.yaml +38 -0
  8. package/fleetops/deploy/shadow-gate/flagger-canary.yaml +34 -0
  9. package/fleetops/deploy/shadow-gate/judge.yaml +51 -0
  10. package/fleetops/deploy/shadow-gate/llmd-canary-example.yaml +35 -0
  11. package/fleetops/deploy/shadow-gate/podmonitor-vllm.yaml +20 -0
  12. package/fleetops/deploy/shadow-live/README.md +41 -0
  13. package/fleetops/deploy/shadow-live/kit.yaml +123 -0
  14. package/fleetops/deploy/shadow-live/load-canary.yaml +26 -0
  15. package/fleetops/deploy/shadow-live/run.sh +53 -0
  16. package/fleetops/docs/ADMISSION.md +9 -9
  17. package/fleetops/docs/FABRIC-STORAGE.md +1 -1
  18. package/fleetops/docs/SERVING.md +11 -1
  19. package/fleetops/docs/SHADOW.md +250 -0
  20. package/fleetops/docs/SIGNALS.md +5 -2
  21. package/fleetops/docs/WORKLOADS.md +1 -1
  22. package/fleetops/package.json +7 -4
  23. package/fleetops/src/adapters/fabric.mjs +19 -7
  24. package/fleetops/src/adapters/live.mjs +38 -5
  25. package/fleetops/src/adapters/logs.mjs +10 -7
  26. package/fleetops/src/adapters/nvsentinel.mjs +95 -0
  27. package/fleetops/src/adapters/topology.mjs +53 -1
  28. package/fleetops/src/admission.mjs +26 -18
  29. package/fleetops/src/api.mjs +2 -1
  30. package/fleetops/src/bundle.mjs +3 -0
  31. package/fleetops/src/calibrate.mjs +1 -1
  32. package/fleetops/src/detect.mjs +1 -1
  33. package/fleetops/src/export.mjs +5 -1
  34. package/fleetops/src/goodput.mjs +0 -2
  35. package/fleetops/src/incidents.mjs +1 -2
  36. package/fleetops/src/ingest.mjs +10 -3
  37. package/fleetops/src/inject.mjs +2 -2
  38. package/fleetops/src/live.mjs +2 -1
  39. package/fleetops/src/llmd.mjs +7 -3
  40. package/fleetops/src/optimize.mjs +1 -1
  41. package/fleetops/src/power.mjs +7 -7
  42. package/fleetops/src/procure.mjs +67 -0
  43. package/fleetops/src/rca.mjs +1 -1
  44. package/fleetops/src/rollout.mjs +1 -1
  45. package/fleetops/src/schema.mjs +3 -2
  46. package/fleetops/src/security.mjs +1 -1
  47. package/fleetops/src/serving.mjs +32 -10
  48. package/fleetops/src/shadow-canary.mjs +74 -0
  49. package/fleetops/src/shadow-gate.mjs +49 -0
  50. package/fleetops/src/shadow-prom.mjs +205 -0
  51. package/fleetops/src/shadow-replay.mjs +147 -0
  52. package/fleetops/src/shadow.mjs +291 -0
  53. package/fleetops/src/stats.mjs +14 -0
  54. package/fleetops/src/traces.mjs +0 -5
  55. package/fleetops/tests/fixtures/real/README.md +5 -0
  56. package/fleetops/tools/admit-node.sh +51 -16
  57. package/fleetops/tools/amd-admit.py +111 -0
  58. package/fleetops/tools/cmd/calibrate.mjs +61 -0
  59. package/fleetops/tools/cmd/capacity.mjs +116 -0
  60. package/fleetops/tools/cmd/common.mjs +32 -0
  61. package/fleetops/tools/cmd/data.mjs +343 -0
  62. package/fleetops/tools/cmd/help.mjs +243 -0
  63. package/fleetops/tools/cmd/incidents.mjs +216 -0
  64. package/fleetops/tools/cmd/rollout.mjs +122 -0
  65. package/fleetops/tools/cmd/server.mjs +122 -0
  66. package/fleetops/tools/cmd/serving.mjs +95 -0
  67. package/fleetops/tools/cmd/shadow.mjs +204 -0
  68. package/fleetops/tools/cmd/training.mjs +79 -0
  69. package/fleetops/tools/collect.sh +6 -1
  70. package/fleetops/tools/fleetops.mjs +18 -1308
  71. package/fleetops/tools/loop-demo.mjs +1 -1
  72. package/fleetops/tools/workload-profile.mjs +0 -1
  73. package/fleetscope/README.md +5 -1
  74. package/fleetscope/build.mjs +4 -0
  75. package/fleetscope/dist/index.html +1013 -28
  76. package/fleetscope/docs/AGENTIC.md +89 -0
  77. package/fleetscope/docs/PLANNING.md +4 -2
  78. package/fleetscope/docs/VALIDATION-AGENTIC.md +37 -0
  79. package/fleetscope/package.json +4 -3
  80. package/fleetscope/src/agentic.js +288 -0
  81. package/fleetscope/src/ask.js +0 -1
  82. package/fleetscope/src/cluster-ui.js +1 -0
  83. package/fleetscope/src/engine.js +29 -13
  84. package/fleetscope/src/index.src.html +15 -5
  85. package/fleetscope/src/inference-ui.js +1 -0
  86. package/fleetscope/src/ingest.js +89 -3
  87. package/fleetscope/src/optimize.js +11 -5
  88. package/fleetscope/src/plan.js +1 -1
  89. package/fleetscope/src/training-ui.js +1 -0
  90. package/fleetscope/tools/agentic.mjs +148 -0
  91. package/fleetscope/tools/tracelab-data.mjs +27 -0
  92. package/gpu-health/README.md +13 -2
  93. package/gpu-health/docs/CONFIG.md +29 -1
  94. package/gpu-health/package.json +7 -4
  95. package/gpu-health/src/actions.mjs +16 -3
  96. package/gpu-health/src/analyze.mjs +3 -0
  97. package/gpu-health/src/config.mjs +3 -0
  98. package/gpu-health/src/executors.mjs +9 -4
  99. package/gpu-health/src/health.mjs +1 -1
  100. package/gpu-health/src/ingest.mjs +27 -3
  101. package/gpu-health/src/platforms.mjs +109 -0
  102. package/gpu-health/src/vendors.mjs +12 -5
  103. package/gpu-health/tools/gpu-health.mjs +6 -4
  104. package/gpu-ledger/README.md +3 -1
  105. package/gpu-ledger/package.json +12 -4
  106. package/gpu-ledger/src/adapters.mjs +3 -2
  107. package/gpu-ledger/src/cloud.mjs +104 -0
  108. package/gpu-ledger/src/core.mjs +12 -10
  109. package/gpu-ledger/tools/ledger.mjs +8 -2
  110. package/harness-ledger/README.md +152 -0
  111. package/harness-ledger/docs/FORMATS.md +114 -0
  112. package/harness-ledger/docs/METHOD.md +133 -0
  113. package/harness-ledger/docs/VALIDATION-ECONOMICS.md +59 -0
  114. package/harness-ledger/docs/VALIDATION-SWEBENCH.md +26 -0
  115. package/harness-ledger/docs/VALIDATION-TRACELAB.md +56 -0
  116. package/harness-ledger/package.json +19 -0
  117. package/harness-ledger/src/demo.mjs +115 -0
  118. package/harness-ledger/src/economics.mjs +184 -0
  119. package/harness-ledger/src/gpu.mjs +80 -0
  120. package/harness-ledger/src/html.mjs +63 -0
  121. package/harness-ledger/src/importers.mjs +247 -0
  122. package/harness-ledger/src/ledger.mjs +128 -0
  123. package/harness-ledger/src/opencost.mjs +55 -0
  124. package/harness-ledger/src/outcomes.mjs +67 -0
  125. package/harness-ledger/src/prices.mjs +75 -0
  126. package/harness-ledger/src/record.mjs +52 -0
  127. package/harness-ledger/src/waste.mjs +136 -0
  128. package/harness-ledger/tools/harness-ledger.mjs +199 -0
  129. package/harness-ledger/tools/validate-economics.mjs +69 -0
  130. package/harness-ledger/tools/validate-swebench.mjs +57 -0
  131. package/harness-ledger/tools/validate-tracelab.mjs +74 -0
  132. package/hybrid-tracing/package.json +4 -3
  133. package/hybrid-tracing/tools/fix-skew.mjs +1 -1
  134. package/inference-sizer/README.md +5 -1
  135. package/inference-sizer/build.mjs +1 -0
  136. package/inference-sizer/dist/index.html +299 -31
  137. package/inference-sizer/docs/ACCELERATORS.md +62 -0
  138. package/inference-sizer/docs/CATALOG.md +71 -0
  139. package/inference-sizer/docs/METHOD.md +1 -1
  140. package/inference-sizer/docs/VALIDATION-INFERENCEX.md +37 -0
  141. package/inference-sizer/package.json +4 -3
  142. package/inference-sizer/src/accelerators.js +194 -0
  143. package/inference-sizer/src/catalog.js +55 -22
  144. package/inference-sizer/src/fit-ui.js +1 -1
  145. package/inference-sizer/src/index.src.html +3 -0
  146. package/inference-sizer/src/model.js +45 -7
  147. package/inference-sizer/src/ui.js +1 -1
  148. package/inference-sizer/tools/validate-agentx.mjs +116 -0
  149. package/inference-sizer/tools/validate-inferencex.mjs +132 -0
  150. package/mcp/README.md +6 -1
  151. package/mcp/server.mjs +34 -0
  152. package/package.json +10 -6
  153. package/schemas/README.md +3 -0
  154. package/schemas/aiinfra.report.schema.json +474 -0
  155. package/schemas/commands.mjs +14 -0
  156. package/schemas/fleetops.shadow.canary.schema.json +96 -0
  157. package/schemas/fleetops.shadow.compare.schema.json +266 -0
  158. package/schemas/fleetops.shadow.prom.schema.json +354 -0
  159. package/schemas/harness-ledger.economics.schema.json +567 -0
  160. package/schemas/sizer.list.schema.json +15 -2
@@ -0,0 +1,152 @@
1
+ # harness-ledger
2
+
3
+ Where agent harnesses waste model resources, across harnesses. It reads what Claude Code, Codex, and any harness
4
+ instrumented with OpenTelemetry or Langfuse already write. It turns each model call into one shared record. Then it
5
+ reports, per harness, session, tool and model, which tokens, dollars and GPU-seconds needn't have been spent, why,
6
+ and what to change.
7
+
8
+ ```
9
+ node tools/harness-ledger.mjs demo # three harnesses and a vLLM fleet, synthetic
10
+ node tools/harness-ledger.mjs scan --since 7d # your own Claude Code and Codex logs on this machine
11
+ node tools/harness-ledger.mjs report traces/ --engine vllm-traces.json --replicas replicas.json --html report.html
12
+ ```
13
+
14
+ ```
15
+ harness-ledger: 77 model calls in 6 sessions from claude-code, codex, langgraph-support
16
+ tokens 3.46M (input 3.44M, of which from cache 2.95M = 86%; output 19.6k)
17
+ cost $2.32 (77/77 calls priced; example prices (pass --prices); 21 by GPU time)
18
+ avoidable $0.7623 (33% of cost): 401.8k tokens of work at full price, 2.15M of context re-read from cache
19
+ outcomes: 5 succeeded, 1 failed ($0.0763 spent on failed tasks); cost per successful task $0.4648
20
+
21
+ Where it goes, by cause:
22
+ cost full-price re-read count
23
+ $0.3465 170.5k 0 3 Context re-sent without a cache hit
24
+ $0.2640 76.5k 0 1 Cache expired during a pause
25
+ $0.0781 1790 169.0k 3 Retrying a failing tool
26
+ $0.0493 117.5k 1.74M 5 Oversized tool output carried forward
27
+ …
28
+ ```
29
+
30
+ ## Why across harnesses works
31
+
32
+ Every harness differs in its logs, but they all make the same thing: model calls, each with tokens in (some from
33
+ cache), tokens out, the tools it asked for, and what those tools returned. One importer per harness converts its
34
+ format into that `llm_call` record. The waste checks and the cost join only read `llm_call`, so a new harness is one
35
+ importer. Token meanings are normalized on the way in: Anthropic's `input_tokens` excludes cache reads, while
36
+ OpenAI's and OpenTelemetry's include them. See [FORMATS.md](docs/FORMATS.md).
37
+
38
+ | Reads | From | What it gets |
39
+ |---|---|---|
40
+ | Claude Code | `~/.claude/projects/*/*.jsonl` | every request's usage with cache reads and writes, tool calls, tool result sizes and errors, subagents |
41
+ | Codex CLI / IDE | `~/.codex/sessions/**/rollout-*.jsonl` | per-response usage with cached input and reasoning, shell and tool calls, outputs, exit codes, subagents and forks |
42
+ | OpenTelemetry GenAI | OTLP JSON, or one span per line | `chat` spans' usage, `gen_ai.tool.definitions` (tools offered), `execute_tool` spans, `invoke_agent` names: Copilot, Gemini CLI, OpenAI Agents SDK, LangGraph and others through OpenLLMetry or OpenInference |
43
+ | OpenInference | same | `llm.token_count.*`, `llm.tools.N`, TOOL spans (Arize Phoenix, LlamaIndex, CrewAI, DSPy) |
44
+ | Langfuse | observation export | GENERATION usage and cost, TOOL observations, sessions |
45
+ | TraceLab | `syfi_coding_trace.jsonl.gz` (streamed) | the public trace of 8,058 Claude Code and Codex sessions: cache accounting, timing, tool names, result sizes, errors |
46
+ | vLLM (`--engine`) | OTLP `llm_request` spans | per-request prefill and decode time per replica, to charge self-hosted calls GPU time |
47
+
48
+ ## What counts as waste
49
+
50
+ | Cause | What happened | Fix it with |
51
+ |---|---|---|
52
+ | Context re-sent without a cache hit | the next call's prefix wasn't read from the prompt cache: the system prompt changed (timestamps, per-call IDs, reordered tools), history was edited, or nothing marked it cacheable | a byte-stable prefix, append-only history, cache breakpoints |
53
+ | Cache expired during a pause | the same, after a pause longer than the cache lifetime | 1-hour cache writes for slow tools and human pauses |
54
+ | Cache writes nobody read | write premium paid for a prefix no later call used | don't cache the last turn of one-shot subagents |
55
+ | Oversized tool output carried forward | a tool returned far more than a summary would, and every later call re-sent it | cap, paginate or summarize tool output; delegate reading to a subagent |
56
+ | Same tool call repeated | identical tool and arguments again in a session | memoize read-only tools; tell the agent nothing changed |
57
+ | Retrying a failing tool | three or more calls in a row with the same tool failing | stop after two, surface the error, make error messages actionable |
58
+ | Failed model calls | errored calls that used tokens | fix oversize requests, rate limits, timeouts |
59
+ | Tool definitions never used | tools sent with every call that the session never called | load tools on demand, tool search |
60
+ | Routing calls on a large model (candidate) | short single-tool steps on a model whose price file names a cheaper one; counted only if it saves after the cheaper model re-reads the context uncached | route them, after checking task success |
61
+
62
+ Each finding carries its tokens (split into work at full price and context re-read from cache), its cost at that
63
+ call's own prices, and the evidence. Causes can overlap on one call. Their cost is capped at what the call cost, so
64
+ the total avoidable never exceeds the bill. The method, the thresholds and what each check can't see are in
65
+ [METHOD.md](docs/METHOD.md).
66
+
67
+ ## Cost: list prices, recorded cost, or GPU time
68
+
69
+ - **Hosted APIs.** `--prices` gives $ per million tokens per model, with cache read and write prices. The built-in
70
+ table holds a few example models so the report reads out of the box. It's labelled as examples: pass yours. Calls
71
+ on models not in the table are counted and listed as unpriced.
72
+ - **Recorded cost.** When a harness logged its own cost (Claude Code `costUSD`, OpenInference `llm.cost.total`,
73
+ Langfuse cost), that cost is used.
74
+ - **Self-hosted models.** `--engine` takes the serving engine's OTLP traces. vLLM writes them with
75
+ `--otlp-traces-endpoint`. `--replicas` gives each pod's GPUs and $/GPU-hour, or takes gpu-ledger usage records and
76
+ its price file. A call is matched to its engine request through W3C trace context (the engine span's parent is the
77
+ harness's chat span), or by trace and time. A replica's busy GPU time is split across its requests by time in the
78
+ model. Idle time between requests is reported per replica and not charged to any harness. The waste checks then
79
+ price prefill and decode in GPU dollars, so a cache miss costs what its prefill cost on the GPUs.
80
+
81
+ `--outcomes` (session → success/failure, JSON or CSV) adds cost on failed tasks and **cost per successful task**,
82
+ the number to compare harnesses and configurations by.
83
+
84
+ ## Unit economics: cost per resolved task, and self-hosting vs the API
85
+
86
+ ```
87
+ harness-ledger economics ~/.claude/projects --outcomes outcomes.csv
88
+ harness-ledger economics traces/ --outcomes outcomes.csv --self-host-model deepseek-v3 --gpu H200 \
89
+ --self-host-success-rate 0.70 --gpu-rate 3
90
+ ```
91
+
92
+ `economics` turns the waste report into numbers a budget owner can use:
93
+ - **Cost per resolved task:** the spend over the sessions that succeeded (`--outcomes`), and the share of spend that
94
+ went to tasks that failed.
95
+ - **Fixes, ranked:** each waste cause's avoidable spend, per resolved task, and the cost per resolved task after it.
96
+ Also a step cap on sessions, computed exactly from each session's own calls, and the successes it would cost.
97
+ - **Self-hosting vs the API:** the same workload sized with the Inference Sizer for an open model on a GPU, through
98
+ FleetScope's agentic path (real arrivals, prompt growth, cache reuse, the KV working set). It is sized for the busiest
99
+ day's peak and kept on all month.
100
+ - The result is a break-even: the GPU-hour price under which self-hosting is cheaper per resolved task (scaled by the
101
+ two models' success rates). With `--gpu-rate`, it also gives the volume from which self-hosting wins.
102
+ - `--opencost FILE|URL` (OpenCost's `/inferenceCost/total`) or `--opencost-prom URL` (its `llm_cost_per_million_tokens`
103
+ gauges) uses OpenCost's measured self-host cost per token instead. Its price per delivered input token is turned into
104
+ a price per prefilled token, so a workload with a different cache hit rate is priced right. `--self-host-price` takes
105
+ prices by hand.
106
+ - `--calibration FILE` sizes with measured engine efficiencies, from `fleetops calibrate` or from a promoted shadow
107
+ upgrade's `<store>/calibration/sizer.json`.
108
+ - `--kv-offload` holds the part of the KV working set that doesn't fit in HBM in host memory (LMCache-style; 375 GB per
109
+ GPU by default, the 3 TB per 8-GPU server InferenceX AgentX allows; `--cpu-kv-gb` changes it). A returning session's
110
+ cached prefix is reloaded over PCIe (`--pcie-gbs`, 64 by default, at 70% of it). Offload is only used when that
111
+ reload fits the TTFT target and the peak minute's reloads leave PCIe under 80% busy. The what-if is reported either
112
+ way, so you can see what offload would save before turning it on.
113
+ - Tokens per megawatt (AgentX's headline metric) is reported next to the GPU count: the peak minute's output tokens/s
114
+ over the provisioned power, from the published per-node power, or the GPU's board power when none is published.
115
+ - Calls longer than the open model's context are counted and flagged.
116
+
117
+ On TraceLab's workload, with SWE-bench success rates ([VALIDATION-ECONOMICS.md](docs/VALIDATION-ECONOMICS.md)):
118
+ - **One team:** at about $5,600 a month of API spend at Sonnet-class prices, self-hosting DeepSeek V3 or Kimi K2 pays
119
+ only below about $0.25–0.50 a GPU-hour. Two whole nodes (one serving, one spare) are the floor at any load.
120
+ - **Pooled teams:** at $3 a GPU-hour on B200 it wins from about 8–16× that volume.
121
+ - **Context:** half the calls exceed those models' 128k context.
122
+
123
+ ## On real data
124
+
125
+ - **Real coding-agent use** ([VALIDATION-TRACELAB.md](docs/VALIDATION-TRACELAB.md)). On TraceLab (8,058 Claude Code
126
+ and Codex sessions, 665k calls, in relative prices):
127
+ - 22% of spend was avoidable.
128
+ - 76% of that was prompt caches expiring during pauses, 18% was misses inside the cache lifetime, and 5% was
129
+ oversized tool output.
130
+ - Oversized tool output is a third of all the context re-read from cache.
131
+ - Claude Code's cache hit rate falls from 98% to 48% once a pause passes five minutes.
132
+ - **Cost per successful task** ([VALIDATION-SWEBENCH.md](docs/VALIDATION-SWEBENCH.md)). On SWE-bench Verified runs of
133
+ one scaffold across 11 models:
134
+ - the median run spends 39% of its budget on tasks it doesn't resolve;
135
+ - a call cap that loses at most a point of resolution rate saves about 1%;
136
+ - among models within 5 points of the best rate, cost per resolved task differs 10×.
137
+
138
+ `harness-ledger outcomes` runs this on any outcome-labelled runs.
139
+
140
+ ## Privacy
141
+
142
+ Transcripts can hold anything: code, secrets, customer data. The `llm_call` record keeps only counts, model and
143
+ tool names, and SHA-256 hashes of tool arguments (for spotting repeats). It never keeps prompt, completion, argument
144
+ or tool-output text. A tool output's size is measured and then dropped. `harness-ledger import --out calls.jsonl`
145
+ gives you a file that is safe to share or to send to a central place, and `report` reads it like the raw logs.
146
+
147
+ ## Where it fits
148
+
149
+ [gpu-ledger](../gpu-ledger/) says which teams' GPUs were useful, idle or lost. harness-ledger goes one level up, to
150
+ which agent steps used the model work those GPUs did. With `--engine`, the two meet: harness call → engine request →
151
+ replica → GPUs → $. [fleetops](../fleetops/) stores the engine spans (`fleetops data import otlp-traces`), and
152
+ [hybrid-tracing](../hybrid-tracing/) fixes clock skew between harness and engine hosts when their traces disagree.
@@ -0,0 +1,114 @@
1
+ # Formats
2
+
3
+ What each importer reads and how it maps to `llm_call`. Files are detected by name and content. `--format
4
+ claude-code|codex|otel|openinference|langfuse` forces a format. `.gz` files are read too.
5
+
6
+ ## The record
7
+
8
+ ```json
9
+ { "kind": "llm_call", "t": 1764000000.5, "harness": "claude-code", "session": "…", "agent": "main", "id": "msg_…|req_…",
10
+ "model": "claude-sonnet-4-5-20250929", "provider": "anthropic",
11
+ "input": 41210, "cacheRead": 40100, "cacheWrite": 1106, "output": 212,
12
+ "toolCalls": [{ "name": "Read", "id": "toolu_…", "argHash": "3f1c…", "resultTokens": 2210 }] }
13
+ ```
14
+
15
+ `input` includes cached tokens (the OpenTelemetry meaning). `cacheRead`/`cacheWrite` are null when the source
16
+ doesn't report cache. Optional: `parent`, `traceId`, `spanId`, `reasoning`, `toolsOffered`, `toolDefTokens`,
17
+ `finish`, `error`, `durS`, `costUSD`, `outcome`. A tool call's `error` is true when the tool failed.
18
+
19
+ ## Claude Code
20
+
21
+ Session transcripts, one JSON object per line, in `~/.claude/projects/<project>/<session>.jsonl` (or under
22
+ `$CLAUDE_CONFIG_DIR`).
23
+
24
+ - `type: "assistant"` lines with `message.usage`: `input_tokens` (excludes cache), `cache_read_input_tokens`,
25
+ `cache_creation_input_tokens`, `output_tokens`. `input` = the sum of the three.
26
+ - Claude Code writes a line per content block of a response, each repeating the usage. Lines with the same
27
+ `message.id` and `requestId` are one call.
28
+ - `tool_use` blocks are the call's tool calls. `tool_result` blocks in later `type: "user"` lines give each result's
29
+ size and `is_error`.
30
+ - `isSidechain: true` lines (subagents) become session `<sessionId>:<agentId>`, with `parent` = the session.
31
+ - `costUSD`, when present, is the recorded cost. API error lines (`isApiErrorMessage`) become failed calls.
32
+
33
+ ## Codex
34
+
35
+ Rollouts in `~/.codex/sessions/YYYY/MM/DD/rollout-<time>-<id>.jsonl` (or under `$CODEX_HOME`).
36
+
37
+ - `session_meta`: the session id, and for subagents and forks the parent (`source.subagent.thread_spawn.parent_thread_id`
38
+ or `forked_from_id`).
39
+ - `turn_context.model`: the model for the calls that follow.
40
+ - Usage: `token_usage_record` lines (one per response, by `response_id`; lines a fork copied from its parent carry
41
+ the parent's `thread_id` and are skipped), or, in rollouts without them, `event_msg` `token_count` events
42
+ (`info.last_token_usage`). A snapshot that repeats the previous total is the same call. `input_tokens` includes
43
+ `cached_input_tokens`; `reasoning_output_tokens` is part of output.
44
+ - `response_item` `function_call` / `custom_tool_call` / `local_shell_call` are tool calls, assigned to the next usage
45
+ event. Their `*_output` items give result size; `metadata.exit_code` ≠ 0 or `success: false` is an error.
46
+
47
+ ## OpenTelemetry GenAI
48
+
49
+ OTLP/JSON bodies (`{"resourceSpans": …}`), arrays of them, or one span per line (as the OTel JS file exporter and
50
+ Copilot write them). Span times may be nanosecond strings, `[seconds, nanos]` or ISO.
51
+
52
+ | Span | Recognized by | Read |
53
+ |---|---|---|
54
+ | model call | `gen_ai.operation.name` = `chat`, `text_completion`, `generate_content` | `gen_ai.usage.input_tokens` (includes cache), `gen_ai.usage.cache_read.input_tokens`, `gen_ai.usage.cache_write.input_tokens`, `gen_ai.usage.output_tokens`, `gen_ai.usage.reasoning.output_tokens`, `gen_ai.response.model` / `request.model`, `gen_ai.provider.name`, `gen_ai.conversation.id`, `gen_ai.tool.definitions`, `gen_ai.response.finish_reasons`, `error.type` |
55
+ | tool | `execute_tool` | `gen_ai.tool.name`, `gen_ai.tool.call.id`, `gen_ai.tool.call.arguments` (hashed), `gen_ai.tool.call.result` (size only), status ERROR |
56
+ | agent | `invoke_agent` | `gen_ai.agent.name`, inherited by the calls under it |
57
+
58
+ A tool span is assigned to the latest model call in its trace that ended before the tool started. The harness name
59
+ is `service.name` unless `--harness` is given. Argument and result content is opt-in in OTel instrumentations; when
60
+ it's off, repeats and output sizes can't be checked, and the rest still can.
61
+
62
+ To get these spans: Gemini CLI, Copilot,
63
+ the OpenAI Agents SDK and Strands emit GenAI spans. LangChain/LangGraph, LlamaIndex, CrewAI and others do through
64
+ OpenLLMetry or OpenInference instrumentations. Point the exporter at a collector with a file exporter, or at
65
+ fleetops' OTLP endpoint, and give harness-ledger the file. (Claude Code's own OTel export,
66
+ `CLAUDE_CODE_ENABLE_TELEMETRY=1`, sends metrics and events rather than GenAI spans; read its transcripts instead.)
67
+
68
+ ## OpenInference
69
+
70
+ The same files, with `openinference.span.kind`. LLM spans: `llm.token_count.prompt` (includes
71
+ `prompt_details.cache_read` and `cache_write`), `llm.token_count.completion`, `completion_details.reasoning`,
72
+ `llm.model_name`, `llm.provider`, `session.id`, `llm.tools.<i>.tool.name` / `tool.json_schema`, `llm.cost.total`.
73
+ TOOL spans: `tool.name`, `input.value` (hashed), `output.value` (size only).
74
+
75
+ ## Langfuse
76
+
77
+ Observation exports: a JSON array, `{"data": […]}` from the public API, JSON lines, or traces with nested
78
+ `observations`.
79
+
80
+ - GENERATION: `usageDetails` (or `usage`). Canonical keys exclude cache: `input` + `input_cached_tokens` (or
81
+ `cache_read_input_tokens`) + `input_cache_creation`. OpenAI-style `prompt_tokens` includes cache. `model`,
82
+ `calculatedTotalCost` / `costDetails.total`, `level: ERROR`, tools from `modelParameters.tools`, tool calls from
83
+ `output.tool_calls` (names and argument hashes only).
84
+ - TOOL observations: tool calls, assigned to the latest generation in the trace that ended before them, with output
85
+ size and `level: ERROR`.
86
+ - Session: `sessionId` (from the observation or its trace), else the trace.
87
+
88
+ ## TraceLab
89
+
90
+ The UW SyFI coding-agent trace ([github.com/uw-syfi/TraceLab](https://github.com/uw-syfi/TraceLab), CC BY 4.0), one
91
+ model call per line, streamed (650 MB inflated):
92
+ - **Usage:** `input_tokens_total` (includes cache); Claude rows have `claude_cache_read_input_tokens` and
93
+ `claude_cache_creation_input_tokens`; Codex rows have `prefix_tokens` (cached input).
94
+ - **Timing:** the call starts at its last input event (user message or tool result) and ends at its last model event.
95
+ - **Tools:** `tools[]` has names, `result_chars` (counted at 4 characters per token) and `is_error`. There are no
96
+ arguments, so repeated tool calls can't be checked.
97
+
98
+ ## Outcomes
99
+
100
+ `--outcomes` file: `{ "<session>": "success" | "failure" }`, SWE-bench `per_instance_details.json` (`resolved`), a JSON array of `{ session, outcome }`, or CSV
101
+ `session,outcome`. `pass`, `resolved`, `true` and `1` read as success; `fail`, `error`, `abandoned`, `false` and `0`
102
+ as failure. A subagent session takes its parent's outcome.
103
+
104
+ ## Engine spans and replicas
105
+
106
+ `--engine`: OTLP traces from the serving engine. vLLM: start it with `--otlp-traces-endpoint` and
107
+ `--collect-detailed-traces model` for prefill and decode times. `--replicas`:
108
+
109
+ ```json
110
+ { "vllm-llama70b-0": { "gpus": 4, "gpuType": "H100", "rate": 2.5 } }
111
+ ```
112
+
113
+ or gpu-ledger usage records (`name`, `gpus`, `gpuType`, optional `rate`), with `--gpu-prices` in gpu-ledger's price
114
+ format for those without a rate.
@@ -0,0 +1,133 @@
1
+ # Method
2
+
3
+ How harness-ledger decides what was avoidable and what it cost. The code is `src/waste.mjs`, `src/prices.mjs` and
4
+ `src/gpu.mjs`; the defaults below are `DEFAULTS` in `waste.mjs` and can be changed with the CLI flags shown.
5
+
6
+ ## Sessions and chains
7
+
8
+ A session is one harness conversation: a Claude Code session file (each subagent is its own session, with the main
9
+ session as `parent`), a Codex rollout, an OTel `gen_ai.conversation.id` (or OpenInference `session.id`, or the trace
10
+ when neither is set), a Langfuse session. Within a session, calls on one model form a **chain**. Side calls on other
11
+ models, such as a small model writing a title, run their own chain, because a prompt cache belongs to one model.
12
+
13
+ A **compaction** is a call whose input is less than half the previous call's in its chain. The context was rewritten
14
+ on purpose, so it isn't a cache miss, and nothing before it is carried past it.
15
+
16
+ ## The checks
17
+
18
+ **Cache misses and expiries.** In an agent loop each call's context is the previous call's context plus the reply
19
+ and tool results, so the previous call's input is a prefix that a prompt cache should serve. For each call after the
20
+ first in a chain:
21
+
22
+ ```
23
+ prefix = min(previous input, this input)
24
+ missed = prefix − this call's cache reads
25
+ ```
26
+
27
+ It is a finding when `missed` is at least 1,024 tokens and 2% of the prefix (below that, cache block rounding and
28
+ small edits explain it). It's `cache-expired` when the gap since the previous call is longer than the cache lifetime
29
+ (`--cache-ttl`, 300 s: Anthropic's default cache and OpenAI's in-memory retention are minutes), else `cache-miss`.
30
+ Cost: missed tokens at what they were billed (cache-write price for the part re-written, input price for the rest),
31
+ minus what they'd have cost as cache reads. Calls without cache reporting (`cacheRead` null: some OTel
32
+ instrumentations) are skipped, and the report says how many calls reported cache.
33
+
34
+ What it can't see: a harness that never enabled caching looks like a miss on every call (which it is, from the
35
+ bill's point of view); a provider whose cache is shared across sessions can serve a first call from cache, which is
36
+ not counted as a saving.
37
+
38
+ **Unread cache writes.** A call that wrote to cache at a premium (cache-write price above input price) where no
39
+ later call in the chain read from cache within the lifetime. Cost: the premium. The last call of every session does
40
+ this; on one-shot subagents it adds up.
41
+
42
+ **Oversized tool output.** A tool result above `--big-result` (8,000 tokens). The part above 1,500 tokens (what a
43
+ summary or a capped output would take) is avoidable in the call that received it and in each later call that carried
44
+ it (until a compaction). Tokens: excess × (1 + calls carried). Cost: the excess at input price once, then at
45
+ cache-read price for each carry when the harness reports cache (input price when it doesn't). Tool output sizes are
46
+ estimated at 4 characters per token; transcripts don't hold the tokenizer's count for them.
47
+
48
+ **Repeated tool calls.** The same tool with the same arguments (compared by hash) within the last 25 tool calls of
49
+ the session, when the earlier one didn't fail. Tokens: the repeat's result, carried as above, plus the call's output
50
+ share. Tools that are meant to repeat (to-do lists, plans, questions to the user) are ignored. A repeat can be
51
+ deliberate (re-running tests after an edit), so the report names the tools: read it as "look here".
52
+
53
+ **Error loops.** A run of three or more consecutive calls in a session whose tool calls all failed, with the same
54
+ tool. The first two are a try and a retry; every call after them is avoidable in full.
55
+
56
+ **Failed calls.** A model call that returned an error but still reported tokens.
57
+
58
+ **Unused tool definitions.** When the request's tool definitions are logged (OTel `gen_ai.tool.definitions`,
59
+ OpenInference `llm.tools`, Langfuse tools), the share of their tokens belonging to tools the session never called, on
60
+ every call. Mostly cache reads, so cheap per call, but they fill context on every turn. Claude Code and Codex don't
61
+ log the definitions they send, so this check needs OTel or Langfuse input.
62
+
63
+ **Model tier (candidate).** A call with at most 300 output tokens, one tool call and no reasoning, on a model whose
64
+ price entry names a `downshift` model. It is counted only when the cheaper model would cost less even after
65
+ prefilling the whole context uncached, since the cache doesn't move with the model. These are reported apart and not
66
+ added to the avoidable total: a cheaper model needs a check that tasks still succeed.
67
+
68
+ ## Overlap
69
+
70
+ A call can have several findings: a bloated tool result can be re-sent without a cache hit. For each call, the
71
+ findings' cost is scaled down so their sum never exceeds the call's cost. The token counts of findings about the
72
+ call's own input (cache, failures, loops, tool definitions) are capped the same way. Carried tool output is counted
73
+ across later calls by design.
74
+
75
+ ## Prices
76
+
77
+ Per call, the first that applies:
78
+
79
+ 1. **GPU time** for a call matched to an engine request with a priced replica (below).
80
+ 2. **Recorded cost**: the harness logged a cost. When the model is also in the price table, the table's per-token
81
+ prices are scaled so the call's cost matches the recorded one. Otherwise the recorded cost is spread with typical
82
+ ratios (cache read 0.1×, cache write 1.25×, output 5× input).
83
+ 3. **Price table**: `--prices`, matched on the model id or a prefix of it (`claude-sonnet-4-5` matches
84
+ `claude-sonnet-4-5-20250929`; provider prefixes like `anthropic/` are dropped).
85
+
86
+ Otherwise the call is unpriced. Its tokens still count, and the report lists the models to add.
87
+
88
+ ## GPU time for self-hosted models
89
+
90
+ 1. **Engine requests.** Spans carrying `gen_ai.latency.e2e` or named `llm_request` (vLLM's request span), with
91
+ queue, prefill and decode times and the replica from `k8s.pod.name` (or host, server address, service).
92
+ 2. **Matching.** The engine span whose parent is the harness's chat span, when trace context was propagated. Else
93
+ the first unmatched engine request in the same trace that started no earlier than a second before the call.
94
+ 3. **Busy cost.** Per replica, busy time is the union of its requests' intervals. Batched requests overlap, so they
95
+ share it. Busy cost = GPUs × $/GPU-h × busy time, split over the replica's requests by time in the model (prefill +
96
+ decode, or end-to-end when the split is missing). The time between the replica's first and last request that isn't
97
+ busy is **idle cost**, reported per replica and left out of the harness's cost (gpu-ledger counts it as idle).
98
+ 4. **Per-token prices.** A call's prefill cost spread over its prefilled tokens (input not served from the prefix
99
+ cache), and its decode cost over its output tokens. Cache reads cost 0. A cache miss then costs the prefill the
100
+ prefix cache would have skipped.
101
+
102
+ ## Outcomes
103
+
104
+ `harness-ledger outcomes` reads runs whose tasks have a cost, a call count and an outcome: SWE-bench per-instance
105
+ results, or tasks as JSON/CSV. Per run it reports:
106
+ - cost per task and per successful task;
107
+ - the share of spend on failed tasks;
108
+ - calls per successful and per failed task;
109
+ - a curve of call caps: for each cap N, every task is stopped at N calls. Each call is charged the task's average
110
+ cost, and a success that needed more than N calls counts as lost. That is a conservative estimate, because later
111
+ calls carry more context and cost more.
112
+
113
+ The cap reported is the one that saves the most while losing at most one point of success rate.
114
+
115
+ ## Validation
116
+
117
+ - Token accounting matches ccusage on ccusage's own Codex fixtures: a subagent rollout (1,010 tokens) and a fork
118
+ that copies its parent's history (16,000 non-cached input, 4,000 cached, 200 output). The fixtures are in
119
+ `tests/fixtures` with ccusage's MIT license.
120
+ - Field names follow the OpenTelemetry GenAI registry (`gen_ai.usage.cache_read.input_tokens` and
121
+ `cache_write.input_tokens` are included in `gen_ai.usage.input_tokens`) and the OpenInference spec
122
+ (`llm.token_count.prompt_details.cache_read`/`cache_write`, `llm.tools.<i>.tool.*`).
123
+ - The checks are tested on constructed sessions with known answers (`tests/harness.test.mjs`). The demo plants one
124
+ example of each cause in three harnesses' native formats and checks they're all found, the GPU cost adds up, and no
125
+ text from the inputs reaches the output.
126
+
127
+ - On real use: TraceLab's 8,058 Claude Code and Codex sessions ([VALIDATION-TRACELAB.md](VALIDATION-TRACELAB.md)).
128
+ The cache-expired check rests on the measured hit rate by pause length. Changing the cache lifetime from 5 to 60
129
+ minutes and the oversized-output threshold from 8k to 20k tokens moves the avoidable total by one point; it changes
130
+ which cause the waste is labelled with, not how much there is.
131
+ - Outcomes: SWE-bench Verified runs of mini-SWE-agent 2.x across 11 models ([VALIDATION-SWEBENCH.md](VALIDATION-SWEBENCH.md)).
132
+
133
+ No real trace yet combines per-call usage with task outcomes, so the waste checks haven't been scored against success.
@@ -0,0 +1,59 @@
1
+ # Agent unit economics: self-hosting vs the API, on a real agent workload
2
+
3
+ Generated by `node harness-ledger/tools/validate-economics.mjs --markdown`. Workload: [TraceLab](https://github.com/uw-syfi/TraceLab) v0.0.2 (CC BY 4.0; Zhu et al., TraceLab: Characterizing Coding Agent Workloads for LLM Serving, arXiv:2606.30560 (2026)), 303 days of day-to-day Claude Code and Codex use: 26.6 sessions and 2,193 model calls a day, with real arrivals, prompt growth and each provider's cache accounting. Task success and calls per task: SWE-bench Verified, mini-SWE-agent 2.x, one run per model (SWE-bench experiments at `40f164d5b8f1`).
4
+
5
+ API cost is in relative units (fresh input 1, cache read 0.1, cache write 1.25, output 5 per million tokens) at **$3 per unit**, a Sonnet-class list price for fresh input; that comes to about $5,619 a month. The self-hosted side is the same workload sized by the Inference Sizer through FleetScope's agentic path (compute and the KV working set, at TTFT 2 s and TPOT 50 ms, for the busiest day's peak, whole 8-GPU nodes plus one spare) and kept on all month. Cost per resolved task scales by each model's SWE-bench resolution rate against Claude 4.5 Sonnet (high) (71%).
6
+
7
+ ## The GPU-hour price under which self-hosting is cheaper
8
+
9
+ | Open model (SWE-bench resolved) | GPU | Calls per task vs the API model | GPUs: busiest day / typical day | **Break-even $/GPU-hour** | Calls over the model's context |
10
+ | --- | --- | --- | --- | --- | --- |
11
+ | DeepSeek V3.2 (high) (70%) | H200 | same | 16 / 16 | **$0.47** | 51% |
12
+ | DeepSeek V3.2 (high) (70%) | H200 | 1.83× (SWE-bench calls ratio) | 16 / 16 | **$0.47** | 51% |
13
+ | DeepSeek V3.2 (high) (70%) | B200 | same | 16 / 16 | **$0.47** | 51% |
14
+ | DeepSeek V3.2 (high) (70%) | B200 | 1.83× (SWE-bench calls ratio) | 16 / 16 | **$0.47** | 51% |
15
+ | Kimi K2.5 (high) (71%) | H200 | same | 32 / 32 | **$0.24** | 51% |
16
+ | Kimi K2.5 (high) (71%) | H200 | 1.06× (SWE-bench calls ratio) | 32 / 32 | **$0.24** | 51% |
17
+ | Kimi K2.5 (high) (71%) | B200 | same | 16 / 16 | **$0.48** | 51% |
18
+ | Kimi K2.5 (high) (71%) | B200 | 1.06× (SWE-bench calls ratio) | 16 / 16 | **$0.48** | 51% |
19
+
20
+ ## The volume at which self-hosting wins, at a stated GPU-hour price
21
+
22
+ Volume as a multiple of this workload. "Own bursts" scales the trace as it is (its busiest day had about 46× its median day's calls); "typical" sizes on a median day's shape, as many teams' bursts that don't line up would look.
23
+
24
+ | Open model | GPU | Calls per task | $2/GPU-h: own bursts / typical | $3/GPU-h: own bursts / typical | $4/GPU-h: own bursts / typical |
25
+ | --- | --- | --- | --- | --- | --- |
26
+ | DeepSeek V3.2 (high) | H200 | same | 22.6× / 5.7× | never (to 256×) / 8.0× | never (to 256×) / 16.0× |
27
+ | DeepSeek V3.2 (high) | H200 | 1.83× | never (to 256×) / 8.0× | never (to 256×) / 16.0× | never (to 256×) / 128.0× |
28
+ | DeepSeek V3.2 (high) | B200 | same | 5.7× / 5.7× | 11.3× / 8.0× | 22.6× / 11.3× |
29
+ | DeepSeek V3.2 (high) | B200 | 1.83× | 11.3× / 5.7× | never (to 256×) / 8.0× | never (to 256×) / 11.3× |
30
+ | Kimi K2.5 (high) | H200 | same | 22.6× / 11.3× | 64.0× / 16.0× | never (to 256×) / 22.6× |
31
+ | Kimi K2.5 (high) | H200 | 1.06× | 22.6× / 11.3× | 128.0× / 16.0× | never (to 256×) / 22.6× |
32
+ | Kimi K2.5 (high) | B200 | same | 11.3× / 5.7× | 16.0× / 8.0× | 32.0× / 11.3× |
33
+ | Kimi K2.5 (high) | B200 | 1.06× | 11.3× / 5.7× | 22.6× / 8.0× | 32.0× / 11.3× |
34
+
35
+ ## What it says
36
+
37
+ - **At one team's volume the API wins.** Self-hosting a frontier-size open model needs at least two whole nodes (one serving, one spare) whatever the load, so at this workload's volume it is cheaper only below the GPU-hour prices above, far under the $2–4 used in the volume table.
38
+ - **The crossover is a volume, and bursts move it.** On B200 at $3/GPU-hour self-hosting wins from about 11.3× this volume with this team's bursts, or 8.0× if peaks were flatter. Pooling many teams onto one fleet is what makes self-hosting pay.
39
+ - **Calls per task move the crossover, not the floor.** On SWE-bench DeepSeek V3.2 makes 1.83× the calls per task of Claude 4.5 Sonnet (high). At one team's volume that changes nothing (the two-node floor carries it); at the volumes where self-hosting could win it pushes the crossover out, because the open model has to serve that many more calls for the same work.
40
+ - **Context is a hard limit, not a cost.** 51% of this workload's calls are longer than DeepSeek V3's or Kimi K2's 128k context. They are capped here, which flatters self-hosting: those sessions would need compaction, or a model with a longer context.
41
+
42
+ ## Fixes before any of this
43
+
44
+ Avoidable spend in this workload (relative units, as in VALIDATION-TRACELAB.md), worth doing whichever way the model is served:
45
+
46
+ | Fix | Share of spend |
47
+ | --- | --- |
48
+ | Cache expired during a pause | 17% |
49
+ | Context re-sent without a cache hit | 3.9% |
50
+ | Oversized tool output carried forward | 1.0% |
51
+ | Cache writes nobody read | 0.3% |
52
+ | Retrying a failing tool | 0.0% |
53
+
54
+ ## Limits
55
+
56
+ - TraceLab has no task outcomes, so cost per resolved task uses SWE-bench resolution rates, from a different (benchmark) workload with one scaffold.
57
+ - The open model is assumed to make as many calls per task as the API model unless a row says otherwise; the SWE-bench calls ratio is a proxy measured on a benchmark, with calls of the same shape.
58
+ - Self-hosted cost is GPUs only (no power, staff or networking beyond the GPU-hour price), and the sizer's production defaults (whole nodes, one spare). `--no-spare` drops the spare.
59
+
@@ -0,0 +1,26 @@
1
+ # Cost per successful task on SWE-bench Verified
2
+
3
+ Generated by `node harness-ledger/tools/validate-swebench.mjs --markdown`. Data: per-instance results (cost, API calls, resolved) of 11 runs of mini-SWE-agent 2.x on SWE-bench Verified's 500 tasks, one run per model, from the [SWE-bench experiments repository](https://github.com/SWE-bench/experiments) at commit `40f164d5b8f1`. Skipped for missing outcomes or costs: 20260226_mini-v2.0.0_gemini-3-pro-high, 20260901_mini-v2.4.2_gemini-3-5-flash. Same scaffold and tasks, so the differences are the models'.
4
+
5
+ | Model | Resolved | Cost per task | **Cost per resolved task** | Spend on unresolved tasks | Calls: resolved / unresolved (mean) | Best call cap losing ≤1 point |
6
+ | --- | --- | --- | --- | --- | --- | --- |
7
+ | GPT 5 mini | 56% | $0.047 | **$0.084** | 54% | 18 / 23 | 40 calls: 2% saved, 0.4 pts lost |
8
+ | MiniMax M2.5 (high) | 76% | $0.073 | **$0.097** | 38% | 54 / 80 | 150 calls: 3% saved, 1.0 pts lost |
9
+ | Kimi K2.5 (high) | 71% | $0.147 | **$0.207** | 42% | 46 / 63 | 125 calls: 3% saved, 0.8 pts lost |
10
+ | Gemini 3 Flash (high) | 76% | $0.356 | **$0.470** | 28% | 55 / 61 | 125 calls: 0% saved, 0.0 pts lost |
11
+ | Claude 4.5 Haiku (high) | 67% | $0.331 | **$0.497** | 45% | 59 / 79 | 125 calls: 3% saved, 1.0 pts lost |
12
+ | DeepSeek V3.2 (high) | 70% | $0.448 | **$0.640** | 40% | 83 / 102 | 200 calls: 1% saved, 0.6 pts lost |
13
+ | GPT 5.2 (high) | 73% | $0.474 | **$0.651** | 38% | 32 / 43 | 75 calls: 2% saved, 0.6 pts lost |
14
+ | Claude 4.6 Opus | 76% | $0.552 | **$0.730** | 39% | 26 / 39 | 100 calls: 1% saved, 0.2 pts lost |
15
+ | GLM 5 (high) | 73% | $0.534 | **$0.734** | 42% | 67 / 100 | 200 calls: 1% saved, 0.8 pts lost |
16
+ | Claude 4.5 Sonnet (high) | 71% | $0.658 | **$0.921** | 37% | 45 / 57 | 100 calls: 1% saved, 0.8 pts lost |
17
+ | Claude 4.5 Opus (high) | 77% | $0.754 | **$0.982** | 36% | 30 / 43 | 75 calls: 1% saved, 0.0 pts lost |
18
+
19
+ ## What it says
20
+
21
+ - **Failed tasks take a large share of the spend.** The median run spends 39% of its budget on tasks it doesn't resolve. That is the number "cost per task" hides and "cost per resolved task" shows.
22
+ - **Failures don't stand out early by length.** Unresolved tasks take 1.34× the calls of resolved ones (median across runs). A cap on calls that loses at most one point of resolution rate saves a median of 1%. Stopping failures early needs a signal other than step count (repeated failing tool calls, no progress on tests).
23
+ - **The model is the big lever.** Among the runs within 5 points of the best resolution rate, cost per resolved task ranges from $0.097 (MiniMax M2.5 (high), 76%) to $0.982 (Claude 4.5 Opus (high), 77%): 10×. List prices and how many calls and tokens each model needs both count. Costs are as the runs recorded them (API list prices at the time).
24
+
25
+ Cap estimates assume every call of a task costs the task's average. Later calls carry more context and cost more, so real savings from a cap are somewhat larger than shown; a resolved task that needed more calls than the cap is counted as lost.
26
+
@@ -0,0 +1,56 @@
1
+ # harness-ledger on real coding-agent use (TraceLab)
2
+
3
+ Generated by `node harness-ledger/tools/validate-tracelab.mjs --markdown`. Data: [TraceLab](https://github.com/uw-syfi/TraceLab) v0.0.2 (CC BY 4.0; Zhu et al., TraceLab: Characterizing Coding Agent Workloads for LLM Serving, arXiv:2606.30560 (2026)): 8,058 sessions and 665,453 model calls of day-to-day Claude Code and Codex use, with each provider's own cache accounting and the tool calls (names, result sizes, errors). Costs are in relative units (`--prices relative`: fresh input 1, cache read 0.1, cache write 1.25, output 5 per million tokens), so harnesses and models compare on the same footing; real prices change the scale, not the shape.
4
+
5
+ **22% of the spend was avoidable.** 114.57B tokens were processed, 96% of input from the prompt cache. The avoidable part is 3.92B tokens processed at full price and 35.62B tokens of context re-read from cache.
6
+
7
+ | Cause | Share of avoidable cost | Findings | Tokens at full price | Context re-read |
8
+ | --- | --- | --- | --- | --- |
9
+ | Cache expired during a pause | 76% | 12,330 | 2.80B | 0 |
10
+ | Context re-sent without a cache hit | 18% | 29,744 | 772.6M | 0 |
11
+ | Oversized tool output carried forward | 4.6% | 12,156 | 347.1M | 35.56B |
12
+ | Cache writes nobody read | 1.5% | 19,910 | 0 | 0 |
13
+ | Retrying a failing tool | 0.2% | 550 | 694.3k | 57.9M |
14
+
15
+ | Harness | Sessions | Avoidable share of its cost | Input from cache |
16
+ | --- | --- | --- | --- |
17
+ | claude-code | 5,319 | 26% | 95% |
18
+ | codex | 2,739 | 14% | 96% |
19
+
20
+ ## The prompt cache after a pause
21
+
22
+ Share of calls that read at least 90% of the previous context from cache, by the pause before the call (contexts over 4k tokens; compactions excluded):
23
+
24
+ | Pause | claude-code | codex |
25
+ | --- | --- | --- |
26
+ | under 60 s | 99% (259,443) | 97% (327,248) |
27
+ | 60 s–5 min | 98% (26,345) | 86% (17,014) |
28
+ | 5 min–10 min | 48% (6,134) | 73% (3,347) |
29
+ | 10 min–30 min | 51% (3,828) | 62% (2,962) |
30
+ | 30 min–60 min | 63% (1,446) | 37% (880) |
31
+ | over 60 min | 1.4% (1,911) | 8.5% (1,231) |
32
+
33
+ Claude Code's hit rate falls by about half once the pause passes five minutes (the default cache lifetime) and to almost nothing after an hour; Codex decays more gradually. That is what the cache-expired check measures: pauses where the context had to be prefilled again. Whether all of it is avoidable depends on what keeping the cache costs: a one-hour cache write is priced at 2× input against 1.25× for five minutes, which pays back on the first re-read after a pause of 5–60 minutes.
34
+
35
+ ## Tools behind the oversized output
36
+
37
+ | Tool | Results over the threshold | Context re-read because of them |
38
+ | --- | --- | --- |
39
+ | exec_command | 5,112 | 1.72B |
40
+ | Read | 3,483 | 9.44B |
41
+ | exec | 1,832 | 18.70B |
42
+ | write_stdin | 959 | 363.0M |
43
+ | view_image | 585 | 5.58B |
44
+ | shell_command | 97 | 50.6M |
45
+ | wait | 34 | 23.6M |
46
+ | Agent | 12 | 9.4M |
47
+
48
+ ## How much the thresholds matter
49
+
50
+ With a one-hour cache lifetime instead of five minutes, and 20k tokens instead of 8k as the oversized-output threshold, the avoidable share is 21% (vs 22%): most of what was "expired" is then counted as plain cache misses, and fewer tool results count as oversized. The total barely moves; which label it gets depends on what you assume the provider's cache lifetime is.
51
+
52
+ ## What this trace can't show
53
+
54
+ - TraceLab records tool names and result sizes but not arguments, so repeated tool calls can't be detected.
55
+ - It doesn't record the tool definitions sent with each call (unused tools) or task outcomes (cost per successful task); see VALIDATION-SWEBENCH.md for outcomes.
56
+
@@ -0,0 +1,19 @@
1
+ {
2
+ "name": "harness-ledger",
3
+ "version": "0.4.0",
4
+ "license": "Apache-2.0",
5
+ "private": true,
6
+ "description": "Where agent harnesses waste model resources, across harnesses: cache misses, bloated tool output, repeats, retries, unused tools; in tokens, dollars and GPU time.",
7
+ "type": "module",
8
+ "bin": {
9
+ "harness-ledger": "tools/harness-ledger.mjs"
10
+ },
11
+ "scripts": {
12
+ "test": "node --test tests/*.test.mjs",
13
+ "demo": "node tools/harness-ledger.mjs demo",
14
+ "test:coverage": "node --test --experimental-test-coverage --test-coverage-exclude='tests/**' --test-coverage-exclude='../**' --test-coverage-lines=94 --test-coverage-branches=80 tests/*.test.mjs"
15
+ },
16
+ "engines": {
17
+ "node": ">=22"
18
+ }
19
+ }