Skip to content

fix(ai-vault): avoid double counting Copilot token usage - #50633

Closed
Afloat16 wants to merge 2 commits into
stablyai:mainfrom
Afloat16:afloat16/orca50-20261127-copilot-usage-accounting
Closed

Afloat16 wants to merge 2 commits into
stablyai:mainfrom
Afloat16:afloat16/orca50-20261127-copilot-usage-accounting

Conversation

@Afloat16

Copy link
Copy Markdown
Contributor

ELI5

Show Copilot’s reported token usage once, and refresh saved totals that were calculated with the old accounting.

What Changed

  • Sum each model’s input and output totals once, without adding cache, reasoning or context-window subsets.
  • Treat present modelMetrics, including an empty object, as authoritative. Keep currentTokens as the fallback for older records without modelMetrics.
  • Use the existing one-time repair mechanism to invalidate only persisted Copilot parse rows. Other agents retain their cached rows, and newly corrected Copilot rows survive reopening the database.

Why

Copilot shutdown modelMetrics report complete input and output totals. Cached-input counts and reasoning-token counts are subsets; currentTokens describes the current context window. Adding these fields again inflates History usage. Correcting only the parser leaves unchanged session files served from persisted rows with the old totals.

Linked Issue

Fixes #50629

Visual Proof

N/A

No graphical layout or interaction component changes. The following before/after results come from the affected production operation with the same fixture input.

Before After
The scanner reports 170,251 instead of 71,747. After a parser-only fix, an unchanged session can still return its stale persisted total (170 in the cache fixture). The same scanner input reports 71,747. The targeted one-time repair removes the stale Copilot row, keeps an unrelated agent row, and retains a rewritten total of 120 after reopening.

Testing

  • I manually tested these changes locally through the production-entry reproductions described below
  • Automated tests added/updated, or explained why not below
  • Every added test fails without this change and avoids the test anti-patterns

Token-accounting parser correctness and persisted derived-data integrity. Tests call the real scanner and SQLite cache; expected totals are hardcoded.

Two focused tests pass. The accounting regression failed on the original production parser. The real-SQLite upgrade regression separately failed with the corrected parser but without the targeted cache repair. Controls cover authoritative empty metrics, the legacy fallback, retention of another agent’s row, and persistence of the corrected total on reopen.

Reproduce the focused tests with:

pnpm test src/main/ai-vault/scanners/copilot/session-scanner-copilot-usage.test.ts --maxWorkers=2

Locally executed through the repository’s test-runtime runner on Linux with Node 24.22.3. macOS, Windows and remote SSH execution are not claimed.

Final integrated validation: 32 focused regression tests in 22 files passed, including the unchanged archive-write failure case that had timed out under earlier heavy concurrent checking. The Drive performance contract passed separately (1 file/1 test). Changed-code quality passed with zero new findings across 129 changed paths; final touched-file formatting and git diff --check passed. Node typechecking passed for 17,026 files and web typechecking for 16,094 files using the repository-supported Bun compiler with one worker. These are aggregate validation results for the prepared contributions, not per-PR test counts.

The required pnpm check:changed --base=9890ea181c0f9ae59fb82da64c4a6fbc0504a817 was attempted after the final edits. Its workspace-package build is blocked because this environment rejects the tsx CLI local IPC socket (listen EPERM). The default tsrs typechecker was also terminated with SIGKILL; the supported Bun typechecking route completed successfully. The complete gate/build is not claimed to pass and still requires CI.

Performance

Constant work per reported model. Opening a cache performs the existing marker lookup and, once per affected cache, removes Copilot rows so they can be reparsed. Subsequent opens keep the marker and corrected rows; other agents are not rescanned by this repair.

Risk

Level: Low

The sensitive compatibility point is older Copilot records that lack modelMetrics; their existing currentTokens fallback remains covered. The repair changes derived cache data, not original session files. Reverting restores the old accounting; it does not restore removed stale rows, which are rebuilt from the original transcripts.

AI Disclosure

Core contribution owner: @Afloat16. Required tooling disclosure: GPT-6 Astra Pro was used for implementation and review.

Review

Reviewed provider scope, overlapping token semantics, legacy fallback and the upgrade path. Numeric processing is platform-neutral; existing host routing, SSH paths and mobile contracts are unchanged. Other agents retain their accounting behavior. The repair uses the existing SQLite mechanism and adds no executable input or network request. No graphical layout or interaction code changes.

Agent skill upstream boundary

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

Notes

The Copilot SDK usage documentation states that cached tokens are already included in inputTokens; modelMetrics.usage.inputTokens has the same inclusive meaning. currentTokens is context-window utilization, and reasoningTokens is an output subset. Targeted contribution-history and repository searches found no equivalent correction.

Primary references:

Checklist

  • This PR is small and focused
  • I explained what changed and why, including the mechanism and before/after result
  • I stated the risk and how to back it out
  • Before/after data evidence is included, with N/A and a reason for graphical proof
  • Self-reviewed for correctness, security and performance
  • Cross-platform, SSH/remote and path/shortcut impact considered
  • Full lint/typecheck/test/build gate: component results and any remaining gate limitation are recorded above; complete CI coverage is still required

