Skip to content

fix: include cached tokens in opencode prompt_tokens calculation - #9

Merged
Haannbboo merged 1 commit into
mainfrom
hip-kumquat
May 22, 2026
Merged

Haannbboo merged 1 commit into
mainfrom
hip-kumquat

Conversation

@Haannbboo

Copy link
Copy Markdown
Owner

Summary

  • Fix OpenCode prompt_tokens calculation to include cached_tokens, matching Claude's handler pattern

Why / Context

The OpenCode OTLP parser was setting prompt_tokens to only input_tokens (the uncached portion), never adding cached_tokens. When a provider returned input=200, cache_read=20000, the system recorded prompt_tokens=200 instead of 20200. The Claude handler already does this correctly.

How It Works

Changed src/otlp.py:365 from int(input_tokens) if input_tokens is not None else None to (int(input_tokens or 0)) + (int(cached or 0)). The cost calculator already handles the split: uncached = max(prompt - cached, 0) prices uncached at input rate and cached at cache_read rate.

Testing

  • uv run python -m pytest -q: 477 passed, 1 skipped

Risk Areas

  • Cost/token accounting: yes — this is the fix, ensures prompt_tokens reflects the total tokens the model processed
  • Provider adapter/model normalization: no — OpenCode OTLP parser only

Review

  • Independent code review completed before commit: no — direct fix, user requested commit
  • Must-fix review findings resolved: n/a
  • Standards checked against AGENTS.md and .agents/commands/llm-tracker.md: yes

@coderabbitai

coderabbitai Bot commented May 22, 2026

Copy link
Copy Markdown

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 73c063d8-2f7d-407b-8931-e5753e423a14

📥 Commits

Reviewing files that changed from the base of the PR and between 41ee11e and 1789952.

📒 Files selected for processing (2)
  • src/otlp.py
  • tests/test_otlp.py

📝 Walkthrough

Summary by CodeRabbit

  • Bug Fixes
    • Enhanced token metrics calculation in usage records to properly compute prompt tokens and total tokens, even when certain token values are unavailable. This ensures more complete and consistent data reporting across various usage scenarios.

Walkthrough

OpenCode OTLP token field normalization was refined: prompt_tokens is now computed by summing input and cached tokens with zero defaults, and total_tokens fallback logic was relaxed to populate whenever completion_tokens is present. Test assertions were updated to validate the new calculations.

Changes

OpenCode OTLP Token Normalization

Layer / File(s) Summary
Token calculation logic
src/otlp.py
prompt_tokens now always computed as input_tokens + cached_tokens (treating missing as 0). total_tokens fallback now triggers when completion_tokens is available, instead of requiring both prompt_tokens and completion_tokens to be non-None.
Test assertion updates
tests/test_otlp.py
Expected prompt_tokens updated in test_extract_opencode_fields_basic (150 → 180) and test_parse_opencode_record_routes_to_record_usage (100 → 120) to match new token calculation logic.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~8 minutes

Poem

🐰 Tokens sum and totals flow,
Input plus cache, zero if low,
Tests now reflect the new light,
OpenCode counts, precise and tight! ✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 33.33% which is insufficient. The required threshold is 80.00%. 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 specifically summarizes the main change: including cached tokens in the OpenCode prompt_tokens calculation.
Description check ✅ Passed The description provides relevant context about the fix, including rationale, implementation details, testing results, and risk assessment—all related to the changeset.
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.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch hip-kumquat

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

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