Skip to content

fix(opencode-usage): count cache-read tokens - #21522

Merged
Jinwoo-H merged 1 commit into
mainfrom
jinwoo/sta-7857-opencode-usage-reader-omits-cache-read-tokens-reports-2-of
Sep 18, 2026
Merged

Jinwoo-H merged 1 commit into
mainfrom
jinwoo/sta-7857-opencode-usage-reader-omits-cache-read-tokens-reports-2-of

Conversation

@Jinwoo-H

@Jinwoo-H Jinwoo-H commented Sep 18, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 3 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​136 $\color{#cf222e}{\Huge{\mathbf{−}}}$​6 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​130
Prod 3 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​13 $\color{#cf222e}{\Huge{\mathbf{−}}}$​9 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​4

ELI5

OpenCode reports cache-read tokens separately from new input. Orca was limiting cache reads to the input count and leaving them out of the total, so long cache-heavy sessions showed only a small fraction of the tokens actually served.

What Changed

  • Count the full OpenCode cache-read value, including values larger than current input.
  • Include cache reads in total token counts without double-counting totals that already include them.
  • Bump the OpenCode usage cache schema so existing undercounted files are rescanned.
  • Preserve the usage-enabled setting while stale analytics are discarded.
  • Add deterministic SQLite regression coverage through parser, daily, session, model, and project projections.

Why

On the local OpenCode database, the old calculation reported 98,275,738 tokens while the corrected calculation reports 2,184,439,781. Recorded cost remains unchanged. Recomputing from the source database is safer than trying to repair old aggregates because the previous cache omitted information needed for an exact migration.

Linked Issue

Fixes #21440

Visual Proof

N/A — this changes the usage data source and persistence logic; no UI layout or interaction changed.

Testing

  • Automated tests added/updated.
  • pnpm exec vitest run src/main/opencode-usage/cache-read-reproduction.test.ts src/main/opencode-usage/scanner.test.ts src/main/opencode-usage/store.test.ts (27 tests)
  • pnpm tc
  • pnpm run check:code-quality:changed
  • git diff --check
  • Validated against the local OpenCode SQLite database on macOS.

Review

The change is isolated to OpenCode usage parsing, cache invalidation, and regression tests. It does not add IPC or wire fields, change remote execution, or alter provider pricing.

Agent skill upstream boundary

  • Not applicable.

Notes

Cross-platform behavior is unchanged: the parser consumes the same SQLite fields and JSON values on macOS, Linux, Windows, and remote hosts. Existing v2 caches are rebuilt from the source database.

Checklist

  • This PR is small and focused
  • I explained what changed and why
  • No UI change; visual proof is N/A
  • Self-reviewed for correctness, security, and performance
  • Cross-platform, SSH/remote, and path impact considered
  • Full pnpm lint, pnpm test, and pnpm build are left to CI; focused type, test, quality, and diff checks pass locally.

@coderabbitai

coderabbitai Bot commented Sep 18, 2026

Copy link
Copy Markdown
Contributor

Review Change StackReview Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 210a3ddd-3191-44a3-b3c6-014427f9806a

📥 Commits

Reviewing files that changed from the base of the PR and between fc3a5d7 and cae4484.

📒 Files selected for processing (6)
  • src/main/opencode-usage/cache-read-reproduction.test.ts
  • src/main/opencode-usage/opencode-usage-provider.ts
  • src/main/opencode-usage/opencode-usage-row-parsing.ts
  • src/main/opencode-usage/persisted-state-normalization.ts
  • src/main/opencode-usage/scanner.test.ts
  • src/main/opencode-usage/store.test.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 2 remain after this review.


📝 Walkthrough

Walkthrough

OpenCode usage parsing now preserves the full cache-read token count and includes it when reported totals are lower than the combined token counters. The OpenCode usage schema version changes from 2 to 3. A cache-heavy SQLite reproduction test checks parsed sessions and usage projections. Persisted states with an older schema reset to current defaults while retaining the scan enabled flag. Related parser, materialization, and normalization tests update their expectations.

Priority: ➖ Normal

Severity of issue fixed: Medium

Merge Risk: ⚪ Minimal · up to cae44

Cache-read usage is carried through the relevant totals and projections, while outdated cached state is reset for rescanning without disabling usage tracking. No actionable merge risk remains.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 3 functions across 6 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely describes the main change: counting OpenCode cache-read tokens.
Description check ✅ Passed The description covers the required sections, explains the user impact and implementation, links issue #21440, provides visual proof as not applicable, and lists focused testing and checklist status. …
Linked Issues check ✅ Passed The changes satisfy the coding objectives in #21440. parseOpenCodeUsageRow reads the OpenCode cache-read value and computes totalTokens from input, output, reasoning, and cache-read tokens when th…
Out of Scope Changes check ✅ Passed The changes stay within #21440. The parser update, schema invalidation, scan-setting preservation, and SQLite regression tests directly support OpenCode usage tracking and cache-read correction. No un…
  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Commit to this branch
  • Create a new PR

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

Comment @coderabbitai help to get the list of available commands.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ℹ️ No critical issues — the cache-read fix is correct and well tested. One coverage gap worth a look.

Reviewed changes

  • Cache-read counting — opencode-usage-row-parsing.ts now takes the full cache.read (dropping the old Math.min(cache.read, input) cap) and computes totalTokens = Math.max(tokens.total, input + output + reasoning + cache.read). This matches OpenCode's own semantics: input is the non-cached input and cache reads are additive.
  • Schema bump — OPENCODE_USAGE_SCHEMA_VERSION 2 → 3 invalidates stale v2 caches so existing undercounted files are rebuilt from source.
  • Enabled preservation — the schema-mismatch branch of persisted-state-normalization.ts now carries scanState.enabled forward while discarding stale analytics, matching the codex/claude readers.
  • Regression coverage — a new session-table reproduction test drives the corrected counters through the parser plus daily/session/model/project projections; scanner.test.ts and store.test.ts totals were updated.

ℹ️ Cache-write tokens are still dropped from the session-table path

The parser now counts cache reads, but tokens_cache_write is never read and the primary session-table path hardcodes cache.write: 0, so cache writes stay out of the total there. OpenCode's own total includes cache write, so for Anthropic/Bedrock sessions — where cache creation is additive — Orca still undercounts, and the session path and message path can disagree for the same usage.

Technical details
# Cache write is excluded from the session-table total

## Affected sites
- `src/main/opencode-usage/opencode-usage-row-queries.ts:102-114` — `selectSessionUsageRows` synthesizes `data.tokens.total = tokens_input + tokens_output + tokens_reasoning` and hardcodes `cache: { read: tokens_cache_read, write: 0 }`. It never selects `tokens_cache_write`.
- `src/main/opencode-usage/opencode-usage-row-parsing.ts:85-88` — the fallback sum `input + output + reasoning + cachedInputTokens` omits cache write; because the session path's synthesized `total` also omits it, `Math.max` resolves to the cache-read-only sum.
- `src/main/opencode-usage/types.ts` — no `cachedWriteTokens` field exists on any projection, so there is nowhere to surface it even if read.

## Evidence (upstream OpenCode)
- `packages/opencode/src/session/session.ts` `getUsage`: `input = inputTokens - cacheRead - cacheWrite`; `total = usage.totalTokens` (AI SDK total, which includes cache read and cache write). So OpenCode's own total = `input + output + reasoning + cache.read + cache.write`.
- `packages/core/src/session/sql.ts`: the `session` table has a `tokens_cache_write` column (alongside `tokens_cache_read`).

## Why it matters
The message-blob path (`opencode-usage-row-queries.ts:149-163`, raw `data`) keeps OpenCode's `total`, which already includes cache write. The session-table path is preferred whenever session rows have usage, so the two paths produce different totals for identical usage. For Anthropic-backed OpenCode sessions, cache-creation tokens are real volume that stays unreported.

## Required outcome
Decide whether cache write belongs in OpenCode totals. If yes, read `tokens_cache_write` (guarded by `columnExists`, since older DBs may lack the column) and add it to the synthesized `total`; adding a `cachedWriteTokens` projection field is optional. If the intent is to fix only the cache-read undercount for now, a short comment noting the deliberate omission would keep the next reader from re-deriving this.

## Open questions for the human
- Is cache write intentionally out of scope for this PR (title says cache-read), or should it land here for parity with the Claude reader, whose total includes cache write?

Pullfrog  | Fix it ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@Jinwoo-H
Jinwoo-H merged commit c5733e8 into main Sep 18, 2026
30 checks passed
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.

OpenCode usage reader omits cache-read tokens; reports ~2% of actual volume (schemaVersion 2 vs Claude's 6)

1 participant