Engineering note · CCSwitcher · 2026-05-15

Aligning cost math with ccusage

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.

ToolsTools/recalc_cost.swift · Tools/verify_cost.sh Referenceryoppippi/ccusage 18.0.11 StatusVERIFIED 30 d

1 · Why we couldn't trust our own numbers

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.

Premise

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.

2 · What we expected — and what was actually there

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 assumedWhat'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.

3 · The bug that exposed the dedup rule

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.

Three rows, same conversation, two different totals In the JSONL, in chronological order: 12:29:06.639Z msg_011Rko… req_011CavnL… stream chunk 1 input=2 output=1 cache_create=11667 cache_read=0 → tokenTotal = 11670 12:29:17.498Z msg_011Rko… req_011CavnL… stream final input=2 output=548 cache_create=11667 cache_read=0 → tokenTotal = 12217 12:30:17.767Z msg_01Gfmo… req_011CavnQ… unrelated request input=1 output=680 cache_create=2032 cache_read=11667 → tokenTotal = 14380 Our first pass — max-tokenTotal wins dedup A vs B → keep B (out=548) sum: 548 + 680 = 1228 total tokens: 32614 → $0.0733 ccusage 18.0.11 — first-seen wins dedup A vs B → keep A (out=1) sum: 1 + 680 = 681 total tokens: 26050 → $0.0651
Figure 1. Rows A and B are the same conversational turn captured at two streaming snapshots. Whether dedup picks the earlier or later snapshot changes 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.

4 · The source-code reading that almost wasted a day

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.

Same JSONL → two ccusage versions → two different totals Input — three rows with the (msg_id, req_id) pair on rows A & B A: out=1 tokenTotal=11670 · B: out=548 tokenTotal=12217 · C: out=680 (different key) npm ccusage@18.0.11 isDuplicateEntry / markAsProcessed row A → not in set → keep, mark row B → already in set → SKIP row C → not in set → keep, mark output = 1 + 680 = 681 GitHub HEAD (unreleased) shouldReplaceEntryMetadata row A → no existing → keep row B → existing, total 12217 > 11670 → REPLACE row C → no existing → keep output = 548 + 680 = 1228
Figure 2. Two ccusage versions, exact same input, totals differ by 80%. The reference implementation isn't "ccusage in general" — it's the bundle that actually shipped to npm.
Takeaway

When reverse-engineering a tool, always read what's installed, not what's in main. The two can disagree on substance, not just style.

5 · File order matters because dedup is first-wins

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 four-stage pipeline, in order 1 · Recursive walk ~/.claude/projects/ **/*.jsonl includes subagents/ 2 · Sort earliest timestamp in each file, asc NOT filename order 3 · Parse + dedup global Set<hash> first-wins hash = msg.id : reqId 4 · Aggregate by (date, model) apply pricing LiteLLM Inside stage 3, processing one row: JSON-parsed row hash = msg.id : reqId hash in Set? (or hash == null) yes skip no, or null hash add to Set (if non-null); push entry Rows with missing message.id or requestId have hash = null and are never deduped — every occurrence is kept.
Figure 3. Stage 2 is the non-obvious one. Sorting by earliest timestamp is what makes the first-wins dedup deterministic across resume/fork scenarios where the same request appears in two files.

6 · Subagents live two directories deep

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.

On-disk layout — what gets missed by a one-level glob ~/.claude/projects/ -Users-joey-Code-CCSwitcher/ 094e0519-….jsonl ← parent session ✓ included 411df4b6-….jsonl ← parent session ✓ included 094e0519-…/ subagents/ agent-ab02835.jsonl ← subagent run ✗ was not included agent-c93af12.jsonl ← subagent run ✗ was not included
Figure 4. The recursive walk in stage 1 is what brings the red rows into the calculation. Their 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.

7 · Pricing comes from LiteLLM, with tiers

The pricing table in CostData.swift was a flat lookup: one rate per model. LiteLLM's table has two surprises:

claude-opus-4-7 · input pricing across the 200k threshold 0 200k 400k tokens $0 $1.00 $2.00 flat-rate model — what we used to compute tier boundary at 200k below 200k: $5 / 1M above 200k: $10 / 1M (≈ 2×) A 400k-token Opus request costs $3.00 on the tiered model vs $2.00 flat. A 50% under-count under-states our biggest bills.
Figure 5. Long-context Opus / Sonnet requests are exactly the cases where users care most about accurate cost — and exactly the cases the flat-rate model gets most wrong.

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.

8 · The final pipeline, end-to-end

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:

FileSystem walkJSONL recursive enumerator sortFilesBy… earliest timestamp parse + dedup global Set LiteLLM /tmp cache 1h enumerator(atPath:) ~/.claude/projects/**/*.jsonl [String] of file paths read each file's earliest timestamp files in ascending order fetch pricing JSON (if cache stale) For each file, each line: JSON.parse(line) hash = msg.id : reqId if hash in Set → skip else add hash, push entry compute cost via LiteLLM per-(date, model) aggregates
Figure 6. The whole script in seven message arrows. The pricing fetch is the one network call; everything else is local I/O over JSONL.

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.

9 · What would break if you removed each piece

Remove…SymptomSeverity
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

10 · Where to look in the repo

PathRole
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.