Skip to content

fix(cloudflare): preserve cached token usage in chat responses - #8342

Open
donaldxdonald wants to merge 1 commit into
QuantumNous:mainfrom
donaldxdonald:codex/fix-cloudflare-cached-usage
Open

donaldxdonald wants to merge 1 commit into
QuantumNous:mainfrom
donaldxdonald:codex/fix-cloudflare-cached-usage

Conversation

@donaldxdonald

@donaldxdonald donaldxdonald commented Nov 15, 2026 •

Copy link
Copy Markdown
Contributor

Agent

  • Tool: Codex,代码由 AI 辅助生成
  • Tool version: 本机 codex-cli 0.169.0
  • Model (full id): 运行环境未提供完整模型 ID
  • Host (CLI / IDE / GitHub coding agent / other): Codex 桌面
  • Date (UTC): 2026-11-15

Links

User request

  • Verbatim:

    那 PR 没有后续更新了,而且 conflict 了。要不把我们这次修复提 PR 吧?

  • Later constraints or corrections from the user:

    确保只修复本次的问题,avoid over-engineering
    还有就是不要增加 relay_cloudflare_test.go 需要遵循仓库的规范,在对应的地方增加测试

Out of scope — refuse

  • Matched: no
  • If yes, what was told to the user: 不适用,Cloudflare 官方渠道,未开启透传

Open gate — do not open unless all are satisfied

  • Out of scope (including pass-through-only forwarding): no
  • Usage / configuration / integration (answered instead of opening): no
  • Required issue facts present without invention: yes,Cloudflare 渠道未使用有效上游 Usage 导致 Reasoning Token 漏算 #6265 的同一根因,本次缓存复现补充如下
  • Verification is actual commands or steps and observed results, not only go build or tests passed: yes
  • Body is short and factual; no unfiltered AI-generated text: yes
  • Open: yes
  • If no, what was told to the user: 不适用

Kind

  • Bug fix
  • New feature
  • Performance / refactor
  • Docs
  • Other:

Issue facts

  • Actual behavior: Cloudflare 渠道未使用有效上游 Usage 导致 Reasoning Token 漏算 #6265 报告 Cloudflare usage 被本地估算覆盖。本次同一 SSE 响应中,上游累计输入 2607、输出 12、缓存读取 2560;New API 追加的最终值变为 3467、2、0。
  • Impact: 缓存折扣无法应用,输入和输出数量也失真。
  • Frequency: 用户报告持续未见缓存;本次合成请求中有一次缓存命中请求明确复现。
  • Evidence that the problem is in new-api rather than the client or upstream: 同一代理响应保留了上游缓存命中帧,随后追加缓存为 0 的最终帧;等价直连请求两次均返回缓存读取 2496。
  • Applicable types and their fields: Relay 为 Cloudflare、@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

Docs and code

Alternatives considered

Files

Path Why
relay/channel/cloudflare/relay_cloudflare.go 流式及非流式保留累计 Token 和缓存读取数量
controller/channel_test_request_test.go 在现有文件中增加 12 个回归用例

Behavior

  • Before: 有效上游 usage 也被本地估算覆盖,流式同时泄露分片 usage 并追加另一组最终值。
  • After: 有效累计 usage 用于结算及最终响应;分片 usage 不再被当作客户端最终用量。
  • Explicit non-goals / leftover work: 不改模型价格、数据库、其他渠道或请求参数;不扩展推理明细及本地推理估算。

Verification

  • Commands and results: 基于 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 通过。
  • Manual steps and observed result: 合成输入为 '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 的差异。该实测验证原问题,修复结果由回归测试验证。
  • UI: screenshot or recording (or why none): 无 UI 改动,使用 SSE 回包及断言验证。
  • Tests added or updated, or why none: 流式累计与增量、客户端不请求 usage、空尾帧、过期摘要、中断回退、非流式、缓存越界、无关计费字段。
  • Databases / providers / platforms exercised: Cloudflare Workers AI 实际请求;本地 Go 1.27.3 / macOS arm64。未改数据库行为,无数据库矩阵验证。
  • Not verified: 补丁部署后的真实请求、其他 Cloudflare 模型、Go 1.26.10、Linux;未运行整个仓库测试。

Risks

Scope check

  • Single focused change: yes
  • Secrets included: no
  • Out of scope (Coding Plan / reverse-engineered channel / third-party wrapper / Codex / pass-through-only forwarding): no

Summary by CodeRabbit

  • Bug Fixes
    • Usage details from Cloudflare responses are now validated before being reported. If they’re missing or inconsistent, usage is estimated from the response text instead.
    • For streamed responses, upstream usage is used only when the stream completes. Usage-only frames are no longer shown to clients, and streamed role labels are preserved.

@coderabbitai

coderabbitai Bot commented Nov 15, 2026 •

Copy link
Copy Markdown
Contributor

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

The 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.

Changes

Cloudflare Chat Usage

Layer / File(s) Summary
Usage validation and non-streaming responses
relay/channel/cloudflare/relay_cloudflare.go
The handler validates upstream token counts and cached-token counts. It uses valid upstream usage or estimates usage from response text.
Streaming usage handling
relay/channel/cloudflare/relay_cloudflare.go, controller/channel_test_request_test.go
The stream handler tracks completion, preserves delta roles, and forwards frames without usage fields. Tests cover valid, missing, and invalid usage across stream and non-stream responses.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Change: Bug fix

Suggested reviewers: calcium-ion, feitianbubu

Merge Risk: Minimal · up to 55ad9

This change keeps upstream cumulative and cached token usage for Cloudflare chat responses instead of overwriting it with local estimates. Fallback estimation remains for missing or invalid usage and for interrupted streams. No merge-blocking risk was identified, and the new regression tests cover the main cases.

Pre-merge checks: Passed 4

Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title names the fix (preserving cached token usage in Cloudflare chat responses) that matches the main change. The raw summary shows changes to cloudflareChatUsage, usage validation including cach…
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.
Full details: Title check

Explanation

The title names the fix (preserving cached token usage in Cloudflare chat responses) that matches the main change. The raw summary shows changes to cloudflareChatUsage, usage validation including cached-token counts, and the relay handler, all of which fit the title. The title is concise, specific, and follows the conventional commit style.

Finishing Touches

Generate unit tests (beta)

  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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

A rabbit checks the tokens in the stream,
And counts cached hops with care.
If upstream totals pass the test,
They travel through the air.
If not, the local counters help,
While “OK” stays in the hare.

Recent review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 48fe8040-4678-4a28-9360-81d3eb5a4096
Commits

Reviewing files that changed from the base of the PR and between 5734554 and 55ad9bd.

Files selected for processing: 2

  • controller/channel_test_request_test.go
  • relay/channel/cloudflare/relay_cloudflare.go

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

This branch has not been deployed

No deployments
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