Our daily-cost display didn't match ccusage's. Tracking down why uncovered a dead JSONL field, a dedup bug that double-counted ~70 requests, and the surprise that ccusage's published npm release runs a different algorithm than the source on its own GitHub HEAD.
CCSwitcher already showed a "today's cost" banner. The math was hand-rolled: walk ~/.claude/projects/*.jsonl, sum usage.input_tokens and friends per assistant row, multiply by a hard-coded Anthropic price table. It looked right, but every time the user spot-checked it against ccusage daily, the numbers were off — sometimes by a few percent, sometimes by ten or more.
Rather than guess at the discrepancy or "calibrate" with a fudge factor, the decision was to treat ccusage as ground truth: re-implement the math from scratch in an isolated Swift script, diff it against ccusage row-by-row, and only port the answer back into the app once the two agreed to the cent.
If our number disagrees with ccusage, the user trusts ccusage. So we don't ship "approximately" — we either match exactly or we don't display cost at all.
The starting mental model was simple: the JSONL files contain a costUSD field, ccusage just sums it, and our app should do the same. Three things turned out to be wrong about that picture before we even reached the algorithm.
| What we assumed | What's actually true |
|---|---|
JSONL rows carry costUSD — we just read it. |
Out of 4,669 assistant rows in a recent 5-day window, exactly 1 had a costUSD field. Claude Code stopped writing it. Cost must be computed from tokens. |
| Pricing comes from Anthropic's published rates. | Anthropic doesn't publish structured pricing. ccusage pulls from LiteLLM's model_prices_and_context_window.json at runtime — the community-maintained source of truth for Claude pricing. |
| One assistant row = one billable request, sum them all. | Streamed requests produce multiple rows with the same (message.id, requestId), and session resume can write the same request across multiple files. Without dedup, ~70 requestIds in our local data appeared in two places. |
So the real algorithm has three load-bearing parts the simple picture missed: a pricing fetcher, a dedup pass, and an awareness of how the JSONL is actually structured on disk.
The clearest discrepancy was on 2026-05-11. Only claude-sonnet-4-6 traffic that day — three assistant rows total, two of them streaming chunks of the same request. ccusage reported 681 output tokens. Our first-pass implementation said 1228.
output_tokens by 547 — a 2× swing on the day's sonnet bill.Both interpretations are defensible. Max-tokenTotal feels obviously correct ("keep the final, complete row"). First-seen feels arbitrary but is what the published ccusage actually does. Our job wasn't to decide which one is right — it was to match what the user's reference tool produces.
Reading ccusage's GitHub source confirmed the algorithm — and pointed at the wrong one.
The latest data-loader.ts on main has a helper called shouldReplaceEntryMetadata that takes a candidate row and an existing row and returns true if the candidate has a higher tokenTotal. The dedup loop calls this helper to decide whether to replace. By the source, max-tokenTotal wins. That matched our implementation. But the empirical output didn't.
The puzzle resolved when we looked at the actual file installed by npx ccusage@latest: a compiled bundle at ~/.npm/_npx/…/dist/data-loader-9ESMosno.js. The published version doesn't ship shouldReplaceEntryMetadata at all. It ships a simpler pair:
function isDuplicateEntry(uniqueHash, processedHashes) {
if (uniqueHash == null) return false;
return processedHashes.has(uniqueHash);
}
function markAsProcessed(uniqueHash, processedHashes) {
if (uniqueHash != null) processedHashes.add(uniqueHash);
}
That's pure first-wins dedup against a single global Set. No tokenTotal comparison, no replacement. The newer algorithm exists in main but hasn't been released to npm yet. Whichever ccusage version users actually run is what they'll compare us to, so the published bundle wins.
When reverse-engineering a tool, always read what's installed, not what's in main. The two can disagree on substance, not just style.
If dedup were max-tokenTotal, the order files are visited wouldn't matter — the same row would always win. With first-wins, order is load-bearing: whichever file is opened first plants its row into the global processedHashes set, and any later file holding the same key is silently dropped.
ccusage sorts files by the earliest timestamp inside each file, not by filename. The intuition: a session that began earlier should claim its own rows, even if a later-named file happens to contain a streamed snapshot of the same request.
The original SessionParseCache only globbed direct .jsonl children of each project dir. Subagent logs — generated whenever Claude Code spawns a child agent — live at ~/.claude/projects/<project>/<sessionUUID>/subagents/agent-*.jsonl, two levels deeper. They were silently invisible to our cost calculation.
requestIds do not collide with the parent session's, so adding them is purely additive once global dedup is in place.Worth noting: across all projects there are ~70 requestIds that appear in both a top-level file and some subagent file globally. They're not subagent-vs-parent of the same session — they're session-resume artifacts where the same request was written to two different top-level files. Without the global dedup step from §5, including the subagent files would have double-counted them. With it, it's safe.
The pricing table in CostData.swift was a flat lookup: one rate per model. LiteLLM's table has two surprises:
*_above_200k_tokens fields in the LiteLLM JSON.provider_specific_entry.fast multiplier.The flat-rate price table in CostData.swift is still good enough for small requests (most users, most days) but undercounts the precise scenario users notice: a single huge codebase analysis or a multi-hour debugging session. Matching LiteLLM closes that gap.
Once all of §3–§7 were understood, the corrected algorithm came together in roughly 200 lines of Swift (Tools/recalc_cost.swift). The sequence below is what runs on every invocation:
Diffed against ccusage daily --since 20260416 --json across the last 30 days — 50 distinct (date, model) rows, $1,888 of spend — every input/output/cache_create/cache_read count matches exactly, and every per-row cost agrees to four decimal places. The verification is wired up as Tools/verify_cost.sh and is expected to run before every release.
$ Tools/verify_cost.sh 30
[1/3] Running our reparser on the last 30 days...
→ 65 (date × model) rows written to /tmp/ccswitcher-verify-cost/ours.json
[2/3] Running latest ccusage (npx -y ccusage@latest)...
→ ccusage 18.0.11, 26 days written to /tmp/ccswitcher-verify-cost/ccusage.json
[3/3] Diffing...
date ours $ ccusage $ Δ
--------------------------------------------------
2026-05-15 130.5558 130.5558 +0.0000
2026-05-13 7.1925 7.1925 +0.0000
... (24 more rows, all +0.0000) ...
--------------------------------------------------
TOTAL 1888.4245 1888.4245 +0.0000
All (date × model × {4 token types, cost}) match within tolerance.
PASS — safe to release.
| Remove… | Symptom | Severity |
|---|---|---|
Global dedup on (message.id, requestId) |
~70 resume-duplicated requests across the user's history get double-counted. Streamed assistant rows balloon further — a single 30-chunk stream over-counts 30×. Daily cost drifts ~10–80% high. | HIGH |
| First-wins tiebreak (use max-tokenTotal instead) | Diverges from the published ccusage bundle on every streamed request. Numbers look reasonable but never match the user's reference tool. | HIGH |
| Sort files by earliest timestamp | When the same (messageId, requestId) appears in two files (session resume), the "winner" becomes non-deterministic — depends on filesystem enumeration order. Numbers fluctuate between runs. |
MEDIUM |
Recursive walk including subagents/ |
All cost from subagent runs (Codex review, Plan, Explore, etc.) silently disappears. Heavy users of subagents see numbers half their actual spend. | HIGH |
| LiteLLM pricing source | The hard-coded table eventually drifts from Anthropic's actual prices (LiteLLM lags official changes by hours, our table by months). Worse, the 200k tier is missing — long-context requests undercount by ~50%. | MEDIUM |
| 200k tiered pricing | Heavy-context Opus / Sonnet requests under-counted by ~50%. Most affects users who do long debugging sessions or large codebase reviews — the loudest segment. | MEDIUM |
Pre-release verify_cost.sh step |
Future ccusage release silently changes its algorithm (as the HEAD-vs-published gap implies will happen). We ship a divergence. Users notice and lose trust. | HIGH |
| Path | Role |
|---|---|
Tools/recalc_cost.swift |
Standalone Swift script — the single place where the algorithm is implemented in isolation and verified against ccusage. Treat this as the canonical reference. |
Tools/verify_cost.sh |
One-shot pre-release check. Runs the recalc script against npx ccusage@latest and exits non-zero on any disagreement. |
CCSwitcher/Services/SessionParseCache.swift |
The in-app version the UI consumes. Must mirror recalc_cost.swift's algorithm. PORTING PENDING |
CCSwitcher/Models/CostData.swift → ModelPricing |
The app's pricing table. Currently flat-rate; should track LiteLLM (incl. 200k tiers) once the port lands. |
COST_VERIFICATION.md |
Process spec — when to verify, what to do on failure, what changed in ccusage. Updated whenever the upstream algorithm shifts. |