From e7fcf51343bcd6e2b51a0ea98c3d04c1276ece32 Mon Sep 17 00:00:00 2001 From: shaw Date: Sat, 5 Dec 2026 10:41:13 +0800 Subject: [PATCH] =?UTF-8?q?fix(ollama,=20billing):=20=E6=8B=A6=E6=88=AA?= =?UTF-8?q?=E6=9C=AA=E9=85=8D=E4=BB=B7=20claude=20=E5=87=BA=E7=AB=99?= =?UTF-8?q?=E6=A8=A1=E5=9E=8B=E5=B9=B6=E5=AF=B9=E9=BD=90=E8=AE=A1=E8=B4=B9?= =?UTF-8?q?=E9=85=8D=E9=A2=9D=E5=B9=B3=E5=8F=B0=E3=80=81=E8=BF=9E=E6=8E=A5?= =?UTF-8?q?=E6=B5=8B=E8=AF=95=E4=B8=8E=E7=9B=91=E6=8E=A7=E4=BD=99=E9=A2=9D?= =?UTF-8?q?=E8=A7=A3=E6=9E=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../account_ollama_cloud_pricing_gate.go | 7 +++++ .../account_ollama_cloud_pricing_gate_test.go | 14 +++++++++ .../account_test_service_cn_adaptive.go | 4 +-- .../account_test_service_ollama_cloud_test.go | 12 +++++++ .../channel_monitor_ollama_cloud_test.go | 11 +++++++ .../service/channel_monitor_quota_fetcher.go | 3 +- .../internal/service/gateway_usage_billing.go | 23 +++++++------- ..._gateway_ollama_cloud_pricing_preflight.go | 6 ++++ .../internal/service/openai_gateway_usage.go | 31 ++++++++----------- 9 files changed, 78 insertions(+), 33 deletions(-) diff --git a/backend/internal/service/account_ollama_cloud_pricing_gate.go b/backend/internal/service/account_ollama_cloud_pricing_gate.go index 5a81b87935..7de3d2d483 100644 --- a/backend/internal/service/account_ollama_cloud_pricing_gate.go +++ b/backend/internal/service/account_ollama_cloud_pricing_gate.go @@ -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) } diff --git a/backend/internal/service/account_ollama_cloud_pricing_gate_test.go b/backend/internal/service/account_ollama_cloud_pricing_gate_test.go index bd0eee2acc..83955d92e4 100644 --- a/backend/internal/service/account_ollama_cloud_pricing_gate_test.go +++ b/backend/internal/service/account_ollama_cloud_pricing_gate_test.go @@ -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) { diff --git a/backend/internal/service/account_test_service_cn_adaptive.go b/backend/internal/service/account_test_service_cn_adaptive.go index 9e8be788e5..ab6574c385 100644 --- a/backend/internal/service/account_test_service_cn_adaptive.go +++ b/backend/internal/service/account_test_service_cn_adaptive.go @@ -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) diff --git a/backend/internal/service/account_test_service_ollama_cloud_test.go b/backend/internal/service/account_test_service_ollama_cloud_test.go index da56d2dd76..0fa18e312a 100644 --- a/backend/internal/service/account_test_service_ollama_cloud_test.go +++ b/backend/internal/service/account_test_service_ollama_cloud_test.go @@ -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)。 diff --git a/backend/internal/service/channel_monitor_ollama_cloud_test.go b/backend/internal/service/channel_monitor_ollama_cloud_test.go index 5acb3c95bf..87d65deb0d 100644 --- a/backend/internal/service/channel_monitor_ollama_cloud_test.go +++ b/backend/internal/service/channel_monitor_ollama_cloud_test.go @@ -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) +} diff --git a/backend/internal/service/channel_monitor_quota_fetcher.go b/backend/internal/service/channel_monitor_quota_fetcher.go index 35db3e39b8..78e2b4564d 100644 --- a/backend/internal/service/channel_monitor_quota_fetcher.go +++ b/backend/internal/service/channel_monitor_quota_fetcher.go @@ -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 diff --git a/backend/internal/service/gateway_usage_billing.go b/backend/internal/service/gateway_usage_billing.go index bb0f207b15..7d468ee871 100644 --- a/backend/internal/service/gateway_usage_billing.go +++ b/backend/internal/service/gateway_usage_billing.go @@ -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, diff --git a/backend/internal/service/openai_gateway_ollama_cloud_pricing_preflight.go b/backend/internal/service/openai_gateway_ollama_cloud_pricing_preflight.go index 7fd4d295aa..1080d2830e 100644 --- a/backend/internal/service/openai_gateway_ollama_cloud_pricing_preflight.go +++ b/backend/internal/service/openai_gateway_ollama_cloud_pricing_preflight.go @@ -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 失败。 diff --git a/backend/internal/service/openai_gateway_usage.go b/backend/internal/service/openai_gateway_usage.go index 6a9b42f65e..e541dd8f69 100644 --- a/backend/internal/service/openai_gateway_usage.go +++ b/backend/internal/service/openai_gateway_usage.go @@ -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,