Skip to content

fix: skip estimated tokens for abnormal streams without usage (#4168) - #6112

Closed
cat0825 wants to merge 5 commits into
QuantumNous:mainfrom
cat0825:codex/fix-4168-stream-no-estimate-billing
Closed

cat0825 wants to merge 5 commits into
QuantumNous:mainfrom
cat0825:codex/fix-4168-stream-no-estimate-billing

Conversation

@cat0825

@cat0825 cat0825 commented Jul 11, 2026 •

Copy link
Copy Markdown

⚠️ 提交说明 / PR Notice

Important

  • 请提供人工撰写的简洁摘要,避免直接粘贴未经整理的 AI 输出。

📝 变更描述 / Description

当流式请求异常结束(client_gone/timeout 等)且上游未返回 usage 时,不再使用估算 prompt tokens 结算扣费。正常结束或上游提供 usage 的路径保持不变,避免误伤。

This PR was AI-assisted and manually reviewed before submission.

🚀 变更类型 / Type of change

  • 🐛 Bug 修复 (Bug fix) - 请关联对应 Issue,避免将设计取舍、理解偏差或预期不一致直接归类为 bug
  • ✨ 新功能 (New feature) - 重大特性建议先通过 Issue 沟通
  • ⚡ 性能优化 / 重构 (Refactor)
  • 📝 文档更新 (Documentation)

🔗 关联任务 / Related Issue

✅ 提交前检查项 / Checklist

  • 人工确认: 我已亲自整理并撰写此描述,没有直接粘贴未经处理的 AI 输出。
  • 非重复提交: 我已搜索现有的 Issues 与 PRs,确认不是重复提交。
  • Bug fix 说明: 若此 PR 标记为 Bug fix,我已提交或关联对应 Issue,且不会将设计取舍、预期不一致或理解偏差直接归类为 bug。
  • 变更理解: 我已理解这些更改的工作原理及可能影响。
  • 范围聚焦: 本 PR 未包含任何与当前任务无关的代码改动。
  • 本地验证: 已在本地运行并通过测试或手动验证,维护者可以据此复核结果。
  • 安全合规: 代码中无敏感凭据,且符合项目代码规范。

📸 运行证明 / Proof of Work

docker run --rm -v "$PWD":/work -w /work -e GOMODCACHE=/gomod -e GOCACHE=/gocache golang:1.25.1 go test ./service -run 'TestCalculateTextQuotaSummary'
ok  	github.com/QuantumNous/new-api/service	0.021s

Summary by CodeRabbit

  • Bug Fixes

    • Prevented quota deductions when a text stream ends abnormally and usage information is unavailable.
    • Preserved estimated prompt-token usage for normally completed streams when usage information is missing.
    • Added clearer processing details when deductions are skipped after abnormal stream termination.
  • Tests

    • Added coverage for normal and abnormal stream completion scenarios.

@coderabbitai

coderabbitai Bot commented Jul 11, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

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: 72eb99f1-0675-469d-9c19-dc636b8e88fc

📥 Commits

Reviewing files that changed from the base of the PR and between 918427d and d14f8c4.

📒 Files selected for processing (2)
  • service/text_quota.go
  • service/text_quota_abnormal_stream_test.go
🚧 Files skipped from review as they are similar to previous changes (2)
  • service/text_quota_abnormal_stream_test.go
  • service/text_quota.go

Included review availability: Your plan provides up to 10 included reviews per hour; 6 remain after this review.


Walkthrough

Text quota settlement skips estimated prompt tokens for abnormal streaming responses without upstream usage, records the skipped billing reason, and retains estimation for normally completed streams. Tests cover both outcomes.

Changes

Text quota billing

Layer / File(s) Summary
Abnormal stream usage handling and validation
service/text_quota.go, service/text_quota_abnormal_stream_test.go
Abnormal streams without upstream usage use empty usage data, resulting in zero tokens and quota. Normal streams retain estimated prompt tokens. The skipped billing reason is added to extraContent.

Estimated code review effort: 2 (Simple) | ~10 minutes

Merge Risk: ⚪ Minimal · up to d14f8

The change narrowly adjusts billing for abnormal streams without upstream usage while preserving normal and usage-backed paths; no actionable merge-blocking risk remains beyond normal checks and review.

Poem

I’m a rabbit guarding the quota gate,
Broken streams now settle at zero rate.
Finished streams keep estimates in line,
Missing usage no longer makes charges climb.
Hop, hop—the billing path is fine!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 22.22% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 9 functions across 3 files. 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 describes the primary change: skipping estimated tokens for abnormal streams without upstream usage.
Linked Issues check ✅ Passed The changes address issue #4168 by skipping estimated prompt tokens when an abnormal stream has no upstream usage, producing zero quota and enabling the pre-authorized billing refund. Normal streams r…
Out of Scope Changes check ✅ Passed All changes are related to issue #4168. The implementation updates abnormal-stream quota handling and adds focused regression tests. No unrelated code changes are identified.
Full details: Linked Issues check

Explanation

The changes address issue #4168 by skipping estimated prompt tokens when an abnormal stream has no upstream usage, producing zero quota and enabling the pre-authorized billing refund. Normal streams retain estimated usage behavior, and regression tests cover both paths.

  • Fix all pre-merge checks with AI
✨ 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.

@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

🤖 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 `@service/text_quota_test.go`:
- Around line 153-200: The added billing-usage tests depend on undefined DTO and
quota symbols, so they cannot compile in the current tree. Before retaining
these tests in
TestCalculateTextQuotaSummaryUsesClaudeBillingUsageBeforeTopLevelUsage and the
related Claude/Gemini/OpenAI cases, land or restore the prerequisite definitions
for Usage.BillingUsage, the dto.New*BillingUsage helpers, effectiveBillingUsage,
and dto.BillingUsageSemantic* constants; otherwise remove the dependent tests
until that stack layer is available.
🪄 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: 2e121a73-f549-4120-a7a2-9e4a04f9bb50

📥 Commits

Reviewing files that changed from the base of the PR and between b04b7f9 and 5e7a804.

📒 Files selected for processing (1)
  • service/text_quota_test.go

Comment thread service/text_quota_test.go Resolved

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

🧹 Nitpick comments (1)
service/text_quota_abnormal_stream_test.go (1)

39-40: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Use assert for non-fatal value checks.

These assertions validate expected values and should use assert.Zero/assert.Equal; reserve require for setup and fatal preconditions.

As per coding guidelines, new or substantially rewritten Go backend tests must use require for setup and fatal assertions and assert for non-fatal value checks.

Also applies to: 67-68

🤖 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 `@service/text_quota_abnormal_stream_test.go` around lines 39 - 40, Replace the
non-fatal require.Zero checks for summary.TotalTokens and summary.Quota,
including the corresponding assertions at the additionally affected lines, with
assert.Zero. Keep require for setup and fatal preconditions only.

Source: Coding guidelines

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

Nitpick comments:
In `@service/text_quota_abnormal_stream_test.go`:
- Around line 39-40: Replace the non-fatal require.Zero checks for
summary.TotalTokens and summary.Quota, including the corresponding assertions at
the additionally affected lines, with assert.Zero. Keep require for setup and
fatal preconditions only.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 98cc2e33-14dc-40fc-915f-b4b14a7a17b3

📥 Commits

Reviewing files that changed from the base of the PR and between 14389c7 and 45ab6c7.

📒 Files selected for processing (1)
  • service/text_quota_abnormal_stream_test.go

@cat0825

cat0825 commented Jul 13, 2026

Copy link
Copy Markdown
Author

已将分支冲突处理完毕并补充异常流回归测试;GitHub 当前显示 MERGEABLE,CodeRabbit 已通过。PR 仍处于 draft,但当前作者账号没有 ready for review 权限;烦请维护者协助转为 Ready。

MAXeaglet pushed a commit to MAXeaglet/new-api that referenced this pull request Jul 17, 2026
@coderabbitai

coderabbitai Bot commented Aug 29, 2026

Copy link
Copy Markdown
Contributor

Note

GitHub couldn't provide a complete incremental comparison for this pull request, so CodeRabbit is performing a full review instead. This review may take a little longer.

@cat0825

cat0825 commented Aug 29, 2026

Copy link
Copy Markdown
Author

已 rebase 到最新 main(此前落后 190 个 commit,现在 ahead 5, behind 0),无冲突,MERGEABLE。

新 head 上 CI 全绿:Backend vet, build, and test pass、Frontend typecheck and test pass、CodeRabbit review completed。

范围未变,仍只是 #4168:异常流(没有 usage 的流式响应)不再按预估 token 计费。

@Calcium-Ion @seefs001 麻烦 review。同上,这个 PR 还是 draft 且我的账号没有 ready for review 权限,烦请帮忙转 Ready。

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.

bug: stream 失败(client_gone/timeout)且 completion_tokens=0 时仍按 prompt_tokens 扣费

2 participants