Skip to content

fix(usage): include OpenCode cache writes in input accounting - #24587

Merged
nwparker merged 1 commit into
mainfrom
nwparker/OpenCode-Usage-Orchestration
Oct 3, 2026
Merged

nwparker merged 1 commit into
mainfrom
nwparker/OpenCode-Usage-Orchestration

Conversation

@nwparker

@nwparker nwparker commented Oct 2, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 4 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​123 $\color{#cf222e}{\Huge{\mathbf{−}}}$​20 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​103
Prod 6 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​39 $\color{#cf222e}{\Huge{\mathbf{−}}}$​11 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​28

ELI5

OpenCode's cached input now appears inside input totals, so the Stats page no longer shows more cached input than total input.

What Changed

Normalize uncached input plus cache reads and writes into Orca's input counters, count both cache buckets in cached input, and rebuild saved scans through schema version 7. Separate cache-write counters survive aggregation and persistence so telemetry continues to report distinct read and write buckets. Daily chart segments subtract cached input from the input segment so each token appears once. Current session/session_v2 merging and cache-write SQL remain intact.

Why

OpenCode stores uncached input separately. Fixing that conversion at the scanner boundary keeps every summary consistent and avoids rewriting the already-correct v2 queries. This narrowly ports the remaining changes from @griffinmartin's #20187; that author is credited in the commit.

Linked Issue

Continues #20187 (its original linked #20186 is outside this campaign's assigned issue list).

Visual Proof

Hidden CDP screenshots below show a private copy of a real OpenCode database scanned by Orca on macOS. Identifying fields are outside the screenshots. Before: input 34.1M / cache 340.2M. After: input 377.9M / cache 343.8M; total remains 380,503,601.

Before
After

Testing

  • I manually tested these changes locally
  • Automated tests added/updated, or explained why not below

OpenCode v2.0.16 source and real installed CLI inspected; read-only database backup scanned through real Orca IPC before/after, then rendered in Settings → Stats & Usage → OpenCode → All local usage / All time. Rebuilt hidden app used the repository's disposable-home isolation helper and isolated ports/profile. No user configuration or shared OpenCode service changed.

66 focused tests pass (9 files), including v1/v2 merged rows, cache-write-only input, projections, and overview calculations. pnpm tc, changed-code quality, touched-file oxlint, oxfmt, and git diff --check pass. Hidden electron-vite build and CLI build pass; full packaging/full suite are left to CI. Linux, Windows, WSL and SSH were considered but not exercised live.

Review

A second real-database projection verified telemetry: input 34,096,719, cache reads 340,213,856, cache writes 3,590,638; the UI retains combined cache totals. The one-time scan rebuild is intentional. This changes accounting categories, not recorded cost or authoritative token totals. Read-only database access and execution-host ownership are preserved.

Agent skill upstream boundary

  • Not applicable; no skill-installer source copied.

Notes

Current reviewed head 8b59a52c1b2420f8712da93b4a09b03ea5dd3013 targets main after the journal-test dependency merged. Its ten usage postblobs and file modes exactly match the reviewed accounting fix; every other entry matches evaluated main 84a4e8a9b0a1a0bd938528aa2dc6e49636917a47. This preserves intervening process/WSL/Git changes rather than replaying an old branch wholesale. The original @griffinmartin credit remains in the source commit.

Nine fresh private SQLite fixture controls pass through usage queries, aggregation, cache reload, schema5/6 invalidation and separate telemetry. Process/WSL integration checks also pass:40 default text-capture cases and8 path cases; usage worker/discovery/WSL transport sources remain unchanged. These are focused controls; the actual installed OpenCode and hidden-renderer proof above remains the earlier genuine database experiment. Full-head CI runs after this update.

Replacement for #20187 after this PR merges. Recorded costs and authoritative token totals are unchanged; cached input categories become consistent across views.

Checklist

  • Focused accounting change
  • User-facing before/after, mechanism and approach explained
  • Before/after screenshots attached
  • Self-reviewed for correctness, security and performance
  • Cross-platform, SSH/remote and path impact considered
  • Full-head checks: CI after this update

@nwparker
nwparker marked this pull request as ready for review October 2, 2026 08:29
@coderabbitai

coderabbitai Bot commented Oct 2, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Navigate logical layers of code changes, visualize relationships, and explore their blast radius.

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: 711acc35-da61-4450-9415-cf8e50e98c89

📥 Commits

Reviewing files that changed from the base of the PR and between 306b457 and 93390bc408e25c15f7aaa9716da48fd25172e8dd.

📒 Files selected for processing (10)
  • src/main/opencode-usage/cache-read-reproduction.test.ts
  • src/main/opencode-usage/cache-write-accounting.test.ts
  • src/main/opencode-usage/opencode-usage-provider.ts
  • src/main/opencode-usage/opencode-usage-row-parsing.ts
  • src/main/opencode-usage/opencode2-session-usage.test.ts
  • src/main/opencode-usage/scanner.test.ts
  • src/main/opencode-usage/scanner.ts
  • src/main/opencode-usage/types.ts
  • src/main/usage/agent-token-usage.ts
  • src/renderer/src/components/stats/CodexUsageDailyChart.tsx

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


📝 Walkthrough

Walkthrough

OpenCode input-token totals now include cache reads and writes. Cached-input totals include both cache buckets, while cache-write tokens remain separately available in usage data and token-session output. The daily chart displays input tokens minus cached input. Tests cover parsing, aggregation, and persistence across database generations.

Priority: ⬇️ Low

Merge Risk: ⚪ Minimal · up to 93390

No actionable merge-blocking issue remains in the reviewed cache-token accounting change. Normal checks can proceed.

Security Architecture Review

Security architecture risk: 🔵 Low · up to 93390

The change is limited to usage accounting and saved usage data. The inspected paths retain read-only database access, worktree attribution, and telemetry controls. No introduced security vulnerability was established, but compatibility and recovery coverage remain incomplete.

Retained concerns
No architecture-level concerns identified.

Security review details

Security Blast Radius

  • inferred — A party able to modify a scanned OpenCode database can influence usage counters for sessions attributed to known worktrees. The inspected change propagates those counters to the local usage cache, chart, and configured telemetry path; it does not establish additional execution or database-write authority.

Trust Boundaries and Controls

  • observed — Scanning opens source databases read-only with query_only enabled and closes them on exit. Telemetry conversion excludes locations without a worktree association. Reporting checks telemetry enablement before processing and again after obtaining analytics session identities.

Resilience and Maintainability Implications

  • observed — Telemetry publishing is serialized. Changed counters advance a per-session revision, unchanged snapshots retain their revision, and revisions are persisted before capture. Restart can retry the same persisted snapshot; downstream deduplication was not established by this inspection. Reporting failures do not invalidate a successful local scan.
🚥 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 4 functions across 10 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly and concisely describes the main change: including OpenCode cache writes in input accounting.
Description check ✅ Passed The description covers the user-facing change, implementation, rationale, linked work, visual proof, testing, review, and checklist. It notes that full packaging and suite checks await CI, and that so…
✨ Finishing Touches 💡 2
📝 Generate docstrings 💡
  • Commit to this branch
  • Create a new PR
🛠️ Fix failing CI checks 💡
  • Commit to this branch
  • Create a new PR
  • Autopilot · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Autopilot is currently an internal CodeRabbit preview.


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.

@nwparker
nwparker force-pushed the nwparker/OpenCode-Usage-Orchestration branch from 93390bc to 5694747 Compare October 2, 2026 09:47

@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 new issues found.

Reviewed changes

No prior Pullfrog review existed on this PR, so this run covered the full 5694747 diff of the two head commits.

  • Normalized OpenCode input accounting — parseOpenCodeUsageRow now treats tokens.input as uncached, folds both cache buckets into cachedInputTokens, and reports inputTokens = uncached + cached, matching the Codex/Muse convention where cache hits live inside input.
  • Retained a distinct cache-write bucket for telemetry — the aggregation metric carries cacheWriteInputTokens through session/location/model/daily rollups and merges, and codexOpenCodeTokenSessions splits cached_input_tokens (read only) from cache_write_input_tokens. Codex entries lack the field, so Codex telemetry is unchanged.
  • Bumped the OpenCode usage schema to 7 — a version mismatch resets the persisted cache (preserving scanState.enabled) and triggers the intentional one-time rescan, while totalTokens now derives from the already-inclusive input without double-counting cache.
  • Fixed the shared daily chart's input segment — Math.max(0, inputTokens - cachedInputTokens) prevents the cached bucket appearing twice in the stacked input segment for Codex, OpenCode, and Muse, all of which define input inclusive of cache hits.

I traced the accounting through row parsing, the metric fold, the two rollup-merge paths, both projection builders, and the telemetry reporter, and verified Codex/Muse input semantics separately. The focused suites (cache-write-accounting, scanner, opencode2-session-usage, cache-read-reproduction, agent-token-usage, usage-daily-chart) pass 47 tests across 6 files.

Pullfrog  | View workflow run | Using deepseek-v4.1-flash (free via Pullfrog for OSS) | 𝕏

@nwparker
nwparker changed the base branch from main to fix/journal-import-test-sampler October 2, 2026 14:47
@nwparker

nwparker commented Oct 2, 2026

Copy link
Copy Markdown
Contributor Author

Updated to 365e810aec36fe4339929b3cff774c37af864b1b with current main's E2E package-variable contract fix. All 10 reviewed product/test post-blobs remain byte-identical. The repeated shard failure checked package names in the installer script after the workflow moved them to ORCA_E2E_APT_PACKAGES; this update retains main's corrected contract test. New-head CI is running. This PR is temporarily stacked on #24767 to include the independently checked journal sampler fix; it will return to main after that parent merges.

OpenCode stores uncached input, cache reads and cache writes separately. Include both cache buckets in total input, keep chart segments disjoint, and preserve separate cache-write telemetry through aggregation and cache reload.

Invalidate older usage caches with schema 7. Port the remaining parser and chart corrections from #20187 by @griffinmartin onto the current v2 scanner, retaining its session-generation handling.

Co-authored-by: griffinmartin <[email protected]>
@nwparker
nwparker force-pushed the nwparker/OpenCode-Usage-Orchestration branch from 365e810 to 8b59a52 Compare October 3, 2026 01:43
@nwparker
nwparker requested a review from brennanb2025 as a code owner October 3, 2026 01:43
@nwparker
nwparker changed the base branch from fix/journal-import-test-sampler to main October 3, 2026 01:43

@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 new issues found.

Reviewed changes

Since the prior Pullfrog review (5391388025, head 5694747), the branch was retargeted from fix/journal-import-test-sampler to main and now carries a single commit 8b59a52c that re-applies the OpenCode cache-input accounting fix. The ten PR files are byte-identical to the previously reviewed blobs (git diff 56947472ca 8b59a52 over those paths is empty), so the accounting behavior is unchanged from what was already verified.

  • Re-applied the reviewed accounting fix on current main — cache-input normalization, the schema-7 cache invalidation, per-bucket cache-write telemetry, and the disjoint chart input segment all carry over without source change.
  • No new behavioral surface in the delta — every remaining difference against main comes from mainline commits, not from this PR.

Pullfrog  | View workflow run | Using deepseek-v4.1-flash (free via Pullfrog for OSS) | 𝕏

@nwparker
nwparker merged commit f146368 into main Oct 3, 2026
73 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.

1 participant