Repository navigation
fix(ai-vault): stop double counting Copilot token usage in History - #50764
Conversation
Copilot session.shutdown modelMetrics already report complete input and output totals: cache reads/writes are included in inputTokens and reasoning tokens are part of outputTokens, while currentTokens is the context-window size. Count input + output once per model, and use currentTokens only when modelMetrics is absent. Shutdowns that carry accountingSnapshot are cumulative across resumes, so a later snapshot shutdown replaces the previous one instead of adding to it. Older CLIs without a snapshot restart metrics each run and are still summed. A zero-usage older-CLI run keeps the cumulative baseline. A one-time parse-cache repair drops persisted Copilot rows so stale totals are reparsed. Fixes #50629 Co-authored-by: Neil <[email protected]>
|
No actionable comments were generated in the recent review. Walkthrough
Severity of issue fixed: Medium Merge Risk:
|
ELI5
The History view showed Copilot sessions using about 2.4x more tokens than they really did. Orca was adding up numbers that already contain each other, and resumed sessions got counted again. Now each token is counted once.
What Changed
Before: for each Copilot
session.shutdownrecord, Orca addedcurrentTokens(the context-window size, not tokens consumed) plus, for each model, input + output + cacheRead + cacheWrite + reasoning. Cache counts are already part ofinputTokensand reasoning is already part ofoutputTokens. For the fixture, History showed 170,251 instead of 71,747.After:
copilotModelMetricsTotalsums onlyinputTokens + outputTokensper model.modelMetricsis present it is authoritative.currentTokensis only a fallback for older records that have nomodelMetrics, as before.accountingSnapshot) restore usage on resume, so each shutdown repeats the earlier runs. A snapshot shutdown now replaces the previous snapshot shutdown's contribution instead of adding to it. Older CLIs (noaccountingSnapshot) restart metrics at zero each run, so their shutdowns are still summed. A zero-usage older-CLI run in between keeps the cumulative baseline. The baseline lives in one optional number onSessionAccumulator(copilotCumulativeShutdownTokens).copilot_usage_rows_version, which uses the existingrowsRepairSqlmechanism) drops persisted Copilot rows so unchanged session files are reparsed and their stale totals go away. Other agents' rows are kept.Why
The upstream contract (github/copilot-sdk
session-events.tsanddocs/features/usage-and-billing.md) says cacheRead and cacheWrite are "included in inputTokens", reasoningTokens are output tokens spent on reasoning, andcurrentTokensis "Total tokens in context window at shutdown". Adding them up again inflates the total.For resumes, local Copilot CLI 1.0.105-1.0.114 sessions with multiple shutdowns show cumulative
modelMetrics: request counts grow and earlier-only models repeat unchanged. Published 1.0.60 rebuilds a fresh usage tracker on resume, so each run's shutdown is per-run. Taking only the latest shutdown would undercount older CLIs, so the code replaces the previous total only when both shutdowns carryaccountingSnapshot.A parser-only fix would leave unchanged sessions showing stale totals from the parse cache. A schema bump would reparse every agent, so the targeted row repair is cheaper.
Linked Issue
Fixes #50629
Visual Proof
N/A. Only token counting in the History scanner changes, with no layout or interaction change. Before/after on the same fixture input:
currentTokens27,176): 170,251~/.copilot/session-state, e.g. b3ad51f7: 52,270,555Testing
I manually tested these changes locally
Automated tests added/updated, or explained why not below
Every added test fails without this change and avoids the test anti-patterns
session-scanner-copilot-usage.test.tsfeeds the real Copilot scanner. On main it fails withexpected 170251 to be 71747. The resume test expects 12,090 (main gives 13,100). The zero-usage older-CLI case expects 3,030 (without the baseline rule it gives 4,040).Cache repair was checked against the real
SessionParseCacheDatabasewith a seeded previous-version DB. On main the stale Copilot row (170) is still served. On this branch the row is dropped, a Claude row and a Codex row whose title mentions "copilot" are kept, and the rewritten total (120) persists after reopening.Ran the parser over real multi-shutdown sessions from local
~/.copilot/session-state(macOS).viteston the usage test andsession-parse-cache-persistence.test.ts: 4 passed. oxlint, oxfmt, anti-slop, native code-quality plugins, ast-grep and the changed-code quality gate are clean on all touched files.Platform: macOS. The change is pure numeric parsing and SQLite, with no path or OS-specific code.
Performance
None that matters. The parser runs once per
session.shutdownline in the forked scan-service child, not on the main or renderer thread.consumeLineon a shutdown line, old vs new, median of 9 x 20k: 1 model 0.55 / 0.51 us, 4 models 0.78 / 0.86 us, 50 models 6.92 / 6.55 us (noise). The one-time repair runs when the scanner child opens the cache. It costs 2-10 ms for 1k-5k rows and 60-146 ms for an adversarial 20k-row cache (mostly the deletes), then one meta-key lookup per open (0.1-0.4 ms), the same as the existing repairs. No new polling, subprocesses, recurring I/O or renderer/store work.Risk
Level: Low
Copilot totals in History will drop, which is the intended correction. The riskiest part is resume accounting. A session that goes new CLI, then an older CLI with real usage, then a new CLI again may still over-count its first run. It never undercounts, and it is still far closer than main. The repair only touches derived cache rows, never session files. A plain revert restores the old accounting. The dropped rows are rebuilt from the transcripts either way.
Review
Reviewed by two agents across three rounds: upstream token semantics, resumed-session cumulative metrics, mixed and older CLI versions, and the cache upgrade path.
Agent skill upstream boundary
Notes
Original fix by @Afloat16 in #50633. Their authorship is preserved on the commit. This PR adds the resumed-session handling on top.
Security, cross-platform, SSH and mobile: numeric parsing only, with no new inputs, network or paths. Older records without
modelMetricskeep thecurrentTokensfallback.Checklist
N/Awith reasonpnpm lint,pnpm typecheck,pnpm test, andpnpm buildpass (or CI will cover; local preferred)