Repository navigation
Description
Summary
The Grok provider in codeburn does not read the turn_completed event's usage field that Grok CLI itself writes to the session file — the authoritative token count (inputTokens, outputTokens, cachedReadTokens, cacheCreationTokens). Instead it reconstructs an estimate from params._meta.totalTokens, a running counter present on other event types (mostly tool_call), using a threshold heuristic to detect new "segments". On a real, cache-heavy session this reconstruction captures roughly 1.4% of the real cache-read volume, and about 6% of total real tokens for the day.
This is not a regression — the same logic (and the same order-of-magnitude gap) is present in already-consolidated data from two prior days, just at a scale where it went unnoticed. It became visible today because of an unusually large, cache-heavy Grok run.
Environment
- codeburn
0.9.20(npmlatestas of 2026-08-10; installed via Homebrew, same bundle) - macOS (Darwin), arm64
- Provider: grok (Grok CLI 1.0.3, model
grok-4.6) - Session store: default
~/.grok/sessions(noGROK_HOMEoverride) - Session volume: 42 sessions with
summary.jsondated the same day, sizes 442 B–2.98 MB (well under the 128 MBreadSessionFilecap). 35 of 42 produce non-zero reconstructed tokens under the current heuristic; 7 are legitimately empty/no-op sessions (~499 B, correctly discarded by theinput === 0 && output === 0early-return).
Expected vs. actual
Expected: token/cost totals for a Grok session should reflect what Grok CLI itself reports as consumed for that session (the turn_completed.usage object), the same way other providers use their tool's own authoritative usage report where one exists.
Actual: codeburn ignores turn_completed.usage entirely for Grok and instead derives input/output/cache-read by watching _meta.totalTokens climb across unrelated event types and guessing turn boundaries from a total < prevTotal * 0.5 reset heuristic.
Evidence
Single-session example (one of several parallel subagent sessions from the same run), comparing the real turn_completed.usage event in that session's updates.jsonl against what codeburn's parser reconstructs from the same file:
Real (turn_completed.usage) |
codeburn (reconstructed) | Captured | |
|---|---|---|---|
| Input tokens | 12,851,663 | 523,200 | ~4% |
| Output tokens | 36,633 | 114,865 | (overcounts here) |
| Cache-read tokens | 12,092,032 | 0 | 0% |
Aggregate across all 35 sessions codeburn counted for the same day (summed from ~/.cache/codeburn/session-cache.v7.json, provider grok), against the real total independently computed by summing turn_completed.usage across every session file for the same day:
| Real (turn_completed.usage, summed) | codeburn (reconstructed, summed) | Captured | |
|---|---|---|---|
| Cache-read tokens | 316,576,384 | 4,553,597 | ~1.4% (undercounted) |
| Input tokens (fresh, non-cache) | 13,106,569 | 9,179,614 | ~70% (undercounted) |
| Output tokens | 1,195,656 | 6,151,771 | ~515% (overcounted ~5×) |
| Total | 330,878,609 | 19,884,982 | ~6% |
The error runs in both directions, not just one: cache-read is captured at only ~1.4% and fresh input at ~70% (both undercounted), while output is overcounted by roughly 5×. Cache-read is still the largest gap in absolute terms — it's the category the current heuristic has no real signal for at all, and it happens to be 95.7% of the real total on a cache-heavy agentic run (many parallel subagents sharing a long context) — but the parser's error is not confined to cache-read alone, and not all in the same direction.
Separately, cacheCreationInputTokens for the Grok provider's returned result object is hardcoded to 0, unconditionally, regardless of what the session actually contains.
Redacted session excerpt
The two events below are copied verbatim (field names and numeric values unchanged) from a real ~/.grok/sessions/<redacted>/<redacted>/updates.jsonl file, two consecutive lines near the end of one session — a tool_call event carrying the _meta.totalTokens counter the current parser reads, immediately followed by the turn_completed event carrying the authoritative usage object it ignores. Every string value that could identify a person, project, file, prompt, or tool argument has been replaced with <redacted>. Only protocol/schema field names, enum-like status values, and numeric fields are real.
{
"timestamp": 1786724676,
"method": "_x.ai/session/update",
"params": {
"sessionId": "<redacted>",
"update": {
"sessionUpdate": "tool_call",
"toolCallId": "<redacted>",
"title": "<redacted>",
"rawInput": {
"tool_name": "<redacted>",
"tool_input": {
"function": "<redacted>"
}
},
"_meta": {
"x.ai/tool": {
"version": 1,
"name": "<redacted>",
"kind": "<redacted>",
"namespace": "<redacted>",
"label": "<redacted>",
"read_only": false
}
}
},
"_meta": {
"totalTokens": 117025,
"eventId": "<redacted>",
"agentTimestampMs": 1786724676663,
"promptId": "<redacted>",
"streamStartMs": 1786724669368,
"turnStartMs": 1786720358061,
"updateType": "<redacted>",
"updateParams": {
"toolCallId": "<redacted>",
"title": "<redacted>",
"kind": "<redacted>",
"status": "<redacted>"
}
}
}
}{
"timestamp": 1786724773,
"method": "_x.ai/session/update",
"params": {
"sessionId": "<redacted>",
"update": {
"sessionUpdate": "turn_completed",
"prompt_id": "<redacted>",
"stop_reason": "cancelled",
"usage": {
"inputTokens": 12851663,
"outputTokens": 36633,
"totalTokens": 12888296,
"cachedReadTokens": 12092032,
"cacheCreationTokens": 0,
"reasoningTokens": 29077,
"modelCalls": 75,
"apiDurationMs": 693511,
"costUsdTicks": 125117780000,
"modelUsage": {
"grok-4.6-build": {
"inputTokens": 12851663,
"outputTokens": 36633,
"totalTokens": 12888296,
"cachedReadTokens": 12092032,
"cacheCreationTokens": 0,
"reasoningTokens": 29077,
"modelCalls": 75,
"apiDurationMs": 693511,
"costUsdTicks": 125117780000
}
},
"numTurns": 75
}
},
"_meta": {
"eventId": "<redacted>",
"agentTimestampMs": 1786724773589
}
}
}These two lines make the fix's premise concrete, not just abstract: the turn_completed event exists, is emitted by Grok CLI itself, and carries a complete usage object for the turn — inputTokens, outputTokens, cachedReadTokens, cacheCreationTokens, all present, all real. It sits two lines after the tool_call event the parser currently reads _meta.totalTokens from, in the exact same updates.jsonl file already being parsed — picking it up would require no new data source, no new file, no new event subscription, just a branch on sessionUpdate === "turn_completed". The parser never adds that branch. For how large the resulting gap actually is, see the aggregate table above (35 sessions, real totals against reconstructed totals).
Where this lives in the code
Working from the shipped bundle (npm/Homebrew [email protected], dist/main.js, which ships with a sourcemap, main.js.map) rather than a main checkout, so please treat these as pointers to re-locate in src/providers/grok.ts rather than exact git blame-able line numbers — the bundle line numbers won't match a fresh clone:
- Session dir resolution —
defaultSessionsDir2(),main.js:12900-12903: resolves$GROK_HOME/sessionsor~/.grok/sessions. Confirmed correct; not the issue. - Session discovery —
discoverSessions4(),main.js:13015: registersupdates.jsonlper session, provider"grok". Confirmed correct; not the issue. - Token reconstruction —
parseUpdates(),main.js:12920, invoked fromcreateParser20(),main.js:12973: readsupdates.jsonlin full (non-streaming), and for each event readsparams._meta.totalTokensoff event types liketool_call. It never branches onupdate.sessionUpdate === "turn_completed"to readupdate.usage. The segment-boundary heuristic istotal < prevTotal * 0.5⇒ new segment, previous segment's peak becomesinputFresh; output is estimated from per-turn first/last values;cacheRead = sumFirst - inputFresh. - Same area:
cacheCreationInputTokens: 0is written into the returned object unconditionally. - Cost calculation from these (already-wrong) numbers —
calculateCost(),main.js:974, called withmodel = summary.current_model_id ?? signals?.primaryModelId ?? "grok-build".
Reproduction
- Run Grok CLI (tested on 1.0.3) on a session with heavy prompt-cache reuse — e.g. a long multi-turn agentic task, or several parallel subagent sessions sharing a large system/context prefix. This maximizes
cachedReadTokensrelative to fresh input. - Open the resulting
~/.grok/sessions/<cwd-url-encoded>/<uuid>/updates.jsonland find theturn_completedline; itsparams.update.usageobject is Grok CLI's own authoritative count for the turn. - Run
codeburn report --provider grok(or inspect~/.cache/codeburn/session-cache.v7.jsonfor that session) and compare its reconstructed input/output/cacheRead against step 2. - Expect a large gap concentrated in cache-read, growing with how cache-heavy the session is.
Suggested fix
In parseUpdates, add a branch for update.sessionUpdate === "turn_completed" that reads update.usage.{inputTokens, outputTokens, cachedReadTokens, cacheCreationTokens, reasoningTokens} directly as the source of truth for that turn, falling back to the current _meta.totalTokens heuristic only when the event is absent (e.g. very old sessions predating Grok CLI writing it).
Offer
The redacted excerpt above already covers the tool_call → turn_completed pair. Happy to go further if it helps: more surrounding events from the same session (additional tool_call/hook_execution context), a less-redacted version of a specific field in private if the exact shape of something matters, or to sanity-check a candidate fix against my own session data. Not committing to sending a PR myself, but willing to if that's useful and the approach above is agreed first, per CONTRIBUTING.md.
Environment: codeburn 0.9.20 (npm), macOS, Node (Homebrew-managed), Grok CLI 1.0.3, model grok-4.6.
Activity
fix(grok): drop the per-model split, clamp reasoning, price the whole…
fix(grok): read the CLI's own completed-turn usage instead of estimat…
test(grok): pin the unpriced-model branch instead of inheriting it fr…
avs-io commentedon Aug 21, 2026
Shipped as #1015 (
72aad9e). Grok now prefersturn_completed.usageover the totalTokens heuristic. Not rebuilding. Remaining estimate path is only for older CLI logs that never wrote the event.saulcanina commentedon Aug 23, 2026
Ran the verification on a real corpus before seeing this was closed. Posting the
numbers for the record, since I don't think the fix has been measured end to end
on a large cache-heavy corpus yet.
Setup: macOS, Node v26.7.0. Baseline 0.9.20 (Homebrew). Candidate
main@e12fb39built from source, run with an isolatedCODEBURN_CACHE_DIRand thereal
HOME. Corpus: 372 session dirs under~/.grok/sessions, 184 of themcarrying
turn_completedrecords (404 records), the rest empty scaffolds with nousage. Data actually spans 2026-07-23 → 2026-08-20.
Ground truth parsed straight from the session files,
turn_completed.usage,deduped by
prompt_idlast-wins:main@e12fb39inputTokens,outputTokensandcacheReadTokensall match ground truthexactly, to the token. Cache-read alone goes from 27.49M to 570.83M, and it
was 93.95% of real consumption, and that was the whole issue.
Two things worth recording beyond the headline:
(15.26M vs 1.26M net) while under-counting input and cache. So historical
output-heavy readings were wrong in the other direction.
is not a Grok problem and not caused by this fix: the report/sessions/overview
totals read
totalOutputTokensalone for every provider that reportsreasoning separately, while the models and audit reports already add it back
through
billableOutputTokens. Filed separately as Reports drop Grok reasoning tokens; optimize double-counts them for codex/copilot after #1078 #1115.Session counts line up too: the candidate reports 184/184 in overview and detail
and correctly leaves out the empty scaffolds.
Thanks to @ozymandiashh for the fix.