Files
new-api/service/subscription_settle_test.go
Seefs 1c0b4d6471 fix(billing): cap subscription usage at settlement instead of rejecting overrun (#8523)
* fix(billing): cap subscription usage at settlement instead of rejecting overrun

When a post-request settlement delta exceeds the remaining subscription quota,
PostConsumeUserSubscriptionDelta rejects the whole update and leaves
amount_used below amount_total. Subsequent requests with small pre-consume
estimates keep passing admission and become free, and secondary subscriptions
are never selected.

Add model.SettleUserSubscriptionDelta to cap positive settlement charges at
AmountTotal (or math.MaxInt64 for unlimited plans), log the uncovered
remainder, and return the applied delta. Route SubscriptionFunding.Settle and
async task settlement to it while keeping PostConsumeUserSubscriptionDelta
strict for reservations and Realtime in-session metering, and without changing
the FundingSource interface signature.

* test(billing): add regression coverage for capped subscription settlement

Consolidate regression cases in service/subscription_settle_test.go covering SettleUserSubscriptionDelta finite capping, unlimited MaxInt64 saturation, refund zero-flooring, BillingSession dual-subscription exhaustion and switching, strict PostConsumeQuota rejection for Realtime in-session metering, and async RecalculateTaskQuota overrun capping.
2026-12-02 15:11:32 +08:00

273 lines
9.4 KiB
Go

package service
import (
"context"
"fmt"
"math"
"net/http"
"net/http/httptest"
"testing"
"time"
"github.com/QuantumNous/new-api/common"
"github.com/QuantumNous/new-api/model"
relaycommon "github.com/QuantumNous/new-api/relay/common"
"github.com/QuantumNous/new-api/relaykit/dto"
"github.com/QuantumNous/new-api/relaykit/types"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func setupSubscriptionSettleTables(t *testing.T) {
t.Helper()
truncate(t)
require.NoError(t, model.DB.AutoMigrate(&model.SubscriptionPlan{}, &model.SubscriptionPreConsumeRecord{}))
t.Cleanup(func() {
model.DB.Exec("DELETE FROM subscription_pre_consume_records")
model.DB.Exec("DELETE FROM subscription_plans")
_ = model.PurgeSubscriptionPlanCache()
})
}
func seedSubscriptionPlanAndInstance(t *testing.T, userID int, total int64, used int64, allowWalletOverflow bool, endOffset time.Duration) *model.UserSubscription {
t.Helper()
plan := &model.SubscriptionPlan{
Title: fmt.Sprintf("Plan-%d", total),
DurationUnit: model.SubscriptionDurationDay,
DurationValue: 1,
TotalAmount: total,
QuotaResetPeriod: model.SubscriptionResetNever,
AllowWalletOverflow: common.GetPointer(allowWalletOverflow),
Enabled: true,
}
require.NoError(t, model.DB.Create(plan).Error)
now := model.GetDBTimestamp()
sub := &model.UserSubscription{
UserId: userID,
PlanId: plan.Id,
AmountTotal: total,
AmountUsed: used,
StartTime: now,
EndTime: now + int64(endOffset.Seconds()),
Status: "active",
AllowWalletOverflow: allowWalletOverflow,
}
require.NoError(t, model.DB.Create(sub).Error)
return sub
}
func newBillingTestContext(t *testing.T) *gin.Context {
t.Helper()
gin.SetMode(gin.TestMode)
c, _ := gin.CreateTestContext(httptest.NewRecorder())
c.Request = httptest.NewRequest(http.MethodPost, "/v1/chat/completions", nil)
return c
}
func TestSettleUserSubscriptionDelta(t *testing.T) {
setupSubscriptionSettleTables(t)
const userID = 901
seedUser(t, userID, 0)
t.Run("finite plan caps overrun and floors refund", func(t *testing.T) {
sub := seedSubscriptionPlanAndInstance(t, userID, 100, 0, false, time.Hour)
steps := []struct {
name string
delta int64
wantApplied int64
wantUsed int64
}{
{name: "normal charge", delta: 40, wantApplied: 40, wantUsed: 40},
{name: "overrun capped at total", delta: 75, wantApplied: 60, wantUsed: 100},
{name: "full plan avoids int64 overflow", delta: math.MaxInt64, wantApplied: 0, wantUsed: 100},
{name: "refund clamped at zero", delta: -500, wantApplied: -100, wantUsed: 0},
{name: "zero delta is no-op", delta: 0, wantApplied: 0, wantUsed: 0},
}
for _, tc := range steps {
applied, err := model.SettleUserSubscriptionDelta(sub.Id, tc.delta)
require.NoError(t, err, tc.name)
assert.Equal(t, tc.wantApplied, applied, tc.name)
assert.Equal(t, tc.wantUsed, getSubscriptionUsed(t, sub.Id), tc.name)
}
})
t.Run("unlimited plan saturates at MaxInt64 without overflow", func(t *testing.T) {
sub := seedSubscriptionPlanAndInstance(t, userID, 0, math.MaxInt64-10, false, time.Hour)
applied, err := model.SettleUserSubscriptionDelta(sub.Id, 100)
require.NoError(t, err)
assert.Equal(t, int64(10), applied)
assert.Equal(t, int64(math.MaxInt64), getSubscriptionUsed(t, sub.Id))
applied, err = model.SettleUserSubscriptionDelta(sub.Id, 1)
require.NoError(t, err)
assert.Zero(t, applied)
assert.Equal(t, int64(math.MaxInt64), getSubscriptionUsed(t, sub.Id))
})
t.Run("invalid subscription id returns error", func(t *testing.T) {
for _, id := range []int{0, -1} {
applied, err := model.SettleUserSubscriptionDelta(id, 10)
require.Error(t, err)
assert.Zero(t, applied)
}
})
}
func TestBillingSessionSubscriptionSettleOverrunSwitchesPlanAndRejects(t *testing.T) {
setupSubscriptionSettleTables(t)
const (
userID = 902
tokenID = 902
tokenInitialQuota = 40_000_000
planTotal = int64(15_000_000)
preConsume = 5_000
actualQuota = 2_250_375
fullDelta = int64(actualQuota - preConsume)
requestsPerPlan = 7
lastAppliedDelta = planTotal - int64(requestsPerPlan-1)*int64(actualQuota) - int64(preConsume)
)
seedUser(t, userID, 0)
seedToken(t, tokenID, userID, "sk-sub-overrun-switch", tokenInitialQuota)
subA := seedSubscriptionPlanAndInstance(t, userID, planTotal, 0, false, time.Hour)
subB := seedSubscriptionPlanAndInstance(t, userID, planTotal, 0, false, 2*time.Hour)
runRequest := func(seq int) (*relaycommon.RelayInfo, *types.NewAPIError) {
c := newBillingTestContext(t)
info := &relaycommon.RelayInfo{
RequestId: fmt.Sprintf("req-sub-overrun-%d", seq),
UserId: userID,
TokenId: tokenID,
TokenKey: "sk-sub-overrun-switch",
OriginModelName: "test-model",
UserSetting: dto.UserSetting{
BillingPreference: "subscription_first",
QuotaWarningEnabled: common.GetPointer(false),
},
}
if apiErr := PreConsumeBilling(c, preConsume, info); apiErr != nil {
return info, apiErr
}
require.NoError(t, SettleBilling(c, info, actualQuota))
return info, nil
}
// Requests 1..7 exhaust subscription A; request 7 caps at planTotal.
for i := range requestsPerPlan {
info, apiErr := runRequest(i + 1)
require.Nil(t, apiErr, "request %d should succeed on sub A", i+1)
assert.Equal(t, subA.Id, info.SubscriptionId)
if i < requestsPerPlan-1 {
assert.Equal(t, fullDelta, info.SubscriptionPostDelta)
} else {
assert.Equal(t, lastAppliedDelta, info.SubscriptionPostDelta)
require.NoError(t, info.Billing.Settle(actualQuota), "repeated settle must be idempotent")
assert.Equal(t, lastAppliedDelta, info.SubscriptionPostDelta)
other := model.NewLogOther()
appendBillingInfo(info, other)
snap := other.Snapshot()
assert.Equal(t, int64(preConsume)+lastAppliedDelta, snap["subscription_consumed"])
assert.Equal(t, int64(0), snap["subscription_remain"])
assert.Equal(t, planTotal, snap["subscription_used"])
}
}
assert.Equal(t, planTotal, getSubscriptionUsed(t, subA.Id))
assert.Zero(t, getSubscriptionUsed(t, subB.Id))
// Requests 8..14 automatically switch to subscription B and exhaust it.
for i := range requestsPerPlan {
info, apiErr := runRequest(requestsPerPlan + i + 1)
require.Nil(t, apiErr, "request %d should succeed on sub B", requestsPerPlan+i+1)
assert.Equal(t, subB.Id, info.SubscriptionId)
if i == requestsPerPlan-1 {
assert.Equal(t, lastAppliedDelta, info.SubscriptionPostDelta)
}
}
assert.Equal(t, planTotal, getSubscriptionUsed(t, subB.Id))
// Request 15 is rejected at pre-consume because both plans are full and wallet overflow is disabled.
_, apiErr := runRequest(2*requestsPerPlan + 1)
require.NotNil(t, apiErr)
assert.Equal(t, http.StatusForbidden, apiErr.StatusCode)
assert.Equal(t, types.ErrorCodeInsufficientUserQuota, apiErr.GetErrorCode())
// Token quota still accounts for the full actual cost of all 14 completed requests.
assert.Equal(t, tokenInitialQuota-2*requestsPerPlan*actualQuota, getTokenRemainQuota(t, tokenID))
}
func TestPostConsumeQuotaRejectsSubscriptionOverrun(t *testing.T) {
setupSubscriptionSettleTables(t)
const (
userID = 903
tokenID = 903
tokenRemain = 10_000
)
seedUser(t, userID, 0)
seedToken(t, tokenID, userID, "sk-sub-strict-post", tokenRemain)
sub := seedSubscriptionPlanAndInstance(t, userID, 100, 90, false, time.Hour)
info := &relaycommon.RelayInfo{
UserId: userID,
TokenId: tokenID,
TokenKey: "sk-sub-strict-post",
BillingSource: BillingSourceSubscription,
SubscriptionId: sub.Id,
}
// PostConsumeQuota backs Realtime PreWssConsumeQuota and must stay strict.
err := PostConsumeQuota(info, 25, 0, false)
require.Error(t, err)
assert.Contains(t, err.Error(), "subscription used exceeds total")
assert.Equal(t, int64(90), getSubscriptionUsed(t, sub.Id))
assert.Zero(t, info.SubscriptionPostDelta)
assert.Equal(t, tokenRemain, getTokenRemainQuota(t, tokenID))
}
func TestRecalculateTaskQuota_SubscriptionOverrunCapsPlan(t *testing.T) {
setupSubscriptionSettleTables(t)
ctx := context.Background()
const (
userID = 904
tokenID = 904
channelID = 904
preConsumed = 50
actualQuota = 200
tokenRemain = 500
)
seedUser(t, userID, 0)
seedToken(t, tokenID, userID, "sk-sub-task-overrun", tokenRemain)
seedChannel(t, channelID)
sub := seedSubscriptionPlanAndInstance(t, userID, 1000, 950, false, time.Hour)
seedChargedAccounting(t, userID, channelID, tokenID, preConsumed, 1)
task := makeTask(userID, channelID, preConsumed, tokenID, BillingSourceSubscription, sub.Id)
require.NoError(t, model.DB.Create(task).Error)
RecalculateTaskQuota(ctx, task, actualQuota, common.NewMessage("subscription overrun settle"))
assert.Equal(t, int64(1000), getSubscriptionUsed(t, sub.Id))
assert.Equal(t, actualQuota, task.Quota)
assert.Equal(t, actualQuota, getTaskQuota(t, task.ID))
assert.Equal(t, tokenRemain-(actualQuota-preConsumed), getTokenRemainQuota(t, tokenID))
usedQuota, requestCount := getUserUsageAccounting(t, userID)
assert.Equal(t, actualQuota, usedQuota)
assert.Equal(t, 1, requestCount)
assert.Equal(t, int64(actualQuota), getChannelUsedQuota(t, channelID))
log := getLastLog(t)
require.NotNil(t, log)
assert.Equal(t, model.LogTypeConsume, log.Type)
assert.Equal(t, actualQuota-preConsumed, log.Quota)
}