From 625f7b0d23c0f5f7d377014132ecc7b43fa9197d Mon Sep 17 00:00:00 2001 From: alfadb Date: Sun, 13 Sep 2026 04:05:44 +0800 Subject: [PATCH] fix(billing): reject unpriced ollama cloud requests before upstream I/O MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ollama_cloud 的定价门禁此前位于 RecordUsage 成本计算(openai_gateway_usage.go B2-④ 分支)——那是异步记账阶段:上游已被调用、响应已写给客户端,拒绝只会让 usage 整条不落账,形成「请求成功但不计费」的静默漏损。 本 commit 把门禁前移到上游 I/O 之前(预检是主门,未定价直接 400、上游零调用): - buildUpstreamRequest(原生 Responses 出站;三条入站路径的转换分支都经过) - sendCCUpstreamRequest(raw CC 出站;三条入站路径的回退分支都经过) - buildNativeAnthropicUpstreamRequest(api_protocol=anthropic 独立构造器) 判定与计费同源:复用 RecordUsage → CalculateCostUnified → ModelPricingResolver 同一条解析链(Group → Channel → LiteLLM → Fallback);无价判定取 calculateTokenCost 的失败条件(token 模式下 GetIntervalPricing 无价可取), 按次/图片/视频模式从不因缺价报错故不视为未定价——预检不比计费更严格, 「只有渠道价」的合法流量不会被误拒(含测试)。 400 照抄 conversation 显式拒绝范式:类型化错误 + 服务层写 400 invalid_request_error(写前 MarkResponseCommitted,同 cyber_policy 先例), handler 检测响应已提交不追加 fallback;错误非 UpstreamFailoverError ⇒ 不换号、不写账号处置。 同时撤销异步阶段的 ollama_cloud 显式拒绝,未定价请求回到既有的零成本落账 + pricing_missing_record_zero_cost 告警路径——该告警是放量观察断言的观测依据, 不能被记账阶段的拒绝吃掉;相应改写 usageRepo.calls==0 的两个用例为 「兜底观测保持可用」的回归。 --- .../service/openai_gateway_cc_pipeline.go | 5 + .../service/openai_gateway_forward.go | 6 + ...penai_gateway_messages_anthropic_native.go | 7 + ..._gateway_ollama_cloud_billing_gate_test.go | 35 ++- ..._gateway_ollama_cloud_pricing_preflight.go | 126 ++++++++++ ...way_ollama_cloud_pricing_preflight_test.go | 230 ++++++++++++++++++ .../internal/service/openai_gateway_usage.go | 22 +- 7 files changed, 405 insertions(+), 26 deletions(-) create mode 100644 backend/internal/service/openai_gateway_ollama_cloud_pricing_preflight.go create mode 100644 backend/internal/service/openai_gateway_ollama_cloud_pricing_preflight_test.go diff --git a/backend/internal/service/openai_gateway_cc_pipeline.go b/backend/internal/service/openai_gateway_cc_pipeline.go index e5ed68c499..1444391dbd 100644 --- a/backend/internal/service/openai_gateway_cc_pipeline.go +++ b/backend/internal/service/openai_gateway_cc_pipeline.go @@ -192,6 +192,11 @@ func (s *OpenAIGatewayService) sendCCUpstreamRequest( // 字段,上游 400 "The `reasoning_content` in the thinking mode must be // passed back to the API"。在共用出站点补空格占位,真实明文不覆盖。 body = ensureDeepSeekChatReasoningPlaceholders(account, body) + // Ollama Cloud 请求期定价预检(raw CC 出站):未定价模型在任何上游 I/O 之前 + // 显式 400,且 400 已由 helper 写出。非 failover 错误 ⇒ 不换号、不写账号处置。 + if err := s.enforceOllamaCloudRequestPricingPreflight(ctx, c, account, body); err != nil { + return nil, err + } upstreamCtx, releaseUpstreamCtx := detachUpstreamContext(ctx) upstreamReq, err := http.NewRequestWithContext(upstreamCtx, http.MethodPost, targetURL, bytes.NewReader(body)) releaseUpstreamCtx() diff --git a/backend/internal/service/openai_gateway_forward.go b/backend/internal/service/openai_gateway_forward.go index 30f028c522..cd950014b9 100644 --- a/backend/internal/service/openai_gateway_forward.go +++ b/backend/internal/service/openai_gateway_forward.go @@ -1441,6 +1441,12 @@ func (s *OpenAIGatewayService) buildUpstreamRequest(ctx context.Context, c *gin. return nil, err } + // Ollama Cloud 请求期定价预检:未定价模型在构造上游请求(即任何上游 I/O)之前 + // 显式 400,且 400 已由 helper 写出。非 UpstreamFailoverError ⇒ 不换号、不写账号处置。 + if err := s.enforceOllamaCloudRequestPricingPreflight(ctx, c, account, body); err != nil { + return nil, err + } + req, err := http.NewRequestWithContext(ctx, "POST", targetURL, bytes.NewReader(body)) if err != nil { return nil, err diff --git a/backend/internal/service/openai_gateway_messages_anthropic_native.go b/backend/internal/service/openai_gateway_messages_anthropic_native.go index 740da84c65..b87d0eddaf 100644 --- a/backend/internal/service/openai_gateway_messages_anthropic_native.go +++ b/backend/internal/service/openai_gateway_messages_anthropic_native.go @@ -179,6 +179,13 @@ func (s *OpenAIGatewayService) buildNativeAnthropicUpstreamRequest( // 地址而非 CC/Responses 地址),详见 helper 注释。 body = clampOllamaCloudAnthropicMessagesMaxTokens(account, account.GetAnthropicProtocolBaseURL(), body) + // Ollama Cloud 请求期定价预检(api_protocol=anthropic 的独立构造器,覆盖 + // messages / responses / chat_completions 三条 anthropic 原生直通入站):未定价 + // 模型在任何上游 I/O 之前显式 400,且 400 已由 helper 写出。 + if err := s.enforceOllamaCloudRequestPricingPreflight(ctx, c, account, body); err != nil { + return nil, nil, err + } + req, err := http.NewRequestWithContext(ctx, http.MethodPost, targetURL, bytes.NewReader(body)) if err != nil { return nil, nil, err diff --git a/backend/internal/service/openai_gateway_ollama_cloud_billing_gate_test.go b/backend/internal/service/openai_gateway_ollama_cloud_billing_gate_test.go index c63bab092e..6effea1a0d 100644 --- a/backend/internal/service/openai_gateway_ollama_cloud_billing_gate_test.go +++ b/backend/internal/service/openai_gateway_ollama_cloud_billing_gate_test.go @@ -2,12 +2,15 @@ package service -// B2-④(请求期 ollama_cloud 定价缺失显式拒绝)与 S1(计费候选过滤纳入 -// ollama_cloud)的回归测试。 +// S1(计费候选过滤纳入 ollama_cloud)与定价缺失兜底路径的回归测试。 // // 关键顺序约束的实证:S1 只在「定价已就位」的前提下才安全——若过滤把候选滤空 // 而定价缺失,会从误计变全零计费。本文件用真实 fallbackPrices(含 ollama 价卡) // 证明:ollama 真实模型名(不含 claude-*)永不被过滤,候选不会滤空。 +// +// 未定价的主门在请求期定价预检(openai_gateway_ollama_cloud_pricing_preflight.go, +// 上游 I/O 之前 400);记账阶段的零成本落账 + 告警是预检漏放的兜底观测,本文件 +// 一并钉住该兜底不被回归吃掉。 import ( "context" @@ -52,10 +55,12 @@ func TestFilterCNProviderBillingModelCandidates_OllamaCloud(t *testing.T) { "显式渠道定价的 claude-* 候选必须保留(既有豁免语义)") } -// B2-④ 主断言:ollama_cloud + 未定价模型 → 400 MODEL_PRICING_MISSING、 -// 不落零成本记录(usage/billing 均不写库、日志无 pricing_missing_record_zero_cost -// 对应的落账路径)。 -func TestOpenAIGatewayRecordUsage_OllamaCloudUnpricedModelRejected(t *testing.T) { +// 请求期定价预检(openai_gateway_ollama_cloud_pricing_preflight.go)成为 ollama_cloud +// 未定价模型的主门之后,记账阶段回到全平台统一的 fail-open:定价缺失 → 零成本落账 +// + `openai_usage.pricing_missing_record_zero_cost` 告警。原 B2-④ 在记账阶段显式拒绝 +// 的用例改写为「兜底观测路径保持可用」的回归:拒绝阶段(异步)连 usage 记录都不写, +// 比零成本记录更难发现,且会吃掉放量观察所依赖的告警。 +func TestOpenAIGatewayRecordUsage_OllamaCloudUnpricedModelZeroCostObserved(t *testing.T) { usageRepo := &openAIRecordUsageLogRepoStub{inserted: true} billingRepo := &openAIRecordUsageBillingRepoStub{result: &UsageBillingApplyResult{Applied: true}} svc := newOpenAIRecordUsageServiceWithBillingRepoForTest(usageRepo, billingRepo, &openAIRecordUsageUserRepoStub{}, &openAIRecordUsageSubRepoStub{}, nil) @@ -74,14 +79,16 @@ func TestOpenAIGatewayRecordUsage_OllamaCloudUnpricedModelRejected(t *testing.T) 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, "拒绝路径不得触发计费入账") + require.NoError(t, err, "记账阶段不再拒绝:未定价模型回退零成本落账(主门在请求期预检)") + require.Equal(t, 1, usageRepo.calls, "零成本记录必须落账,作为 pricing_missing_record_zero_cost 告警的观测依据") + require.NotNil(t, usageRepo.lastLog) + require.Equal(t, 0.0, usageRepo.lastLog.ActualCost) } // claude-* 请求打到 ollama_cloud:候选被 S1 滤空 → ErrModelPricingUnavailable → -// B2-④ 显式拒绝。这是「按 Anthropic 价静默误计」被修复后的目标行为。 -func TestOpenAIGatewayRecordUsage_OllamaCloudClaudeNameRejected(t *testing.T) { +// 与其他平台一致的零成本落账。请求期该模型若未定价会先被预检 400(不发上游); +// 记账阶段不再有第二条拒绝路径。 +func TestOpenAIGatewayRecordUsage_OllamaCloudClaudeNameZeroCostObserved(t *testing.T) { usageRepo := &openAIRecordUsageLogRepoStub{inserted: true} billingRepo := &openAIRecordUsageBillingRepoStub{result: &UsageBillingApplyResult{Applied: true}} svc := newOpenAIRecordUsageServiceWithBillingRepoForTest(usageRepo, billingRepo, &openAIRecordUsageUserRepoStub{}, &openAIRecordUsageSubRepoStub{}, nil) @@ -100,8 +107,10 @@ func TestOpenAIGatewayRecordUsage_OllamaCloudClaudeNameRejected(t *testing.T) { User: &User{ID: 2}, Account: &Account{ID: 3, Platform: PlatformOllamaCloud}, }) - requireModelPricingMissing(t, err) - require.Zero(t, usageRepo.calls) + require.NoError(t, err) + require.Equal(t, 1, usageRepo.calls) + require.NotNil(t, usageRepo.lastLog) + require.Equal(t, 0.0, usageRepo.lastLog.ActualCost) } // 已定价模型(真实 :tag 请求形态)→ 正常落账且 actual_cost > 0: diff --git a/backend/internal/service/openai_gateway_ollama_cloud_pricing_preflight.go b/backend/internal/service/openai_gateway_ollama_cloud_pricing_preflight.go new file mode 100644 index 0000000000..9c23e5cab9 --- /dev/null +++ b/backend/internal/service/openai_gateway_ollama_cloud_pricing_preflight.go @@ -0,0 +1,126 @@ +package service + +// 请求期 ollama_cloud 定价预检:在上游 I/O 之前拒绝无价可循的出站模型(客户端 +// 得到 400),取代曾在 RecordUsage 成本计算里执行的异步阶段拒绝。异步阶段的拒绝 +// 位置是错的——那时上游已被调用、响应已写给客户端(各 handler 先 Forward,再把 +// RecordUsage 投递给后台 worker,其错误只在闭包里打日志),拒绝只会让 usage 整条 +// 不落账,形成「请求成功但不计费」的静默漏损。 +// +// 挂点(合计覆盖 ollama_cloud 的全部 HTTP 出站): +// - buildUpstreamRequest 原生 Responses 出站;三条入站路径的转换分支都经过它 +// - sendCCUpstreamRequest raw CC 出站;三条入站路径的回退分支都经过它 +// - buildNativeAnthropicUpstreamRequest api_protocol=anthropic 的独立构造器 +// +// 判定与计费同源:复用 RecordUsage → CalculateCostUnified → ModelPricingResolver +// 的同一条解析链(Group → Channel → LiteLLM → Fallback)。无价判定取 +// calculateTokenCost 的失败条件(token 模式下 GetIntervalPricing 无价可取);按次 / +// 图片 / 视频模式走 calculatePerRequestCost,从不因缺价报错,因此不视为未定价—— +// 预检绝不会比计费更严格,「只有渠道价 / 分组价」的合法流量不会被误拒。 +// +// 预检是主门;未定价请求被放行(理论上仅剩 body 无模型名等无法判定的形态)时, +// 计费侧回退到既有的零成本落账 + `openai_usage.pricing_missing_record_zero_cost` +// 告警路径——那条告警是放量观察断言的观测依据,不能被本门禁遮蔽。 + +import ( + "context" + "fmt" + "net/http" + "strings" + + "github.com/Wei-Shaw/sub2api/internal/pkg/ctxkey" + "github.com/gin-gonic/gin" + "github.com/tidwall/gjson" +) + +// openAIOllamaCloudUnpricedModelError 标记 ollama_cloud 出站模型名在计费同一条 +// 解析链上无价可循。网关必须把它应答为 400 invalid_request_error,不得向上游转发, +// 也不得触发账号 failover。 +type openAIOllamaCloudUnpricedModelError struct { + model string +} + +func (e *openAIOllamaCloudUnpricedModelError) Error() string { + return fmt.Sprintf( + "model %q has no pricing configured and cannot be billed: configure model pricing (base, group or channel) or adjust the account model_mapping/allowed_models", + e.model, + ) +} + +// respondOpenAIOllamaCloudUnpricedModelError 按 respondOpenAIStatelessFieldError 的 +// 先例由服务层直接写出 400 invalid_request_error。写前 MarkResponseCommitted 与 +// cyber_policy / grok content 拒绝同款:handler 侧 ensureForwardErrorResponse / +// ensureAnthropicErrorResponse 检测到响应已提交便不再追加 fallback 错误;返回的 +// 错误非 UpstreamFailoverError——不换号、不写账号处置。 +func respondOpenAIOllamaCloudUnpricedModelError(c *gin.Context, err *openAIOllamaCloudUnpricedModelError) { + setOpsUpstreamError(c, http.StatusBadRequest, err.Error(), "") + MarkResponseCommitted(c) + c.JSON(http.StatusBadRequest, gin.H{"error": gin.H{ + "type": "invalid_request_error", + "message": err.Error(), + }}) +} + +// ollamaCloudBillingGroupFromContext 取认证中间件放入 ctx 的计费分组(与利润门 D +// 同一口径:计费永远按 apiKey 自身分组),用于分组/渠道定价查找。ctx 无有效分组 +// (内部调用、直接构造 service 的单测)时返回 nil——等价于计费在无分组输入下的 +// 解析行为,不会让预检更严格。 +func ollamaCloudBillingGroupFromContext(ctx context.Context) *Group { + if ctx == nil { + return nil + } + group, _ := ctx.Value(ctxkey.Group).(*Group) + if IsGroupContextValid(group) { + return group + } + return nil +} + +// ollamaCloudModelUnpricedForBilling 报告模型在计费的解析链上是否无价可循。 +// s.resolver 为 nil 时恒返回 false(放行):生产 wire 必然注入 resolver,直接构造 +// struct 的单测与内部调用不应被门禁拦截(与 resolveOpenAIChannelPricing 的 nil 守卫 +// 同一取舍)。 +func (s *OpenAIGatewayService) ollamaCloudModelUnpricedForBilling(ctx context.Context, model string) bool { + if s == nil || s.resolver == nil { + return false + } + group := ollamaCloudBillingGroupFromContext(ctx) + var groupID *int64 + if group != nil { + gid := group.ID + groupID = &gid + } + resolved := s.resolver.Resolve(ctx, PricingInput{Model: model, GroupID: groupID, Group: group}) + if resolved == nil { + return true + } + // 与 CalculateCostUnified 的模式分发一致:按次/图片/视频模式由 + // calculatePerRequestCost 计价,缺价只会得到 0 而不会报错;只有 token 模式 + // 会在 GetIntervalPricing 无价可取时以 ErrModelPricingUnavailable 失败。 + if resolved.Mode != BillingModeToken { + return false + } + // 定价上下文取 1 token(最低档):GetIntervalPricing 返回 nil 与否只取决于 + // BasePricing 是否存在,与上下文档位无关,与 calculateTokenCost 的失败条件 + // 完全同一条链。 + return s.resolver.GetIntervalPricing(resolved, 1) == nil +} + +// enforceOllamaCloudRequestPricingPreflight 在上游 I/O 之前对 ollama_cloud 出站做 +// 定价预检。未定价时写出 400 并返回类型化错误,调用方原样 `return nil, err` 即可 +// 终止本次出站(构造的请求不会发出,上游零调用)。非 ollama_cloud 账号、出站 +// body 缺模型名(无法判定,交由计费侧零成本告警观测)一律放行。 +func (s *OpenAIGatewayService) enforceOllamaCloudRequestPricingPreflight(ctx context.Context, c *gin.Context, account *Account, body []byte) error { + if account == nil || !account.IsOllamaCloud() { + return nil + } + model := strings.TrimSpace(gjson.GetBytes(body, "model").String()) + if model == "" { + return nil + } + if !s.ollamaCloudModelUnpricedForBilling(ctx, model) { + return nil + } + err := &openAIOllamaCloudUnpricedModelError{model: model} + respondOpenAIOllamaCloudUnpricedModelError(c, err) + return err +} diff --git a/backend/internal/service/openai_gateway_ollama_cloud_pricing_preflight_test.go b/backend/internal/service/openai_gateway_ollama_cloud_pricing_preflight_test.go new file mode 100644 index 0000000000..6086fadede --- /dev/null +++ b/backend/internal/service/openai_gateway_ollama_cloud_pricing_preflight_test.go @@ -0,0 +1,230 @@ +//go:build unit + +package service + +// 请求期 ollama_cloud 定价预检的回归测试(上游 I/O 之前 400)。 +// +// 最重要的验收断言是「上游零调用 + 不 failover / 不写账号处置」:未定价请求必须在 +// 构造上游请求之前被终止,客户端拿到 400 invalid_request_error,而不是像旧的异步 +// 阶段拒绝那样——上游已被调用、响应已写给客户端之后才在记账阶段丢弃 usage。 + +import ( + "bytes" + "context" + "errors" + "net/http" + "net/http/httptest" + "testing" + + "github.com/Wei-Shaw/sub2api/internal/pkg/ctxkey" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" +) + +// newPricingPreflightTestService 构造带真实定价解析链(fallbackPrices 价卡 + +// 可选渠道定价)的网关服务,供预检测试复用。 +func newPricingPreflightTestService(upstream *httpUpstreamRecorder, groupID int64, channelPricings []ChannelModelPricing) *OpenAIGatewayService { + bs := NewBillingService(nil, nil) + svc := &OpenAIGatewayService{ + cfg: rawChatCompletionsTestConfig(), + httpUpstream: upstream, + billingService: bs, + resolver: NewModelPricingResolver(nil, bs), + } + if len(channelPricings) > 0 { + svc.channelService = newChannelServiceWithPricings(groupID, channelPricings) + svc.resolver = NewModelPricingResolver(svc.channelService, bs) + } + return svc +} + +// pricingPreflightGroup 构造通过 IsGroupContextValid 的认证分组(ctxkey.Group 载体)。 +func pricingPreflightGroup(id int64, modelPricing ...ChannelModelPricing) *Group { + return &Group{ + ID: id, + Platform: PlatformOllamaCloud, + Status: StatusActive, + Hydrated: true, + ModelPricing: modelPricing, + } +} + +func pricingPreflightContext(path string, body []byte, group *Group) (*gin.Context, *httptest.ResponseRecorder, context.Context) { + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, path, bytes.NewReader(body)) + c.Request.Header.Set("Content-Type", "application/json") + ctx := context.Background() + if group != nil { + ctx = context.WithValue(ctx, ctxkey.Group, group) + } + return c, rec, ctx +} + +// assertPricingPreflightRejected 汇总预检拒绝路径的共同断言:上游零调用(最重要)、 +// 客户端可见 400 invalid_request_error、响应已提交标记(handler 不追加 fallback)、 +// 返回类型化错误且非 UpstreamFailoverError(不换号、不写账号处置)。 +func assertPricingPreflightRejected(t *testing.T, c *gin.Context, upstream *httpUpstreamRecorder, rec *httptest.ResponseRecorder, err error, wantModel string) { + t.Helper() + + require.Nil(t, upstream.lastReq, "未定价请求不得发起任何上游调用(核心验收断言)") + require.Nil(t, upstream.lastBody) + require.Equal(t, http.StatusBadRequest, rec.Code, "client-visible 状态码必须是 400") + require.Equal(t, "invalid_request_error", gjson.Get(rec.Body.String(), "error.type").String()) + require.Contains(t, rec.Body.String(), wantModel, "错误体必须点名未定价模型") + require.True(t, IsResponseCommitted(c), "响应已提交标记必须置位(handler 不再追加 fallback 错误)") + + var unpricedErr *openAIOllamaCloudUnpricedModelError + require.ErrorAs(t, err, &unpricedErr, "必须是预检类型化错误") + var failoverErr *UpstreamFailoverError + require.False(t, errors.As(err, &failoverErr), "预检错误不得是 failover 错误") +} + +// TestOllamaCloudPricingPreflight_RejectsUnpricedBeforeUpstream 主验收:原生 +// Responses 出站(buildUpstreamRequest 挂点)上,未定价模型在发起上游请求之前被 +// 400 终止。 +func TestOllamaCloudPricingPreflight_RejectsUnpricedBeforeUpstream(t *testing.T) { + gin.SetMode(gin.TestMode) + + upstream := &httpUpstreamRecorder{err: errors.New("must not reach upstream")} + svc := newPricingPreflightTestService(upstream, 0, nil) + account := adaptiveProtocolTestAccount(PlatformOllamaCloud, nil) + + body := []byte(`{"model":"totally-unpriced-model","input":"hi","stream":false}`) + c, rec, ctx := pricingPreflightContext("/v1/responses", body, nil) + _, err := svc.Forward(ctx, c, account, body) + assertPricingPreflightRejected(t, c, upstream, rec, err, "totally-unpriced-model") +} + +// TestOllamaCloudPricingPreflight_BasePricedModelPasses 基础价(fallbackPrices 命中) +// 的模型必须正常出站——预检只拒无价可循的名字。 +func TestOllamaCloudPricingPreflight_BasePricedModelPasses(t *testing.T) { + gin.SetMode(gin.TestMode) + + upstream := &httpUpstreamRecorder{err: errors.New("stop after capture")} + svc := newPricingPreflightTestService(upstream, 0, nil) + account := adaptiveProtocolTestAccount(PlatformOllamaCloud, nil) + + body := []byte(`{"model":"gpt-oss:120b-cloud","input":"hi","stream":false}`) + c, rec, ctx := pricingPreflightContext("/v1/responses", body, nil) + _, err := svc.Forward(ctx, c, account, body) + require.NotNil(t, upstream.lastReq, "已定价模型不得被预检拦截") + require.Equal(t, "https://ollama.com/v1/responses", upstream.lastReq.URL.String()) + require.NotEqual(t, http.StatusBadRequest, rec.Code) + require.Error(t, err) // upstream 被Recorder 短路,错误来自传输层,与预检无关 +} + +// TestOllamaCloudPricingPreflight_ChannelOnlyPricedModelPasses 「判定与计费同源」的 +// 关键用例:模型只在渠道定价里配置、不在基础价里 → 计费能算出成本,预检不得拒绝。 +func TestOllamaCloudPricingPreflight_ChannelOnlyPricedModelPasses(t *testing.T) { + gin.SetMode(gin.TestMode) + + const groupID = int64(777) + upstream := &httpUpstreamRecorder{err: errors.New("stop after capture")} + svc := newPricingPreflightTestService(upstream, groupID, []ChannelModelPricing{ + tokenPricingForModels([]string{"channel-only-model"}, 3.0), + }) + account := adaptiveProtocolTestAccount(PlatformOllamaCloud, nil) + + body := []byte(`{"model":"channel-only-model","input":"hi","stream":false}`) + c, rec, ctx := pricingPreflightContext("/v1/responses", body, pricingPreflightGroup(groupID)) + _, err := svc.Forward(ctx, c, account, body) + require.NotNil(t, upstream.lastReq, "只有渠道价的模型不得被预检误拒(预检不得比计费更严格)") + require.Equal(t, "channel-only-model", gjson.GetBytes(upstream.lastBody, "model").String()) + require.NotEqual(t, http.StatusBadRequest, rec.Code) + require.Error(t, err) // upstream 短路错误,与预检无关 +} + +// TestOllamaCloudModelUnpricedForBilling_MatchesBillingChain 钉住判定函数与计费 +// 解析链(Group → Channel → LiteLLM → Fallback)的同源矩阵。 +func TestOllamaCloudModelUnpricedForBilling_MatchesBillingChain(t *testing.T) { + const groupID = int64(778) + bs := NewBillingService(nil, nil) + channelSvc := newChannelServiceWithPricings(groupID, []ChannelModelPricing{ + tokenPricingForModels([]string{"channel-only-model"}, 3.0), + { + Platform: PlatformOpenAI, + Models: []string{"per-request-only-model"}, + BillingMode: BillingModePerRequest, + PerRequestPrice: f64p(0.5), + }, + }) + svc := &OpenAIGatewayService{ + billingService: bs, + channelService: channelSvc, + resolver: NewModelPricingResolver(channelSvc, bs), + } + // resolver 缺失(直接构造 service 的场景)恒放行。 + require.False(t, (&OpenAIGatewayService{}).ollamaCloudModelUnpricedForBilling(context.Background(), "totally-unpriced-model")) + + withGroup := context.WithValue(context.Background(), ctxkey.Group, pricingPreflightGroup(groupID)) + + // 基础价命中(fallbackPrices ollama 价卡,含 :tag 两级 fallback)。 + require.False(t, svc.ollamaCloudModelUnpricedForBilling(context.Background(), "gpt-oss:120b-cloud")) + // 全链未命中。 + require.True(t, svc.ollamaCloudModelUnpricedForBilling(context.Background(), "totally-unpriced-model")) + // 只有渠道价(token 模式):带认证分组 → 有价;不带分组 → 计费同样看不到渠道价。 + require.False(t, svc.ollamaCloudModelUnpricedForBilling(withGroup, "channel-only-model")) + require.True(t, svc.ollamaCloudModelUnpricedForBilling(context.Background(), "channel-only-model")) + // 渠道按次模式:calculatePerRequestCost 从不因缺价报错 → 永不判无价。 + require.False(t, svc.ollamaCloudModelUnpricedForBilling(withGroup, "per-request-only-model")) + // 分组价卡命中。 + groupWithPricing := pricingPreflightGroup(groupID, tokenPricingForModels([]string{"group-priced-model"}, 2.0)) + groupCtx := context.WithValue(context.Background(), ctxkey.Group, groupWithPricing) + require.False(t, svc.ollamaCloudModelUnpricedForBilling(groupCtx, "group-priced-model")) +} + +// TestOllamaCloudPricingPreflight_RawCCPathRejectsUnpriced raw CC 出站挂点 +// (sendCCUpstreamRequest):显式 api_protocol=chat_completions 的 ollama 账号, +// 未定价模型在发送前 400、上游零调用。 +func TestOllamaCloudPricingPreflight_RawCCPathRejectsUnpriced(t *testing.T) { + gin.SetMode(gin.TestMode) + + upstream := &httpUpstreamRecorder{err: errors.New("must not reach upstream")} + svc := newPricingPreflightTestService(upstream, 0, nil) + account := &Account{ + ID: 907, + Name: "ollama-cloud-cc", + Platform: PlatformOllamaCloud, + Type: AccountTypeAPIKey, + Concurrency: 1, + Credentials: map[string]any{ + "api_key": "sk-test", + "api_protocol": APIProtocolChatCompletions, + "base_url": "https://ollama.com", + }, + } + + body := []byte(`{"model":"totally-unpriced-model","messages":[{"role":"user","content":"hi"}],"stream":false}`) + c, rec, ctx := pricingPreflightContext("/v1/chat/completions", body, nil) + _, err := svc.forwardAsRawChatCompletions(ctx, c, account, body, "") + assertPricingPreflightRejected(t, c, upstream, rec, err, "totally-unpriced-model") +} + +// TestOllamaCloudPricingPreflight_AnthropicNativePathRejectsUnpriced 第三挂点 +// (buildNativeAnthropicUpstreamRequest):api_protocol=anthropic 的 ollama 账号走 +// 独立构造器,未定价模型同样必须在任何上游 I/O 之前 400。 +func TestOllamaCloudPricingPreflight_AnthropicNativePathRejectsUnpriced(t *testing.T) { + gin.SetMode(gin.TestMode) + + upstream := &httpUpstreamRecorder{err: errors.New("must not reach upstream")} + svc := newPricingPreflightTestService(upstream, 0, nil) + account := &Account{ + ID: 908, + Name: "ollama-cloud-anthropic", + Platform: PlatformOllamaCloud, + Type: AccountTypeAPIKey, + Concurrency: 1, + Credentials: map[string]any{ + "api_key": "sk-test", + "api_protocol": APIProtocolAnthropic, + "base_url": "https://ollama.com", + }, + } + + body := []byte(`{"model":"totally-unpriced-model","max_tokens":64,"messages":[{"role":"user","content":"hi"}],"stream":false}`) + c, rec, ctx := pricingPreflightContext("/v1/messages", body, nil) + _, err := svc.ForwardAsAnthropic(ctx, c, account, body, "", "") + assertPricingPreflightRejected(t, c, upstream, rec, err, "totally-unpriced-model") +} diff --git a/backend/internal/service/openai_gateway_usage.go b/backend/internal/service/openai_gateway_usage.go index 04f5696d52..d71823161f 100644 --- a/backend/internal/service/openai_gateway_usage.go +++ b/backend/internal/service/openai_gateway_usage.go @@ -13,7 +13,6 @@ 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" @@ -170,8 +169,10 @@ func groupBillsOpenAIFastAtStandard(apiKey *APIKey, account *Account, serviceTie // AND COALESCE(a.credentials->'model_mapping','{}'::jsonb) = '{}'::jsonb; // // 上线后观察断言:日志中 `openai_usage.pricing_missing_record_zero_cost` 出现 -// 次数必须为 0(出现即回滚放量);ollama_cloud 的定价缺失会走上方 B2-④ 的 -// MODEL_PRICING_MISSING 显式拒绝而非零成本落账。 +// 次数必须为 0(出现即回滚放量)。定价门禁已前移到上游 I/O 之前的请求期预检 +// (openai_gateway_ollama_cloud_pricing_preflight.go,未定价直接 400,不发上游); +// 记账阶段不再拒绝——这里只保留零成本落账 + 本告警作为「预检漏放」的兜底观测, +// 两者不互相遮蔽:告警出现即说明有请求绕过了预检,需要排查而不是靠记账阶段补拒。 // // RecordUsage records usage and deducts balance func (s *OpenAIGatewayService) RecordUsage(ctx context.Context, input *OpenAIRecordUsageInput) error { @@ -277,16 +278,11 @@ 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)) - } + // 定价缺失回到既有的全平台 fail-open 设计:零成本落账 + Warn 告警。 + // ollama_cloud 的请求期拒绝已前移到上游 I/O 之前的定价预检(见 + // openai_gateway_ollama_cloud_pricing_preflight.go);记账阶段拒绝会在 + // 上游已调用、响应已写给客户端之后连 usage 记录一起丢掉,比零成本记录 + // 更难发现,故不再在此拒绝——本告警是「预检漏放」的观测依据。 logger.L().With( zap.String("component", "service.openai_gateway"), zap.Strings("billing_models", billingModels),