Skip to content

[codex] Fix channel test cache billing - #5340

Open
Brisbanehuang wants to merge 1 commit into
QuantumNous:mainfrom
Brisbanehuang:codex/fix-channel-test-cache-billing
Open

[codex] Fix channel test cache billing#5340
Brisbanehuang wants to merge 1 commit into
QuantumNous:mainfrom
Brisbanehuang:codex/fix-channel-test-cache-billing

Conversation

@Brisbanehuang

@Brisbanehuang Brisbanehuang commented Jun 6, 2026

Copy link
Copy Markdown

Summary

  • Apply cached prompt token ratios when calculating non-tiered channel test quota.
  • Add a regression test covering cached prompt tokens in settleTestQuota.

Root cause

Channel/model tests write their own consume log through settleTestQuota. The non-tiered fallback formula counted all prompt tokens at the full model ratio, while the log metadata already included cache_tokens and cache_ratio. This made the log list quota disagree with the expanded billing details for cached requests.

Validation

  • go test ./controller -run TestSettleTestQuotaAppliesCacheRatio -count=1 initially failed with actual quota 11295 instead of expected 2655.
  • go test ./controller -run 'TestSettleTestQuota|TestBuildTestLogOther|TestResolveChannelTestUserID' -count=1\n\nNote: go test ./controller -count=1 still fails locally in an unrelated existing test, TestListModelsTokenLimitIncludesTieredBillingModel, with the local SQLite test database state.\n

Summary by CodeRabbit

  • Bug Fixes

    • Updated quota calculation to apply cache ratio to cached prompt tokens and perform a single model-scaling rounding, improving token usage accuracy.
  • Tests

    • Added tests verifying correct application of cache ratio and that semantic cached tokens are treated as prompt-base cached tokens in quota computation.

@coderabbitai

coderabbitai Bot commented Jun 6, 2026

Copy link
Copy Markdown
Contributor

Too much diff to scan? Review this PR in Change Stack to start with the highest-impact changes.

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

Run ID: 0dae2eec-622c-49de-b2f3-6183224fc06a

📥 Commits

Reviewing files that changed from the base of the PR and between a26c974 and 3b9a836.

📒 Files selected for processing (2)
  • controller/channel-test.go
  • controller/channel_test_internal_test.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • controller/channel-test.go

Walkthrough

settleTestQuota now separates prompt cached tokens and applies CacheRatio and CompletionRatio to compute quotaTokens, subtracts cached tokens for non-Claude semantics, then multiplies by ModelRatio and rounds once. Two tests validate cache-ratio application and Claude semantic cached-token treatment.

Changes

Cached Token Quota Calculation

Layer / File(s) Summary
Cache-aware quota computation
controller/channel-test.go
settleTestQuota computes quota as promptTokens + cachedTokensCacheRatio + completionTokensCompletionRatio, subtracts cachedTokens for non-Claude semantics, then applies ModelRatio once and rounds the result.
Unit tests for cached-token handling
controller/channel_test_internal_test.go
Adds TestSettleTestQuotaAppliesCacheRatio and TestSettleTestQuotaKeepsClaudeSemanticCachedTokensInPromptBase asserting numeric quotas (2655 and 1410) and nil results for the respective scenarios.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

  • QuantumNous/new-api#2798: Related cached-token billing changes that populate PromptTokensDetails.CachedTokens and wire cache ratios.
  • QuantumNous/new-api#3438: Related quota/token accounting updates handling cached tokens and Claude semantics.

Suggested reviewers

  • seefs001

Poem

🐰 I hopped through tokens, cached and new,
Counted prompts and completions too.
A CacheRatio sprinkle, ModelRatio's fold,
Numbers settled tidy, tests told.
Cheers — the quota math is snug like stew!

🚥 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%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and specifically describes the main change: fixing cache billing calculation in channel test quota logic.
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 unit tests (beta)
  • Create PR with unit tests

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 and usage tips.

@Brisbanehuang
Brisbanehuang marked this pull request as ready for review June 6, 2026 08:44

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

Actionable comments posted: 1

🧹 Nitpick comments (1)
controller/channel_test_internal_test.go (1)

44-59: ⚡ Quick win

Add a Claude-semantic regression case next to this one.

This only exercises the OpenAI-style prompt-cache+cache*ratio path. The production quota code has a separate Claude/message branch where cached tokens are not subtracted from the prompt base, so this test suite still won’t catch that mismatch in settleTestQuota. A second case with UsageSemantic: "anthropic" or Claude RelayInfo would pin that contract.

Based on learnings, Claude/OpenRouter billing paths intentionally treat cached prompt tokens differently from the generic OpenAI-style path.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@controller/channel_test_internal_test.go` around lines 44 - 59, Add a second
test in controller/channel_test_internal_test.go alongside
TestSettleTestQuotaAppliesCacheRatio that exercises the Claude/semantic billing
branch by calling settleTestQuota with a dto.Usage configured for the Claude
path (e.g., set UsageSemantic to "anthropic" or populate RelayInfo to indicate
Claude) and appropriate dto.Usage.PromptTokensDetails.CachedTokens; assert the
expected quota differs per the Claude rule (cached tokens not subtracted from
prompt base). Reference settleTestQuota, TestSettleTestQuotaAppliesCacheRatio,
dto.Usage, UsageSemantic, RelayInfo and types.PriceData when adding the new case
so the Claude/message branch is covered.

Source: Learnings

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@controller/channel-test.go`:
- Around line 549-553: The current quota calculation unconditionally subtracts
CachedTokens which is incorrect for Claude semantics; change the quotaTokens
computation to branch on the semantics: for non-Claude semantics compute
quotaTokens = promptTokens - cacheTokens + cacheTokens*priceData.CacheRatio +
completionTokens*priceData.CompletionRatio, but for Claude semantics do not
subtract cacheTokens (use quotaTokens = promptTokens +
cacheTokens*priceData.CacheRatio + completionTokens*priceData.CompletionRatio).
Locate the variables promptTokens, cacheTokens
(usage.PromptTokensDetails.CachedTokens), completionTokens, quotaTokens and
priceData in the function and implement the conditional using the existing
semantics indicator (e.g., usage.Semantic or an isClaudeSemantic() check) so
Claude/OpenRouter paths match the runtime quota logic.

---

Nitpick comments:
In `@controller/channel_test_internal_test.go`:
- Around line 44-59: Add a second test in
controller/channel_test_internal_test.go alongside
TestSettleTestQuotaAppliesCacheRatio that exercises the Claude/semantic billing
branch by calling settleTestQuota with a dto.Usage configured for the Claude
path (e.g., set UsageSemantic to "anthropic" or populate RelayInfo to indicate
Claude) and appropriate dto.Usage.PromptTokensDetails.CachedTokens; assert the
expected quota differs per the Claude rule (cached tokens not subtracted from
prompt base). Reference settleTestQuota, TestSettleTestQuotaAppliesCacheRatio,
dto.Usage, UsageSemantic, RelayInfo and types.PriceData when adding the new case
so the Claude/message branch is covered.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 733900d0-1a97-4b84-bdc0-8c1af9d92430

📥 Commits

Reviewing files that changed from the base of the PR and between adc390c and a26c974.

📒 Files selected for processing (2)
  • controller/channel-test.go
  • controller/channel_test_internal_test.go

Comment thread controller/channel-test.go
@Brisbanehuang
Brisbanehuang force-pushed the codex/fix-channel-test-cache-billing branch from a26c974 to 3b9a836 Compare June 6, 2026 08:50
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