fix: account for cache tokens in channel tests
⚠️ 提交说明 / PR Notice
[!IMPORTANT]
- 请提供人工撰写的简洁摘要,避免直接粘贴未经整理的 AI 输出。
📝 变更描述 / Description
(简述:做了什么?为什么这样改能生效?请基于你对代码逻辑的理解来写,避免粘贴未经整理的内容)
渠道模型测试的非阶梯计费原先使用了一套简化公式,只计算普通输入和输出 tokens,没有复用正式请求链路中的文本计费逻辑,因此遇到 cache read/write tokens 时会漏算缓存部分。这个改动让渠道测试结算复用正常文本请求的 quota 计算,并补充缓存 token 语义推断和回归测试,避免测试日志中的消耗金额与实际模型用量不一致。
🚀 变更类型 / Type of change
- [x] 🐛 Bug 修复 (Bug fix) - 请关联对应 Issue,避免将设计取舍、理解偏差或预期不一致直接归类为 bug
- [ ] ✨ 新功能 (New feature) - 重大特性建议先通过 Issue 沟通
- [ ] ⚡ 性能优化 / 重构 (Refactor)
- [ ] 📝 文档更新 (Documentation)
🔗 关联任务 / Related Issue
- Closes # (如有)
✅ 提交前检查项 / Checklist
- [x] 人工确认: 我已亲自整理并撰写此描述,没有直接粘贴未经处理的 AI 输出。
- [x] 非重复提交: 我已搜索现有的 Issues 与 PRs,确认不是重复提交。
- [x] Bug fix 说明: 若此 PR 标记为
Bug fix,我已提交或关联对应 Issue,且不会将设计取舍、预期不一致或理解偏差直接归类为 bug。 - [x] 变更理解: 我已理解这些更改的工作原理及可能影响。
- [x] 范围聚焦: 本 PR 未包含任何与当前任务无关的代码改动。
- [x] 本地验证: 已在本地运行并通过测试或手动验证,维护者可以据此复核结果。
- [x] 安全合规: 代码中无敏感凭据,且符合项目代码规范。
📸 运行证明 / Proof of Work
(请在此粘贴截图、关键日志或测试报告,以证明变更生效)
已通过本地回归测试:
docker run --rm -v /Users/dave/workspace/new-api:/workspace -w /workspace golang:1.25.1 go test ./service ./controller -count=1
Summary by CodeRabbit
-
Bug Fixes
- Quota calculations now include cached input tokens, ensuring accurate usage and billing when token caching is present.
-
New Features
- Improved detection of cache-separated token usage and enhanced support for Anthropic Claude–style usage semantics.
-
Tests
- Added unit tests verifying cached-token handling, inferred usage semantics, and corrected quota results.
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: 84ea9e37-d37e-4182-a07f-6f14be4364be
📥 Commits
Reviewing files that changed from the base of the PR and between 0218a3a693b9dff9284db2e362cd0a9f19bb4e85 and 38ac4a3f295cc527f12a204a431e914f6421d74e.
📒 Files selected for processing (2)
controller/channel-test.gocontroller/channel_test_internal_test.go
🚧 Files skipped from review as they are similar to previous changes (2)
- controller/channel_test_internal_test.go
- controller/channel-test.go
Walkthrough
Adds detection for Anthropic-style separated cache-read usage, exposes CalculateTextQuotaForUsage to compute text quotas without logging, refactors settleTestQuota to use that helper, and adds tests verifying cache-inclusive quota calculation.
Changes
Cache-aware quota calculation and integration
| Layer / File(s) | Summary |
|---|---|
Cache detection and quota calculation helper service/text_quota.go, service/text_quota_test.go |
Adds usageLooksLikeSeparatedInputCache to detect separated cache-read token patterns, updates usageSemanticFromUsage to infer "anthropic" when detected, and exports CalculateTextQuotaForUsage which returns the computed quota (delegates to calculateTextQuotaSummary). Includes unit test validating inferred semantic flags, preserved prompt tokens, and quota == 989 for separated cache reads. |
Test quota handler integration and validation controller/channel-test.go, controller/channel_test_internal_test.go |
settleTestQuota now ensures info exists, assigns info.PriceData, and calls service.CalculateTextQuotaForUsage instead of performing inline quota math. Adds time import and new test TestSettleTestQuotaIncludesCacheReadTokens asserting quota includes cached input tokens (expected 989). |
Sequence Diagram
sequenceDiagram
participant CalculateTextQuotaForUsage
participant usageSemanticFromUsage
participant usageLooksLikeSeparatedInputCache
participant calculateTextQuotaSummary
CalculateTextQuotaForUsage->>usageSemanticFromUsage: pass relayInfo, usage
usageSemanticFromUsage->>usageLooksLikeSeparatedInputCache: check cached token pattern
usageLooksLikeSeparatedInputCache-->>usageSemanticFromUsage: returns cache-detected
usageSemanticFromUsage-->>CalculateTextQuotaForUsage: infer "anthropic" semantic
CalculateTextQuotaForUsage->>calculateTextQuotaSummary: compute quota with inferred semantic
calculateTextQuotaSummary-->>CalculateTextQuotaForUsage: return Quota
Estimated code review effort
🎯 3 (Moderate) | ⏱️ ~20 minutes
Possibly related PRs
- QuantumNous/new-api#3438: Adjusts quota accounting by guarding OpenRouter-specific handling with
IsClaudeUsageSemanticflag that this PR sets during separated-cache detection. - QuantumNous/new-api#2798: Populates cached token fields; those tokens are now detected and billed by this PR's separated-cache inference logic.
- QuantumNous/new-api#2811: Also deals with Claude cached input token representation relied on by the quota inference in this PR.
Suggested reviewers
- seefs001
Poem
🐰 Hopping through tokens, soft and spry,
I count the cache beneath the sky.
Anthropic reads no longer hide,
Quota tallies now align with pride.
— a rabbit's hop of code and rhyme
🚥 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 'fix: account for cache tokens in channel tests' accurately describes the main change: modifying channel test quota calculation to properly account for cache tokens, which were previously omitted. |
| 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.
Comment @coderabbitai help to get the list of available commands and usage tips.
#5419