Skip to content

fix(ai-vault): stop double counting Copilot token usage in History - #50764

Merged
nwparker merged 1 commit into
mainfrom
bugbash/pr-50633
Nov 27, 2026
Merged

nwparker merged 1 commit into
mainfrom
bugbash/pr-50633

Conversation

@nwparker

@nwparker nwparker commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor

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.

Files Added Deleted Net
Test 1 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​66 0 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​66
Prod 4 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​25 $\color{#cf222e}{\Huge{\mathbf{−}}}$​14 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​11

What Changed

Before: for each Copilot session.shutdown record, Orca added currentTokens (the context-window size, not tokens consumed) plus, for each model, input + output + cacheRead + cacheWrite + reasoning. Cache counts are already part of inputTokens and reasoning is already part of outputTokens. For the fixture, History showed 170,251 instead of 71,747.

After:

  • copilotModelMetricsTotal sums only inputTokens + outputTokens per model.
  • When modelMetrics is present it is authoritative. currentTokens is only a fallback for older records that have no modelMetrics, as before.
  • Resumed sessions: newer Copilot CLIs (they write 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 (no accountingSnapshot) 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 on SessionAccumulator (copilotCumulativeShutdownTokens).
  • A one-time parse-cache repair (copilot_usage_rows_version, which uses the existing rowsRepairSql mechanism) 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.ts and docs/features/usage-and-billing.md) says cacheRead and cacheWrite are "included in inputTokens", reasoningTokens are output tokens spent on reasoning, and currentTokens is "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 carry accountingSnapshot.

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:

Before After
One shutdown (71,282 in / 345 out, plus a second model at 100 / 20, with cache subsets and currentTokens 27,176): 170,251 71,747
Per-run, then snapshot, then cumulative snapshot shutdowns: 13,100 12,090
Real resumed sessions from local ~/.copilot/session-state, e.g. b3ad51f7: 52,270,555 26,177,840 (matches the last cumulative shutdown)

Testing

  • 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.ts feeds the real Copilot scanner. On main it fails with expected 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 SessionParseCacheDatabase with 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).

  • vitest on the usage test and session-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.shutdown line in the forked scan-service child, not on the main or renderer thread. consumeLine on 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

  • Not applicable, or this change copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.

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 modelMetrics keep the currentTokens fallback.

Checklist

  • This PR is small and focused
  • I explained what changed and why (ELI5, the user-facing before/after, the mechanism, and why over the alternatives)
  • I stated the risk: what could break, for whom, and how to back it out
  • Before/after screenshots or videos attached for UI changes, or N/A with reason
  • Self-reviewed for correctness, security, and performance
  • Cross-platform, SSH/remote, and path/shortcut impact considered (or N/A)
  • pnpm lint, pnpm typecheck, pnpm test, and pnpm build pass (or CI will cover; local preferred)

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]>
@coderabbitai

coderabbitai Bot commented Nov 27, 2026

Copy link
Copy Markdown
Contributor

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

The scanner now sums Copilot input and output tokens without separately adding cache or reasoning subsets. It replaces prior cumulative shutdown usage when an accounting snapshot is present. A one-time cache repair deletes Copilot rows before setting the version marker.

Severity of issue fixed: Medium

Merge Risk: Minimal · up to 3a53f

This change corrects Copilot token totals in History and repairs stale cached totals once. No concrete merge-blocking risk was found. The author notes a narrow edge case where switching CLI versions may over-count a single run.

Pre-merge checks: Passed 4

