Skip to content

fix: decrement used_quota when refunding async task quota - #4323

Open
octo-patch wants to merge 1 commit into
QuantumNous:mainfrom
octo-patch:fix/issue-4211-refund-used-quota
Open

octo-patch wants to merge 1 commit into
QuantumNous:mainfrom
octo-patch:fix/issue-4211-refund-used-quota

Conversation

@octo-patch

@octo-patch octo-patch commented Apr 18, 2026 •

Copy link
Copy Markdown

Fixes #4211

Problem

When an async task fails (triggering RefundTaskQuota) or is over-charged (triggering RecalculateTaskQuota with a negative delta), the system correctly restores the user's remaining quota (wallet balance) but does not decrement used_quota. Since the frontend displays total quota as remaining + used, every refund inflates the total by the refunded amount.

Example from the issue:

  • Start: remaining ¥10, used ¥0, total ¥10
  • After pre-charge: remaining ¥7.74, used ¥2.26, total ¥10 ✅
  • After task failure refund: remaining ¥10, used ¥2.26 (unchanged), total ¥12.26 ❌

Root causes in service/task_billing.go:

  1. RefundTaskQuota: calls taskAdjustFunding(-quota) but never calls UpdateUserUsedQuota or UpdateChannelUsedQuota.
  2. RecalculateTaskQuota: in the quotaDelta > 0 (extra charge) branch it correctly calls UpdateUserUsedQuotaAndRequestCount + UpdateChannelUsedQuota, but the quotaDelta < 0 (refund) branch had no such calls.

Solution

  • Add model.UpdateUserUsedQuota(id, quota int) — like UpdateUserUsedQuotaAndRequestCount but without incrementing request_count, suitable for refund adjustments.
  • RefundTaskQuota: after restoring the wallet, call model.UpdateUserUsedQuota(task.UserId, -quota) and model.UpdateChannelUsedQuota(task.ChannelId, -quota).
  • RecalculateTaskQuota refund branch: call the same two functions with quotaDelta (which is negative).

Testing

  1. Set up a user with an initial balance (e.g., ¥10).
  2. Trigger an async task that pre-charges (e.g., ¥2.26).
  3. Let the task fail so RefundTaskQuota is called.
  4. Verify: remaining = ¥10, used = ¥0, total = ¥10 (no inflation).

Summary by CodeRabbit

Release Notes

  • Bug Fixes
    • Enhanced quota refund operations to properly track used quota at both user and channel levels.
    • Improved quota recalculation accuracy during refund scenarios.

…tumNous#4211)

When an async task fails or is over-charged and triggers a refund, the
system correctly returned quota to the user's wallet but forgot to
decrease their used_quota. This caused the displayed "total quota"
(remaining + used) to inflate by the refunded amount on every refund.

Changes:
- Add exported model.UpdateUserUsedQuota that adjusts used_quota only,
  without touching request_count (unlike UpdateUserUsedQuotaAndRequestCount).
- RefundTaskQuota: call UpdateUserUsedQuota(-quota) and
  UpdateChannelUsedQuota(-quota) after restoring the wallet balance.
- RecalculateTaskQuota: extend the refund branch (quotaDelta < 0) to
  call UpdateUserUsedQuota and UpdateChannelUsedQuota with the negative
  delta, mirroring what the charge branch already does.
@coderabbitai

coderabbitai Bot commented Apr 18, 2026 •

Copy link
Copy Markdown
Contributor

Walkthrough

The changes introduce a new function to update user-used quota independently and apply it to task billing refund operations to correctly decrement used quota during refunds, fixing a bug where total quota calculations became inaccurate.

Changes

Cohort / File(s) Summary
New Quota Update Function
model/user.go
Added exported function UpdateUserUsedQuota(id int, quota int) that updates used_quota only, with conditional batching logic mirroring the existing UpdateUserUsedQuotaAndRequestCount pattern.
Task Billing Refund Operations
service/task_billing.go
Modified RefundTaskQuota to decrement persisted used quota for both user and channel after refund processing. Modified RecalculateTaskQuota to update used quota counters when refund cases occur (quotaDelta <= 0).

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~12 minutes

Poem

