feat(billing): gate unpriced ollama cloud models at save and request time

- save-time gate on admin account create/update (and AccountService, which has
  no production consumers but is the spec-mandated location): non-empty
  model_mapping values and empty-mapping allowed_models lists must all resolve
  via GetModelPricing, otherwise 400 MODEL_PRICING_MISSING
- request-time gate: ollama_cloud accounts no longer fall into the global
  zero-cost path when pricing is unavailable; explicit 4xx instead
- operational preflight SQL documented as comments (not a migration)
- include ollama_cloud in the billing model candidate filter (S1) so claude-*
  names can no longer be priced at Anthropic rates for this platform
- keep ollama_cloud out of the LiteLLM platform map on purpose (comment only)
- refresh a stale comment in upstream_billing_probe.go
This commit is contained in:
alfadb committed 2026-09-13 10:38:55 +08:00
1 parent 707bcafd82
commit d36c935255
14 files changed
+641 -16

No files matched your search

+1 -1
View File
@@ -190,7 +190,7 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) {
adminAccountRepository := repository.NewAdminAccountRepository(client, db, schedulerCache)
proxyExitInfoProber := repository.NewProxyExitInfoProber(configConfig)
proxyLatencyCache := repository.NewProxyLatencyCache(redisClient)
adminService := service.NewAdminService(configConfig, userRepository, adminGroupRepository, adminAccountRepository, proxyRepository, apiKeyRepository, redeemCodeRepository, userGroupRateRepository, userRPMCache, billingCacheService, proxyExitInfoProber, proxyLatencyCache, apiKeyAuthCacheInvalidator, client, settingService, subscriptionService, userSubscriptionRepository, privacyClientFactory, openAIGatewayService, affiliateService, compositeModelRouteRepository, compositeRouteResolver, channelService)
adminService := service.NewAdminService(configConfig, userRepository, adminGroupRepository, adminAccountRepository, proxyRepository, apiKeyRepository, redeemCodeRepository, userGroupRateRepository, userRPMCache, billingCacheService, proxyExitInfoProber, proxyLatencyCache, apiKeyAuthCacheInvalidator, client, settingService, subscriptionService, userSubscriptionRepository, privacyClientFactory, openAIGatewayService, affiliateService, compositeModelRouteRepository, compositeRouteResolver, channelService, billingService)
adminUserHandler := admin.NewUserHandler(adminService, concurrencyService, serviceUserPlatformQuotaRepository, billingCache, totpService, userService, settingService)
groupCapacityService := service.NewGroupCapacityService(accountRepository, groupRepository, concurrencyService, sessionLimitCache, rpmCache)
groupHandler := admin.NewGroupHandlerWithConfig(adminService, dashboardService, groupCapacityService, configConfig)
@@ -634,6 +634,11 @@ func (h *ChannelHandler) GetModelDefaultPricing(c *gin.Context) {
// platformToLiteLLMProvider maps a channel platform name to the corresponding
// LiteLLM provider string used as the key in the pricing catalog.
//
// ollama_cloud 故意不在本表(C24):LiteLLM 目录没有 ollama 条目,加了映射只会
// 绕过 SyncPricingModels 的 unsupported 分支返回空列表(静默空池)。保持缺席,
// 让 sync-models?platform=ollama_cloud 显式返回 400 UNSUPPORTED_PLATFORM;
// ollama 定价走 billing_service.go fallbackPrices 的 ollama 条目(B2-② 落点)。
var platformToLiteLLMProvider = map[string]string{
service.PlatformAnthropic: "anthropic",
service.PlatformOpenAI: "openai",
@@ -566,6 +566,35 @@ func TestSyncPricingModels_ValidPlatform_EmptyService(t *testing.T) {
}
}
// C24:ollama_cloud 故意不进 platformToLiteLLMProvider(LiteLLM 目录无 ollama
// 条目,加映射只会返回空列表 = 静默空池),必须保持 400 UNSUPPORTED_PLATFORM;
// 其余平台不受影响。
func TestSyncPricingModels_OllamaCloudUnsupported(t *testing.T) {
svc := service.NewPricingService(nil, nil)
router := setupSyncPricingModelsRouter(svc)
req := httptest.NewRequest(http.MethodGet, "/channels/pricing/sync-models?platform="+service.PlatformOllamaCloud, nil)
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
require.Equal(t, http.StatusBadRequest, w.Code)
var body struct {
Code int `json:"code"`
Reason string `json:"reason"`
}
require.NoError(t, json.Unmarshal(w.Body.Bytes(), &body))
require.Equal(t, http.StatusBadRequest, body.Code)
require.Equal(t, "UNSUPPORTED_PLATFORM", body.Reason)
// 非回归:其它平台照常 200。
for _, platform := range []string{"anthropic", "openai", service.PlatformOpenCodeGo} {
req := httptest.NewRequest(http.MethodGet, "/channels/pricing/sync-models?platform="+platform, nil)
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
require.Equal(t, http.StatusOK, w.Code, "platform=%s", platform)
}
}
func setupModelDefaultPricingRouter() *gin.Engine {
gin.SetMode(gin.TestMode)
router := gin.New()
+1 -1
View File
@@ -1480,7 +1480,7 @@ func newContractDeps(t *testing.T) *contractDeps {
settingRepo := newStubSettingRepo()
settingService := service.NewSettingService(settingRepo, cfg)
adminService := service.NewAdminService(nil, userRepo, groupRepo, &accountRepo, proxyRepo, apiKeyRepo, redeemRepo, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil)
adminService := service.NewAdminService(nil, userRepo, groupRepo, &accountRepo, proxyRepo, apiKeyRepo, redeemRepo, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil)
authHandler := handler.NewAuthHandler(cfg, nil, userService, settingService, nil, redeemService, nil, nil)
apiKeyHandler := handler.NewAPIKeyHandler(apiKeyService)
usageHandler := handler.NewUsageHandler(usageService, apiKeyService, nil, nil)
@@ -217,7 +217,7 @@ func TestDuplicateCreatePathMintsFreshSeedWhenEligible(t *testing.T) {
func TestAccountServiceCreateAndUpdateCodexSeedLifecycle(t *testing.T) {
ctx := context.Background()
repo := &upstreamBillingProbeAccountRepo{accounts: make(map[int64]*Account)}
svc := NewAccountService(repo, nil)
svc := NewAccountService(repo, nil, nil)
created, err := svc.Create(ctx, CreateAccountRequest{
Name: "legacy-create",
@@ -0,0 +1,110 @@
package service
import (
"fmt"
"strings"
infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors"
)
// OllamaCloudAllowedModelsExtraKey 是 ollama_cloud 账号在 model_mapping 为空时
// 声明可出站模型清单的 extra 键。值为字符串数组(如 ["gpt-oss:120b","qwen3.5:397b"])。
//
// 背景:account.IsModelSupported 对空 model_mapping 一律放行所有模型名,因此
// 只扫 mapping 目标值的校验对空 mapping 账号零覆盖;ollama_cloud 的计费又是
// 白名单语义(未列价的模型名显式拒绝计费),所以保存期必须拿到一个有限的
// 可出站模型名集合来断言「全部可被 GetModelPricing 解析」,否则只能全量拒绝。
const OllamaCloudAllowedModelsExtraKey = "allowed_models"
// accountModelPricingLookup 是保存期无价门禁所需的最小定价查询面,
// *BillingService 以同一查价链(LiteLLM → fallback,含 :tag 两级 fallback)实现。
type accountModelPricingLookup interface {
GetModelPricing(model string) (*ModelPricing, error)
}
// validateOllamaCloudAccountModelPricingGate 是 B2-③ 的保存期无价门禁:
// ollama_cloud 账号保存时断言「该账号可出站的模型名集合均可被 GetModelPricing 解析」。
//
// 可出站集合的取法与 account.IsModelSupported 的放行语义对齐:
// - 非空 model_mapping → 扫全部目标值(映射后真正发往上游的名字);
// - 空 model_mapping → 必须同时提供 OllamaCloudAllowedModelsExtraKey 显式清单,
// 清单全量纳入断言;空 mapping 且无清单一律拒绝(此时账号对全部模型名放行,
// 门禁对它零覆盖,是静默零计费的敞口)。
//
// 只对 ollama_cloud 生效:其它平台的保存路径行为不变(多数平台定价缺失走
// 请求期零成本兜底,属于既有的全平台 fail-open 设计,见
// openai_gateway_usage.go 的 pricing_missing_record_zero_cost 分支)。
// lookup 为 nil 时跳过(生产 wire 必然注入 *BillingService;仅直接构造
// struct 的单元测试/内部调用会出现)。
func validateOllamaCloudAccountModelPricingGate(lookup accountModelPricingLookup, account *Account) error {
if lookup == nil || account == nil || !account.IsOllamaCloud() {
return nil
}
models := ollamaCloudOutboundModelNames(account)
if len(models) == 0 {
return infraerrors.BadRequest("MODEL_PRICING_MISSING",
fmt.Sprintf("ollama_cloud 账号 model_mapping 为空时必须在 extra.%s 提供显式的可出站模型清单,否则无法保证全部模型可计费",
OllamaCloudAllowedModelsExtraKey))
}
unpriced := make([]string, 0)
for _, model := range models {
if _, err := lookup.GetModelPricing(model); err != nil {
unpriced = append(unpriced, model)
}
}
if len(unpriced) > 0 {
return infraerrors.BadRequest("MODEL_PRICING_MISSING",
fmt.Sprintf("以下 ollama_cloud 模型缺少定价,无法保证计费(请先补价或调整 model_mapping/%s): %s",
OllamaCloudAllowedModelsExtraKey, strings.Join(unpriced, ", ")))
}
return nil
}
// ollamaCloudOutboundModelNames 收集 ollama_cloud 账号的可出站模型名集合
// (去重、去空)。空 mapping 且无有效清单时返回 nil。
//
// 清单值兼容两种形态:JSON 反序列化出的 []any(元素为 string),以及程序化
// 构造的 []string。非字符串元素跳过(由清单「缺失即拒绝」的语义兜底不严的
// 情况——含非字符串元素的清单视同未提供,见下方 return nil)。
func ollamaCloudOutboundModelNames(account *Account) []string {
seen := make(map[string]struct{})
out := make([]string, 0)
appendModel := func(model string) {
trimmed := strings.TrimSpace(model)
if trimmed == "" {
return
}
if _, dup := seen[trimmed]; dup {
return
}
seen[trimmed] = struct{}{}
out = append(out, trimmed)
}
if mapping := account.GetModelMapping(); len(mapping) > 0 {
for _, target := range mapping {
appendModel(target)
}
return out
}
switch list := account.Extra[OllamaCloudAllowedModelsExtraKey].(type) {
case []any:
for _, item := range list {
model, ok := item.(string)
if !ok {
return nil
}
appendModel(model)
}
case []string:
for _, model := range list {
appendModel(model)
}
default:
return nil
}
return out
}
@@ -0,0 +1,254 @@
package service
// B2-③ 保存期无价门禁回归测试(ollama_cloud):
// ① mapping 目标含未定价名 → Create/Update 返回 400 MODEL_PRICING_MISSING 且
// message 含该模型名;
// ② 空 mapping 无 allowed_models 清单 → 400;
// ③ 空 mapping + 显式清单(全部已定价,含真实 :tag 形态)→ 通过;
// ④ 非 ollama 平台同样配置不受影响(回归)。
//
// 门禁同时接在两条保存路径上:
// - AccountService.Create/Update(本文件,spec 权威位置);
// - adminServiceImpl.CreateAccount/UpdateAccount(生产 admin handler 实际走
// 的路径,见 TestAdminCreateAccount.../TestAdminUpdateAccount...)。
import (
"context"
"testing"
"github.com/Wei-Shaw/sub2api/internal/config"
infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors"
"github.com/stretchr/testify/require"
)
func newOllamaGateAccountService(repo AccountRepository) *AccountService {
return NewAccountService(repo, nil, NewBillingService(&config.Config{}, nil))
}
func requireModelPricingMissing(t *testing.T, err error, wantNames ...string) {
t.Helper()
require.Error(t, err)
require.Equal(t, 400, infraerrors.Code(err), "必须映射为 400: %v", err)
require.Equal(t, "MODEL_PRICING_MISSING", infraerrors.Reason(err))
for _, name := range wantNames {
require.Contains(t, infraerrors.Message(err), name, "message 必须列出未定价模型名")
}
}
func TestAccountServiceCreateOllamaCloudPricingGate(t *testing.T) {
ctx := context.Background()
t.Run("mapping目标含未定价名_400并列出该名", func(t *testing.T) {
repo := &upstreamBillingProbeAccountRepo{accounts: make(map[int64]*Account)}
svc := newOllamaGateAccountService(repo)
_, err := svc.Create(ctx, CreateAccountRequest{
Name: "ollama-bad-mapping",
Platform: PlatformOllamaCloud,
Type: AccountTypeAPIKey,
Credentials: map[string]any{"api_key": "k", "model_mapping": map[string]any{"alias": "totally-unpriced-model"}},
})
requireModelPricingMissing(t, err, "totally-unpriced-model")
require.Empty(t, repo.accounts, "被拒绝的账号不得落库")
})
t.Run("空mapping且无清单_400", func(t *testing.T) {
repo := &upstreamBillingProbeAccountRepo{accounts: make(map[int64]*Account)}
svc := newOllamaGateAccountService(repo)
_, err := svc.Create(ctx, CreateAccountRequest{
Name: "ollama-no-list",
Platform: PlatformOllamaCloud,
Type: AccountTypeAPIKey,
Credentials: map[string]any{"api_key": "k"},
})
requireModelPricingMissing(t, err)
require.Contains(t, infraerrors.Message(err), OllamaCloudAllowedModelsExtraKey)
require.Empty(t, repo.accounts)
})
t.Run("空mapping加已定价清单_通过", func(t *testing.T) {
repo := &upstreamBillingProbeAccountRepo{accounts: make(map[int64]*Account)}
svc := newOllamaGateAccountService(repo)
created, err := svc.Create(ctx, CreateAccountRequest{
Name: "ollama-with-list",
Platform: PlatformOllamaCloud,
Type: AccountTypeAPIKey,
Credentials: map[string]any{"api_key": "k", "base_url": "https://ollama.com/v1"},
Extra: map[string]any{
OllamaCloudAllowedModelsExtraKey: []any{"gpt-oss:120b-cloud", "qwen3.5:397b"},
},
})
require.NoError(t, err)
require.NotNil(t, created)
require.NotEmpty(t, repo.accounts)
})
t.Run("mapping目标全部已定价_通过", func(t *testing.T) {
repo := &upstreamBillingProbeAccountRepo{accounts: make(map[int64]*Account)}
svc := newOllamaGateAccountService(repo)
_, err := svc.Create(ctx, CreateAccountRequest{
Name: "ollama-priced-mapping",
Platform: PlatformOllamaCloud,
Type: AccountTypeAPIKey,
Credentials: map[string]any{
"api_key": "k",
"model_mapping": map[string]any{"big": "gpt-oss:120b", "coder": "qwen3.5:397b"},
},
})
require.NoError(t, err)
})
t.Run("非ollama平台不受影响_回归", func(t *testing.T) {
for _, platform := range []string{PlatformOpenAI, PlatformKimi, PlatformAnthropic} {
repo := &upstreamBillingProbeAccountRepo{accounts: make(map[int64]*Account)}
svc := newOllamaGateAccountService(repo)
created, err := svc.Create(ctx, CreateAccountRequest{
Name: "legacy-" + platform,
Platform: platform,
Type: AccountTypeAPIKey,
Credentials: map[string]any{"api_key": "k"},
})
require.NoError(t, err, "platform=%s 的空 mapping 账号保存不得被门禁拦截", platform)
require.NotNil(t, created)
}
})
}
func TestAccountServiceUpdateOllamaCloudPricingGate(t *testing.T) {
ctx := context.Background()
newOllamaAccount := func(t *testing.T) (*upstreamBillingProbeAccountRepo, *AccountService, *Account) {
t.Helper()
repo := &upstreamBillingProbeAccountRepo{accounts: make(map[int64]*Account)}
svc := newOllamaGateAccountService(repo)
created, err := svc.Create(ctx, CreateAccountRequest{
Name: "ollama-update",
Platform: PlatformOllamaCloud,
Type: AccountTypeAPIKey,
Credentials: map[string]any{
"api_key": "k",
"model_mapping": map[string]any{"big": "gpt-oss:120b"},
},
})
require.NoError(t, err)
return repo, svc, created
}
t.Run("改成未定价目标_400", func(t *testing.T) {
_, svc, created := newOllamaAccount(t)
_, err := svc.Update(ctx, created.ID, UpdateAccountRequest{
Credentials: &map[string]any{"api_key": "k", "model_mapping": map[string]any{"big": "totally-unpriced-model"}},
})
requireModelPricingMissing(t, err, "totally-unpriced-model")
})
t.Run("清空mapping且无清单_400", func(t *testing.T) {
_, svc, created := newOllamaAccount(t)
_, err := svc.Update(ctx, created.ID, UpdateAccountRequest{
Credentials: &map[string]any{"api_key": "k"},
})
requireModelPricingMissing(t, err)
})
t.Run("换成已定价清单_通过", func(t *testing.T) {
repo, svc, created := newOllamaAccount(t)
updated, err := svc.Update(ctx, created.ID, UpdateAccountRequest{
Credentials: &map[string]any{"api_key": "k"},
Extra: &map[string]any{
OllamaCloudAllowedModelsExtraKey: []any{"gpt-oss:20b"},
},
})
require.NoError(t, err)
require.Equal(t, []any{"gpt-oss:20b"}, updated.Extra[OllamaCloudAllowedModelsExtraKey])
require.NotNil(t, repo.accounts[created.ID])
})
t.Run("非ollama平台更新不受影响_回归", func(t *testing.T) {
repo := &upstreamBillingProbeAccountRepo{accounts: make(map[int64]*Account)}
svc := newOllamaGateAccountService(repo)
created, err := svc.Create(ctx, CreateAccountRequest{
Name: "kimi-update",
Platform: PlatformKimi,
Type: AccountTypeAPIKey,
Credentials: map[string]any{"api_key": "k", "model_mapping": map[string]any{"k2": "kimi-k2-0905-preview"}},
})
require.NoError(t, err)
updated, err := svc.Update(ctx, created.ID, UpdateAccountRequest{
Credentials: &map[string]any{"api_key": "k"},
})
require.NoError(t, err, "kimi 账号清空 mapping 的更新不得被门禁拦截")
require.NotNil(t, updated)
})
}
// 生产 admin handler 实际走的保存路径(adminServiceImpl.CreateAccount/UpdateAccount)
// 同样必须挂门禁——只测 AccountService 而 admin 路径漏挂,等于门禁空转。
func TestAdminCreateAccountOllamaCloudPricingGate(t *testing.T) {
svc := &adminServiceImpl{accountRepo: &upstreamBillingProbeAccountRepo{accounts: make(map[int64]*Account)}, billingService: NewBillingService(&config.Config{}, nil)}
_, err := svc.CreateAccount(context.Background(), &CreateAccountInput{
Name: "ollama-admin-unpriced",
Platform: PlatformOllamaCloud,
Type: AccountTypeAPIKey,
Credentials: map[string]any{"api_key": "k", "model_mapping": map[string]any{"alias": "totally-unpriced-model"}},
SkipDefaultGroupBind: true,
})
requireModelPricingMissing(t, err, "totally-unpriced-model")
created, err := svc.CreateAccount(context.Background(), &CreateAccountInput{
Name: "ollama-admin-priced",
Platform: PlatformOllamaCloud,
Type: AccountTypeAPIKey,
Credentials: map[string]any{"api_key": "k"},
Extra: map[string]any{OllamaCloudAllowedModelsExtraKey: []any{"gpt-oss:120b-cloud", "nemotron-3-super"}},
SkipDefaultGroupBind: true,
})
require.NoError(t, err)
require.NotNil(t, created)
}
func TestAdminUpdateAccountOllamaCloudPricingGate(t *testing.T) {
repo := &upstreamBillingProbeAccountRepo{accounts: make(map[int64]*Account)}
svc := &adminServiceImpl{accountRepo: repo, billingService: NewBillingService(&config.Config{}, nil)}
created, err := svc.CreateAccount(context.Background(), &CreateAccountInput{
Name: "ollama-admin-update",
Platform: PlatformOllamaCloud,
Type: AccountTypeAPIKey,
Credentials: map[string]any{"api_key": "k"},
Extra: map[string]any{OllamaCloudAllowedModelsExtraKey: []any{"gpt-oss:120b-cloud"}},
SkipDefaultGroupBind: true,
})
require.NoError(t, err)
_, err = svc.UpdateAccount(context.Background(), created.ID, &UpdateAccountInput{
Credentials: map[string]any{"api_key": "k", "model_mapping": map[string]any{"alias": "totally-unpriced-model"}},
})
requireModelPricingMissing(t, err, "totally-unpriced-model")
updated, err := svc.UpdateAccount(context.Background(), created.ID, &UpdateAccountInput{
Credentials: map[string]any{"api_key": "k", "model_mapping": map[string]any{"alias": "qwen3.5:397b"}},
})
require.NoError(t, err)
require.NotNil(t, updated)
}
// gate helper 单元测试:清单值形态与非 ollama 平台短路。
func TestOllamaCloudOutboundModelNames(t *testing.T) {
account := &Account{Platform: PlatformOllamaCloud, Credentials: map[string]any{
"model_mapping": map[string]any{"a": "gpt-oss:120b", "b": "", "c": "qwen3.5:397b", "d": "gpt-oss:120b"},
}}
// map 迭代顺序不定,只断言集合内容(去空、去重)。
require.ElementsMatch(t, []string{"gpt-oss:120b", "qwen3.5:397b"}, ollamaCloudOutboundModelNames(account))
account = &Account{Platform: PlatformOllamaCloud, Extra: map[string]any{
OllamaCloudAllowedModelsExtraKey: []any{"gpt-oss:20b", " "},
}}
require.Equal(t, []string{"gpt-oss:20b"}, ollamaCloudOutboundModelNames(account))
account = &Account{Platform: PlatformOllamaCloud, Extra: map[string]any{
OllamaCloudAllowedModelsExtraKey: []any{"gpt-oss:20b", 42},
}}
require.Nil(t, ollamaCloudOutboundModelNames(account), "含非字符串元素的清单视同未提供(拒绝语义)")
account = &Account{Platform: PlatformOpenAI}
require.Nil(t, ollamaCloudOutboundModelNames(account))
}
+16 -3
View File
@@ -207,6 +207,8 @@ type UpdateAccountRequest struct {
type AccountService struct {
accountRepo AccountRepository
groupRepo GroupRepository
// B2-③ 保存期无价门禁用:ollama_cloud 账号保存时断言可出站模型名全部可定价。
billingService *BillingService
}
type groupExistenceBatchChecker interface {
@@ -214,10 +216,11 @@ type groupExistenceBatchChecker interface {
}
// NewAccountService 创建账号服务实例
func NewAccountService(accountRepo AccountRepository, groupRepo GroupRepository) *AccountService {
func NewAccountService(accountRepo AccountRepository, groupRepo GroupRepository, billingService *BillingService) *AccountService {
return &AccountService{
accountRepo: accountRepo,
groupRepo: groupRepo,
accountRepo: accountRepo,
groupRepo: groupRepo,
billingService: billingService,
}
}
@@ -250,6 +253,11 @@ func (s *AccountService) Create(ctx context.Context, req CreateAccountRequest) (
account.AutoPauseOnExpired = true
}
// B2-③ 保存期无价门禁:ollama_cloud 账号的可出站模型名必须全部可定价。
if err := validateOllamaCloudAccountModelPricingGate(s.billingService, account); err != nil {
return nil, err
}
if err := s.accountRepo.Create(ctx, account); err != nil {
return nil, fmt.Errorf("create account: %w", err)
}
@@ -374,6 +382,11 @@ func (s *AccountService) Update(ctx context.Context, id int64, req UpdateAccount
}
}
// B2-③ 保存期无价门禁:ollama_cloud 账号的可出站模型名必须全部可定价。
if err := validateOllamaCloudAccountModelPricingGate(s.billingService, account); err != nil {
return nil, err
}
// 执行更新
if err := s.accountRepo.Update(ctx, account); err != nil {
return nil, fmt.Errorf("update account: %w", err)
+11
View File
@@ -527,6 +527,10 @@ func (s *adminServiceImpl) CreateAccount(ctx context.Context, input *CreateAccou
if err != nil {
return nil, err
}
// B2-③ 保存期无价门禁:ollama_cloud 账号的可出站模型名必须全部可定价。
if err := validateOllamaCloudAccountModelPricingGate(s.billingService, account); err != nil {
return nil, err
}
if err := s.ValidateAccountGroupBindings(ctx, groupIDs); err != nil {
return nil, err
}
@@ -837,6 +841,13 @@ func (s *adminServiceImpl) UpdateAccount(ctx context.Context, id int64, input *U
}
}
// B2-③ 保存期无价门禁:ollama_cloud 账号的可出站模型名必须全部可定价。
// 放在全部字段/Extra 变更应用完、任何写操作之前,credentials(含
// model_mapping)与 extra(含 allowed_models)读到的都是本次请求生效后的状态。
if err := validateOllamaCloudAccountModelPricingGate(s.billingService, account); err != nil {
return nil, err
}
billingSettingsAppliedAtomically := false
updater := s.accountBillingRepo
if updater == nil {
@@ -709,6 +709,9 @@ type adminServiceImpl struct {
affiliateService adminRechargeAffiliateAccruer
compositeRouteRepo CompositeModelRouteRepository
compositeResolver *CompositeRouteResolver
// B2-③ 保存期无价门禁用:ollama_cloud 账号保存时断言可出站模型名全部可定价。
// 生产 wire 注入;直接构造 struct 的单测可为 nil(门禁对 nil 跳过)。
billingService *BillingService
// 分组平台变更后用来失效渠道缓存;可为 nil(缓存会在 TTL 到期后自然重建)
channelCacheInvalidator ChannelCacheInvalidator
}
@@ -752,6 +755,7 @@ func NewAdminService(
compositeRouteRepo CompositeModelRouteRepository,
compositeResolver *CompositeRouteResolver,
channelCacheInvalidator ChannelCacheInvalidator,
billingService *BillingService,
) AdminService {
return &adminServiceImpl{
cfg: cfg,
@@ -780,6 +784,7 @@ func NewAdminService(
affiliateService: affiliateService,
compositeRouteRepo: compositeRouteRepo,
compositeResolver: compositeResolver,
billingService: billingService,
channelCacheInvalidator: channelCacheInvalidator,
}
@@ -739,7 +739,7 @@ func TestAccountServiceUpdateStripsOllamaManagedExtra(t *testing.T) {
OllamaCloudUsageSnapshotExtraKey: map[string]any{"status": OllamaCloudUsageStatusOK},
}
repo := &ollamaManagedExtraUpdateRepo{account: account}
svc := NewAccountService(repo, nil)
svc := NewAccountService(repo, nil, nil)
requestedExtra := map[string]any{
"note": "preserved",
OllamaCloudUsageSessionExtraKey: "forged-ciphertext",
@@ -0,0 +1,160 @@
//go:build unit
package service
// B2-④(请求期 ollama_cloud 定价缺失显式拒绝)与 S1(计费候选过滤纳入
// ollama_cloud)的回归测试。
//
// 关键顺序约束的实证:S1 只在「定价已就位」的前提下才安全——若过滤把候选滤空
// 而定价缺失,会从误计变全零计费。本文件用真实 fallbackPrices(含 ollama 价卡)
// 证明:ollama 真实模型名(不含 claude-*)永不被过滤,候选不会滤空。
import (
"context"
"testing"
"time"
"github.com/stretchr/testify/require"
)
func TestFilterCNProviderBillingModelCandidates_OllamaCloud(t *testing.T) {
svc := &OpenAIGatewayService{} // resolver 为 nil → 无显式分组/渠道定价
apiKey := &APIKey{Group: &Group{ID: 1, Platform: PlatformOllamaCloud}}
ollamaAccount := &Account{ID: 4, Platform: PlatformOllamaCloud}
// claude-* 被移除,ollama 真实模型名保留 → 候选不会滤空。
filtered := svc.filterCNProviderBillingModelCandidates(context.Background(), ollamaAccount, apiKey,
[]string{"claude-sonnet-4-5", "gpt-oss:120b-cloud", "qwen3.5:397b"})
require.Equal(t, []string{"gpt-oss:120b-cloud", "qwen3.5:397b"}, filtered,
"ollama 真实模型名必须保留,只有 claude-* 被过滤")
// 全 claude 候选才会被清空(上层走 B2-④ 显式拒绝,而非误计 Anthropic 价)。
allClaude := svc.filterCNProviderBillingModelCandidates(context.Background(), ollamaAccount, apiKey,
[]string{"claude-sonnet-4-5", "claude-opus-4-1"})
require.Empty(t, allClaude)
// 未定价的非 claude 名也不过滤(过滤只针对 claude-*,不查价)。
unpriced := svc.filterCNProviderBillingModelCandidates(context.Background(), ollamaAccount, apiKey,
[]string{"totally-unpriced-model"})
require.Equal(t, []string{"totally-unpriced-model"}, unpriced)
// 既有豁免语义回归:运营者显式配置 claude 渠道价时 claude 名保留。
const groupID = int64(778)
svcWithChannel := &OpenAIGatewayService{billingService: NewBillingService(nil, nil)}
svcWithChannel.channelService = newChannelServiceWithPricings(groupID, []ChannelModelPricing{
tokenPricingForModels([]string{"claude-sonnet-4-5"}, 3.0),
})
svcWithChannel.resolver = NewModelPricingResolver(svcWithChannel.channelService, svcWithChannel.billingService)
apiKeyWithGroup := &APIKey{Group: &Group{ID: groupID, Platform: PlatformOllamaCloud}}
kept := svcWithChannel.filterCNProviderBillingModelCandidates(context.Background(), ollamaAccount, apiKeyWithGroup,
[]string{"claude-sonnet-4-5", "gpt-oss:120b-cloud"})
require.Equal(t, []string{"claude-sonnet-4-5", "gpt-oss:120b-cloud"}, kept,
"显式渠道定价的 claude-* 候选必须保留(既有豁免语义)")
}
// B2-④ 主断言:ollama_cloud + 未定价模型 → 400 MODEL_PRICING_MISSING、
// 不落零成本记录(usage/billing 均不写库、日志无 pricing_missing_record_zero_cost
// 对应的落账路径)。
func TestOpenAIGatewayRecordUsage_OllamaCloudUnpricedModelRejected(t *testing.T) {
usageRepo := &openAIRecordUsageLogRepoStub{inserted: true}
billingRepo := &openAIRecordUsageBillingRepoStub{result: &UsageBillingApplyResult{Applied: true}}
svc := newOpenAIRecordUsageServiceWithBillingRepoForTest(usageRepo, billingRepo, &openAIRecordUsageUserRepoStub{}, &openAIRecordUsageSubRepoStub{}, nil)
err := svc.RecordUsage(context.Background(), &OpenAIRecordUsageInput{
Result: &OpenAIForwardResult{
RequestID: "resp_ollama_unpriced",
Usage: OpenAIUsage{
InputTokens: 1_000_000,
OutputTokens: 0,
},
Model: "totally-unpriced-model",
Duration: time.Second,
},
APIKey: &APIKey{ID: 1},
User: &User{ID: 2},
Account: &Account{ID: 3, Platform: PlatformOllamaCloud},
})
requireModelPricingMissing(t, err, "totally-unpriced-model")
require.Zero(t, usageRepo.calls, "拒绝路径不得写 usage log(零成本落账被收窄掉)")
require.Zero(t, billingRepo.calls, "拒绝路径不得触发计费入账")
}
// claude-* 请求打到 ollama_cloud:候选被 S1 滤空 → ErrModelPricingUnavailable →
// B2-④ 显式拒绝。这是「按 Anthropic 价静默误计」被修复后的目标行为。
func TestOpenAIGatewayRecordUsage_OllamaCloudClaudeNameRejected(t *testing.T) {
usageRepo := &openAIRecordUsageLogRepoStub{inserted: true}
billingRepo := &openAIRecordUsageBillingRepoStub{result: &UsageBillingApplyResult{Applied: true}}
svc := newOpenAIRecordUsageServiceWithBillingRepoForTest(usageRepo, billingRepo, &openAIRecordUsageUserRepoStub{}, &openAIRecordUsageSubRepoStub{}, nil)
err := svc.RecordUsage(context.Background(), &OpenAIRecordUsageInput{
Result: &OpenAIForwardResult{
RequestID: "resp_ollama_claude_name",
Usage: OpenAIUsage{
InputTokens: 1_000_000,
OutputTokens: 0,
},
Model: "claude-sonnet-4-5",
Duration: time.Second,
},
APIKey: &APIKey{ID: 1},
User: &User{ID: 2},
Account: &Account{ID: 3, Platform: PlatformOllamaCloud},
})
requireModelPricingMissing(t, err)
require.Zero(t, usageRepo.calls)
}
// 已定价模型(真实 :tag 请求形态)→ 正常落账且 actual_cost > 0:
// 证明 S1 过滤 + B2-① tag fallback + B2-② 价卡组合后,ollama 正常请求计费完整。
func TestOpenAIGatewayRecordUsage_OllamaCloudPricedModelBilledPositive(t *testing.T) {
usageRepo := &openAIRecordUsageLogRepoStub{inserted: true}
billingRepo := &openAIRecordUsageBillingRepoStub{result: &UsageBillingApplyResult{Applied: true}}
svc := newOpenAIRecordUsageServiceWithBillingRepoForTest(usageRepo, billingRepo, &openAIRecordUsageUserRepoStub{}, &openAIRecordUsageSubRepoStub{}, nil)
err := svc.RecordUsage(context.Background(), &OpenAIRecordUsageInput{
Result: &OpenAIForwardResult{
RequestID: "resp_ollama_priced",
Usage: OpenAIUsage{
InputTokens: 1_000_000,
OutputTokens: 0,
},
Model: "gpt-oss:120b-cloud",
Duration: time.Second,
},
APIKey: &APIKey{ID: 1},
User: &User{ID: 2},
Account: &Account{ID: 3, Platform: PlatformOllamaCloud},
})
require.NoError(t, err)
require.Equal(t, 1, usageRepo.calls)
require.NotNil(t, usageRepo.lastLog)
require.Greater(t, usageRepo.lastLog.ActualCost, 0.0,
"gpt-oss:120b-cloud 经 :tag fallback 命中 ollama 价卡,actual_cost 必须为正")
}
// 只收窄 ollama_cloud 的回归:其它平台的定价缺失保持既有 fail-open
// (零成本落账 + Warn),不得被本批改动波及。
func TestOpenAIGatewayRecordUsage_NonOllamaPlatformZeroCostFallbackPreserved(t *testing.T) {
usageRepo := &openAIRecordUsageLogRepoStub{inserted: true}
billingRepo := &openAIRecordUsageBillingRepoStub{result: &UsageBillingApplyResult{Applied: true}}
svc := newOpenAIRecordUsageServiceWithBillingRepoForTest(usageRepo, billingRepo, &openAIRecordUsageUserRepoStub{}, &openAIRecordUsageSubRepoStub{}, nil)
err := svc.RecordUsage(context.Background(), &OpenAIRecordUsageInput{
Result: &OpenAIForwardResult{
RequestID: "resp_openai_unpriced_zero_cost",
Usage: OpenAIUsage{
InputTokens: 1_000_000,
OutputTokens: 0,
},
Model: "totally-unpriced-model",
Duration: time.Second,
},
APIKey: &APIKey{ID: 1},
User: &User{ID: 2},
Account: &Account{ID: 3, Platform: PlatformOpenAI},
})
require.NoError(t, err, "非 ollama 平台的定价缺失必须保持既有零成本落账行为")
require.Equal(t, 1, usageRepo.calls)
require.NotNil(t, usageRepo.lastLog)
require.Equal(t, 0.0, usageRepo.lastLog.ActualCost)
}
@@ -13,6 +13,7 @@ import (
"time"
"github.com/Wei-Shaw/sub2api/internal/config"
infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors"
"github.com/Wei-Shaw/sub2api/internal/pkg/logger"
"github.com/Wei-Shaw/sub2api/internal/pkg/timezone"
"go.uber.org/zap"
@@ -150,6 +151,28 @@ func groupBillsOpenAIFastAtStandard(apiKey *APIKey, account *Account, serviceTie
}
}
// 运营 preflight SQL(B2-④,上线/放量前人工执行;是一次性运营检查,不是迁移,
// 不要放进 migrations/)。用于在放量前扫出「保存期门禁(B2-③)生效前就已存在、
// 或绕过门禁写入」的无价 ollama_cloud 账号;两条都期望 0 行:
//
// -- 1) model_mapping 目标值必须全部有价(<已定价模型名集合> 取
// -- billing_service.go fallbackPrices 的 ollama 条目 + 复用同名条目的模型;
// -- 注意 :tag 名靠两级查价 fallback 命中,集合里放裸名即可);期望 0 行
// SELECT a.id, kv.value AS target_model FROM accounts a,
// jsonb_each_text(COALESCE(a.credentials->'model_mapping','{}'::jsonb)) AS kv
// WHERE a.deleted_at IS NULL AND a.platform = 'ollama_cloud'
// AND kv.value NOT IN (<已定价模型名集合>);
//
// -- 2) 空 mapping 账号(jsonb_each_text 展开为 0 行,第 1 条扫不到);期望 0 行
// -- (B2-③ 之后新账号必须带 extra.allowed_models 清单;此处命中的只能是
// -- 门禁上线前的存量账号,需人工补 mapping/清单或下线)
// SELECT a.id FROM accounts a WHERE a.deleted_at IS NULL AND a.platform = 'ollama_cloud'
// AND COALESCE(a.credentials->'model_mapping','{}'::jsonb) = '{}'::jsonb;
//
// 上线后观察断言:日志中 `openai_usage.pricing_missing_record_zero_cost` 出现
// 次数必须为 0(出现即回滚放量);ollama_cloud 的定价缺失会走上方 B2-④ 的
// MODEL_PRICING_MISSING 显式拒绝而非零成本落账。
//
// RecordUsage records usage and deducts balance
func (s *OpenAIGatewayService) RecordUsage(ctx context.Context, input *OpenAIRecordUsageInput) error {
if input == nil {
@@ -254,6 +277,16 @@ func (s *OpenAIGatewayService) RecordUsage(ctx context.Context, input *OpenAIRec
if !isUsagePricingUnavailableError(err) {
return err
}
// B2-④ 平台收窄断言:ollama_cloud 的计费是白名单语义(fallbackPrices
// 未列出的模型名显式拒绝计费),定价缺失说明配置漏了——静默零成本落账
// 等于免费送量。这里显式拒绝(400,message 列出候选模型名),不落入下方
// 的零成本路径;其余平台保持既有全平台 fail-open 设计不变。此时 usage
// 记录尚未写库(下方才建 UsageLog),提前返回即整条拒绝、无部分入账。
if account.IsOllamaCloud() {
return infraerrors.BadRequest("MODEL_PRICING_MISSING",
fmt.Sprintf("ollama cloud model pricing missing for billing models: %s (requested: %s)",
strings.Join(billingModels, ", "), input.OriginalModel))
}
logger.L().With(
zap.String("component", "service.openai_gateway"),
zap.Strings("billing_models", billingModels),
@@ -915,19 +948,22 @@ func groupMediaPricingLooksIncomplete(group *Group) bool {
group.VideoPrice480P == nil && group.VideoPrice720P == nil && group.VideoPrice1080P == nil
}
// filterCNProviderBillingModelCandidates 过滤国产供应商(kimi/zhipu/deepseek)
// 账号的计费候选模型名:claude-* 候选仅在运营者显式配置了分组/渠道定价时保留。
// filterCNProviderBillingModelCandidates 过滤 CN/类 CN 平台(kimi/zhipu/deepseek/
// opencode_go/ollama_cloud)账号的计费候选模型名:claude-* 候选仅在运营者显式
// 配置了分组/渠道定价时保留。
//
// 背景:候选链的兜底候选含客户端请求的原始模型名。CN 上游的 Anthropic 兼容端点
// 接受 claude-* 模型名但从不真正服务 Claude 模型;若放行,目录里的 Claude 价卡
// 与 getFallbackPricing 的 "claude"→Sonnet 统一兜底会把 CN 流量按 Claude 原价
// (数倍~数十倍)静默误计,且 usage 日志显示的正是 claude-* 名,无从察觉。
// ollama_cloud 同理:它服务的是自家托管模型(qwen3.5/gpt-oss/nemotron 等),
// 请求里的 claude-* 名不会真的被 Claude 服务,放行即按 Anthropic 价误计。
// 候选全部落空时走既有的零成本+告警路径(openai_usage.pricing_missing_record_
// zero_cost),与定价层「未知型号不回退以避免误计价」的既有设计意图一致;
// 运营者的修复手段是配置账号级 model_mapping(映射到已定价的 CN 模型)或
// 分组/渠道显式定价。
// zero_cost;ollama_cloud 已由 B2-④ 收窄为显式拒绝),与定价层「未知型号不回退
// 以避免误计价」的既有设计意图一致;运营者的修复手段是配置账号级 model_mapping
// (映射到已定价的 CN/ollama 模型)或分组/渠道显式定价。
func (s *OpenAIGatewayService) filterCNProviderBillingModelCandidates(ctx context.Context, account *Account, apiKey *APIKey, candidates []string) []string {
if account == nil || (!account.IsCNProvider() && !account.IsOpenCodeGo()) {
if account == nil || (!account.IsCNProvider() && !account.IsOpenCodeGo() && !account.IsOllamaCloud()) {
return candidates
}
out := make([]string, 0, len(candidates))
@@ -1035,9 +1035,11 @@ func isUpstreamBillingProbeAccount(account *Account) bool {
// relays (the only targets that can answer /v1/sub2api/billing) always do
// probe. OpenAI-platform accounts never reach this check: they keep the
// upstream-official behavior of probing api.openai.com.
// ollama.com is a first-class configuration here (Ollama Cloud accounts are
// platform openai/anthropic with base_url https://ollama.com/v1), and it is
// an official provider API just like the rest, so it belongs on this list.
// ollama.com is a first-class configuration here (it is the official Ollama
// Cloud API base: platform ollama_cloud accounts use https://ollama.com/v1,
// and legacy openai/anthropic-platform accounts may still point at the same
// host), and it is an official provider API just like the rest, so it belongs
// on this list.
// CN provider domains (moonshot.cn / kimi.com / bigmodel.cn / deepseek.com)
// serve the same role: official APIs that can never host /v1/sub2api/billing,
// so their accounts short-circuit to "unsupported" without a request.