Check name Status Explanation
Title check Passed The title "fix(ai-vault): stop double counting Copilot token usage in History" names the main change: Copilot token totals in the History view no longer double count cache, reasoning, and context-wind…
Description check Passed The description follows the repository template closely. It has ELI5, What Changed, Why, Linked Issue (Fixes #50629), Visual Proof (N/A with reason), Testing, Performance, Risk (Level: Low, with a rev…
Linked Issues check Passed Directly linked issue #50629 has three coding requirements. (1) Count Copilot shutdown usage once. The parser diff at session-scanner-copilot-parser.ts uses copilotModelMetricsTotal(metrics) when mode…
Out of Scope Changes check Passed Changed files map to the linked issue. Parser and token-values changes fix the double-counted usage fields. The parse-cache repair fixes stale rows, as the issue requires. The SessionAccumulator prope…
Full details: Title check

Explanation

The title "fix(ai-vault): stop double counting Copilot token usage in History" names the main change: Copilot token totals in the History view no longer double count cache, reasoning, and context-window values. The changeset matches this: it sums only inputTokens and outputTokens per model, prefers modelMetrics over currentTokens, and adds a parse-cache repair. The title is short, specific, and follows a conventional commit style.

Full details: Description check

Explanation

The description follows the repository template closely. It has ELI5, What Changed, Why, Linked Issue (Fixes #50629), Visual Proof (N/A with reason), Testing, Performance, Risk (Level: Low, with a revert path), Review, Agent skill boundary, Notes, and Checklist sections. It gives concrete before and after numbers, names the affected files and mechanisms, and describes the resumed-session trade-off. Minor gaps: the Testing platform is stated only as macOS, and the final checklist item for pnpm lint, typecheck, test, and build is unchecked. The description does not claim these ran in full, so it is acceptable. The AI Disclosure section was left as template text, which is allowed for team members.

Full details: Linked Issues check

Explanation

Directly linked issue #50629 has three coding requirements. (1) Count Copilot shutdown usage once. The parser diff at session-scanner-copilot-parser.ts uses copilotModelMetricsTotal(metrics) when modelMetrics is present, and currentTokens only when it is absent. The token-values summary shows the per-model sum is inputTokens + outputTokens, which excludes cache subsets, reasoning subsets, and currentTokens. This meets the 71,747 expectation for the fixture. (2) Remove stale cached Copilot totals. session-parse-cache-database.ts at head adds rowsRepairSql('copilot_usage_rows_version', instr(rows.session, '"agent":"copilot"') > 0) to ROWS_REPAIR_SQL. This deletes only Copilot rows once and sets the meta marker. (3) Keep other agents' rows and persist the corrected total. The filter matches only Copilot agent rows, so other agents' rows are not deleted. The reported cache test (stale 170 replaced by 120 after reopen) and scanner tests (authoritative empty metrics, legacy fallback) are described in the PR, but I did not execute them. The parse-cache diff tool returned no text, so the repair logic was read from the head file only. Resume handling (accountingSnapshot) goes beyond the issue text but targets repeated counting of the same usage, which is within the issue's double-counting scope.

Full details: Out of Scope Changes check

Explanation

Changed files map to the linked issue. Parser and token-values changes fix the double-counted usage fields. The parse-cache repair fixes stale rows, as the issue requires. The SessionAccumulator property copilotCumulativeShutdownTokens supports the resumed-session rule in the parser. That rule prevents the same cumulative usage from being added on each resume, which is a form of the double counting in #50629. The test file covers the parser behavior. No unrelated files were identified in the summary. The resumed-session logic is not named in #50629, so a reviewer may want to confirm it is wanted in this PR. This does not show an unrelated change.

  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

Recent review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 6e04c6cd-1cbd-4b07-9cc5-50d6f8079b51
Commits

Reviewing files that changed from the base of the PR and between 72aea61 and 3a53f44.

Files selected for processing: 5

  • src/main/ai-vault/parse-cache/session-parse-cache-database.ts
  • src/main/ai-vault/parsing/session-scanner-token-values.ts
  • src/main/ai-vault/scanners/copilot/session-scanner-copilot-parser.ts
  • src/main/ai-vault/scanners/copilot/session-scanner-copilot-usage.test.ts
  • src/main/ai-vault/session-scanner-types.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 0 remain after this review.

@nwparker
nwparker merged commit c7d335f into main Nov 27, 2026
97 of 100 checks passed
@nwparker
nwparker deleted the bugbash/pr-50633 branch November 27, 2026 10:04
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Copilot token totals double count overlapping usage fields and retain stale cached totals

2 participants