Skip to content

Grok provider undercounts tokens by ~98% on cache-read: parser reconstructs from a heuristic instead of reading the authoritative turn_completed.usage event #998

Closed

Description

@saulcanina

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 (npm latest as 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 (no GROK_HOME override)
  • Session volume: 42 sessions with summary.json dated the same day, sizes 442 B–2.98 MB (well under the 128 MB readSessionFile cap). 35 of 42 produce non-zero reconstructed tokens under the current heuristic; 7 are legitimately empty/no-op sessions (~499 B, correctly discarded by the input === 0 && output === 0 early-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/sessions or ~/.grok/sessions. Confirmed correct; not the issue.
  • Session discovery — discoverSessions4(), main.js:13015: registers updates.jsonl per session, provider "grok". Confirmed correct; not the issue.
  • Token reconstruction — parseUpdates(), main.js:12920, invoked from createParser20(), main.js:12973: reads updates.jsonl in full (non-streaming), and for each event reads params._meta.totalTokens off event types like tool_call. It never branches on update.sessionUpdate === "turn_completed" to read update.usage. The segment-boundary heuristic is total < prevTotal * 0.5 ⇒ new segment, previous segment's peak becomes inputFresh; output is estimated from per-turn first/last values; cacheRead = sumFirst - inputFresh.
  • Same area: cacheCreationInputTokens: 0 is written into the returned object unconditionally.
  • Cost calculation from these (already-wrong) numbers — calculateCost(), main.js:974, called with model = summary.current_model_id ?? signals?.primaryModelId ?? "grok-build".

Reproduction

  1. 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 cachedReadTokens relative to fresh input.
  2. Open the resulting ~/.grok/sessions/<cwd-url-encoded>/<uuid>/updates.jsonl and find the turn_completed line; its params.update.usage object is Grok CLI's own authoritative count for the turn.
  3. Run codeburn report --provider grok (or inspect ~/.cache/codeburn/session-cache.v7.json for that session) and compare its reconstructed input/output/cacheRead against step 2.
  4. 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

  1. avs-io commented on Aug 21, 2026

    @avs-io
    Collaborator

    Shipped as #1015 (72aad9e). Grok now prefers turn_completed.usage over the totalTokens heuristic. Not rebuilding. Remaining estimate path is only for older CLI logs that never wrote the event.

  2. saulcanina commented on Aug 23, 2026

    @saulcanina
    Author

    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 @
    e12fb39 built from source, run with an isolated CODEBURN_CACHE_DIR and the
    real HOME. Corpus: 372 session dirs under ~/.grok/sessions, 184 of them
    carrying turn_completed records (404 records), the rest empty scaffolds with no
    usage. Data actually spans 2026-07-23 → 2026-08-20.

    Ground truth parsed straight from the session files, turn_completed.usage,
    deduped by prompt_id last-wins:

    tokens % of truth
    ground truth 607,588,697 100%
    0.9.20 62,029,363 10.21%
    main @ e12fb39 604,957,355 99.57%

    inputTokens, outputTokens and cacheReadTokens all match ground truth
    exactly, 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:

    • The old heuristic was not uniformly low. It over-counted output by ~12x
      (15.26M vs 1.26M net) while under-counting input and cache. So historical
      output-heavy readings were wrong in the other direction.
    • The remaining 0.43% gap equals the reasoning volume to the exact token. That
      is not a Grok problem and not caused by this fix: the report/sessions/overview
      totals read totalOutputTokens alone for every provider that reports
      reasoning 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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions