Repository navigation
fix(cloudflare): preserve cached token usage in chat responses - #8342
donaldxdonald wants to merge 1 commit into
Conversation
|
No actionable comments were generated in the recent review. WalkthroughThe Cloudflare relay validates upstream usage for streaming and non-streaming chat responses. It uses valid token counts when available and estimates usage otherwise. Streaming responses now preserve upstream delta roles and omit empty usage-only frames from forwarded output. ChangesCloudflare Chat Usage
Estimated code review effort: 3 (Moderate) | ~20 minutes Change: Bug fix Suggested reviewers: Merge Risk:
|
Agent
Links
User request
Out of scope — refuse
Open gate — do not open unless all are satisfied
go buildor tests passed: yesKind
Issue facts
@cf/deepseek-ai/deepseek-v4.1-flash-1017、OpenAI Chat Completions、非透传。原日志为POST /v1/chat/completions,本次实测为 Playground 的POST /pg/chat/completions,HTTP 200。Billing 表达式为tier("base", p * 0.04 + c * 0.08 + cr * 0.008),分组倍率 1;原消费日志为local_count_tokens=true、usage_billing_path="local"、cache_tokens=0。按本次上游用量,舍入前应为(47*0.04+12*0.08+2560*0.008)/1000000=$0.00002332,未提取该次合成请求扣费日志。部署为官方镜像、VPS / Docker Compose / PostgreSQL,最初报告 rc.47,本次页面显示 rc.51,未独立核对容器标签。Frontend、部署升级故障不适用。Change
Cloudflare Chat Completions 优先采用经过总量与缓存边界校验的上游累计 usage。流式只在正常结束后使用累计结果,不累加分片增量;按客户端设置最多发送一条最终 usage。缺失、无效或中断时沿用本地估算。仅提取总输入、总输出和缓存读取字段,避免接受无关计费字段。
Research
Duplicate / prior art
Cloudflare cache、cloudflare usageCONFLICTING。用户明确要求提交基于当前 main 的修复。本 PR 聚焦已复现的缓存用量丢失,不声称替代 fix(cloudflare): preserve upstream reasoning token usage #6266 的全部推理明细及回退改动。Docs and code
pkg/billingexpr/expr.md规定显式引用cr时从p扣除缓存读取。cfStreamHandler/cfHandler原先无条件调用service.ResponseText2Usage,该函数只估算文本并设置本地计数标记;Cloudflare 已在streamSupportedChannels中。Cloudflare 模型文档及缓存文档支持缓存读取,实测上游返回prompt_tokens_details.cached_tokens。Alternatives considered
Files
relay/channel/cloudflare/relay_cloudflare.gocontroller/channel_test_request_test.goBehavior
Verification
57345547b,将生产文件暂时恢复为该提交版本,保留新测试,运行go test ./controller -run '^TestCloudflareChatUsage/stream_summary$' -count=1,失败并观测到输入 4000、缓存 0,预期为 3554、3456。应用补丁后,go test ./controller -run '^TestCloudflareChatUsage$' -count=1 -v的 12 个用例全部通过。go test ./controller ./relay ./relay/channel/cloudflare ./relay/channel/openai ./service通过,controller 44.105s、relay 0.823s、openai 0.671s、service 14.451s,cloudflare 无独立测试文件。gofmt -l无输出,git diff --check通过。'Cache usage regression test 2026-11-16.\n' + 'The quick brown fox jumps over the lazy dog.\n'.repeat(256) + '\nReply with only OK.',stream=true、max_tokens=12,未显式设置stream_options。Cloudflare 直连两次均正常返回 OK、[DONE],输入 2607、输出 12、缓存 2496;New API 重复生成同一输入,得到上文同一响应中缓存 2560 → 0 的差异。该实测验证原问题,修复结果由回归测试验证。Risks
[DONE]时仍会回退本地估算,缓存无法从文本推算。Scope check
Summary by CodeRabbit