Skip to content

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

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

fix: isolate subscription pre-consume by request group (#5200)#6090
cat0825 wants to merge 2 commits into
QuantumNous:mainfrom
cat0825:codex/fix-5200-subscription-group

Conversation

@cat0825

@cat0825 cat0825 commented Jul 10, 2026

Copy link
Copy Markdown
Contributor

⚠️ 提交说明 / 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 输出。
  • 非重复提交: 我已搜索现有的 IssuesPRs,确认不是重复提交。
  • 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
    • Subscription quota pre-consumption now respects the requested upgrade group.
    • Billing sessions preserve upgrade-group information when allocating subscription funds.
  • Bug Fixes
    • Prevented quota and wallet overflow checks from using subscription plans that belong to a different upgrade group.
  • Tests
    • Added coverage for group-scoped pre-consumption behavior, including backward-compatible handling of empty upgrade-group plans.

@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

Run ID: 8ed66998-c879-4fd7-81aa-aa902a5d3dba

📥 Commits

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

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

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

Possibly related PRs

Poem

A rabbit hops through groups so neat,
Matching plans now claim the treat.
Mismatched credits stay in place,
Wallet checks follow billing’s trace.
“Nibble-safe quotas!” sings the hare.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly summarizes the main change: making subscription pre-consume respect request groups.
Linked Issues check ✅ Passed The PR matches #5200 by passing the request group through billing and skipping subscriptions whose upgrade_group does not match.
Out of Scope Changes check ✅ Passed The added tests and schema cleanup support the group-aware subscription change and do not introduce unrelated scope.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
✨ 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
@cat0825

cat0825 commented Jul 10, 2026

Copy link
Copy Markdown
Contributor 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
Contributor 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
Contributor 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
Contributor 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
Contributor Author

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

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

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