🐰 A quota bug has hopped away,
Used counters now decay the right way,
Refunds restore both old and new,
Total sums stay honest and true! 🌟

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 60.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 accurately describes the main change: adding logic to decrement used_quota during async task refunds, which directly addresses the core problem identified in the PR objectives.
Linked Issues check ✅ Passed All code changes directly address the objectives in issue #4211: added UpdateUserUsedQuota function and integrated it into RefundTaskQuota and RecalculateTaskQuota to decrement used_quota on refunds.
Out of Scope Changes check ✅ Passed All changes are scoped to fixing issue #4211: new UpdateUserUsedQuota function in model/user.go and updates to RefundTaskQuota and RecalculateTaskQuota in service/task_billing.go are directly necessary for the solution.

✏️ 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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@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 the current code and only fix it if needed.

Inline comments:
In `@service/task_billing.go`:
- Around line 167-169: The refund path must symmetrically decrement used_quota
without touching request_count: replace the prior pre-charge increment usage by
calling UpdateUserUsedQuota(task.UserId, -quota) and
UpdateChannelUsedQuota(task.ChannelId, -quota) (mirroring
UpdateUserUsedQuotaAndRequestCount for charge) while keeping request_count
unchanged; ensure the early guard if quota == 0 return remains and that you
restore the funding source first, then call UpdateUserUsedQuota and
UpdateChannelUsedQuota so used_quota is decremented after refunds are applied.
🪄 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: eaa20577-551d-4b34-beb0-3249e1bf8986

📥 Commits

Reviewing files that changed from the base of the PR and between 5b9dcf1 and c397407.

📒 Files selected for processing (2)
  • model/user.go
  • service/task_billing.go

Comment thread service/task_billing.go
Comment on lines +167 to +169
// 3. 减少已用额度统计
model.UpdateUserUsedQuota(task.UserId, -quota)
model.UpdateChannelUsedQuota(task.ChannelId, -quota)

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.

⚠️ Potential issue | 🟡 Minor

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Find async task pre-charge sites and check they increment used_quota symmetrically.
rg -nP --type=go -C3 '\bDecreaseUserQuota\s*\(|PostConsumeUserSubscriptionDelta\s*\(' 
echo "---"
rg -nP --type=go -C2 'UpdateUserUsedQuota(AndRequestCount)?\s*\('

Repository: QuantumNous/new-api

Length of output: 8366


🏁 Script executed:

# Check if this PR modifies funding_source.go or other pre-charge paths
# Look for git diff or check which files are in the PR
git diff --name-only HEAD~1 HEAD 2>/dev/null | grep -E '(funding_source|quota)\.go' || echo "Unable to check git diff, checking file sizes instead"
# Get context on the billing functions in task_billing.go to understand the complete flow
fd task_billing.go --exec wc -l {} \;
head -200 service/task_billing.go | tail -60

Repository: QuantumNous/new-api

Length of output: 1862


Refund correctly decrements used_quota — fix matches issue #4211.

Lines 168-169 properly mirror the pre-charge increment at line 63 (UpdateUserUsedQuotaAndRequestCount). Using UpdateUserUsedQuota with a negative value symmetrically decrements both user and channel used_quota, which resolves the total-inflation bug. request_count is intentionally left unchanged, which is correct behavior for a refund.

The guard at line 161 (if quota == 0 return) and the sequence—restore funding source first (line 161), then restore used_quota (lines 168-169)—are sound.

Note: This PR's changes to task_billing.go maintain internal consistency. However, if the broader codebase has other async pre-charge paths that increase used_quota independently, those sites should also have corresponding refund paths to prevent the used_quota from going negative. Scope this validation to other files if needed.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@service/task_billing.go` around lines 167 - 169, The refund path must
symmetrically decrement used_quota without touching request_count: replace the
prior pre-charge increment usage by calling UpdateUserUsedQuota(task.UserId,
-quota) and UpdateChannelUsedQuota(task.ChannelId, -quota) (mirroring
UpdateUserUsedQuotaAndRequestCount for charge) while keeping request_count
unchanged; ensure the early guard if quota == 0 return remains and that you
restore the funding source first, then call UpdateUserUsedQuota and
UpdateChannelUsedQuota so used_quota is decremented after refunds are applied.

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