@coderabbitai

coderabbitai Bot commented Nov 27, 2026

Copy link
Copy Markdown
Contributor

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

Copilot token accounting now sums input and output tokens. Shutdown records use model metrics when valid and otherwise use currentTokens. A one-time parse-cache repair deletes cached Copilot rows while preserving unrelated rows. Tests cover token totals, shutdown behavior, cache invalidation, and reparsing.

Severity of issue fixed: Medium

Merge Risk: Minimal · up to a5b65

Copilot token totals no longer double-count cache and reasoning subsets, and stale cached Copilot totals are repaired once and reparsed. Other agents' cached rows are kept. No concrete merge-blocking risk was found; CI should still pass before merging.

Pre-merge checks: Passed 4

Check name Status Explanation
Title check Passed The title "fix(ai-vault): avoid double counting Copilot token usage" names the main change. The changeset sums Copilot modelMetrics input and output once, treats modelMetrics as authoritative, and add…
Description check Passed The description follows the repository template and fills every required section: ELI5, What Changed, Why, Linked Issue (Fixes #50629), Visual Proof (N/A with reason), Testing, Performance, Risk with …
Linked Issues check Passed Issue #50629 requires four coding changes. (1) Copilot shutdown totals must sum modelMetrics input and output only. The diff in session-scanner-copilot-parser.ts and session-scanner-token-values.ts se…
Out of Scope Changes check Passed All changed areas relate to #50629. The parser and token-value changes implement the accounting fix. The session-parse-cache-database.ts change implements the targeted Copilot-only repair. session-par…
Full details: Title check

Explanation

The title "fix(ai-vault): avoid double counting Copilot token usage" names the main change. The changeset sums Copilot modelMetrics input and output once, treats modelMetrics as authoritative, and adds a one-time repair that invalidates stale Copilot parse rows. The title covers the core fix. It does not mention the cache repair, which is a secondary part of the change.

Full details: Description check

Explanation

The description follows the repository template and fills every required section: ELI5, What Changed, Why, Linked Issue (Fixes #50629), Visual Proof (N/A with reason), Testing, Performance, Risk with level and back-out plan, AI Disclosure, Review, Agent skill boundary, and Checklist. The Testing section explains the focused tests and their results. It also states what was not verified (macOS, Windows, SSH, and the full gate). The Performance section gives a one-line rationale with the cache-repair cost. The only unchecked item is the full lint/typecheck/test/build gate, which the author states still requires CI.

Full details: Linked Issues check

Explanation

Issue #50629 requires four coding changes. (1) Copilot shutdown totals must sum modelMetrics input and output only. The diff in session-scanner-copilot-parser.ts and session-scanner-token-values.ts sets copilotModelMetricsTotal to numberValue(usage.inputTokens) + numberValue(usage.outputTokens). Cache and reasoning subsets are no longer added. (2) A present modelMetrics record, including an empty one, must be authoritative. The parser now uses asRecord(data.modelMetrics) and returns the metrics total when the record exists. (3) currentTokens must remain the fallback when modelMetrics is absent. The parser uses numberValue(data.currentTokens) in that case. (4) A one-time repair must remove only persisted Copilot parse rows, keep other agents' rows, and persist the corrected total after reopening. The raw summary states that session-parse-cache-database.ts adds a Copilot-only delete inside the existing one-time repair. The raw summary also states that the regression tests cover these cases. I did not run the tests. The test coverage is taken from the PR summary and not independently verified. The code changes match the stated requirements.

Full details: Out of Scope Changes check

Explanation

All changed areas relate to #50629. The parser and token-value changes implement the accounting fix. The session-parse-cache-database.ts change implements the targeted Copilot-only repair. session-parse-cache-previous-row.test-fixture.ts provides fixture data for the upgrade regression. session-scanner-copilot-usage.test.ts holds the regression and control tests. The PR description's Notes and Agent skill upstream boundary sections are documentation and disclosure, not code changes. No unrelated code change appears in the reviewed summary. I did not inspect the cache-database diff directly, so that file's connection to the issue rests on the raw summary.

  • 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: 4350a756-18ef-4acd-9aac-4f7732f546a5
Commits

Reviewing files that changed from the base of the PR and between 2bd1b46 and a5b65db.

Files selected for processing: 5

  • src/main/ai-vault/parse-cache/session-parse-cache-database.ts
  • src/main/ai-vault/parse-cache/session-parse-cache-previous-row.test-fixture.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

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

Copy link
Copy Markdown
Contributor

Thanks so much @Afloat16 for finding and fixing this! We've carried your fix forward in #50764, rebased onto main and extended to handle resumed Copilot sessions (cumulative shutdown metrics). Your authorship is preserved on the landing commit. Closing this one in favor of #50764.

@nwparker nwparker closed this Nov 27, 2026
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