Skip to content

fix(task): keep async task usage accounting consistent - #6754

Open
MokoYee wants to merge 1 commit into
QuantumNous:mainfrom
MokoYee:fix/async-task-usage-accounting
Open

MokoYee wants to merge 1 commit into
QuantumNous:mainfrom
MokoYee:fix/async-task-usage-accounting

Conversation

@MokoYee

@MokoYee MokoYee commented Aug 10, 2026 •

Copy link
Copy Markdown

⚠️ 提交说明 / PR Notice

Important

  • 本 PR 由 AI 辅助生成并提交,提交前已完成本地验证,请维护者复核。

📝 变更描述 / Description

异步任务提交时会将预扣额度计入用户和渠道累计用量。任务失败或实际费用低于预扣额度时,现有逻辑只恢复余额、订阅及令牌额度,没有同步回减累计用量,导致用户总额度虚增。

本次修改让失败退款和差额结算同步调整用户及渠道累计用量;结算阶段只修正最终用量,不再重复增加请求次数。同时补充全额退款、正负差额、退款失败和批量更新场景的回归测试。

与 #4323 相比,本 PR 基于当前 main,并补充了正差额结算请求次数和自动化测试覆盖。

本次修改由 AI 辅助实现,提交者已逐行审查并完成本地验证。

🚀 变更类型 / Type of change

  • 🐛 Bug 修复 (Bug fix)

🔗 关联任务 / Related Issue

✅ 提交前检查项 / Checklist

  • 人工确认: 我已亲自整理并撰写此描述,没有直接粘贴未经处理的 AI 输出。
  • 非重复提交: 我已搜索现有的 Issues 与 PRs,并在描述中说明与 fix: decrement used_quota when refunding async task quota #4323 的实质差异。
  • Bug fix 说明: 本 PR 已关联确认的 Bug Issue Bug 报告:异步任务退款导致用户总额度异常增加 #4211。
  • 变更理解: 我已理解这些更改的工作原理及可能影响。
  • 范围聚焦: 本 PR 未包含任何与当前任务无关的代码改动。
  • 本地验证: 已在本地运行并通过测试及静态检查。
  • 安全合规: 代码中无敏感凭据,且符合项目代码规范。

📸 运行证明 / Proof of Work

  • go test ./service ./model -count=1
  • go vet ./service ./model
  • git diff --check

以上命令均通过。

Summary by CodeRabbit

  • Bug Fixes
    • Corrected quota accounting for refunds and recalculations.
    • Refunds now reduce accumulated usage without altering request counts.
    • Difference settlements update user and channel usage accurately.
    • Prevented accounting changes when billing refunds fail.

@coderabbitai

coderabbitai Bot commented Aug 10, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Linked Issues check ✅ Passed The changes update used quota during refunds and difference settlement without altering request counts, satisfying issue #4211.
Out of Scope Changes check ✅ Passed All production and test changes directly support consistent user and channel quota accounting for asynchronous task refunds.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly summarizes the main change: fixing async task usage accounting consistency.
✨ 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.

@MokoYee
MokoYee force-pushed the fix/async-task-usage-accounting branch from 4933423 to 5ce5021 Compare August 10, 2026 11:14

@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: 2

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

118-126: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Make batch-update mode explicit in the test fixture.

UpdateUserUsedQuota and UpdateChannelUsedQuota switch between direct database writes and queued batch records using common.BatchUpdateEnabled. These tests read the database immediately after the service call. Unless truncate or TestMain sets and flushes this state, the assertions depend on ambient global state. Set the mode explicitly and add a separate batch-mode test with an explicit flush.

As per coding guidelines, backend test fixtures must initialize settings explicitly.

🤖 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/task_billing_test.go` around lines 118 - 126, Update the task billing
test fixtures around seedUsageAccounting and the related service-call tests to
set common.BatchUpdateEnabled explicitly instead of relying on ambient state.
Preserve direct-update coverage, add a separate batch-mode test that enables
batching and explicitly flushes queued updates before database assertions, and
restore the setting after each test to prevent global-state leakage.

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.

Inline comments:
In `@model/user.go`:
- Around line 1347-1353: Update UpdateUserUsedQuota and updateUserUsedQuota to
return and propagate a persistence error, treating zero affected rows as failure
instead of only logging database errors. Make the BatchUpdateEnabled path
retryable or durable by returning an equivalent result, then update the refund
and recalculation flows in task billing to handle failures and keep the task
marker pending until both user and channel usage updates succeed.

In `@service/task_billing.go`:
- Around line 249-251: Update the settlement flow at
service/task_billing.go:249-251 to atomically commit actualQuota with both user
and channel usage deltas, or make failed usage updates safely replayable. Also
update the refund/pending-marker transition at service/task_billing.go:181-185
so refund deltas are committed together with the state change and retries cannot
reapply -quota; use the existing task billing transition symbols and preserve
signed delta semantics.

---

Nitpick comments:
In `@service/task_billing_test.go`:
- Around line 118-126: Update the task billing test fixtures around
seedUsageAccounting and the related service-call tests to set
common.BatchUpdateEnabled explicitly instead of relying on ambient state.
Preserve direct-update coverage, add a separate batch-mode test that enables
batching and explicitly flushes queued updates before database assertions, and
restore the setting after each test to prevent global-state leakage.
🪄 Autofix

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 Plus

Run ID: 332644a5-3a46-46e5-8234-8545368daf63

📥 Commits

Reviewing files that changed from the base of the PR and between 9c97e78 and 4933423.

📒 Files selected for processing (4)
  • model/user.go
  • model/user_update_test.go
  • service/task_billing.go
  • service/task_billing_test.go

Comment thread model/user.go Resolved
Comment thread service/task_billing.go Resolved

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.

Bug 报告:异步任务退款导致用户总额度异常增加

1 participant