fix: use last streaming entry for output token count#108
Merged
Conversation
The transcript deduplication was taking the first entry per requestId, which carries a partial output_tokens count (1-7 tokens from the streaming start). The final entry has the real count. This caused a ~15% undercount of output tokens compared to native telemetry. Change from skip-if-seen to last-write-wins: store the last entry per requestId, then sum across all requestIds after reading the transcript.
Contributor
Author
Plugin vs Native Token Gap — Investigation SummaryAfter fixing the streaming dedup bug in this PR, I investigated the remaining token gap between the plugin and native Claude Code telemetry. Root causeThe transcript file does not record token usage for background API calls. Two types are missing:
Native tracing captures both as MagnitudeOn a real 29-turn Opus session ($19.30 total):
|
mosheshaham-dash0
approved these changes
Jun 4, 2026
SubagentStop events were silently dropped, losing 28-71% of session tokens. Route SubagentStop through sendLLMTrace, reading token usage from the sub-agent transcript file and emitting invoke_agent spans with gen_ai.agent.name, parented under the Agent tool call span.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
output_tokenscount (1–7 tokens from the streaming start). The last entry has the final count.output_tokens: 1while the last had the real value (100–1280).224,818reported vs263,699actual across one session). Input tokens and cache tokens were unaffected.Test plan
TestReadTurnUsageDeduplicatesRequestIDupdated to use differentoutput_tokensvalues across streaming entries (1 vs 150) and assert the final value is usedgo test ./...)claude_code.token.usagecounter