Skip to content

fix: isolate subscription pre-consume by request group (#5200) - #6090

Closed
cat0825 wants to merge 3 commits into
QuantumNous:mainfrom
cat0825:codex/fix-5200-subscription-group
Closed

cat0825 wants to merge 3 commits into
QuantumNous:mainfrom
cat0825:codex/fix-5200-subscription-group

Conversation

@cat0825

@cat0825 cat0825 commented Jul 10, 2026 •

Copy link
Copy Markdown

⚠️ 提交说明 / PR Notice

Important

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

📝 变更描述 / Description

订阅预扣现在会校验请求实际使用的 group。带 upgrade_group 的订阅计划只覆盖同分组请求,避免跨分组模型错误扣订阅额度。billing session 会把 relayInfo.UsingGroup 传入预扣路径;UpgradeGroup 为空的计划保持原有兼容行为。

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 ./model -run 'TestPreConsumeUserSubscriptionForGroup'
ok  	github.com/QuantumNous/new-api/model	0.025s

Summary by CodeRabbit

  • New Features
    • Added upgrade-group–aware subscription quota pre-consumption and wallet overflow fallback.
    • Billing sessions now retain upgrade-group context when allocating subscription funds.
  • Bug Fixes
    • Prevented quota and wallet overflow checks from considering plans tied to different upgrade groups.
    • Preserved wildcard behavior for plans without an upgrade group.
  • Tests
    • Added coverage for group matching, mismatched plans, and wildcard compatibility.
    • Improved test database setup and cleanup for subscription records.

@coderabbitai

coderabbitai Bot commented Jul 10, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

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: 53697104-4bb0-417a-846a-353923570c4e

📥 Commits

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

📒 Files selected for processing (5)
  • model/subscription.go
  • model/subscription_group_test.go
  • model/task_cas_test.go
  • service/billing_session.go
  • service/funding_source.go
🚧 Files skipped from review as they are similar to previous changes (5)
  • service/funding_source.go
  • model/task_cas_test.go
  • service/billing_session.go
  • model/subscription_group_test.go
  • model/subscription.go

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


Walkthrough

Subscription billing now carries the relay group into quota pre-consumption and wallet-overflow checks. Group-aware selection trims request groups, skips mismatched subscription plans, and preserves empty-group compatibility. Tests verify selection and database isolation.

Changes

Subscription group scoping

Layer / File(s) Summary
Group-aware subscription selection
model/subscription.go
Adds group-scoped quota and wallet-overflow checks, normalizes request groups, and skips plans with mismatched non-empty upgrade groups.
Billing group propagation
service/funding_source.go, service/billing_session.go
Stores relayInfo.UsingGroup in SubscriptionFunding, passes it to pre-consumption, and applies it to wallet fallback checks.
Group selection validation
model/subscription_group_test.go, model/task_cas_test.go
Tests matching, mismatched, and wildcard plan selection while isolating pre-consumption records.

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

Merge Risk: ⚪ Minimal · up to 5aadf

The change limits subscription pre-consumption to matching request groups while preserving compatibility for plans without an upgrade group; no actionable merge-blocking risk remains after normal checks and review.

Poem

A rabbit checks each group with care,
Matching plans receive their share.
Mismatched plans remain untouched,
Wallet checks use the group passed.
Quotas hop along the right track.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 41.67% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 12 functions across 5 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 isolating subscription pre-consumption by request group and matches issue #5200.
Linked Issues check ✅ Passed The changes satisfy issue #5200. Subscription plans with a non-empty UpgradeGroup apply only to matching request groups, while empty UpgradeGroup values retain wildcard compatibility. Wallet overflow …
Out of Scope Changes check ✅ Passed All production and test changes support request-group subscription isolation, wallet fallback behavior, or the required test database setup. No unrelated code changes are evident.
Full details: Linked Issues check

Explanation

The changes satisfy issue #5200. Subscription plans with a non-empty UpgradeGroup apply only to matching request groups, while empty UpgradeGroup values retain wildcard compatibility. Wallet overflow checks also use the request group.

  • 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

🧹 Nitpick comments (1)
model/subscription_group_test.go (1)

48-63: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add a backward-compatibility test for empty UpgradeGroup.

The current test validates the skip behavior for mismatched groups. A plan with an empty UpgradeGroup should remain usable for any requestGroup — this is the core backward-compatibility guarantee stated in the PR objectives. Adding a test protects this invariant against future regressions.

♻️ Suggested additional test
+func TestPreConsumeUserSubscriptionForGroupEmptyUpgradeGroupBackwardCompat(t *testing.T) {
+	truncateTables(t)
+
+	const userID = 6101
+	seedGroupPlan(t, 6101, "")   // empty UpgradeGroup — should match any group
+	seedGroupSubscription(t, 6101, userID, 6101, 0)
+
+	res, err := PreConsumeUserSubscriptionForGroup("req-group-any", userID, "deepseek-v4", "some-other-group", 0, 300)
+	require.NoError(t, err)
+
+	assert.Equal(t, 6101, res.UserSubscriptionId)
+	assert.EqualValues(t, 300, groupSubscriptionUsed(t, 6101))
+}
🤖 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 `@model/subscription_group_test.go` around lines 48 - 63, Add a test alongside
TestPreConsumeUserSubscriptionForGroupSkipsMismatchedPlanGroup that seeds a
subscription whose plan has an empty UpgradeGroup, invokes
PreConsumeUserSubscriptionForGroup with a non-empty requestGroup, and asserts
the empty-group subscription is selected and its usage increases while
mismatched candidates remain unused.
🤖 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/billing_session.go`:
- Line 390: Update UserActiveSubscriptionsAllowWalletOverflow to filter active
subscriptions by requestGroup before evaluating allow_wallet_overflow; only
subscriptions matching the request’s group should be able to block wallet
fallback. Ensure the caller passes the relayInfo.UsingGroup value through the
request-group parameter and preserve existing behavior for matching
subscriptions.

---

Nitpick comments:
In `@model/subscription_group_test.go`:
- Around line 48-63: Add a test alongside
TestPreConsumeUserSubscriptionForGroupSkipsMismatchedPlanGroup that seeds a
subscription whose plan has an empty UpgradeGroup, invokes
PreConsumeUserSubscriptionForGroup with a non-empty requestGroup, and asserts
the empty-group subscription is selected and its usage increases while
mismatched candidates remain unused.
🪄 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: f79d87d5-d5fc-4c4c-a111-6e4deb786480

📥 Commits

Reviewing files that changed from the base of the PR and between f2c7cd3 and 535cfc1.

📒 Files selected for processing (5)
  • model/subscription.go
  • model/subscription_group_test.go
  • model/task_cas_test.go
  • service/billing_session.go
  • service/funding_source.go

Comment thread service/billing_session.go Resolved
@cat0825

cat0825 commented Jul 10, 2026

Copy link
Copy Markdown
Author

Addressed CodeRabbit feedback:

  1. Wallet overflow check is now group-aware via UserActiveSubscriptionsAllowWalletOverflowForGroup(userId, requestGroup).
  2. Added empty UpgradeGroup backward-compat pre-consume test.

Pushed in db1c1fe.

3 similar comments
@cat0825

cat0825 commented Jul 10, 2026

Copy link
Copy Markdown
Author

Addressed CodeRabbit feedback:

  1. Wallet overflow check is now group-aware via UserActiveSubscriptionsAllowWalletOverflowForGroup(userId, requestGroup).
  2. Added empty UpgradeGroup backward-compat pre-consume test.

Pushed in db1c1fe.

@cat0825

cat0825 commented Jul 10, 2026

Copy link
Copy Markdown
Author

Addressed CodeRabbit feedback:

  1. Wallet overflow check is now group-aware via UserActiveSubscriptionsAllowWalletOverflowForGroup(userId, requestGroup).
  2. Added empty UpgradeGroup backward-compat pre-consume test.

Pushed in db1c1fe.

@cat0825

cat0825 commented Jul 10, 2026

Copy link
Copy Markdown
Author

Addressed CodeRabbit feedback:

  1. Wallet overflow check is now group-aware via UserActiveSubscriptionsAllowWalletOverflowForGroup(userId, requestGroup).
  2. Added empty UpgradeGroup backward-compat pre-consume test.

Pushed in db1c1fe.

@cat0825

cat0825 commented Jul 11, 2026

Copy link
Copy Markdown
Author

@Calcium-Ion @t0ng7u 麻烦有空时 review 一下这个 PR。

范围:仅 #5200 — 订阅预扣按请求 group 隔离;CodeRabbit 反馈(wallet overflow 需 group-aware、empty UpgradeGroup 兼容测试)已在后续 commit 修完。谢谢。

@cat0825

cat0825 commented Jul 20, 2026

Copy link
Copy Markdown
Author

Rebased onto latest main to resolve the merge conflict.

Conflict was only in model/task_cas_test.go cleanup helpers (subscription_pre_consume_records delete). Kept the needed cleanup line and dropped the duplicate user_oauth_bindings delete already present upstream.

Local verification:

  • go test ./model -run 'TestPreConsumeUserSubscriptionForGroup|TestUserActiveSubscriptionsAllowWallet' -count=1 → ok

@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(此前落后 122 个 commit,现在 ahead 3, behind 0),无冲突,MERGEABLE。

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

范围未变,仍只是 #5200:按请求分组隔离订阅预扣。

@Calcium-Ion @seefs001 与 #6089 相邻,建议一并 review。

@seefs001 seefs001 closed this Aug 29, 2026
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: 订阅计费未校验模型分组 — 跨分组模型也能扣订阅额度

2 participants