fix(ollama, billing): 拦截未配价 claude 出站模型并对齐计费配额平台、连接测试与监控余额解析

This commit is contained in:
shaw committed 2026-12-05 10:41:13 +08:00
1 parent 18f11c391a
commit e7fcf51343
9 files changed
+78 -33

No files matched your search

@@ -59,6 +59,13 @@ func validateOllamaCloudAccountModelPricingGate(lookup accountModelPricingLookup
unpriced := make([]string, 0)
for _, model := range models {
// 计费侧对托管模型上游(accountServesHostedModels,含 ollama_cloud)会剔除未在渠道/分组
// 显式配价的 claude-* 候选;保存期门禁不接受仅渠道/分组层定价,故含 claude 的出站模型名
// 必须一并拦截,避免通过门禁后在记账阶段落入 $0。
if strings.Contains(strings.ToLower(model), "claude") {
unpriced = append(unpriced, model)
continue
}
if _, err := lookup.GetModelPricing(model); err != nil {
unpriced = append(unpriced, model)
}
@@ -646,6 +646,20 @@ func TestAdminSetAccountSchedulableOllamaCloudPricingGate(t *testing.T) {
require.Empty(t, repo.schedulableCalls)
})
t.Run("出站含claude模型名_门禁与无渠道价预检一律拒绝防零计费", func(t *testing.T) {
repo, svc := newSvc(t)
account := seedOllamaGateAccount(t, repo, func(a *Account) {
a.Name = "ollama-claude-target"
a.Credentials = map[string]any{"api_key": "k", "model_mapping": map[string]any{"alias": "claude-sonnet-4-5"}}
})
_, err := svc.SetAccountSchedulable(ctx, account.ID, true)
requireModelPricingMissing(t, err, "claude-sonnet-4-5")
resolver := NewModelPricingResolver(nil, svc.billingService)
require.True(t, ollamaCloudModelUnpricedForBilling(ctx, resolver, "claude-sonnet-4-5"),
"无分组/渠道显式定价时预检必须拦截 claude-*,对齐 RecordUsage 的 dropUnpricedClaudeBillingCandidates")
})
t.Run("启用已定价账号_通过", func(t *testing.T) {
repo, svc := newSvc(t)
account := seedOllamaGateAccount(t, repo, func(a *Account) {
@@ -68,7 +68,7 @@ func (s *AccountTestService) testCNProviderAdaptiveAnthropicConnection(c *gin.Co
if err != nil {
return s.sendErrorAndEnd(c, fmt.Sprintf("Invalid adaptive Anthropic base URL: %s", err.Error()))
}
apiURL := strings.TrimRight(baseURL, "/") + "/v1/messages"
apiURL := nativeAnthropicMessagesURL(account, baseURL)
payload, err := createTestPayload(testModelID)
if err != nil {
@@ -247,7 +247,7 @@ func (s *AccountTestService) testCNProviderAnthropicConnection(c *gin.Context, a
if err != nil {
return s.sendErrorAndEnd(c, fmt.Sprintf("Invalid Anthropic base URL: %s", err.Error()))
}
if hint := cnAnthropicBaseURLMisconfigHint(baseURL, account.routesByModel()); hint != "" {
if hint := cnAnthropicBaseURLMisconfigHint(baseURL, account.routesByModel() || account.IsOllamaCloud()); hint != "" {
return s.sendErrorAndEnd(c, hint)
}
apiURL := nativeAnthropicMessagesURL(account, baseURL)
@@ -112,6 +112,18 @@ func TestAccountTestService_OllamaCloudPinnedAnthropicProtocol(t *testing.T) {
require.Empty(t, req.URL.RawQuery)
require.Equal(t, "Bearer sk-ollama-test", req.Header.Get("Authorization"))
require.Contains(t, recorder.Body.String(), `"type":"test_complete"`)
// 带 /v1 后缀的自定义基址与线上 nativeAnthropicMessagesURL 对齐:不报误配,且不拼出 /v1/v1/messages。
accountWithV1 := ollamaCloudTestAccount(506, map[string]any{
"api_protocol": APIProtocolAnthropic,
"base_url": "https://ollama.com/v1",
})
svcV1, upstreamV1 := adaptiveCNAccountTestService(accountWithV1, adaptiveCNAnthropicTestResponse())
cV1, recorderV1 := newTestContext()
require.NoError(t, svcV1.TestAccountConnection(cV1, accountWithV1.ID, "", "", AccountTestModeDefault))
require.Len(t, upstreamV1.requests, 1)
require.Equal(t, "https://ollama.com/v1/messages", upstreamV1.requests[0].URL.String())
require.Contains(t, recorderV1.Body.String(), `"type":"test_complete"`)
}
// 钉 responses:单端点 /v1/responses + 无状态归一化(store=false)。
@@ -241,3 +241,14 @@ func TestQuotaFetcher_OpenCodeGoStillRoutesToCNQuota(t *testing.T) {
require.Equal(t, 1, cnQuota.calls)
require.Equal(t, 0, usage.getCalls())
}
func TestParseOllamaCloudBalanceUSD_RejectsNonFiniteValues(t *testing.T) {
for _, raw := range []string{"NaN", "Inf", "+Inf", "-Inf", "Infinity", "$NaN", "USD$Inf"} {
val, ok := parseOllamaCloudBalanceUSD(raw)
require.False(t, ok, "raw=%q", raw)
require.Zero(t, val)
}
val, ok := parseOllamaCloudBalanceUSD("$12.50")
require.True(t, ok)
require.InDelta(t, 12.50, val, 1e-9)
}
@@ -4,6 +4,7 @@ import (
"context"
"fmt"
"log/slog"
"math"
"sort"
"strconv"
"strings"
@@ -545,7 +546,7 @@ func parseOllamaCloudBalanceUSD(raw string) (float64, bool) {
return 0, false
}
value, err := strconv.ParseFloat(raw, 64)
if err != nil {
if err != nil || math.IsNaN(value) || math.IsInf(value, 0) {
return 0, false
}
return value, true
@@ -799,12 +799,20 @@ func usagePricingContext(ctx context.Context, apiKey *APIKey, quotaPlatform stri
}
func (s *GatewayService) recordUsageCore(ctx context.Context, input *recordUsageCoreInput) error {
ctx = usagePricingContext(ctx, input.APIKey, input.QuotaPlatform)
result := input.Result
apiKey := input.APIKey
user := input.User
account := input.Account
subscription := input.Subscription
// 配额平台在入口即回退到选中账号平台,保证渠道定价作用域与末尾配额扣减同源。
quotaPlatform := input.QuotaPlatform
if quotaPlatform == "" {
quotaPlatform = PlatformFromAPIKey(apiKey)
if quotaPlatform == PlatformComposite && account != nil {
quotaPlatform = account.Platform
}
}
ctx = usagePricingContext(ctx, apiKey, quotaPlatform)
ApplyForwardImageBillingResolution(result)
logServiceTierBillingDowngrade("service.gateway", account, result.RequestID, ApplyForwardServiceTierBillingResolution(result))
@@ -847,7 +855,8 @@ func (s *GatewayService) recordUsageCore(ctx context.Context, input *recordUsage
result.UpstreamResponseModelConflict,
result.ImageCount > 0 || result.AudioUsage != nil || result.SearchCount > 0 || result.CacheStorageTokenHours > 0,
); responseModel != "" && !strings.EqualFold(responseModel, strings.TrimSpace(billingModel)) {
if identified, responseChannelPriced := s.hasIdentifiedResponseModelPricing(ctx, responseModel, apiKey); identified {
if identified, responseChannelPriced := s.hasIdentifiedResponseModelPricing(ctx, responseModel, apiKey); identified &&
(!accountServesHostedModels(account) || !strings.Contains(strings.ToLower(responseModel), "claude") || responseChannelPriced) {
responseCost := s.calculateRecordUsageCost(ctx, result, apiKey, responseModel, multiplier, imageMultiplier, pricingAt)
baselineChannelPriced := s.resolveChannelPricing(ctx, billingModel, apiKey) != nil
if responseModelBillingAdoptable(cost, responseCost, baselineChannelPriced, responseChannelPriced) {
@@ -893,16 +902,6 @@ func (s *GatewayService) recordUsageCore(ctx context.Context, input *recordUsage
return nil
}
// 配额平台由 handler 在请求 ctx 内经 QuotaPlatform() 算定并通过 input 传入;
// 后扣运行在 worker 池的 background ctx 上,无法再从 ctx 取 ForcePlatform。
// 缺省(未设置)时回退到分组平台,保持对其它调用方的兼容。
quotaPlatform := input.QuotaPlatform
if quotaPlatform == "" {
quotaPlatform = PlatformFromAPIKey(apiKey)
if quotaPlatform == PlatformComposite && account != nil {
quotaPlatform = account.Platform
}
}
requestID := usageLog.RequestID
_, billingErr := applyUsageBilling(ctx, requestID, usageLog, &postUsageBillingParams{
Cost: cost,
@@ -107,6 +107,12 @@ func ollamaCloudModelUnpricedForBilling(ctx context.Context, resolver *ModelPric
if resolved == nil {
return true
}
// 与 RecordUsage 的 dropUnpricedClaudeBillingCandidates 对齐:ollama_cloud 上游不按全局
// Claude 价卡对 claude-* 出站名计费,仅显式配置分组/渠道定价时放行。
if strings.Contains(strings.ToLower(strings.TrimSpace(model)), "claude") &&
resolved.Source != PricingSourceGroup && resolved.Source != PricingSourceChannel {
return true
}
// 与 CalculateCostUnified 的模式分发一致:按次/图片/视频模式由
// calculatePerRequestCost 计价,缺价只会得到 0 而不会报错;只有 token 模式
// 会在 GetIntervalPricing 无价可取时以 ErrModelPricingUnavailable 失败。
@@ -248,15 +248,23 @@ func (s *OpenAIGatewayService) RecordUsage(ctx context.Context, input *OpenAIRec
if result == nil {
return errors.New("openai usage result is nil")
}
ctx = usagePricingContext(ctx, input.APIKey, input.QuotaPlatform)
if s.rateLimitService != nil && input.Account != nil && input.Account.Platform == PlatformOpenAI {
s.rateLimitService.ResetOpenAI403Counter(ctx, input.Account.ID)
}
apiKey := input.APIKey
user := input.User
account := input.Account
subscription := input.Subscription
// 配额平台在入口即回退到选中账号平台(含 RecordCyberPolicyUsageLog 等缺省调用方),
// 使 usagePricingContext 的渠道定价作用域与下方 user×platform 配额扣减严格同源。
quotaPlatform := input.QuotaPlatform
if quotaPlatform == "" {
quotaPlatform = PlatformFromAPIKey(apiKey)
if quotaPlatform == PlatformComposite && account != nil {
quotaPlatform = account.Platform
}
}
ctx = usagePricingContext(ctx, apiKey, quotaPlatform)
if s.rateLimitService != nil && account != nil && account.Platform == PlatformOpenAI {
s.rateLimitService.ResetOpenAI403Counter(ctx, account.ID)
}
billingAccount, err := resolveCredentialAccount(ctx, s.accountRepo, account)
if err != nil {
return err
@@ -584,19 +592,6 @@ func (s *OpenAIGatewayService) RecordUsage(ctx context.Context, input *OpenAIRec
return nil
}
// Async usage billing runs outside the original request context, so it
// cannot recover ForcePlatform there. Fall back for internal/test callers.
// fallback 与 generic 路径(gateway_usage_billing.go)同语义:composite 分组
// 请求缺省时回退到选中账号自己的平台——composite/openai 组默认值不是实际
// user×platform 配额维度,真正的 pool 请求必须按选中 account.Platform 扣减。
quotaPlatform := input.QuotaPlatform
if quotaPlatform == "" {
quotaPlatform = PlatformFromAPIKey(apiKey)
if quotaPlatform == PlatformComposite && account != nil {
quotaPlatform = account.Platform
}
}
_, billingErr := applyUsageBilling(ctx, requestID, usageLog, &postUsageBillingParams{
Cost: cost,
User: user,