From d1f65572c146df4efef8039633894b164af82f34 Mon Sep 17 00:00:00 2001 From: alfadb Date: Sat, 12 Sep 2026 14:04:04 +0800 Subject: [PATCH 01/81] feat(composite): balance compatible providers with sticky sessions MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit composite 路由改为按兼容平台候选池跨平台调度:调度状态归属候选池并支持 previous_response_id sticky 绑定,per-attempt 策略按渠道限制、平台/渠道配额与 RPM 准入筛选,出站记录仅记实际选中的 upstream。 --- .../internal/handler/composite_platform.go | 104 +- .../handler/composite_platform_pool_test.go | 205 +++ .../handler/composite_pool_attempt_policy.go | 219 ++++ .../composite_pool_attempt_policy_test.go | 322 +++++ backend/internal/handler/endpoint.go | 15 +- .../handler/endpoint_upstream_record_test.go | 89 ++ .../handler/openai_chat_completions.go | 85 +- .../handler/openai_gateway_handler.go | 198 ++- backend/internal/handler/ops_error_logger.go | 4 + backend/internal/pkg/ctxkey/ctxkey.go | 5 + backend/internal/server/routes/gateway.go | 207 +++- ..._composite_cross_platform_dispatch_test.go | 518 ++++++++ ...eway_composite_pool_attempt_policy_test.go | 824 ++++++++++++ .../gateway_composite_pool_policy_test.go | 611 +++++++++ .../routes/gateway_composite_pool_test.go | 372 ++++++ .../internal/service/billing_cache_service.go | 27 + .../service/composite_account_claims.go | 100 ++ .../service/composite_account_claims_test.go | 180 +++ .../internal/service/composite_model_route.go | 48 +- .../internal/service/composite_platform.go | 79 ++ .../service/composite_platform_test.go | 62 +- .../composite_pool_attempt_policy_test.go | 378 ++++++ .../service/composite_pool_contract_test.go | 356 ++++++ .../internal/service/composite_pool_policy.go | 95 ++ .../service/composite_route_resolver.go | 14 + .../gateway_forward_as_chat_completions.go | 1 + .../gateway_hotpath_optimization_test.go | 47 +- .../internal/service/gateway_scheduling.go | 13 +- backend/internal/service/gateway_service.go | 113 +- .../service/gateway_upstream_record_test.go | 115 ++ .../service/gateway_upstream_request.go | 9 + .../service/openai_account_scheduler.go | 152 ++- .../service/openai_account_scheduler_test.go | 25 + .../openai_composite_pool_scheduling_test.go | 1102 +++++++++++++++++ .../service/openai_gateway_messages.go | 3 + ...penai_gateway_messages_anthropic_native.go | 6 + .../openai_gateway_messages_chat_fallback.go | 3 + .../service/openai_gateway_scheduling.go | 126 +- .../internal/service/openai_gateway_usage.go | 6 + .../service/openai_ws_forwarder_support.go | 30 +- .../internal/service/ops_upstream_context.go | 55 + 41 files changed, 6682 insertions(+), 241 deletions(-) create mode 100644 backend/internal/handler/composite_platform_pool_test.go create mode 100644 backend/internal/handler/composite_pool_attempt_policy.go create mode 100644 backend/internal/handler/composite_pool_attempt_policy_test.go create mode 100644 backend/internal/handler/endpoint_upstream_record_test.go create mode 100644 backend/internal/server/routes/gateway_composite_cross_platform_dispatch_test.go create mode 100644 backend/internal/server/routes/gateway_composite_pool_attempt_policy_test.go create mode 100644 backend/internal/server/routes/gateway_composite_pool_policy_test.go create mode 100644 backend/internal/server/routes/gateway_composite_pool_test.go create mode 100644 backend/internal/service/composite_account_claims.go create mode 100644 backend/internal/service/composite_account_claims_test.go create mode 100644 backend/internal/service/composite_pool_attempt_policy_test.go create mode 100644 backend/internal/service/composite_pool_contract_test.go create mode 100644 backend/internal/service/composite_pool_policy.go create mode 100644 backend/internal/service/gateway_upstream_record_test.go create mode 100644 backend/internal/service/openai_composite_pool_scheduling_test.go diff --git a/backend/internal/handler/composite_platform.go b/backend/internal/handler/composite_platform.go index 6e613aa3e4..dd2e4ce03c 100644 --- a/backend/internal/handler/composite_platform.go +++ b/backend/internal/handler/composite_platform.go @@ -10,6 +10,45 @@ import ( "github.com/tidwall/gjson" ) +// compositeAccountPoolCandidates 返回当前 composite 请求的账号池候选集合; +// 非池请求返回 false。与 service pool 语义一致:已有明确 resolved endpoint +// pin(如 Gemini fallback)时按 single 处理——候选数据保留在 ctx 但不作为 +// 活跃池,handler/route 准入均以 pin 优先。 +func compositeAccountPoolCandidates(c *gin.Context) ([]string, bool) { + if c == nil || c.Request == nil { + return nil, false + } + if _, resolved := service.ResolvedTargetPlatformFromContext(c.Request.Context()); resolved { + return nil, false + } + candidates := service.CompositeCandidatePlatformsFromContext(c.Request.Context()) + if len(candidates) == 0 { + return nil, false + } + return candidates, true +} + +// compositeCandidatesWithinAllowed 报告账号池候选是否被允许集完整包含; +// 池不折叠为单一平台,任一候选越界即不允许。 +func compositeCandidatesWithinAllowed(candidates, allowed []string) bool { + if len(candidates) == 0 { + return false + } + for _, candidate := range candidates { + found := false + for _, allowedPlatform := range allowed { + if candidate == allowedPlatform { + found = true + break + } + } + if !found { + return false + } + } + return true +} + func ensureCompositeTargetPlatform(c *gin.Context, apiKey *service.APIKey, model string) { if c == nil || c.Request == nil || apiKey == nil || apiKey.Group == nil || apiKey.Group.Platform != service.PlatformComposite { return @@ -17,6 +56,11 @@ func ensureCompositeTargetPlatform(c *gin.Context, apiKey *service.APIKey, model if _, ok := service.ResolvedTargetPlatformFromContext(c.Request.Context()); ok { return } + // 账号池请求已由路由层写入完整池决策:不在这里做单平台 detector, + // 避免把池折叠成一个平台或产生与 selector 不一致的二次解析。 + if _, ok := compositeAccountPoolCandidates(c); ok { + return + } if platform, ok := service.DetectModelPlatform(model); ok { c.Request = c.Request.WithContext(service.WithResolvedTargetPlatform(c.Request.Context(), platform)) } @@ -27,6 +71,9 @@ func compositeTargetPlatformAllowed(c *gin.Context, apiKey *service.APIKey, mode return true } ensureCompositeTargetPlatform(c, apiKey, model) + if candidates, ok := compositeAccountPoolCandidates(c); ok { + return compositeCandidatesWithinAllowed(candidates, allowed) + } platform, ok := service.ResolvedTargetPlatformFromContext(c.Request.Context()) if !ok { return false @@ -44,6 +91,11 @@ func compositeTargetPlatformResolved(c *gin.Context, apiKey *service.APIKey, mod return true } ensureCompositeTargetPlatform(c, apiKey, model) + // 账号池是已解析的完整决策(候选集合非空且已落 ctx),不因缺少单一 + // ResolvedTargetPlatform 而视为未解析。 + if _, ok := compositeAccountPoolCandidates(c); ok { + return true + } _, ok := service.ResolvedTargetPlatformFromContext(c.Request.Context()) return ok } @@ -172,7 +224,57 @@ func bindOpenAIReasoningEffortPolicyForMessagesRequest(c *gin.Context, apiKey *s } maxEffort, mappings, overLimit, ok := openAIReasoningEffortPolicyForRequest(c, apiKey) if !ok { - return + // composite 账号池请求没有单一目标平台,准入期判不出策略族;Forward + // 服务侧按选中账号是否 openai 决定是否应用(与 single-openai 目标同 + // 语义),因此这里直接绑定组策略,其余平台的选中结果服务侧会跳过。 + if _, isPool := compositeAccountPoolCandidates(c); !isPool { + return + } + maxEffort, mappings, overLimit = apiKey.Group.MaxReasoningEffort, apiKey.Group.ReasoningEffortMappings, apiKey.Group.MaxReasoningEffortOverLimit } c.Request = c.Request.WithContext(service.WithOpenAIReasoningEffortPolicy(c.Request.Context(), maxEffort, mappings, overLimit)) } + +// compositePoolResponseStateGuardApplies 报告当前请求是否为 composite 账号池 +// 请求(无单一目标 pin)。previous_response_id 状态归属守卫仅适用池请求; +// 单目标请求保留既有转发语义。 +func compositePoolResponseStateGuardApplies(c *gin.Context, apiKey *service.APIKey) bool { + if c == nil || c.Request == nil || apiKey == nil || apiKey.Group == nil || apiKey.Group.Platform != service.PlatformComposite { + return false + } + _, isPool := compositeAccountPoolCandidates(c) + return isPool +} + +// releaseCompositePoolSelection 在选号之后、handler 抢槽之前的守卫早退路径上 +// 释放 selector 已持有的账号槽位(Acquired=true 时 ReleaseFunc 非空)。置空 +// ReleaseFunc 保证恰一次释放,不与后续 acquire/release 路径重复。 +func releaseCompositePoolSelection(selection *service.AccountSelectionResult) { + if selection != nil && selection.ReleaseFunc != nil { + selection.ReleaseFunc() + selection.ReleaseFunc = nil + } +} + +// applyCompositePoolReasoningEffortPolicyForSelectedAccount 在账号选定后为 +// composite 账号池请求补齐组 reasoning-effort 策略(CC/Responses 直转路径: +// 服务侧 forward 不再应用组策略)。池请求准入期没有单一目标平台,无法预判 +// 策略族;选中 openai 账号时与 single-openai 同语义应用组上限/映射,选中 +// grok/CN/OpenCode Go 时维持这些平台独立分组「不套用」的既有语义。单目标 +// 请求已在准入期应用,这里跳过。err 非 nil 表示 deny/over-limit,调用方须以 +// respondOpenAIReasoningEffortPolicyError 终止请求。 +func applyCompositePoolReasoningEffortPolicyForSelectedAccount(c *gin.Context, apiKey *service.APIKey, account *service.Account, body []byte) ([]byte, bool, error) { + if c == nil || c.Request == nil || apiKey == nil || apiKey.Group == nil || apiKey.Group.Platform != service.PlatformComposite || account == nil { + return body, false, nil + } + if _, resolved := service.ResolvedTargetPlatformFromContext(c.Request.Context()); resolved { + return body, false, nil + } + if _, isPool := compositeAccountPoolCandidates(c); !isPool { + return body, false, nil + } + if account.Platform != service.PlatformOpenAI { + return body, false, nil + } + return service.ApplyOpenAIReasoningEffortPolicy(body, apiKey.Group.MaxReasoningEffort, apiKey.Group.ReasoningEffortMappings, apiKey.Group.MaxReasoningEffortOverLimit) +} diff --git a/backend/internal/handler/composite_platform_pool_test.go b/backend/internal/handler/composite_platform_pool_test.go new file mode 100644 index 0000000000..a4983272ce --- /dev/null +++ b/backend/internal/handler/composite_platform_pool_test.go @@ -0,0 +1,205 @@ +package handler + +import ( + "net/http/httptest" + "testing" + + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +func newCompositePoolTestContext(t *testing.T, path string, platforms ...string) (*gin.Context, *service.APIKey) { + t.Helper() + gin.SetMode(gin.TestMode) + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + c.Request = httptest.NewRequest("POST", path, nil) + if len(platforms) > 0 { + c.Request = c.Request.WithContext(service.WithCompositeCandidatePlatforms(c.Request.Context(), platforms)) + } + apiKey := &service.APIKey{Group: &service.Group{Platform: service.PlatformComposite}} + return c, apiKey +} + +// 账号池请求不得在 handler 侧再做单平台 detector 解析:池保持未折叠, +// ResolvedTargetPlatform 不被写入,候选集合原样保留。 +func TestEnsureCompositeTargetPlatformKeepsPoolUnfolded(t *testing.T) { + c, apiKey := newCompositePoolTestContext(t, "/v1/chat/completions", + service.PlatformDeepseek, service.PlatformZhipu) + + ensureCompositeTargetPlatform(c, apiKey, "deepseek-chat") + + _, resolved := service.ResolvedTargetPlatformFromContext(c.Request.Context()) + require.False(t, resolved, "pool request must not gain a single resolved platform from the detector") + candidates := service.CompositeCandidatePlatformsFromContext(c.Request.Context()) + require.Equal(t, []string{service.PlatformDeepseek, service.PlatformZhipu}, candidates) +} + +// 兼容族文本端点准入:全部候选属于 7 类兼容族的池放行,任一候选越界拒绝; +// 池不被折叠成单一平台后单独判断。 +func TestOpenAICompatibleTextTargetAllowedPoolSemantics(t *testing.T) { + family := []string{ + service.PlatformOpenAI, service.PlatformGrok, + service.PlatformKimi, service.PlatformZhipu, service.PlatformDeepseek, + service.PlatformMiniMax, service.PlatformOpenCodeGo, + } + + // 全族整体(7 候选)与任意真子集(此处抽 3 个代表)都放行。 + for _, subset := range [][]string{family, {service.PlatformDeepseek, service.PlatformOpenCodeGo}, {service.PlatformGrok}, {service.PlatformMiniMax, service.PlatformZhipu, service.PlatformKimi}} { + c, apiKey := newCompositePoolTestContext(t, "/v1/messages", subset...) + require.Truef(t, openAICompatibleTextTargetAllowed(c, apiKey, "deepseek-flash"), "subset=%v", subset) + } + + for _, subset := range [][]string{ + {service.PlatformAnthropic, service.PlatformDeepseek}, + {service.PlatformOpenAI, service.PlatformGemini}, + {service.PlatformAntigravity}, + } { + c, apiKey := newCompositePoolTestContext(t, "/v1/messages", subset...) + require.Falsef(t, openAICompatibleTextTargetAllowed(c, apiKey, "deepseek-flash"), "subset=%v", subset) + } +} + +// openai-only 端点(live/alpha search/embeddings 既有准入):池收窄为合法 +// single(仅 {openai})才放行,更宽的池清晰拒绝。 +func TestCompositeTargetPlatformAllowedPoolNarrowsOpenAIOnlyEndpoints(t *testing.T) { + c, apiKey := newCompositePoolTestContext(t, "/v1/live", service.PlatformOpenAI) + require.True(t, compositeTargetPlatformAllowed(c, apiKey, "gpt-realtime", service.PlatformOpenAI)) + + c, apiKey = newCompositePoolTestContext(t, "/v1/live", service.PlatformOpenAI, service.PlatformGrok) + require.False(t, compositeTargetPlatformAllowed(c, apiKey, "gpt-realtime", service.PlatformOpenAI)) + c, apiKey = newCompositePoolTestContext(t, "/alpha/search", service.PlatformGrok) + require.False(t, compositeTargetPlatformAllowed(c, apiKey, "gpt-5", service.PlatformOpenAI)) +} + +// 池是已解析的完整决策:compositeTargetPlatformResolved 不得因缺少单一 +// ResolvedTargetPlatform 把池请求判为未解析。 +func TestCompositeTargetPlatformResolvedPoolCountsAsResolved(t *testing.T) { + c, apiKey := newCompositePoolTestContext(t, "/v1/messages", + service.PlatformDeepseek, service.PlatformOpenCodeGo) + require.True(t, compositeTargetPlatformResolved(c, apiKey, "deepseek-flash")) + _, resolved := service.ResolvedTargetPlatformFromContext(c.Request.Context()) + require.False(t, resolved) +} + +// messages dispatch 豁免与单目标同语义:候选全部为 grok/CN/OpenCode Go 时 +// 豁免分组开关;混有 openai 候选时仍受开关控制。 +func TestAllowOpenAICompatibleMessagesDispatchPoolExemptions(t *testing.T) { + newKey := func(allow bool) *service.APIKey { + return &service.APIKey{Group: &service.Group{ + Platform: service.PlatformComposite, + AllowMessagesDispatch: allow, + }} + } + + // 全 CN/grok 池:与对应独立分组同语义豁免。 + c, _ := newCompositePoolTestContext(t, "/v1/messages", service.PlatformDeepseek, service.PlatformGrok, service.PlatformKimi) + require.True(t, allowOpenAICompatibleMessagesDispatch(c, newKey(false))) + + // 混有 openai 候选:受分组开关控制。 + c, _ = newCompositePoolTestContext(t, "/v1/messages", service.PlatformOpenAI, service.PlatformDeepseek) + require.False(t, allowOpenAICompatibleMessagesDispatch(c, newKey(false))) + require.True(t, allowOpenAICompatibleMessagesDispatch(c, newKey(true))) + + // 纯 openai 池:受分组开关控制。 + c, _ = newCompositePoolTestContext(t, "/v1/messages", service.PlatformOpenAI) + require.False(t, allowOpenAICompatibleMessagesDispatch(c, newKey(false))) + + // 非 composite 分组不读池上下文。 + c, _ = newCompositePoolTestContext(t, "/v1/messages", service.PlatformDeepseek) + anthropicKey := &service.APIKey{Group: &service.Group{Platform: service.PlatformAnthropic}} + require.False(t, allowOpenAICompatibleMessagesDispatch(c, anthropicKey)) +} + +// effectiveAPIKeyPlatform 在池请求上保持组平台回退语义(不猜单平台)。 +func TestEffectiveAPIKeyPlatformWithPoolKeepsGroupFallback(t *testing.T) { + c, apiKey := newCompositePoolTestContext(t, "/v1/messages", service.PlatformDeepseek, service.PlatformKimi) + require.Equal(t, service.PlatformComposite, effectiveAPIKeyPlatform(c, apiKey)) +} + +// 池请求的组 effort 策略在账号选定后补齐:选中 openai 账号 → 与 +// single-openai 同语义应用组上限;选中 grok/CN 账号 → 维持不套用语义; +// 单目标请求不重复应用。 +func TestApplyCompositePoolReasoningEffortPolicyForSelectedAccount(t *testing.T) { + overCeiling := []byte(`{"model":"gpt-5.6","reasoning":{"effort":"xhigh"}}`) + + // 池 + openai 账号:超限 effort 被压到组上限。 + c, apiKey := newCompositePoolTestContext(t, "/v1/responses", service.PlatformOpenAI, service.PlatformDeepseek) + apiKey.Group.MaxReasoningEffort = "medium" + capped, changed, err := applyCompositePoolReasoningEffortPolicyForSelectedAccount( + c, apiKey, &service.Account{Platform: service.PlatformOpenAI}, overCeiling) + require.NoError(t, err) + require.True(t, changed) + require.Contains(t, string(capped), `"effort":"medium"`) + + // 池 + grok 账号:维持 grok 独立分组不套用语义。 + c, apiKey = newCompositePoolTestContext(t, "/v1/responses", service.PlatformOpenAI, service.PlatformDeepseek) + _, changed, err = applyCompositePoolReasoningEffortPolicyForSelectedAccount( + c, apiKey, &service.Account{Platform: service.PlatformGrok}, overCeiling) + require.NoError(t, err) + require.False(t, changed) + + // 池 + CN 账号:同上。 + c, apiKey = newCompositePoolTestContext(t, "/v1/responses", service.PlatformDeepseek) + _, changed, err = applyCompositePoolReasoningEffortPolicyForSelectedAccount( + c, apiKey, &service.Account{Platform: service.PlatformDeepseek}, overCeiling) + require.NoError(t, err) + require.False(t, changed) + + // 单目标请求已在准入期应用,选后不重复。 + c, apiKey = newCompositePoolTestContext(t, "/v1/responses") + c.Request = c.Request.WithContext(service.WithResolvedTargetPlatform(c.Request.Context(), service.PlatformOpenAI)) + _, changed, err = applyCompositePoolReasoningEffortPolicyForSelectedAccount( + c, apiKey, &service.Account{Platform: service.PlatformOpenAI}, overCeiling) + require.NoError(t, err) + require.False(t, changed) + + // 非 composite 分组不适用。 + plainKey := &service.APIKey{Group: &service.Group{Platform: service.PlatformOpenAI, MaxReasoningEffort: "medium"}} + c2, _ := gin.CreateTestContext(httptest.NewRecorder()) + c2.Request = httptest.NewRequest("POST", "/v1/responses", nil) + _, changed, err = applyCompositePoolReasoningEffortPolicyForSelectedAccount( + c2, plainKey, &service.Account{Platform: service.PlatformOpenAI}, overCeiling) + require.NoError(t, err) + require.False(t, changed) +} + +// 池请求在 messages 桥准入期绑定组策略 ctx:服务侧 ForwardAsAnthropic 按选中 +// 账号是否 openai 决定是否应用;显式 effort 缺省时不绑定(保桥默认值语义)。 +func TestBindOpenAIReasoningEffortPolicyForMessagesRequestPool(t *testing.T) { + explicit := []byte(`{"model":"deepseek-flash","output_config":{"effort":"xhigh"}}`) + defaulted := []byte(`{"model":"deepseek-flash"}`) + + // 池 + 显式 effort:绑定组策略。 + c, apiKey := newCompositePoolTestContext(t, "/v1/messages", service.PlatformDeepseek, service.PlatformOpenCodeGo) + apiKey.Group.MaxReasoningEffort = "medium" + bindOpenAIReasoningEffortPolicyForMessagesRequest(c, apiKey, explicit) + capped, changed, err := service.ApplyOpenAIReasoningEffortPolicyFromContext(c.Request.Context(), explicit) + require.NoError(t, err) + require.True(t, changed, "pool messages bind must carry the group policy for the bridge to apply") + require.Contains(t, string(capped), `"effort":"medium"`, "xhigh must be clamped to the group ceiling") + + // 池 + 无显式 effort:不绑定(桥默认 effort 不受上限改写)。 + c, apiKey = newCompositePoolTestContext(t, "/v1/messages", service.PlatformDeepseek, service.PlatformOpenCodeGo) + bindOpenAIReasoningEffortPolicyForMessagesRequest(c, apiKey, defaulted) + _, changed, err = service.ApplyOpenAIReasoningEffortPolicyFromContext(c.Request.Context(), defaulted) + require.NoError(t, err) + require.False(t, changed) +} + +// pool 判定与 service 一致:已有 resolved endpoint pin(Gemini fallback)时按 +// single 语义——候选数据保留但不作为活跃池;allowed/dispatch 以 pin 优先。 +func TestCompositePoolDetectionDefersToResolvedPin(t *testing.T) { + c, apiKey := newCompositePoolTestContext(t, "/v1beta/models/gemini-2.5-pro:generateContent", + service.PlatformGemini, service.PlatformDeepseek) + c.Request = c.Request.WithContext(service.WithResolvedTargetPlatform(c.Request.Context(), service.PlatformGemini)) + + // pin 存在时不按活跃池判定:gemini pin 被允许集完整包含。 + require.True(t, compositeTargetPlatformAllowed(c, apiKey, "gemini-2.5-pro", service.PlatformGemini)) + require.True(t, compositeTargetPlatformResolved(c, apiKey, "gemini-2.5-pro")) + _, isPool := compositeAccountPoolCandidates(c) + require.False(t, isPool, "resolved pin must deactivate the pool for admission semantics") + + // pin 存在时按 pin 作为生效平台(single 语义)。 + require.Equal(t, service.PlatformGemini, effectiveAPIKeyPlatform(c, apiKey)) +} diff --git a/backend/internal/handler/composite_pool_attempt_policy.go b/backend/internal/handler/composite_pool_attempt_policy.go new file mode 100644 index 0000000000..c75e860856 --- /dev/null +++ b/backend/internal/handler/composite_pool_attempt_policy.go @@ -0,0 +1,219 @@ +package handler + +import ( + "context" + "net/http" + "strconv" + + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/gin-gonic/gin" +) + +// composite 账号池 per-attempt 平台策略(审查修复增量4)。 +// +// 设计C契约:7 兼容族池请求进入原 OpenAIGatewayHandler/selector;池请求的公开 +// request context / 公开 body 保持 immutable(不把选中平台写回 c.Request)。账号 +// 选定后,本文件为该 attempt 构造局部 ctx(WithResolvedTargetPlatform,仅作用于 +// 该次渠道/计费/forward),并对实际平台补做 user×platform 配额预检与渠道限制检 +// 查——准入 CheckBillingEligibility 时池没有 resolved 平台,这两个维度都被跳过, +// 不得只后扣不预检。 +// +// 业务限制的平台级 deny 通过 compositePoolPlatformDenials 记录,再选时以「filtered +// candidate ctx」传 selector 做整平台 mask(不把兄弟账号逐个试穿 maxAccountSwitches, +// 不写 selector 的原 ctx)。所有候选被业务限制时按原 billingErrorDetails / 渠道 +// 限制错误语义明确终止,不误报 model unsupported。本文件全部为纯读检查,不写任何 +// 生产持久状态、不新增 RPM 计数。 + +// compositePoolAttemptPolicyApplies 报告当前请求是否按 composite 账号池做 +// per-attempt 平台策略检查:composite 分组 + ctx 携带候选池 + 无 resolved 单目标。 +// 显式 pin / single / 普通分组保持旧行为,不做 per-attempt 补检。 +func compositePoolAttemptPolicyApplies(c *gin.Context, apiKey *service.APIKey) bool { + if c == nil || c.Request == nil || apiKey == nil || apiKey.Group == nil || apiKey.Group.Platform != service.PlatformComposite { + return false + } + if _, resolved := service.ResolvedTargetPlatformFromContext(c.Request.Context()); resolved { + return false + } + _, isPool := compositeAccountPoolCandidates(c) + return isPool +} + +// compositePoolAttemptContext 为选中账号派生 attempt 局部 ctx:在原请求 ctx 之上 +// 携带 ResolvedTargetPlatform=account.Platform,仅供该 attempt 的渠道作用域、配额 +// 预检、forward 与计费使用。base(c.Request.Context())不被修改;下一次 selector +// 仍看原候选池。已带 resolved 目标的 ctx 原样返回(单目标请求不走池语义)。 +func compositePoolAttemptContext(base context.Context, account *service.Account) context.Context { + if base == nil || account == nil || account.Platform == "" { + return base + } + if _, resolved := service.ResolvedTargetPlatformFromContext(base); resolved { + return base + } + return service.WithResolvedTargetPlatform(base, account.Platform) +} + +// compositePoolPlatformDenials 记录一次请求内被业务限制(配额/渠道限制)的平台, +// 供 failover 再选时做整平台 mask。每个请求一个实例,仅在 handler 的顺序 failover +// 循环里读写,无并发访问。 +type compositePoolPlatformDenials struct { + denied map[string]struct{} +} + +func newCompositePoolPlatformDenials() *compositePoolPlatformDenials { + return &compositePoolPlatformDenials{denied: make(map[string]struct{})} +} + +func (d *compositePoolPlatformDenials) deny(platform string) { + if d == nil || platform == "" { + return + } + if d.denied == nil { + d.denied = make(map[string]struct{}) + } + d.denied[platform] = struct{}{} +} + +// filterCandidates 返回剔除被 deny 平台后的候选副本;入参不被修改。 +func (d *compositePoolPlatformDenials) filterCandidates(candidates []string) []string { + if d == nil || len(d.denied) == 0 { + return append([]string(nil), candidates...) + } + remaining := make([]string, 0, len(candidates)) + for _, platform := range candidates { + if _, blocked := d.denied[platform]; blocked { + continue + } + remaining = append(remaining, platform) + } + return remaining +} + +// list 返回已 deny 平台的排序副本(写入 ctx 前归一化由 service 侧完成)。 +func (d *compositePoolPlatformDenials) list() []string { + if d == nil { + return nil + } + platforms := make([]string, 0, len(d.denied)) + for platform := range d.denied { + platforms = append(platforms, platform) + } + return platforms +} + +// compositePoolSelectionRetryContext 返回下一次选号使用的 ctx:候选池保持 +// immutable(原样保留,不收缩),只叠加请求局部的 deniedPlatforms 列表—— +// selector 在 list/sticky 门按该列表过滤,sticky 账号因 denied 暂时排除时按 +// excluded 语义提前返回、不清粘性绑定(改由后续成功请求的正常 Set 改绑)。 +// 返回 false 表示候选已全部被业务限制,调用方应终止请求而非再选号。未 deny +// 任何平台时原样返回 base。 +func compositePoolSelectionRetryContext(base context.Context, denials *compositePoolPlatformDenials) (context.Context, bool) { + if base == nil { + return nil, false + } + candidates := service.CompositeCandidatePlatformsFromContext(base) + if len(candidates) == 0 { + return base, true + } + if denials == nil || len(denials.denied) == 0 { + return base, true + } + // 候选已全部被业务限制:终止而不是再选号。 + if len(denials.filterCandidates(candidates)) == 0 { + return nil, false + } + return service.WithCompositePoolDeniedPlatforms(base, denials.list()), true +} + +// compositePoolAttemptPolicyFailure 描述选中账号未通过 per-attempt 平台策略的 +// 原因。两者互斥评估,但结构上可同时存在(先 quota 后渠道都拒绝时以 quota 为准)。 +type compositePoolAttemptPolicyFailure struct { + // QuotaErr 非 nil 表示 user×platform 日/周/月配额耗尽 + //(ErrUserPlatform{Daily,Weekly,Monthly}QuotaExhausted,带 window_resets_at + // metadata),按 billingErrorDetails 语义终止。 + QuotaErr error + // ChannelRestricted 表示该模型在选中平台作用域下被渠道定价限制拒绝,按调度 + // 阶段渠道限制同语义终止(账号存在且模型受支持,仅当前平台被限制)。 + ChannelRestricted bool +} + +func (f compositePoolAttemptPolicyFailure) denied() bool { + return f.QuotaErr != nil || f.ChannelRestricted +} + +// compositePoolAttemptPolicy 汇总一次 attempt 的策略检查结果。 +type compositePoolAttemptPolicy struct { + // AttemptCtx 仅供该 attempt 的渠道/计费/forward 使用;不写回 c.Request。 + AttemptCtx context.Context + // Mapping 是选中平台作用域的渠道映射;公开 body immutable,channel-mapped + // body 由调用方从 canonical body 派生。 + Mapping service.ChannelMappingResult + // Failure 非 denied 时才允许 forward。 + Failure compositePoolAttemptPolicyFailure +} + +// evaluateCompositePoolAttemptPolicy 对选中账号做 attempt 级平台策略检查: +// 1. user×platform 配额预检(纯检查 + cache 回填,不写 RPM、不扣费、不再调用 +// CheckBillingEligibility——那会二次计数); +// 2. 平台作用域渠道限制(requested/channel_mapped/response 计费基准 + upstream +// 基准的逐账号检查,与调度阶段同语义、仅作用域为选中平台)。 +// +// requireCompact 须与本次选号调用一致(/responses/compact 路径为 true)。 +func evaluateCompositePoolAttemptPolicy( + baseCtx context.Context, + billing *service.BillingCacheService, + gateway *service.OpenAIGatewayService, + apiKey *service.APIKey, + subscription *service.UserSubscription, + account *service.Account, + requestedModel string, + requireCompact bool, +) compositePoolAttemptPolicy { + result := compositePoolAttemptPolicy{AttemptCtx: baseCtx} + if baseCtx == nil || account == nil || account.Platform == "" { + return result + } + result.AttemptCtx = compositePoolAttemptContext(baseCtx, account) + result.Failure.QuotaErr = compositePoolAttemptQuotaError(billing, result.AttemptCtx, apiKey, subscription, account.Platform) + if result.Failure.QuotaErr != nil { + // 平台配额已耗尽:渠道映射仍按平台作用域解析,但请求不再外发。 + if gateway != nil && apiKey != nil && apiKey.GroupID != nil { + result.Mapping = gateway.CompositePoolAttemptChannelMapping(result.AttemptCtx, apiKey.GroupID, requestedModel) + } + return result + } + if gateway != nil && apiKey != nil && apiKey.GroupID != nil { + result.Mapping = gateway.CompositePoolAttemptChannelMapping(result.AttemptCtx, apiKey.GroupID, requestedModel) + result.Failure.ChannelRestricted = gateway.CompositePoolAttemptChannelRestricted(result.AttemptCtx, apiKey.GroupID, account, requestedModel, requireCompact) + } + return result +} + +// compositePoolAttemptQuotaError 是 service 纯配额预检的 handler 侧薄入口。 +func compositePoolAttemptQuotaError(billing *service.BillingCacheService, attemptCtx context.Context, apiKey *service.APIKey, subscription *service.UserSubscription, platform string) error { + if billing == nil || apiKey == nil || platform == "" { + return nil + } + return billing.CheckUserPlatformQuotaEligibilityForRequest(attemptCtx, apiKey.User, apiKey.Group, subscription, platform) +} + +// respondCompositePoolAttemptPolicyFailure 按 deny 原因以既有错误语义明确终止请求: +// - 配额耗尽 → billingErrorDetails(429 rate_limit_exceeded + Retry-After); +// - 渠道限制 → 503 api_error(与调度阶段渠道限制的分类一致;账号与模型持久 +// 配置都存在,不误报 model_not_found / model unsupported)。 +// +// write 由调用方按入站端点选择(OpenAI 信封 handleStreamingAwareError / Anthropic +// 信封 anthropicStreamingAwareError),并自行闭包 streamStarted。 +func respondCompositePoolAttemptPolicyFailure(c *gin.Context, failure compositePoolAttemptPolicyFailure, write func(*gin.Context, int, string, string)) { + if write == nil || !failure.denied() { + return + } + if failure.QuotaErr != nil { + status, code, message, retryAfter := billingErrorDetails(failure.QuotaErr) + if retryAfter > 0 { + c.Header("Retry-After", strconv.Itoa(retryAfter)) + } + write(c, status, code, message) + return + } + write(c, http.StatusServiceUnavailable, "api_error", "Service temporarily unavailable") +} diff --git a/backend/internal/handler/composite_pool_attempt_policy_test.go b/backend/internal/handler/composite_pool_attempt_policy_test.go new file mode 100644 index 0000000000..85c0036f34 --- /dev/null +++ b/backend/internal/handler/composite_pool_attempt_policy_test.go @@ -0,0 +1,322 @@ +package handler + +// composite 账号池 per-attempt 平台策略(handler 侧辅助文件)的单元测试: +// attempt 局部 ctx 纯度、被拒平台的整平台 mask 与重选 ctx、配额/渠道限制的终止 +// 错误语义。池完整链路(选号→策略→forward→计费)的行为测试在 +// internal/server/routes/gateway_composite_pool_attempt_policy_test.go(待 2B +// handler 文件移交接线后补齐)。 + +import ( + "context" + "net/http" + "net/http/httptest" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +// ── fakes:只覆盖测试涉及的缓存/仓储入口,其余方法内嵌接口零值 ──────────────── + +type poolAttemptFakeQuotaCache struct { + service.BillingCache + entry *service.UserPlatformQuotaCacheEntry +} + +func (f *poolAttemptFakeQuotaCache) GetUserPlatformQuotaCache(context.Context, int64, string) (*service.UserPlatformQuotaCacheEntry, bool, error) { + if f.entry == nil { + return nil, false, nil + } + return f.entry, true, nil +} + +func (f *poolAttemptFakeQuotaCache) SetUserPlatformQuotaCache(context.Context, int64, string, *service.UserPlatformQuotaCacheEntry, time.Duration) error { + return nil +} + +type poolAttemptFakeQuotaRepo struct { + service.UserPlatformQuotaRepository + rec *service.UserPlatformQuotaRecord +} + +func (f *poolAttemptFakeQuotaRepo) GetByUserPlatform(context.Context, int64, string) (*service.UserPlatformQuotaRecord, error) { + return f.rec, nil +} + +type poolAttemptFakeChannelRepo struct { + service.ChannelRepository + channels []service.Channel + platforms map[int64]string + listAllCnt int +} + +func (f *poolAttemptFakeChannelRepo) ListAll(context.Context) ([]service.Channel, error) { + f.listAllCnt++ + return f.channels, nil +} + +func (f *poolAttemptFakeChannelRepo) GetGroupPlatforms(context.Context, []int64) (map[int64]string, error) { + return f.platforms, nil +} + +func newPoolAttemptBilling(t *testing.T, entry *service.UserPlatformQuotaCacheEntry) *service.BillingCacheService { + t.Helper() + cfg := &config.Config{RunMode: config.RunModeStandard} + cfg.Billing.UserPlatformQuotaCacheTTLSeconds = 60 + return service.NewBillingCacheService( + &poolAttemptFakeQuotaCache{entry: entry}, nil, nil, nil, nil, nil, cfg, + &poolAttemptFakeQuotaRepo{}) +} + +// ── compositePoolAttemptContext ────────────────────────────────────────────── + +func TestCompositePoolAttemptContextIsolatesPlatform(t *testing.T) { + base := service.WithCompositeCandidatePlatforms(context.Background(), []string{"deepseek", "openai"}) + + attemptCtx := compositePoolAttemptContext(base, &service.Account{Platform: "deepseek"}) + + // attempt ctx 携带选中平台,base 候选池保持 immutable 且不携带 resolved。 + platform, ok := service.ResolvedTargetPlatformFromContext(attemptCtx) + require.True(t, ok) + require.Equal(t, "deepseek", platform) + require.Equal(t, []string{"deepseek", "openai"}, service.CompositeCandidatePlatformsFromContext(attemptCtx)) + + _, resolved := service.ResolvedTargetPlatformFromContext(base) + require.False(t, resolved, "original request ctx must stay pool-shaped (no resolved target)") + require.Equal(t, []string{"deepseek", "openai"}, service.CompositeCandidatePlatformsFromContext(base)) +} + +func TestCompositePoolAttemptContextGuards(t *testing.T) { + var nilCtx context.Context + require.Nil(t, compositePoolAttemptContext(nilCtx, &service.Account{Platform: "openai"})) + + base := context.Background() + require.Equal(t, base, compositePoolAttemptContext(base, nil)) + require.Equal(t, base, compositePoolAttemptContext(base, &service.Account{Platform: ""})) + + alreadyResolved := service.WithResolvedTargetPlatform(base, "grok") + require.Equal(t, alreadyResolved, compositePoolAttemptContext(alreadyResolved, &service.Account{Platform: "openai"}), + "resolved single-target requests must not be overridden by pool attempt semantics") +} + +// ── compositePoolPlatformDenials / compositePoolSelectionRetryContext ──────── + +func TestCompositePoolPlatformDenialsMaskWholePlatform(t *testing.T) { + denials := newCompositePoolPlatformDenials() + denials.deny("openai") + denials.deny("openai") // 幂等 + + remaining := denials.filterCandidates([]string{"deepseek", "grok", "openai"}) + require.Equal(t, []string{"deepseek", "grok"}, remaining) + require.Len(t, denials.filterCandidates([]string{"deepseek", "openai"}), 1) +} + +func TestCompositePoolSelectionRetryContextMasksCandidates(t *testing.T) { + base := service.WithCompositeCandidatePlatforms(context.Background(), []string{"deepseek", "openai"}) + denials := newCompositePoolPlatformDenials() + + // 无 deny:原样返回 base(候选池不变)。 + retryCtx, ok := compositePoolSelectionRetryContext(base, denials) + require.True(t, ok) + require.Equal(t, base, retryCtx) + + denials.deny("openai") + retryCtx, ok = compositePoolSelectionRetryContext(base, denials) + require.True(t, ok) + // 候选池保持 immutable(不收缩),仅叠加请求局部 deniedPlatforms 列表。 + require.Equal(t, []string{"deepseek", "openai"}, service.CompositeCandidatePlatformsFromContext(retryCtx)) + require.Equal(t, []string{"openai"}, service.CompositePoolDeniedPlatformsFromContext(retryCtx)) + require.Equal(t, []string{"deepseek", "openai"}, service.CompositeCandidatePlatformsFromContext(base), + "original request ctx candidates must stay immutable") + require.Nil(t, service.CompositePoolDeniedPlatformsFromContext(base), + "base request ctx must not carry the denied overlay") + _, resolved := service.ResolvedTargetPlatformFromContext(retryCtx) + require.False(t, resolved, "retry ctx must not collapse into the last attempted account's platform") + + denials.deny("deepseek") + _, ok = compositePoolSelectionRetryContext(base, denials) + require.False(t, ok, "all candidates business-limited → terminate instead of re-selecting") +} + +// ── respondCompositePoolAttemptPolicyFailure ───────────────────────────────── + +func TestRespondCompositePoolAttemptPolicyFailure_QuotaMapsToBillingErrorDetails(t *testing.T) { + var gotStatus int + var gotCode string + write := func(c *gin.Context, status int, code, message string) { + gotStatus = status + gotCode = code + } + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/chat/completions", nil) + + respondCompositePoolAttemptPolicyFailure(c, compositePoolAttemptPolicyFailure{ + QuotaErr: service.ErrUserPlatformDailyQuotaExhausted, + }, write) + + require.Equal(t, http.StatusTooManyRequests, gotStatus) + require.Equal(t, "rate_limit_exceeded", gotCode) + require.NotEmpty(t, c.Writer.Header().Get("Retry-After"), "quota denial must keep the Retry-After semantics of billingErrorDetails") +} + +func TestRespondCompositePoolAttemptPolicyFailure_ChannelRestrictionStays503(t *testing.T) { + var gotStatus int + var gotErrType string + write := func(c *gin.Context, status int, code, message string) { + gotStatus = status + gotErrType = code + } + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/chat/completions", nil) + + respondCompositePoolAttemptPolicyFailure(c, compositePoolAttemptPolicyFailure{ChannelRestricted: true}, write) + + require.Equal(t, http.StatusServiceUnavailable, gotStatus, + "channel restriction must keep the selection-stage channel-restriction classification") + require.Equal(t, "api_error", gotErrType) + require.Empty(t, c.Writer.Header().Get("Retry-After")) +} + +func TestRespondCompositePoolAttemptPolicyFailure_NotDeniedDoesNotWrite(t *testing.T) { + called := false + write := func(c *gin.Context, status int, code, message string) { called = true } + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/chat/completions", nil) + + respondCompositePoolAttemptPolicyFailure(c, compositePoolAttemptPolicyFailure{}, write) + require.False(t, called) +} + +// ── compositePoolAttemptPolicyApplies ──────────────────────────────────────── + +func poolAttemptGinContext(base context.Context) *gin.Context { + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/chat/completions", nil).WithContext(base) + return c +} + +func TestCompositePoolAttemptPolicyAppliesOnlyToActivePools(t *testing.T) { + compositeKey := &service.APIKey{Group: &service.Group{ID: 1, Platform: service.PlatformComposite}} + + pool := poolAttemptGinContext(service.WithCompositeCandidatePlatforms(context.Background(), []string{"openai"})) + require.True(t, compositePoolAttemptPolicyApplies(pool, compositeKey)) + + // 显式 resolved 单目标(pin/detector)与普通分组保持旧行为。 + resolved := poolAttemptGinContext(service.WithCompositeCandidatePlatforms( + service.WithResolvedTargetPlatform(context.Background(), "openai"), []string{"openai"})) + require.False(t, compositePoolAttemptPolicyApplies(resolved, compositeKey)) + + plain := poolAttemptGinContext(context.Background()) + require.False(t, compositePoolAttemptPolicyApplies(plain, compositeKey)) + + openAIKey := &service.APIKey{Group: &service.Group{ID: 2, Platform: service.PlatformOpenAI}} + require.False(t, compositePoolAttemptPolicyApplies(pool, openAIKey)) +} + +// ── evaluateCompositePoolAttemptPolicy ─────────────────────────────────────── + +func TestEvaluateCompositePoolAttemptPolicy_QuotaDeniedBlocksBeforeForward(t *testing.T) { + zero := 0.0 + now := time.Now().UTC() + billing := newPoolAttemptBilling(t, &service.UserPlatformQuotaCacheEntry{ + DailyUsageUSD: 0, + DailyLimitUSD: &zero, + DailyWindowStart: &now, + SchemaVersion: service.UserPlatformQuotaCacheSchemaV1, + }) + base := service.WithCompositeCandidatePlatforms(context.Background(), []string{"openai", "deepseek"}) + apiKey := &service.APIKey{GroupID: &[]int64{1}[0], Group: &service.Group{ID: 1, Platform: service.PlatformComposite}, User: &service.User{ID: 42}} + + attempt := evaluateCompositePoolAttemptPolicy( + base, billing, nil, apiKey, nil, &service.Account{Platform: "openai"}, "gpt-4", false) + + require.ErrorIs(t, attempt.Failure.QuotaErr, service.ErrUserPlatformDailyQuotaExhausted) + require.True(t, attempt.Failure.denied()) + _, resolved := service.ResolvedTargetPlatformFromContext(attempt.AttemptCtx) + require.True(t, resolved) + _, baseResolved := service.ResolvedTargetPlatformFromContext(base) + require.False(t, baseResolved, "base request ctx must stay untouched") +} + +func TestEvaluateCompositePoolAttemptPolicy_ChannelRestrictionDeniesSelectedPlatform(t *testing.T) { + now := time.Now().UTC() + billing := newPoolAttemptBilling(t, &service.UserPlatformQuotaCacheEntry{ + DailyWindowStart: &now, + SchemaVersion: service.UserPlatformQuotaCacheSchemaV1, // limits 全 nil → 配额放行 + }) + channelSvc := service.NewChannelService(&poolAttemptFakeChannelRepo{ + channels: []service.Channel{{ + ID: 1, + Status: service.StatusActive, + GroupIDs: []int64{4311}, + RestrictModels: true, + BillingModelSource: service.BillingModelSourceRequested, + ModelPricing: []service.ChannelModelPricing{ + {Platform: service.PlatformOpenAI, Models: []string{"gpt-*"}}, + }, + }}, + platforms: map[int64]string{4311: service.PlatformComposite}, + }, nil, nil, nil, nil) + gateway := service.NewOpenAIGatewayService( + nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, + nil, nil, nil, nil, nil, channelSvc, nil, nil, nil, + ) + groupID := int64(4311) + apiKey := &service.APIKey{GroupID: &groupID, Group: &service.Group{ID: groupID, Platform: service.PlatformComposite}} + base := service.WithCompositeCandidatePlatforms(context.Background(), []string{"openai", "deepseek"}) + + // openai 账号 + openai 作用域内的模型 → 放行且映射直通。 + allowed := evaluateCompositePoolAttemptPolicy( + base, billing, gateway, apiKey, nil, &service.Account{Platform: service.PlatformOpenAI}, "gpt-4", false) + require.False(t, allowed.Failure.denied()) + + // deepseek 账号:gpt-4 不在 deepseek 作用域定价内 → 渠道限制拒绝该平台, + // 且不能把 openai 行跨平台扫进来误放行。 + denied := evaluateCompositePoolAttemptPolicy( + base, billing, gateway, apiKey, nil, &service.Account{Platform: service.PlatformDeepseek}, "gpt-4", false) + require.NoError(t, denied.Failure.QuotaErr) + require.True(t, denied.Failure.ChannelRestricted) + require.False(t, denied.Mapping.Mapped, + "channel mapping must be scoped to the selected platform, not resolved across pool platforms") +} + +// TestCompositePoolAttemptChannelPolicyIsPureAndLazy 复核渠道策略 helper 的纯度: +// 只做纯读 + lazy cache 加载——重复评估结论稳定;cache 只在首次查询时从仓储构建 +// 一次,后续评估走进程内快照,不产生仓储重复读、不写任何状态(无计数、无扣费 +// 入口可触达)。 +func TestCompositePoolAttemptChannelPolicyIsPureAndLazy(t *testing.T) { + repo := &poolAttemptFakeChannelRepo{ + channels: []service.Channel{{ + ID: 1, + Status: service.StatusActive, + GroupIDs: []int64{4312}, + RestrictModels: true, + BillingModelSource: service.BillingModelSourceRequested, + ModelPricing: []service.ChannelModelPricing{ + {Platform: service.PlatformOpenAI, Models: []string{"gpt-*"}}, + }, + }}, + platforms: map[int64]string{4312: service.PlatformComposite}, + } + channelSvc := service.NewChannelService(repo, nil, nil, nil, nil) + gateway := service.NewOpenAIGatewayService( + nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, + nil, nil, nil, nil, nil, channelSvc, nil, nil, nil, + ) + groupID := int64(4312) + attemptCtx := service.WithResolvedTargetPlatform(context.Background(), service.PlatformDeepseek) + account := &service.Account{Platform: service.PlatformDeepseek} + + first := gateway.CompositePoolAttemptChannelRestricted(attemptCtx, &groupID, account, "gpt-4", false) + second := gateway.CompositePoolAttemptChannelRestricted(attemptCtx, &groupID, account, "gpt-4", false) + mapping := gateway.CompositePoolAttemptChannelMapping(attemptCtx, &groupID, "gpt-4") + + require.True(t, first) + require.True(t, second, "repeated evaluation must be stable (pure read, no state change)") + require.False(t, mapping.Mapped) + require.LessOrEqual(t, repo.listAllCnt, 1, + "channel cache must be built lazily once; repeat checks must read the in-process snapshot") +} diff --git a/backend/internal/handler/endpoint.go b/backend/internal/handler/endpoint.go index 82d8279e90..4b46a25aaa 100644 --- a/backend/internal/handler/endpoint.go +++ b/backend/internal/handler/endpoint.go @@ -320,11 +320,24 @@ func GetInboundEndpoint(c *gin.Context) string { // GetUpstreamEndpoint derives the upstream endpoint from the context // and the account platform. Handlers call this after scheduling an // account, passing account.Platform. +// +// 优先级:真实出站记录 > 平台运行时端点 > 入站推导兜底。 +// 显式记录的端点(service.SetOpsUpstreamEndpoint,由实际 forwarder 在发送前 +// 写入)优先于任何 group/platform 推导——即使 group 平台是 composite; +// 仅在没有任何实际出站记录时才回退到 DeriveUpstreamEndpoint,且推导值只是 +// 兜底,不代表真实出站。 func GetUpstreamEndpoint(c *gin.Context, platform string) string { + // 实际 forwarder 在发送前写入的端点拥有最高优先级,对所有平台生效 + // (含 composite 组与 api_protocol adaptive 的真实 path)。 + if endpoint := service.GetOpsUpstreamEndpoint(c); endpoint != "" { + return endpoint + } // OpenAI 转发服务维护独立的运行时端点上下文,覆盖普通入站推导。 // 这对 force_chat_completions 的错误路径尤为重要:此时可能没有 // ForwardResult,不能把入站 /v1/responses 误报成上游端点。 - if platform == service.PlatformOpenAI || platform == service.PlatformGrok || service.IsMultiProtocolAPIKeyProvider(platform) { + // composite 组经 OpenAI handler 转发兼容池账号时同样适用:此时 + // group 平台是 composite,若不读取该记录会错误回退到入站推导。 + if platform == service.PlatformOpenAI || platform == service.PlatformGrok || platform == service.PlatformComposite || service.IsMultiProtocolAPIKeyProvider(platform) { if endpoint := service.GetActualOpenAIUpstreamEndpoint(c); endpoint != "" { return endpoint } diff --git a/backend/internal/handler/endpoint_upstream_record_test.go b/backend/internal/handler/endpoint_upstream_record_test.go new file mode 100644 index 0000000000..0942bebc59 --- /dev/null +++ b/backend/internal/handler/endpoint_upstream_record_test.go @@ -0,0 +1,89 @@ +package handler + +import ( + "net/http" + "net/http/httptest" + "testing" + + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +// composite 组 inbound=/v1/chat/completions、实际出站 /v1/messages:显式记录的 +// actual endpoint 必须优先于 group/platform 推导;无记录时 composite 缺 +// DeriveUpstreamEndpoint case,才回退入站(仅兜底,不代表真实出站)。 +func TestGetUpstreamEndpointPrefersActualOutboundRecordOverCompositeFallback(t *testing.T) { + recorder := httptest.NewRecorder() + c, _ := gin.CreateTestContext(recorder) + c.Request = httptest.NewRequest(http.MethodPost, EndpointChatCompletions, nil) + c.Set(ctxKeyInboundEndpoint, EndpointChatCompletions) + + // 无任何实际出站记录:回退入站推导。 + require.Equal(t, EndpointChatCompletions, GetUpstreamEndpoint(c, service.PlatformComposite)) + + // generic forwarder 发送前记录真实出站 /v1/messages 后必须原样返回, + // 且不因传入平台不同而被推导值覆盖。 + service.SetOpsUpstreamEndpoint(c, EndpointMessages) + require.Equal(t, EndpointMessages, GetUpstreamEndpoint(c, service.PlatformComposite)) + require.Equal(t, EndpointMessages, GetUpstreamEndpoint(c, service.PlatformAnthropic)) + require.Equal(t, EndpointMessages, GetUpstreamEndpoint(c, service.PlatformOpenAI)) + + // 实际出站就是 CC 时保持 CC,不得被平台推导改写。 + service.SetOpsUpstreamEndpoint(c, EndpointChatCompletions) + require.Equal(t, EndpointChatCompletions, GetUpstreamEndpoint(c, service.PlatformComposite)) +} + +// composite 组经 OpenAI handler 转发兼容池账号:actualOpenAI 运行时记录对 +// composite 平台同样要生效,不能漏读后回退到入站推导。 +func TestGetUpstreamEndpointCompositeReadsOpenAIRuntimeOverride(t *testing.T) { + recorder := httptest.NewRecorder() + c, _ := gin.CreateTestContext(recorder) + c.Request = httptest.NewRequest(http.MethodPost, EndpointChatCompletions, nil) + c.Set(ctxKeyInboundEndpoint, EndpointChatCompletions) + + service.SetActualOpenAIUpstreamEndpoint(c, EndpointChatCompletions) + require.Equal(t, EndpointChatCompletions, GetUpstreamEndpoint(c, service.PlatformComposite)) + + service.SetActualOpenAIUpstreamEndpoint(c, EndpointResponses) + require.Equal(t, EndpointResponses, GetUpstreamEndpoint(c, service.PlatformComposite)) + + // generic 记录优先级高于 OpenAI 运行时记录(同为最近一次出站尝试时, + // generic 记录来自更底层发送点)。 + service.SetOpsUpstreamEndpoint(c, EndpointMessages) + require.Equal(t, EndpointMessages, GetUpstreamEndpoint(c, service.PlatformComposite)) +} + +// 每次账号重选(含 failover 重试)后,上一账号的尝试级元数据不得残留, +// 否则失败日志会把旧账号的端点/模型安到新账号头上。 +func TestSetOpsSelectedAccountResetsAttemptScopedMetadata(t *testing.T) { + recorder := httptest.NewRecorder() + c, _ := gin.CreateTestContext(recorder) + c.Request = httptest.NewRequest(http.MethodPost, EndpointMessages, nil) + + service.SetOpsUpstreamEndpoint(c, EndpointMessages) + service.SetActualOpenAIUpstreamEndpoint(c, EndpointResponses) + service.SetOpsUpstreamModel(c, "gpt-5.2") + service.SetOpsUpstreamEndpoint(c, "/v1/v1/messages") + + setOpsSelectedAccount(c, 42, service.PlatformAnthropic) + + require.Empty(t, service.GetOpsUpstreamEndpoint(c)) + require.Empty(t, service.GetActualOpenAIUpstreamEndpoint(c)) + require.Empty(t, c.GetString(opsUpstreamModelKey)) + require.Equal(t, int64(42), c.GetInt64(opsAccountIDKey)) +} + +// GetUpstreamEndpoint 旧行为保持:无记录时 anthropic 推导 /v1/messages、 +// antigravity handler 记录优先于推导。 +func TestGetUpstreamEndpointFallbackBehaviorUnchanged(t *testing.T) { + recorder := httptest.NewRecorder() + c, _ := gin.CreateTestContext(recorder) + c.Request = httptest.NewRequest(http.MethodPost, EndpointChatCompletions, nil) + c.Set(ctxKeyInboundEndpoint, EndpointChatCompletions) + + require.Equal(t, EndpointMessages, GetUpstreamEndpoint(c, service.PlatformAnthropic)) + + setActualUpstreamEndpoint(c, EndpointAntigravityGenerateContent) + require.Equal(t, EndpointAntigravityGenerateContent, GetUpstreamEndpoint(c, service.PlatformAntigravity)) +} diff --git a/backend/internal/handler/openai_chat_completions.go b/backend/internal/handler/openai_chat_completions.go index 0a371f12eb..9339b54b1e 100644 --- a/backend/internal/handler/openai_chat_completions.go +++ b/backend/internal/handler/openai_chat_completions.go @@ -116,6 +116,12 @@ func (h *OpenAIGatewayHandler) ChatCompletions(c *gin.Context) { // 解析渠道级模型映射 channelMapping, _ := h.gatewayService.ResolveChannelMappingAndRestrict(c.Request.Context(), apiKey.GroupID, reqModel) + // composite 账号池请求:composite 作用域的渠道查找会跨平台行匹配(无 resolved + // 平台),映射/限制不可靠。canonical body 保持公开模型、选号也用公开模型; + // 平台作用域映射/限制在账号选定后按选中平台解析,非池请求保持原语义。 + if compositePoolAttemptPolicyApplies(c, apiKey) { + channelMapping = service.ChannelMappingResult{MappedModel: reqModel} + } forwardModel := openAIChannelForwardModel(channelMapping, reqModel) if h.errorPassthroughService != nil { @@ -174,13 +180,19 @@ func (h *OpenAIGatewayHandler) ChatCompletions(c *gin.Context) { ccPricingCtx, pricingAt := h.gatewayService.WithOpenAIRequestPricingContext(c.Request.Context(), apiKey.GroupID) c.Request = c.Request.WithContext(ccPricingCtx) + // composite 账号池 per-attempt 平台策略状态:被配额/渠道限制拒绝的平台记入 + // deniedPlatforms,重选时以 filtered candidate ctx 传 selector 做整平台 mask; + // 原请求 ctx 的候选池 immutable,不把选中账号写回。非池请求恒不生效。 + poolDenials := newCompositePoolPlatformDenials() + selectionCtx := c.Request.Context() + for { if failoverClientGone(c) { return } reqLog.Debug("openai_chat_completions.account_selecting", zap.Int("excluded_account_count", len(failedAccountIDs))) selection, scheduleDecision, err := h.gatewayService.SelectAccountWithSchedulerForCapability( - c.Request.Context(), + selectionCtx, apiKey.GroupID, "", sessionHash, @@ -233,6 +245,51 @@ func (h *OpenAIGatewayHandler) ChatCompletions(c *gin.Context) { _ = scheduleDecision setOpsSelectedAccount(c, account.ID, account.Platform) + // composite 账号池请求的组 effort 策略在账号选定后按账号平台补齐; + // 放在槽位获取前,deny/over-limit 可直接终止而不占槽。 + poolPolicyBody := body + if cappedBody, changed, err := applyCompositePoolReasoningEffortPolicyForSelectedAccount(c, apiKey, account, body); err != nil { + releaseCompositePoolSelection(selection) + respondOpenAIReasoningEffortPolicyError(c, err, h.errorResponse) + return + } else if changed { + poolPolicyBody = cappedBody + } + + // composite 账号池 per-attempt 平台策略:对实际选中平台补做 user×platform + // 配额预检与渠道映射/限制(准入 CheckBillingEligibility 时池没有 resolved + // 平台、这两个维度被跳过;不得只后扣不预检)。检查为纯读,不写 RPM/计数, + // 不得以重复调用 CheckBillingEligibility 代替。deny 不占并发槽:无状态 + // 请求记 deniedPlatforms 后按 masked 候选池整平台重选;候选全部被业务 + // 限制时按原语义终止,不误报 model unsupported。(chat 无 prevID 状态, + // 无 pinned 分支。) + attemptPolicy := compositePoolAttemptPolicy{AttemptCtx: c.Request.Context(), Mapping: channelMapping} + isPoolAttempt := false + if compositePoolAttemptPolicyApplies(c, apiKey) { + attemptPolicy = evaluateCompositePoolAttemptPolicy( + c.Request.Context(), h.billingCacheService, h.gatewayService, apiKey, subscription, account, reqModel, false) + isPoolAttempt = true + if attemptPolicy.Failure.denied() { + releaseCompositePoolSelection(selection) + // streaming-aware writer:并发排队心跳可能已开始流,终止时不能拼 JSON。 + streamAwareWrite := func(cc *gin.Context, status int, code, message string) { + h.handleStreamingAwareError(cc, status, code, message, streamStarted) + } + poolDenials.deny(account.Platform) + // 同时排除该账号:下一轮 masked ctx 下 sticky 层对 excluded 账号 + // 提前返回(不 clear),不会把原 sticky 账号当 platform mismatch + // 清掉粘性绑定;其它平台成功后按用户目标正常改绑。 + failedAccountIDs[account.ID] = struct{}{} + retryCtx, ok := compositePoolSelectionRetryContext(c.Request.Context(), poolDenials) + if !ok { + respondCompositePoolAttemptPolicyFailure(c, attemptPolicy.Failure, streamAwareWrite) + return + } + selectionCtx = retryCtx + continue + } + } + accountReleaseFunc, slotResult := h.acquireResponsesAccountSlot(c, apiKey.GroupID, sessionHash, selection, reqStream, &streamStarted, reqLog) if slotResult == openAISlotAcquireProfitVetoed { // 利润终检否决:排除该账号重新选号;否决次数达上限则按无可用账号终止。 @@ -249,9 +306,14 @@ func (h *OpenAIGatewayHandler) ChatCompletions(c *gin.Context) { service.SetOpsLatencyMs(c, service.OpsRoutingLatencyMsKey, time.Since(routingStart).Milliseconds()) forwardStart := time.Now() - forwardBody := body + forwardBody := poolPolicyBody if channelMapping.Mapped { - forwardBody = h.gatewayService.ReplaceModelInBody(body, channelMapping.MappedModel) + forwardBody = h.gatewayService.ReplaceModelInBody(poolPolicyBody, channelMapping.MappedModel) + } + // 池请求按选中平台的渠道映射从 poolPolicyBody 派生本次 attempt 的 body: + // 公开模型 → 选中平台渠道映射 → 账号 model_mapping(forward 服务内应用)。 + if isPoolAttempt { + forwardBody = openAIModelMappedBody(poolPolicyBody, attemptPolicy.Mapping.Mapped, attemptPolicy.Mapping.MappedModel, h.gatewayService.ReplaceModelInBody) } writerSizeBeforeForward := c.Writer.Size() result, err := func() (*service.OpenAIForwardResult, error) { @@ -260,13 +322,19 @@ func (h *OpenAIGatewayHandler) ChatCompletions(c *gin.Context) { accountReleaseFunc() } }() - return h.gatewayService.ForwardAsChatCompletions(c.Request.Context(), c, account, forwardBody, promptCacheKey, "") + // 池请求的 attempt 局部 ctx 携带选中平台:forward 内渠道定价作用域与 + // 计费 QuotaPlatform 跟随实际平台,不写回 c.Request。 + forwardCtx := c.Request.Context() + if isPoolAttempt { + forwardCtx = attemptPolicy.AttemptCtx + } + return h.gatewayService.ForwardAsChatCompletions(forwardCtx, c, account, forwardBody, promptCacheKey, "") }() var cyberBlockBodyChat []byte if service.GetOpsCyberPolicy(c) != nil { cyberBlockBodyChat = body } - h.recordCyberPolicyIfMarked(c, apiKey, account, subscription, reqModel, err != nil, cyberBlockBodyChat, clientRequestedUsageFields(c, channelMapping, reqModel, ""), service.HashUsageRequestPayload(body)) + h.recordCyberPolicyIfMarked(c, apiKey, account, subscription, reqModel, err != nil, cyberBlockBodyChat, clientRequestedUsageFields(c, attemptPolicy.Mapping, reqModel, ""), service.HashUsageRequestPayload(body)) forwardDurationMs := time.Since(forwardStart).Milliseconds() upstreamLatencyMs, _ := getContextInt64(c, service.OpsUpstreamLatencyMsKey) @@ -289,7 +357,12 @@ func (h *OpenAIGatewayHandler) ChatCompletions(c *gin.Context) { clientIP := ip.GetClientIP(c) inboundEndpoint := GetInboundEndpoint(c) upstreamEndpoint := resolveOpenAIUpstreamEndpoint(c, account, res) + // 池请求按选中平台计量 user×platform 配额(尝试 ctx 携带 resolved 平台); + // 非池保持准入语义不变。 quotaPlatform := service.QuotaPlatform(c.Request.Context(), apiKey) + if isPoolAttempt { + quotaPlatform = service.QuotaPlatform(attemptPolicy.AttemptCtx, apiKey) + } sessionID := service.ExtractClientSessionID(c) cyberBlocked := service.GetOpsCyberPolicy(c) != nil h.submitOpenAIUsageRecordTask(c.Request.Context(), res, func(ctx context.Context) { @@ -306,7 +379,7 @@ func (h *OpenAIGatewayHandler) ChatCompletions(c *gin.Context) { APIKeyService: h.apiKeyService, QuotaPlatform: quotaPlatform, SessionID: sessionID, - ChannelUsageFields: clientRequestedUsageFields(c, channelMapping, reqModel, res.UpstreamModel), + ChannelUsageFields: clientRequestedUsageFields(c, attemptPolicy.Mapping, reqModel, res.UpstreamModel), PricingAt: pricingAt, CyberBlocked: cyberBlocked, }); err != nil { diff --git a/backend/internal/handler/openai_gateway_handler.go b/backend/internal/handler/openai_gateway_handler.go index 21f0cace70..097d824f18 100644 --- a/backend/internal/handler/openai_gateway_handler.go +++ b/backend/internal/handler/openai_gateway_handler.go @@ -206,6 +206,16 @@ func resolveOpenAIMessagesDispatchMappedModel(c *gin.Context, apiKey *service.AP (platform == service.PlatformGrok || service.IsMultiProtocolAPIKeyProvider(platform)) { return "" } + // 账号池候选含任一 grok/CN/OpenCode Go 时同样不套 gpt-5.x 默认映射 + // (与对应单平台语义一致,否则 claude-* 别名被改写成 gpt 默认后账号 + // 声明失配);候选全为 openai 时保留既有分组默认。 + if candidates := service.CompositeCandidatePlatformsFromContext(c.Request.Context()); len(candidates) > 0 { + for _, platform := range candidates { + if platform == service.PlatformGrok || service.IsMultiProtocolAPIKeyProvider(platform) { + return "" + } + } + } } return strings.TrimSpace(apiKey.Group.ResolveMessagesDispatchModel(requestedModel)) } @@ -324,6 +334,20 @@ func allowOpenAICompatibleMessagesDispatch(c *gin.Context, apiKey *service.APIKe (platform == service.PlatformGrok || service.IsMultiProtocolAPIKeyProvider(platform)) { return true } + // 账号池候选与单目标同语义:候选全部为 grok/CN/OpenCode Go 时豁免; + // 混有 openai 候选时仍受分组开关控制,不折叠候选。 + if candidates := service.CompositeCandidatePlatformsFromContext(c.Request.Context()); len(candidates) > 0 { + allExempt := true + for _, platform := range candidates { + if platform != service.PlatformGrok && !service.IsMultiProtocolAPIKeyProvider(platform) { + allExempt = false + break + } + } + if allExempt { + return true + } + } } return apiKey.Group.AllowMessagesDispatch } @@ -569,6 +593,13 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) { // 解析渠道级模型映射 channelMapping, _ := h.gatewayService.ResolveChannelMappingAndRestrict(c.Request.Context(), apiKey.GroupID, reqModel) + // composite 账号池请求:composite 作用域的渠道查找会跨平台行匹配(无 resolved + // 平台),映射/限制不可靠。canonical body 保持公开模型、选号也用公开模型; + // 真正的平台作用域映射/限制在账号选定后按选中平台解析 + //(evaluateCompositePoolAttemptPolicy),非池请求保持原映射语义。 + if compositePoolAttemptPolicyApplies(c, apiKey) { + channelMapping = service.ChannelMappingResult{MappedModel: reqModel} + } forwardBody := openAIModelMappedBody(body, channelMapping.Mapped, channelMapping.MappedModel, h.gatewayService.ReplaceModelInBody) seedOpenAIForwardImageIntentHint(c, channelMapping.Mapped, imageIntent) forwardModel := openAIChannelForwardModel(channelMapping, reqModel) @@ -663,6 +694,12 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) { pricingCtx, pricingAt := h.gatewayService.WithOpenAIRequestPricingContext(c.Request.Context(), apiKey.GroupID) c.Request = c.Request.WithContext(pricingCtx) + // composite 账号池 per-attempt 平台策略状态:被配额/渠道限制拒绝的平台记入 + // deniedPlatforms,重选时以 filtered candidate ctx 传 selector 做整平台 mask; + // 原请求 ctx 的候选池 immutable,不把选中账号写回。非池请求恒不生效。 + poolDenials := newCompositePoolPlatformDenials() + selectionCtx := c.Request.Context() + for { // Streaming Forward intentionally detaches the upstream request so usage can // be drained after a disconnect. Re-check the client context before every @@ -673,7 +710,7 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) { // Select account supporting the requested model reqLog.Debug("openai.account_selecting", zap.Int("excluded_account_count", len(failedAccountIDs))) selection, scheduleDecision, err := h.gatewayService.SelectAccountWithSchedulerForCapability( - c.Request.Context(), + selectionCtx, apiKey.GroupID, previousResponseID, sessionHash, @@ -737,7 +774,22 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) { zap.Float64("load_skew", scheduleDecision.LoadSkew), ) account := selection.Account - if previousResponseID != "" && requestPlatform == service.PlatformOpenAI && !account.IsOpenAIApiKey() { + // composite 账号池状态归属守卫:携带 previous_response_id 的池请求必须 + // 命中状态归属账号(StickyPreviousHit),否则在任何转发之前明确拒绝—— + // 不区分候选平台(CN A→CN B / CN→OpenCode / CN→openai 的未 hit 转移 + // 一律拒绝),不静默剥离 prevID、不把会话状态跨账号携带。pin 账号首跳 + // 失败被排除后再选到其他账号时同样由此拦下。早退须先释放 selector 已 + // 持有的槽位(Acquired=true 时 ReleaseFunc 非空,恰一次)。 + if previousResponseID != "" && compositePoolResponseStateGuardApplies(c, apiKey) && !scheduleDecision.StickyPreviousHit { + releaseCompositePoolSelection(selection) + h.errorResponse(c, http.StatusBadRequest, "invalid_request_error", + "previous_response_id belongs to a response owned by a different account; continue on the account that owns this response state or start a new response") + return + } + // 仅实际 openai 平台账号要求 API-key 才支持 HTTP continuation; + // pool 请求的 requestPlatform 归一化恒为 openai,不得作为判据 + // (否则 sticky 命中的 CN/OpenCode 账号会被误排除)。 + if previousResponseID != "" && account.Platform == service.PlatformOpenAI && !account.IsOpenAIApiKey() { // The public Responses HTTP API supports previous_response_id on API-key // accounts. OAuth/SetupToken upstreams do not, so keep searching instead // of silently deleting continuation state from a mixed account pool. @@ -764,6 +816,57 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) { reqLog.Debug("openai.account_selected", zap.Int64("account_id", account.ID), zap.String("account_name", account.Name)) setOpsSelectedAccount(c, account.ID, account.Platform) + // composite 账号池请求的组 effort 策略在账号选定后按账号平台补齐; + // 放在槽位获取前,deny/over-limit 可直接终止而不占槽。canonical + // forwardBody 保持不可变,策略结果只用于本次尝试的派生。 + poolPolicyBody := forwardBody + if cappedBody, changed, err := applyCompositePoolReasoningEffortPolicyForSelectedAccount(c, apiKey, account, forwardBody); err != nil { + releaseCompositePoolSelection(selection) + respondOpenAIReasoningEffortPolicyError(c, err, h.errorResponse) + return + } else if changed { + poolPolicyBody = cappedBody + } + + // composite 账号池 per-attempt 平台策略:对实际选中平台补做 user×platform + // 配额预检与渠道映射/限制(准入 CheckBillingEligibility 时池没有 resolved + // 平台、这两个维度被跳过;不得只后扣不预检)。检查为纯读,不写 RPM/计数, + // 不得以重复调用 CheckBillingEligibility 代替。deny 不占并发槽: + // - pinned(prevID 状态归属)请求:直接回原 policy 错误(配额 429+重试 + // 头 / 渠道 503),不换账号、不删 previousID、不改绑定; + // - 无状态请求:记 deniedPlatforms 后按 masked 候选池整平台重选, + // 候选全部被业务限制时按原语义终止,不误报 model unsupported。 + attemptPolicy := compositePoolAttemptPolicy{AttemptCtx: c.Request.Context(), Mapping: channelMapping} + isPoolAttempt := false + if compositePoolAttemptPolicyApplies(c, apiKey) { + attemptPolicy = evaluateCompositePoolAttemptPolicy( + c.Request.Context(), h.billingCacheService, h.gatewayService, apiKey, subscription, account, reqModel, requireCompact) + isPoolAttempt = true + if attemptPolicy.Failure.denied() { + releaseCompositePoolSelection(selection) + // streaming-aware writer:并发排队心跳可能已开始流,终止时不能拼 JSON。 + streamAwareWrite := func(cc *gin.Context, status int, code, message string) { + h.handleStreamingAwareError(cc, status, code, message, streamStarted) + } + if previousResponseID != "" && compositePoolResponseStateGuardApplies(c, apiKey) { + respondCompositePoolAttemptPolicyFailure(c, attemptPolicy.Failure, streamAwareWrite) + return + } + poolDenials.deny(account.Platform) + // 同时排除该账号:下一轮 masked ctx 下 sticky 层对 excluded 账号 + // 提前返回(不 clear),不会把原 sticky 账号当 platform mismatch + // 清掉粘性绑定;其它平台成功后按用户目标正常改绑。 + failedAccountIDs[account.ID] = struct{}{} + retryCtx, ok := compositePoolSelectionRetryContext(c.Request.Context(), poolDenials) + if !ok { + respondCompositePoolAttemptPolicyFailure(c, attemptPolicy.Failure, streamAwareWrite) + return + } + selectionCtx = retryCtx + continue + } + } + accountReleaseFunc, slotResult := h.acquireResponsesAccountSlot(c, apiKey.GroupID, sessionHash, selection, reqStream, &streamStarted, reqLog) if slotResult == openAISlotAcquireProfitVetoed { // 利润终检否决:排除该账号重新选号,全池耗尽由下一轮选号报错; @@ -787,20 +890,32 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) { // 跨 passthrough 边界的 failover:从 Kiro 等透传账号切到 Bedrock 等非透传账号前, // 从不可变的 canonical forwardBody 派生本次尝试 body 并整块剔除上游私有的加密 // reasoning item(含耦合的 id/summary),避免非透传上游 400 拒绝 Kiro reasoning 形态。 - attemptBody := h.deriveOpenAIForwardAttemptBody(reqLog, forwardBody, account, &passthroughFailoverState) + // 池请求先按选中平台的渠道映射从 poolPolicyBody 派生本次 attempt 的 + // channel-mapped body,再交给账号级 model_mapping(derive 内应用一次)。 + attemptChannelBody := poolPolicyBody + if isPoolAttempt { + attemptChannelBody = openAIModelMappedBody(poolPolicyBody, attemptPolicy.Mapping.Mapped, attemptPolicy.Mapping.MappedModel, h.gatewayService.ReplaceModelInBody) + } + attemptBody := h.deriveOpenAIForwardAttemptBody(reqLog, attemptChannelBody, account, &passthroughFailoverState) result, err := func() (*service.OpenAIForwardResult, error) { defer func() { if accountReleaseFunc != nil { accountReleaseFunc() } }() - return h.gatewayService.Forward(c.Request.Context(), c, account, attemptBody) + // 池请求的 attempt 局部 ctx 携带选中平台:forward 内的渠道定价作用域 + // 与计费 QuotaPlatform 都跟随实际平台,不写回 c.Request。 + forwardCtx := c.Request.Context() + if isPoolAttempt { + forwardCtx = attemptPolicy.AttemptCtx + } + return h.gatewayService.Forward(forwardCtx, c, account, attemptBody) }() var cyberBlockBodyHTTP []byte if service.GetOpsCyberPolicy(c) != nil { cyberBlockBodyHTTP = sessionHashBody } - h.recordCyberPolicyIfMarked(c, apiKey, account, subscription, reqModel, err != nil, cyberBlockBodyHTTP, clientRequestedUsageFields(c, channelMapping, reqModel, ""), service.HashUsageRequestPayload(body)) + h.recordCyberPolicyIfMarked(c, apiKey, account, subscription, reqModel, err != nil, cyberBlockBodyHTTP, clientRequestedUsageFields(c, attemptPolicy.Mapping, reqModel, ""), service.HashUsageRequestPayload(body)) forwardDurationMs := time.Since(forwardStart).Milliseconds() upstreamLatencyMs, _ := getContextInt64(c, service.OpsUpstreamLatencyMsKey) responseLatencyMs := forwardDurationMs @@ -823,7 +938,12 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) { requestPayloadHash := service.HashUsageRequestPayload(body) inboundEndpoint := GetInboundEndpoint(c) upstreamEndpoint := resolveOpenAIUpstreamEndpoint(c, account, res) + // 池请求按选中平台计量 user×platform 配额(尝试 ctx 携带 resolved 平台); + // 非池保持准入语义不变。 quotaPlatform := service.QuotaPlatform(c.Request.Context(), apiKey) + if isPoolAttempt { + quotaPlatform = service.QuotaPlatform(attemptPolicy.AttemptCtx, apiKey) + } sessionID := service.ExtractClientSessionID(c) cyberBlocked := service.GetOpsCyberPolicy(c) != nil h.submitOpenAIUsageRecordTask(c.Request.Context(), res, func(ctx context.Context) { @@ -841,7 +961,7 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) { APIKeyService: h.apiKeyService, QuotaPlatform: quotaPlatform, SessionID: sessionID, - ChannelUsageFields: clientRequestedUsageFields(c, channelMapping, reqModel, res.UpstreamModel), + ChannelUsageFields: clientRequestedUsageFields(c, attemptPolicy.Mapping, reqModel, res.UpstreamModel), PricingAt: pricingAt, CyberBlocked: cyberBlocked, NativeCompactionV2: nativeV2, @@ -1233,6 +1353,12 @@ func (h *OpenAIGatewayHandler) Messages(c *gin.Context) { // 解析渠道级模型映射 channelMappingMsg, _ := h.gatewayService.ResolveChannelMappingAndRestrict(c.Request.Context(), apiKey.GroupID, reqModel) + // composite 账号池请求:composite 作用域的渠道查找会跨平台行匹配(无 resolved + // 平台),映射/限制不可靠。平台作用域映射/限制在账号选定后按选中平台解析, + // 非池请求保持原语义。 + if compositePoolAttemptPolicyApplies(c, apiKey) { + channelMappingMsg = service.ChannelMappingResult{MappedModel: reqModel} + } mappedBodyForMessages := newOpenAIModelMappedBodyCache(body, h.gatewayService.ReplaceModelInBody) // 绑定错误透传服务,允许 service 层在非 failover 错误场景复用规则。 @@ -1296,6 +1422,12 @@ func (h *OpenAIGatewayHandler) Messages(c *gin.Context) { msgPricingCtx, pricingAt := h.gatewayService.WithOpenAIRequestPricingContext(c.Request.Context(), apiKey.GroupID) c.Request = c.Request.WithContext(msgPricingCtx) + // composite 账号池 per-attempt 平台策略状态:被配额/渠道限制拒绝的平台记入 + // deniedPlatforms,重选时以 filtered candidate ctx 传 selector 做整平台 mask; + // 原请求 ctx 的候选池 immutable,不把选中账号写回。非池请求恒不生效。 + poolDenials := newCompositePoolPlatformDenials() + selectionCtx := c.Request.Context() + for { if failoverClientGone(c) { return @@ -1306,7 +1438,7 @@ func (h *OpenAIGatewayHandler) Messages(c *gin.Context) { } reqLog.Debug("openai_messages.account_selecting", zap.Int("excluded_account_count", len(failedAccountIDs))) selection, scheduleDecision, err := h.gatewayService.SelectAccountWithSchedulerForCapability( - c.Request.Context(), + selectionCtx, apiKey.GroupID, "", // no previous_response_id sessionHash, @@ -1360,6 +1492,36 @@ func (h *OpenAIGatewayHandler) Messages(c *gin.Context) { _ = scheduleDecision setOpsSelectedAccount(c, account.ID, account.Platform) + // composite 账号池 per-attempt 平台策略:对实际选中平台补做 user×platform + // 配额预检与渠道映射/限制(准入 CheckBillingEligibility 时池没有 resolved + // 平台、这两个维度被跳过;不得只后扣不预检)。检查为纯读,不写 RPM/计数。 + // deny 不占并发槽:无状态请求记 deniedPlatforms 后按 masked 候选池整平台 + // 重选;候选全部被业务限制时按原语义终止,不误报 model unsupported。 + // (messages 循环无 previous_response_id,无 pinned 分支。) + attemptPolicyMsg := compositePoolAttemptPolicy{AttemptCtx: c.Request.Context(), Mapping: channelMappingMsg} + isPoolAttemptMsg := false + if compositePoolAttemptPolicyApplies(c, apiKey) { + attemptPolicyMsg = evaluateCompositePoolAttemptPolicy( + c.Request.Context(), h.billingCacheService, h.gatewayService, apiKey, subscription, account, reqModel, false) + isPoolAttemptMsg = true + if attemptPolicyMsg.Failure.denied() { + releaseCompositePoolSelection(selection) + poolDenials.deny(account.Platform) + // 同时排除该账号:下一轮 masked ctx 下 sticky 层对 excluded 账号 + // 提前返回(不 clear),不清掉原 sticky 粘性绑定。 + failedAccountIDs[account.ID] = struct{}{} + retryCtx, ok := compositePoolSelectionRetryContext(c.Request.Context(), poolDenials) + if !ok { + respondCompositePoolAttemptPolicyFailure(c, attemptPolicyMsg.Failure, func(cc *gin.Context, status int, code, message string) { + h.anthropicStreamingAwareError(cc, status, code, message, streamStarted) + }) + return + } + selectionCtx = retryCtx + continue + } + } + accountReleaseFunc, slotResult := h.acquireResponsesAccountSlot(c, apiKey.GroupID, sessionHash, selection, reqStream, &streamStarted, reqLog) if slotResult == openAISlotAcquireProfitVetoed { // 利润终检否决:排除该账号重新选号,全池耗尽由下一轮选号报错; @@ -1378,8 +1540,9 @@ func (h *OpenAIGatewayHandler) Messages(c *gin.Context) { forwardStart := time.Now() defaultMappedModel := strings.TrimSpace(effectiveMappedModel) - // 应用渠道模型映射到请求体 - forwardBody := mappedBodyForMessages(channelMappingMsg.Mapped, channelMappingMsg.MappedModel) + // 应用渠道模型映射到请求体;池请求按选中平台的渠道映射从 canonical body + // 派生本次 attempt 的 body:公开模型 → 选中平台渠道映射 → 账号 model_mapping。 + forwardBody := mappedBodyForMessages(attemptPolicyMsg.Mapping.Mapped, attemptPolicyMsg.Mapping.MappedModel) writerSizeBeforeForward := c.Writer.Size() result, err := func() (*service.OpenAIForwardResult, error) { defer func() { @@ -1387,13 +1550,19 @@ func (h *OpenAIGatewayHandler) Messages(c *gin.Context) { accountReleaseFunc() } }() - return h.gatewayService.ForwardAsAnthropic(c.Request.Context(), c, account, forwardBody, promptCacheKey, defaultMappedModel) + // 池请求的 attempt 局部 ctx 携带选中平台:forward 内渠道定价作用域与 + // 计费 QuotaPlatform 跟随实际平台,不写回 c.Request。 + forwardCtx := c.Request.Context() + if isPoolAttemptMsg { + forwardCtx = attemptPolicyMsg.AttemptCtx + } + return h.gatewayService.ForwardAsAnthropic(forwardCtx, c, account, forwardBody, promptCacheKey, defaultMappedModel) }() var cyberBlockBodyMsg []byte if service.GetOpsCyberPolicy(c) != nil { cyberBlockBodyMsg = body } - h.recordCyberPolicyIfMarked(c, apiKey, account, subscription, reqModel, err != nil, cyberBlockBodyMsg, clientRequestedUsageFields(c, channelMappingMsg, reqModel, ""), service.HashUsageRequestPayload(body)) + h.recordCyberPolicyIfMarked(c, apiKey, account, subscription, reqModel, err != nil, cyberBlockBodyMsg, clientRequestedUsageFields(c, attemptPolicyMsg.Mapping, reqModel, ""), service.HashUsageRequestPayload(body)) forwardDurationMs := time.Since(forwardStart).Milliseconds() upstreamLatencyMs, _ := getContextInt64(c, service.OpsUpstreamLatencyMsKey) responseLatencyMs := forwardDurationMs @@ -1417,7 +1586,12 @@ func (h *OpenAIGatewayHandler) Messages(c *gin.Context) { requestPayloadHash := service.HashUsageRequestPayload(body) inboundEndpoint := GetInboundEndpoint(c) upstreamEndpoint := resolveOpenAIUpstreamEndpoint(c, account, res) + // 池请求按选中平台计量 user×platform 配额(尝试 ctx 携带 resolved 平台); + // 非池保持准入语义不变。 quotaPlatform := service.QuotaPlatform(c.Request.Context(), apiKey) + if isPoolAttemptMsg { + quotaPlatform = service.QuotaPlatform(attemptPolicyMsg.AttemptCtx, apiKey) + } sessionID := service.ExtractClientSessionID(c) cyberBlocked := service.GetOpsCyberPolicy(c) != nil h.submitOpenAIUsageRecordTask(c.Request.Context(), res, func(ctx context.Context) { @@ -1435,7 +1609,7 @@ func (h *OpenAIGatewayHandler) Messages(c *gin.Context) { APIKeyService: h.apiKeyService, QuotaPlatform: quotaPlatform, SessionID: sessionID, - ChannelUsageFields: clientRequestedUsageFields(c, channelMappingMsg, reqModel, res.UpstreamModel), + ChannelUsageFields: clientRequestedUsageFields(c, attemptPolicyMsg.Mapping, reqModel, res.UpstreamModel), PricingAt: pricingAt, CyberBlocked: cyberBlocked, }); err != nil { diff --git a/backend/internal/handler/ops_error_logger.go b/backend/internal/handler/ops_error_logger.go index a4e30814ca..650e0994bb 100644 --- a/backend/internal/handler/ops_error_logger.go +++ b/backend/internal/handler/ops_error_logger.go @@ -468,7 +468,11 @@ func setOpsSelectedAccount(c *gin.Context, accountID int64, platform ...string) if c == nil || accountID <= 0 { return } + // 尝试级元数据随账号切换重置:Handler 在账号 failover 间复用同一个 Gin + // context,上一账号的实际出站端点/模型不得泄漏到下一账号的失败日志。 service.ClearOpsUpstreamModel(c) + service.ClearOpsUpstreamEndpoint(c) + service.ClearActualOpenAIUpstreamEndpoint(c) c.Set(opsAccountIDKey, accountID) if c.Request != nil { ctx := context.WithValue(c.Request.Context(), ctxkey.AccountID, accountID) diff --git a/backend/internal/pkg/ctxkey/ctxkey.go b/backend/internal/pkg/ctxkey/ctxkey.go index c34ef589a0..02aa89bfa1 100644 --- a/backend/internal/pkg/ctxkey/ctxkey.go +++ b/backend/internal/pkg/ctxkey/ctxkey.go @@ -20,6 +20,11 @@ const ( // CompositeRouteSource 标识 composite 解析结果来自显式路由还是内置模型探测。 CompositeRouteSource Key = "ctx_composite_route_source" + // CompositeCandidatePlatforms 是 composite 多平台候选池(account_pool 决策) + // 的参与平台集合(去重升序)。与 ResolvedTargetPlatform 互斥写入:池决策不 + // 固定单一目标平台,选号期间不得被最终账号平台覆盖。 + CompositeCandidatePlatforms Key = "ctx_composite_candidate_platforms" + // RequestID 为服务端生成/透传的请求 ID。 RequestID Key = "ctx_request_id" diff --git a/backend/internal/server/routes/gateway.go b/backend/internal/server/routes/gateway.go index 870ae14c5c..e75ea51ad2 100644 --- a/backend/internal/server/routes/gateway.go +++ b/backend/internal/server/routes/gateway.go @@ -2,6 +2,7 @@ package routes import ( "errors" + "fmt" "net/http" "strings" @@ -45,26 +46,8 @@ func RegisterGatewayRoutes( // 保证校验发生在合成路由改写与调度之前,且只看客户端书写的模型名。 groupModelAllowlist := middleware.GroupModelAllowlist() - isOpenAIResponsesCompatibleGatewayPlatform := func(c *gin.Context) bool { - switch getGroupPlatform(c) { - case service.PlatformOpenAI, service.PlatformGrok, - service.PlatformKimi, service.PlatformZhipu, service.PlatformDeepseek, - service.PlatformMiniMax, service.PlatformOpenCodeGo: - // 国产 OpenAI 兼容供应商与 openai/grok 一样经 OpenAI 网关转发。 - return true - default: - return false - } - } countTokensHandler := func(c *gin.Context) { - switch getGroupPlatform(c) { - case service.PlatformOpenAI, service.PlatformKimi, service.PlatformZhipu, service.PlatformDeepseek, service.PlatformMiniMax, service.PlatformOpenCodeGo: - h.OpenAIGateway.CountTokens(c) - case service.PlatformGrok: - h.OpenAIGateway.GrokCountTokens(c) - default: - h.Gateway.CountTokens(c) - } + dispatchOpenAICompatibleCountTokens(c, h.OpenAIGateway.CountTokens, h.OpenAIGateway.GrokCountTokens, h.Gateway.CountTokens) } codexModelsHandler := func(c *gin.Context) { dispatchCodexModelsGateway(c, h.OpenAIGateway.CodexModels, h.Gateway.CodexModels) @@ -196,11 +179,7 @@ func RegisterGatewayRoutes( { // /v1/messages: auto-route based on group platform gateway.POST("/messages", func(c *gin.Context) { - if isOpenAIResponsesCompatibleGatewayPlatform(c) { - h.OpenAIGateway.Messages(c) - return - } - h.Gateway.Messages(c) + dispatchOpenAICompatibleGateway(c, h.OpenAIGateway.Messages, h.Gateway.Messages) }) // System One carries only JSON text, so it uses the text body limit. gateway.POST("/systemone", textBodyLimit, h.Gateway.SystemOne) @@ -218,18 +197,10 @@ func RegisterGatewayRoutes( gateway.GET("/live/:call_id", h.OpenAIGateway.LiveSideband) // OpenAI Responses API: auto-route based on group platform gateway.POST("/responses", func(c *gin.Context) { - if isOpenAIResponsesCompatibleGatewayPlatform(c) { - h.OpenAIGateway.Responses(c) - return - } - h.Gateway.Responses(c) + dispatchOpenAICompatibleGateway(c, h.OpenAIGateway.Responses, h.Gateway.Responses) }) gateway.POST("/responses/*subpath", guardResponsesSubpath(func(c *gin.Context) { - if isOpenAIResponsesCompatibleGatewayPlatform(c) { - h.OpenAIGateway.Responses(c) - return - } - h.Gateway.Responses(c) + dispatchOpenAICompatibleGateway(c, h.OpenAIGateway.Responses, h.Gateway.Responses) })) gateway.POST("/alpha/search", textBodyLimit, h.OpenAIGateway.AlphaSearch) gateway.GET("/responses", func(c *gin.Context) { @@ -237,11 +208,7 @@ func RegisterGatewayRoutes( }) // OpenAI Chat Completions API: auto-route based on group platform gateway.POST("/chat/completions", func(c *gin.Context) { - if isOpenAIResponsesCompatibleGatewayPlatform(c) { - h.OpenAIGateway.ChatCompletions(c) - return - } - h.Gateway.ChatCompletions(c) + dispatchOpenAICompatibleGateway(c, h.OpenAIGateway.ChatCompletions, h.Gateway.ChatCompletions) }) gateway.POST("/embeddings", textBodyLimit, func(c *gin.Context) { if !isOpenAIOnlyEndpointGatewayPlatform(c) { @@ -359,11 +326,7 @@ func RegisterGatewayRoutes( // OpenAI Responses API(不带v1前缀的别名)— auto-route based on group platform responsesHandler := func(c *gin.Context) { - if isOpenAIResponsesCompatibleGatewayPlatform(c) { - h.OpenAIGateway.Responses(c) - return - } - h.Gateway.Responses(c) + dispatchOpenAICompatibleGateway(c, h.OpenAIGateway.Responses, h.Gateway.Responses) } // 根路径别名共用中间件链:白名单准入在 apiKeyAuth 之后、compositeTarget // 之前,避免逐条路由手工维护链导致漏挂。 @@ -399,11 +362,7 @@ func RegisterGatewayRoutes( } // OpenAI Chat Completions API(不带v1前缀的别名)— auto-route based on group platform rootRoute(http.MethodPost, "/chat/completions", bodyLimit, func(c *gin.Context) { - if isOpenAIResponsesCompatibleGatewayPlatform(c) { - h.OpenAIGateway.ChatCompletions(c) - return - } - h.Gateway.ChatCompletions(c) + dispatchOpenAICompatibleGateway(c, h.OpenAIGateway.ChatCompletions, h.Gateway.ChatCompletions) }) rootRoute(http.MethodPost, "/embeddings", textBodyLimit, func(c *gin.Context) { if !isOpenAIOnlyEndpointGatewayPlatform(c) { @@ -546,6 +505,136 @@ func getGroupPlatform(c *gin.Context) string { return apiKey.Group.Platform } +// isOpenAICompatibleGatewayFamilyPlatform 报告单个平台是否经 OpenAI 网关转发 +// (openai/grok/国产 OpenAI 兼容供应商/OpenCode Go)。 +func isOpenAICompatibleGatewayFamilyPlatform(platform string) bool { + switch platform { + case service.PlatformOpenAI, service.PlatformGrok, + service.PlatformKimi, service.PlatformZhipu, service.PlatformDeepseek, + service.PlatformMiniMax, service.PlatformOpenCodeGo: + // 国产 OpenAI 兼容供应商与 openai/grok 一样经 OpenAI 网关转发。 + return true + default: + return false + } +} + +// compositePoolCandidatePlatforms 返回 composite 账号池请求的候选平台集合; +// 非池请求(未写池候选)返回 false。与 service pool 语义一致:已有明确 +// resolved endpoint pin(如 Gemini fallback、显式 single 决策)时按 single +// 处理——候选数据保留在 ctx 但不作为活跃池。 +func compositePoolCandidatePlatforms(c *gin.Context) ([]string, bool) { + if c == nil || c.Request == nil { + return nil, false + } + if _, resolved := service.ResolvedTargetPlatformFromContext(c.Request.Context()); resolved { + return nil, false + } + candidates := service.CompositeCandidatePlatformsFromContext(c.Request.Context()) + if len(candidates) == 0 { + return nil, false + } + return candidates, true +} + +// writeCompositeRouteAdmissionError 按实际入站 endpoint 选择错误信封: +// messages 系列(Anthropic 协议入口)沿用 {"type":"error","error":{...}}, +// 其余 OpenAI 端点沿用 {"error":{...}},随后 Abort。 +func writeCompositeRouteAdmissionError(c *gin.Context, status int, message string) { + service.MarkOpsClientBusinessLimited(c, service.OpsClientBusinessLimitedReasonLocalModelConfiguration) + envelope := gin.H{"error": gin.H{"type": "invalid_request_error", "message": message}} + if c.Request != nil && c.Request.URL != nil && strings.Contains(c.Request.URL.Path, "/messages") { + envelope = gin.H{"type": "error", "error": gin.H{"type": "invalid_request_error", "message": message}} + } + c.JSON(status, envelope) + c.Abort() +} + +// isCompositeOpenAIFamilyPool 报告账号池候选是否全部属于 OpenAI 兼容族。 +// 池的 handler 家族只由族归属决定,与池大小无关。 +func isCompositeOpenAIFamilyPool(candidates []string) bool { + if len(candidates) == 0 { + return false + } + for _, platform := range candidates { + if !isOpenAICompatibleGatewayFamilyPlatform(platform) { + return false + } + } + return true +} + +// isOpenAIResponsesCompatibleGatewayPlatform 报告请求是否应进入 OpenAI 兼容族 +// handler。账号池请求没有单一目标平台:池候选全部属于兼容族才进入,混入其他 +// 族时返回 false,由 dispatchOpenAICompatibleGateway 显式拒绝,不允许按池大小 +// 或猜测选族。 +func isOpenAIResponsesCompatibleGatewayPlatform(c *gin.Context) bool { + if candidates, ok := compositePoolCandidatePlatforms(c); ok { + return isCompositeOpenAIFamilyPool(candidates) + } + return isOpenAICompatibleGatewayFamilyPlatform(getGroupPlatform(c)) +} + +// dispatchOpenAICompatibleGateway 把文本端点(messages/responses/chat +// completions)路由进 OpenAI 兼容族:账号池候选全部属于兼容族 → OpenAI 网关; +// 跨族池 → 显式 400(点名候选,不落入通用网关的错误协议);单目标沿用既有族 +// 判断落通用网关。 +func dispatchOpenAICompatibleGateway(c *gin.Context, openAIHandler, genericHandler gin.HandlerFunc) { + if candidates, ok := compositePoolCandidatePlatforms(c); ok { + if isCompositeOpenAIFamilyPool(candidates) { + openAIHandler(c) + return + } + rejectCompositeCrossFamilyPool(c, candidates) + return + } + if isOpenAICompatibleGatewayFamilyPlatform(getGroupPlatform(c)) { + openAIHandler(c) + return + } + genericHandler(c) +} + +// dispatchOpenAICompatibleCountTokens 沿用 count_tokens 的既有语义:openai 与 +// 国产兼容供应商走 OpenAI CountTokens,grok 走本地估算;账号池候选全部属于 +// 兼容族时进入 OpenAI CountTokens(沿用其原有端点能力/不支持语义),跨族池 +// 明确拒绝。 +func dispatchOpenAICompatibleCountTokens(c *gin.Context, compatibleHandler, grokHandler, genericHandler gin.HandlerFunc) { + if candidates, ok := compositePoolCandidatePlatforms(c); ok { + if isCompositeOpenAIFamilyPool(candidates) { + compatibleHandler(c) + return + } + rejectCompositeCrossFamilyPool(c, candidates) + return + } + switch getGroupPlatform(c) { + case service.PlatformOpenAI, service.PlatformKimi, service.PlatformZhipu, service.PlatformDeepseek, service.PlatformMiniMax, service.PlatformOpenCodeGo: + compatibleHandler(c) + case service.PlatformGrok: + grokHandler(c) + default: + genericHandler(c) + } +} + +// rejectCompositeCrossFamilyPool 对混入非兼容族候选(或全部为原生协议族)的 +// 账号池写显式 400 并点名候选平台:这类请求没有统一的 handler 家族, +// 猜测单个平台或落入通用网关都会产生误导性错误。 +func rejectCompositeCrossFamilyPool(c *gin.Context, candidates []string) { + foreign := make([]string, 0, len(candidates)) + for _, platform := range candidates { + if !isOpenAICompatibleGatewayFamilyPlatform(platform) { + foreign = append(foreign, platform) + } + } + writeCompositeRouteAdmissionError(c, http.StatusBadRequest, fmt.Sprintf( + "Composite account pool for this model spans multiple protocol families (candidates: %s; unsupported for OpenAI-compatible endpoints: %s)", + strings.Join(candidates, ", "), + strings.Join(foreign, ", "), + )) +} + func compositeTargetPlatformMiddleware(resolver *service.CompositeRouteResolver) gin.HandlerFunc { if resolver == nil { resolver = service.NewCompositeRouteResolver(nil) @@ -586,13 +675,19 @@ func compositeTargetPlatformMiddleware(resolver *service.CompositeRouteResolver) c.Abort() return } - if decision.Matched { - c.Request = c.Request.WithContext(service.WithCompositeRouteDecision(c.Request.Context(), decision)) - if upstreamModel := strings.TrimSpace(decision.UpstreamModel); upstreamModel != "" && upstreamModel != model && gjson.ValidBytes(body) { - if _, modelPath := requestmodel.JSONModelPathForRoute(routePath, body); modelPath != "" { - if rewritten, rewriteErr := sjson.SetBytes(body, modelPath, upstreamModel); rewriteErr == nil { - body = rewritten - } + if !decision.Matched { + // composite 请求的模型既无显式路由、也无账号映射/候选池可归入 + // 具体平台:继续放行只会落到通用网关并按通用协议报错。对 + // composite 在入口明确以请求错误拒绝(带模型名与原因),信封 + // 按入站 endpoint 协议选择。 + writeCompositeRouteAdmissionError(c, http.StatusBadRequest, fmt.Sprintf("Model %q cannot be resolved to any platform in this composite group (%s)", model, decision.Reason)) + return + } + c.Request = c.Request.WithContext(service.WithCompositeRouteDecision(c.Request.Context(), decision)) + if upstreamModel := strings.TrimSpace(decision.UpstreamModel); upstreamModel != "" && upstreamModel != model && gjson.ValidBytes(body) { + if _, modelPath := requestmodel.JSONModelPathForRoute(routePath, body); modelPath != "" { + if rewritten, rewriteErr := sjson.SetBytes(body, modelPath, upstreamModel); rewriteErr == nil { + body = rewritten } } } diff --git a/backend/internal/server/routes/gateway_composite_cross_platform_dispatch_test.go b/backend/internal/server/routes/gateway_composite_cross_platform_dispatch_test.go new file mode 100644 index 0000000000..707527dba1 --- /dev/null +++ b/backend/internal/server/routes/gateway_composite_cross_platform_dispatch_test.go @@ -0,0 +1,518 @@ +//go:build unit + +package routes + +// RED 回归测试(feature/composite-cross-platform-scheduling)。 +// +// 已知故障:composite 分组中同一公开模型被多个不同平台的 group-bound 账号 +// 同时声明(各有账号级 model_mapping),且未配置显式 composite route 时, +// CompositeRouteResolver.Resolve 命中 ownership.Ambiguous 后直接返回 +// Matched=false(不再回落 DetectModelPlatform)。中间件因此不写入 +// ResolvedTargetPlatform,routes 层的 isOpenAIResponsesCompatibleGatewayPlatform +// 判定失败,把 POST /v1/chat/completions 误分发给通用 Anthropic 网关 +// handler(h.Gateway.ChatCompletions)。该 handler 走 CC→Responses→Anthropic +// 桥接,出站请求被拼成 {base_url}/v1/messages?beta=true——当账号 base_url +// 以 /v1 结尾时即为 /v1/v1/messages。 +// +// 期望行为(待实现修绿):该场景应统一进入 OpenAI 兼容网关 handler,由其 +// 现有 selector 在跨平台候选池中选号;无论选中哪个账号,出站都必须是 +// OpenAI Chat Completions 转发({base_url}/chat/completions,base 以 /v1 +// 结尾时不得重复拼版本段),且 body.model 为选中账号 model_mapping 映射后 +// 的上游模型。 +// +// 链路真实性:本测试经 RegisterGatewayRoutes 挂载真实中间件链 +// (bodyLimit→apiKeyAuth→groupModelAllowlist→compositeTarget→…→handler 分发), +// composite 中间件持有与 GatewayService 真实 resolveCompositeModelOwnership +// 绑定的 CompositeRouteResolver;两条 handler 分支都是真实 handler +// (GatewayHandler + OpenAIGatewayHandler),账号与分组通过 +// RegisterGatewayRoutes 生产同款注入方式放置。出站经 HTTPUpstream 桩捕获, +// 不发起任何真实网络请求。 + +import ( + "context" + "io" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/Wei-Shaw/sub2api/internal/handler" + "github.com/Wei-Shaw/sub2api/internal/pkg/tlsfingerprint" + servermiddleware "github.com/Wei-Shaw/sub2api/internal/server/middleware" + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" +) + +const ( + compositeDispatchGroupID = int64(4101) + compositeDispatchDeepseekID = int64(4111) + compositeDispatchOpenCodeID = int64(4112) + + compositeDispatchDeepseekBase = "https://deepseek-composite-fake.test/v1" + compositeDispatchOpenCodeBase = "https://opencode-composite-fake.test/v1" + + // compositeDispatchPublicModel 是两个平台账号同时声明(各自 model_mapping + // 的 key)的公开模型名,命中内置 detector 的 deepseek- 前缀,因此歧义 + // 只能由账号归属判断暴露。 + compositeDispatchPublicModel = "deepseek-flash" +) + +// compositeDispatchUpstream 捕获两条网关服务(通用 + OpenAI 兼容)的全部出站。 +type compositeDispatchUpstream struct { + service.HTTPUpstream + + mu sync.Mutex + captured []compositeDispatchCapturedRequest +} + +type compositeDispatchCapturedRequest struct { + accountID int64 + url string + path string + host string + model string +} + +func (u *compositeDispatchUpstream) record(req *http.Request, accountID int64) { + var body []byte + if req.Body != nil { + body, _ = io.ReadAll(req.Body) + } + captured := compositeDispatchCapturedRequest{ + accountID: accountID, + url: req.URL.String(), + path: req.URL.Path, + host: req.URL.Hostname(), + model: gjson.GetBytes(body, "model").String(), + } + u.mu.Lock() + u.captured = append(u.captured, captured) + u.mu.Unlock() +} + +func (u *compositeDispatchUpstream) Do(req *http.Request, _ string, accountID int64, _ int) (*http.Response, error) { + u.record(req, accountID) + return u.respond(req), nil +} + +func (u *compositeDispatchUpstream) DoWithTLS(req *http.Request, _ string, accountID int64, _ int, _ *tlsfingerprint.Profile) (*http.Response, error) { + u.record(req, accountID) + return u.respond(req), nil +} + +// respond 按出站 path 返回最小可解析响应:CC 路径回最小 CC JSON;其他路径 +// (即错误分发的 Anthropic 桥)回最小 Anthropic SSE,让两条链路都能完整走完, +// 避免把 RED 失败变成 failover 风暴或解析 panic。 +func (u *compositeDispatchUpstream) respond(req *http.Request) *http.Response { + if strings.HasSuffix(req.URL.Path, "/chat/completions") { + return compositeDispatchResponse("application/json", `{"id":"chatcmpl-red","object":"chat.completion","model":"deepseek-flash","choices":[{"index":0,"message":{"role":"assistant","content":"ok"},"finish_reason":"stop"}],"usage":{"prompt_tokens":1,"completion_tokens":1,"total_tokens":2}}`) + } + sse := "event: message_start\n" + + `data: {"type":"message_start","message":{"id":"msg-red","type":"message","role":"assistant","model":"deepseek-flash","content":[],"stop_reason":null,"usage":{"input_tokens":1,"output_tokens":1}}}` + "\n\n" + + "event: message_delta\n" + + `data: {"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":1}}` + "\n\n" + + "event: message_stop\n" + + `data: {"type":"message_stop"}` + "\n\n" + return compositeDispatchResponse("text/event-stream", sse) +} + +func compositeDispatchResponse(contentType, body string) *http.Response { + return &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{contentType}}, + Body: io.NopCloser(strings.NewReader(body)), + } +} + +func (u *compositeDispatchUpstream) snapshot() []compositeDispatchCapturedRequest { + u.mu.Lock() + defer u.mu.Unlock() + return append([]compositeDispatchCapturedRequest(nil), u.captured...) +} + +// compositeDispatchAccountRepo 提供 deepseek + opencode_go 两个可调度账号。 +type compositeDispatchAccountRepo struct { + service.AccountRepository + accounts []service.Account +} + +func cloneCompositeDispatchAccounts(accounts []service.Account) []service.Account { + out := make([]service.Account, 0, len(accounts)) + for _, account := range accounts { + copy := account + credentials := make(map[string]any, len(account.Credentials)) + for key, value := range account.Credentials { + credentials[key] = value + } + copy.Credentials = credentials + out = append(out, copy) + } + return out +} + +func (r *compositeDispatchAccountRepo) schedulable() []service.Account { + out := make([]service.Account, 0, len(r.accounts)) + for _, account := range r.accounts { + if account.IsSchedulable() { + out = append(out, account) + } + } + return out +} + +func (r *compositeDispatchAccountRepo) GetByID(_ context.Context, id int64) (*service.Account, error) { + for _, account := range r.accounts { + if account.ID == id { + copy := account + return ©, nil + } + } + return nil, nil +} + +func (r *compositeDispatchAccountRepo) GetByIDs(_ context.Context, ids []int64) ([]*service.Account, error) { + out := make([]*service.Account, 0, len(ids)) + for _, id := range ids { + if account, err := r.GetByID(context.Background(), id); err == nil && account != nil { + out = append(out, account) + } + } + return out, nil +} + +func (r *compositeDispatchAccountRepo) ListSchedulable(context.Context) ([]service.Account, error) { + return cloneCompositeDispatchAccounts(r.schedulable()), nil +} + +func (r *compositeDispatchAccountRepo) ListSchedulableByGroupID(_ context.Context, groupID int64) ([]service.Account, error) { + out := make([]service.Account, 0) + for _, account := range r.schedulable() { + for _, id := range account.GroupIDs { + if id == groupID { + out = append(out, account) + break + } + } + } + return cloneCompositeDispatchAccounts(out), nil +} + +func (r *compositeDispatchAccountRepo) ListSchedulableByPlatform(_ context.Context, platform string) ([]service.Account, error) { + out := make([]service.Account, 0) + for _, account := range r.schedulable() { + if account.Platform == platform { + out = append(out, account) + } + } + return cloneCompositeDispatchAccounts(out), nil +} + +func (r *compositeDispatchAccountRepo) ListSchedulableByGroupIDAndPlatform(_ context.Context, groupID int64, platform string) ([]service.Account, error) { + out := make([]service.Account, 0) + for _, account := range r.schedulable() { + if account.Platform != platform { + continue + } + for _, id := range account.GroupIDs { + if id == groupID { + out = append(out, account) + break + } + } + } + return cloneCompositeDispatchAccounts(out), nil +} + +func (r *compositeDispatchAccountRepo) ListSchedulableUngroupedByPlatform(_ context.Context, platform string) ([]service.Account, error) { + return r.ListSchedulableByPlatform(context.Background(), platform) +} + +func (r *compositeDispatchAccountRepo) ListSchedulableByPlatforms(_ context.Context, platforms []string) ([]service.Account, error) { + out := make([]service.Account, 0) + for _, account := range r.schedulable() { + for _, platform := range platforms { + if account.Platform == platform { + out = append(out, account) + break + } + } + } + return cloneCompositeDispatchAccounts(out), nil +} + +func (r *compositeDispatchAccountRepo) ListSchedulableByGroupIDAndPlatforms(_ context.Context, groupID int64, platforms []string) ([]service.Account, error) { + out := make([]service.Account, 0) + for _, account := range r.schedulable() { + matchedPlatform := false + for _, platform := range platforms { + if account.Platform == platform { + matchedPlatform = true + break + } + } + if !matchedPlatform { + continue + } + for _, id := range account.GroupIDs { + if id == groupID { + out = append(out, account) + break + } + } + } + return cloneCompositeDispatchAccounts(out), nil +} + +func (r *compositeDispatchAccountRepo) ListSchedulableUngroupedByPlatforms(_ context.Context, platforms []string) ([]service.Account, error) { + return r.ListSchedulableByPlatforms(context.Background(), platforms) +} + +// ListModelAvailabilityCandidates 对齐接口语义:仅按持久化配置(active + +// schedulable)返回候选,不做瞬态运行时过滤;groupID 为 nil 时 includeGrouped +// 决定扫全量还是仅未分组账号。WIP 的 resolveCompositeModelOwnership 经此查询 +// composite 账号归属。 +func (r *compositeDispatchAccountRepo) ListModelAvailabilityCandidates(_ context.Context, groupID *int64, platforms []string, includeGrouped bool) ([]service.Account, error) { + out := make([]service.Account, 0) + for _, account := range r.schedulable() { + if len(platforms) > 0 { + matchedPlatform := false + for _, platform := range platforms { + if account.Platform == platform { + matchedPlatform = true + break + } + } + if !matchedPlatform { + continue + } + } + if groupID == nil && !includeGrouped && len(account.GroupIDs) > 0 { + continue + } + if groupID != nil { + inGroup := false + for _, id := range account.GroupIDs { + if id == *groupID { + inGroup = true + break + } + } + if !inGroup { + continue + } + } + out = append(out, account) + } + return cloneCompositeDispatchAccounts(out), nil +} + +// compositeDispatchGroupRepo 满足通用调度器 resolveGatewayGroup 的分组读取。 +type compositeDispatchGroupRepo struct { + service.GroupRepository + group *service.Group +} + +func (r *compositeDispatchGroupRepo) GetByID(context.Context, int64) (*service.Group, error) { + return r.group, nil +} + +func (r *compositeDispatchGroupRepo) GetByIDLite(context.Context, int64) (*service.Group, error) { + return r.group, nil +} + +// compositeDispatchConcurrencyCache 放行用户/账号槽位并安全释放。 +type compositeDispatchConcurrencyCache struct { + service.ConcurrencyCache +} + +func (m *compositeDispatchConcurrencyCache) AcquireUserSlot(context.Context, int64, int, string) (bool, error) { + return true, nil +} + +func (m *compositeDispatchConcurrencyCache) ReleaseUserSlot(context.Context, int64, string) error { + return nil +} + +func (m *compositeDispatchConcurrencyCache) AcquireAccountSlot(context.Context, int64, int, string) (bool, error) { + return true, nil +} + +func (m *compositeDispatchConcurrencyCache) ReleaseAccountSlot(context.Context, int64, string) error { + return nil +} + +func (m *compositeDispatchConcurrencyCache) GetAccountConcurrency(context.Context, int64) (int, error) { + return 0, nil +} + +func (m *compositeDispatchConcurrencyCache) GetAccountConcurrencyBatch(_ context.Context, accountIDs []int64) (map[int64]int, error) { + result := make(map[int64]int, len(accountIDs)) + for _, accountID := range accountIDs { + result[accountID] = 0 + } + return result, nil +} + +func (m *compositeDispatchConcurrencyCache) IncrementAccountWaitCount(context.Context, int64, int) (bool, error) { + return true, nil +} + +func (m *compositeDispatchConcurrencyCache) DecrementAccountWaitCount(context.Context, int64) error { + return nil +} + +func (m *compositeDispatchConcurrencyCache) GetAccountWaitingCount(context.Context, int64) (int, error) { + return 0, nil +} + +func (m *compositeDispatchConcurrencyCache) IncrementWaitCount(context.Context, int64, int) (bool, error) { + return true, nil +} + +func (m *compositeDispatchConcurrencyCache) DecrementWaitCount(context.Context, int64) error { + return nil +} + +func (m *compositeDispatchConcurrencyCache) GetUserConcurrency(context.Context, int64) (int, error) { + return 0, nil +} + +func TestCompositeAmbiguousModelChatCompletionsForwardedViaOpenAIGatewayUpstream(t *testing.T) { + gin.SetMode(gin.TestMode) + + groupID := compositeDispatchGroupID + group := &service.Group{ + ID: groupID, + Platform: service.PlatformComposite, + Status: service.StatusActive, + } + user := &service.User{ID: 4103, Status: service.StatusActive} + apiKey := &service.APIKey{ + ID: 4102, + GroupID: &groupID, + User: user, + Group: group, + } + + repo := &compositeDispatchAccountRepo{ + accounts: []service.Account{ + { + ID: compositeDispatchDeepseekID, Name: "cn-deepseek", + Platform: service.PlatformDeepseek, Type: service.AccountTypeAPIKey, + Status: service.StatusActive, Schedulable: true, Concurrency: 4, Priority: 1, + Credentials: map[string]any{ + "api_key": "test-deepseek-key", + "base_url": compositeDispatchDeepseekBase, + "model_mapping": map[string]any{compositeDispatchPublicModel: "deepseek-chat"}, + }, + GroupIDs: []int64{compositeDispatchGroupID}, + AccountGroups: []service.AccountGroup{{AccountID: compositeDispatchDeepseekID, GroupID: compositeDispatchGroupID, Priority: 1}}, + }, + { + ID: compositeDispatchOpenCodeID, Name: "opencode-go", + Platform: service.PlatformOpenCodeGo, Type: service.AccountTypeAPIKey, + Status: service.StatusActive, Schedulable: true, Concurrency: 4, Priority: 2, + Credentials: map[string]any{ + "api_key": "test-opencode-key", + "base_url": compositeDispatchOpenCodeBase, + "model_mapping": map[string]any{compositeDispatchPublicModel: "deepseek-v4"}, + }, + GroupIDs: []int64{compositeDispatchGroupID}, + AccountGroups: []service.AccountGroup{{AccountID: compositeDispatchOpenCodeID, GroupID: compositeDispatchGroupID, Priority: 1}}, + }, + }, + } + groupRepo := &compositeDispatchGroupRepo{group: group} + upstream := &compositeDispatchUpstream{} + + // 无显式 route:空 repo 的 resolver,经 NewGatewayService 绑定真实的 + // resolveCompositeModelOwnership(账号归属判定),与生产装配同构。 + compositeResolver := service.NewCompositeRouteResolver(nil) + + cfg := &config.Config{RunMode: config.RunModeSimple} + cfg.Gateway.MaxBodySize = 1024 * 1024 + cfg.Gateway.TextMaxBodySize = 1024 * 1024 + cfg.Gateway.MaxAccountSwitches = 3 + cfg.Security.URLAllowlist.AllowInsecureHTTP = true + + billingService := service.NewBillingService(cfg, nil) + billingCache := service.NewBillingCacheService(nil, nil, nil, nil, nil, nil, cfg, nil) + concurrencyService := service.NewConcurrencyService(&compositeDispatchConcurrencyCache{}) + deferred := &service.DeferredService{} + + genericGateway := service.NewGatewayService( + repo, groupRepo, nil, nil, nil, nil, nil, nil, cfg, nil, + concurrencyService, billingService, nil, billingCache, nil, + upstream, deferred, nil, nil, nil, nil, nil, nil, nil, nil, + compositeResolver, nil, nil, + ) + openAIGateway := service.NewOpenAIGatewayService( + repo, nil, nil, nil, nil, nil, nil, cfg, nil, nil, + billingService, nil, billingCache, upstream, deferred, + nil, nil, nil, nil, nil, nil, nil, + ) + + handlers := &handler.Handlers{ + Gateway: handler.NewGatewayHandler( + genericGateway, nil, nil, nil, nil, + concurrencyService, billingCache, nil, nil, nil, nil, nil, nil, + cfg, nil, + ), + OpenAIGateway: handler.NewOpenAIGatewayHandler( + openAIGateway, concurrencyService, billingCache, &service.APIKeyService{}, + nil, nil, nil, nil, cfg, + ), + AsyncImage: handler.NewAsyncImageHandler(nil, nil), + } + + router := gin.New() + RegisterGatewayRoutes( + router, + handlers, + servermiddleware.APIKeyAuthMiddleware(func(c *gin.Context) { + c.Set(string(servermiddleware.ContextKeyAPIKey), apiKey) + c.Set(string(servermiddleware.ContextKeyUser), servermiddleware.AuthSubject{UserID: user.ID, Concurrency: 1}) + c.Next() + }), + nil, + nil, + nil, + nil, + compositeResolver, + cfg, + ) + + requestBody := `{"model":"` + compositeDispatchPublicModel + `","messages":[{"role":"user","content":"hi"}],"stream":false}` + req := httptest.NewRequest(http.MethodPost, "/v1/chat/completions", strings.NewReader(requestBody)) + req.Header.Set("Content-Type", "application/json") + w := httptest.NewRecorder() + + router.ServeHTTP(w, req) + + captured := upstream.snapshot() + require.NotEmpty(t, captured, + "composite CC request must be forwarded to an upstream, got status=%d body=%s", w.Code, w.Body.String()) + + expectedModelByHost := map[string]string{ + "deepseek-composite-fake.test": "deepseek-chat", + "opencode-composite-fake.test": "deepseek-v4", + } + for _, request := range captured { + require.NotContainsf(t, request.path, "/messages", + "composite chat completions must never be dispatched through the Anthropic messages bridge (account=%d url=%s model=%s)", + request.accountID, request.url, request.model) + // 精确相等而非后缀匹配:两个 fake base 均以 /v1 结尾,后缀匹配放得过 + // /v1/v1/chat/completions 这类重复版本段拼接。 + require.Equalf(t, "/v1/chat/completions", request.path, + "outbound must hit the OpenAI-compatible chat completions endpoint exactly once-versioned (account=%d url=%s)", request.accountID, request.url) + expectedModel, knownHost := expectedModelByHost[request.host] + require.Truef(t, knownHost, "outbound must only hit the fake composite upstreams (url=%s)", request.url) + require.Equalf(t, expectedModel, request.model, + "outbound body.model must be the selected account's model_mapping target (account=%d url=%s)", request.accountID, request.url) + } + require.Equal(t, http.StatusOK, w.Code, w.Body.String()) +} diff --git a/backend/internal/server/routes/gateway_composite_pool_attempt_policy_test.go b/backend/internal/server/routes/gateway_composite_pool_attempt_policy_test.go new file mode 100644 index 0000000000..71c7cdc031 --- /dev/null +++ b/backend/internal/server/routes/gateway_composite_pool_attempt_policy_test.go @@ -0,0 +1,824 @@ +//go:build unit + +package routes + +// composite 账号池 per-attempt 平台策略(审查修复增量4)的 handler 级回归: +// 经真实 RegisterGatewayRoutes + fake upstream 验证 +// 1. 渠道限制拒绝选中平台时不发付费外呼,普通请求 mask 后换其他平台; +// 2. 平台配额耗尽时不发往该平台,成功请求只向实际选中平台计量配额; +// 3. RPM 每请求只按准入计一次(policy deny 重选不重复计数); +// 4. 公开模型 → 选中平台渠道映射 → 账号 model_mapping 的顺序按 attempt 独立; +// 5. pinned(previous_response_id 命中状态归属)请求遭配额拒绝时返回原 policy +// 错误(429+Retry-After)、不外呼、不换账号、不删除绑定。 +// 出站经 HTTPUpstream 桩捕获,不发起真实网络请求。 + +import ( + "context" + "fmt" + "io" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/Wei-Shaw/sub2api/internal/handler" + "github.com/Wei-Shaw/sub2api/internal/pkg/tlsfingerprint" + servermiddleware "github.com/Wei-Shaw/sub2api/internal/server/middleware" + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" +) + +const ( + attemptPolicyGroupID = int64(4330) + attemptPolicyUserID = int64(4331) + attemptPolicyAPIKey = int64(4332) +) + +// ── fakes ──────────────────────────────────────────────────────────────────── + +type attemptPolicyCapturedRequest struct { + accountID int64 + host string + path string + body []byte +} + +// attemptPolicyUpstream 捕获出站请求并按 host 注入可配置失败。 +type attemptPolicyUpstream struct { + service.HTTPUpstream + + mu sync.Mutex + captured []attemptPolicyCapturedRequest + failHost map[string]bool +} + +func (u *attemptPolicyUpstream) capture(req *http.Request, accountID int64) []byte { + var body []byte + if req.Body != nil { + body, _ = io.ReadAll(req.Body) + } + u.mu.Lock() + u.captured = append(u.captured, attemptPolicyCapturedRequest{accountID: accountID, host: req.URL.Hostname(), path: req.URL.Path, body: body}) + u.mu.Unlock() + return body +} + +func (u *attemptPolicyUpstream) snapshot() []attemptPolicyCapturedRequest { + u.mu.Lock() + defer u.mu.Unlock() + return append([]attemptPolicyCapturedRequest(nil), u.captured...) +} + +func (u *attemptPolicyUpstream) hosts() []string { + snapshot := u.snapshot() + hosts := make([]string, 0, len(snapshot)) + for _, item := range snapshot { + hosts = append(hosts, item.host) + } + return hosts +} + +func (u *attemptPolicyUpstream) respondFor(req *http.Request, body []byte) *http.Response { + if u.failHost[req.URL.Hostname()] { + return &http.Response{ + StatusCode: http.StatusTooManyRequests, + Header: http.Header{"Content-Type": []string{"application/json"}, "Retry-After": []string{"60"}}, + Body: io.NopCloser(strings.NewReader(`{"error":{"message":"rate limited"}}`)), + } + } + if strings.Contains(req.URL.Path, "/responses") { + // 原生 Responses 上游:stream=true 回最小 completed SSE;stream=false 回 + // Responses JSON 对象(含 id,供响应→账号绑定与 usage 解析)。 + if gjson.GetBytes(body, "stream").Bool() { + sse := "event: response.completed\n" + + `data: {"type":"response.completed","response":{"id":"resp_pin","object":"response","status":"completed","model":"deepseek-chat","output":[],"usage":{"input_tokens":200000,"output_tokens":100000,"total_tokens":300000}}}` + "\n\n" + return compositeDispatchResponse("text/event-stream", sse) + } + return compositeDispatchResponse("application/json", + `{"id":"resp_pin","object":"response","status":"completed","model":"deepseek-chat","output":[],"usage":{"input_tokens":200000,"output_tokens":100000,"total_tokens":300000}}`) + } + return compositeDispatchResponse("application/json", `{"id":"resp_pin","object":"chat.completion","model":"deepseek-chat","choices":[{"index":0,"message":{"role":"assistant","content":"ok"},"finish_reason":"stop"}],"usage":{"prompt_tokens":200000,"completion_tokens":100000,"total_tokens":300000}}`) +} + +func (u *attemptPolicyUpstream) Do(req *http.Request, _ string, accountID int64, _ int) (*http.Response, error) { + body := u.capture(req, accountID) + return u.respondFor(req, body), nil +} + +func (u *attemptPolicyUpstream) DoWithTLS(req *http.Request, _ string, accountID int64, _ int, _ *tlsfingerprint.Profile) (*http.Response, error) { + body := u.capture(req, accountID) + return u.respondFor(req, body), nil +} + +// attemptPolicyQuotaCache 平台可感知的 user×platform 配额缓存:entries 缺席视为 +// MISS(DB fail-open 放行),incrPlatforms 记录每次配额累加的平台维度。 +type attemptPolicyQuotaCache struct { + service.BillingCache + + mu sync.Mutex + entries map[string]*service.UserPlatformQuotaCacheEntry + incrPlatform []string +} + +func (f *attemptPolicyQuotaCache) GetUserBalance(context.Context, int64) (float64, error) { + return 100.0, nil +} + +func (f *attemptPolicyQuotaCache) InvalidateUserBalance(context.Context, int64) error { return nil } + +func (f *attemptPolicyQuotaCache) GetUserPlatformQuotaCache(_ context.Context, _ int64, platform string) (*service.UserPlatformQuotaCacheEntry, bool, error) { + f.mu.Lock() + defer f.mu.Unlock() + entry, ok := f.entries[platform] + return entry, ok, nil +} + +func (f *attemptPolicyQuotaCache) SetUserPlatformQuotaCache(context.Context, int64, string, *service.UserPlatformQuotaCacheEntry, time.Duration) error { + return nil +} + +func (f *attemptPolicyQuotaCache) IncrUserPlatformQuotaUsageCache(_ context.Context, _ int64, platform string, _ float64, _ time.Duration, _ bool) error { + f.mu.Lock() + defer f.mu.Unlock() + f.incrPlatform = append(f.incrPlatform, platform) + return nil +} + +func (f *attemptPolicyQuotaCache) setEntry(platform string, entry *service.UserPlatformQuotaCacheEntry) { + f.mu.Lock() + defer f.mu.Unlock() + if entry == nil { + delete(f.entries, platform) + return + } + f.entries[platform] = entry +} + +func (f *attemptPolicyQuotaCache) incrSnapshot() []string { + f.mu.Lock() + defer f.mu.Unlock() + return append([]string(nil), f.incrPlatform...) +} + +func exhaustedAttemptPolicyEntry(now time.Time) *service.UserPlatformQuotaCacheEntry { + zero := 0.0 + return &service.UserPlatformQuotaCacheEntry{ + DailyUsageUSD: 0, + DailyLimitUSD: &zero, + DailyWindowStart: &now, + SchemaVersion: service.UserPlatformQuotaCacheSchemaV1, + } +} + +func allowedAttemptPolicyEntry(now time.Time) *service.UserPlatformQuotaCacheEntry { + limit := 5.0 + return &service.UserPlatformQuotaCacheEntry{ + DailyUsageUSD: 0, + DailyLimitUSD: &limit, + DailyWindowStart: &now, + SchemaVersion: service.UserPlatformQuotaCacheSchemaV1, + } +} + +// attemptPolicyRPMCache 记录 RPM 递增次数:policy deny 重选不得重复计数。 +type attemptPolicyRPMCache struct { + service.UserRPMCache + + mu sync.Mutex + group int + user int +} + +func (f *attemptPolicyRPMCache) IncrementUserGroupRPM(context.Context, int64, int64) (int, error) { + f.mu.Lock() + defer f.mu.Unlock() + f.group++ + return f.group, nil +} + +func (f *attemptPolicyRPMCache) IncrementUserRPM(context.Context, int64) (int, error) { + f.mu.Lock() + defer f.mu.Unlock() + f.user++ + return f.user, nil +} + +func (f *attemptPolicyRPMCache) total() int { + f.mu.Lock() + defer f.mu.Unlock() + return f.group + f.user +} + +type attemptPolicyUserRepo struct { + service.UserRepository + + mu sync.Mutex + deductCalls int +} + +func (f *attemptPolicyUserRepo) DeductBalance(context.Context, int64, float64) error { + f.mu.Lock() + defer f.mu.Unlock() + f.deductCalls++ + return nil +} + +// attemptPolicyStickyCache 带计数器的进程内 sticky 会话缓存:验证 policy deny +// masked 重选不会清掉原 sticky 绑定(DeleteSessionAccountID 零调用)。 +type attemptPolicyStickyCache struct { + service.GatewayCache + + mu sync.Mutex + bindings map[string]int64 + setCnt int + deleteCnt int +} + +func newAttemptPolicyStickyCache() *attemptPolicyStickyCache { + return &attemptPolicyStickyCache{bindings: make(map[string]int64)} +} + +func (c *attemptPolicyStickyCache) GetSessionAccountID(_ context.Context, groupID int64, sessionHash string) (int64, error) { + c.mu.Lock() + defer c.mu.Unlock() + id, ok := c.bindings[fmt.Sprintf("%d:%s", groupID, sessionHash)] + if !ok { + return 0, service.ErrStickySessionNotFound + } + return id, nil +} + +func (c *attemptPolicyStickyCache) SetSessionAccountID(_ context.Context, groupID int64, sessionHash string, accountID int64, _ time.Duration) error { + c.mu.Lock() + defer c.mu.Unlock() + c.setCnt++ + c.bindings[fmt.Sprintf("%d:%s", groupID, sessionHash)] = accountID + return nil +} + +func (c *attemptPolicyStickyCache) RefreshSessionTTL(context.Context, int64, string, time.Duration) error { + return nil +} + +func (c *attemptPolicyStickyCache) DeleteSessionAccountID(_ context.Context, groupID int64, sessionHash string) error { + c.mu.Lock() + defer c.mu.Unlock() + c.deleteCnt++ + delete(c.bindings, fmt.Sprintf("%d:%s", groupID, sessionHash)) + return nil +} + +func (c *attemptPolicyStickyCache) SetGrokVideoPendingBilling(context.Context, string, []byte, time.Duration) error { + return nil +} + +func (c *attemptPolicyStickyCache) GetGrokVideoPendingBilling(context.Context, string) ([]byte, error) { + return nil, nil +} + +func (c *attemptPolicyStickyCache) ClaimGrokVideoBilled(context.Context, string, time.Duration) (bool, error) { + return true, nil +} + +func (c *attemptPolicyStickyCache) ReleaseGrokVideoBilled(context.Context, string) error { + return nil +} + +func (c *attemptPolicyStickyCache) SetReasoningContent(context.Context, string, string, time.Duration) error { + return nil +} + +func (c *attemptPolicyStickyCache) GetReasoningContent(context.Context, string) (string, error) { + return "", nil +} + +func (c *attemptPolicyStickyCache) snapshot() (map[string]int64, int, int) { + c.mu.Lock() + defer c.mu.Unlock() + out := make(map[string]int64, len(c.bindings)) + for key, value := range c.bindings { + out[key] = value + } + return out, c.setCnt, c.deleteCnt +} + +type attemptPolicyQuotaRepo struct { + service.UserPlatformQuotaRepository +} + +func (f *attemptPolicyQuotaRepo) GetByUserPlatform(context.Context, int64, string) (*service.UserPlatformQuotaRecord, error) { + return nil, nil +} + +type attemptPolicyChannelRepo struct { + service.ChannelRepository + channels []service.Channel + platforms map[int64]string +} + +func (f *attemptPolicyChannelRepo) ListAll(context.Context) ([]service.Channel, error) { + return f.channels, nil +} + +func (f *attemptPolicyChannelRepo) GetGroupPlatforms(context.Context, []int64) (map[int64]string, error) { + return f.platforms, nil +} + +// ── fixtures ───────────────────────────────────────────────────────────────── + +func newAttemptPolicyAccount(id int64, platform string, priority int, modelMapping map[string]any) service.Account { + credentials := map[string]any{ + "api_key": "test-key-" + platform, + "base_url": "https://" + platform + "-pool-fake.test/v1", + } + if modelMapping != nil { + credentials["model_mapping"] = modelMapping + } + return service.Account{ + ID: id, Name: "pool-" + platform, + Platform: platform, Type: service.AccountTypeAPIKey, + Status: service.StatusActive, Schedulable: true, Concurrency: 4, Priority: priority, + Credentials: credentials, + GroupIDs: []int64{attemptPolicyGroupID}, + AccountGroups: []service.AccountGroup{ + {AccountID: id, GroupID: attemptPolicyGroupID, Priority: 1}, + }, + } +} + +type attemptPolicyRouterInput struct { + accounts []service.Account + quotaCache *attemptPolicyQuotaCache + rpmCache *attemptPolicyRPMCache + upstream *attemptPolicyUpstream + channel *service.Channel + userRepo *attemptPolicyUserRepo + stickyCache *attemptPolicyStickyCache + groupMutate func(group *service.Group) +} + +func newCompositePoolAttemptPolicyRouter(t *testing.T, in attemptPolicyRouterInput) *gin.Engine { + t.Helper() + gin.SetMode(gin.TestMode) + + if in.quotaCache == nil { + in.quotaCache = &attemptPolicyQuotaCache{entries: map[string]*service.UserPlatformQuotaCacheEntry{}} + } + if in.upstream == nil { + in.upstream = &attemptPolicyUpstream{} + } + if in.stickyCache == nil { + in.stickyCache = newAttemptPolicyStickyCache() + } + if in.userRepo == nil { + in.userRepo = &attemptPolicyUserRepo{} + } + + cfg := &config.Config{RunMode: config.RunModeStandard} + cfg.Default.RateMultiplier = 1 + cfg.Gateway.MaxBodySize = 1024 * 1024 + cfg.Gateway.TextMaxBodySize = 1024 * 1024 + cfg.Gateway.MaxAccountSwitches = 3 + cfg.Security.URLAllowlist.AllowInsecureHTTP = true + + repo := &compositeDispatchAccountRepo{accounts: in.accounts} + group := &service.Group{ + ID: attemptPolicyGroupID, + Platform: service.PlatformComposite, + Status: service.StatusActive, + RateMultiplier: 1, + } + if in.groupMutate != nil { + in.groupMutate(group) + } + groupRepo := &compositeDispatchGroupRepo{group: group} + + var channelSvc *service.ChannelService + if in.channel != nil { + channelSvc = service.NewChannelService(&attemptPolicyChannelRepo{ + channels: []service.Channel{*in.channel}, + platforms: map[int64]string{attemptPolicyGroupID: service.PlatformComposite}, + }, nil, nil, nil, nil) + } + + billingService := service.NewBillingService(cfg, nil) + pricingResolver := service.NewModelPricingResolver(nil, billingService) + billingCache := service.NewBillingCacheService( + in.quotaCache, nil, nil, nil, in.rpmCache, nil, cfg, &attemptPolicyQuotaRepo{}) + concurrencyService := service.NewConcurrencyService(&compositeDispatchConcurrencyCache{}) + deferred := &service.DeferredService{} + + compositeResolver := service.NewCompositeRouteResolver(nil) + + genericGateway := service.NewGatewayService( + repo, groupRepo, nil, nil, nil, nil, nil, nil, cfg, nil, + concurrencyService, billingService, nil, billingCache, nil, + in.upstream, deferred, nil, nil, nil, nil, nil, nil, channelSvc, nil, + compositeResolver, nil, nil, + ) + openAIGateway := service.NewOpenAIGatewayService( + repo, nil, nil, in.userRepo, nil, nil, in.stickyCache, cfg, nil, concurrencyService, + billingService, nil, billingCache, in.upstream, deferred, + nil, nil, pricingResolver, channelSvc, nil, nil, &attemptPolicyQuotaRepo{}, + ) + + handlers := &handler.Handlers{ + Gateway: handler.NewGatewayHandler( + genericGateway, nil, nil, nil, nil, + concurrencyService, billingCache, nil, nil, nil, nil, nil, nil, + cfg, nil, + ), + OpenAIGateway: handler.NewOpenAIGatewayHandler( + openAIGateway, concurrencyService, billingCache, &service.APIKeyService{}, + nil, nil, nil, nil, cfg, + ), + AsyncImage: handler.NewAsyncImageHandler(nil, nil), + } + + router := gin.New() + RegisterGatewayRoutes( + router, + handlers, + servermiddleware.APIKeyAuthMiddleware(func(c *gin.Context) { + groupID := group.ID + c.Set(string(servermiddleware.ContextKeyAPIKey), &service.APIKey{ + ID: attemptPolicyAPIKey, + GroupID: &groupID, + User: &service.User{ID: attemptPolicyUserID, Status: service.StatusActive}, + Group: group, + }) + c.Set(string(servermiddleware.ContextKeyUser), servermiddleware.AuthSubject{UserID: attemptPolicyUserID, Concurrency: 1}) + c.Next() + }), + nil, + nil, + nil, + nil, + compositeResolver, + cfg, + ) + return router +} + +func postAttemptPolicyRequest(t *testing.T, router *gin.Engine, path, body string) *httptest.ResponseRecorder { + t.Helper() + req := httptest.NewRequest(http.MethodPost, path, strings.NewReader(body)) + req.Header.Set("Content-Type", "application/json") + w := httptest.NewRecorder() + router.ServeHTTP(w, req) + return w +} + +// ── 1) 渠道限制拒绝选中平台 → 不付费外呼该平台,mask 后换其他平台 ──────────── +func TestCompositePoolAttemptPolicyChannelRestrictionSwitchesPlatform(t *testing.T) { + now := time.Now().UTC() + quotaCache := &attemptPolicyQuotaCache{entries: map[string]*service.UserPlatformQuotaCacheEntry{ + service.PlatformDeepseek: allowedAttemptPolicyEntry(now), + service.PlatformOpenAI: allowedAttemptPolicyEntry(now), + }} + upstream := &attemptPolicyUpstream{} + // 渠道只把 deepseek-flash 列入 openai 平台允许定价;deepseek 平台无任何 + // 定价行 → RestrictModels 下 deepseek 平台对该模型受限。 + channel := &service.Channel{ + ID: 1, + Status: service.StatusActive, + GroupIDs: []int64{attemptPolicyGroupID}, + RestrictModels: true, + BillingModelSource: service.BillingModelSourceRequested, + ModelPricing: []service.ChannelModelPricing{ + {Platform: service.PlatformOpenAI, Models: []string{"deepseek-flash"}}, + }, + } + router := newCompositePoolAttemptPolicyRouter(t, attemptPolicyRouterInput{ + accounts: []service.Account{ + newAttemptPolicyAccount(4333, service.PlatformDeepseek, 1, map[string]any{"deepseek-flash": "deepseek-chat"}), + newAttemptPolicyAccount(4334, service.PlatformOpenAI, 2, map[string]any{"deepseek-flash": "deepseek-chat"}), + }, + quotaCache: quotaCache, + upstream: upstream, + channel: channel, + }) + + w := postAttemptPolicyRequest(t, router, "/v1/chat/completions", + `{"model":"deepseek-flash","messages":[{"role":"user","content":"hi"}],"stream":false}`) + + require.Equal(t, http.StatusOK, w.Code, w.Body.String()) + hosts := upstream.hosts() + require.NotEmpty(t, hosts) + for _, host := range hosts { + require.NotContains(t, host, "deepseek-pool-fake.test", + "channel-restricted platform must never receive the paid request") + require.Contains(t, host, "openai-pool-fake.test", + "request must be served by an allowed platform") + } +} + +// ── 2) 平台配额耗尽 → 不发往该平台;成功请求只对选中平台计量配额 ──────────── +func TestCompositePoolAttemptPolicyQuotaExhaustedSkipsPlatform(t *testing.T) { + now := time.Now().UTC() + quotaCache := &attemptPolicyQuotaCache{entries: map[string]*service.UserPlatformQuotaCacheEntry{ + service.PlatformOpenAI: exhaustedAttemptPolicyEntry(now), + service.PlatformDeepseek: allowedAttemptPolicyEntry(now), + }} + upstream := &attemptPolicyUpstream{} + userRepo := &attemptPolicyUserRepo{} + router := newCompositePoolAttemptPolicyRouter(t, attemptPolicyRouterInput{ + accounts: []service.Account{ + newAttemptPolicyAccount(4333, service.PlatformOpenAI, 1, map[string]any{"deepseek-flash": "deepseek-chat"}), + newAttemptPolicyAccount(4334, service.PlatformDeepseek, 2, map[string]any{"deepseek-flash": "deepseek-chat"}), + }, + quotaCache: quotaCache, + upstream: upstream, + userRepo: userRepo, + }) + + w := postAttemptPolicyRequest(t, router, "/v1/chat/completions", + `{"model":"deepseek-flash","messages":[{"role":"user","content":"hi"}],"stream":false}`) + + require.Equal(t, http.StatusOK, w.Code, w.Body.String()) + for _, host := range upstream.hosts() { + require.NotContains(t, host, "openai-pool-fake.test", + "quota-exhausted platform must not receive the request") + } + require.NotEmpty(t, upstream.hosts(), "request must still be served by the healthy platform") + + incremented := quotaCache.incrSnapshot() + require.NotEmpty(t, incremented, "successful usage must increment the user×platform quota") + for _, platform := range incremented { + require.Equal(t, service.PlatformDeepseek, platform, + "quota must be deducted on the actually selected platform, never composite/openai default") + } +} + +// ── 3) RPM 只按准入计一次(policy deny 重选不重复计数) ─────────────────────── +func TestCompositePoolAttemptPolicyDenyDoesNotDoubleCountRPM(t *testing.T) { + now := time.Now().UTC() + quotaCache := &attemptPolicyQuotaCache{entries: map[string]*service.UserPlatformQuotaCacheEntry{ + service.PlatformDeepseek: allowedAttemptPolicyEntry(now), + service.PlatformOpenAI: allowedAttemptPolicyEntry(now), + }} + rpmCache := &attemptPolicyRPMCache{} + upstream := &attemptPolicyUpstream{} + channel := &service.Channel{ + ID: 1, + Status: service.StatusActive, + GroupIDs: []int64{attemptPolicyGroupID}, + RestrictModels: true, + BillingModelSource: service.BillingModelSourceRequested, + ModelPricing: []service.ChannelModelPricing{ + {Platform: service.PlatformOpenAI, Models: []string{"deepseek-flash"}}, + }, + } + router := newCompositePoolAttemptPolicyRouter(t, attemptPolicyRouterInput{ + accounts: []service.Account{ + newAttemptPolicyAccount(4333, service.PlatformDeepseek, 1, map[string]any{"deepseek-flash": "deepseek-chat"}), + newAttemptPolicyAccount(4334, service.PlatformOpenAI, 2, map[string]any{"deepseek-flash": "deepseek-chat"}), + }, + quotaCache: quotaCache, + rpmCache: rpmCache, + upstream: upstream, + channel: channel, + groupMutate: func(group *service.Group) { group.RPMLimit = 10 }, + }) + + w := postAttemptPolicyRequest(t, router, "/v1/chat/completions", + `{"model":"deepseek-flash","messages":[{"role":"user","content":"hi"}],"stream":false}`) + + require.Equal(t, http.StatusOK, w.Code, w.Body.String()) + require.Len(t, upstream.hosts(), 1, "failover via policy mask must end in exactly one paid attempt") + require.Equal(t, 1, rpmCache.total(), + "RPM must be counted once at admission; policy deny re-selection must not re-run CheckBillingEligibility") +} + +// ── 4) 公开模型 → 选中平台渠道映射 → 账号 mapping,按 attempt 独立 ─────────── +func TestCompositePoolAttemptPolicyMappingOrderPerAttempt(t *testing.T) { + now := time.Now().UTC() + quotaCache := &attemptPolicyQuotaCache{entries: map[string]*service.UserPlatformQuotaCacheEntry{ + service.PlatformDeepseek: allowedAttemptPolicyEntry(now), + service.PlatformOpenAI: allowedAttemptPolicyEntry(now), + }} + upstream := &attemptPolicyUpstream{failHost: map[string]bool{"deepseek-pool-fake.test": true}} + // 渠道映射只配置在 openai 平台行:deepseek-flash → deepseek-pro。 + channel := &service.Channel{ + ID: 1, + Status: service.StatusActive, + GroupIDs: []int64{attemptPolicyGroupID}, + BillingModelSource: service.BillingModelSourceRequested, + ModelMapping: map[string]map[string]string{ + service.PlatformOpenAI: {"deepseek-flash": "deepseek-pro"}, + }, + } + router := newCompositePoolAttemptPolicyRouter(t, attemptPolicyRouterInput{ + accounts: []service.Account{ + // deepseek 账号首跳上游失败 → failover;其账号映射 deepseek-flash→deepseek-chat。 + newAttemptPolicyAccount(4333, service.PlatformDeepseek, 1, map[string]any{"deepseek-flash": "deepseek-chat"}), + // openai 账号在渠道映射结果上再套账号映射 deepseek-pro→deepseek-final; + // identity key 保留 deepseek-flash 以通过池 claims 能力门。公开模型若 + // 被错误地先做账号映射会得到 "account-direct"(渠道行无该映射,保持 + // 原样),与正确顺序的 "deepseek-final" 可判别。 + newAttemptPolicyAccount(4334, service.PlatformOpenAI, 2, map[string]any{"deepseek-flash": "account-direct", "deepseek-pro": "deepseek-final"}), + }, + quotaCache: quotaCache, + upstream: upstream, + channel: channel, + }) + + w := postAttemptPolicyRequest(t, router, "/v1/chat/completions", + `{"model":"deepseek-flash","messages":[{"role":"user","content":"hi"}],"stream":false}`) + + require.Equal(t, http.StatusOK, w.Code, w.Body.String()) + captured := upstream.snapshot() + require.Len(t, captured, 2, "one attempt per platform after failover") + + byHost := make(map[string]attemptPolicyCapturedRequest, len(captured)) + for _, item := range captured { + byHost[item.host] = item + } + deepseekAttempt, ok := byHost["deepseek-pool-fake.test"] + require.True(t, ok, "deepseek account must be attempted first") + require.Equal(t, "deepseek-chat", gjson.GetBytes(deepseekAttempt.body, "model").String(), + "deepseek attempt must apply only its own account mapping (no cross-platform channel mapping)") + + openAIAttempt, ok := byHost["openai-pool-fake.test"] + require.True(t, ok, "failover must reach the openai account") + require.Equal(t, "deepseek-final", gjson.GetBytes(openAIAttempt.body, "model").String(), + "openai attempt must apply channel mapping (deepseek-flash→deepseek-pro) then account mapping (→deepseek-final)") +} + +// ── 5) pinned 请求遭平台配额拒绝:原 policy 错误、不外呼、不改绑定 ─────────── +func TestCompositePoolAttemptPolicyPinnedQuotaDeniedStaysOnOwner(t *testing.T) { + now := time.Now().UTC() + // owner 选 openai 平台账号(priority 1):openai 账号走原生 Responses 转发, + // 成功后 bindHTTPResponseAccount 落 response→account 与 owner 绑定。 + quotaCache := &attemptPolicyQuotaCache{entries: map[string]*service.UserPlatformQuotaCacheEntry{ + service.PlatformDeepseek: allowedAttemptPolicyEntry(now), + service.PlatformOpenAI: allowedAttemptPolicyEntry(now), + }} + upstream := &attemptPolicyUpstream{} + router := newCompositePoolAttemptPolicyRouter(t, attemptPolicyRouterInput{ + accounts: []service.Account{ + newAttemptPolicyAccount(4334, service.PlatformOpenAI, 1, map[string]any{"deepseek-flash": "deepseek-chat"}), + newAttemptPolicyAccount(4333, service.PlatformDeepseek, 2, map[string]any{"deepseek-flash": "deepseek-chat"}), + }, + quotaCache: quotaCache, + upstream: upstream, + }) + + // 请求 A:/v1/responses 成功 → 上游响应 id=resp_pin 绑定到 openai 账号。 + wA := postAttemptPolicyRequest(t, router, "/v1/responses", + `{"model":"deepseek-flash","input":"hi","prompt_cache_key":"sess-attempt-pin","stream":false}`) + require.Equal(t, http.StatusOK, wA.Code, wA.Body.String()) + capturedAfterA := len(upstream.snapshot()) + require.NotEmpty(t, upstream.hosts()) + + // 平台配额耗尽(openai 为状态归属平台)。 + quotaCache.setEntry(service.PlatformOpenAI, exhaustedAttemptPolicyEntry(now)) + + // 请求 B:同会话 + prevID 命中状态归属 → 配额拒绝必须以原 policy 错误终止: + // 429+Retry-After(非 400 掩盖),不外呼、不换账号、绑定不删。 + wB := postAttemptPolicyRequest(t, router, "/v1/responses", + `{"model":"deepseek-flash","input":"continue","prompt_cache_key":"sess-attempt-pin","previous_response_id":"resp_pin","stream":false}`) + require.Equal(t, http.StatusTooManyRequests, wB.Code, wB.Body.String()) + require.Contains(t, wB.Body.String(), "rate_limit_exceeded") + require.NotEmpty(t, wB.Header().Get("Retry-After")) + require.Len(t, upstream.snapshot(), capturedAfterA, "pinned quota denial must never reach the upstream") + + // 请求 C:配额恢复后同 prevID 仍服务 → 绑定未被删除且未跨账号。 + quotaCache.setEntry(service.PlatformOpenAI, allowedAttemptPolicyEntry(now)) + wC := postAttemptPolicyRequest(t, router, "/v1/responses", + `{"model":"deepseek-flash","input":"continue","prompt_cache_key":"sess-attempt-pin","previous_response_id":"resp_pin","stream":false}`) + require.Equal(t, http.StatusOK, wC.Code, wC.Body.String()) + require.Len(t, upstream.snapshot(), capturedAfterA+1) + lastHost := upstream.hosts()[len(upstream.hosts())-1] + require.Contains(t, lastHost, "openai-pool-fake.test", + "binding must stay on the owner platform after a pinned policy denial") +} + +// ── 6) policy deny masked 重选不清原 sticky 绑定 ───────────────────────────── +// deny 时同步 failedAccountIDs 排除该账号:下一轮 masked ctx 下 sticky 层对 +// excluded 账号提前返回(不 clear),DeleteSessionAccountID 零调用;其它平台 +// 成功后 sticky 按用户目标正常改绑(Set 覆盖,而非 Delete)。 +func TestCompositePoolAttemptPolicyDenyKeepsStickyBinding(t *testing.T) { + now := time.Now().UTC() + quotaCache := &attemptPolicyQuotaCache{entries: map[string]*service.UserPlatformQuotaCacheEntry{ + service.PlatformDeepseek: allowedAttemptPolicyEntry(now), + service.PlatformOpenAI: allowedAttemptPolicyEntry(now), + }} + upstream := &attemptPolicyUpstream{} + stickyCache := newAttemptPolicyStickyCache() + router := newCompositePoolAttemptPolicyRouter(t, attemptPolicyRouterInput{ + accounts: []service.Account{ + newAttemptPolicyAccount(4333, service.PlatformDeepseek, 1, map[string]any{"deepseek-flash": "deepseek-chat"}), + newAttemptPolicyAccount(4334, service.PlatformOpenAI, 2, map[string]any{"deepseek-flash": "deepseek-chat"}), + }, + quotaCache: quotaCache, + upstream: upstream, + stickyCache: stickyCache, + }) + + // 请求 1:session 建立粘性绑定(deepseek priority 1 命中)。 + w1 := postAttemptPolicyRequest(t, router, "/v1/chat/completions", + `{"model":"deepseek-flash","messages":[{"role":"user","content":"hi"}],"prompt_cache_key":"sess-ap-sticky","stream":false}`) + require.Equal(t, http.StatusOK, w1.Code, w1.Body.String()) + bindings1, setCnt1, deleteCnt1 := stickyCache.snapshot() + t.Logf("DEBUG sticky bindings after R1: %v set=%d delete=%d", bindings1, setCnt1, deleteCnt1) + require.GreaterOrEqual(t, setCnt1, 1, "session must establish a sticky binding") + require.Equal(t, 0, deleteCnt1) + require.NotEmpty(t, bindings1, "sticky binding must exist after the first request") + for _, accountID := range bindings1 { + require.Equal(t, int64(4333), accountID, "sticky binding must point at the first-served account") + } + + // deepseek 平台配额耗尽。 + quotaCache.setEntry(service.PlatformDeepseek, exhaustedAttemptPolicyEntry(now)) + hostsBefore := len(upstream.hosts()) + + // 请求 2:同 session → sticky 命中 deepseek → quota 预检拒绝 → mask 重选 + // openai 成功。全程不允许清除原 sticky 绑定。 + w2 := postAttemptPolicyRequest(t, router, "/v1/chat/completions", + `{"model":"deepseek-flash","messages":[{"role":"user","content":"hi"}],"prompt_cache_key":"sess-ap-sticky","stream":false}`) + require.Equal(t, http.StatusOK, w2.Code, w2.Body.String()) + for _, host := range upstream.hosts()[hostsBefore:] { + require.Contains(t, host, "openai-pool-fake.test", + "denied platform must not receive the request; failover must reach the healthy platform") + } + + bindings2, setCnt2, deleteCnt2 := stickyCache.snapshot() + require.Equal(t, 0, deleteCnt2, + "policy-deny mask re-selection must never delete the original sticky binding") + require.Equal(t, 1, len(bindings2), "the same session key must be re-pointed, not fanned out") + for _, accountID := range bindings2 { + require.Equal(t, int64(4334), accountID, + "sticky binding must be re-pointed to the successfully served account via Set (not Delete+re-add churn)") + } + require.Greater(t, setCnt2, setCnt1) +} + +// ── 7) 兄弟账号同平台:sticky X、deny 落平台后 Y 不外呼、Z 接管、delKeys=0 ──── +// 复审 A 场景:池含 X/Y(deepseek)+Z(opencode),sticky 绑 X;deepseek 平台被 +// policy deny 后 masked 重选里 sticky X 与兄弟 Y 都不得被平台失配清绑定, +// 整个 deepseek 平台零外呼,Z 接管后 sticky 经正常 Set 改绑 Z。 +func TestCompositePoolAttemptPolicyDenyWithSiblingAccountsKeepsBinding(t *testing.T) { + now := time.Now().UTC() + quotaCache := &attemptPolicyQuotaCache{entries: map[string]*service.UserPlatformQuotaCacheEntry{ + service.PlatformDeepseek: allowedAttemptPolicyEntry(now), + service.PlatformOpenAI: allowedAttemptPolicyEntry(now), + service.PlatformOpenCodeGo: allowedAttemptPolicyEntry(now), + }} + upstream := &attemptPolicyUpstream{} + stickyCache := newAttemptPolicyStickyCache() + router := newCompositePoolAttemptPolicyRouter(t, attemptPolicyRouterInput{ + accounts: []service.Account{ + newAttemptPolicyAccount(4333, service.PlatformDeepseek, 1, map[string]any{"deepseek-flash": "deepseek-chat"}), + newAttemptPolicyAccount(4335, service.PlatformDeepseek, 2, map[string]any{"deepseek-flash": "deepseek-chat"}), + newAttemptPolicyAccount(4336, service.PlatformOpenCodeGo, 3, map[string]any{"deepseek-flash": "deepseek-chat"}), + }, + quotaCache: quotaCache, + upstream: upstream, + stickyCache: stickyCache, + }) + + // 请求 1:session 绑定 X(deepseek priority 1)。 + w1 := postAttemptPolicyRequest(t, router, "/v1/chat/completions", + `{"model":"deepseek-flash","messages":[{"role":"user","content":"hi"}],"prompt_cache_key":"sess-ap-sibling","stream":false}`) + require.Equal(t, http.StatusOK, w1.Code, w1.Body.String()) + bindings1, _, deleteCnt1 := stickyCache.snapshot() + require.Equal(t, 0, deleteCnt1) + require.Len(t, bindings1, 1) + for _, accountID := range bindings1 { + require.Equal(t, int64(4333), accountID, "session must bind the first-served deepseek account X") + } + + // deepseek 平台配额耗尽(X/Y 所在平台整体被 deny)。 + quotaCache.setEntry(service.PlatformDeepseek, exhaustedAttemptPolicyEntry(now)) + hostsBefore := len(upstream.hosts()) + + // 请求 2:同 session → sticky X 命中 → deepseek quota 拒绝 → masked 重选: + // X/Y 同平台均不外呼、绑定不清,Z(opencode)接管成功。 + w2 := postAttemptPolicyRequest(t, router, "/v1/chat/completions", + `{"model":"deepseek-flash","messages":[{"role":"user","content":"hi"}],"prompt_cache_key":"sess-ap-sibling","stream":false}`) + require.Equal(t, http.StatusOK, w2.Code, w2.Body.String()) + hostsR2 := upstream.hosts()[hostsBefore:] + require.NotEmpty(t, hostsR2) + for _, host := range hostsR2 { + require.NotContains(t, host, "deepseek-pool-fake.test", + "sibling deepseek accounts must never receive the request after the platform denial") + require.Contains(t, host, "opencode_go-pool-fake.test", + "request must be served by the remaining healthy platform") + } + + // 零 delete;成功后 sticky 经 Set 正常改绑 Z。 + _, _, deleteCnt2 := stickyCache.snapshot() + require.Equal(t, 0, deleteCnt2, "no sticky binding may be deleted by the temporary platform denial") + bindings2, _, _ := stickyCache.snapshot() + require.Len(t, bindings2, 1) + for _, accountID := range bindings2 { + require.Equal(t, int64(4336), accountID, + "after a successful take-over the sticky binding is updated normally via Set") + } +} diff --git a/backend/internal/server/routes/gateway_composite_pool_policy_test.go b/backend/internal/server/routes/gateway_composite_pool_policy_test.go new file mode 100644 index 0000000000..6367af9e6c --- /dev/null +++ b/backend/internal/server/routes/gateway_composite_pool_policy_test.go @@ -0,0 +1,611 @@ +//go:build unit + +package routes + +// composite 账号池 handler 级守卫测试:经真实 RegisterGatewayRoutes 链路验证 +// 1) previous_response_id 状态归属守卫(owner 合法但调度未命中 pin 时明确拒绝、 +// 不外呼、selector 预占槽位恰一次释放);2) reasoning-effort deny 早退同样 +// 恰一次释放;3) 非 pool 请求携带已归属 prevID 保持既有转发行为;4) 池策略 +// cap 按 attempt 应用、failover 跨平台不泄漏。出站经 HTTPUpstream 桩捕获, +// 不发起真实网络请求。 + +import ( + "context" + "fmt" + "io" + "net/http" + "net/http/httptest" + "strings" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/Wei-Shaw/sub2api/internal/handler" + "github.com/Wei-Shaw/sub2api/internal/pkg/tlsfingerprint" + servermiddleware "github.com/Wei-Shaw/sub2api/internal/server/middleware" + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" +) + +// countingConcurrencyCache 在 RED fixture 的放行语义上为账号槽位加计数, +// 用于断言守卫早退对 selector 已持有槽位的恰一次释放。 +type countingConcurrencyCache struct { + service.ConcurrencyCache + + acquireAccountCalls atomic.Int64 + releaseAccountCalls atomic.Int64 +} + +func (m *countingConcurrencyCache) AcquireUserSlot(context.Context, int64, int, string) (bool, error) { + return true, nil +} + +func (m *countingConcurrencyCache) ReleaseUserSlot(context.Context, int64, string) error { + return nil +} + +func (m *countingConcurrencyCache) AcquireAccountSlot(_ context.Context, _ int64, _ int, _ string) (bool, error) { + m.acquireAccountCalls.Add(1) + return true, nil +} + +func (m *countingConcurrencyCache) ReleaseAccountSlot(_ context.Context, _ int64, _ string) error { + m.releaseAccountCalls.Add(1) + return nil +} + +func (m *countingConcurrencyCache) GetAccountConcurrency(context.Context, int64) (int, error) { + return 0, nil +} + +func (m *countingConcurrencyCache) GetAccountConcurrencyBatch(_ context.Context, accountIDs []int64) (map[int64]int, error) { + result := make(map[int64]int, len(accountIDs)) + for _, id := range accountIDs { + result[id] = 0 + } + return result, nil +} + +func (m *countingConcurrencyCache) IncrementAccountWaitCount(context.Context, int64, int) (bool, error) { + return true, nil +} + +func (m *countingConcurrencyCache) DecrementAccountWaitCount(context.Context, int64) error { + return nil +} + +func (m *countingConcurrencyCache) GetAccountWaitingCount(context.Context, int64) (int, error) { + return 0, nil +} + +func (m *countingConcurrencyCache) IncrementWaitCount(context.Context, int64, int) (bool, error) { + return true, nil +} + +func (m *countingConcurrencyCache) DecrementWaitCount(context.Context, int64) error { + return nil +} + +func (m *countingConcurrencyCache) GetUserConcurrency(context.Context, int64) (int, error) { + return 0, nil +} + +// stickyMemoryGatewayCache 提供进程内粘性会话绑定,驱动 scheduler 的 +// session-sticky 预占槽位路径(Acquired=true + ReleaseFunc)。 +type stickyMemoryGatewayCache struct { + mu sync.Mutex + bindings map[string]int64 + bindingKey func(groupID int64, sessionHash string) string +} + +func newStickyMemoryGatewayCache() *stickyMemoryGatewayCache { + return &stickyMemoryGatewayCache{bindings: make(map[string]int64)} +} + +func (c *stickyMemoryGatewayCache) key(groupID int64, sessionHash string) string { + return fmt.Sprintf("%d:%s", groupID, sessionHash) +} + +func (c *stickyMemoryGatewayCache) GetSessionAccountID(_ context.Context, groupID int64, sessionHash string) (int64, error) { + c.mu.Lock() + defer c.mu.Unlock() + id, ok := c.bindings[c.key(groupID, sessionHash)] + if !ok { + return 0, service.ErrStickySessionNotFound + } + return id, nil +} + +func (c *stickyMemoryGatewayCache) SetSessionAccountID(_ context.Context, groupID int64, sessionHash string, accountID int64, _ time.Duration) error { + c.mu.Lock() + defer c.mu.Unlock() + c.bindings[c.key(groupID, sessionHash)] = accountID + return nil +} + +func (c *stickyMemoryGatewayCache) RefreshSessionTTL(context.Context, int64, string, time.Duration) error { + return nil +} + +func (c *stickyMemoryGatewayCache) DeleteSessionAccountID(_ context.Context, groupID int64, sessionHash string) error { + c.mu.Lock() + defer c.mu.Unlock() + delete(c.bindings, c.key(groupID, sessionHash)) + return nil +} + +func (c *stickyMemoryGatewayCache) SetGrokVideoPendingBilling(context.Context, string, []byte, time.Duration) error { + return nil +} + +func (c *stickyMemoryGatewayCache) GetGrokVideoPendingBilling(context.Context, string) ([]byte, error) { + return nil, nil +} + +func (c *stickyMemoryGatewayCache) ClaimGrokVideoBilled(context.Context, string, time.Duration) (bool, error) { + return true, nil +} + +func (c *stickyMemoryGatewayCache) ReleaseGrokVideoBilled(context.Context, string) error { + return nil +} + +func (c *stickyMemoryGatewayCache) SetReasoningContent(context.Context, string, string, time.Duration) error { + return nil +} + +func (c *stickyMemoryGatewayCache) GetReasoningContent(context.Context, string) (string, error) { + return "", nil +} + +type poolPolicyCapturedRequest struct { + accountID int64 + host string + body []byte +} + +// captureUpstream 捕获出站请求(原始 body),并按 host 注入可配置失败以驱动 +// failover;openai 平台账号经 Responses 协议转发,返回最小 completed SSE。 +type captureUpstream struct { + service.HTTPUpstream + + mu sync.Mutex + captured []poolPolicyCapturedRequest + failHost map[string]bool +} + +func (u *captureUpstream) capture(req *http.Request, accountID int64) []byte { + var body []byte + if req.Body != nil { + body, _ = io.ReadAll(req.Body) + } + u.mu.Lock() + u.captured = append(u.captured, poolPolicyCapturedRequest{ + accountID: accountID, + host: req.URL.Hostname(), + body: body, + }) + u.mu.Unlock() + return body +} + +func (u *captureUpstream) capturedSnapshot() []poolPolicyCapturedRequest { + u.mu.Lock() + defer u.mu.Unlock() + return append([]poolPolicyCapturedRequest(nil), u.captured...) +} + +func (u *captureUpstream) respondFor(req *http.Request) *http.Response { + if u.failHost[req.URL.Hostname()] { + return &http.Response{ + StatusCode: http.StatusTooManyRequests, + Header: http.Header{ + "Content-Type": []string{"application/json"}, + "Retry-After": []string{"60"}, + }, + Body: io.NopCloser(strings.NewReader(`{"error":{"message":"rate limited"}}`)), + } + } + if strings.Contains(req.URL.Path, "/responses") { + sse := "event: response.completed\n" + + `data: {"type":"response.completed","response":{"id":"resp_pool","object":"response","status":"completed","model":"deepseek-chat","output":[{"type":"message","role":"assistant","content":[{"type":"output_text","text":"ok"}]}],"usage":{"input_tokens":1,"output_tokens":1,"total_tokens":2}}}` + "\n\n" + return compositeDispatchResponse("text/event-stream", sse) + } + // id 使用 resp_ 前缀:生产 bindHTTPResponseAccount 会把该 id 绑定到选中 + // 账号,第二条请求的 previous_response_id 需通过 resp_* 形态校验。 + return compositeDispatchResponse("application/json", `{"id":"resp_pool_chat","object":"chat.completion","model":"deepseek-chat","choices":[{"index":0,"message":{"role":"assistant","content":"ok"},"finish_reason":"stop"}],"usage":{"prompt_tokens":1,"completion_tokens":1,"total_tokens":2}}`) +} + +func (u *captureUpstream) Do(req *http.Request, _ string, accountID int64, _ int) (*http.Response, error) { + u.capture(req, accountID) + return u.respondFor(req), nil +} + +func (u *captureUpstream) DoWithTLS(req *http.Request, _ string, accountID int64, _ int, _ *tlsfingerprint.Profile) (*http.Response, error) { + u.capture(req, accountID) + return u.respondFor(req), nil +} + +type poolPolicyRouterInput struct { + group *service.Group + accounts []service.Account + cache *countingConcurrencyCache + upstream *captureUpstream + apiKeyID int64 +} + +const ( + poolPolicyGroupID = int64(4210) + poolPolicyUserID = int64(4201) +) + +func newCompositePoolPolicyTestRouter(t *testing.T, in poolPolicyRouterInput) (*gin.Engine, *service.OpenAIGatewayService) { + t.Helper() + gin.SetMode(gin.TestMode) + + if in.cache == nil { + in.cache = &countingConcurrencyCache{} + } + if in.upstream == nil { + in.upstream = &captureUpstream{} + } + apiKeyID := in.apiKeyID + if apiKeyID == 0 { + apiKeyID = 4202 + } + repo := &compositeDispatchAccountRepo{accounts: in.accounts} + groupRepo := &compositeDispatchGroupRepo{group: in.group} + + compositeResolver := service.NewCompositeRouteResolver(nil) + + cfg := &config.Config{RunMode: config.RunModeSimple} + cfg.Gateway.MaxBodySize = 1024 * 1024 + cfg.Gateway.TextMaxBodySize = 1024 * 1024 + cfg.Gateway.MaxAccountSwitches = 3 + cfg.Security.URLAllowlist.AllowInsecureHTTP = true + + billingService := service.NewBillingService(cfg, nil) + billingCache := service.NewBillingCacheService(nil, nil, nil, nil, nil, nil, cfg, nil) + concurrencyService := service.NewConcurrencyService(in.cache) + deferred := &service.DeferredService{} + + genericGateway := service.NewGatewayService( + repo, groupRepo, nil, nil, nil, nil, nil, nil, cfg, nil, + concurrencyService, billingService, nil, billingCache, nil, + in.upstream, deferred, nil, nil, nil, nil, nil, nil, nil, nil, + compositeResolver, nil, nil, + ) + openAIGateway := service.NewOpenAIGatewayService( + repo, nil, nil, nil, nil, nil, newStickyMemoryGatewayCache(), cfg, nil, concurrencyService, + billingService, nil, billingCache, in.upstream, deferred, + nil, nil, nil, nil, nil, nil, nil, + ) + + handlers := &handler.Handlers{ + Gateway: handler.NewGatewayHandler( + genericGateway, nil, nil, nil, nil, + concurrencyService, billingCache, nil, nil, nil, nil, nil, nil, + cfg, nil, + ), + OpenAIGateway: handler.NewOpenAIGatewayHandler( + openAIGateway, concurrencyService, billingCache, &service.APIKeyService{}, + nil, nil, nil, nil, cfg, + ), + AsyncImage: handler.NewAsyncImageHandler(nil, nil), + } + + router := gin.New() + RegisterGatewayRoutes( + router, + handlers, + servermiddleware.APIKeyAuthMiddleware(func(c *gin.Context) { + groupID := in.group.ID + c.Set(string(servermiddleware.ContextKeyAPIKey), &service.APIKey{ + ID: apiKeyID, + GroupID: &groupID, + User: &service.User{ID: poolPolicyUserID, Status: service.StatusActive}, + Group: in.group, + }) + c.Set(string(servermiddleware.ContextKeyUser), servermiddleware.AuthSubject{UserID: poolPolicyUserID, Concurrency: 1}) + c.Next() + }), + nil, + nil, + nil, + nil, + compositeResolver, + cfg, + ) + return router, openAIGateway +} + +func newPoolPolicyGroup(mutate func(group *service.Group)) *service.Group { + group := &service.Group{ + ID: poolPolicyGroupID, + Platform: service.PlatformComposite, + Status: service.StatusActive, + } + if mutate != nil { + mutate(group) + } + return group +} + +func newPoolPolicyAccount(id int64, platform string, priority int) service.Account { + return newPoolPolicyAccountWithMapping(id, platform, priority, map[string]any{ + "deepseek-flash": "deepseek-chat", + }) +} + +func newPoolPolicyAccountWithMapping(id int64, platform string, priority int, mapping map[string]any) service.Account { + return service.Account{ + ID: id, Name: "pool-" + platform, + Platform: platform, Type: service.AccountTypeAPIKey, + Status: service.StatusActive, Schedulable: true, Concurrency: 4, Priority: priority, + Credentials: map[string]any{ + "api_key": "test-key-" + platform, + "base_url": "https://" + platform + "-pool-fake.test/v1", + "model_mapping": mapping, + }, + GroupIDs: []int64{poolPolicyGroupID}, + AccountGroups: []service.AccountGroup{{AccountID: id, GroupID: poolPolicyGroupID, Priority: 1}}, + } +} + +func postPoolPolicyRequest(t *testing.T, router *gin.Engine, path, body string) *httptest.ResponseRecorder { + t.Helper() + req := httptest.NewRequest(http.MethodPost, path, strings.NewReader(body)) + req.Header.Set("Content-Type", "application/json") + w := httptest.NewRecorder() + router.ServeHTTP(w, req) + return w +} + +// 池请求携带已归属本用户的 previous_response_id、调度未命中状态归属账号 +// (StickyPreviousHit=false)时:任何转发之前明确 400 拒绝,不外呼,sticky +// 层预占的账号槽位被恰一次释放。 +func TestCompositePoolPreviousResponseIDRejectsWithoutPin(t *testing.T) { + cache := &countingConcurrencyCache{} + upstream := &captureUpstream{} + group := newPoolPolicyGroup(nil) + router, openAIGateway := newCompositePoolPolicyTestRouter(t, poolPolicyRouterInput{ + group: group, + accounts: []service.Account{newPoolPolicyAccount(4211, service.PlatformOpenAI, 1), newPoolPolicyAccount(4212, service.PlatformDeepseek, 2)}, + cache: cache, + upstream: upstream, + }) + + // 请求 A(无 prevID,带 prompt_cache_key):建立 sticky 绑定。 + wA := postPoolPolicyRequest(t, router, "/v1/chat/completions", + `{"model":"deepseek-flash","messages":[{"role":"user","content":"hi"}],"prompt_cache_key":"sess-pool-guard","stream":false}`) + require.Equal(t, http.StatusOK, wA.Code, wA.Body.String()) + acquireAfterA := cache.acquireAccountCalls.Load() + + // 预绑定 response 归属(模拟该 prevID 属于本用户的历史响应)。 + require.NoError(t, openAIGateway.BindOpenAIHTTPResponseOwner(context.Background(), poolPolicyGroupID, "resp_owned", poolPolicyUserID, 4202)) + + // 请求 B(同会话 + prevID):未命中 pin → 拒绝且不外呼。 + wB := postPoolPolicyRequest(t, router, "/v1/responses", + `{"model":"deepseek-flash","input":"hi","prompt_cache_key":"sess-pool-guard","previous_response_id":"resp_owned","stream":false}`) + + require.Equal(t, http.StatusBadRequest, wB.Code, wB.Body.String()) + require.Contains(t, wB.Body.String(), "previous_response_id") + require.Equal(t, acquireAfterA, cache.acquireAccountCalls.Load()-1, + "request B must pre-acquire the account slot once via the sticky layer") + require.Equal(t, acquireAfterA+1, cache.releaseAccountCalls.Load(), + "guard must release the pre-acquired slot exactly once") +} + +// reasoning-effort deny 在账号选定后触发:403 拒绝、不外呼、sticky 层预占的 +// 槽位恰一次释放(不泄漏、不重复释放)。 +func TestCompositePoolReasoningPolicyDenyReleasesSelectorSlot(t *testing.T) { + cache := &countingConcurrencyCache{} + upstream := &captureUpstream{} + group := newPoolPolicyGroup(func(group *service.Group) { + group.ReasoningEffortMappings = []service.ReasoningEffortMapping{{From: "xhigh", To: "deny"}} + }) + router, _ := newCompositePoolPolicyTestRouter(t, poolPolicyRouterInput{ + group: group, + accounts: []service.Account{newPoolPolicyAccount(4211, service.PlatformOpenAI, 1), newPoolPolicyAccount(4212, service.PlatformDeepseek, 2)}, + cache: cache, + upstream: upstream, + }) + + // 请求 A:建立 sticky 绑定(无 deny 冲突的正常 effort)。 + wA := postPoolPolicyRequest(t, router, "/v1/chat/completions", + `{"model":"deepseek-flash","messages":[{"role":"user","content":"hi"}],"prompt_cache_key":"sess-pool-deny","reasoning_effort":"low","stream":false}`) + require.Equal(t, http.StatusOK, wA.Code, wA.Body.String()) + acquireAfterA := cache.acquireAccountCalls.Load() + releaseAfterA := cache.releaseAccountCalls.Load() + + // 请求 B:同会话 + deny effort → 选号预占后由策略守卫终止。 + wB := postPoolPolicyRequest(t, router, "/v1/chat/completions", + `{"model":"deepseek-flash","messages":[{"role":"user","content":"hi"}],"prompt_cache_key":"sess-pool-deny","reasoning_effort":"xhigh","stream":false}`) + + require.Equal(t, http.StatusForbidden, wB.Code, wB.Body.String()) + require.Equal(t, upstream.capturedSnapshot()[len(upstream.capturedSnapshot())-1].accountID != 0, true) + require.Equal(t, acquireAfterA+1, cache.acquireAccountCalls.Load(), + "request B must pre-acquire the account slot once via the sticky layer") + require.Equal(t, releaseAfterA+1, cache.releaseAccountCalls.Load(), + "deny path must release the pre-acquired slot exactly once") +} + +// 非 pool 请求(单一 openai 目标)携带已归属 prevID 保持既有转发行为,不受 +// 池状态守卫影响。 +func TestNonCompositePoolPreviousResponseIDStillForwards(t *testing.T) { + upstream := &captureUpstream{} + group := &service.Group{ID: poolPolicyGroupID, Platform: service.PlatformOpenAI, Status: service.StatusActive} + router, openAIGateway := newCompositePoolPolicyTestRouter(t, poolPolicyRouterInput{ + group: group, + accounts: []service.Account{newPoolPolicyAccount(4211, service.PlatformOpenAI, 1)}, + upstream: upstream, + }) + require.NoError(t, openAIGateway.BindOpenAIHTTPResponseOwner(context.Background(), poolPolicyGroupID, "resp_owned", poolPolicyUserID, 4202)) + + w := postPoolPolicyRequest(t, router, "/v1/responses", + `{"model":"deepseek-flash","input":"hi","previous_response_id":"resp_owned","stream":false}`) + + require.Equal(t, http.StatusOK, w.Code, w.Body.String()) + require.NotEmpty(t, upstream.capturedSnapshot(), "non-pool requests keep the existing prevID forwarding behavior") +} + +// 池策略 cap 按 attempt 应用:deepseek 账号首跳失败后 failover 到 openai, +// openai attempt 使用从 canonical body 新鲜 cap 的 medium——策略按 attempt +// 应用、canonical body 不被改写。 +func TestCompositePoolReasoningPolicyCapAppliedPerAttempt(t *testing.T) { + upstream := &captureUpstream{failHost: map[string]bool{ + "deepseek-pool-fake.test": true, + }} + group := newPoolPolicyGroup(func(group *service.Group) { + group.MaxReasoningEffort = "medium" + }) + router, _ := newCompositePoolPolicyTestRouter(t, poolPolicyRouterInput{ + group: group, + accounts: []service.Account{ + newPoolPolicyAccount(4211, service.PlatformDeepseek, 1), + newPoolPolicyAccount(4212, service.PlatformOpenAI, 2), + }, + upstream: upstream, + }) + + w := postPoolPolicyRequest(t, router, "/v1/chat/completions", + `{"model":"deepseek-flash","messages":[{"role":"user","content":"hi"}],"reasoning_effort":"xhigh","stream":false}`) + + require.Equal(t, http.StatusOK, w.Code, w.Body.String()) + + captured := upstream.capturedSnapshot() + require.Len(t, captured, 2, "one attempt per account after failover") + byHost := make(map[string]poolPolicyCapturedRequest, len(captured)) + for _, record := range captured { + byHost[record.host] = record + } + deepseekAttempt, ok := byHost["deepseek-pool-fake.test"] + require.True(t, ok, "deepseek account must be attempted first") + require.Equal(t, "xhigh", gjson.GetBytes(deepseekAttempt.body, "reasoning_effort").String(), + "non-openai attempt must keep the client effort uncapped") + openaiAttempt, ok := byHost["openai-pool-fake.test"] + require.True(t, ok, "failover must reach the openai account") + // openai 平台账号经 CC→Responses 协议转发,出站体为 reasoning.effort。 + require.Equal(t, "medium", gjson.GetBytes(openaiAttempt.body, "reasoning.effort").String(), + "openai attempt must carry the group-capped effort applied per attempt") +} + +// CN 账号真正的 previous_response pin(正向,依赖 2A 的 pool HTTP 资格门修复): +// 第一条用仅 CN 父账号 claim 的模型建立 resp→CN 绑定;第二条换新 session 种子 +// 并让另一候选优先级更高(排除了 same-session sticky 的解释),只有 +// previous_response_id 命中原 CN 账号才能选中它并转发。2A 修复前该用例 RED。 +func TestCompositePoolCNPreviousResponseIDPinBeatsPriorityAndSeed(t *testing.T) { + upstream := &captureUpstream{} + group := newPoolPolicyGroup(nil) + // kimi 优先级更高(p1):无 pin 时 load-balance 会选 kimi; + // deepseek(p2,native Responses)是 resp id 的归属账号。 + cnParent := newPoolPolicyAccountWithMapping(4211, service.PlatformDeepseek, 2, map[string]any{ + "deepseek-flash": "deepseek-chat", + "pool-model": "deepseek-chat", + }) + cnParent.Credentials["api_protocol"] = service.APIProtocolResponses + other := newPoolPolicyAccountWithMapping(4212, service.PlatformKimi, 1, map[string]any{ + "pool-model": "kimi-chat", + }) + router, _ := newCompositePoolPolicyTestRouter(t, poolPolicyRouterInput{ + group: group, + accounts: []service.Account{cnParent, other}, + upstream: upstream, + }) + + // 第一条:仅 deepseek claim 的模型 → 绑定 resp id → deepseek。 + wA := postPoolPolicyRequest(t, router, "/v1/responses", + `{"model":"deepseek-flash","input":"hi","prompt_cache_key":"sess-pin-a","stream":false}`) + require.Equal(t, http.StatusOK, wA.Code, wA.Body.String()) + capturedA := upstream.capturedSnapshot() + require.Len(t, capturedA, 1) + require.Equal(t, int64(4211), capturedA[0].accountID, "first request must be served by the CN parent account") + + responseID := gjson.GetBytes(wA.Body.Bytes(), "id").String() + require.True(t, strings.HasPrefix(responseID, "resp_"), "downstream response must carry a resp_* id, got %q", responseID) + + // 第二条:新 session 种子(sticky 不可命中)+ 双账号池模型 + kimi 优先级更高; + // 只有 previous_response_id 的真 pin 才能解释选中 deepseek。 + wB := postPoolPolicyRequest(t, router, "/v1/responses", + `{"model":"pool-model","input":"continue","prompt_cache_key":"sess-pin-b","previous_response_id":"`+responseID+`","stream":false}`) + + require.Equal(t, http.StatusOK, wB.Code, wB.Body.String()) + captured := upstream.capturedSnapshot() + require.Len(t, captured, 2) + require.Equal(t, int64(4211), captured[1].accountID, + "previous_response_id pin must select the owning CN account over the higher-priority candidate") + require.Equal(t, "deepseek-pool-fake.test", captured[1].host) +} + +// CN→CN 未 hit 跨账号转移必须拒绝:resp id 归属 deepseek,deepseek 首跳 429 +// failover 后选中另一 CN 候选(kimi)时,状态守卫在任何转发前 400 终止, +// kimi 不收到带旧 prevID 的请求(该用例在 2A 修复前后都必须保持绿)。 +func TestCompositePoolPreviousResponseIDRejectsCrossCNSelection(t *testing.T) { + upstream := &captureUpstream{} + group := newPoolPolicyGroup(nil) + cnParent := newPoolPolicyAccountWithMapping(4211, service.PlatformDeepseek, 1, map[string]any{ + "deepseek-flash": "deepseek-chat", + "pool-model": "deepseek-chat", + }) + cnParent.Credentials["api_protocol"] = service.APIProtocolResponses + other := newPoolPolicyAccountWithMapping(4212, service.PlatformKimi, 2, map[string]any{ + "pool-model": "kimi-chat", + }) + router, _ := newCompositePoolPolicyTestRouter(t, poolPolicyRouterInput{ + group: group, + accounts: []service.Account{cnParent, other}, + upstream: upstream, + }) + + // 第一条:仅 deepseek claim 的模型 → 绑定 resp id → deepseek。 + wA := postPoolPolicyRequest(t, router, "/v1/responses", + `{"model":"deepseek-flash","input":"hi","prompt_cache_key":"sess-cross-a","stream":false}`) + require.Equal(t, http.StatusOK, wA.Code, wA.Body.String()) + responseID := gjson.GetBytes(wA.Body.Bytes(), "id").String() + require.True(t, strings.HasPrefix(responseID, "resp_"), "downstream response must carry a resp_* id, got %q", responseID) + + // 第二条:新 session 种子 + 双账号池模型;武装 deepseek 首跳 429, + // failover 到 kimi 时守卫必须拒绝——kimi 不收到带旧 prevID 的转发。 + upstream.mu.Lock() + upstream.failHost = map[string]bool{"deepseek-pool-fake.test": true} + upstream.mu.Unlock() + capturedBefore := len(upstream.capturedSnapshot()) + wB := postPoolPolicyRequest(t, router, "/v1/responses", + `{"model":"pool-model","input":"continue","prompt_cache_key":"sess-cross-b","previous_response_id":"`+responseID+`","stream":false}`) + + require.Equal(t, http.StatusBadRequest, wB.Code, wB.Body.String()) + require.Contains(t, wB.Body.String(), "previous_response_id") + for _, record := range upstream.capturedSnapshot()[capturedBefore:] { + require.NotEqual(t, "kimi-pool-fake.test", record.host, + "the non-owning CN account must never receive the old prevID") + } +} + +// claude-* 别名被两个兼容族账号同时 claim 时,/v1/messages 不套 gpt-5.x +// 默认 dispatch 映射(池含 CN),仍按账号级 model_mapping 转发。 +func TestCompositePoolMessagesClaudeAliasUsesAccountMapping(t *testing.T) { + upstream := &captureUpstream{} + group := newPoolPolicyGroup(nil) + router, _ := newCompositePoolPolicyTestRouter(t, poolPolicyRouterInput{ + group: group, + accounts: []service.Account{ + newPoolPolicyAccountWithMapping(4211, service.PlatformDeepseek, 1, map[string]any{"claude-alias": "deepseek-chat"}), + newPoolPolicyAccountWithMapping(4212, service.PlatformKimi, 2, map[string]any{"claude-alias": "kimi-claude"}), + }, + upstream: upstream, + }) + + w := postPoolPolicyRequest(t, router, "/v1/messages", + `{"model":"claude-alias","max_tokens":32,"messages":[{"role":"user","content":"hi"}]}`) + + require.Equal(t, http.StatusOK, w.Code, w.Body.String()) + captured := upstream.capturedSnapshot() + require.NotEmpty(t, captured, "claude alias claimed by pool accounts must forward") + require.Equal(t, "deepseek-pool-fake.test", captured[0].host) + require.Equal(t, "deepseek-chat", gjson.GetBytes(captured[0].body, "model").String(), + "outbound model must come from the selected account's model_mapping, not the gpt-5.x dispatch default") +} diff --git a/backend/internal/server/routes/gateway_composite_pool_test.go b/backend/internal/server/routes/gateway_composite_pool_test.go new file mode 100644 index 0000000000..97a2cf2c62 --- /dev/null +++ b/backend/internal/server/routes/gateway_composite_pool_test.go @@ -0,0 +1,372 @@ +package routes + +import ( + "context" + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + + servermiddleware "github.com/Wei-Shaw/sub2api/internal/server/middleware" + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +// compositePoolOwnershipStub 让 resolver 对任意模型返回多平台账号池决策。 +type compositePoolOwnershipStub struct { + platforms []string +} + +func (s compositePoolOwnershipStub) ResolveModelOwnership(_ context.Context, _ int64, _ string) (service.CompositeModelOwnership, error) { + return service.CompositeModelOwnership{CandidatePlatforms: s.platforms}, nil +} + +func newCompositePoolTestRouter(t *testing.T, terminal gin.HandlerFunc, ownership compositePoolOwnershipStub, groupPlatform string) *gin.Engine { + t.Helper() + gin.SetMode(gin.TestMode) + router := gin.New() + router.Use(gin.HandlerFunc(servermiddleware.APIKeyAuthMiddleware(func(c *gin.Context) { + groupID := int64(1) + c.Set(string(servermiddleware.ContextKeyAPIKey), &service.APIKey{ + GroupID: &groupID, + Group: &service.Group{ID: groupID, Platform: groupPlatform}, + }) + c.Next() + }))) + resolver := service.NewCompositeRouteResolver(compositeRouteRepoStub{}) + resolver.SetModelOwnershipResolver(ownership.ResolveModelOwnership) + router.Use(compositeTargetPlatformMiddleware(resolver)) + router.POST("/v1/chat/completions", terminal) + return router +} + +// 账号池决策必须把完整候选集合写入 ctx(去重升序),且不写单一 +// ResolvedTargetPlatform、不改写 body 模型、来源标记 account_pool。 +func TestCompositeTargetPlatformMiddlewareWritesPoolDecision(t *testing.T) { + seen := false + router := newCompositePoolTestRouter(t, func(c *gin.Context) { + seen = true + candidates := service.CompositeCandidatePlatformsFromContext(c.Request.Context()) + require.Equal(t, []string{service.PlatformDeepseek, service.PlatformZhipu}, candidates) + + _, resolved := service.ResolvedTargetPlatformFromContext(c.Request.Context()) + require.False(t, resolved, "pool decision must not pin a single target platform") + + source, ok := service.CompositeRouteSourceFromContext(c.Request.Context()) + require.True(t, ok) + require.Equal(t, service.CompositeRouteSourceAccountPool, source) + + publicModel, ok := service.RequestedPublicModelFromContext(c.Request.Context()) + require.True(t, ok) + require.Equal(t, "cn-alias", publicModel) + + _, upstream := service.ResolvedUpstreamModelFromContext(c.Request.Context()) + require.False(t, upstream, "pool decision must not resolve an upstream model") + + body, err := io.ReadAll(c.Request.Body) + require.NoError(t, err) + require.JSONEq(t, `{"model":"cn-alias","messages":[]}`, string(body), + "pool request must keep the public model in the body") + c.Status(http.StatusNoContent) + }, compositePoolOwnershipStub{platforms: []string{service.PlatformZhipu, service.PlatformDeepseek}}, service.PlatformComposite) + + req := httptest.NewRequest(http.MethodPost, "/v1/chat/completions", strings.NewReader(`{"model":"cn-alias","messages":[]}`)) + req.Header.Set("Content-Type", "application/json") + w := httptest.NewRecorder() + router.ServeHTTP(w, req) + + require.True(t, seen, "pool request must reach the terminal handler") + require.Equal(t, http.StatusNoContent, w.Code) +} + +// composite 请求的模型无法解析到任何平台时必须显式 400,不能再静默放行到 +// 通用网关按通用协议报错。 +func TestCompositeTargetPlatformMiddlewareRejectsUnresolvedModel(t *testing.T) { + router := newCompositePoolTestRouter(t, func(c *gin.Context) { + t.Fatal("unresolvable composite model must not reach any handler") + }, compositePoolOwnershipStub{}, service.PlatformComposite) + + req := httptest.NewRequest(http.MethodPost, "/v1/chat/completions", strings.NewReader(`{"model":"totally-unknown-alias"}`)) + req.Header.Set("Content-Type", "application/json") + w := httptest.NewRecorder() + router.ServeHTTP(w, req) + + require.Equal(t, http.StatusBadRequest, w.Code) + require.Contains(t, w.Body.String(), "totally-unknown-alias") +} + +// 非 composite 分组保持原行为:无模型解析拦截。 +func TestCompositeTargetPlatformMiddlewareKeepsNonCompositeBehavior(t *testing.T) { + router := newCompositePoolTestRouter(t, func(c *gin.Context) { + _, resolved := service.ResolvedTargetPlatformFromContext(c.Request.Context()) + require.False(t, resolved) + candidates := service.CompositeCandidatePlatformsFromContext(c.Request.Context()) + require.Empty(t, candidates) + c.Status(http.StatusNoContent) + }, compositePoolOwnershipStub{platforms: []string{service.PlatformDeepseek}}, service.PlatformAnthropic) + + req := httptest.NewRequest(http.MethodPost, "/v1/chat/completions", strings.NewReader(`{"model":"weird-model"}`)) + req.Header.Set("Content-Type", "application/json") + w := httptest.NewRecorder() + router.ServeHTTP(w, req) + + require.Equal(t, http.StatusNoContent, w.Code) +} + +// 全部 7 类兼容族平台的任意非空子集池都必须进入 OpenAI 网关 handler; +// 池大小不参与族判断。 +func TestDispatchOpenAICompatibleGatewayRoutesAllFamilyPoolSubsets(t *testing.T) { + family := []string{ + service.PlatformOpenAI, service.PlatformGrok, + service.PlatformKimi, service.PlatformZhipu, service.PlatformDeepseek, + service.PlatformMiniMax, service.PlatformOpenCodeGo, + } + subsets := allNonEmptySubsets(family) + require.Len(t, subsets, 127) + for _, subset := range subsets { + var openAI, generic int + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/chat/completions", nil).WithContext( + service.WithCompositeCandidatePlatforms(context.Background(), subset)) + dispatchOpenAICompatibleGateway(c, + func(c *gin.Context) { openAI++ }, + func(c *gin.Context) { generic++ }) + require.Equal(t, 1, openAI, "subset=%v must route to the OpenAI gateway handler", subset) + require.Zero(t, generic, "subset=%v must not fall through to the generic handler", subset) + } +} + +// 单一 DeepSeek 目标与全兼容族池走同一个 OpenAI handler,不产生第二次选号 +// 或不同 sticky 语义。 +func TestDispatchOpenAICompatibleGatewaySingleDeepSeekMatchesPoolFamily(t *testing.T) { + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/chat/completions", nil) + c.Set(string(servermiddleware.ContextKeyAPIKey), &service.APIKey{ + Group: &service.Group{Platform: service.PlatformComposite}, + }) + c.Request = c.Request.WithContext(service.WithResolvedTargetPlatform(c.Request.Context(), service.PlatformDeepseek)) + + var openAI, generic int + dispatchOpenAICompatibleGateway(c, + func(c *gin.Context) { openAI++ }, + func(c *gin.Context) { generic++ }) + require.Equal(t, 1, openAI) + require.Zero(t, generic) +} + +// 跨原生协议族池(兼容族混 anthropic/gemini/antigravity,或全部为原生族) +// 必须显式 400 并点名候选平台,不得落入通用 handler。 +func TestDispatchOpenAICompatibleGatewayRejectsCrossFamilyPool(t *testing.T) { + for _, subset := range [][]string{ + {service.PlatformAnthropic, service.PlatformDeepseek}, + {service.PlatformOpenAI, service.PlatformGrok, service.PlatformGemini}, + {service.PlatformAnthropic}, + {service.PlatformAntigravity, service.PlatformKimi}, + {service.PlatformAnthropic, service.PlatformGemini, service.PlatformAntigravity}, + } { + var openAI, generic int + recorder := httptest.NewRecorder() + c, _ := gin.CreateTestContext(recorder) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", nil).WithContext( + service.WithCompositeCandidatePlatforms(context.Background(), subset)) + dispatchOpenAICompatibleGateway(c, + func(c *gin.Context) { openAI++ }, + func(c *gin.Context) { generic++ }) + require.Zero(t, openAI, "subset=%v must not enter the OpenAI handler", subset) + require.Zero(t, generic, "subset=%v must not fall through to the generic handler", subset) + require.True(t, c.IsAborted(), "subset=%v must abort", subset) + require.Equal(t, http.StatusBadRequest, recorder.Code, "subset=%v", subset) + for _, platform := range subset { + require.Contains(t, recorder.Body.String(), platform, "subset=%v must name every candidate", subset) + } + } +} + +// 非 composite 分组与解析到原生族单目标的 composite 分组保持既有落通用 +// handler 的行为(显式 route + 普通分组不回归)。 +func TestDispatchOpenAICompatibleGatewayKeepsGenericTargets(t *testing.T) { + // anthropic 普通分组。 + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", nil) + c.Set(string(servermiddleware.ContextKeyAPIKey), &service.APIKey{ + Group: &service.Group{Platform: service.PlatformAnthropic}, + }) + var openAI, generic int + dispatchOpenAICompatibleGateway(c, + func(c *gin.Context) { openAI++ }, + func(c *gin.Context) { generic++ }) + require.Zero(t, openAI) + require.Equal(t, 1, generic) + + // composite 解析到 claude 单目标。 + c2, _ := gin.CreateTestContext(httptest.NewRecorder()) + c2.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", nil) + c2.Set(string(servermiddleware.ContextKeyAPIKey), &service.APIKey{ + Group: &service.Group{Platform: service.PlatformComposite}, + }) + c2.Request = c2.Request.WithContext(service.WithResolvedTargetPlatform(c2.Request.Context(), service.PlatformAnthropic)) + openAI, generic = 0, 0 + dispatchOpenAICompatibleGateway(c2, + func(c *gin.Context) { openAI++ }, + func(c *gin.Context) { generic++ }) + require.Zero(t, openAI) + require.Equal(t, 1, generic) +} + +// count_tokens 沿用既有端点语义:兼容族池进 OpenAI CountTokens,跨族池 +// 明确拒绝,grok 单目标保留 GrokCountTokens。 +func TestDispatchOpenAICompatibleCountTokensPoolAndSingle(t *testing.T) { + var compatible, grok, generic int + handlers := []gin.HandlerFunc{ + func(c *gin.Context) { compatible++ }, + func(c *gin.Context) { grok++ }, + func(c *gin.Context) { generic++ }, + } + + newContext := func(seed func(c *gin.Context)) *gin.Context { + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages/count_tokens", nil) + seed(c) + return c + } + + // 兼容族池(含 grok 候选)进 OpenAI CountTokens。 + dispatchOpenAICompatibleCountTokens(newContext(func(c *gin.Context) { + c.Request = c.Request.WithContext(service.WithCompositeCandidatePlatforms(c.Request.Context(), + []string{service.PlatformDeepseek, service.PlatformGrok})) + }), handlers[0], handlers[1], handlers[2]) + require.Equal(t, 1, compatible) + require.Zero(t, grok) + require.Zero(t, generic) + + // 跨族池拒绝,任何 handler 都不执行。 + c := newContext(func(c *gin.Context) { + c.Request = c.Request.WithContext(service.WithCompositeCandidatePlatforms(c.Request.Context(), + []string{service.PlatformAnthropic, service.PlatformDeepseek})) + }) + compatible, grok, generic = 0, 0, 0 + dispatchOpenAICompatibleCountTokens(c, handlers[0], handlers[1], handlers[2]) + require.Zero(t, compatible) + require.Zero(t, grok) + require.Zero(t, generic) + require.True(t, c.IsAborted()) + + // grok 单目标保留本地估算路径。 + compatible, grok, generic = 0, 0, 0 + dispatchOpenAICompatibleCountTokens(newContext(func(c *gin.Context) { + c.Set(string(servermiddleware.ContextKeyAPIKey), &service.APIKey{ + Group: &service.Group{Platform: service.PlatformGrok}, + }) + }), handlers[0], handlers[1], handlers[2]) + require.Equal(t, 1, grok) + require.Zero(t, compatible) + require.Zero(t, generic) + + // anthropic 普通分组保持通用 CountTokens。 + compatible, grok, generic = 0, 0, 0 + dispatchOpenAICompatibleCountTokens(newContext(func(c *gin.Context) { + c.Set(string(servermiddleware.ContextKeyAPIKey), &service.APIKey{ + Group: &service.Group{Platform: service.PlatformAnthropic}, + }) + }), handlers[0], handlers[1], handlers[2]) + require.Equal(t, 1, generic) + require.Zero(t, compatible) + require.Zero(t, grok) +} + +// allNonEmptySubsets 返回 platforms 的全部非空子集(2^n - 1 个)。 +func allNonEmptySubsets(platforms []string) [][]string { + total := 1 << len(platforms) + subsets := make([][]string, 0, total-1) + for mask := 1; mask < total; mask++ { + subset := make([]string, 0, len(platforms)) + for i, platform := range platforms { + if mask&(1< 0 } type CompositeRouteInput struct { diff --git a/backend/internal/service/composite_platform.go b/backend/internal/service/composite_platform.go index c10e335cbe..bd6a8fe733 100644 --- a/backend/internal/service/composite_platform.go +++ b/backend/internal/service/composite_platform.go @@ -2,6 +2,7 @@ package service import ( "context" + "slices" "strings" "github.com/Wei-Shaw/sub2api/internal/pkg/ctxkey" @@ -31,10 +32,71 @@ func ResolvedTargetPlatformFromContext(ctx context.Context) (string, bool) { return platform, true } +// normalizeCompositeCandidatePlatforms 归一化候选平台集合:去空白、去空项、 +// 去重并按升序排列;输入为空时返回 nil。池集合在写入 ctx / decision 前必须 +// 经过该函数,保证「稳定候选契约」:同一候选集在请求生命周期内表现一致。 +func normalizeCompositeCandidatePlatforms(platforms []string) []string { + normalized := make([]string, 0, len(platforms)) + for _, platform := range platforms { + platform = strings.TrimSpace(platform) + if platform == "" { + continue + } + if slices.Contains(normalized, platform) { + continue + } + normalized = append(normalized, platform) + } + if len(normalized) == 0 { + return nil + } + slices.Sort(normalized) + return normalized +} + +// WithCompositeCandidatePlatforms 在 ctx 上携带 composite 多平台候选池。输入 +// 会被归一化(去重升序),存入 ctx 的是内部副本;空集合不写入。 +func WithCompositeCandidatePlatforms(ctx context.Context, platforms []string) context.Context { + if ctx == nil { + return ctx + } + normalized := normalizeCompositeCandidatePlatforms(platforms) + if len(normalized) == 0 { + return ctx + } + return context.WithValue(ctx, ctxkey.CompositeCandidatePlatforms, normalized) +} + +// CompositeCandidatePlatformsFromContext 返回当前请求的候选池快照(去重升序)。 +// 返回值为副本,调用方修改不会影响 ctx;未携带池时返回 nil。 +func CompositeCandidatePlatformsFromContext(ctx context.Context) []string { + if ctx == nil { + return nil + } + platforms, ok := ctx.Value(ctxkey.CompositeCandidatePlatforms).([]string) + if !ok || len(platforms) == 0 { + return nil + } + return slices.Clone(platforms) +} + func WithCompositeRouteDecision(ctx context.Context, decision CompositeRouteDecision) context.Context { if ctx == nil || !decision.Matched { return ctx } + if isCompositePoolDecision(decision) { + // pool 决策:只携带候选集合与公开模型/来源,不写 ResolvedTargetPlatform / + // ResolvedUpstreamModel——最终平台由 selector 选定,选号/重试期间不得被 + // 单一账号平台覆盖,池请求也不改写 body 模型。 + ctx = WithCompositeCandidatePlatforms(ctx, decision.CandidatePlatforms) + if model := strings.TrimSpace(decision.PublicModel); model != "" { + ctx = context.WithValue(ctx, ctxkey.RequestedPublicModel, model) + } + if source := strings.TrimSpace(decision.Source); source != "" { + ctx = context.WithValue(ctx, ctxkey.CompositeRouteSource, source) + } + return ctx + } ctx = WithResolvedTargetPlatform(ctx, decision.TargetPlatform) if model := strings.TrimSpace(decision.UpstreamModel); model != "" { ctx = context.WithValue(ctx, ctxkey.ResolvedUpstreamModel, model) @@ -196,6 +258,23 @@ func (s *GatewayService) resolveCompositeRouteDecision(ctx context.Context, grou Endpoint: normalizeCompositeRouteEndpoint(endpoint), }, true, nil } + // 已解析的池决策优先于重新解析:避免因 TargetPlatform 为空被误报 unknown + // 或折叠成 detector 单平台。显式 pin(ResolvedTargetPlatform)仍优先于池, + // 保持既有 single 行为(如 gemini 端点 fallback pin)。 + if candidates := CompositeCandidatePlatformsFromContext(ctx); len(candidates) > 0 { + source := CompositeRouteSourceAccountPool + if resolvedSource, sourceOK := CompositeRouteSourceFromContext(ctx); sourceOK && resolvedSource != "" { + source = resolvedSource + } + return CompositeRouteDecision{ + Matched: true, + Source: source, + GroupID: group.ID, + PublicModel: requestedModel, + CandidatePlatforms: candidates, + Endpoint: normalizeCompositeRouteEndpoint(endpoint), + }, true, nil + } decision, err := s.compositeResolver.Resolve(ctx, group.ID, requestedModel, endpoint) if err != nil { return decision, false, err diff --git a/backend/internal/service/composite_platform_test.go b/backend/internal/service/composite_platform_test.go index 4b11366a29..56189f4048 100644 --- a/backend/internal/service/composite_platform_test.go +++ b/backend/internal/service/composite_platform_test.go @@ -13,7 +13,13 @@ type compositeOwnershipAccountRepo struct { accounts []Account } -func (r *compositeOwnershipAccountRepo) ListSchedulableByGroupID(context.Context, int64) ([]Account, error) { +func (r *compositeOwnershipAccountRepo) ListModelAvailabilityCandidates(_ context.Context, groupID *int64, platforms []string, _ bool) ([]Account, error) { + if groupID == nil { + return nil, nil + } + if len(platforms) == 0 { + return nil, nil + } return r.accounts, nil } @@ -49,36 +55,42 @@ func TestResolveCompositeModelOwnershipKeepsProviderAccountsIsolated(t *testing. require.Equal(t, CompositeModelOwnership{TargetPlatform: PlatformOpenAI, Matched: true}, openAIOwnership) } -// Scenario: 通配符和空映射不声明所有权 -func TestResolveCompositeModelOwnershipRequiresNonEmptyExactMappings(t *testing.T) { +// Scenario: 通配映射按既有通配语义声明;映射目标为空的别名不构成声明; +// 精确声明平台不被其他平台的通配 catch-all 冒领(声明强度分层)。 +func TestResolveCompositeModelOwnershipHonorsWildcardMappings(t *testing.T) { groupID := int64(7) - repo := &compositeOwnershipAccountRepo{ - accounts: []Account{ - { - ID: 1, - Platform: PlatformOpenAI, - Credentials: map[string]any{ - "model_mapping": map[string]any{"*": "gpt-5", "gpt-*": "gpt-5", "empty-alias": ""}, - }, - }, - { - ID: 2, - Platform: PlatformGrok, - Credentials: map[string]any{ - "model_mapping": map[string]any{"grok-public": "grok-4"}, - }, - }, + openAIAccount := Account{ + ID: 1, + Platform: PlatformOpenAI, + Credentials: map[string]any{ + "model_mapping": map[string]any{"*": "gpt-5", "gpt-*": "gpt-5", "empty-alias": ""}, }, } + grokAccount := Account{ + ID: 2, + Platform: PlatformGrok, + Credentials: map[string]any{ + "model_mapping": map[string]any{"grok-public": "grok-4"}, + }, + } + repo := &compositeOwnershipAccountRepo{accounts: []Account{openAIAccount, grokAccount}} svc := &GatewayService{accountRepo: repo} - for _, model := range []string{"gpt-5", "empty-alias", "unknown-alias"} { + // 完全无强声明时才回退通配命中平台:gpt-5 / unknown-alias 仅 openai 通配命中。 + for _, model := range []string{"gpt-5", "unknown-alias"} { ownership, err := svc.resolveCompositeModelOwnership(context.Background(), groupID, model) require.NoError(t, err) - require.Equal(t, CompositeModelOwnership{}, ownership, "model=%s", model) + require.Equal(t, CompositeModelOwnership{TargetPlatform: PlatformOpenAI, Matched: true}, ownership, "model=%s", model) } - ownership, err := svc.resolveCompositeModelOwnership(context.Background(), groupID, "grok-public") + // 映射目标为空的条目不构成声明,也无其他平台可声明。 + ownership, err := svc.resolveCompositeModelOwnership(context.Background(), groupID, "empty-alias") + require.NoError(t, err) + require.Equal(t, CompositeModelOwnership{}, ownership) + + // grok 精确声明为强声明:openai 的 "*" 通配(弱声明)不与之混池, + // 否则 grok 请求会被改写成 gpt-5(回归)。 + ownership, err = svc.resolveCompositeModelOwnership(context.Background(), groupID, "grok-public") require.NoError(t, err) require.Equal(t, CompositeModelOwnership{TargetPlatform: PlatformGrok, Matched: true}, ownership) } @@ -98,9 +110,13 @@ func TestResolveCompositeModelOwnershipAllowsSamePlatformAndRejectsCrossPlatform require.NoError(t, err) require.Equal(t, CompositeModelOwnership{TargetPlatform: PlatformOpenAI, Matched: true}, samePlatform) + // 跨平台同名别名:返回稳定候选池(去重升序),不再是裸 Ambiguous。 ambiguous, err := svc.resolveCompositeModelOwnership(context.Background(), groupID, "ambiguous") require.NoError(t, err) - require.Equal(t, CompositeModelOwnership{Ambiguous: true}, ambiguous) + require.True(t, ambiguous.Matched) + require.False(t, ambiguous.Ambiguous) + require.Empty(t, ambiguous.TargetPlatform) + require.Equal(t, []string{PlatformDeepseek, PlatformOpenAI}, ambiguous.CandidatePlatforms) } func TestNewGatewayServiceWiresCompositeModelOwnershipResolver(t *testing.T) { diff --git a/backend/internal/service/composite_pool_attempt_policy_test.go b/backend/internal/service/composite_pool_attempt_policy_test.go new file mode 100644 index 0000000000..f7d0ee760d --- /dev/null +++ b/backend/internal/service/composite_pool_attempt_policy_test.go @@ -0,0 +1,378 @@ +//go:build unit + +package service + +// composite 账号池 per-attempt 平台策略的 service 侧单元测试: +// 1. CheckUserPlatformQuotaEligibilityForRequest:复现 CheckBillingEligibility 的 +// 豁免条件(simple / 订阅),standard 模式下按平台拦截或放行; +// 2. CompositePoolAttemptChannelRestricted / CompositePoolAttemptChannelMapping: +// attempt 局部 ctx(ResolvedTargetPlatform=选中平台)把渠道限制与映射作用域 +// 收窄到选中平台——修复池请求无 resolved 时按 composite 分组跨平台行匹配而 +// 绕过渠道映射/定价限制的缺陷。 + +import ( + "context" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/stretchr/testify/require" +) + +// ── CheckUserPlatformQuotaEligibilityForRequest ───────────────────────────── + +func newPoolAttemptBillingService(repo UserPlatformQuotaRepository, cache BillingCache, runMode string) *BillingCacheService { + cfg := &config.Config{RunMode: runMode} + cfg.Billing.UserPlatformQuotaCacheTTLSeconds = 60 + return &BillingCacheService{ + cache: cache, + cfg: cfg, + userPlatformQuotaRepo: repo, + } +} + +func TestCheckUserPlatformQuotaEligibilityForRequest_SimpleModeSkips(t *testing.T) { + // fakeZeroQuotaCache 在被查询时必然拦截(limit=0):simple 模式必须跳过检查。 + fake := &fakeZeroQuotaCache{} + s := newPoolAttemptBillingService(&fakeQuotaRepo{}, fake, config.RunModeSimple) + + err := s.CheckUserPlatformQuotaEligibilityForRequest( + context.Background(), &User{ID: 42}, &Group{ID: 10, Platform: PlatformComposite}, nil, "openai") + + require.NoError(t, err) + require.False(t, fake.called, "simple mode must not consult user×platform quota cache") +} + +func TestCheckUserPlatformQuotaEligibilityForRequest_SubscriptionModeSkips(t *testing.T) { + fake := &fakeZeroQuotaCache{} + s := newPoolAttemptBillingService(&fakeQuotaRepo{}, fake, config.RunModeStandard) + + group := &Group{ID: 10, Platform: PlatformComposite, SubscriptionType: "subscription", Status: StatusActive} + err := s.CheckUserPlatformQuotaEligibilityForRequest( + context.Background(), &User{ID: 42}, group, &UserSubscription{Status: SubscriptionStatusActive}, "openai") + + require.NoError(t, err) + require.False(t, fake.called, "subscription mode must bypass user×platform quota (same as CheckBillingEligibility)") +} + +func TestCheckUserPlatformQuotaEligibilityForRequest_SubscriptionGroupWithoutSubscriptionChecks(t *testing.T) { + // 订阅分组但 subscription 为 nil:与 CheckBillingEligibility 的 isSubscriptionMode + // 判定一致(group.IsSubscriptionType() && subscription != nil),回落 standard 检查。 + fake := &fakeZeroQuotaCache{} + s := newPoolAttemptBillingService(&fakeQuotaRepo{}, fake, config.RunModeStandard) + + group := &Group{ID: 10, Platform: PlatformComposite, SubscriptionType: "subscription", Status: StatusActive} + err := s.CheckUserPlatformQuotaEligibilityForRequest( + context.Background(), &User{ID: 42}, group, nil, "openai") + + require.ErrorIs(t, err, ErrUserPlatformDailyQuotaExhausted) + require.True(t, fake.called) +} + +func TestCheckUserPlatformQuotaEligibilityForRequest_StandardBlocksExhaustedPlatform(t *testing.T) { + fake := &fakeZeroQuotaCache{} + s := newPoolAttemptBillingService(&fakeQuotaRepo{}, fake, config.RunModeStandard) + + err := s.CheckUserPlatformQuotaEligibilityForRequest( + context.Background(), &User{ID: 42}, &Group{ID: 10, Platform: PlatformComposite}, nil, "openai") + + require.ErrorIs(t, err, ErrUserPlatformDailyQuotaExhausted) + require.True(t, fake.called, "standard mode must consult the user×platform quota cache") +} + +func TestCheckUserPlatformQuotaEligibilityForRequest_StandardAllowsBelowLimit(t *testing.T) { + dailyLimit := 5.0 + now := time.Now().UTC() + cache := &fakeFullCache{entry: &UserPlatformQuotaCacheEntry{ + DailyUsageUSD: 1.0, + DailyLimitUSD: &dailyLimit, + DailyWindowStart: &now, + SchemaVersion: UserPlatformQuotaCacheSchemaV1, + }} + s := newPoolAttemptBillingService(&fakeQuotaRepo{}, cache, config.RunModeStandard) + + err := s.CheckUserPlatformQuotaEligibilityForRequest( + context.Background(), &User{ID: 42}, &Group{ID: 10, Platform: PlatformComposite}, nil, "openai") + + require.NoError(t, err) +} + +func TestCheckUserPlatformQuotaEligibilityForRequest_EmptyPlatformAllows(t *testing.T) { + fake := &fakeZeroQuotaCache{} + s := newPoolAttemptBillingService(&fakeQuotaRepo{}, fake, config.RunModeStandard) + + err := s.CheckUserPlatformQuotaEligibilityForRequest( + context.Background(), &User{ID: 42}, &Group{ID: 10, Platform: PlatformComposite}, nil, "") + + require.NoError(t, err) + require.False(t, fake.called) +} + +// ── CompositePoolAttemptChannelRestricted / CompositePoolAttemptChannelMapping ── + +const poolAttemptGroupID = int64(4310) + +// newPoolAttemptChannelService 构造 composite 分组的渠道服务:cache 装填时按映射 +// 条目自身平台展开(expandMappingToCache),查找作用域由 ctx 的 ResolvedTargetPlatform +// 决定(channelLookupPlatform)。 +func newPoolAttemptChannelService(t *testing.T, ch Channel) *ChannelService { + t.Helper() + repo := makeStandardRepo(ch, map[int64]string{poolAttemptGroupID: PlatformComposite}) + svc := newTestChannelService(repo) + // 预热 cache(lazy load 在首次查询时也会构建,这里显式触发以便失败立现)。 + if _, err := svc.loadCache(context.Background()); err != nil { + t.Fatalf("load channel cache: %v", err) + } + return svc +} + +func newPoolAttemptOpenAIGateway(channelSvc *ChannelService) *OpenAIGatewayService { + return &OpenAIGatewayService{channelService: channelSvc} +} + +func poolAttemptCtx(platform string) context.Context { + return WithResolvedTargetPlatform(context.Background(), platform) +} + +func TestCompositePoolAttemptChannelRestricted_ScopesToSelectedPlatform(t *testing.T) { + // 渠道只对 openai 平台声明 gpt-* 定价且开启模型限制。 + ch := Channel{ + ID: 1, + Status: StatusActive, + GroupIDs: []int64{poolAttemptGroupID}, + RestrictModels: true, + BillingModelSource: BillingModelSourceRequested, + ModelPricing: []ChannelModelPricing{ + {Platform: PlatformOpenAI, Models: []string{"gpt-*"}}, + }, + } + svc := newPoolAttemptOpenAIGateway(newPoolAttemptChannelService(t, ch)) + groupID := poolAttemptGroupID + + // 选中 openai 账号:gpt-4 在 openai 作用域定价内 → 放行。 + require.False(t, svc.CompositePoolAttemptChannelRestricted( + poolAttemptCtx(PlatformOpenAI), &groupID, &Account{Platform: PlatformOpenAI}, "gpt-4", false)) + + // 选中 deepseek 账号:gpt-4 不在 deepseek 作用域定价内 → 拒绝该平台。 + // (无 resolved 的旧作用域会跨平台扫到 openai 行而误放行——即本修复目标。) + require.True(t, svc.CompositePoolAttemptChannelRestricted( + poolAttemptCtx(PlatformDeepseek), &groupID, &Account{Platform: PlatformDeepseek}, "gpt-4", false)) + + // 无 attempt ctx(池原 ctx,无 resolved):复现旧缺陷语义作对照——跨平台扫描 + // 把 openai 行的 gpt-* 当作命中,deepseek 账号被误放行。 + require.False(t, svc.CompositePoolAttemptChannelRestricted( + context.Background(), &groupID, &Account{Platform: PlatformDeepseek}, "gpt-4", false)) +} + +func TestCompositePoolAttemptChannelRestricted_UpstreamBillingSourcePerAccount(t *testing.T) { + // BillingModelSource=upstream:调度阶段 checkChannelPricingRestriction 不判 + // (billingModel 为空),改由逐账号 upstream 模型检查。attempt 作用域同样适用。 + ch := Channel{ + ID: 1, + Status: StatusActive, + GroupIDs: []int64{poolAttemptGroupID}, + RestrictModels: true, + BillingModelSource: BillingModelSourceUpstream, + ModelPricing: []ChannelModelPricing{ + {Platform: PlatformDeepseek, Models: []string{"deepseek-chat"}}, + }, + } + svc := newPoolAttemptOpenAIGateway(newPoolAttemptChannelService(t, ch)) + groupID := poolAttemptGroupID + openAIAccount := &Account{ + Platform: PlatformOpenAI, Type: AccountTypeAPIKey, + Credentials: map[string]any{ + "api_key": "k", "base_url": "https://openai-fake.test/v1", + "model_mapping": map[string]any{"gpt-4": "deepseek-chat"}, + }, + } + + // openai 账号把 gpt-4 映射为 deepseek-chat,但 openai 作用域没有该定价 → 拒绝。 + require.True(t, svc.CompositePoolAttemptChannelRestricted( + poolAttemptCtx(PlatformOpenAI), &groupID, openAIAccount, "gpt-4", false)) + + // deepseek 作用域存在 deepseek-chat 定价 → 放行。 + deepseekAccount := &Account{ + Platform: PlatformDeepseek, Type: AccountTypeAPIKey, + Credentials: map[string]any{ + "api_key": "k", "base_url": "https://deepseek-fake.test/v1", + "model_mapping": map[string]any{"gpt-4": "deepseek-chat"}, + }, + } + require.False(t, svc.CompositePoolAttemptChannelRestricted( + poolAttemptCtx(PlatformDeepseek), &groupID, deepseekAccount, "gpt-4", false)) +} + +func TestCompositePoolAttemptChannelMapping_ScopesToSelectedPlatform(t *testing.T) { + ch := Channel{ + ID: 1, + Status: StatusActive, + GroupIDs: []int64{poolAttemptGroupID}, + BillingModelSource: BillingModelSourceRequested, + ModelMapping: map[string]map[string]string{ + PlatformOpenAI: {"gpt-4": "gpt-4o"}, + PlatformDeepseek: {"deepseek-flash": "deepseek-chat"}, + }, + } + svc := newPoolAttemptOpenAIGateway(newPoolAttemptChannelService(t, ch)) + groupID := poolAttemptGroupID + + openAIMapping := svc.CompositePoolAttemptChannelMapping(poolAttemptCtx(PlatformOpenAI), &groupID, "gpt-4") + require.True(t, openAIMapping.Mapped) + require.Equal(t, "gpt-4o", openAIMapping.MappedModel) + + // 同一模型在 deepseek 作用域没有映射 → 保持原模型直通,不跨平台串 openai 行。 + deepseekMapping := svc.CompositePoolAttemptChannelMapping(poolAttemptCtx(PlatformDeepseek), &groupID, "gpt-4") + require.False(t, deepseekMapping.Mapped) + require.Equal(t, "gpt-4", deepseekMapping.MappedModel) +} + +func TestCompositePoolAttemptChannelHelpers_NilGuards(t *testing.T) { + var svc *OpenAIGatewayService + groupID := poolAttemptGroupID + require.False(t, svc.CompositePoolAttemptChannelRestricted(context.Background(), &groupID, &Account{Platform: PlatformOpenAI}, "gpt-4", false)) + mapping := svc.CompositePoolAttemptChannelMapping(context.Background(), &groupID, "gpt-4") + require.False(t, mapping.Mapped) + require.Equal(t, "gpt-4", mapping.MappedModel) +} + +// ── deniedPlatforms selector 门(sticky / list) ───────────────────────────── +// +// 复审 A 收尾:deny 不得收缩候选池(候选池 immutable),而是经请求局部 +// deniedPlatforms 在 selector list/sticky 门过滤;sticky 账号因所属平台被 deny +// 暂时排除时必须按 excluded 语义早退——不 delete 粘性绑定(即使该账号不在 +// excludedIDs / failedAccountIDs 里)。 + +type compositePoolGateStickyCache struct { + GatewayCache + stickyID int64 + deletes int +} + +func (f *compositePoolGateStickyCache) GetSessionAccountID(context.Context, int64, string) (int64, error) { + if f.stickyID > 0 { + return f.stickyID, nil + } + return 0, ErrStickySessionNotFound +} + +func (f *compositePoolGateStickyCache) SetSessionAccountID(context.Context, int64, string, int64, time.Duration) error { + return nil +} + +func (f *compositePoolGateStickyCache) RefreshSessionTTL(context.Context, int64, string, time.Duration) error { + return nil +} + +func (f *compositePoolGateStickyCache) DeleteSessionAccountID(context.Context, int64, string) error { + f.deletes++ + return nil +} + +type compositePoolGateAccountRepo struct { + AccountRepository + byID map[int64]*Account +} + +func (f *compositePoolGateAccountRepo) GetByID(_ context.Context, id int64) (*Account, error) { + if account, ok := f.byID[id]; ok { + copy := *account + return ©, nil + } + return nil, nil +} + +func (f *compositePoolGateAccountRepo) ListSchedulable(context.Context) ([]Account, error) { + return f.listByPlatform(""), nil +} + +func (f *compositePoolGateAccountRepo) ListSchedulableByGroupID(context.Context, int64) ([]Account, error) { + return f.listByPlatform(""), nil +} + +func (f *compositePoolGateAccountRepo) ListSchedulableByPlatform(_ context.Context, platform string) ([]Account, error) { + return f.listByPlatform(platform), nil +} + +func (f *compositePoolGateAccountRepo) ListSchedulableByGroupIDAndPlatform(_ context.Context, _ int64, platform string) ([]Account, error) { + return f.listByPlatform(platform), nil +} + +func (f *compositePoolGateAccountRepo) ListSchedulableUngroupedByPlatform(_ context.Context, platform string) ([]Account, error) { + return f.listByPlatform(platform), nil +} + +func (f *compositePoolGateAccountRepo) listByPlatform(platform string) []Account { + out := make([]Account, 0, len(f.byID)) + for _, account := range f.byID { + if platform == "" || account.Platform == platform { + out = append(out, *account) + } + } + return out +} + +func newCompositePoolGateService() (*OpenAIGatewayService, *compositePoolGateStickyCache) { + stickyCache := &compositePoolGateStickyCache{stickyID: 4333} + // mapping 声明与 routes 夹具一致:池 claims 能力门按 mapping key 判定。 + credentials := map[string]any{ + "api_key": "k", + "base_url": "https://deepseek-pool-fake.test/v1", + "model_mapping": map[string]any{"deepseek-flash": "deepseek-chat"}, + } + svc := &OpenAIGatewayService{ + cache: stickyCache, + accountRepo: &compositePoolGateAccountRepo{byID: map[int64]*Account{ + 4333: {ID: 4333, Platform: PlatformDeepseek, Type: AccountTypeAPIKey, Status: StatusActive, Schedulable: true, Concurrency: 4, Credentials: credentials}, + 4334: {ID: 4334, Platform: PlatformOpenAI, Type: AccountTypeAPIKey, Status: StatusActive, Schedulable: true, Concurrency: 4}, + }}, + cfg: &config.Config{}, + } + return svc, stickyCache +} + +// sticky 账号 X(deepseek)在平台被 deny 时:早退返回 nil 且零 delete——即使 X 不在 +// excludedIDs(即失败的不是 X 自己,而是同平台的兄弟账号 Y)。 +func TestCompositePoolStickyGateSkipsDeniedPlatformWithoutDelete(t *testing.T) { + svc, stickyCache := newCompositePoolGateService() + groupID := int64(4330) + base := WithCompositeCandidatePlatforms(context.Background(), []string{PlatformDeepseek, PlatformOpenAI}) + deniedCtx := WithCompositePoolDeniedPlatforms(base, []string{PlatformDeepseek}) + + // 非空洞前提:同夹具下 X 可正常加载(排除"加载失败导致 nil"的假阳性)。 + fetched, err := svc.getSchedulableAccount(context.Background(), 4333) + require.NoError(t, err) + require.NotNil(t, fetched) + require.Equal(t, PlatformDeepseek, fetched.Platform) + + account := svc.tryStickySessionHit(deniedCtx, &groupID, PlatformOpenAI, "sess-gate", "deepseek-flash", nil, false, 0, OpenAIEndpointCapabilityChatCompletions) + require.Nil(t, account, "denied-platform sticky account must be temporarily skipped") + require.Equal(t, 0, stickyCache.deletes, "temporary denial must not delete the sticky binding") +} + +// list 门:denied 平台从 pool 桶与单平台桶中被过滤。 +func TestCompositePoolListGateFiltersDeniedPlatforms(t *testing.T) { + svc, _ := newCompositePoolGateService() + groupID := int64(4330) + base := WithCompositeCandidatePlatforms(context.Background(), []string{PlatformDeepseek, PlatformOpenAI}) + deniedCtx := WithCompositePoolDeniedPlatforms(base, []string{PlatformDeepseek}) + + accounts, err := svc.listSchedulableAccountsForCompositePool(deniedCtx, &groupID, []string{PlatformDeepseek, PlatformOpenAI}) + require.NoError(t, err) + for _, account := range accounts { + require.NotEqual(t, PlatformDeepseek, account.Platform, "denied platform must be filtered from the pool list") + } + + single, err := svc.listSchedulableAccountsSinglePlatform(deniedCtx, &groupID, PlatformDeepseek) + require.NoError(t, err) + require.Empty(t, single, "single-platform listing under a denied attempt ctx must return an empty bucket") + + // 对照:无 denied overlay 时两个平台桶都可用。 + accounts, err = svc.listSchedulableAccountsForCompositePool(base, &groupID, []string{PlatformDeepseek, PlatformOpenAI}) + require.NoError(t, err) + platforms := map[string]bool{} + for _, account := range accounts { + platforms[account.Platform] = true + } + require.True(t, platforms[PlatformDeepseek] && platforms[PlatformOpenAI]) +} diff --git a/backend/internal/service/composite_pool_contract_test.go b/backend/internal/service/composite_pool_contract_test.go new file mode 100644 index 0000000000..9c5c51c4b7 --- /dev/null +++ b/backend/internal/service/composite_pool_contract_test.go @@ -0,0 +1,356 @@ +package service + +import ( + "context" + "testing" + "time" + + "github.com/stretchr/testify/require" +) + +// composite 跨平台稳定候选池(account_pool)契约测试。 +// +// 覆盖必测项:a 双平台显式同别名→有序 pool;b 官方 deepseek 空 mapping + +// opencode 显式 mapping→pool、空 mapping 无关 openai/zhipu 不入;e 显式 route +// 仍 single 且 UpstreamModel 语义不变;f 瞬态限流不改能力池、配置移除声明改变 +// 能力;h ctx roundtrip 池不被单 target 污染、切片引用修改不影响 ctx。 + +func compositePoolOwnershipRepo(accounts []Account) *compositeOwnershipAccountRepo { + return &compositeOwnershipAccountRepo{accounts: accounts} +} + +// a. 双平台对同一公开模型的显式映射 → Matched=true + 去重升序 CandidatePlatforms。 +func TestCompositePoolOwnershipDualPlatformExplicitAlias(t *testing.T) { + groupID := int64(7) + repo := compositePoolOwnershipRepo([]Account{ + { + ID: 1, + Platform: PlatformZhipu, + Credentials: map[string]any{ + "model_mapping": map[string]any{"router-model": "glm-5.2"}, + }, + }, + { + ID: 2, + Platform: PlatformDeepseek, + Credentials: map[string]any{ + "model_mapping": map[string]any{"router-model": "deepseek-v4-pro"}, + }, + }, + // 同平台重复声明去重:openai 两个账号都声明,不产生重复平台项。 + { + ID: 3, + Platform: PlatformOpenAI, + Credentials: map[string]any{ + "model_mapping": map[string]any{"router-model": "gpt-5"}, + }, + }, + { + ID: 4, + Platform: PlatformOpenAI, + Credentials: map[string]any{ + "model_mapping": map[string]any{"router-model": "gpt-5.1"}, + }, + }, + }) + svc := &GatewayService{accountRepo: repo} + + ownership, err := svc.resolveCompositeModelOwnership(context.Background(), groupID, "router-model") + require.NoError(t, err) + require.True(t, ownership.Matched) + require.False(t, ownership.Ambiguous) + require.Empty(t, ownership.TargetPlatform) + require.Equal(t, []string{PlatformDeepseek, PlatformOpenAI, PlatformZhipu}, ownership.CandidatePlatforms) +} + +// b. 官方 deepseek 空 mapping(规则B,强声明)+ opencode 显式 mapping(规则A +// 精确,强声明)→ 双平台 pool;空 mapping 的无关 openai/zhipu 账号不入池。 +func TestCompositePoolOwnershipDeepseekNativePlusOpenCodeMapping(t *testing.T) { + groupID := int64(7) + repo := compositePoolOwnershipRepo([]Account{ + {ID: 1, Platform: PlatformDeepseek}, + { + ID: 2, + Platform: PlatformOpenCodeGo, + Credentials: map[string]any{ + "model_mapping": map[string]any{"deepseek-chat": "deepseek-chat"}, + }, + }, + {ID: 3, Platform: PlatformOpenAI}, + {ID: 4, Platform: PlatformZhipu}, + }) + svc := &GatewayService{accountRepo: repo} + + ownership, err := svc.resolveCompositeModelOwnership(context.Background(), groupID, "deepseek-chat") + require.NoError(t, err) + require.True(t, ownership.Matched) + require.Empty(t, ownership.TargetPlatform) + require.Equal(t, []string{PlatformDeepseek, PlatformOpenCodeGo}, ownership.CandidatePlatforms) + + // 仅 deepseek 空 mapping 声明时保持 single(既有语义)。 + single, err := svc.resolveCompositeModelOwnership(context.Background(), groupID, "deepseek-reasoner") + require.NoError(t, err) + require.Equal(t, CompositeModelOwnership{TargetPlatform: PlatformDeepseek, Matched: true}, single) +} + +// 声明强度分层:有强声明平台时通配 catch-all 平台不混池;完全无强声明才 +// 使用通配命中平台集合(可构成 fallback 池)。 +func TestCompositePoolOwnershipClaimStrengthTiering(t *testing.T) { + groupID := int64(7) + svc := func(accounts []Account) *GatewayService { + return &GatewayService{accountRepo: compositePoolOwnershipRepo(accounts)} + } + + // grok 精确(强)+ openai/zhipu "*"(弱)→ 仅 grok(否则 grok 请求被改写为 + // 通配目标模型,回归)。 + grokFirst := svc([]Account{ + { + ID: 1, + Platform: PlatformGrok, + Credentials: map[string]any{ + "model_mapping": map[string]any{"grok-public": "grok-4.3"}, + }, + }, + { + ID: 2, + Platform: PlatformOpenAI, + Credentials: map[string]any{"model_mapping": map[string]any{"*": "gpt-5"}}, + }, + { + ID: 3, + Platform: PlatformZhipu, + Credentials: map[string]any{"model_mapping": map[string]any{"*": "glm-5.2"}}, + }, + }) + ownership, err := grokFirst.resolveCompositeModelOwnership(context.Background(), groupID, "grok-public") + require.NoError(t, err) + require.Equal(t, CompositeModelOwnership{TargetPlatform: PlatformGrok, Matched: true}, ownership) + + // 无任何强声明:deepseek/zhipu 均只有通配命中 → 使用通配 fallback 平台集合。 + wildcardOnly := svc([]Account{ + { + ID: 1, + Platform: PlatformDeepseek, + Credentials: map[string]any{"model_mapping": map[string]any{"team-*": "deepseek-v4"}}, + }, + { + ID: 2, + Platform: PlatformZhipu, + Credentials: map[string]any{"model_mapping": map[string]any{"team-*": "glm-5.2", "zhipu-*": "glm-5.2"}}, + }, + }) + fallback, err := wildcardOnly.resolveCompositeModelOwnership(context.Background(), groupID, "team-alpha") + require.NoError(t, err) + require.True(t, fallback.Matched) + require.Empty(t, fallback.TargetPlatform) + require.Equal(t, []string{PlatformDeepseek, PlatformZhipu}, fallback.CandidatePlatforms) + + // 仅单个平台通配命中 → fallback single。 + singleWildcard, err := wildcardOnly.resolveCompositeModelOwnership(context.Background(), groupID, "zhipu-x") + require.NoError(t, err) + require.Equal(t, CompositeModelOwnership{TargetPlatform: PlatformZhipu, Matched: true}, singleWildcard) +} + +// e. 显式 route 优先于 pool,route 的 UpstreamModel 改写语义不变。 +func TestCompositePoolResolverExplicitRouteBeatsPool(t *testing.T) { + resolver := NewCompositeRouteResolver(compositeRouteRepoStub{ + routes: []CompositeModelRoute{ + { + ID: 10, + GroupID: 7, + PublicModel: "router-model", + MatchType: CompositeRouteMatchExact, + TargetPlatform: PlatformKimi, + UpstreamModel: "kimi-k2-thinking", + Endpoint: CompositeRouteEndpointAny, + Enabled: true, + }, + }, + }) + resolver.SetModelOwnershipResolver(func(context.Context, int64, string) (CompositeModelOwnership, error) { + return CompositeModelOwnership{ + Matched: true, + CandidatePlatforms: []string{PlatformKimi, PlatformZhipu}, + }, nil + }) + + decision, err := resolver.Resolve(context.Background(), 7, "router-model", CompositeRouteEndpointMessages) + require.NoError(t, err) + require.True(t, decision.Matched) + require.Equal(t, CompositeRouteSourceExplicit, decision.Source) + require.Equal(t, PlatformKimi, decision.TargetPlatform) + require.Equal(t, "kimi-k2-thinking", decision.UpstreamModel) + require.Empty(t, decision.CandidatePlatforms) + require.NotNil(t, decision.Route) +} + +// ownership 返回多平台候选 → pool decision;Ambiguous=true 但未携带候选的旧 +// mock/异常输入仍明确失败。 +func TestCompositePoolResolverReturnsPoolForOwnershipCandidates(t *testing.T) { + resolver := NewCompositeRouteResolver(nil) + resolver.SetModelOwnershipResolver(func(context.Context, int64, string) (CompositeModelOwnership, error) { + return CompositeModelOwnership{ + Matched: true, + CandidatePlatforms: []string{PlatformZhipu, PlatformDeepseek, PlatformDeepseek}, + }, nil + }) + + decision, err := resolver.Resolve(context.Background(), 7, "shared-alias", CompositeRouteEndpointChatCompletions) + require.NoError(t, err) + require.True(t, decision.Matched) + require.Equal(t, CompositeRouteSourceAccountPool, decision.Source) + require.Empty(t, decision.TargetPlatform) + require.Empty(t, decision.UpstreamModel) + require.Equal(t, []string{PlatformDeepseek, PlatformZhipu}, decision.CandidatePlatforms) +} + +func TestCompositePoolResolverAmbiguousWithoutCandidatesStillFails(t *testing.T) { + resolver := NewCompositeRouteResolver(nil) + resolver.SetModelOwnershipResolver(func(context.Context, int64, string) (CompositeModelOwnership, error) { + return CompositeModelOwnership{Ambiguous: true}, nil + }) + + decision, err := resolver.Resolve(context.Background(), 7, "shared-alias", CompositeRouteEndpointChatCompletions) + require.NoError(t, err) + require.False(t, decision.Matched) + require.Empty(t, decision.TargetPlatform) + require.Empty(t, decision.CandidatePlatforms) + require.Equal(t, "model is exposed by multiple provider platforms", decision.Reason) +} + +// f. 候选账号全部 rate-limited / overloaded 时能力池不变(选择期健康由 +// scheduler 后续处理);配置移除声明则能力立即变化。 +func TestCompositePoolOwnershipUnaffectedByTransientAccountState(t *testing.T) { + groupID := int64(7) + now := time.Now() + repo := compositePoolOwnershipRepo([]Account{ + { + ID: 1, + Platform: PlatformDeepseek, + RateLimitedAt: &now, + RateLimitResetAt: &now, + Credentials: map[string]any{ + "model_mapping": map[string]any{"deepseek-chat": "deepseek-chat"}, + }, + }, + { + ID: 2, + Platform: PlatformOpenCodeGo, + OverloadUntil: &now, + Credentials: map[string]any{ + "model_mapping": map[string]any{"deepseek-chat": "deepseek-chat"}, + }, + }, + }) + svc := &GatewayService{accountRepo: repo} + + limited, err := svc.resolveCompositeModelOwnership(context.Background(), groupID, "deepseek-chat") + require.NoError(t, err) + require.True(t, limited.Matched) + require.Equal(t, []string{PlatformDeepseek, PlatformOpenCodeGo}, limited.CandidatePlatforms) + + // 配置移除 opencode 声明 → 池坍缩为 deepseek single。 + repo.accounts = []Account{repo.accounts[0]} + single, err := svc.resolveCompositeModelOwnership(context.Background(), groupID, "deepseek-chat") + require.NoError(t, err) + require.Equal(t, CompositeModelOwnership{TargetPlatform: PlatformDeepseek, Matched: true}, single) + + // 配置移除全部声明 → 能力消失(0 候选,回退 detector/unknown 原逻辑)。 + repo.accounts = nil + none, err := svc.resolveCompositeModelOwnership(context.Background(), groupID, "deepseek-chat") + require.NoError(t, err) + require.Equal(t, CompositeModelOwnership{}, none) +} + +// h. ctx roundtrip:池决策不写 ResolvedTargetPlatform / ResolvedUpstreamModel; +// getter 返回副本;显式 pin 不污染池值(但 shortcut 以 pin 为先,保持 single 行为)。 +func TestCompositePoolContextRoundTrip(t *testing.T) { + poolDecision := CompositeRouteDecision{ + Matched: true, + Source: CompositeRouteSourceAccountPool, + GroupID: 7, + PublicModel: "deepseek-chat", + CandidatePlatforms: []string{PlatformDeepseek, PlatformOpenCodeGo}, + Endpoint: CompositeRouteEndpointAny, + } + ctx := WithCompositeRouteDecision(context.Background(), poolDecision) + + candidates := CompositeCandidatePlatformsFromContext(ctx) + require.Equal(t, []string{PlatformDeepseek, PlatformOpenCodeGo}, candidates) + _, hasPlatform := ResolvedTargetPlatformFromContext(ctx) + require.False(t, hasPlatform) + _, hasUpstream := ResolvedUpstreamModelFromContext(ctx) + require.False(t, hasUpstream) + source, hasSource := CompositeRouteSourceFromContext(ctx) + require.True(t, hasSource) + require.Equal(t, CompositeRouteSourceAccountPool, source) + + // 切片引用修改不影响 ctx 内的池。 + candidates[0] = "polluted" + require.Equal(t, []string{PlatformDeepseek, PlatformOpenCodeGo}, CompositeCandidatePlatformsFromContext(ctx)) + + // WithCompositeCandidatePlatforms 归一化:去重、去空白、升序、副本。 + normalizedCtx := WithCompositeCandidatePlatforms(context.Background(), + []string{PlatformZhipu, " ", PlatformDeepseek, PlatformZhipu}) + require.Equal(t, []string{PlatformDeepseek, PlatformZhipu}, CompositeCandidatePlatformsFromContext(normalizedCtx)) + require.Nil(t, CompositeCandidatePlatformsFromContext(WithCompositeCandidatePlatforms(context.Background(), nil))) + require.Nil(t, CompositeCandidatePlatformsFromContext(context.Background())) + + // 单平台决策不携带池。 + singleCtx := WithCompositeRouteDecision(context.Background(), CompositeRouteDecision{ + Matched: true, + Source: CompositeRouteSourceAccount, + GroupID: 7, + PublicModel: "deepseek-chat", + TargetPlatform: PlatformDeepseek, + UpstreamModel: "deepseek-chat", + }) + require.Nil(t, CompositeCandidatePlatformsFromContext(singleCtx)) +} + +// resolveCompositeRouteDecision:池在 ctx 时 shortcut 返回完整 pool decision +// (不报 unknown、不折叠 detector);显式 pin 优先于池(既有 single 行为)。 +func TestCompositePoolShortcutDecisionFromContext(t *testing.T) { + svc := &GatewayService{compositeResolver: NewCompositeRouteResolver(nil)} + group := &Group{ID: 7, Platform: PlatformComposite} + + poolCtx := WithCompositeRouteDecision(context.Background(), CompositeRouteDecision{ + Matched: true, + Source: CompositeRouteSourceAccountPool, + GroupID: 7, + PublicModel: "shared-alias", + CandidatePlatforms: []string{PlatformDeepseek, PlatformZhipu}, + }) + + decision, ok, err := svc.resolveCompositeRouteDecision(poolCtx, group, "shared-alias", CompositeRouteEndpointMessages) + require.NoError(t, err) + require.True(t, ok) + require.True(t, decision.Matched) + require.True(t, isCompositePoolDecision(decision)) + require.Equal(t, CompositeRouteSourceAccountPool, decision.Source) + require.Empty(t, decision.TargetPlatform) + require.Empty(t, decision.UpstreamModel) + require.Equal(t, []string{PlatformDeepseek, PlatformZhipu}, decision.CandidatePlatforms) + + // 显式 pin(如 gemini 端点 fallback)优先:保持既有 single 行为,且池值不被污染。 + pinnedCtx := WithResolvedTargetPlatform(poolCtx, PlatformOpenAI) + pinned, ok, err := svc.resolveCompositeRouteDecision(pinnedCtx, group, "shared-alias", CompositeRouteEndpointMessages) + require.NoError(t, err) + require.True(t, ok) + require.False(t, isCompositePoolDecision(pinned)) + require.Equal(t, PlatformOpenAI, pinned.TargetPlatform) + require.Equal(t, []string{PlatformDeepseek, PlatformZhipu}, CompositeCandidatePlatformsFromContext(pinnedCtx)) +} + +// isCompositePoolDecision 判定契约。 +func TestIsCompositePoolDecision(t *testing.T) { + require.False(t, isCompositePoolDecision(CompositeRouteDecision{ + Matched: true, + TargetPlatform: PlatformOpenAI, + })) + require.False(t, isCompositePoolDecision(CompositeRouteDecision{Matched: true})) + require.True(t, isCompositePoolDecision(CompositeRouteDecision{ + Matched: true, + CandidatePlatforms: []string{PlatformOpenAI}, + })) +} diff --git a/backend/internal/service/composite_pool_policy.go b/backend/internal/service/composite_pool_policy.go new file mode 100644 index 0000000000..076dcbe8ce --- /dev/null +++ b/backend/internal/service/composite_pool_policy.go @@ -0,0 +1,95 @@ +package service + +import "context" + +// composite 账号池 per-attempt 渠道策略薄包装。 +// +// 背景(审查 BUG B):channelLookupPlatform 的作用域取 ForcePlatform > +// ResolvedTargetPlatform(composite 分组)> 分组平台。池请求在选号前 ctx 没有 +// resolved 平台,调度阶段 checkChannelPricingRestriction / 渠道映射按 composite +// 分组跨全部具体平台行匹配,渠道映射与定价限制被绕过。 +// +// 修复方式:handler 在账号选定后构造 attempt 局部 ctx +//(WithResolvedTargetPlatform(originalCtx, account.Platform),仅供该 attempt 的 +// 渠道/计费/forward),再用本文件的入口做平台作用域策略检查。这里只复用既有 +// 语义、不新增渠道服务行为: +// - CompositePoolAttemptChannelRestricted 与调度阶段同一组合检查: +// checkChannelPricingRestriction(requested/channel_mapped/response 计费基准) +// + BillingModelSource=upstream 时的逐账号 upstream 模型检查,仅作用域换为 +// 选中平台。 +// - CompositePoolAttemptChannelMapping 返回平台作用域的渠道映射,供 +// per-attempt 派生 channel-mapped body 与 usage 字段。 +// +// 全部为纯读 + lazy cache 加载:不扣费、不写计数、不改任何持久状态。 + +// compositePoolDeniedPlatformsKey 携带一次请求内的 deniedPlatforms 列表。 +// 与收缩候选池不同:候选池保持 immutable,selector 在 list/sticky 门上按本列表 +// 过滤,sticky 账号因 denied 暂时排除时按 excluded 语义提前返回、不清粘性绑定。 +type compositePoolDeniedPlatformsKey struct{} + +// WithCompositePoolDeniedPlatforms 在 ctx 上写入 deniedPlatforms 副本(去重升序)。 +// 空列表不改写 ctx。请求局部、不落任何持久状态。 +func WithCompositePoolDeniedPlatforms(ctx context.Context, platforms []string) context.Context { + normalized := normalizeCompositeCandidatePlatforms(platforms) + if ctx == nil || len(normalized) == 0 { + return ctx + } + return context.WithValue(ctx, compositePoolDeniedPlatformsKey{}, normalized) +} + +// CompositePoolDeniedPlatformsFromContext 返回当前请求的 deniedPlatforms 快照 +// (副本);未携带时返回 nil。导出供 handler 断言与诊断。 +func CompositePoolDeniedPlatformsFromContext(ctx context.Context) []string { + if ctx == nil { + return nil + } + platforms, ok := ctx.Value(compositePoolDeniedPlatformsKey{}).([]string) + if !ok { + return nil + } + out := make([]string, len(platforms)) + copy(out, platforms) + return out +} + +// compositePoolPlatformDenied 报告平台是否被本次请求的策略 deny 暂时排除。 +func compositePoolPlatformDenied(ctx context.Context, platform string) bool { + if ctx == nil || platform == "" { + return false + } + for _, denied := range CompositePoolDeniedPlatformsFromContext(ctx) { + if denied == platform { + return true + } + } + return false +} + +// CompositePoolAttemptChannelRestricted 报告选中账号平台作用域下该模型是否被 +// 渠道定价限制拒绝。ctx 必须是带 ResolvedTargetPlatform=account.Platform 的 +// attempt 局部 ctx。语义与调度阶段逐候选检查一致(checkChannelPricingRestriction +// + upstream 计费基准的逐账号检查),不重复检查用户配额或 RPM。 +func (s *OpenAIGatewayService) CompositePoolAttemptChannelRestricted(ctx context.Context, groupID *int64, account *Account, requestedModel string, requireCompact bool) bool { + if s == nil || groupID == nil || account == nil || requestedModel == "" { + return false + } + if s.checkChannelPricingRestriction(ctx, groupID, requestedModel) { + return true + } + if s.needsUpstreamChannelRestrictionCheck(ctx, groupID) && + s.isUpstreamModelRestrictedByChannel(ctx, *groupID, account, requestedModel, requireCompact) { + return true + } + return false +} + +// CompositePoolAttemptChannelMapping 返回选中账号平台作用域的渠道级模型映射。 +// ctx 必须是带 ResolvedTargetPlatform=account.Platform 的 attempt 局部 ctx, +// 保证映射只在该平台的映射行内解析,不跨平台串行。公开请求模型仍由调用方持有, +// 映射结果仅用于该 attempt 的 body 派生 / 计费字段。 +func (s *OpenAIGatewayService) CompositePoolAttemptChannelMapping(ctx context.Context, groupID *int64, requestedModel string) ChannelMappingResult { + if s == nil || groupID == nil { + return ChannelMappingResult{MappedModel: requestedModel} + } + return s.ResolveChannelMapping(ctx, *groupID, requestedModel) +} diff --git a/backend/internal/service/composite_route_resolver.go b/backend/internal/service/composite_route_resolver.go index 5d73de7de0..be86c74548 100644 --- a/backend/internal/service/composite_route_resolver.go +++ b/backend/internal/service/composite_route_resolver.go @@ -112,7 +112,21 @@ func (r *CompositeRouteResolver) Resolve(ctx context.Context, groupID int64, mod if _, detectable := DetectModelPlatform(model); !detectable { return decision, fmt.Errorf("resolve account model ownership: %w", err) } + } else if len(normalizeCompositeCandidatePlatforms(ownership.CandidatePlatforms)) > 1 { + // 稳定候选池:同一公开模型由多个平台同时提供。Matched=true 且 + // TargetPlatform 为空,不回退 generic/detector,也不在此猜单平台; + // 选择期由统一 OpenAI 兼容 selector 按既有 priority/load/sticky 决定。 + return CompositeRouteDecision{ + Matched: true, + Source: CompositeRouteSourceAccountPool, + GroupID: groupID, + PublicModel: model, + CandidatePlatforms: normalizeCompositeCandidatePlatforms(ownership.CandidatePlatforms), + Endpoint: endpoint, + }, nil } else if ownership.Ambiguous { + // 旧形态保护:Ambiguous=true 但未携带候选集合(老 mock / 异常输入) + // 仍明确失败,不伪造 pool,也不让 detector 猜单平台。 decision.Reason = "model is exposed by multiple provider platforms" return decision, nil } else if ownership.Matched { diff --git a/backend/internal/service/gateway_forward_as_chat_completions.go b/backend/internal/service/gateway_forward_as_chat_completions.go index 60b14488cd..e655089361 100644 --- a/backend/internal/service/gateway_forward_as_chat_completions.go +++ b/backend/internal/service/gateway_forward_as_chat_completions.go @@ -164,6 +164,7 @@ func (s *GatewayService) ForwardAsChatCompletions( AccountName: account.Name, UpstreamStatusCode: resp.StatusCode, UpstreamRequestID: resp.Header.Get("x-request-id"), + UpstreamURL: safeUpstreamURL(upstreamReq.URL.String()), Kind: "failover", Message: upstreamMsg, }) diff --git a/backend/internal/service/gateway_hotpath_optimization_test.go b/backend/internal/service/gateway_hotpath_optimization_test.go index 7a44456102..db7e31d9ec 100644 --- a/backend/internal/service/gateway_hotpath_optimization_test.go +++ b/backend/internal/service/gateway_hotpath_optimization_test.go @@ -180,6 +180,15 @@ func (s *modelsListAccountRepoStub) ListSchedulableByGroupID(ctx context.Context return out, nil } +// ListModelAvailabilityCandidates 模拟仓储的配置态查询:忽略限流/过载等瞬态 +// 状态字段,只按 byGroup 返回持久化配置的账号池。 +func (s *modelsListAccountRepoStub) ListModelAvailabilityCandidates(ctx context.Context, groupID *int64, platforms []string, _ bool) ([]Account, error) { + if groupID == nil || len(platforms) == 0 { + return nil, nil + } + return s.ListSchedulableByGroupID(ctx, *groupID) +} + func (s *modelsListAccountRepoStub) ListSchedulable(ctx context.Context) ([]Account, error) { s.listAllCalls.Add(1) if s.err != nil { @@ -565,9 +574,11 @@ func TestGetAvailableModels_UsesShortCacheAndSupportsInvalidation(t *testing.T) require.Equal(t, int64(2), store) } -// Scenario: 账号模型变更会失效所属平台缓存 -func TestResolveCompositeModelOwnershipUsesModelsCacheInvalidation(t *testing.T) { +// Scenario: ownership 基于配置态查询即时解析——不经过 modelsListCache TTL, +// 配置移除声明后能力立即变化;瞬态限流字段不影响能力池。 +func TestResolveCompositeModelOwnershipReflectsConfigImmediately(t *testing.T) { groupID := int64(9) + rateLimitedReset := time.Now().Add(30 * time.Minute) repo := &modelsListAccountRepoStub{ byGroup: map[int64][]Account{ groupID: {{ @@ -588,21 +599,39 @@ func TestResolveCompositeModelOwnershipUsesModelsCacheInvalidation(t *testing.T) require.Equal(t, CompositeModelOwnership{TargetPlatform: PlatformDeepseek, Matched: true}, first) require.Equal(t, int64(1), repo.listByGroupCalls.Load()) + // 瞬态限流字段(配置态查询会忽略)不改变能力。 + repo.byGroup[groupID] = []Account{{ + ID: 1, + Platform: PlatformDeepseek, + RateLimitedAt: &rateLimitedReset, + RateLimitResetAt: &rateLimitedReset, + Credentials: map[string]any{"model_mapping": map[string]any{"company-model": "deepseek-v4-pro"}}, + }} + transient, err := svc.resolveCompositeModelOwnership(context.Background(), groupID, "company-model") + require.NoError(t, err) + require.Equal(t, first, transient) + require.Equal(t, int64(2), repo.listByGroupCalls.Load()) + + // 配置移除声明后能力立即消失(无 TTL 旧列表)。 + repo.byGroup[groupID] = []Account{{ + ID: 2, + Platform: PlatformOpenAI, + }} + removed, err := svc.resolveCompositeModelOwnership(context.Background(), groupID, "company-model") + require.NoError(t, err) + require.Equal(t, CompositeModelOwnership{}, removed) + require.Equal(t, int64(3), repo.listByGroupCalls.Load()) + + // 换平台声明后立即生效。 repo.byGroup[groupID] = []Account{{ ID: 2, Platform: PlatformOpenAI, Credentials: map[string]any{"model_mapping": map[string]any{"company-model": "gpt-5"}}, }} - cached, err := svc.resolveCompositeModelOwnership(context.Background(), groupID, "company-model") - require.NoError(t, err) - require.Equal(t, first, cached) - require.Equal(t, int64(1), repo.listByGroupCalls.Load()) - - svc.InvalidateAvailableModelsCache(&groupID, PlatformDeepseek) refreshed, err := svc.resolveCompositeModelOwnership(context.Background(), groupID, "company-model") require.NoError(t, err) require.Equal(t, CompositeModelOwnership{TargetPlatform: PlatformOpenAI, Matched: true}, refreshed) - require.Equal(t, int64(2), repo.listByGroupCalls.Load()) + require.Equal(t, int64(4), repo.listByGroupCalls.Load()) } func TestGetAvailableModels_ErrorAndGlobalListBranches(t *testing.T) { diff --git a/backend/internal/service/gateway_scheduling.go b/backend/internal/service/gateway_scheduling.go index 059d7e2b2c..8acd70519c 100644 --- a/backend/internal/service/gateway_scheduling.go +++ b/backend/internal/service/gateway_scheduling.go @@ -56,6 +56,11 @@ func (s *GatewayService) SelectAccountForModelWithExclusions(ctx context.Context if !ok { return nil, fmt.Errorf("%w supporting model: %s (composite target platform unknown)", ErrNoAvailableAccounts, requestedModel) } + if isCompositePoolDecision(decision) { + // 多平台候选池由统一 OpenAI 兼容 selector 选择(openai_gateway_scheduling + // 链路);generic 调度器不消费池,显式失败避免以空平台误调度。 + return nil, fmt.Errorf("%w supporting model: %s (composite candidate pool %s)", ErrNoAvailableAccounts, requestedModel, strings.Join(decision.CandidatePlatforms, ",")) + } platform = decision.TargetPlatform requestedModel = decision.UpstreamModel ctx = WithCompositeRouteDecision(ctx, decision) @@ -987,6 +992,9 @@ func (s *GatewayService) resolvePlatform(ctx context.Context, groupID *int64, gr if !ok { return "", false, fmt.Errorf("%w supporting model: %s (composite target platform unknown)", ErrNoAvailableAccounts, requestedModel) } + if isCompositePoolDecision(decision) { + return "", false, fmt.Errorf("%w supporting model: %s (composite candidate pool %s)", ErrNoAvailableAccounts, requestedModel, strings.Join(decision.CandidatePlatforms, ",")) + } return decision.TargetPlatform, false, nil } return group.Platform, false, nil @@ -1004,6 +1012,9 @@ func (s *GatewayService) resolvePlatform(ctx context.Context, groupID *int64, gr if !ok { return "", false, fmt.Errorf("%w supporting model: %s (composite target platform unknown)", ErrNoAvailableAccounts, requestedModel) } + if isCompositePoolDecision(decision) { + return "", false, fmt.Errorf("%w supporting model: %s (composite candidate pool %s)", ErrNoAvailableAccounts, requestedModel, strings.Join(decision.CandidatePlatforms, ",")) + } return decision.TargetPlatform, false, nil } return group.Platform, false, nil @@ -2609,7 +2620,7 @@ func summarizeSelectionFailureStats(stats selectionFailureStats) string { // 对于 Antigravity 平台,会先获取映射后的最终模型名(包括 thinking 后缀)再检查支持 func (s *GatewayService) isModelSupportedByAccountWithContext(ctx context.Context, account *Account, requestedModel string) bool { if source, ok := CompositeRouteSourceFromContext(ctx); ok && source == CompositeRouteSourceAccount { - if publicModel, modelOK := RequestedPublicModelFromContext(ctx); modelOK && !explicitModelMappingClaims(*account, publicModel) { + if publicModel, modelOK := RequestedPublicModelFromContext(ctx); modelOK && !CompositeAccountClaimsModel(account, publicModel) { return false } } diff --git a/backend/internal/service/gateway_service.go b/backend/internal/service/gateway_service.go index c22097ede1..1eaeea250f 100644 --- a/backend/internal/service/gateway_service.go +++ b/backend/internal/service/gateway_service.go @@ -71,9 +71,8 @@ const ( ) const ( - cacheTTLTarget5m = "5m" - cacheTTLTarget1h = "1h" - compositeModelOwnershipCachePrefix = "composite-owner|" + cacheTTLTarget5m = "5m" + cacheTTLTarget1h = "1h" ) // ForceCacheBillingContextKey 强制缓存计费上下文键 @@ -529,10 +528,6 @@ func modelsListCacheKey(groupID *int64, platform string) string { return fmt.Sprintf("%d|%s", derefGroupID(groupID), strings.TrimSpace(platform)) } -func compositeModelOwnershipCacheKey(groupID int64, model string) string { - return fmt.Sprintf("%s%d|%s", compositeModelOwnershipCachePrefix, groupID, strings.TrimSpace(model)) -} - func prefetchedStickyGroupIDFromContext(ctx context.Context) (int64, bool) { return PrefetchedStickyGroupIDFromContext(ctx) } @@ -1482,59 +1477,82 @@ func (s *GatewayService) GetAvailableModels(ctx context.Context, groupID *int64, return cloneStringSlice(models) } +// compositeOwnershipQueryPlatforms 返回 ownership 候选扫描的平台全集。 +// ListModelAvailabilityCandidates 要求显式传入平台列表(空列表返回空结果), +// 这里传入全部可承接请求的具体平台,与旧 ListSchedulableByGroupID 的扫描范围 +// 保持一致,组隔离由该查询的 groupID 维度保证。 +func compositeOwnershipQueryPlatforms() []string { + return []string{ + PlatformAnthropic, PlatformOpenAI, PlatformGemini, PlatformAntigravity, PlatformGrok, + PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo, + } +} + +// resolveCompositeModelOwnership 基于持久化配置判断一个公开模型由组内哪些平台 +// 提供。数据源是 ListModelAvailabilityCandidates(active + schedulable,显式 +// 忽略限流/过载/临时不可调度等瞬态状态),能力谓词是统一共享的 +// CompositeAccountClaimStrength。刻意不经过 modelsListCache:旧 TTL 缓存会把 +// 「带瞬态过滤的旧健康列表」喂给池,全部候选 rate-limited 时能力会凭空消失; +// 移除后每次解析即反映最新配置(含 mapping 移除),代价是每次一次配置态查询。 +// +// 声明强度分层:精确 mapping 命中与受控 native 空映射同为强声明;通配命中仅 +// 为弱声明(fallback)。存在强声明平台时仅强声明平台构成池/单平台,完全无强 +// 声明才回退通配命中平台集合,避免通配 catch-all 账号与显式声明平台混池。 +// +// 返回:0 候选 → 零值(调用方回退 detector / unknown);1 候选 → 单平台 +// (既有语义);>1 → Matched=true + CandidatePlatforms(去重升序)的池。 func (s *GatewayService) resolveCompositeModelOwnership(ctx context.Context, groupID int64, model string) (CompositeModelOwnership, error) { model = strings.TrimSpace(model) if s == nil || s.accountRepo == nil || groupID <= 0 || model == "" { return CompositeModelOwnership{}, nil } - cacheKey := compositeModelOwnershipCacheKey(groupID, model) - if s.modelsListCache != nil { - if cached, found := s.modelsListCache.Get(cacheKey); found { - if ownership, ok := cached.(CompositeModelOwnership); ok { - return ownership, nil - } - } - } - - accounts, err := s.accountRepo.ListSchedulableByGroupID(ctx, groupID) + accounts, err := s.accountRepo.ListModelAvailabilityCandidates(ctx, &groupID, compositeOwnershipQueryPlatforms(), true) if err != nil { return CompositeModelOwnership{}, err } - platforms := make(map[string]struct{}) - for _, account := range accounts { + strongPlatforms := make(map[string]struct{}) + wildcardPlatforms := make(map[string]struct{}) + for i := range accounts { + account := &accounts[i] platform := strings.TrimSpace(account.Platform) - if !isConcreteRequestPlatform(platform) || !explicitModelMappingClaims(account, model) { + if !isConcreteRequestPlatform(platform) { continue } - platforms[platform] = struct{}{} + switch CompositeAccountClaimStrength(account, model) { + case CompositeClaimExplicit: + strongPlatforms[platform] = struct{}{} + case CompositeClaimWildcard: + wildcardPlatforms[platform] = struct{}{} + } + } + + claimedPlatforms := strongPlatforms + if len(claimedPlatforms) == 0 { + claimedPlatforms = wildcardPlatforms } ownership := CompositeModelOwnership{} - if len(platforms) == 1 { - for platform := range platforms { + switch len(claimedPlatforms) { + case 1: + for platform := range claimedPlatforms { ownership.TargetPlatform = platform } ownership.Matched = true - } else if len(platforms) > 1 { - ownership.Ambiguous = true - } - - if s.modelsListCache != nil { - s.modelsListCache.Set(cacheKey, ownership, s.modelsListCacheTTL) + default: + if len(claimedPlatforms) > 1 { + candidates := make([]string, 0, len(claimedPlatforms)) + for platform := range claimedPlatforms { + candidates = append(candidates, platform) + } + ownership.Matched = true + ownership.CandidatePlatforms = normalizeCompositeCandidatePlatforms(candidates) + } } return ownership, nil } -func explicitModelMappingClaims(account Account, model string) bool { - if account.Credentials == nil || model == "" { - return false - } - mapped, ok := stringMappingFromRaw(account.Credentials["model_mapping"])[model] - return ok && strings.TrimSpace(mapped) != "" -} - // GetCompositeRouteModels returns public IDs from enabled exact composite routes. func (s *GatewayService) GetCompositeRouteModels(ctx context.Context, groupID *int64, endpoint string, includeSystemOne bool) ([]string, error) { if s == nil || s.compositeResolver == nil || groupID == nil { @@ -1582,7 +1600,6 @@ func (s *GatewayService) InvalidateAvailableModelsCache(groupID *int64, platform if s == nil || s.modelsListCache == nil { return } - s.invalidateCompositeModelOwnershipCache(groupID) normalizedPlatform := strings.TrimSpace(platform) // 完整匹配时精准失效;否则按维度批量失效。 @@ -1611,26 +1628,6 @@ func (s *GatewayService) InvalidateAvailableModelsCache(groupID *int64, platform } } -func (s *GatewayService) invalidateCompositeModelOwnershipCache(groupID *int64) { - for key := range s.modelsListCache.Items() { - if !strings.HasPrefix(key, compositeModelOwnershipCachePrefix) { - continue - } - if groupID == nil { - s.modelsListCache.Delete(key) - continue - } - parts := strings.SplitN(strings.TrimPrefix(key, compositeModelOwnershipCachePrefix), "|", 2) - if len(parts) != 2 { - continue - } - cachedGroupID, err := strconv.ParseInt(parts[0], 10, 64) - if err == nil && cachedGroupID == *groupID { - s.modelsListCache.Delete(key) - } - } -} - const debugGatewayBodyDefaultFilename = "gateway_debug.log" // initDebugGatewayBodyFile 初始化网关调试日志文件。 diff --git a/backend/internal/service/gateway_upstream_record_test.go b/backend/internal/service/gateway_upstream_record_test.go new file mode 100644 index 0000000000..7d9cfa8c06 --- /dev/null +++ b/backend/internal/service/gateway_upstream_record_test.go @@ -0,0 +1,115 @@ +//go:build unit + +package service + +import ( + "bytes" + "context" + "errors" + "io" + "net/http" + "net/http/httptest" + "testing" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +// composite 组 inbound=/v1/chat/completions 经 CC→Anthropic 桥打到 Anthropic +// 上游 404(非 failover 分支,无 ForwardResult):buildUpstreamRequest 发送前 +// 记录的实际出站端点与最终映射模型必须保留,供错误日志如实报告。 +func TestForwardAsChatCompletionsRetainsActualUpstreamMetadataOn404(t *testing.T) { + gin.SetMode(gin.TestMode) + upstream := &queuedHTTPUpstreamStub{responses: []*http.Response{{ + StatusCode: http.StatusNotFound, + Header: http.Header{"X-Request-Id": []string{"nf-404"}}, + Body: io.NopCloser(http.NoBody), + }}} + svc := &GatewayService{ + cfg: &config.Config{}, + httpUpstream: upstream, + tlsFPProfileService: &TLSFingerprintProfileService{}, + } + body := []byte(`{"model":"claude-sonnet-4-5","messages":[{"role":"user","content":"hello"}]}`) + recorder := httptest.NewRecorder() + c, _ := gin.CreateTestContext(recorder) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/chat/completions", nil) + account := &Account{ + ID: 7, + Name: "cc-bridge-anthropic", + Platform: PlatformAnthropic, + Type: AccountTypeAPIKey, + Credentials: map[string]any{"api_key": "test-key"}, + } + + _, err := svc.ForwardAsChatCompletions(context.Background(), c, account, body, nil) + require.Error(t, err) + require.Contains(t, err.Error(), "404") + + // 实际出站 path(不含 ?beta=true query)与最终映射模型都被保留。 + require.Equal(t, "/v1/messages", GetOpsUpstreamEndpoint(c)) + require.Equal(t, "claude-sonnet-4-5", c.GetString(OpsUpstreamModelKey)) + require.Equal(t, 1, upstream.callCount) +} + +// adaptive/anthropic 协议账号(composite 兼容池常见):/v1/messages 入站零转换 +// 直通供应商原生 /v1/messages。传输层失败也要保留真实端点与映射模型,不得 +// 报成按平台推导的 /v1/responses。 +func TestForwardAsAnthropicNativeBridgeRecordsActualPathAndModel(t *testing.T) { + gin.SetMode(gin.TestMode) + upstream := &httpUpstreamRecorder{err: errors.New("stop after capture")} + svc := &OpenAIGatewayService{cfg: rawChatCompletionsTestConfig(), httpUpstream: upstream} + account := adaptiveProtocolTestAccount(PlatformDeepseek, map[string]any{ + APIProtocolAnthropic: "http://anthropic.example", + }) + body := []byte(`{"model":"deepseek-chat","max_tokens":32,"messages":[{"role":"user","content":"hello"}],"stream":false}`) + recorder := httptest.NewRecorder() + c, _ := gin.CreateTestContext(recorder) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", bytes.NewReader(body)) + c.Request.Header.Set("Content-Type", "application/json") + + _, err := svc.ForwardAsAnthropic(context.Background(), c, account, body, "", "") + require.Error(t, err) + require.NotNil(t, upstream.lastReq) + require.Equal(t, "http://anthropic.example/v1/messages", upstream.lastReq.URL.String()) + + require.Equal(t, "/v1/messages", GetOpsUpstreamEndpoint(c)) + require.Equal(t, normalizeOpenAIModelForUpstream(account, "deepseek-chat"), c.GetString(OpsUpstreamModelKey)) +} + +// 固定 chat_completions 协议的 Messages 入站回退桥:端点由共享 CC 管线记录为 +// /v1/chat/completions(实际 CC 保持 CC),模型在发送前记录最终映射值。 +func TestForwardAsAnthropicRawCCBridgeRecordsMappedModel(t *testing.T) { + gin.SetMode(gin.TestMode) + upstream := &httpUpstreamRecorder{err: errors.New("stop after capture")} + svc := &OpenAIGatewayService{cfg: rawChatCompletionsTestConfig(), httpUpstream: upstream} + // 注意:固定 chat_completions 协议(非 adaptive)才会走 raw CC 回退桥; + // adaptive 账号的 /v1/messages 永远直通原生 Anthropic 端点。 + account := &Account{ + ID: 702, + Name: "cc-only-cn", + Platform: PlatformDeepseek, + Type: AccountTypeAPIKey, + Concurrency: 1, + Credentials: map[string]any{ + "api_key": "sk-test", + "api_protocol": APIProtocolChatCompletions, + "account_mode": AccountModePayG, + "base_url": "http://chat.example", + }, + } + body := []byte(`{"model":"deepseek-chat","max_tokens":32,"messages":[{"role":"user","content":"hello"}],"stream":false}`) + recorder := httptest.NewRecorder() + c, _ := gin.CreateTestContext(recorder) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", bytes.NewReader(body)) + c.Request.Header.Set("Content-Type", "application/json") + + _, err := svc.ForwardAsAnthropic(context.Background(), c, account, body, "", "") + require.Error(t, err) + require.NotNil(t, upstream.lastReq) + require.Equal(t, "http://chat.example/v1/chat/completions", upstream.lastReq.URL.String()) + + require.Equal(t, "/v1/chat/completions", GetActualOpenAIUpstreamEndpoint(c)) + require.Equal(t, normalizeOpenAIModelForUpstream(account, "deepseek-chat"), c.GetString(OpsUpstreamModelKey)) +} diff --git a/backend/internal/service/gateway_upstream_request.go b/backend/internal/service/gateway_upstream_request.go index 06ee09822c..0215a86085 100644 --- a/backend/internal/service/gateway_upstream_request.go +++ b/backend/internal/service/gateway_upstream_request.go @@ -222,6 +222,12 @@ func (s *GatewayService) buildUpstreamRequest(ctx context.Context, c *gin.Contex logClaudeMimicDebug(req, body, account, tokenType, mimicClaudeCode) } + // 发送前记录本次实际出站端点与最终映射模型:Do 之后即使 404/500 等失败 + // 没有 ForwardResult,错误日志也能报告真实上游路径(含错误拼接,如 + // /v1/v1/messages),而不是按入站路径推导的值。仅记录 URL path,不含 + // query(?beta=true)/userinfo/凭证。 + SetOpsUpstreamRequestTarget(c, req, modelID) + return req, body, nil } @@ -347,6 +353,9 @@ func (s *GatewayService) buildUpstreamRequestAnthropicVertex( "stream": strconv.FormatBool(reqStream), }) + // 与直连路径一致:发送前记录实际出站端点与最终模型,失败也保留。 + SetOpsUpstreamRequestTarget(c, req, modelID) + return req, nil } diff --git a/backend/internal/service/openai_account_scheduler.go b/backend/internal/service/openai_account_scheduler.go index ae4e2c2321..97e5f57197 100644 --- a/backend/internal/service/openai_account_scheduler.go +++ b/backend/internal/service/openai_account_scheduler.go @@ -379,6 +379,61 @@ func newDefaultOpenAIAccountScheduler(service *OpenAIGatewayService, stats *open } } +// attemptPreviousResponseLayer 尝试 previous_response_id 归属层:高级调度器 +// Select 与 legacy+active composite pool 两条路径共用同一套 pin 选择与 +// 兼容/transport/group/model/profit 复检。attempted=true 表示本层已执行(无论 +// 是否命中);selection 非 nil 即命中(含 owner WaitPlan),decision 已置 +// StickyPreviousHit 与层名。 +func (s *defaultOpenAIAccountScheduler) attemptPreviousResponseLayer( + ctx context.Context, + req OpenAIAccountScheduleRequest, + decision *OpenAIAccountScheduleDecision, +) (*AccountSelectionResult, bool, error) { + previousResponseID := strings.TrimSpace(req.PreviousResponseID) + if previousResponseID == "" || NormalizeOpenAICompatiblePlatform(req.Platform) != PlatformOpenAI || + (req.StickyWeighted && req.PreviousResponseCanMove) { + return nil, false, nil + } + selection, err := s.service.selectAccountByPreviousResponseIDForCapability( + ctx, + req.GroupID, + previousResponseID, + req.RequestedModel, + req.ExcludedIDs, + req.RequiredCapability, + req.RequireCompact, + ) + if err != nil { + return nil, true, err + } + if selection != nil && selection.Account != nil { + compatible, _ := s.isAccountRequestCompatibleReason(ctx, selection.Account, req) + hasGroupMetadata := len(selection.Account.GroupIDs) > 0 || len(selection.Account.AccountGroups) > 0 + groupCompatible := !hasGroupMetadata || openAIStickyAccountMatchesGroup(selection.Account, req.GroupID) + if hasGroupMetadata && s.service != nil { + groupCompatible = s.service.openAIAccountMatchesSchedulingGroup(selection.Account, req.GroupID) + } + if !groupCompatible || + !compatible || !s.isAccountTransportCompatible(selection.Account, req.RequiredTransport) { + if selection.ReleaseFunc != nil { + selection.ReleaseFunc() + } + selection = nil + } + } + if selection != nil && selection.Account != nil { + decision.Layer = openAIAccountScheduleLayerPreviousResponse + decision.StickyPreviousHit = true + decision.SelectedAccountID = selection.Account.ID + decision.SelectedAccountType = selection.Account.Type + if req.SessionHash != "" { + _ = s.service.bindOpenAIStickySessionDuringSelection(ctx, req.GroupID, req.SessionHash, selection.Account.ID) + } + return selection, true, nil + } + return nil, true, nil +} + func (s *defaultOpenAIAccountScheduler) Select( ctx context.Context, req OpenAIAccountScheduleRequest, @@ -393,46 +448,12 @@ func (s *defaultOpenAIAccountScheduler) Select( s.metrics.recordSelect(decision) }() - previousResponseID := strings.TrimSpace(req.PreviousResponseID) - if previousResponseID != "" && NormalizeOpenAICompatiblePlatform(req.Platform) == PlatformOpenAI && - (!req.StickyWeighted || !req.PreviousResponseCanMove) { - selection, err := s.service.selectAccountByPreviousResponseIDForCapability( - ctx, - req.GroupID, - previousResponseID, - req.RequestedModel, - req.ExcludedIDs, - req.RequiredCapability, - req.RequireCompact, - ) - if err != nil { - return nil, decision, err - } - if selection != nil && selection.Account != nil { - compatible, _ := s.isAccountRequestCompatibleReason(ctx, selection.Account, req) - hasGroupMetadata := len(selection.Account.GroupIDs) > 0 || len(selection.Account.AccountGroups) > 0 - groupCompatible := !hasGroupMetadata || openAIStickyAccountMatchesGroup(selection.Account, req.GroupID) - if hasGroupMetadata && s.service != nil { - groupCompatible = s.service.openAIAccountMatchesSchedulingGroup(selection.Account, req.GroupID) - } - if !groupCompatible || - !compatible || !s.isAccountTransportCompatible(selection.Account, req.RequiredTransport) { - if selection.ReleaseFunc != nil { - selection.ReleaseFunc() - } - selection = nil - } - } - if selection != nil && selection.Account != nil { - decision.Layer = openAIAccountScheduleLayerPreviousResponse - decision.StickyPreviousHit = true - decision.SelectedAccountID = selection.Account.ID - decision.SelectedAccountType = selection.Account.Type - if req.SessionHash != "" { - _ = s.service.bindOpenAIStickySessionDuringSelection(ctx, req.GroupID, req.SessionHash, selection.Account.ID) - } - return selection, decision, nil - } + selection, attempted, err := s.attemptPreviousResponseLayer(ctx, req, &decision) + if err != nil { + return nil, decision, err + } + if attempted && selection != nil { + return selection, decision, nil } if req.GuardianParentAccountID > 0 { @@ -528,7 +549,13 @@ func (s *defaultOpenAIAccountScheduler) selectBySessionHash( clearBinding() return nil, false, nil } - if shouldClearStickySession(account, req.RequestedModel) || account.Platform != NormalizeOpenAICompatiblePlatform(req.Platform) || !account.IsOpenAICompatible() || !account.IsSchedulable() { + // composite pool denied 平台:sticky 账号只是暂时排除——必须在 + // shouldClearStickySession / recheck 等会 clearBinding 的分支之前跳过, + // 保留绑定回落其它候选。 + if compositePoolPlatformDenied(ctx, account.Platform) { + return nil, false, nil + } + if shouldClearStickySession(account, req.RequestedModel) || !openAISchedulingPlatformMatchesAccount(ctx, account, req.Platform) || !account.IsOpenAICompatible() || !account.IsSchedulable() { clearBinding() return nil, false, nil } @@ -1286,6 +1313,11 @@ func (s *defaultOpenAIAccountScheduler) tryFallbackToWeightedSticky( if err != nil || account == nil { continue } + // composite pool denied 平台:weighted sticky 回落同样不得回到被暂时 + // 排除的平台(不 delete,仅跳过)。 + if compositePoolPlatformDenied(ctx, account.Platform) { + continue + } if !s.isAccountRequestCompatible(ctx, account, req) || !s.isAccountTransportCompatible(account, req.RequiredTransport) { continue } @@ -1453,7 +1485,7 @@ func (s *defaultOpenAIAccountScheduler) selectByLoadBalance( filterStats.exclude("not_schedulable") continue } - if account.Platform != NormalizeOpenAICompatiblePlatform(req.Platform) || !account.IsOpenAICompatible() { + if !openAISchedulingPlatformMatchesAccount(ctx, account, req.Platform) || !account.IsOpenAICompatible() { filterStats.exclude("platform_mismatch") continue } @@ -1777,13 +1809,18 @@ func (s *defaultOpenAIAccountScheduler) isAccountRequestCompatibleReason(ctx con return false, "account_nil" } if source, ok := CompositeRouteSourceFromContext(ctx); ok && source == CompositeRouteSourceAccount { - if publicModel, modelOK := RequestedPublicModelFromContext(ctx); modelOK && !explicitModelMappingClaims(*account, publicModel) { + if publicModel, modelOK := RequestedPublicModelFromContext(ctx); modelOK && !CompositeAccountClaimsModel(account, publicModel) { return false, "account_model_not_owned" } } if req.RequirePrivacySet && !account.IsPrivacySet() { return false, "privacy_not_set" } + // composite account_pool:候选池 immutable,粘性/previous_response_id/抢槽后 + // 复检都必须重新校验池成员资格,防止池外账号经复检路径混入(池塌缩)。 + if openAICompositePoolActive(ctx) && !openAICompositePoolAllowsAccount(ctx, account) { + return false, "platform_mismatch" + } if s != nil && s.service != nil && s.service.isOpenAIAccountRequestRuntimeBlocked(account, req.RequestedModel) { return false, "runtime_blocked" } @@ -1812,7 +1849,7 @@ func (s *defaultOpenAIAccountScheduler) isAccountRequestCompatibleReason(ctx con }) { return false, "shadow_parent_unhealthy" } - if req.RequestedModel != "" && !account.IsModelSupported(req.RequestedModel) { + if req.RequestedModel != "" && !openAISchedulingModelSupported(ctx, account, req.RequestedModel) { return false, "model_not_supported" } if req.GroupID != nil && s != nil && s.service != nil && @@ -2370,6 +2407,33 @@ func (s *OpenAIGatewayService) selectAccountWithSchedulerOnce( return selection, decision, nil } } + // composite account_pool:legacy 调度的 previous_response_id 归属层。 + // 高级调度器关闭时 legacy 分支原本完全忽略 prevID;仅对「active pool + + // 非空 prevID」复用与高级调度器相同的 pin 选择与兼容/transport/group/ + // model/profit 复检,命中或 owner WaitPlan 均置 StickyPreviousHit。 + // 非池请求(含普通 legacy OpenAI)不进入本层,行为不变。 + if strings.TrimSpace(previousResponseID) != "" && openAICompositePoolActive(ctx) { + legacyScheduler := &defaultOpenAIAccountScheduler{service: s, stats: newOpenAIAccountRuntimeStats()} + pinSelection, attempted, pinErr := legacyScheduler.attemptPreviousResponseLayer(ctx, OpenAIAccountScheduleRequest{ + GroupID: groupID, + Platform: platform, + SessionHash: sessionHash, + RequestedModel: requestedModel, + RequiredTransport: requiredTransport, + RequiredCapability: requiredCapability, + RequiredImageCapability: requiredImageCapability, + RequireCompact: requireCompact, + ExcludedIDs: excludedIDs, + RequirePrivacySet: s.openAIGroupRequiresPrivacySet(ctx, groupID), + PreviousResponseID: previousResponseID, + }, &decision) + if pinErr != nil { + return nil, decision, pinErr + } + if attempted && pinSelection != nil && pinSelection.Account != nil { + return pinSelection, decision, nil + } + } legacySessionHash := sessionHash if preserveGuardianParentBinding { legacySessionHash = "" diff --git a/backend/internal/service/openai_account_scheduler_test.go b/backend/internal/service/openai_account_scheduler_test.go index 2b68313070..b58bf9140f 100644 --- a/backend/internal/service/openai_account_scheduler_test.go +++ b/backend/internal/service/openai_account_scheduler_test.go @@ -62,6 +62,31 @@ func (r schedulerTestOpenAIAccountRepo) ListSchedulableUngroupedByPlatform(ctx c return r.ListSchedulableByPlatform(ctx, platform) } +// ListModelAvailabilityCandidates 对齐 accountRepository.ListModelAvailabilityCandidates +// 的 group 分支语义:platforms 为空返回空结果;只返回持久化配置满足 +// active + schedulable 且平台在显式白名单内的账号,忽略限流/过载等瞬态状态。 +// 与本 fake 其余 List* 方法一致,组隔离不在此模拟(fake 内存数据未建组隔离语义)。 +func (r schedulerTestOpenAIAccountRepo) ListModelAvailabilityCandidates(_ context.Context, groupID *int64, platforms []string, _ bool) ([]Account, error) { + if groupID == nil || len(platforms) == 0 { + return []Account{}, nil + } + allowed := make(map[string]struct{}, len(platforms)) + for _, platform := range platforms { + allowed[platform] = struct{}{} + } + result := make([]Account, 0, len(r.accounts)) + for _, acc := range r.accounts { + if acc.Status != StatusActive || !acc.Schedulable { + continue + } + if _, ok := allowed[acc.Platform]; !ok { + continue + } + result = append(result, acc) + } + return result, nil +} + type schedulerGroupAwareOpenAIAccountRepo struct { schedulerTestOpenAIAccountRepo } diff --git a/backend/internal/service/openai_composite_pool_scheduling_test.go b/backend/internal/service/openai_composite_pool_scheduling_test.go new file mode 100644 index 0000000000..216bc01c79 --- /dev/null +++ b/backend/internal/service/openai_composite_pool_scheduling_test.go @@ -0,0 +1,1102 @@ +package service + +// 增量2A:OpenAI 兼容族 selector 跨平台候选池(composite account_pool)测试。 +// +// 覆盖: +// a. 双平台同模型按原 priority/load(LRU)跨平台选中; +// b. 同 session 连续请求与负载变化保持 sticky; +// c. sticky 缓存命名空间保持 openai: 前缀,legacy 读回退/双写不变; +// d. 失败排除首账号后跨平台选中并粘新账号,池不塌缩; +// e. 换 group 不复用绑定、换 model 重新资格检查; +// f. claims 谓词:官方 deepseek 空 mapping 参与、opencode_go 需显式 mapping、 +// 无关平台空 mapping 不入池; +// g. 全部候选瞬态不可用时保持无容量错误语义(ErrNoAvailableAccounts); +// h. previous_response_id pin 归属保持:pool 内仍优先同账号;账号失效按原策略 +// 删绑定;池外账号保留绑定且不跨平台带走 previous_response_id。 + +import ( + "context" + "errors" + "strconv" + "strings" + "sync" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/stretchr/testify/require" +) + +// ---- 测试专用 fake ---- + +// compositePoolTestCache 按 (groupID, cacheKey) 记录 sticky 绑定,并原样记录全部 +// Set/Delete 的 cacheKey,供命名空间(openai: 前缀)断言使用。 +type compositePoolTestCache struct { + GatewayCache + mu sync.Mutex + bindings map[string]int64 + setKeys []string + delKeys []string +} + +func compositePoolCacheKey(groupID int64, cacheKey string) string { + return strconv.FormatInt(groupID, 10) + "|" + cacheKey +} + +func (c *compositePoolTestCache) GetSessionAccountID(_ context.Context, groupID int64, cacheKey string) (int64, error) { + c.mu.Lock() + defer c.mu.Unlock() + if id, ok := c.bindings[compositePoolCacheKey(groupID, cacheKey)]; ok { + return id, nil + } + return 0, ErrStickySessionNotFound +} + +func (c *compositePoolTestCache) SetSessionAccountID(_ context.Context, groupID int64, cacheKey string, accountID int64, _ time.Duration) error { + c.mu.Lock() + defer c.mu.Unlock() + if c.bindings == nil { + c.bindings = make(map[string]int64) + } + c.bindings[compositePoolCacheKey(groupID, cacheKey)] = accountID + c.setKeys = append(c.setKeys, cacheKey) + return nil +} + +func (c *compositePoolTestCache) RefreshSessionTTL(_ context.Context, _ int64, _ string, _ time.Duration) error { + return nil +} + +func (c *compositePoolTestCache) DeleteSessionAccountID(_ context.Context, groupID int64, cacheKey string) error { + c.mu.Lock() + defer c.mu.Unlock() + delete(c.bindings, compositePoolCacheKey(groupID, cacheKey)) + c.delKeys = append(c.delKeys, cacheKey) + return nil +} + +func (c *compositePoolTestCache) binding(groupID int64, cacheKey string) (int64, bool) { + c.mu.Lock() + defer c.mu.Unlock() + id, ok := c.bindings[compositePoolCacheKey(groupID, cacheKey)] + return id, ok +} + +// compositePoolTestRepo 平台过滤语义与生产 repo 一致;组维度按账号 GroupIDs +// 过滤(对齐生产 ListSchedulableByGroupIDAndPlatform 的 SQL 语义),指针接收者 +// 支持用例中途改账号状态(解绑组、移除 mapping)。 +type compositePoolTestRepo struct { + AccountRepository + accounts []Account +} + +func (r *compositePoolTestRepo) GetByID(_ context.Context, id int64) (*Account, error) { + for i := range r.accounts { + if r.accounts[i].ID == id { + return &r.accounts[i], nil + } + } + return nil, errors.New("account not found") +} + +func accountInGroup(account *Account, groupID int64) bool { + if account == nil { + return false + } + return openAIStickyAccountMatchesGroup(account, &groupID) +} + +func (r *compositePoolTestRepo) listByPlatform(platform string) []Account { + var out []Account + for i := range r.accounts { + if r.accounts[i].Platform == platform { + out = append(out, r.accounts[i]) + } + } + return out +} + +func (r *compositePoolTestRepo) listByPlatformAndGroup(platform string, groupID int64) []Account { + var out []Account + for i := range r.accounts { + if r.accounts[i].Platform == platform && accountInGroup(&r.accounts[i], groupID) { + out = append(out, r.accounts[i]) + } + } + return out +} + +func (r *compositePoolTestRepo) ListSchedulableByPlatform(_ context.Context, platform string) ([]Account, error) { + return r.listByPlatform(platform), nil +} + +func (r *compositePoolTestRepo) ListSchedulableByGroupIDAndPlatform(_ context.Context, groupID int64, platform string) ([]Account, error) { + return r.listByPlatformAndGroup(platform, groupID), nil +} + +func (r *compositePoolTestRepo) ListSchedulableUngroupedByPlatform(_ context.Context, platform string) ([]Account, error) { + var out []Account + for i := range r.accounts { + if r.accounts[i].Platform == platform && openAIStickyAccountMatchesGroup(&r.accounts[i], nil) { + out = append(out, r.accounts[i]) + } + } + return out, nil +} + +func compositePoolTestAccount(id int64, platform string, groupID int64, priority int, mapping map[string]any) Account { + account := Account{ + ID: id, + Platform: platform, + Type: AccountTypeAPIKey, + Status: StatusActive, + Schedulable: true, + Concurrency: 1, + Priority: priority, + GroupIDs: []int64{groupID}, + } + if mapping != nil { + account.Credentials = map[string]any{"model_mapping": mapping} + } + return account +} + +func newCompositePoolTestService(accounts []Account, cache GatewayCache) *OpenAIGatewayService { + cfg := &config.Config{} + cfg.Gateway.Scheduling.LoadBatchEnabled = false + cfg.Gateway.OpenAIWS.SessionHashReadOldFallback = true + cfg.Gateway.OpenAIWS.SessionHashDualWriteOld = true + return &OpenAIGatewayService{ + accountRepo: &compositePoolTestRepo{accounts: accounts}, + cache: cache, + cfg: cfg, + concurrencyService: NewConcurrencyService(schedulerTestConcurrencyCache{}), + } +} + +func newCompositePoolAdvancedTestService(t *testing.T, accounts []Account, cache GatewayCache) *OpenAIGatewayService { + t.Helper() + resetOpenAIAdvancedSchedulerSettingCacheForTest() + svc := newCompositePoolTestService(accounts, cache) + svc.rateLimitService = newOpenAIAdvancedSchedulerRateLimitService("true") + require.True(t, svc.isOpenAIAdvancedSchedulerEnabled(context.Background())) + return svc +} + +// ---- a. 跨平台按 priority / load 选中 ---- + +func TestOpenAICompositePool_SelectsAcrossPlatformsByPriorityAndLoad(t *testing.T) { + resetOpenAIAdvancedSchedulerSettingCacheForTest() + defer resetOpenAIAdvancedSchedulerSettingCacheForTest() + + groupID := int64(22001) + // 公开模型 my-model 由两个平台账号分别经显式映射 claim(claims 规则 A), + // 保证同模型可跨平台比较 priority/load。 + model := "my-model" + pool := []string{PlatformDeepseek, PlatformOpenAI} + ctx := WithCompositeCandidatePlatforms(context.Background(), pool) + + build := func(deepseekPriority, openaiPriority int, deepseekUsed, openaiUsed *time.Time) (*OpenAIGatewayService, *compositePoolTestRepo) { + repo := &compositePoolTestRepo{accounts: []Account{ + compositePoolTestAccount(33001, PlatformDeepseek, groupID, deepseekPriority, map[string]any{"my-model": "deepseek-chat"}), + compositePoolTestAccount(33002, PlatformOpenAI, groupID, openaiPriority, map[string]any{"my-model": "gpt-4o"}), + }} + repo.accounts[0].LastUsedAt = deepseekUsed + repo.accounts[1].LastUsedAt = openaiUsed + return newCompositePoolTestService(repo.accounts, &compositePoolTestCache{}), repo + } + + // priority 更小者跨平台获胜:openai(0) 压过 deepseek(5)。 + svc, _ := build(5, 0, nil, nil) + selected, err := svc.SelectAccountForModelWithExclusions(ctx, &groupID, "", model, nil) + require.NoError(t, err) + require.EqualValues(t, 33002, selected.ID) + + // 反转 priority:deepseek(0) 获胜。 + svc, _ = build(0, 5, nil, nil) + selected, err = svc.SelectAccountForModelWithExclusions(ctx, &groupID, "", model, nil) + require.NoError(t, err) + require.EqualValues(t, 33001, selected.ID) + + // 同 priority 时 LRU:更久未用(或从未使用)的账号获胜。 + now := time.Now() + svc, _ = build(0, 0, &now, nil) + selected, err = svc.SelectAccountForModelWithExclusions(ctx, &groupID, "", model, nil) + require.NoError(t, err) + require.EqualValues(t, 33002, selected.ID) + + stale := now.Add(-2 * time.Hour) + recent := now.Add(-1 * time.Hour) + svc, _ = build(0, 0, &stale, &recent) + selected, err = svc.SelectAccountForModelWithExclusions(ctx, &groupID, "", model, nil) + require.NoError(t, err) + require.EqualValues(t, 33001, selected.ID) +} + +// ---- b. 同 session 连续请求与负载变化保持 sticky ---- + +func TestOpenAICompositePool_StickySessionPersistsAcrossRequestsAndLoadChange(t *testing.T) { + resetOpenAIAdvancedSchedulerSettingCacheForTest() + defer resetOpenAIAdvancedSchedulerSettingCacheForTest() + + groupID := int64(22002) + model := "my-model" + sessionHash := "sesspoolb00000001" + ctx := WithCompositeCandidatePlatforms(context.Background(), []string{PlatformDeepseek, PlatformOpenAI}) + + repo := &compositePoolTestRepo{accounts: []Account{ + compositePoolTestAccount(33001, PlatformDeepseek, groupID, 0, map[string]any{"my-model": "deepseek-chat"}), + compositePoolTestAccount(33002, PlatformOpenAI, groupID, 0, map[string]any{"my-model": "gpt-4o"}), + }} + cache := &compositePoolTestCache{} + svc := newCompositePoolTestService(repo.accounts, cache) + + // 首次:候选池按序选中 deepseek 并写绑定。 + first, err := svc.SelectAccountForModelWithExclusions(ctx, &groupID, sessionHash, model, nil) + require.NoError(t, err) + require.EqualValues(t, 33001, first.ID) + bound, ok := cache.binding(groupID, "openai:"+sessionHash) + require.True(t, ok) + require.EqualValues(t, 33001, bound) + + // 负载变化(sticky 账号刚被使用):同 session 仍粘原账号。 + now := time.Now() + repo.accounts[0].LastUsedAt = &now + second, err := svc.SelectAccountForModelWithExclusions(ctx, &groupID, sessionHash, model, nil) + require.NoError(t, err) + require.EqualValues(t, 33001, second.ID) + + // 对照:无 session 时负载/LRU 生效,选中另一个平台账号。 + third, err := svc.SelectAccountForModelWithExclusions(ctx, &groupID, "", model, nil) + require.NoError(t, err) + require.EqualValues(t, 33002, third.ID) +} + +// ---- c. sticky 命名空间(openai:)与 legacy 读回退/双写不变 ---- + +func TestOpenAICompositePool_StickyCacheKeyOpenAINamespaceAndLegacyCompat(t *testing.T) { + resetOpenAIAdvancedSchedulerSettingCacheForTest() + defer resetOpenAIAdvancedSchedulerSettingCacheForTest() + + groupID := int64(22003) + sessionHash := "sesspoolc00000001" + legacyHash, _ := deriveOpenAISessionHashes("legacy-seed-c") + + build := func(cache GatewayCache) *OpenAIGatewayService { + repo := &compositePoolTestRepo{accounts: []Account{ + compositePoolTestAccount(34001, PlatformOpenAI, groupID, 0, map[string]any{"my-model": "gpt-4o"}), + }} + return newCompositePoolTestService(repo.accounts, cache) + } + + // dual-write:主键 + legacy 键都写,且保持 openai: 前缀。 + cache := &compositePoolTestCache{} + svc := build(cache) + ctx := withOpenAILegacySessionHash( + WithCompositeCandidatePlatforms(context.Background(), []string{PlatformOpenAI}), + legacyHash, + ) + require.NoError(t, svc.BindStickySession(ctx, &groupID, sessionHash, 34001)) + require.Contains(t, cache.setKeys, "openai:"+sessionHash) + require.Contains(t, cache.setKeys, "openai:"+legacyHash) + for _, key := range cache.setKeys { + require.True(t, strings.HasPrefix(key, "openai:"), "sticky key must keep openai: prefix, got %q", key) + } + + // legacy 读回退:主键 miss、legacy 键 hit。 + legacyOnlyCache := &compositePoolTestCache{bindings: map[string]int64{ + compositePoolCacheKey(groupID, "openai:"+legacyHash): 34001, + }} + svc2 := build(legacyOnlyCache) + _, readTotalBefore, _ := openAIStickyCompatStats() + got, err := svc2.getStickySessionAccountID(ctx, &groupID, sessionHash) + require.NoError(t, err) + require.EqualValues(t, 34001, got) + _, readTotalAfter, _ := openAIStickyCompatStats() + require.Greater(t, readTotalAfter, readTotalBefore, "legacy read fallback should be counted") + + // 候选数 1→2 命名空间不变:池选中后写入的仍全部是 openai: 前缀。 + poolCache := &compositePoolTestCache{} + svc3 := newCompositePoolTestService([]Account{ + compositePoolTestAccount(34001, PlatformDeepseek, groupID, 0, map[string]any{"my-model": "deepseek-chat"}), + compositePoolTestAccount(34002, PlatformOpenAI, groupID, 0, map[string]any{"my-model": "gpt-4o"}), + }, poolCache) + poolCtx := WithCompositeCandidatePlatforms(context.Background(), []string{PlatformDeepseek, PlatformOpenAI}) + _, err = svc3.SelectAccountForModelWithExclusions(poolCtx, &groupID, sessionHash, "my-model", nil) + require.NoError(t, err) + require.NotEmpty(t, poolCache.setKeys) + for _, key := range poolCache.setKeys { + require.True(t, strings.HasPrefix(key, "openai:"), "pool sticky key must keep openai: prefix, got %q", key) + } +} + +// ---- d. 失败排除后跨平台选中并粘新账号,池不塌缩 ---- + +func TestOpenAICompositePool_FailoverExcludesFailedAccountAndSticksToNewPlatform(t *testing.T) { + resetOpenAIAdvancedSchedulerSettingCacheForTest() + defer resetOpenAIAdvancedSchedulerSettingCacheForTest() + + groupID := int64(22004) + model := "my-model" + sessionHash := "sesspoold00000001" + pool := []string{PlatformDeepseek, PlatformOpenAI} + ctx := WithCompositeCandidatePlatforms(context.Background(), pool) + + repo := &compositePoolTestRepo{accounts: []Account{ + compositePoolTestAccount(33001, PlatformDeepseek, groupID, 0, map[string]any{"my-model": "deepseek-chat"}), + compositePoolTestAccount(33002, PlatformOpenAI, groupID, 0, map[string]any{"my-model": "gpt-4o"}), + }} + cache := &compositePoolTestCache{} + svc := newCompositePoolTestService(repo.accounts, cache) + + first, err := svc.SelectAccountForModelWithExclusions(ctx, &groupID, sessionHash, model, nil) + require.NoError(t, err) + require.EqualValues(t, 33001, first.ID) + + // 排除失败账号后跨平台选中 openai,并更新同组绑定。 + excluded := map[int64]struct{}{33001: {}} + second, err := svc.SelectAccountForModelWithExclusions(ctx, &groupID, sessionHash, model, excluded) + require.NoError(t, err) + require.EqualValues(t, 33002, second.ID) + bound, ok := cache.binding(groupID, "openai:"+sessionHash) + require.True(t, ok) + require.EqualValues(t, 33002, bound) + + // 后续请求粘新账号。 + third, err := svc.SelectAccountForModelWithExclusions(ctx, &groupID, sessionHash, model, nil) + require.NoError(t, err) + require.EqualValues(t, 33002, third.ID) + + // 池 immutable:ctx 候选池完整、未写 ResolvedTargetPlatform(不塌缩)。 + require.ElementsMatch(t, pool, CompositeCandidatePlatformsFromContext(ctx)) + _, resolved := ResolvedTargetPlatformFromContext(ctx) + require.False(t, resolved) +} + +// ---- e. 换 group 不复用绑定;换 model 重新资格检查 ---- + +func TestOpenAICompositePool_StickyGroupIsolationAndModelRequalification(t *testing.T) { + resetOpenAIAdvancedSchedulerSettingCacheForTest() + defer resetOpenAIAdvancedSchedulerSettingCacheForTest() + + groupA := int64(22005) + groupB := int64(22006) + sessionHash := "sesspoole00000001" + ctx := WithCompositeCandidatePlatforms(context.Background(), []string{PlatformDeepseek, PlatformOpenAI}) + + repo := &compositePoolTestRepo{accounts: []Account{ + compositePoolTestAccount(33001, PlatformDeepseek, groupA, 0, map[string]any{"model-a": "x-a"}), + compositePoolTestAccount(33002, PlatformOpenAI, groupA, 0, map[string]any{"model-b": "x-b"}), + }} + cache := &compositePoolTestCache{} + svc := newCompositePoolTestService(repo.accounts, cache) + + // group A 的绑定对 group B 不可见。 + require.NoError(t, svc.BindStickySession(ctx, &groupA, sessionHash, 33001)) + boundA, ok := cache.binding(groupA, "openai:"+sessionHash) + require.True(t, ok) + require.EqualValues(t, 33001, boundA) + _, ok = cache.binding(groupB, "openai:"+sessionHash) + require.False(t, ok) + + // 换 model:原 sticky 账号不 claim 新模型 → 重新资格检查选中 A2 并改绑。 + selected, err := svc.SelectAccountForModelWithExclusions(ctx, &groupA, sessionHash, "model-b", nil) + require.NoError(t, err) + require.EqualValues(t, 33002, selected.ID) + boundA, ok = cache.binding(groupA, "openai:"+sessionHash) + require.True(t, ok) + require.EqualValues(t, 33002, boundA) + + // 再换回 model-a:sticky(A2)不 claim model-a → 重新选中 A1。 + selected, err = svc.SelectAccountForModelWithExclusions(ctx, &groupA, sessionHash, "model-a", nil) + require.NoError(t, err) + require.EqualValues(t, 33001, selected.ID) +} + +// ---- f. claims 谓词约束池内模型能力 ---- + +func TestOpenAICompositePool_ClaimsPredicateGatesPoolMembership(t *testing.T) { + resetOpenAIAdvancedSchedulerSettingCacheForTest() + defer resetOpenAIAdvancedSchedulerSettingCacheForTest() + + poolCtx := WithCompositeCandidatePlatforms(context.Background(), []string{PlatformKimi, PlatformDeepseek, PlatformOpenCodeGo}) + deepseekAccount := compositePoolTestAccount(35001, PlatformDeepseek, 22007, 0, nil) + kimiAccount := compositePoolTestAccount(35002, PlatformKimi, 22007, 0, nil) + opencodeMapped := compositePoolTestAccount(35003, PlatformOpenCodeGo, 22007, 0, map[string]any{"my-model": "deepseek-chat"}) + + // 官方 deepseek 空 mapping:native detector 命中 → 可 claim。 + require.True(t, openAISchedulingModelSupported(poolCtx, &deepseekAccount, "deepseek-chat")) + // 无关平台空 mapping:不得凭 IsModelSupported 的 allow-all 冒领。 + require.False(t, openAISchedulingModelSupported(poolCtx, &kimiAccount, "deepseek-chat")) + require.True(t, kimiAccount.IsModelSupported("deepseek-chat"), "旧语义 allow-all 仍成立,池路径必须改用 claims 谓词") + // opencode_go:显式 mapping 命中可入池,空/未命中不入。 + require.True(t, openAISchedulingModelSupported(poolCtx, &opencodeMapped, "my-model")) + require.False(t, openAISchedulingModelSupported(poolCtx, &opencodeMapped, "deepseek-chat")) + // 非 pool 请求保持 IsModelSupported 原语义。 + require.True(t, openAISchedulingModelSupported(context.Background(), &kimiAccount, "deepseek-chat")) + + // 资格检查命名否决点。 + reason := openAICompatibleAccountEligibilityFailureReason(poolCtx, &kimiAccount, PlatformOpenAI, "deepseek-chat", false, "") + require.Equal(t, "model_not_supported", reason) + + // 选号层:kimi 被过滤,deepseek 入选。 + groupID := int64(22007) + repo := &compositePoolTestRepo{accounts: []Account{deepseekAccount, kimiAccount}} + cache := &compositePoolTestCache{} + svc := newCompositePoolTestService(repo.accounts, cache) + selection, err := svc.SelectAccountForModelWithExclusions(poolCtx, &groupID, "", "deepseek-chat", nil) + require.NoError(t, err) + require.EqualValues(t, 35001, selection.ID) +} + +// ---- g. 全瞬态不可用保持无容量错误语义 ---- + +func TestOpenAICompositePool_AllTransientUnavailableKeepsNoCapacityError(t *testing.T) { + resetOpenAIAdvancedSchedulerSettingCacheForTest() + defer resetOpenAIAdvancedSchedulerSettingCacheForTest() + + groupID := int64(22008) + ctx := WithCompositeCandidatePlatforms(context.Background(), []string{PlatformDeepseek, PlatformOpenAI}) + + rateLimitedUntil := time.Now().Add(time.Hour) + deepseekAccount := compositePoolTestAccount(33001, PlatformDeepseek, 22008, 0, nil) + deepseekAccount.RateLimitResetAt = &rateLimitedUntil + openaiAccount := compositePoolTestAccount(33002, PlatformOpenAI, 22008, 0, nil) + openaiAccount.RateLimitResetAt = &rateLimitedUntil + + svc := newCompositePoolTestService([]Account{deepseekAccount, openaiAccount}, &compositePoolTestCache{}) + _, err := svc.SelectAccountForModelWithExclusions(ctx, &groupID, "", "deepseek-chat", nil) + require.Error(t, err) + require.True(t, errors.Is(err, ErrNoAvailableAccounts), "pool 全部瞬态不可用应保持无容量错误,got %v", err) + require.False(t, errors.Is(err, ErrNoAvailableCompactAccounts)) + require.Contains(t, err.Error(), "no available OpenAI accounts supporting model: deepseek-chat") +} + +// ---- h. previous_response_id pin 归属保持 ---- + +func TestOpenAICompositePool_PreviousResponseIDPinStaysWithOwnerAccount(t *testing.T) { + resetOpenAIAdvancedSchedulerSettingCacheForTest() + defer resetOpenAIAdvancedSchedulerSettingCacheForTest() + + groupID := int64(22009) + responseID := "resp_pool_h_0001" + model := "gpt-5.1" + pool := []string{PlatformDeepseek, PlatformOpenAI} + + newRepo := func() *compositePoolTestRepo { + // A1(openai,空 mapping)native claim gpt-5.1;A2(deepseek)显式映射 claim 同模型。 + return &compositePoolTestRepo{accounts: []Account{ + compositePoolTestAccount(33001, PlatformOpenAI, groupID, 0, nil), + compositePoolTestAccount(33002, PlatformDeepseek, groupID, 0, map[string]any{"gpt-5.1": "deepseek-chat"}), + }} + } + + buildSvc := func(t *testing.T, repo *compositePoolTestRepo) (*OpenAIGatewayService, OpenAIWSStateStore) { + t.Helper() + svc := newCompositePoolAdvancedTestService(t, repo.accounts, &compositePoolTestCache{}) + store := svc.getOpenAIWSStateStore() + require.NotNil(t, store) + return svc, store + } + + ctx := WithCompositeCandidatePlatforms(context.Background(), pool) + + // 1) pool 内有效 pin:仍优先同账号。 + repo := newRepo() + svc, store := buildSvc(t, repo) + require.NoError(t, store.BindResponseAccount(ctx, groupID, responseID, 33001, time.Hour)) + selection, decision, err := svc.SelectAccountWithScheduler(ctx, &groupID, responseID, "", model, nil, OpenAIUpstreamTransportAny, false) + require.NoError(t, err) + require.NotNil(t, selection) + require.EqualValues(t, 33001, selection.Account.ID) + require.True(t, decision.StickyPreviousHit) + require.Equal(t, openAIAccountScheduleLayerPreviousResponse, decision.Layer) + bound, err := store.GetResponseAccount(ctx, groupID, responseID) + require.NoError(t, err) + require.EqualValues(t, 33001, bound) + + // 2) pinned 账号失效:按原策略删除响应绑定,回落池内另一平台。 + repo = newRepo() + repo.accounts[0].Schedulable = false + svc, store = buildSvc(t, repo) + require.NoError(t, store.BindResponseAccount(ctx, groupID, responseID, 33001, time.Hour)) + selection, decision, err = svc.SelectAccountWithScheduler(ctx, &groupID, responseID, "", model, nil, OpenAIUpstreamTransportAny, false) + require.NoError(t, err) + require.NotNil(t, selection) + require.EqualValues(t, 33002, selection.Account.ID) + require.False(t, decision.StickyPreviousHit) + bound, err = store.GetResponseAccount(ctx, groupID, responseID) + require.NoError(t, err) + require.EqualValues(t, 0, bound, "失效账号的响应绑定应按原策略删除") + + // 3) pinned 账号在池外(账号健康):本次不使用 pin、不删除绑定, + // previous_response_id 不得悄悄跨平台带走。pin 层已抢到的槽必须先释放 + // (ReleaseFunc),再以池内账号重新出号——槽位/租约不得泄漏。 + repo = newRepo() + acquiredIDs, releasedIDs := []int64{}, []int64{} + svc = newCompositePoolAdvancedTestService(t, repo.accounts, &compositePoolTestCache{}) + svc.concurrencyService = NewConcurrencyService(schedulerTestConcurrencyCache{ + acquiredIDs: &acquiredIDs, + releasedIDs: &releasedIDs, + }) + store = svc.getOpenAIWSStateStore() + require.NotNil(t, store) + require.NoError(t, store.BindResponseAccount(ctx, groupID, responseID, 33001, time.Hour)) + narrowCtx := WithCompositeCandidatePlatforms(context.Background(), []string{PlatformDeepseek}) + selection, decision, err = svc.SelectAccountWithScheduler(narrowCtx, &groupID, responseID, "", model, nil, OpenAIUpstreamTransportAny, false) + require.NoError(t, err) + require.NotNil(t, selection) + require.EqualValues(t, 33002, selection.Account.ID) + require.False(t, decision.StickyPreviousHit) + bound, err = store.GetResponseAccount(ctx, groupID, responseID) + require.NoError(t, err) + require.EqualValues(t, 33001, bound, "池外健康账号的响应绑定应保留") + require.NotEmpty(t, acquiredIDs, "pin 命中路径应曾尝试抢槽") + require.Contains(t, releasedIDs, int64(33001), "池外 pin 账号已占槽必须先释放") + require.NotContains(t, releasedIDs, int64(33002), "最终选中账号的槽位不得被释放") + if release := selection.ReleaseFunc; release != nil { + t.Cleanup(release) + } + + // 4) pinned 账号被显式排除(failover 重选限制):pin 不得使用,绑定保留, + // 改选池内剩余账号。 + repo = newRepo() + svc, store = buildSvc(t, repo) + require.NoError(t, store.BindResponseAccount(ctx, groupID, responseID, 33001, time.Hour)) + excluded := map[int64]struct{}{33001: {}} + selection, decision, err = svc.SelectAccountWithScheduler(ctx, &groupID, responseID, "", model, excluded, OpenAIUpstreamTransportAny, false) + require.NoError(t, err) + require.NotNil(t, selection) + require.EqualValues(t, 33002, selection.Account.ID) + require.False(t, decision.StickyPreviousHit) + bound, err = store.GetResponseAccount(ctx, groupID, responseID) + require.NoError(t, err) + require.EqualValues(t, 33001, bound, "被排除账号的响应绑定不应被改写") + + // 5) pin miss + 同 session:状态请求重选仍遵循 sticky 语义——绑定跟随 + // 实际选中的新账号(同组),不产生跨组/跨平台漂移。 + repo = newRepo() + repo.accounts[0].Schedulable = false + svc, store = buildSvc(t, repo) + sessionHash := "sesspoolh00000001" + require.NoError(t, store.BindResponseAccount(ctx, groupID, responseID, 33001, time.Hour)) + require.NoError(t, svc.BindStickySession(ctx, &groupID, sessionHash, 33001)) + selection, decision, err = svc.SelectAccountWithScheduler(ctx, &groupID, responseID, sessionHash, model, nil, OpenAIUpstreamTransportAny, false) + require.NoError(t, err) + require.NotNil(t, selection) + require.EqualValues(t, 33002, selection.Account.ID) + require.False(t, decision.StickyPreviousHit) + poolCache, cacheAsserted := svc.cache.(*compositePoolTestCache) + require.True(t, cacheAsserted) + bound, ok := poolCache.binding(groupID, "openai:"+sessionHash) + require.True(t, ok) + require.EqualValues(t, 33002, bound, "状态请求重选后 session 绑定应跟随新账号") +} + +// ---- 高级调度器 sticky 的池成员校验 ---- + +func TestOpenAICompositePool_AdvancedSchedulerStickyRespectsPoolMembership(t *testing.T) { + groupID := int64(22010) + sessionHash := "sesspoolf00000001" + model := "gpt-5.1" + + repo := &compositePoolTestRepo{accounts: []Account{ + compositePoolTestAccount(33001, PlatformOpenAI, groupID, 0, nil), + compositePoolTestAccount(33002, PlatformDeepseek, groupID, 5, map[string]any{"gpt-5.1": "deepseek-chat"}), + compositePoolTestAccount(33003, PlatformKimi, groupID, 0, map[string]any{"gpt-5.1": "kimi-chat"}), + }} + + // sticky 命中池内账号:保持粘连。 + cache := &compositePoolTestCache{} + svc := newCompositePoolAdvancedTestService(t, repo.accounts, cache) + ctx := WithCompositeCandidatePlatforms(context.Background(), []string{PlatformDeepseek, PlatformOpenAI}) + require.NoError(t, svc.BindStickySession(ctx, &groupID, sessionHash, 33001)) + selection, decision, err := svc.SelectAccountWithScheduler(ctx, &groupID, "", sessionHash, model, nil, OpenAIUpstreamTransportAny, false) + require.NoError(t, err) + require.EqualValues(t, 33001, selection.Account.ID) + require.True(t, decision.StickySessionHit) + + // sticky 指向池外账号(kimi 不在候选池):绑定清理,回落池内选号。 + cache2 := &compositePoolTestCache{} + svc2 := newCompositePoolAdvancedTestService(t, repo.accounts, cache2) + require.NoError(t, svc2.BindStickySession(ctx, &groupID, sessionHash, 33003)) + selection, decision, err = svc2.SelectAccountWithScheduler(ctx, &groupID, "", sessionHash, model, nil, OpenAIUpstreamTransportAny, false) + require.NoError(t, err) + require.NotNil(t, selection) + require.NotEqualValues(t, 33003, selection.Account.ID) + require.False(t, decision.StickySessionHit) + require.Contains(t, cache2.delKeys, "openai:"+sessionHash) +} + +// ---- sticky 解绑/映射移除后的组归属与资格复检 ---- +// +// 绑定的 sticky 账号从同组解绑(GroupIDs 变更)或 model_mapping 不再 claim 后, +// 命中缓存的 sticky 账号不得因「平台属于池 + 可调度」而继续命中: +// 组归属经 openAIAccountMatchesSchedulingGroup / openAIStickyAccountMatchesGroup +// (GroupIDs/AccountGroups)复检,模型资格经 claims 谓词复检;随后绑定清理。 + +func TestOpenAICompositePool_StickyMissAfterAccountLeavesGroupOrLosesMapping(t *testing.T) { + groupID := int64(22011) + otherGroup := int64(22099) + sessionHash := "sesspoolg00000001" + model := "my-model" + + newAccounts := func() []Account { + return []Account{ + compositePoolTestAccount(33001, PlatformDeepseek, groupID, 0, map[string]any{"my-model": "deepseek-chat"}), + compositePoolTestAccount(33002, PlatformOpenAI, groupID, 5, map[string]any{"my-model": "gpt-4o"}), + } + } + ctx := WithCompositeCandidatePlatforms(context.Background(), []string{PlatformDeepseek, PlatformOpenAI}) + + t.Run("advanced_scheduler_sticky", func(t *testing.T) { + repo := &compositePoolTestRepo{accounts: newAccounts()} + cache := &compositePoolTestCache{} + svc := newCompositePoolAdvancedTestService(t, repo.accounts, cache) + require.NoError(t, svc.BindStickySession(ctx, &groupID, sessionHash, 33001)) + + // 基线:sticky 命中。 + selection, decision, err := svc.SelectAccountWithScheduler(ctx, &groupID, "", sessionHash, model, nil, OpenAIUpstreamTransportAny, false) + require.NoError(t, err) + require.EqualValues(t, 33001, selection.Account.ID) + require.True(t, decision.StickySessionHit) + + // 账号被移出本组:sticky 不得继续命中;绑定先清理、再随重选改指组内 + // 另一平台账号(跨平台 failover 粘新账号)。 + repo.accounts[0].GroupIDs = []int64{otherGroup} + selection, decision, err = svc.SelectAccountWithScheduler(ctx, &groupID, "", sessionHash, model, nil, OpenAIUpstreamTransportAny, false) + require.NoError(t, err) + require.NotNil(t, selection) + require.NotEqualValues(t, 33001, selection.Account.ID) + require.False(t, decision.StickySessionHit) + rebound, bound := cache.binding(groupID, "openai:"+sessionHash) + require.True(t, bound) + require.NotEqualValues(t, 33001, rebound, "解绑账号的绑定应被清理并改指新账号") + + // mapping 移除(不再 claim my-model):sticky 同样不得命中;资格失格属 + // 瞬态语义,绑定按原策略保留在原账号上等待恢复,同时报无容量错误。 + repo.accounts[1].Credentials = nil + _, decision, err = svc.SelectAccountWithScheduler(ctx, &groupID, "", sessionHash, model, nil, OpenAIUpstreamTransportAny, false) + require.Error(t, err, "组内已无可 claim 该模型的账号,应报无容量") + require.True(t, errors.Is(err, ErrNoAvailableAccounts)) + require.False(t, decision.StickySessionHit) + stillBound, bound := cache.binding(groupID, "openai:"+sessionHash) + require.True(t, bound) + require.EqualValues(t, 33002, stillBound) + }) + + t.Run("legacy_sticky", func(t *testing.T) { + repo := &compositePoolTestRepo{accounts: newAccounts()} + cache := &compositePoolTestCache{} + svc := newCompositePoolTestService(repo.accounts, cache) + require.NoError(t, svc.BindStickySession(ctx, &groupID, sessionHash, 33001)) + + selection, err := svc.SelectAccountForModelWithExclusions(ctx, &groupID, sessionHash, model, nil) + require.NoError(t, err) + require.EqualValues(t, 33001, selection.ID) + + // 移出本组:legacy sticky 命中路径同样复检组归属并清理绑定, + // 随后重选改指组内另一平台账号。 + repo.accounts[0].GroupIDs = []int64{otherGroup} + selection, err = svc.SelectAccountForModelWithExclusions(ctx, &groupID, sessionHash, model, nil) + require.NoError(t, err) + require.NotEqualValues(t, 33001, selection.ID) + rebound, bound := cache.binding(groupID, "openai:"+sessionHash) + require.True(t, bound) + require.EqualValues(t, 33002, rebound, "解绑账号的绑定应被清理并改指新账号") + }) +} + +// ---- 显式 force 平台语义:resolved 平台优先于池,池不得绕过 ---- + +func TestOpenAICompositePool_ExplicitForcePlatformOverridesPool(t *testing.T) { + groupID := int64(22012) + pool := []string{PlatformKimi, PlatformOpenAI} + resolvedCtx := WithResolvedTargetPlatform( + WithCompositeCandidatePlatforms(context.Background(), pool), + PlatformDeepseek, + ) + + // resolved 存在时池视为不活跃:平台门回退到单平台相等语义。 + require.False(t, openAICompositePoolActive(resolvedCtx)) + deepseekAccount := compositePoolTestAccount(36001, PlatformDeepseek, groupID, 0, map[string]any{"my-model": "deepseek-chat"}) + kimiAccount := compositePoolTestAccount(36002, PlatformKimi, groupID, 0, map[string]any{"my-model": "kimi-chat"}) + require.True(t, openAISchedulingPlatformMatchesAccount(resolvedCtx, &deepseekAccount, PlatformDeepseek)) + require.False(t, openAISchedulingPlatformMatchesAccount(resolvedCtx, &kimiAccount, PlatformDeepseek)) + + // listSchedulableAccounts 只读取 resolved 平台桶,不合并候选池。 + repo := &compositePoolTestRepo{accounts: []Account{deepseekAccount, kimiAccount}} + svc := newCompositePoolTestService(repo.accounts, &compositePoolTestCache{}) + accounts, err := svc.listSchedulableAccounts(resolvedCtx, &groupID, PlatformDeepseek) + require.NoError(t, err) + require.Len(t, accounts, 1) + require.EqualValues(t, 36001, accounts[0].ID) + + // 选号结果同样只落在 resolved 平台账号上。 + selected, err := svc.selectAccountForModelWithExclusions(resolvedCtx, &groupID, PlatformDeepseek, "", "my-model", nil, false, 0, "", false) + require.NoError(t, err) + require.EqualValues(t, 36001, selected.ID) +} + +// ---- 选号期 passthrough 例外(review#6):残留旧 mapping 不误踢、构池不放宽 ---- + +func TestOpenAICompositePool_PassthroughStaleMappingSelectionException(t *testing.T) { + resetOpenAIAdvancedSchedulerSettingCacheForTest() + defer resetOpenAIAdvancedSchedulerSettingCacheForTest() + + newPassthroughAccount := func() Account { + // passthrough 开启 + credentials 残留旧的非空 mapping(#4936 场景), + // 残留 mapping 不 claim 请求模型。 + account := compositePoolTestAccount(37001, PlatformOpenAI, 22013, 0, map[string]any{"old-model": "legacy-upstream"}) + account.Extra = map[string]any{"openai_passthrough": true} + return account + } + + // 构池/ownership 谓词保持严格:passthrough 残留 mapping 未命中不得 claim。 + passthroughAccount := newPassthroughAccount() + require.True(t, passthroughAccount.IsOpenAIPassthroughEnabled()) + require.False(t, CompositeAccountClaimsModel(&passthroughAccount, "my-model"), + "构池谓词不得因 passthrough 放宽,否则 passthrough 会 claim 所有模型") + + // 候选池含 openai:选号期 passthrough 例外生效,残留 mapping 未命中仍入选。 + groupID := int64(22013) + poolCtx := WithCompositeCandidatePlatforms(context.Background(), []string{PlatformOpenAI}) + strictPeer := compositePoolTestAccount(37002, PlatformOpenAI, 22013, 0, map[string]any{"my-model": "gpt-4o"}) + svc := newCompositePoolTestService([]Account{passthroughAccount, strictPeer}, &compositePoolTestCache{}) + selected, err := svc.SelectAccountForModelWithExclusions(poolCtx, &groupID, "", "my-model", nil) + require.NoError(t, err) + require.EqualValues(t, 37001, selected.ID, + "passthrough 残留 mapping 未命中应经选号期例外入选(peer priority 相同,按池序先到)") + + // 无 openai 候选:passthrough openai 账号不得越池,选中池内 deepseek。 + repoCtx := WithCompositeCandidatePlatforms(context.Background(), []string{PlatformDeepseek}) + deepseekPeer := compositePoolTestAccount(37003, PlatformDeepseek, 22013, 0, map[string]any{"my-model": "deepseek-chat"}) + svc2 := newCompositePoolTestService([]Account{newPassthroughAccount(), deepseekPeer}, &compositePoolTestCache{}) + selected, err = svc2.SelectAccountForModelWithExclusions(repoCtx, &groupID, "", "my-model", nil) + require.NoError(t, err) + require.EqualValues(t, 37003, selected.ID, "passthrough 不得越出候选池") + + // 池内无任何可服务账号(仅 passthrough 残留 mapping 且其平台不在池):无容量。 + onlyPassthroughCtx := WithCompositeCandidatePlatforms(context.Background(), []string{PlatformDeepseek}) + svc3 := newCompositePoolTestService([]Account{newPassthroughAccount()}, &compositePoolTestCache{}) + _, err = svc3.SelectAccountForModelWithExclusions(onlyPassthroughCtx, &groupID, "", "my-model", nil) + require.Error(t, err) + require.True(t, errors.Is(err, ErrNoAvailableAccounts)) +} + +// ---- composite account_pool 下 CN/OpenCode 的 previous_response_id 归属 ---- +// +// 底层事实:bindHTTPResponseAccount(openai_gateway_response_handling.go)对 +// CN/OpenCode native HTTP Responses 同样经 OpenAIWSStateStore.BindResponseAccount +// 写绑定,但 resolveAccountByPreviousResponseIDForCapability 原来只认 OpenAI 平台。 +// 放宽仅限「池上下文 + OpenAI 兼容族 APIKey」;OAuth/SetupToken/WS/单平台规则 +// 不扩大,models/group/pool/health/capability/excluded 全部原门保留。 + +func TestOpenAICompositePool_PreviousResponseIDCNAndOpenCodePoolOwners(t *testing.T) { + resetOpenAIAdvancedSchedulerSettingCacheForTest() + defer resetOpenAIAdvancedSchedulerSettingCacheForTest() + + groupID := int64(22014) + responseID := "resp_pool_cn_0001" + model := "my-model" + + newAccounts := func() []Account { + return []Account{ + compositePoolTestAccount(38001, PlatformDeepseek, groupID, 0, map[string]any{"my-model": "deepseek-chat"}), + compositePoolTestAccount(38002, PlatformKimi, groupID, 0, map[string]any{"my-model": "kimi-chat"}), + compositePoolTestAccount(38003, PlatformOpenCodeGo, groupID, 0, map[string]any{"my-model": "oc-chat"}), + } + } + buildSvc := func(t *testing.T, accounts []Account) (*OpenAIGatewayService, OpenAIWSStateStore) { + t.Helper() + svc := newCompositePoolAdvancedTestService(t, accounts, &compositePoolTestCache{}) + store := svc.getOpenAIWSStateStore() + require.NotNil(t, store) + return svc, store + } + poolCtx := WithCompositeCandidatePlatforms(context.Background(), []string{PlatformDeepseek, PlatformKimi, PlatformOpenCodeGo}) + + // 1) CN(deepseek APIKey)有效绑定:命中并原 key 续接。 + repo := &compositePoolTestRepo{accounts: newAccounts()} + svc, store := buildSvc(t, repo.accounts) + require.NoError(t, store.BindResponseAccount(poolCtx, groupID, responseID, 38001, time.Hour)) + selection, decision, err := svc.SelectAccountWithScheduler(poolCtx, &groupID, responseID, "", model, nil, OpenAIUpstreamTransportAny, false) + require.NoError(t, err) + require.NotNil(t, selection) + require.EqualValues(t, 38001, selection.Account.ID) + require.True(t, decision.StickyPreviousHit, "CN 有效 owner 应命中 pin") + bound, err := store.GetResponseAccount(poolCtx, groupID, responseID) + require.NoError(t, err) + require.EqualValues(t, 38001, bound, "命中后原 key 续接同账号") + + // 2) OpenCode APIKey 有效绑定:同样命中。 + repo = &compositePoolTestRepo{accounts: newAccounts()} + svc, store = buildSvc(t, repo.accounts) + require.NoError(t, store.BindResponseAccount(poolCtx, groupID, responseID, 38003, time.Hour)) + selection, decision, err = svc.SelectAccountWithScheduler(poolCtx, &groupID, responseID, "", model, nil, OpenAIUpstreamTransportAny, false) + require.NoError(t, err) + require.NotNil(t, selection) + require.EqualValues(t, 38003, selection.Account.ID) + require.True(t, decision.StickyPreviousHit, "OpenCode 有效 owner 应命中 pin") + + // 3) 池外:绑定指向 kimi 但本次池只有 deepseek——无 hit、绑定保留、不跨池带走。 + repo = &compositePoolTestRepo{accounts: newAccounts()} + svc, store = buildSvc(t, repo.accounts) + require.NoError(t, store.BindResponseAccount(poolCtx, groupID, responseID, 38002, time.Hour)) + narrowCtx := WithCompositeCandidatePlatforms(context.Background(), []string{PlatformDeepseek}) + selection, decision, err = svc.SelectAccountWithScheduler(narrowCtx, &groupID, responseID, "", model, nil, OpenAIUpstreamTransportAny, false) + require.NoError(t, err) + require.NotNil(t, selection) + require.EqualValues(t, 38001, selection.Account.ID) + require.False(t, decision.StickyPreviousHit) + bound, err = store.GetResponseAccount(poolCtx, groupID, responseID) + require.NoError(t, err) + require.EqualValues(t, 38002, bound, "池外健康账号绑定保留") + + // 4) 解绑(移出本组):无 hit、绑定保留、重选遵循组内 sticky 语义。 + repo = &compositePoolTestRepo{accounts: newAccounts()} + svc, store = buildSvc(t, repo.accounts) + require.NoError(t, store.BindResponseAccount(poolCtx, groupID, responseID, 38001, time.Hour)) + repo.accounts[0].GroupIDs = []int64{22099} + selection, decision, err = svc.SelectAccountWithScheduler(poolCtx, &groupID, responseID, "", model, nil, OpenAIUpstreamTransportAny, false) + require.NoError(t, err) + require.NotNil(t, selection) + require.NotEqualValues(t, 38001, selection.Account.ID) + require.False(t, decision.StickyPreviousHit) + bound, err = store.GetResponseAccount(poolCtx, groupID, responseID) + require.NoError(t, err) + require.EqualValues(t, 38001, bound, "解绑账号绑定保留(组归属复检在选号层拒绝)") + + // 5) mapping 不支持:绑定账号不再 claim 请求模型——无 hit、绑定保留。 + repo = &compositePoolTestRepo{accounts: newAccounts()} + svc, store = buildSvc(t, repo.accounts) + require.NoError(t, store.BindResponseAccount(poolCtx, groupID, responseID, 38001, time.Hour)) + repo.accounts[0].Credentials = map[string]any{"model_mapping": map[string]any{"gpt-5.1": "x"}} + selection, decision, err = svc.SelectAccountWithScheduler(poolCtx, &groupID, responseID, "", model, nil, OpenAIUpstreamTransportAny, false) + require.NoError(t, err) + require.NotNil(t, selection) + require.NotEqualValues(t, 38001, selection.Account.ID) + require.False(t, decision.StickyPreviousHit) + bound, err = store.GetResponseAccount(poolCtx, groupID, responseID) + require.NoError(t, err) + require.EqualValues(t, 38001, bound, "mapping 失格属瞬态,绑定保留") + + // 6) expired(AutoPauseOnExpired 到期):无 hit 且按失效原策略删除绑定。 + repo = &compositePoolTestRepo{accounts: newAccounts()} + svc, store = buildSvc(t, repo.accounts) + require.NoError(t, store.BindResponseAccount(poolCtx, groupID, responseID, 38001, time.Hour)) + expiredAt := time.Now().Add(-time.Hour) + repo.accounts[0].AutoPauseOnExpired = true + repo.accounts[0].ExpiresAt = &expiredAt + selection, decision, err = svc.SelectAccountWithScheduler(poolCtx, &groupID, responseID, "", model, nil, OpenAIUpstreamTransportAny, false) + require.NoError(t, err) + require.NotNil(t, selection) + require.False(t, decision.StickyPreviousHit) + bound, err = store.GetResponseAccount(poolCtx, groupID, responseID) + require.NoError(t, err) + require.EqualValues(t, 0, bound, "失效账号绑定按原策略删除") + + // 7) excluded:无 hit、绑定保留。 + repo = &compositePoolTestRepo{accounts: newAccounts()} + svc, store = buildSvc(t, repo.accounts) + require.NoError(t, store.BindResponseAccount(poolCtx, groupID, responseID, 38001, time.Hour)) + excluded := map[int64]struct{}{38001: {}} + selection, decision, err = svc.SelectAccountWithScheduler(poolCtx, &groupID, responseID, "", model, excluded, OpenAIUpstreamTransportAny, false) + require.NoError(t, err) + require.NotNil(t, selection) + require.NotEqualValues(t, 38001, selection.Account.ID) + require.False(t, decision.StickyPreviousHit) + bound, err = store.GetResponseAccount(poolCtx, groupID, responseID) + require.NoError(t, err) + require.EqualValues(t, 38001, bound, "被排除账号绑定保留") + + // 8) 单平台(kimi、无池):pin 层不尝试,规则不扩大。 + repo = &compositePoolTestRepo{accounts: newAccounts()} + svc, store = buildSvc(t, repo.accounts) + require.NoError(t, store.BindResponseAccount(poolCtx, groupID, responseID, 38002, time.Hour)) + singleCtx := context.Background() + selection, decision, err = svc.selectAccountWithScheduler(singleCtx, &groupID, responseID, "", model, nil, OpenAIUpstreamTransportAny, "", "", false, PlatformKimi, false, true) + require.NoError(t, err) + require.NotNil(t, selection) + require.False(t, decision.StickyPreviousHit, "单平台 kimi 不得启用 OpenAI previous_response pin") + bound, err = store.GetResponseAccount(poolCtx, groupID, responseID) + require.NoError(t, err) + require.EqualValues(t, 38002, bound) + + // 9) OpenAI OAuth(非 APIKey、非 WSv2):状态归属 WSv2 session,规则不变。 + oauthAccount := compositePoolTestAccount(38004, PlatformOpenAI, groupID, 0, nil) + oauthAccount.Type = AccountTypeOAuth + repo = &compositePoolTestRepo{accounts: append(newAccounts(), oauthAccount)} + svc, store = buildSvc(t, repo.accounts) + require.NoError(t, store.BindResponseAccount(poolCtx, groupID, responseID, 38004, time.Hour)) + selection, decision, err = svc.SelectAccountWithScheduler(poolCtx, &groupID, responseID, "", model, nil, OpenAIUpstreamTransportAny, false) + require.NoError(t, err) + require.NotNil(t, selection) + require.False(t, decision.StickyPreviousHit, "OAuth 续链状态属 WSv2 session,HTTP 池路径不得复用") + bound, err = store.GetResponseAccount(poolCtx, groupID, responseID) + require.NoError(t, err) + require.EqualValues(t, 38004, bound, "OAuth 绑定保留,不删除") + + // 10) Grok APIKey 有效 owner(HTTP 绑定):与 CN/OpenCode 同权命中。 + // IsMultiProtocolAPIKeyProvider 不含 grok,兼容族判定必须用 IsOpenAICompatible。 + grokAccount := compositePoolTestAccount(38005, PlatformGrok, groupID, 0, map[string]any{"my-model": "grok-chat"}) + repo = &compositePoolTestRepo{accounts: append(newAccounts(), grokAccount)} + svc, store = buildSvc(t, repo.accounts) + grokPoolCtx := WithCompositeCandidatePlatforms(context.Background(), []string{PlatformDeepseek, PlatformGrok}) + require.NoError(t, store.BindResponseAccount(grokPoolCtx, groupID, responseID, 38005, time.Hour)) + selection, decision, err = svc.SelectAccountWithScheduler(grokPoolCtx, &groupID, responseID, "", model, nil, OpenAIUpstreamTransportAny, false) + require.NoError(t, err) + require.NotNil(t, selection) + require.EqualValues(t, 38005, selection.Account.ID) + require.True(t, decision.StickyPreviousHit, "grok APIKey 有效 owner 应命中 pin") + bound, err = store.GetResponseAccount(grokPoolCtx, groupID, responseID) + require.NoError(t, err) + require.EqualValues(t, 38005, bound, "grok 命中后原 key 续接") + + // 11) Grok 池外(本次池仅 deepseek):无 hit,绑定保留——不得仅因非 OpenAI 被删。 + repo = &compositePoolTestRepo{accounts: append(newAccounts(), grokAccount)} + svc, store = buildSvc(t, repo.accounts) + require.NoError(t, store.BindResponseAccount(grokPoolCtx, groupID, responseID, 38005, time.Hour)) + selection, decision, err = svc.SelectAccountWithScheduler(narrowCtx, &groupID, responseID, "", model, nil, OpenAIUpstreamTransportAny, false) + require.NoError(t, err) + require.NotNil(t, selection) + require.False(t, decision.StickyPreviousHit) + bound, err = store.GetResponseAccount(grokPoolCtx, groupID, responseID) + require.NoError(t, err) + require.EqualValues(t, 38005, bound, "grok 池外健康 owner 绑定保留,删除不得仅因非 OpenAI") +} + +// ---- legacy 调度(高级调度器关闭)+ active pool 的 previous_response_id 归属 ---- +// +// 与 TestOpenAICompositePool_PreviousResponseIDCNAndOpenCodePoolOwners 对偶: +// legacy 分支原本完全忽略 prevID,现仅对「active pool + 非空 prevID」复用同一 +// pin 选择与复检 helper;非池 legacy 行为不变。覆盖 CN/OpenCode/grok valid pin +// (含适用 capability)、pin 缺失、池外、excluded、owner 不可用。 + +func TestOpenAICompositePool_LegacySchedulerPoolPreviousResponseIDOwners(t *testing.T) { + resetOpenAIAdvancedSchedulerSettingCacheForTest() + defer resetOpenAIAdvancedSchedulerSettingCacheForTest() + + groupID := int64(22015) + responseID := "resp_pool_legacy_0001" + model := "my-model" + + newAccounts := func() []Account { + return []Account{ + compositePoolTestAccount(39001, PlatformDeepseek, groupID, 0, map[string]any{"my-model": "deepseek-chat"}), + compositePoolTestAccount(39002, PlatformKimi, groupID, 0, map[string]any{"my-model": "kimi-chat"}), + compositePoolTestAccount(39003, PlatformOpenCodeGo, groupID, 0, map[string]any{"my-model": "oc-chat"}), + } + } + // legacy:不注入 advanced 设置(默认关闭)。 + buildSvc := func(t *testing.T, accounts []Account) (*OpenAIGatewayService, OpenAIWSStateStore) { + t.Helper() + svc := newCompositePoolTestService(accounts, &compositePoolTestCache{}) + require.False(t, svc.isOpenAIAdvancedSchedulerEnabled(context.Background())) + store := svc.getOpenAIWSStateStore() + require.NotNil(t, store) + return svc, store + } + poolCtx := WithCompositeCandidatePlatforms(context.Background(), []string{PlatformDeepseek, PlatformKimi, PlatformOpenCodeGo}) + + // 1) CN valid pin(含适用 capability=Responses):legacy 命中并原 key 续接。 + repo := &compositePoolTestRepo{accounts: newAccounts()} + svc, store := buildSvc(t, repo.accounts) + require.NoError(t, store.BindResponseAccount(poolCtx, groupID, responseID, 39001, time.Hour)) + selection, decision, err := svc.selectAccountWithScheduler(poolCtx, &groupID, responseID, "", model, nil, + OpenAIUpstreamTransportAny, OpenAIEndpointCapabilityResponses, "", false, PlatformOpenAI, false, true) + require.NoError(t, err) + require.NotNil(t, selection) + require.EqualValues(t, 39001, selection.Account.ID) + require.True(t, decision.StickyPreviousHit, "legacy+pool 的 CN 有效 owner 应命中 pin") + bound, err := store.GetResponseAccount(poolCtx, groupID, responseID) + require.NoError(t, err) + require.EqualValues(t, 39001, bound) + + // 2) OpenCode valid pin:legacy 命中。 + repo = &compositePoolTestRepo{accounts: newAccounts()} + svc, store = buildSvc(t, repo.accounts) + require.NoError(t, store.BindResponseAccount(poolCtx, groupID, responseID, 39003, time.Hour)) + selection, decision, err = svc.SelectAccountWithScheduler(poolCtx, &groupID, responseID, "", model, nil, OpenAIUpstreamTransportAny, false) + require.NoError(t, err) + require.NotNil(t, selection) + require.EqualValues(t, 39003, selection.Account.ID) + require.True(t, decision.StickyPreviousHit) + + // 3) grok valid pin:legacy 命中(兼容族判定含 grok)。 + grokAccount := compositePoolTestAccount(39004, PlatformGrok, groupID, 0, map[string]any{"my-model": "grok-chat"}) + repo = &compositePoolTestRepo{accounts: append(newAccounts(), grokAccount)} + svc, store = buildSvc(t, repo.accounts) + grokPoolCtx := WithCompositeCandidatePlatforms(context.Background(), []string{PlatformDeepseek, PlatformGrok}) + require.NoError(t, store.BindResponseAccount(grokPoolCtx, groupID, responseID, 39004, time.Hour)) + selection, decision, err = svc.SelectAccountWithScheduler(grokPoolCtx, &groupID, responseID, "", model, nil, OpenAIUpstreamTransportAny, false) + require.NoError(t, err) + require.NotNil(t, selection) + require.EqualValues(t, 39004, selection.Account.ID) + require.True(t, decision.StickyPreviousHit) + + // 4) pin 缺失(未绑定):无 hit,回落 LB 按 priority 选中。 + repo = &compositePoolTestRepo{accounts: newAccounts()} + svc, _ = buildSvc(t, repo.accounts) + repo.accounts[1].Priority = -1 + selection, decision, err = svc.SelectAccountWithScheduler(poolCtx, &groupID, responseID, "", model, nil, OpenAIUpstreamTransportAny, false) + require.NoError(t, err) + require.NotNil(t, selection) + require.EqualValues(t, 39002, selection.Account.ID) + require.False(t, decision.StickyPreviousHit) + + // 5) 池外:绑定指向 kimi 但本次池只有 deepseek——无 hit、绑定保留。 + repo = &compositePoolTestRepo{accounts: newAccounts()} + svc, store = buildSvc(t, repo.accounts) + require.NoError(t, store.BindResponseAccount(poolCtx, groupID, responseID, 39002, time.Hour)) + narrowCtx := WithCompositeCandidatePlatforms(context.Background(), []string{PlatformDeepseek}) + selection, decision, err = svc.SelectAccountWithScheduler(narrowCtx, &groupID, responseID, "", model, nil, OpenAIUpstreamTransportAny, false) + require.NoError(t, err) + require.NotNil(t, selection) + require.EqualValues(t, 39001, selection.Account.ID) + require.False(t, decision.StickyPreviousHit) + bound, err = store.GetResponseAccount(poolCtx, groupID, responseID) + require.NoError(t, err) + require.EqualValues(t, 39002, bound, "池外健康 owner 绑定保留,不得仅因非 OpenAI 被删") + + // 6) excluded:无 hit、绑定保留。 + repo = &compositePoolTestRepo{accounts: newAccounts()} + svc, store = buildSvc(t, repo.accounts) + require.NoError(t, store.BindResponseAccount(poolCtx, groupID, responseID, 39001, time.Hour)) + excluded := map[int64]struct{}{39001: {}} + selection, decision, err = svc.SelectAccountWithScheduler(poolCtx, &groupID, responseID, "", model, excluded, OpenAIUpstreamTransportAny, false) + require.NoError(t, err) + require.NotNil(t, selection) + require.NotEqualValues(t, 39001, selection.Account.ID) + require.False(t, decision.StickyPreviousHit) + bound, err = store.GetResponseAccount(poolCtx, groupID, responseID) + require.NoError(t, err) + require.EqualValues(t, 39001, bound) + + // 7) owner 不可用:无 hit、绑定按失效原策略删除、LB 选中另一账号。 + repo = &compositePoolTestRepo{accounts: newAccounts()} + svc, store = buildSvc(t, repo.accounts) + require.NoError(t, store.BindResponseAccount(poolCtx, groupID, responseID, 39001, time.Hour)) + repo.accounts[0].Schedulable = false + selection, decision, err = svc.SelectAccountWithScheduler(poolCtx, &groupID, responseID, "", model, nil, OpenAIUpstreamTransportAny, false) + require.NoError(t, err) + require.NotNil(t, selection) + require.EqualValues(t, 39002, selection.Account.ID) + require.False(t, decision.StickyPreviousHit) + bound, err = store.GetResponseAccount(poolCtx, groupID, responseID) + require.NoError(t, err) + require.EqualValues(t, 0, bound, "失效 owner 绑定按原策略删除") + + // 8) 非池 legacy(无池 ctx):pin 层不进入;platform=openai 的 legacy 在 + // CN-only repo 上本就无容量(原行为),CN 绑定不受影响。 + repo = &compositePoolTestRepo{accounts: newAccounts()} + svc, store = buildSvc(t, repo.accounts) + require.NoError(t, store.BindResponseAccount(poolCtx, groupID, responseID, 39001, time.Hour)) + _, decision, err = svc.SelectAccountWithScheduler(context.Background(), &groupID, responseID, "", model, nil, OpenAIUpstreamTransportAny, false) + require.Error(t, err) + require.True(t, errors.Is(err, ErrNoAvailableAccounts)) + require.False(t, decision.StickyPreviousHit, "非池 legacy 不进入 pin 层") + bound, err = store.GetResponseAccount(poolCtx, groupID, responseID) + require.NoError(t, err) + require.EqualValues(t, 39001, bound) +} diff --git a/backend/internal/service/openai_gateway_messages.go b/backend/internal/service/openai_gateway_messages.go index a45dd5e565..a1ce80fc9d 100644 --- a/backend/internal/service/openai_gateway_messages.go +++ b/backend/internal/service/openai_gateway_messages.go @@ -406,6 +406,9 @@ func (s *OpenAIGatewayService) ForwardAsAnthropic( if account.ProxyID != nil && account.Proxy != nil { proxyURL = account.Proxy.URL() } + // Codex transform 等可能在初始映射后再归一模型;发送前记录最终 slug + // (端点已在步骤 6 前按实际分流记录),失败路径的错误日志保留真实模型。 + SetOpsUpstreamModel(c, upstreamModel) // Grok may reject encrypted reasoning replayed under a different OAuth // account/cache identity. Match forwardGrokResponses: one strip+retry before // treating the 400 as a hard failure / failover trigger. diff --git a/backend/internal/service/openai_gateway_messages_anthropic_native.go b/backend/internal/service/openai_gateway_messages_anthropic_native.go index 0026046a58..baabaaa34d 100644 --- a/backend/internal/service/openai_gateway_messages_anthropic_native.go +++ b/backend/internal/service/openai_gateway_messages_anthropic_native.go @@ -100,6 +100,12 @@ func (s *OpenAIGatewayService) forwardAnthropicViaNativeAnthropicEndpoint( return nil, err } + // adaptive/anthropic 协议账号的真实出站端点是供应商原生 /v1/messages(非 + // Responses)。发送前记录实际端点与最终映射模型,404/500 等失败没有 + // OpenAIForwardResult 时错误日志仍能报告真实值。 + SetOpsUpstreamEndpoint(c, "/v1/messages") + SetOpsUpstreamModel(c, upstreamModel) + resp, err := s.doOpenAIUpstream(upstreamReq, proxyURL, account) if err != nil { return nil, s.handleOpenAIUpstreamTransportError(ctx, c, account, err, true) diff --git a/backend/internal/service/openai_gateway_messages_chat_fallback.go b/backend/internal/service/openai_gateway_messages_chat_fallback.go index 2d2c997b97..47e612cb45 100644 --- a/backend/internal/service/openai_gateway_messages_chat_fallback.go +++ b/backend/internal/service/openai_gateway_messages_chat_fallback.go @@ -120,6 +120,9 @@ func (s *OpenAIGatewayService) forwardAnthropicViaRawChatCompletions( if err != nil { return nil, err } + // 发送前记录最终映射模型(端点由 sendCCUpstreamRequest 统一记录), + // 失败路径的错误日志才能带上真实的 account-mapped model。 + SetOpsUpstreamModel(c, upstreamModel) resp, err := s.sendCCUpstreamRequest(ctx, c, account, targetURL, chatBody, clientStream, apiKey, account.GetOpenAIUserAgent(), "") if err != nil { return nil, err diff --git a/backend/internal/service/openai_gateway_scheduling.go b/backend/internal/service/openai_gateway_scheduling.go index fe93880ee0..c0cc98a6dc 100644 --- a/backend/internal/service/openai_gateway_scheduling.go +++ b/backend/internal/service/openai_gateway_scheduling.go @@ -299,6 +299,69 @@ func NormalizeOpenAICompatiblePlatform(platform string) string { } } +// ---- composite account_pool 契约接入点(增量2A) ---- +// +// 池上下文与模型能力谓词的所有权在增量1(composite_platform.go / +// composite_account_claims.go):WithCompositeCandidatePlatforms / +// CompositeCandidatePlatformsFromContext 携带 immutable 候选池, +// CompositeAccountClaimsModel 是构池与选号共用的能力谓词。以下辅助函数直接调用 +// 契约函数:池请求(ctx 携带候选池)在 OpenAI 兼容族内做跨平台调度,无池请求 +// 行为与增量2A 之前一致。 + +// openAICompositePoolActive 报告当前请求是否按「composite account_pool」调度。 +// 显式 force/单 target 路由(ctx 已带 ResolvedTargetPlatform,含 Gemini pin 语义) +// 优先于池:resolved 平台不允许被池成员资格绕过;此时即使 ctx 残留候选池也按 +// 单平台旧行为调度,选号/重试不得写 resolved 把池缩小(池 immutable)。 +func openAICompositePoolActive(ctx context.Context) bool { + if _, resolved := ResolvedTargetPlatformFromContext(ctx); resolved { + return false + } + return len(CompositeCandidatePlatformsFromContext(ctx)) > 0 +} + +// openAICompositePoolAllowsAccount 判定账号是否属于本次请求的候选池。 +// 无池时恒为 false,调用方据此保持原平台相等门行为。 +func openAICompositePoolAllowsAccount(ctx context.Context, account *Account) bool { + if account == nil || !account.IsOpenAICompatible() { + return false + } + for _, platform := range CompositeCandidatePlatformsFromContext(ctx) { + if platform == account.Platform { + return true + } + } + return false +} + +// openAISchedulingPlatformMatchesAccount 是调度选号/sticky 的账号平台门: +// 单平台请求保持原 NormalizeOpenAICompatiblePlatform 相等语义; +// 池请求改为候选池成员校验(池 immutable,选号/重试不塌缩)。 +func openAISchedulingPlatformMatchesAccount(ctx context.Context, account *Account, platform string) bool { + if openAICompositePoolActive(ctx) { + return openAICompositePoolAllowsAccount(ctx, account) + } + return account != nil && account.Platform == NormalizeOpenAICompatiblePlatform(platform) +} + +// openAISchedulingModelSupported 是选号/sticky 的模型能力门: +// 池请求使用契约共享谓词(非空 mapping 精确/通配命中,空 mapping 仅 native +// 平台命中),单平台请求保持 IsModelSupported 原语义。 +// +// 选号期 passthrough 例外:passthrough 账号只替换认证、模型语义交由上游决定, +// credentials 残留旧的非空 mapping 未命中时不得误踢出候选(#4936 语义在池路径 +// 的等价保留)。该例外仅在池成员资格已另行验证的「选号期」生效;构池/ownership +// 谓词 CompositeAccountClaimsModel 保持严格——passthrough 不得据此在构建候选池 +// 时 claim 所有模型。 +func openAISchedulingModelSupported(ctx context.Context, account *Account, requestedModel string) bool { + if account == nil || requestedModel == "" { + return true + } + if openAICompositePoolActive(ctx) { + return CompositeAccountClaimsModel(account, requestedModel) || account.IsOpenAIPassthroughEnabled() + } + return account.IsModelSupported(requestedModel) +} + // noAvailableOpenAISelectionError builds the standard "no account available" error // while preserving the legacy /responses/compact error when applicable. // details carries an optional machine-parseable exclusion summary (e.g. @@ -392,17 +455,7 @@ func openAICompatibleAccountEligibilityFailureReasonBeforeProfit(ctx context.Con if account == nil { return "account_nil" } - // account_model composite routes publish an alias that only accounts with an - // explicit model mapping own. Both scheduler modes (advanced and legacy) must - // enforce ownership before any priority/sticky/transport consideration; a - // non-owner would forward the raw public alias and get model_not_found or - // hit an unrelated same-name upstream model. - if source, ok := CompositeRouteSourceFromContext(ctx); ok && source == CompositeRouteSourceAccount { - if publicModel, modelOK := RequestedPublicModelFromContext(ctx); modelOK && !explicitModelMappingClaims(*account, publicModel) { - return "account_model_not_owned" - } - } - if account.Platform != platform || !account.IsOpenAICompatible() { + if !account.IsOpenAICompatible() || !openAISchedulingPlatformMatchesAccount(ctx, account, platform) { return "platform_mismatch" } if !account.IsSchedulableForModelWithContext(ctx, requestedModel) { @@ -441,7 +494,7 @@ func openAICompatibleAccountEligibilityFailureReasonBeforeProfit(ctx context.Con return "quota_auto_pause" } } - if requestedModel != "" && !account.IsModelSupported(requestedModel) { + if requestedModel != "" && !openAISchedulingModelSupported(ctx, account, requestedModel) { return "model_not_supported" } if !account.SupportsOpenAIEndpointCapability(requiredCapability) { @@ -976,6 +1029,11 @@ func (s *OpenAIGatewayService) tryStickySessionHit(ctx context.Context, groupID if err != nil { return nil } + // composite pool denied 平台:sticky 账号只是暂时排除——不 delete(绑定保留), + // 不进入下方任何会清绑定的分支,直接回落其它候选。 + if compositePoolPlatformDenied(ctx, account.Platform) { + return nil + } // 检查账号是否需要清理粘性会话 // Check if sticky session should be cleared @@ -1211,7 +1269,9 @@ func (s *OpenAIGatewayService) selectAccountWithLoadAwareness(ctx context.Contex accountID := stickyAccountID if accountID > 0 && !isExcluded(accountID) { account, err := s.getSchedulableAccount(ctx, accountID) - if err == nil { + if err == nil && !compositePoolPlatformDenied(ctx, account.Platform) { + // composite pool denied 平台:sticky 账号暂时排除——不 delete、 + // 不计 spillover,直接落 Layer 2。 clearSticky := shouldClearStickySession(account, requestedModel) if clearSticky { _ = s.deleteStickySessionAccountID(ctx, groupID, sessionHash) @@ -1499,7 +1559,47 @@ func (s *OpenAIGatewayService) selectAccountWithLoadAwareness(ctx context.Contex } func (s *OpenAIGatewayService) listSchedulableAccounts(ctx context.Context, groupID *int64, platform string) ([]Account, error) { + if openAICompositePoolActive(ctx) { + return s.listSchedulableAccountsForCompositePool(ctx, groupID, CompositeCandidatePlatformsFromContext(ctx)) + } + return s.listSchedulableAccountsSinglePlatform(ctx, groupID, platform) +} + +// listSchedulableAccountsForCompositePool 逐候选 platform 读取既有单平台桶并把 +// 结果复制进新 slice、按账号 ID 去重。每个桶经独立的 snapshot→DB fallback 链路, +// 语义与单平台完全等价;池本身 immutable,这里不就地修改任何共享缓存元素,也 +// 不对桶做排序(priority/load/LRU 排序留给下游既有选号算法)。 +// excludedIDs 由调用方按账号 ID 传递,跨平台天然通用;所有候选健康但均不合格时 +// 由下游 filter 产出无容量错误(ErrNoAvailableAccounts),不升级为 UnsupportedModel。 +func (s *OpenAIGatewayService) listSchedulableAccountsForCompositePool(ctx context.Context, groupID *int64, platforms []string) ([]Account, error) { + merged := make([]Account, 0, len(platforms)*4) + seen := make(map[int64]struct{}, len(platforms)*4) + for _, platform := range platforms { + // 本次请求被策略 deny 的平台:整平台跳过(候选池本身不变)。 + if compositePoolPlatformDenied(ctx, platform) { + continue + } + bucket, err := s.listSchedulableAccountsSinglePlatform(ctx, groupID, platform) + if err != nil { + return nil, err + } + for i := range bucket { + if _, duplicate := seen[bucket[i].ID]; duplicate { + continue + } + seen[bucket[i].ID] = struct{}{} + merged = append(merged, bucket[i]) + } + } + return merged, nil +} + +func (s *OpenAIGatewayService) listSchedulableAccountsSinglePlatform(ctx context.Context, groupID *int64, platform string) ([]Account, error) { platform = NormalizeOpenAICompatiblePlatform(platform) + // 单平台请求的 attempt ctx 若携带 denied 平台:临时排除,空桶返回。 + if compositePoolPlatformDenied(ctx, platform) { + return nil, nil + } if s.schedulerSnapshot != nil { accounts, _, err := s.schedulerSnapshot.ListSchedulableAccounts(ctx, groupID, platform, false) if err != nil { diff --git a/backend/internal/service/openai_gateway_usage.go b/backend/internal/service/openai_gateway_usage.go index 824d2b94dd..84e6fd49f5 100644 --- a/backend/internal/service/openai_gateway_usage.go +++ b/backend/internal/service/openai_gateway_usage.go @@ -498,9 +498,15 @@ func (s *OpenAIGatewayService) RecordUsage(ctx context.Context, input *OpenAIRec // 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{ diff --git a/backend/internal/service/openai_ws_forwarder_support.go b/backend/internal/service/openai_ws_forwarder_support.go index 02332f1884..e84ede5e3a 100644 --- a/backend/internal/service/openai_ws_forwarder_support.go +++ b/backend/internal/service/openai_ws_forwarder_support.go @@ -520,6 +520,21 @@ func (s *OpenAIGatewayService) ResolveAccountIDByPreviousResponseIDForScheduler( return accountID } +// openAICompositePoolHTTPResponsesOwner 报告账号是否可作为 composite account_pool +// 请求的 native HTTP Responses previous_response_id 归属账号。判定口径(已核对 +// 实际方法而非名称推论):池上下文 + OpenAI 兼容族(IsOpenAICompatible = 7 族 +// 全集 openai/grok/kimi/zhipu/deepseek/minimax/opencode_go,含 grok—— +// IsMultiProtocolAPIKeyProvider 不含 grok,不可用)+ APIKey 类型。 +// 这些平台的 HTTP Responses 归属本就经 bindHTTPResponseAccount 写入同一 store; +// 本次请求池外成员与 OpenAI 平台同权——resolve 放行、由 scheduler.Select 的池 +// 成员/claims/组复检拒绝并保留绑定,避免绑定仅因非 OpenAI 被误删。 +// OAuth/SetupToken 续链状态属 WSv2 session,不在此列;WS 入口不写 active pool +// ctx、单平台无池,范围天然受限。required capability 等门在后续原位校验。 +func openAICompositePoolHTTPResponsesOwner(ctx context.Context, account *Account) bool { + return openAICompositePoolActive(ctx) && account != nil && + account.Type == AccountTypeAPIKey && account.IsOpenAICompatible() +} + func (s *OpenAIGatewayService) resolveAccountByPreviousResponseIDForCapability( ctx context.Context, groupID *int64, @@ -560,10 +575,14 @@ func (s *OpenAIGatewayService) resolveAccountByPreviousResponseIDForCapability( // survive an HTTP fallback. Official API-key Responses HTTP requests are // different: previous_response_id is supported by the provider and scoped to // the selected key/project, so the response-id binding must retain that key. - if !account.IsOpenAIApiKey() && s.getOpenAIWSProtocolResolver().Resolve(account).Transport != OpenAIUpstreamTransportResponsesWebsocketV2 { + // composite account_pool 例外:池上下文中的 CN/OpenCode APIKey 账号经 + // bindHTTPResponseAccount 持有同 key 的真实 HTTP 归属,与 OpenAI APIKey 同权。 + if !openAICompositePoolHTTPResponsesOwner(ctx, account) && !account.IsOpenAIApiKey() && + s.getOpenAIWSProtocolResolver().Resolve(account).Transport != OpenAIUpstreamTransportResponsesWebsocketV2 { return 0, nil, "", nil } - if shouldClearStickySession(account, requestedModel) || !account.IsOpenAI() || !account.IsSchedulable() { + if shouldClearStickySession(account, requestedModel) || + (!account.IsOpenAI() && !openAICompositePoolHTTPResponsesOwner(ctx, account)) || !account.IsSchedulable() { _ = store.DeleteResponseAccount(ctx, derefGroupID(groupID), responseID) return 0, nil, "", nil } @@ -571,7 +590,7 @@ func (s *OpenAIGatewayService) resolveAccountByPreviousResponseIDForCapability( _ = store.DeleteResponseAccount(ctx, derefGroupID(groupID), responseID) return 0, nil, "", nil } - if requestedModel != "" && !account.IsModelSupported(requestedModel) { + if requestedModel != "" && !openAISchedulingModelSupported(ctx, account, requestedModel) { return 0, nil, "", nil } if !account.SupportsOpenAIEndpointCapability(requiredCapability) { @@ -596,7 +615,8 @@ func (s *OpenAIGatewayService) resolveAccountByPreviousResponseIDForCapability( _ = store.DeleteResponseAccount(ctx, derefGroupID(groupID), responseID) return 0, nil, "", nil } - if shouldClearStickySession(latest, requestedModel) || !latest.IsOpenAI() || !latest.IsSchedulable() { + if shouldClearStickySession(latest, requestedModel) || + (!latest.IsOpenAI() && !openAICompositePoolHTTPResponsesOwner(ctx, latest)) || !latest.IsSchedulable() { _ = store.DeleteResponseAccount(ctx, derefGroupID(groupID), responseID) return 0, nil, "", nil } @@ -610,7 +630,7 @@ func (s *OpenAIGatewayService) resolveAccountByPreviousResponseIDForCapability( _ = store.DeleteResponseAccount(ctx, derefGroupID(groupID), responseID) return 0, nil, "", nil } - if requestedModel != "" && !latest.IsModelSupported(requestedModel) { + if requestedModel != "" && !openAISchedulingModelSupported(ctx, latest, requestedModel) { return 0, nil, "", nil } if !latest.SupportsOpenAIEndpointCapability(requiredCapability) { diff --git a/backend/internal/service/ops_upstream_context.go b/backend/internal/service/ops_upstream_context.go index 4d09a43ae6..0b25628ae5 100644 --- a/backend/internal/service/ops_upstream_context.go +++ b/backend/internal/service/ops_upstream_context.go @@ -3,6 +3,7 @@ package service import ( "encoding/json" "errors" + "net/http" "strconv" "strings" "time" @@ -22,6 +23,12 @@ const ( OpsUpstreamErrorsKey = "ops_upstream_errors" OpsUpstreamModelKey = "ops_upstream_model" + // OpsUpstreamEndpointKey 保存最近一次真实出站尝试的端点路径。由各实际 + // forwarder 在发送前写入;GetUpstreamEndpoint(handler)优先消费它, + // 使失败日志报告真实上游路径而不是按 group/platform 推导的入站路径 + // (例如 composite 组 inbound=/v1/chat/completions 实际打到 /v1/messages)。 + OpsUpstreamEndpointKey = "ops_upstream_endpoint" + // Optional stage latencies (milliseconds) for troubleshooting and alerting. OpsAuthLatencyMsKey = "ops_auth_latency_ms" OpsRoutingLatencyMsKey = "ops_routing_latency_ms" @@ -100,6 +107,54 @@ func ClearOpsUpstreamModel(c *gin.Context) { c.Set(OpsUpstreamModelKey, "") } +// SetOpsUpstreamEndpoint records the endpoint path of the current outbound +// attempt. Call it immediately before the request is dispatched so that error +// paths (404/500, transport failures) still report the real upstream target. +// Only the URL path is stored — never query strings, userinfo or credentials. +func SetOpsUpstreamEndpoint(c *gin.Context, endpoint string) { + if c == nil { + return + } + if endpoint = strings.TrimSpace(endpoint); endpoint != "" { + c.Set(OpsUpstreamEndpointKey, endpoint) + } +} + +// GetOpsUpstreamEndpoint returns the endpoint recorded by the latest outbound +// attempt in this request, or "" when no attempt was recorded. +func GetOpsUpstreamEndpoint(c *gin.Context) string { + if c == nil { + return "" + } + value, exists := c.Get(OpsUpstreamEndpointKey) + if !exists { + return "" + } + endpoint, _ := value.(string) + return strings.TrimSpace(endpoint) +} + +// ClearOpsUpstreamEndpoint invalidates attempt-scoped endpoint attribution +// before a newly selected account starts its forward attempt. +func ClearOpsUpstreamEndpoint(c *gin.Context) { + if c == nil { + return + } + c.Set(OpsUpstreamEndpointKey, "") +} + +// SetOpsUpstreamRequestTarget snapshots the actual outbound request target and +// the final mapped model immediately before dispatch. It is called by real +// forwarders once the http.Request is built; a request that later fails still +// keeps the metadata for ops error attribution. +func SetOpsUpstreamRequestTarget(c *gin.Context, req *http.Request, model string) { + if c == nil || req == nil || req.URL == nil { + return + } + SetOpsUpstreamEndpoint(c, req.URL.Path) + SetOpsUpstreamModel(c, model) +} + func MarkOpsClientBusinessLimited(c *gin.Context, reason string) { if c == nil { return From 006ed5af252055084faca6581d109e101b957e90 Mon Sep 17 00:00:00 2001 From: alfadb Date: Sat, 12 Sep 2026 14:27:53 +0800 Subject: [PATCH 02/81] fix(composite): handle unavailable sticky accounts without panic --- .../openai_composite_pool_sticky_nil_test.go | 179 ++++++++++++++++++ .../service/openai_gateway_scheduling.go | 7 +- 2 files changed, 184 insertions(+), 2 deletions(-) create mode 100644 backend/internal/service/openai_composite_pool_sticky_nil_test.go diff --git a/backend/internal/service/openai_composite_pool_sticky_nil_test.go b/backend/internal/service/openai_composite_pool_sticky_nil_test.go new file mode 100644 index 0000000000..a63e642e1a --- /dev/null +++ b/backend/internal/service/openai_composite_pool_sticky_nil_test.go @@ -0,0 +1,179 @@ +package service + +// 回归:sticky 命中的账号经 getSchedulableAccount 返回 (nil, nil) 时不得 panic。 +// +// getSchedulableAccount 合法返回 (nil, nil)(snapshot miss / 调度阈值暂停 / +// grok 免费额度耗尽均收敛为 nil, nil)。composite 平台 denied 检查 +// compositePoolPlatformDenied(ctx, account.Platform) 若位于 nil 判定之前, +// 读取 account.Platform 即 nil deref —— 非 composite 池请求同样 500。 +// +// 覆盖: +// a. legacy 无 batch 路径(SelectAccountForModelWithExclusions → +// tryStickySessionHit):nil 账号跳过 sticky 尝试(不删绑定),正常选号 +// 命中健康替代账号; +// b. legacy 负载 batch 路径(SelectAccountWithLoadAwareness → Layer 1 +// sticky):nil 账号降级落 Layer 2,选中健康替代账号; +// c. 非 pool / pool / pool+denied 三种 ctx 均不 panic; +// d. advanced scheduler 路径在 getSchedulableAccount 之后先做 err/nil 双判 +// (openai_account_scheduler.go sticky 链路),本就 nil 安全,作回归对照; +// 不为测试改变任何绑定策略。 + +import ( + "context" + "testing" + + "github.com/stretchr/testify/require" +) + +// stickyNilAccountRepo 让指定账号在 GetByID 时返回 (nil, nil),其余行为与 +// compositePoolTestRepo 完全一致,模拟 getSchedulableAccount 的合法 nil 返回。 +// 该账号对调度 listing 同样不可见:生产 listSchedulableAccountsSinglePlatform +// 对阈值暂停 / grok 额度耗尽账号本就做同样过滤,listing 与 GetByID 保持一致。 +type stickyNilAccountRepo struct { + *compositePoolTestRepo + nilIDs map[int64]struct{} +} + +func (r *stickyNilAccountRepo) GetByID(ctx context.Context, id int64) (*Account, error) { + if _, vanished := r.nilIDs[id]; vanished { + return nil, nil + } + return r.compositePoolTestRepo.GetByID(ctx, id) +} + +func (r *stickyNilAccountRepo) visibleAccounts(accounts []Account) []Account { + out := make([]Account, 0, len(accounts)) + for _, acc := range accounts { + if _, vanished := r.nilIDs[acc.ID]; vanished { + continue + } + out = append(out, acc) + } + return out +} + +func (r *stickyNilAccountRepo) ListSchedulableByPlatform(ctx context.Context, platform string) ([]Account, error) { + accounts, err := r.compositePoolTestRepo.ListSchedulableByPlatform(ctx, platform) + return r.visibleAccounts(accounts), err +} + +func (r *stickyNilAccountRepo) ListSchedulableByGroupIDAndPlatform(ctx context.Context, groupID int64, platform string) ([]Account, error) { + accounts, err := r.compositePoolTestRepo.ListSchedulableByGroupIDAndPlatform(ctx, groupID, platform) + return r.visibleAccounts(accounts), err +} + +func (r *stickyNilAccountRepo) ListSchedulableUngroupedByPlatform(ctx context.Context, platform string) ([]Account, error) { + accounts, err := r.compositePoolTestRepo.ListSchedulableUngroupedByPlatform(ctx, platform) + return r.visibleAccounts(accounts), err +} + +// newStickyNilDerefTestService 基于既有 composite pool fixture 构造服务,并把 +// accountRepo 换成对指定账号返回 (nil, nil) 的包装 repo。 +func newStickyNilDerefTestService(accounts []Account, cache GatewayCache, vanishedAccountID int64) *OpenAIGatewayService { + svc := newCompositePoolTestService(accounts, cache) + svc.accountRepo = &stickyNilAccountRepo{ + compositePoolTestRepo: &compositePoolTestRepo{accounts: accounts}, + nilIDs: map[int64]struct{}{vanishedAccountID: {}}, + } + return svc +} + +func stickyNilDerefTestContexts() map[string]func() context.Context { + return map[string]func() context.Context{ + // 非 composite 池:plain ctx 也曾 panic(deref 发生在 denied 判定取参之前)。 + "plain_ctx_no_pool": func() context.Context { return context.Background() }, + "composite_pool_ctx": func() context.Context { + return WithCompositeCandidatePlatforms(context.Background(), []string{PlatformDeepseek, PlatformOpenAI}) + }, + "composite_pool_denied_ctx": func() context.Context { + ctx := WithCompositeCandidatePlatforms(context.Background(), []string{PlatformDeepseek, PlatformOpenAI}) + return WithCompositePoolDeniedPlatforms(ctx, []string{PlatformDeepseek}) + }, + } +} + +// stickyNilDerefAccounts:44001 (deepseek) 是 sticky 指向、"查询即消失"的账号; +// 44002 (openai) 是健康替代账号。 +func stickyNilDerefAccounts(groupID int64) []Account { + return []Account{ + compositePoolTestAccount(44001, PlatformDeepseek, groupID, 0, map[string]any{"my-model": "deepseek-chat"}), + compositePoolTestAccount(44002, PlatformOpenAI, groupID, 0, map[string]any{"my-model": "gpt-4o"}), + } +} + +// ---- a. legacy 无 batch:tryStickySessionHit 命中 (nil, nil) 账号 ---- + +func TestOpenAICompositePoolStickyNilAccount_LegacyNoBatchFallsBack(t *testing.T) { + resetOpenAIAdvancedSchedulerSettingCacheForTest() + defer resetOpenAIAdvancedSchedulerSettingCacheForTest() + + groupID := int64(22021) + model := "my-model" + sessionHash := "sessnilstick00001" + + for name, newCtx := range stickyNilDerefTestContexts() { + t.Run(name, func(t *testing.T) { + cache := &compositePoolTestCache{} + svc := newStickyNilDerefTestService(stickyNilDerefAccounts(groupID), cache, 44001) + ctx := newCtx() + require.NoError(t, svc.BindStickySession(ctx, &groupID, sessionHash, 44001)) + + account, err := svc.SelectAccountForModelWithExclusions(ctx, &groupID, sessionHash, model, nil) + require.NoError(t, err) + require.NotNil(t, account) + require.EqualValues(t, 44002, account.ID) + // sticky 指向 (nil, nil) 账号:跳过 sticky 尝试而非清绑定; + // 全程不得出现对该 session 的 delete(绑定由正常选号接管)。 + require.NotContains(t, cache.delKeys, "openai:"+sessionHash) + }) + } +} + +// ---- b. legacy 负载 batch:Layer 1 sticky 命中 (nil, nil) 账号 ---- + +func TestOpenAICompositePoolStickyNilAccount_LegacyLoadBatchFallsToLayer2(t *testing.T) { + resetOpenAIAdvancedSchedulerSettingCacheForTest() + defer resetOpenAIAdvancedSchedulerSettingCacheForTest() + + groupID := int64(22022) + model := "my-model" + sessionHash := "sessnilstick00002" + + for name, newCtx := range stickyNilDerefTestContexts() { + t.Run(name, func(t *testing.T) { + cache := &compositePoolTestCache{} + svc := newStickyNilDerefTestService(stickyNilDerefAccounts(groupID), cache, 44001) + svc.cfg.Gateway.Scheduling.LoadBatchEnabled = true + ctx := newCtx() + require.NoError(t, svc.BindStickySession(ctx, &groupID, sessionHash, 44001)) + + result, err := svc.SelectAccountWithLoadAwareness(ctx, &groupID, sessionHash, model, nil) + require.NoError(t, err) + require.NotNil(t, result) + require.NotNil(t, result.Account) + require.EqualValues(t, 44002, result.Account.ID) + }) + } +} + +// ---- d. advanced scheduler 回归对照(本就 nil 安全,不为测试改绑定策略) ---- + +func TestOpenAICompositePoolStickyNilAccount_AdvancedSchedulerControl(t *testing.T) { + groupID := int64(22023) + model := "my-model" + sessionHash := "sessnilstick00003" + + cache := &compositePoolTestCache{} + svc := newStickyNilDerefTestService(stickyNilDerefAccounts(groupID), cache, 44001) + svc.rateLimitService = newOpenAIAdvancedSchedulerRateLimitService("true") + svc.cfg.Gateway.Scheduling.LoadBatchEnabled = true + ctx := WithCompositeCandidatePlatforms(context.Background(), []string{PlatformDeepseek, PlatformOpenAI}) + require.NoError(t, svc.BindStickySession(ctx, &groupID, sessionHash, 44001)) + + selection, decision, err := svc.SelectAccountWithScheduler(ctx, &groupID, "", sessionHash, model, nil, OpenAIUpstreamTransportAny, false) + require.NoError(t, err) + require.NotNil(t, selection) + require.NotNil(t, selection.Account) + require.EqualValues(t, 44002, selection.Account.ID) + require.False(t, decision.StickySessionHit) +} diff --git a/backend/internal/service/openai_gateway_scheduling.go b/backend/internal/service/openai_gateway_scheduling.go index c0cc98a6dc..b8295ad0a0 100644 --- a/backend/internal/service/openai_gateway_scheduling.go +++ b/backend/internal/service/openai_gateway_scheduling.go @@ -1026,7 +1026,9 @@ func (s *OpenAIGatewayService) tryStickySessionHit(ctx context.Context, groupID } account, err := s.getSchedulableAccount(ctx, accountID) - if err != nil { + // (nil, nil) 合法(snapshot miss / 调度阈值暂停 / grok 额度耗尽): + // 跳过 sticky 尝试、保留绑定,回落正常选号。 + if err != nil || account == nil { return nil } // composite pool denied 平台:sticky 账号只是暂时排除——不 delete(绑定保留), @@ -1269,7 +1271,8 @@ func (s *OpenAIGatewayService) selectAccountWithLoadAwareness(ctx context.Contex accountID := stickyAccountID if accountID > 0 && !isExcluded(accountID) { account, err := s.getSchedulableAccount(ctx, accountID) - if err == nil && !compositePoolPlatformDenied(ctx, account.Platform) { + // 保持旧 nil 降级语义:(nil, nil) 与 sticky miss 等价,直接落 Layer 2。 + if err == nil && account != nil && !compositePoolPlatformDenied(ctx, account.Platform) { // composite pool denied 平台:sticky 账号暂时排除——不 delete、 // 不计 spillover,直接落 Layer 2。 clearSticky := shouldClearStickySession(account, requestedModel) From 16612cd6a73a25a6fe6d373f542e8bf2f263b1dc Mon Sep 17 00:00:00 2001 From: alfadb Date: Sat, 12 Sep 2026 14:48:56 +0800 Subject: [PATCH 03/81] test(composite): align empty-mapping deepseek fixtures with official model whitelist MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 组合 fix/deepseek-model-name-validation 后,DeepSeek 空 mapping 账号的 IsModelSupported 改按官方白名单判定,deepseek-chat 已不在白名单。composite 规则B(空 mapping native claim)语义不变,测试夹具从已退役的 deepseek-chat 换成白名单名 deepseek-flash / deepseek-v4-pro。 --- .../service/composite_account_claims_test.go | 13 +++++++------ .../service/composite_pool_contract_test.go | 11 ++++++----- .../openai_composite_pool_scheduling_test.go | 5 +++-- 3 files changed, 16 insertions(+), 13 deletions(-) diff --git a/backend/internal/service/composite_account_claims_test.go b/backend/internal/service/composite_account_claims_test.go index 2c54c49a9c..17e08549dc 100644 --- a/backend/internal/service/composite_account_claims_test.go +++ b/backend/internal/service/composite_account_claims_test.go @@ -52,13 +52,14 @@ func TestCompositeAccountClaimsModel_NormalizedLookupHit(t *testing.T) { // 规则B:空 mapping 仅当 detector 平台一致且 IsModelSupported 通过。 func TestCompositeAccountClaimsModel_EmptyMappingNativeOnly(t *testing.T) { deepseek := &Account{Platform: PlatformDeepseek} - require.True(t, CompositeAccountClaimsModel(deepseek, "deepseek-chat")) + // 使用受支持的 DeepSeek 模型名(空 mapping native claim 受官方白名单约束)。 + require.True(t, CompositeAccountClaimsModel(deepseek, "deepseek-flash")) // detector 平台不一致的空 mapping 账号不得冒领(测试 b 的谓词面)。 openAI := &Account{Platform: PlatformOpenAI} - require.False(t, CompositeAccountClaimsModel(openAI, "deepseek-chat")) + require.False(t, CompositeAccountClaimsModel(openAI, "deepseek-flash")) zhipu := &Account{Platform: PlatformZhipu} - require.False(t, CompositeAccountClaimsModel(zhipu, "deepseek-chat")) + require.False(t, CompositeAccountClaimsModel(zhipu, "deepseek-flash")) // detector 不认识的模型,空 mapping 任何平台都不得 claim。 require.False(t, CompositeAccountClaimsModel(deepseek, "unknown-alias")) @@ -144,9 +145,9 @@ func TestCompositeAccountClaimStrength(t *testing.T) { } require.Equal(t, CompositeClaimNone, CompositeAccountClaimStrength(emptyTarget, "empty-alias")) - // 受控 native 空 mapping 与精确同强等级。 + // 受控 native 空 mapping 与精确同强等级(模型名须在 deepseek 官方白名单内)。 native := &Account{Platform: PlatformDeepseek} - require.Equal(t, CompositeClaimExplicit, CompositeAccountClaimStrength(native, "deepseek-chat")) + require.Equal(t, CompositeClaimExplicit, CompositeAccountClaimStrength(native, "deepseek-flash")) // detector 不认识的模型无声明。 require.Equal(t, CompositeClaimNone, CompositeAccountClaimStrength(native, "unknown-alias")) require.Equal(t, CompositeClaimNone, CompositeAccountClaimStrength(nil, "gpt-5")) @@ -176,5 +177,5 @@ func TestCompositeAccountClaimsModel_IgnoresTransientState(t *testing.T) { RateLimitResetAt: &now, OverloadUntil: &now, } - require.True(t, CompositeAccountClaimsModel(account, "deepseek-chat")) + require.True(t, CompositeAccountClaimsModel(account, "deepseek-flash")) } diff --git a/backend/internal/service/composite_pool_contract_test.go b/backend/internal/service/composite_pool_contract_test.go index 9c5c51c4b7..79cc63a283 100644 --- a/backend/internal/service/composite_pool_contract_test.go +++ b/backend/internal/service/composite_pool_contract_test.go @@ -63,8 +63,9 @@ func TestCompositePoolOwnershipDualPlatformExplicitAlias(t *testing.T) { require.Equal(t, []string{PlatformDeepseek, PlatformOpenAI, PlatformZhipu}, ownership.CandidatePlatforms) } -// b. 官方 deepseek 空 mapping(规则B,强声明)+ opencode 显式 mapping(规则A -// 精确,强声明)→ 双平台 pool;空 mapping 的无关 openai/zhipu 账号不入池。 +// b. 官方 deepseek 空 mapping(规则B,强声明,使用受支持的 DeepSeek 模型名) +// + opencode 显式 mapping(规则A 精确,强声明)→ 双平台 pool;空 mapping 的 +// 无关 openai/zhipu 账号不入池。 func TestCompositePoolOwnershipDeepseekNativePlusOpenCodeMapping(t *testing.T) { groupID := int64(7) repo := compositePoolOwnershipRepo([]Account{ @@ -73,7 +74,7 @@ func TestCompositePoolOwnershipDeepseekNativePlusOpenCodeMapping(t *testing.T) { ID: 2, Platform: PlatformOpenCodeGo, Credentials: map[string]any{ - "model_mapping": map[string]any{"deepseek-chat": "deepseek-chat"}, + "model_mapping": map[string]any{"deepseek-flash": "deepseek-flash"}, }, }, {ID: 3, Platform: PlatformOpenAI}, @@ -81,14 +82,14 @@ func TestCompositePoolOwnershipDeepseekNativePlusOpenCodeMapping(t *testing.T) { }) svc := &GatewayService{accountRepo: repo} - ownership, err := svc.resolveCompositeModelOwnership(context.Background(), groupID, "deepseek-chat") + ownership, err := svc.resolveCompositeModelOwnership(context.Background(), groupID, "deepseek-flash") require.NoError(t, err) require.True(t, ownership.Matched) require.Empty(t, ownership.TargetPlatform) require.Equal(t, []string{PlatformDeepseek, PlatformOpenCodeGo}, ownership.CandidatePlatforms) // 仅 deepseek 空 mapping 声明时保持 single(既有语义)。 - single, err := svc.resolveCompositeModelOwnership(context.Background(), groupID, "deepseek-reasoner") + single, err := svc.resolveCompositeModelOwnership(context.Background(), groupID, "deepseek-v4-pro") require.NoError(t, err) require.Equal(t, CompositeModelOwnership{TargetPlatform: PlatformDeepseek, Matched: true}, single) } diff --git a/backend/internal/service/openai_composite_pool_scheduling_test.go b/backend/internal/service/openai_composite_pool_scheduling_test.go index 216bc01c79..38cc418b67 100644 --- a/backend/internal/service/openai_composite_pool_scheduling_test.go +++ b/backend/internal/service/openai_composite_pool_scheduling_test.go @@ -425,7 +425,8 @@ func TestOpenAICompositePool_ClaimsPredicateGatesPoolMembership(t *testing.T) { opencodeMapped := compositePoolTestAccount(35003, PlatformOpenCodeGo, 22007, 0, map[string]any{"my-model": "deepseek-chat"}) // 官方 deepseek 空 mapping:native detector 命中 → 可 claim。 - require.True(t, openAISchedulingModelSupported(poolCtx, &deepseekAccount, "deepseek-chat")) + // 使用受支持的 DeepSeek 模型名(空 mapping native claim 受官方白名单约束)。 + require.True(t, openAISchedulingModelSupported(poolCtx, &deepseekAccount, "deepseek-flash")) // 无关平台空 mapping:不得凭 IsModelSupported 的 allow-all 冒领。 require.False(t, openAISchedulingModelSupported(poolCtx, &kimiAccount, "deepseek-chat")) require.True(t, kimiAccount.IsModelSupported("deepseek-chat"), "旧语义 allow-all 仍成立,池路径必须改用 claims 谓词") @@ -444,7 +445,7 @@ func TestOpenAICompositePool_ClaimsPredicateGatesPoolMembership(t *testing.T) { repo := &compositePoolTestRepo{accounts: []Account{deepseekAccount, kimiAccount}} cache := &compositePoolTestCache{} svc := newCompositePoolTestService(repo.accounts, cache) - selection, err := svc.SelectAccountForModelWithExclusions(poolCtx, &groupID, "", "deepseek-chat", nil) + selection, err := svc.SelectAccountForModelWithExclusions(poolCtx, &groupID, "", "deepseek-flash", nil) require.NoError(t, err) require.EqualValues(t, 35001, selection.ID) } From 7ff8fd34586e4c5285868763b4e765968b18c723 Mon Sep 17 00:00:00 2001 From: alfadb Date: Sun, 13 Sep 2026 15:55:13 +0800 Subject: [PATCH 04/81] feat(composite): serve cross-family pools via per-account protocol dispatch MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 解除 composite 候选池的协议族限制:入站任意协议族端点可服务池内任意 平台账号,厂商多协议时优先与入站相同的协议族(零转换),否则协议转换。 - routes:混族/全原生族池不再 400,落 generic 网关按选中账号分发; 全 OpenAI 族池仍走 OpenAI handler(不变) - generic 调度器放行池:跨平台候选合并选号、池感知平台/模型门、 sticky 复检防塌缩(镜像 OpenAI 族池调度) - generic 转发 base 协议化:多协议账号打 GetAnthropicProtocolBaseURL 的 {base}/v1/messages(无 ?beta=true、认证/clamp 同源),classic anthropic 不回归 - generic Messages/Responses/ChatCompletions 循环池化:per-attempt 配额与渠道策略(复用 OpenAI 池策略)、attempt ctx + platform 作用域 渠道映射;纯 OpenAI 族账号按端点委派 OpenAI 网关同族链,usage 适配 进既有计费流;count_tokens 不可计数账号排除重选 - 谓词能力驱动(IsAnthropicProtocol/adaptive/GetAnthropicProtocolBaseURL), 不引入平台硬编码清单,后续多协议平台合入后零改动继承 --- .../composite_generic_pool_messages_test.go | 463 ++++++++++++++ ...posite_generic_pool_text_endpoints_test.go | 393 ++++++++++++ .../handler/composite_pool_attempt_policy.go | 93 +++ backend/internal/handler/gateway_handler.go | 120 +++- .../gateway_handler_chat_completions.go | 95 ++- .../handler/gateway_handler_responses.go | 89 ++- backend/internal/server/routes/gateway.go | 34 +- .../routes/gateway_composite_pool_test.go | 115 +++- .../service/composite_generic_pool.go | 82 +++ .../composite_generic_pool_scheduling_test.go | 594 ++++++++++++++++++ .../service/gateway_anthropic_passthrough.go | 21 +- .../internal/service/gateway_count_tokens.go | 40 +- .../internal/service/gateway_scheduling.go | 187 ++++-- .../service/gateway_upstream_request.go | 70 ++- 14 files changed, 2229 insertions(+), 167 deletions(-) create mode 100644 backend/internal/handler/composite_generic_pool_messages_test.go create mode 100644 backend/internal/handler/composite_generic_pool_text_endpoints_test.go create mode 100644 backend/internal/service/composite_generic_pool.go create mode 100644 backend/internal/service/composite_generic_pool_scheduling_test.go diff --git a/backend/internal/handler/composite_generic_pool_messages_test.go b/backend/internal/handler/composite_generic_pool_messages_test.go new file mode 100644 index 0000000000..a41e80f49c --- /dev/null +++ b/backend/internal/handler/composite_generic_pool_messages_test.go @@ -0,0 +1,463 @@ +//go:build unit + +package handler + +import ( + "context" + "fmt" + "io" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/Wei-Shaw/sub2api/internal/pkg/ctxkey" + "github.com/Wei-Shaw/sub2api/internal/pkg/tlsfingerprint" + middleware2 "github.com/Wei-Shaw/sub2api/internal/server/middleware" + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" +) + +// ---- composite generic Messages/CountTokens 池化(B1)测试 ---- +// +// 构造手法对齐 gateway_handler_warmup_intercept_unit_test.go(真实 GatewayService + +// fake scheduler cache / group repo / concurrency cache,RunModeSimple 跳过计费)与 +// openai_gateway_credential_failover_loop_test.go(fake HTTPUpstream 假上游)。 + +// compositePoolUpstreamCall 记录一次假上游调用。 +type compositePoolUpstreamCall struct { + Path string + Body []byte + Authorization string + APIKeyHeader string + AccountID int64 +} + +// compositePoolFakeUpstream 实现 service.HTTPUpstream,按调用序回放构造的响应。 +type compositePoolFakeUpstream struct { + mu sync.Mutex + calls []compositePoolUpstreamCall + respond func(call compositePoolUpstreamCall, index int) *http.Response +} + +func (u *compositePoolFakeUpstream) Do(req *http.Request, _ string, accountID int64, _ int) (*http.Response, error) { + body, _ := io.ReadAll(req.Body) + u.mu.Lock() + call := compositePoolUpstreamCall{ + Path: req.URL.Path, + Body: body, + Authorization: req.Header.Get("Authorization"), + APIKeyHeader: req.Header.Get("x-api-key"), + AccountID: accountID, + } + u.calls = append(u.calls, call) + respond := u.respond + u.mu.Unlock() + if respond != nil { + return respond(call, len(u.calls)-1), nil + } + return &http.Response{ + StatusCode: http.StatusInternalServerError, + Header: http.Header{"Content-Type": []string{"application/json"}}, + Body: io.NopCloser(strings.NewReader(`{"error":{"type":"api_error","message":"upstream failed"}}`)), + }, nil +} + +func (u *compositePoolFakeUpstream) DoWithTLS(req *http.Request, proxyURL string, accountID int64, concurrency int, _ *tlsfingerprint.Profile) (*http.Response, error) { + return u.Do(req, proxyURL, accountID, concurrency) +} + +func (u *compositePoolFakeUpstream) snapshot() []compositePoolUpstreamCall { + u.mu.Lock() + defer u.mu.Unlock() + return append([]compositePoolUpstreamCall(nil), u.calls...) +} + +// chatCompletionsOKResponse 返回一份带 usage 的非流式 Chat Completions 响应。 +func chatCompletionsOKResponse(model string, promptTokens, completionTokens int) *http.Response { + body := fmt.Sprintf( + `{"id":"chatcmpl-pool","object":"chat.completion","created":1,"model":%q,"choices":[{"index":0,"message":{"role":"assistant","content":"hi from %s"},"finish_reason":"stop"}],"usage":{"prompt_tokens":%d,"completion_tokens":%d}}`, + model, model, promptTokens, completionTokens) + return &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{"application/json"}, "X-Request-Id": []string{"req-cc-pool"}}, + Body: io.NopCloser(strings.NewReader(body)), + } +} + +// anthropicMessagesOKResponse 返回一份 Anthropic Messages 成功响应。 +func anthropicMessagesOKResponse() *http.Response { + body := `{"id":"msg_pool_native","type":"message","role":"assistant","model":"claude-sonnet-4-5","content":[{"type":"text","text":"hi from anthropic"}],"stop_reason":"end_turn","usage":{"input_tokens":12,"output_tokens":5}}` + return &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{"application/json"}, "X-Request-Id": []string{"req-native-pool"}}, + Body: io.NopCloser(strings.NewReader(body)), + } +} + +// countTokensOKResponse 返回一份 Anthropic count_tokens 成功响应。 +func countTokensOKResponse() *http.Response { + return &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{"application/json"}}, + Body: io.NopCloser(strings.NewReader(`{"input_tokens":42}`)), + } +} + +// compositePoolUsageLogRepo 捕获 usage_log 写入(RunModeSimple 只走 best-effort 写入)。 +type compositePoolUsageLogRepo struct { + service.UsageLogRepository + mu sync.Mutex + logs []*service.UsageLog +} + +func (r *compositePoolUsageLogRepo) CreateBestEffort(_ context.Context, log *service.UsageLog) error { + r.mu.Lock() + defer r.mu.Unlock() + r.logs = append(r.logs, log) + return nil +} + +func (r *compositePoolUsageLogRepo) snapshot() []*service.UsageLog { + r.mu.Lock() + defer r.mu.Unlock() + return append([]*service.UsageLog(nil), r.logs...) +} + +// compositePoolMessagesHarness 组装 generic Messages/CountTokens 池化测试的 handler。 +type compositePoolMessagesHarness struct { + handler *GatewayHandler + group *service.Group + openAIUpstream *compositePoolFakeUpstream + gwUpstream *compositePoolFakeUpstream + usageRepo *compositePoolUsageLogRepo +} + +func newCompositePoolMessagesHarness(t *testing.T, accounts []*service.Account) *compositePoolMessagesHarness { + t.Helper() + gin.SetMode(gin.TestMode) + + groupID := int64(41011) + group := &service.Group{ID: groupID, Platform: service.PlatformComposite, Status: service.StatusActive, Hydrated: true} + + cfg := &config.Config{RunMode: config.RunModeSimple} + cfg.Security = config.SecurityConfig{URLAllowlist: config.URLAllowlistConfig{Enabled: false}} + + usageRepo := &compositePoolUsageLogRepo{} + openAIUpstream := &compositePoolFakeUpstream{} + gwUpstream := &compositePoolFakeUpstream{} + + schedulerCache := &fakeSchedulerCache{accounts: accounts} + schedulerSnapshot := service.NewSchedulerSnapshotService(schedulerCache, nil, nil, nil, nil) + billingService := service.NewBillingService(cfg, nil) + + gatewayService := service.NewGatewayService( + nil, // accountRepo:调度走 scheduler snapshot + &fakeGroupRepo{group: group}, + usageRepo, // usageLogRepo:捕获 usage 行 + nil, nil, nil, nil, // usageBillingRepo / userRepo / userSubRepo / userGroupRateRepo + nil, // cache:禁用 sticky + cfg, + schedulerSnapshot, + nil, // concurrencyService:负载感知降级 + billingService, + nil, nil, nil, // rateLimitService / billingCacheService / identityService + gwUpstream, // httpUpstream:generic Forward / CountTokens 假上游 + nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, + ) + + openAIGatewayService := service.NewOpenAIGatewayService( + nil, nil, nil, nil, nil, nil, nil, + cfg, + nil, nil, + billingService, + nil, nil, + openAIUpstream, // httpUpstream:委派链假上游 + nil, nil, nil, nil, nil, nil, nil, nil, + ) + + billingCacheService := service.NewBillingCacheService(nil, nil, nil, nil, nil, nil, cfg, nil) + t.Cleanup(billingCacheService.Stop) + + handler := &GatewayHandler{ + gatewayService: gatewayService, + openAIGatewayService: openAIGatewayService, + billingCacheService: billingCacheService, + concurrencyHelper: NewConcurrencyHelper(service.NewConcurrencyService(&fakeConcurrencyCache{}), SSEPingFormatClaude, 0), + maxAccountSwitches: 3, + cfg: cfg, + } + return &compositePoolMessagesHarness{ + handler: handler, + group: group, + openAIUpstream: openAIUpstream, + gwUpstream: gwUpstream, + usageRepo: usageRepo, + } +} + +// newCompositePoolGatewayRequest 构造带候选池 ctx 与 composite 分组身份的请求。 +func (h *compositePoolMessagesHarness) newRequest(t *testing.T, path, body string, platforms ...string) (*gin.Context, *httptest.ResponseRecorder) { + t.Helper() + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + req := httptest.NewRequest(http.MethodPost, path, strings.NewReader(body)) + req.Header.Set("Content-Type", "application/json") + ctx := service.WithCompositeCandidatePlatforms(context.Background(), platforms) + ctx = context.WithValue(ctx, ctxkey.Group, h.group) + req = req.WithContext(ctx) + c.Request = req + + apiKey := &service.APIKey{ + ID: 41012, + UserID: 41013, + GroupID: &h.group.ID, + Status: service.StatusActive, + User: &service.User{ID: 41013, Concurrency: 10, Balance: 100}, + Group: h.group, + } + c.Set(string(middleware2.ContextKeyAPIKey), apiKey) + c.Set(string(middleware2.ContextKeyUser), middleware2.AuthSubject{UserID: apiKey.UserID, Concurrency: 10}) + return c, rec +} + +func poolMessagesBody() string { + return `{"model":"my-model","max_tokens":64,"stream":false,"messages":[{"role":"user","content":"hello"}]}` +} + +func poolCountTokensBody() string { + return `{"model":"my-model","messages":[{"role":"user","content":"hello"}]}` +} + +// poolKimiAccount 纯 OpenAI 族(CC 协议)kimi 账号:池选中后委派 ForwardAsAnthropic。 +func poolKimiAccount(id int64, groupID int64, priority int) *service.Account { + return &service.Account{ + ID: id, Name: fmt.Sprintf("kimi-%d", id), Platform: service.PlatformKimi, + Type: service.AccountTypeAPIKey, Status: service.StatusActive, Schedulable: true, + Concurrency: 1, Priority: priority, + AccountGroups: []service.AccountGroup{{AccountID: id, GroupID: groupID}}, + Credentials: map[string]any{ + "api_key": "kimi-key", + "base_url": "https://kimi.example/v1", + "api_protocol": service.APIProtocolChatCompletions, + "model_mapping": map[string]any{"my-model": "kimi-k3"}, + }, + } +} + +// poolAnthropicAccount anthropic 原生 APIKey 账号:走既有 generic Forward。 +func poolAnthropicAccount(id int64, groupID int64, priority int) *service.Account { + return &service.Account{ + ID: id, Name: fmt.Sprintf("anthropic-%d", id), Platform: service.PlatformAnthropic, + Type: service.AccountTypeAPIKey, Status: service.StatusActive, Schedulable: true, + Concurrency: 1, Priority: priority, + AccountGroups: []service.AccountGroup{{AccountID: id, GroupID: groupID}}, + Credentials: map[string]any{ + "api_key": "anthropic-key", + "base_url": "https://relay.example", + "model_mapping": map[string]any{"my-model": "claude-sonnet-4-5"}, + }, + } +} + +// poolAdaptiveKimiAccount 多协议 adaptive kimi 账号(Anthropic 协议 base 可解析): +// 走既有 generic Forward(service 层协议化 base)。 +func poolAdaptiveKimiAccount(id int64, groupID int64, priority int) *service.Account { + return &service.Account{ + ID: id, Name: fmt.Sprintf("kimi-adaptive-%d", id), Platform: service.PlatformKimi, + Type: service.AccountTypeAPIKey, Status: service.StatusActive, Schedulable: true, + Concurrency: 1, Priority: priority, + AccountGroups: []service.AccountGroup{{AccountID: id, GroupID: groupID}}, + Credentials: map[string]any{ + "api_key": "adaptive-key", + "api_protocol": service.APIProtocolAdaptive, + "api_base_urls": map[string]any{"anthropic": "https://adaptive.example"}, + "model_mapping": map[string]any{"my-model": "claude-sonnet-4-5"}, + }, + } +} + +// 池选中纯 OpenAI 族账号:委派 OpenAIGatewayService.ForwardAsAnthropic 转发(假上游 +// 收到 Chat Completions 请求),响应以 Anthropic Messages 格式写回,usage 适配进 +// 既有 RecordUsage 流(token 计数与模型映射链不丢)。 +func TestCompositePoolMessagesDelegatesPureOpenAIFamilyAccount(t *testing.T) { + h := newCompositePoolMessagesHarness(t, []*service.Account{poolKimiAccount(41101, 41011, 0)}) + h.openAIUpstream.respond = func(compositePoolUpstreamCall, int) *http.Response { + return chatCompletionsOKResponse("kimi-k3", 11, 7) + } + + c, rec := h.newRequest(t, "/v1/messages", poolMessagesBody(), service.PlatformAnthropic, service.PlatformKimi) + h.handler.Messages(c) + + require.Equal(t, http.StatusOK, rec.Code) + require.Equal(t, "message", gjson.GetBytes(rec.Body.Bytes(), "type").String(), + "委派链响应必须是 Anthropic Messages 格式") + require.Equal(t, int64(11), gjson.GetBytes(rec.Body.Bytes(), "usage.input_tokens").Int()) + require.Equal(t, int64(7), gjson.GetBytes(rec.Body.Bytes(), "usage.output_tokens").Int()) + + // 假上游收到的是 Chat Completions 请求(协议转换链生效)。 + calls := h.openAIUpstream.snapshot() + require.Len(t, calls, 1) + require.True(t, strings.HasSuffix(calls[0].Path, "/chat/completions"), "upstream path=%s", calls[0].Path) + require.Contains(t, string(calls[0].Body), `"model":"kimi-k3"`, "账号级 model_mapping 必须生效") + require.Contains(t, calls[0].Authorization, "kimi-key") + + // 选中账号 ops 记录为 kimi 账号。 + selected, ok := c.Get(opsAccountIDKey) + require.True(t, ok) + require.EqualValues(t, 41101, selected) + + // usage 适配记录已提交:token 计数与模型映射链进入 usage 行。 + logs := h.usageRepo.snapshot() + require.Len(t, logs, 1) + require.Equal(t, 11, logs[0].InputTokens) + require.Equal(t, 7, logs[0].OutputTokens) + require.EqualValues(t, 41101, logs[0].AccountID) + require.Equal(t, "my-model", logs[0].Model, "公开请求模型作为计费/展示模型记录") + require.NotNil(t, logs[0].UpstreamModel) + require.Equal(t, "kimi-k3", *logs[0].UpstreamModel) +} + +// 池选中多协议账号(adaptive,Anthropic 协议 base 可解析):走既有 generic Forward +// (假上游收到 {base}/v1/messages 请求),不委派 OpenAI 链。 +func TestCompositePoolMessagesMultiProtocolAccountUsesGenericForward(t *testing.T) { + h := newCompositePoolMessagesHarness(t, []*service.Account{poolAdaptiveKimiAccount(41201, 41011, 0)}) + h.gwUpstream.respond = func(compositePoolUpstreamCall, int) *http.Response { + return anthropicMessagesOKResponse() + } + + c, rec := h.newRequest(t, "/v1/messages", poolMessagesBody(), service.PlatformAnthropic, service.PlatformKimi) + h.handler.Messages(c) + + require.Equal(t, http.StatusOK, rec.Code) + require.Equal(t, "msg_pool_native", gjson.GetBytes(rec.Body.Bytes(), "id").String()) + + calls := h.gwUpstream.snapshot() + require.Len(t, calls, 1) + require.True(t, strings.HasSuffix(calls[0].Path, "/v1/messages"), "upstream path=%s", calls[0].Path) + require.False(t, strings.HasSuffix(calls[0].Path, "/chat/completions")) + require.Equal(t, "adaptive-key", calls[0].APIKeyHeader, "多协议账号默认 x-api-key 认证") + require.Empty(t, h.openAIUpstream.snapshot(), "多协议账号不得委派 OpenAI 链") + + selected, ok := c.Get(opsAccountIDKey) + require.True(t, ok) + require.EqualValues(t, 41201, selected) + + logs := h.usageRepo.snapshot() + require.Len(t, logs, 1) + require.Equal(t, 12, logs[0].InputTokens) + require.Equal(t, 5, logs[0].OutputTokens) +} + +// 委派链返回 UpstreamFailoverError:走既有 failover 语义换号重选,改用 anthropic +// 原生账号的 generic Forward 完成请求。 +func TestCompositePoolMessagesDelegationFailoverSwitchesAccount(t *testing.T) { + h := newCompositePoolMessagesHarness(t, []*service.Account{ + poolKimiAccount(41301, 41011, 0), + poolAnthropicAccount(41302, 41011, 5), + }) + h.gwUpstream.respond = func(compositePoolUpstreamCall, int) *http.Response { + return anthropicMessagesOKResponse() + } + // kimi 假上游默认回 500(respond 为 nil 时的兜底响应即 500)。 + + c, rec := h.newRequest(t, "/v1/messages", poolMessagesBody(), service.PlatformAnthropic, service.PlatformKimi) + h.handler.Messages(c) + + require.Equal(t, http.StatusOK, rec.Code) + require.Equal(t, "msg_pool_native", gjson.GetBytes(rec.Body.Bytes(), "id").String(), + "failover 后应由 anthropic 原生账号完成请求") + + // 第一次委派失败(CC 上游 500),第二次走 generic Forward。 + require.Len(t, h.openAIUpstream.snapshot(), 1) + require.Len(t, h.gwUpstream.snapshot(), 1) + require.True(t, strings.HasSuffix(h.gwUpstream.snapshot()[0].Path, "/v1/messages")) + + selected, ok := c.Get(opsAccountIDKey) + require.True(t, ok) + require.EqualValues(t, 41302, selected, "ops 记录最终选中的 anthropic 账号") + + logs := h.usageRepo.snapshot() + require.Len(t, logs, 1) + require.EqualValues(t, 41302, logs[0].AccountID) +} + +// count_tokens 池请求选中纯 OpenAI 族账号:跳过该账号重选(排除集),而不是对 +// /v1/messages/count_tokens 报 500。池内无可计数账号时按无可用账号终止。 +func TestCompositePoolCountTokensSkipsUncountableOpenAIAccount(t *testing.T) { + h := newCompositePoolMessagesHarness(t, []*service.Account{poolKimiAccount(41401, 41011, 0)}) + + c, rec := h.newRequest(t, "/v1/messages/count_tokens", poolCountTokensBody(), service.PlatformAnthropic, service.PlatformKimi) + h.handler.CountTokens(c) + + require.NotEqual(t, http.StatusOK, rec.Code, "纯 OpenAI 族账号被跳过后按无可用账号终止") + require.Empty(t, h.gwUpstream.snapshot(), "不可计数账号不得转发 count_tokens") + require.Empty(t, h.openAIUpstream.snapshot()) +} + +// count_tokens 池请求跳过纯 OpenAI 族账号后改选可计数的 anthropic 账号并成功转发。 +func TestCompositePoolCountTokensSkipsThenForwardsCountableAccount(t *testing.T) { + h := newCompositePoolMessagesHarness(t, []*service.Account{ + poolKimiAccount(41501, 41011, 0), + poolAnthropicAccount(41502, 41011, 5), + }) + h.gwUpstream.respond = func(compositePoolUpstreamCall, int) *http.Response { + return countTokensOKResponse() + } + + c, rec := h.newRequest(t, "/v1/messages/count_tokens", poolCountTokensBody(), service.PlatformAnthropic, service.PlatformKimi) + h.handler.CountTokens(c) + + require.Equal(t, http.StatusOK, rec.Code) + require.Equal(t, int64(42), gjson.GetBytes(rec.Body.Bytes(), "input_tokens").Int()) + + calls := h.gwUpstream.snapshot() + require.Len(t, calls, 1) + require.True(t, strings.HasSuffix(calls[0].Path, "/v1/messages/count_tokens"), "upstream path=%s", calls[0].Path) + require.Equal(t, "anthropic-key", calls[0].APIKeyHeader) + + selected, ok := c.Get(opsAccountIDKey) + require.True(t, ok) + require.EqualValues(t, 41502, selected, "ops 记录最终选中的可计数账号") +} + +// 池账号委派分发谓词与结果适配器的纯函数契约。 +func TestCompositePoolAccountDelegationPredicateAndAdapter(t *testing.T) { + // 纯 OpenAI 族账号(含 openai/grok/国产 CC 供应商)→ 委派。 + require.True(t, compositePoolAccountDelegatesToOpenAI(poolKimiAccount(1, 1, 0))) + require.True(t, compositePoolAccountDelegatesToOpenAI(&service.Account{Platform: service.PlatformOpenAI})) + require.True(t, compositePoolAccountDelegatesToOpenAI(&service.Account{Platform: service.PlatformGrok})) + + // anthropic 原生 / gemini / antigravity → 既有 Forward。 + require.False(t, compositePoolAccountDelegatesToOpenAI(poolAnthropicAccount(2, 1, 0))) + require.False(t, compositePoolAccountDelegatesToOpenAI(&service.Account{Platform: service.PlatformGemini})) + require.False(t, compositePoolAccountDelegatesToOpenAI(&service.Account{Platform: service.PlatformAntigravity})) + + // 多协议(adaptive / anthropic-协议)账号 → 既有 Forward(service 协议化 base)。 + require.False(t, compositePoolAccountDelegatesToOpenAI(poolAdaptiveKimiAccount(3, 1, 0))) + require.False(t, compositePoolAccountDelegatesToOpenAI(nil)) + + // 结果适配:usage token 计数与元数据逐字段映射,nil 安全。 + require.Nil(t, adaptOpenAIForwardResultToForwardResult(nil)) + adapted := adaptOpenAIForwardResultToForwardResult(&service.OpenAIForwardResult{ + RequestID: "rid", + Usage: service.OpenAIUsage{InputTokens: 3, OutputTokens: 4, CacheCreationInputTokens: 5, CacheReadInputTokens: 6}, + Model: "public", + UpstreamModel: "upstream", + Stream: true, + SearchCount: 2, + }) + require.Equal(t, "rid", adapted.RequestID) + require.Equal(t, 3, adapted.Usage.InputTokens) + require.Equal(t, 4, adapted.Usage.OutputTokens) + require.Equal(t, 5, adapted.Usage.CacheCreationInputTokens) + require.Equal(t, 6, adapted.Usage.CacheReadInputTokens) + require.Equal(t, "public", adapted.Model) + require.Equal(t, "upstream", adapted.UpstreamModel) + require.True(t, adapted.Stream) + require.Equal(t, 2, adapted.SearchCount) +} diff --git a/backend/internal/handler/composite_generic_pool_text_endpoints_test.go b/backend/internal/handler/composite_generic_pool_text_endpoints_test.go new file mode 100644 index 0000000000..62c33f6fbf --- /dev/null +++ b/backend/internal/handler/composite_generic_pool_text_endpoints_test.go @@ -0,0 +1,393 @@ +//go:build unit + +package handler + +import ( + "fmt" + "io" + "net/http" + "strings" + "testing" + + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" +) + +// ---- composite generic Responses / ChatCompletions 池化(B2)测试 ---- +// +// 复用 composite_generic_pool_messages_test.go(B1)的假上游 / usage 捕获 / harness +// 组装手法:池候选 ctx + composite 分组身份 + RunModeSimple 跳过计费,委派链与 +// generic 转换链分别挂 openAIUpstream / gwUpstream 假上游。 + +func poolResponsesBody() string { + return `{"model":"my-model","stream":false,"input":"hello","max_output_tokens":64}` +} + +func poolChatCompletionsBody() string { + return `{"model":"my-model","stream":false,"messages":[{"role":"user","content":"hello"}]}` +} + +// poolKimiResponsesAccount 固定 responses 协议的 kimi 账号(UsesNativeCNResponses): +// Responses 入站按原生 Responses 端点委派。 +func poolKimiResponsesAccount(id int64, groupID int64, priority int) *service.Account { + return &service.Account{ + ID: id, Name: fmt.Sprintf("kimi-resp-%d", id), Platform: service.PlatformKimi, + Type: service.AccountTypeAPIKey, Status: service.StatusActive, Schedulable: true, + Concurrency: 1, Priority: priority, + AccountGroups: []service.AccountGroup{{AccountID: id, GroupID: groupID}}, + Credentials: map[string]any{ + "api_key": "kimi-resp-key", + "base_url": "https://kimi.example/v1", + "api_protocol": service.APIProtocolResponses, + "model_mapping": map[string]any{"my-model": "kimi-k3"}, + }, + } +} + +// poolZhipuAdaptiveAccount 无原生 Responses 端点的 adaptive 国产账号(GLM 平台): +// Responses 入站不委派(走既有 generic 转换链)。 +func poolZhipuAdaptiveAccount(id int64, groupID int64, priority int) *service.Account { + return &service.Account{ + ID: id, Name: fmt.Sprintf("zhipu-adaptive-%d", id), Platform: service.PlatformZhipu, + Type: service.AccountTypeAPIKey, Status: service.StatusActive, Schedulable: true, + Concurrency: 1, Priority: priority, + AccountGroups: []service.AccountGroup{{AccountID: id, GroupID: groupID}}, + Credentials: map[string]any{ + "api_key": "zhipu-adaptive-key", + "api_protocol": service.APIProtocolAdaptive, + "api_base_urls": map[string]any{"anthropic": "https://zhipu-adaptive.example"}, + "model_mapping": map[string]any{"my-model": "glm-4.7"}, + }, + } +} + +// anthropicMessagesSSEStreamResponse 返回一段完整的 Anthropic Messages SSE 流。 +// generic Responses/CC → Anthropic 转换链强制上游流式(clientStream 无关),假上游 +// 必须以 SSE 回包,缓冲转换链聚合成入站协议格式写回。 +func anthropicMessagesSSEStreamResponse() *http.Response { + sse := strings.Join([]string{ + `event: message_start`, + `data: {"type":"message_start","message":{"id":"msg_pool_sse","type":"message","role":"assistant","model":"claude-sonnet-4-5","content":[],"usage":{"input_tokens":12,"output_tokens":1}}}`, + ``, + `event: content_block_delta`, + `data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"hi from anthropic"}}`, + ``, + `event: message_delta`, + `data: {"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":5}}`, + ``, + `event: message_stop`, + `data: {"type":"message_stop"}`, + ``, + }, "\n") + return &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{"text/event-stream"}, "X-Request-Id": []string{"req-native-pool-sse"}}, + Body: io.NopCloser(strings.NewReader(sse)), + } +} + +// 池选中纯 OpenAI 族账号(国产 CC 固定):Responses 入站委派 OpenAI 网关 +// Responses 链(链内降级 Responses→CC 直转原生 CC 端点),响应以 Responses 格式 +// 写回,usage 适配进既有 RecordUsage 流(token 计数与模型映射链不丢)。 +func TestCompositePoolResponsesDelegatesPureOpenAIFamilyAccount(t *testing.T) { + h := newCompositePoolMessagesHarness(t, []*service.Account{poolKimiAccount(42101, 41011, 0)}) + h.openAIUpstream.respond = func(compositePoolUpstreamCall, int) *http.Response { + return chatCompletionsOKResponse("kimi-k3", 11, 7) + } + + c, rec := h.newRequest(t, "/v1/responses", poolResponsesBody(), service.PlatformAnthropic, service.PlatformKimi) + h.handler.Responses(c) + + require.Equal(t, http.StatusOK, rec.Code) + require.Equal(t, "response", gjson.GetBytes(rec.Body.Bytes(), "object").String(), + "委派链响应必须是 OpenAI Responses 格式") + require.Equal(t, int64(11), gjson.GetBytes(rec.Body.Bytes(), "usage.input_tokens").Int()) + require.Equal(t, int64(7), gjson.GetBytes(rec.Body.Bytes(), "usage.output_tokens").Int()) + + // 假上游收到的是 Responses→CC 降级转换后的 Chat Completions 请求(链内分流生效)。 + calls := h.openAIUpstream.snapshot() + require.Len(t, calls, 1) + require.True(t, strings.HasSuffix(calls[0].Path, "/chat/completions"), "upstream path=%s", calls[0].Path) + require.Contains(t, string(calls[0].Body), `"model":"kimi-k3"`, "账号级 model_mapping 必须生效") + require.Contains(t, calls[0].Authorization, "kimi-key") + require.Empty(t, h.gwUpstream.snapshot(), "纯 OpenAI 族账号不得走 generic 转换链") + + // usage 适配记录已提交:token 计数与模型映射链进入 usage 行。 + logs := h.usageRepo.snapshot() + require.Len(t, logs, 1) + require.Equal(t, 11, logs[0].InputTokens) + require.Equal(t, 7, logs[0].OutputTokens) + require.EqualValues(t, 42101, logs[0].AccountID) + require.Equal(t, "my-model", logs[0].Model, "公开请求模型作为计费/展示模型记录") + require.NotNil(t, logs[0].UpstreamModel) + require.Equal(t, "kimi-k3", *logs[0].UpstreamModel) +} + +// 池选中固定 responses 协议的国产账号(UsesNativeCNResponses):Responses 入站 +// 委派 OpenAI 链直连原生 Responses 端点(零转换)。 +func TestCompositePoolResponsesDelegatesNativeCNResponsesAccount(t *testing.T) { + h := newCompositePoolMessagesHarness(t, []*service.Account{poolKimiResponsesAccount(42151, 41011, 0)}) + h.openAIUpstream.respond = func(compositePoolUpstreamCall, int) *http.Response { + return openAIResponsesOKResponse("my-model", 13, 8) + } + + c, rec := h.newRequest(t, "/v1/responses", poolResponsesBody(), service.PlatformAnthropic, service.PlatformKimi) + h.handler.Responses(c) + + require.Equal(t, http.StatusOK, rec.Code) + require.Equal(t, int64(13), gjson.GetBytes(rec.Body.Bytes(), "usage.input_tokens").Int()) + require.Equal(t, int64(8), gjson.GetBytes(rec.Body.Bytes(), "usage.output_tokens").Int()) + + calls := h.openAIUpstream.snapshot() + require.Len(t, calls, 1) + require.True(t, strings.HasSuffix(calls[0].Path, "/responses"), "upstream path=%s", calls[0].Path) + require.False(t, strings.HasSuffix(calls[0].Path, "/chat/completions"), "原生 Responses 账号不得降级 CC") + require.Empty(t, h.gwUpstream.snapshot()) + + logs := h.usageRepo.snapshot() + require.Len(t, logs, 1) + require.Equal(t, 13, logs[0].InputTokens) + require.Equal(t, 8, logs[0].OutputTokens) + require.EqualValues(t, 42151, logs[0].AccountID) +} + +// 池选中 anthropic 原生账号:走既有 generic Responses→Anthropic 转换链(假上游 +// 收到 {base}/v1/messages),不委派 OpenAI 链。 +func TestCompositePoolResponsesAnthropicAccountUsesGenericConversion(t *testing.T) { + h := newCompositePoolMessagesHarness(t, []*service.Account{poolAnthropicAccount(42201, 41011, 0)}) + h.gwUpstream.respond = func(compositePoolUpstreamCall, int) *http.Response { + return anthropicMessagesSSEStreamResponse() + } + + c, rec := h.newRequest(t, "/v1/responses", poolResponsesBody(), service.PlatformAnthropic, service.PlatformKimi) + h.handler.Responses(c) + + require.Equal(t, http.StatusOK, rec.Code) + require.Equal(t, int64(12), gjson.GetBytes(rec.Body.Bytes(), "usage.input_tokens").Int()) + require.Equal(t, int64(5), gjson.GetBytes(rec.Body.Bytes(), "usage.output_tokens").Int()) + + calls := h.gwUpstream.snapshot() + require.Len(t, calls, 1) + require.True(t, strings.HasSuffix(calls[0].Path, "/v1/messages"), "upstream path=%s", calls[0].Path) + require.Equal(t, "anthropic-key", calls[0].APIKeyHeader) + require.Empty(t, h.openAIUpstream.snapshot(), "anthropic 账号不得委派 OpenAI 链") + + logs := h.usageRepo.snapshot() + require.Len(t, logs, 1) + require.Equal(t, 12, logs[0].InputTokens) + require.Equal(t, 5, logs[0].OutputTokens) +} + +// Responses 委派链返回 failover 错误:走既有 failover 语义换号重选,改用 +// anthropic 原生账号的 generic 转换链完成请求。 +func TestCompositePoolResponsesDelegationFailoverSwitchesAccount(t *testing.T) { + h := newCompositePoolMessagesHarness(t, []*service.Account{ + poolKimiAccount(42301, 41011, 0), + poolAnthropicAccount(42302, 41011, 5), + }) + h.gwUpstream.respond = func(compositePoolUpstreamCall, int) *http.Response { + return anthropicMessagesSSEStreamResponse() + } + // kimi 假上游默认回 500(respond 为 nil 时的兜底响应即 500)。 + + c, rec := h.newRequest(t, "/v1/responses", poolResponsesBody(), service.PlatformAnthropic, service.PlatformKimi) + h.handler.Responses(c) + + require.Equal(t, http.StatusOK, rec.Code) + require.Equal(t, int64(12), gjson.GetBytes(rec.Body.Bytes(), "usage.input_tokens").Int(), + "failover 后应由 anthropic 账号的 generic 转换链完成请求") + + // 第一次委派失败(CC 上游 500),第二次走 generic 转换链。 + require.Len(t, h.openAIUpstream.snapshot(), 1) + require.Len(t, h.gwUpstream.snapshot(), 1) + require.True(t, strings.HasSuffix(h.gwUpstream.snapshot()[0].Path, "/v1/messages")) + + selected, ok := c.Get(opsAccountIDKey) + require.True(t, ok) + require.EqualValues(t, 42302, selected, "ops 记录最终选中的 anthropic 账号") + + logs := h.usageRepo.snapshot() + require.Len(t, logs, 1) + require.EqualValues(t, 42302, logs[0].AccountID) +} + +// 池选中纯 OpenAI 族账号(国产 CC 固定):CC 入站委派 OpenAI 网关 CC 链,同族 +// 零转换直转原生 CC 端点,响应与 usage 走既有链路。 +func TestCompositePoolChatCompletionsDelegatesPureOpenAIFamilyAccount(t *testing.T) { + h := newCompositePoolMessagesHarness(t, []*service.Account{poolKimiAccount(42401, 41011, 0)}) + h.openAIUpstream.respond = func(compositePoolUpstreamCall, int) *http.Response { + return chatCompletionsOKResponse("kimi-k3", 11, 7) + } + + c, rec := h.newRequest(t, "/v1/chat/completions", poolChatCompletionsBody(), service.PlatformAnthropic, service.PlatformKimi) + h.handler.ChatCompletions(c) + + require.Equal(t, http.StatusOK, rec.Code) + require.Equal(t, "hi from kimi-k3", gjson.GetBytes(rec.Body.Bytes(), "choices.0.message.content").String(), + "同族 CC 入站零转换,响应为 Chat Completions 格式") + require.Equal(t, int64(11), gjson.GetBytes(rec.Body.Bytes(), "usage.prompt_tokens").Int()) + + calls := h.openAIUpstream.snapshot() + require.Len(t, calls, 1) + require.True(t, strings.HasSuffix(calls[0].Path, "/chat/completions"), "upstream path=%s", calls[0].Path) + require.Contains(t, string(calls[0].Body), `"model":"kimi-k3"`, "账号级 model_mapping 必须生效") + require.Contains(t, calls[0].Authorization, "kimi-key") + require.Empty(t, h.gwUpstream.snapshot(), "纯 OpenAI 族账号不得走 generic 转换链") + + logs := h.usageRepo.snapshot() + require.Len(t, logs, 1) + require.Equal(t, 11, logs[0].InputTokens) + require.Equal(t, 7, logs[0].OutputTokens) + require.EqualValues(t, 42401, logs[0].AccountID) + require.Equal(t, "my-model", logs[0].Model) + require.NotNil(t, logs[0].UpstreamModel) + require.Equal(t, "kimi-k3", *logs[0].UpstreamModel) +} + +// 池选中 adaptive 多协议账号:CC 入站由 OpenAI CC 链直转供应商原生 CC 端点 +// (入站同族优先,零转换;与其在纯 OpenAI 族池中的行为一致),不走 CC→Anthropic +// 既有转换链。 +func TestCompositePoolChatCompletionsAdaptiveAccountDelegatesNativeCC(t *testing.T) { + h := newCompositePoolMessagesHarness(t, []*service.Account{poolAdaptiveKimiAccount(42451, 41011, 0)}) + h.openAIUpstream.respond = func(compositePoolUpstreamCall, int) *http.Response { + return chatCompletionsOKResponse("claude-sonnet-4-5", 9, 4) + } + + c, rec := h.newRequest(t, "/v1/chat/completions", poolChatCompletionsBody(), service.PlatformAnthropic, service.PlatformKimi) + h.handler.ChatCompletions(c) + + require.Equal(t, http.StatusOK, rec.Code) + require.Equal(t, int64(9), gjson.GetBytes(rec.Body.Bytes(), "usage.prompt_tokens").Int()) + + calls := h.openAIUpstream.snapshot() + require.Len(t, calls, 1) + require.True(t, strings.HasSuffix(calls[0].Path, "/chat/completions"), "upstream path=%s", calls[0].Path) + require.Empty(t, h.gwUpstream.snapshot(), "adaptive 账号 CC 入站走原生 CC,不经 generic 转换链") + + logs := h.usageRepo.snapshot() + require.Len(t, logs, 1) + require.Equal(t, 9, logs[0].InputTokens) + require.Equal(t, 4, logs[0].OutputTokens) + require.EqualValues(t, 42451, logs[0].AccountID) +} + +// 池选中 anthropic 原生账号:CC 入站走既有 generic CC→Anthropic 转换链(假上游 +// 收到 {base}/v1/messages),不委派 OpenAI 链。 +func TestCompositePoolChatCompletionsAnthropicAccountUsesGenericConversion(t *testing.T) { + h := newCompositePoolMessagesHarness(t, []*service.Account{poolAnthropicAccount(42501, 41011, 0)}) + h.gwUpstream.respond = func(compositePoolUpstreamCall, int) *http.Response { + return anthropicMessagesSSEStreamResponse() + } + + c, rec := h.newRequest(t, "/v1/chat/completions", poolChatCompletionsBody(), service.PlatformAnthropic, service.PlatformKimi) + h.handler.ChatCompletions(c) + + require.Equal(t, http.StatusOK, rec.Code, rec.Body.String()) + require.Equal(t, int64(12), gjson.GetBytes(rec.Body.Bytes(), "usage.prompt_tokens").Int()) + + calls := h.gwUpstream.snapshot() + require.Len(t, calls, 1) + require.True(t, strings.HasSuffix(calls[0].Path, "/v1/messages"), "upstream path=%s", calls[0].Path) + require.Empty(t, h.openAIUpstream.snapshot(), "anthropic 账号不得委派 OpenAI 链") + + logs := h.usageRepo.snapshot() + require.Len(t, logs, 1) + require.Equal(t, 12, logs[0].InputTokens) + require.Equal(t, 5, logs[0].OutputTokens) +} + +// CC 委派链返回 failover 错误:走既有 failover 语义换号重选,改用 anthropic +// 原生账号的 generic 转换链完成请求。 +func TestCompositePoolChatCompletionsDelegationFailoverSwitchesAccount(t *testing.T) { + h := newCompositePoolMessagesHarness(t, []*service.Account{ + poolKimiAccount(42601, 41011, 0), + poolAnthropicAccount(42602, 41011, 5), + }) + h.gwUpstream.respond = func(compositePoolUpstreamCall, int) *http.Response { + return anthropicMessagesSSEStreamResponse() + } + // kimi 假上游默认回 500(respond 为 nil 时的兜底响应即 500)。 + + c, rec := h.newRequest(t, "/v1/chat/completions", poolChatCompletionsBody(), service.PlatformAnthropic, service.PlatformKimi) + h.handler.ChatCompletions(c) + + require.Equal(t, http.StatusOK, rec.Code) + require.Equal(t, int64(12), gjson.GetBytes(rec.Body.Bytes(), "usage.prompt_tokens").Int(), + "failover 后应由 anthropic 账号的 generic 转换链完成请求") + + require.Len(t, h.openAIUpstream.snapshot(), 1) + require.Len(t, h.gwUpstream.snapshot(), 1) + require.True(t, strings.HasSuffix(h.gwUpstream.snapshot()[0].Path, "/v1/messages")) + + selected, ok := c.Get(opsAccountIDKey) + require.True(t, ok) + require.EqualValues(t, 42602, selected, "ops 记录最终选中的 anthropic 账号") + + logs := h.usageRepo.snapshot() + require.Len(t, logs, 1) + require.EqualValues(t, 42602, logs[0].AccountID) +} + +// B2 端点委派分发谓词与结果适配器(图片计费字段)的纯函数契约。 +func TestCompositePoolTextEndpointDelegationPredicates(t *testing.T) { + // Responses 入站:纯 OpenAI 族与原生 Responses 账号 → 委派。 + require.True(t, compositePoolAccountDelegatesResponsesToOpenAI(poolKimiAccount(1, 1, 0))) + require.True(t, compositePoolAccountDelegatesResponsesToOpenAI(&service.Account{Platform: service.PlatformOpenAI})) + require.True(t, compositePoolAccountDelegatesResponsesToOpenAI(&service.Account{Platform: service.PlatformGrok})) + require.True(t, compositePoolAccountDelegatesResponsesToOpenAI(poolKimiResponsesAccount(2, 1, 0))) + // 有原生 Responses 端点的 adaptive 账号同样委派(入站同族零转换)。 + require.True(t, compositePoolAccountDelegatesResponsesToOpenAI(poolAdaptiveKimiAccount(3, 1, 0))) + + // anthropic 原生 / gemini / antigravity / 无原生 Responses 的 adaptive → 既有转换。 + require.False(t, compositePoolAccountDelegatesResponsesToOpenAI(poolAnthropicAccount(4, 1, 0))) + require.False(t, compositePoolAccountDelegatesResponsesToOpenAI(&service.Account{Platform: service.PlatformGemini})) + require.False(t, compositePoolAccountDelegatesResponsesToOpenAI(&service.Account{Platform: service.PlatformAntigravity})) + require.False(t, compositePoolAccountDelegatesResponsesToOpenAI(poolZhipuAdaptiveAccount(5, 1, 0))) + require.False(t, compositePoolAccountDelegatesResponsesToOpenAI(nil)) + + // CC 入站:OpenAI 兼容族(含 adaptive,链内直转原生 CC)→ 委派。 + require.True(t, compositePoolAccountDelegatesChatCompletionsToOpenAI(poolKimiAccount(6, 1, 0))) + require.True(t, compositePoolAccountDelegatesChatCompletionsToOpenAI(poolAdaptiveKimiAccount(7, 1, 0))) + require.True(t, compositePoolAccountDelegatesChatCompletionsToOpenAI(poolZhipuAdaptiveAccount(8, 1, 0))) + require.True(t, compositePoolAccountDelegatesChatCompletionsToOpenAI(&service.Account{Platform: service.PlatformGrok})) + + // anthropic-协议 / gemini / antigravity → 既有转换。 + require.False(t, compositePoolAccountDelegatesChatCompletionsToOpenAI(poolAnthropicAccount(9, 1, 0))) + require.False(t, compositePoolAccountDelegatesChatCompletionsToOpenAI(&service.Account{Platform: service.PlatformGemini})) + require.False(t, compositePoolAccountDelegatesChatCompletionsToOpenAI(&service.Account{Platform: service.PlatformAntigravity})) + require.False(t, compositePoolAccountDelegatesChatCompletionsToOpenAI(nil)) + + // 结果适配:图片/搜索计费字段逐字段映射,nil 安全。 + require.Nil(t, adaptOpenAIForwardResultToForwardResult(nil)) + adapted := adaptOpenAIForwardResultToForwardResult(&service.OpenAIForwardResult{ + ImageCount: 2, + ImageSize: "2K", + ImageInputSize: "1K", + ImageOutputSize: "2K", + ImageOutputSizes: []string{"2K", "2K"}, + ImageSizeSource: "response", + ImageSizeBreakdown: map[string]int{"2K": 2}, + SearchCount: 3, + }) + require.Equal(t, 2, adapted.ImageCount) + require.Equal(t, "2K", adapted.ImageSize) + require.Equal(t, "1K", adapted.ImageInputSize) + require.Equal(t, "2K", adapted.ImageOutputSize) + require.Equal(t, []string{"2K", "2K"}, adapted.ImageOutputSizes) + require.Equal(t, "response", adapted.ImageSizeSource) + require.Equal(t, map[string]int{"2K": 2}, adapted.ImageSizeBreakdown) + require.Equal(t, 3, adapted.SearchCount) +} + +// openAIResponsesOKResponse 返回一份带 usage 的非流式 Responses 成功响应。 +func openAIResponsesOKResponse(model string, inputTokens, outputTokens int) *http.Response { + body := fmt.Sprintf( + `{"id":"resp_pool","object":"response","created_at":1,"status":"completed","model":%q,"output":[],"usage":{"input_tokens":%d,"output_tokens":%d}}`, + model, inputTokens, outputTokens) + return &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{"application/json"}, "X-Request-Id": []string{"req-resp-pool"}}, + Body: io.NopCloser(strings.NewReader(body)), + } +} diff --git a/backend/internal/handler/composite_pool_attempt_policy.go b/backend/internal/handler/composite_pool_attempt_policy.go index c75e860856..4fc612f43a 100644 --- a/backend/internal/handler/composite_pool_attempt_policy.go +++ b/backend/internal/handler/composite_pool_attempt_policy.go @@ -217,3 +217,96 @@ func respondCompositePoolAttemptPolicyFailure(c *gin.Context, failure compositeP } write(c, http.StatusServiceUnavailable, "api_error", "Service temporarily unavailable") } + +// compositePoolAccountDelegatesToOpenAI 报告池请求选中的账号是否需要委派 OpenAI +// 网关的 /v1/messages 兼容链转发。generic(Anthropic 原生)转发路径覆盖: +// anthropic 原生、gemini / antigravity 既有调度平台,以及能解析出 Anthropic 协议 +// 上游 base 的 anthropic-协议 / adaptive 多协议账号(service 层已按账号协议化 +// 上游 base);其余纯 OpenAI 族账号(openai/grok/国产供应商/OpenCode Go,无 +// Anthropic 协议能力)由委派链完成协议转换。仅池激活时调用。 +func compositePoolAccountDelegatesToOpenAI(account *service.Account) bool { + if account == nil { + return false + } + switch account.Platform { + case service.PlatformAnthropic, service.PlatformGemini, service.PlatformAntigravity: + return false + } + if account.IsAnthropicProtocol() || account.IsAdaptiveAPIProtocol() { + // 多协议账号走既有 generic Forward(servable 门已保证 Anthropic 协议 + // base 非空);不应停留在 Chat Completions 协议上被误委派。 + return false + } + return true +} + +// compositePoolAccountDelegatesResponsesToOpenAI 报告池请求选中的账号在入站 +// /v1/responses 时是否委派 OpenAI 网关 Responses 链(OpenAIGatewayService.Forward) +// 转发。入站同族优先(零或近零转换):纯 OpenAI 族账号(openai/grok/国产 CC 固定/ +// OpenCode Go)与具备原生 Responses 端点的国产账号(UsesNativeCNResponses,含 +// fixed responses 与 adaptive)交该链按账号协议直连或轻量转换;anthropic 原生 / +// gemini / antigravity / anthropic-协议 / 无原生 Responses 的 adaptive 账号走 +// 既有 generic Responses→Anthropic 转换。仅池激活时调用。 +func compositePoolAccountDelegatesResponsesToOpenAI(account *service.Account) bool { + if account == nil { + return false + } + return compositePoolAccountDelegatesToOpenAI(account) || account.UsesNativeCNResponses() +} + +// compositePoolAccountDelegatesChatCompletionsToOpenAI 报告池请求选中的账号在入站 +// /v1/chat/completions 时是否委派 OpenAI 网关 CC 链(OpenAIGatewayService. +// ForwardAsChatCompletions)转发。入站同族优先(零转换):OpenAI 兼容族账号交该链, +// 其中 adaptive 国产账号由该链直转供应商原生 CC 端点(forwardAsChatCompletions 的 +// adaptive 分支,与其在纯 OpenAI 族池中的行为一致);anthropic-协议 / gemini / +// antigravity 走既有 generic CC→Anthropic 转换。仅池激活时调用。 +func compositePoolAccountDelegatesChatCompletionsToOpenAI(account *service.Account) bool { + if account == nil { + return false + } + return account.IsOpenAICompatible() && !account.IsAnthropicProtocol() +} + +// adaptOpenAIForwardResultToForwardResult 把委派链(OpenAIGatewayService 转发方法) +// 的转发结果适配进 generic 计费链的 ForwardResult:usage token 计数、模型、请求 +// 元数据与图片/搜索计费字段逐字段映射,经既有 usage 提交流入账,计费不丢。 +// nil 安全;错误路径携带的部分结果(流中断排水 usage)同样适配。 +func adaptOpenAIForwardResultToForwardResult(src *service.OpenAIForwardResult) *service.ForwardResult { + if src == nil { + return nil + } + return &service.ForwardResult{ + RequestID: src.RequestID, + UpstreamHeaders: src.UpstreamHeaders, + Usage: service.ClaudeUsage{ + InputTokens: src.Usage.InputTokens, + OutputTokens: src.Usage.OutputTokens, + CacheCreationInputTokens: src.Usage.CacheCreationInputTokens, + CacheReadInputTokens: src.Usage.CacheReadInputTokens, + ImageOutputTokens: src.Usage.ImageOutputTokens, + }, + Model: src.Model, + UpstreamModel: src.UpstreamModel, + UpstreamResponseModel: src.UpstreamResponseModel, + UpstreamResponseModelConflict: src.UpstreamResponseModelConflict, + UpstreamResponseServiceTier: src.UpstreamResponseServiceTier, + Stream: src.Stream, + Duration: src.Duration, + FirstTokenMs: src.FirstTokenMs, + ClientDisconnect: src.ClientDisconnect, + ReasoningEffort: src.ReasoningEffort, + RequestedReasoningEffort: src.RequestedReasoningEffort, + ServiceTier: src.ServiceTier, + SearchCount: src.SearchCount, + AudioUsage: src.AudioUsage, + // 生图计费字段:/v1/responses 是 token+图片混合计费端点,委派链产出的 + // 图片尺寸/数量必须随 usage 进入 generic 计费链(B2 扩展)。 + ImageCount: src.ImageCount, + ImageSize: src.ImageSize, + ImageInputSize: src.ImageInputSize, + ImageOutputSize: src.ImageOutputSize, + ImageOutputSizes: src.ImageOutputSizes, + ImageSizeSource: src.ImageSizeSource, + ImageSizeBreakdown: src.ImageSizeBreakdown, + } +} diff --git a/backend/internal/handler/gateway_handler.go b/backend/internal/handler/gateway_handler.go index beb9400d11..8bb38292a2 100644 --- a/backend/internal/handler/gateway_handler.go +++ b/backend/internal/handler/gateway_handler.go @@ -637,6 +637,12 @@ func (h *GatewayHandler) Messages(c *gin.Context) { } fallbackUsed := false + // composite 账号池请求状态(B1:generic Messages 循环池化)。池激活判定与 + // generic 调度器共用同一谓词(ctx 携带候选池且无 resolved 平台);非池请求 + // poolDenials 恒为空、attempt 策略不生效,整条路径零变化。 + isPoolRequest := service.GenericCompositePoolActive(c.Request.Context()) + poolDenials := newCompositePoolPlatformDenials() + // 单账号分组提前设置 SingleAccountRetry 标记,让 Service 层首次 503 就不设模型限流标记。 // 避免单账号分组收到 503 (MODEL_CAPACITY_EXHAUSTED) 时设 29s 限流,导致后续请求连续快速失败。 if h.gatewayService.IsSingleAntigravityAccountGroup(c.Request.Context(), currentAPIKey.GroupID) { @@ -679,7 +685,16 @@ func (h *GatewayHandler) Messages(c *gin.Context) { zap.Bool("has_bound_session", hasBoundSession), zap.Int("failed_account_count", len(fs.FailedAccountIDs)), ) - selection, err := h.gatewayService.SelectAccountWithLoadAwareness(c.Request.Context(), currentAPIKey.GroupID, sessionKey, reqModel, fs.FailedAccountIDs, parsedReq.MetadataUserID, subject.UserID) + // 池请求把业务限制 deny 过的平台按 deniedPlatforms 整平台 mask 后重选 + //(候选池 immutable,mask 只叠加在当前请求 ctx 之上);无 deny 时 + // 返回原 ctx,非池请求不经此分支,选号 ctx 与原行为一致。 + selectCtx := c.Request.Context() + if isPoolRequest { + if maskedCtx, ok := compositePoolSelectionRetryContext(selectCtx, poolDenials); ok { + selectCtx = maskedCtx + } + } + selection, err := h.gatewayService.SelectAccountWithLoadAwareness(selectCtx, currentAPIKey.GroupID, sessionKey, reqModel, fs.FailedAccountIDs, parsedReq.MetadataUserID, subject.UserID) if err != nil { if failoverClientGone(c) { reqLog.Info("gateway.account_select_aborted_client_disconnected", zap.Error(err)) @@ -736,6 +751,36 @@ func (h *GatewayHandler) Messages(c *gin.Context) { zap.Bool("sticky_honored", sessionBoundAccountID > 0 && sessionBoundAccountID == account.ID), ) + // composite 账号池 per-attempt 平台策略:对实际选中平台补做 user×platform + // 配额预检与渠道映射/限制(准入 CheckBillingEligibility 时池没有 resolved + // 平台、这两个维度被跳过;不得只后扣不预检)。检查为纯读,不写 RPM/计数, + // 放在槽位获取前:deny 不占并发槽。generic 循环无 previous_response_id, + // 无 pinned 分支;deny 记入 poolDenials 后按 masked 候选池整平台重选, + // 候选全部被业务限制时按原语义终止,不误报 model unsupported。 + attemptPolicy := compositePoolAttemptPolicy{AttemptCtx: c.Request.Context(), Mapping: channelMapping} + isPoolAttempt := false + if isPoolRequest && compositePoolAttemptPolicyApplies(c, apiKey) { + attemptPolicy = evaluateCompositePoolAttemptPolicy( + c.Request.Context(), h.billingCacheService, h.openAIGatewayService, apiKey, subscription, account, reqModel, false) + isPoolAttempt = true + if attemptPolicy.Failure.denied() { + releaseCompositePoolSelection(selection) + // 选号链可能已为该账号注册会话槽:排除前释放,镜像 profit-veto 分支。 + h.gatewayService.ReleaseAccountSession(context.Background(), account, sessionKey) + poolDenials.deny(account.Platform) + fs.FailedAccountIDs[account.ID] = struct{}{} + // 候选全部被业务限制:按 deny 原因明确终止(后续重选不再尝试)。 + if _, ok := compositePoolSelectionRetryContext(c.Request.Context(), poolDenials); !ok { + streamAwareWrite := func(cc *gin.Context, status int, code, message string) { + h.handleStreamingAwareError(cc, status, code, message, streamStarted) + } + respondCompositePoolAttemptPolicyFailure(c, attemptPolicy.Failure, streamAwareWrite) + return + } + continue + } + } + // 检查请求拦截(预热请求、SUGGESTION MODE等) if account.IsInterceptWarmupEnabled() { interceptType := detectInterceptType(body, reqModel, parsedReq.MaxTokens, isClaudeCodeClient) @@ -890,9 +935,15 @@ func (h *GatewayHandler) Messages(c *gin.Context) { // ===== 用户消息串行队列 END ===== // 渠道模型映射只作用于本次账号尝试,避免 failover 后污染原始 ParsedRequest。 - if channelMapping.Mapped { - attemptParsedReq.Model = channelMapping.MappedModel - if err := attemptParsedReq.ReplaceBody(h.gatewayService.ReplaceModelInBody(attemptParsedReq.Body.Bytes(), channelMapping.MappedModel)); err != nil { + // 池请求按选中平台的渠道映射(attempt 策略产出,platform-scoped)派生, + // 不用 composite 作用域的请求级映射(无 resolved 平台时跨平台行匹配不可靠)。 + attemptChannelMapping := channelMapping + if isPoolAttempt { + attemptChannelMapping = attemptPolicy.Mapping + } + if attemptChannelMapping.Mapped { + attemptParsedReq.Model = attemptChannelMapping.MappedModel + if err := attemptParsedReq.ReplaceBody(h.gatewayService.ReplaceModelInBody(attemptParsedReq.Body.Bytes(), attemptChannelMapping.MappedModel)); err != nil { h.errorResponse(c, http.StatusBadRequest, "invalid_request_error", "Failed to parse request body") return } @@ -914,10 +965,26 @@ func (h *GatewayHandler) Messages(c *gin.Context) { if fs.ForceCacheBilling { requestCtx = service.WithForceCacheBilling(requestCtx) } + // 池请求的 attempt 局部 ctx 携带选中平台(不写回 c.Request):forward 内的 + // 渠道定价作用域与计费 QuotaPlatform 跟随实际平台,对齐 OpenAI 池 attempt 语义。 + if isPoolRequest { + requestCtx = compositePoolAttemptContext(requestCtx, account) + } // 记录 Forward 前已写入字节数,Forward 后若增加则说明 SSE 内容已发,禁止 failover writerSizeBeforeForward := c.Writer.Size() if account.Platform == service.PlatformAntigravity && account.Type != service.AccountTypeAPIKey { result, err = h.antigravityGatewayService.Forward(requestCtx, c, account, attemptBody, hasBoundSession) + } else if isPoolRequest && compositePoolAccountDelegatesToOpenAI(account) { + // 纯 OpenAI 族账号(无 Anthropic 协议能力)在池激活时委派 OpenAI 网关的 + // /v1/messages 兼容链:Anthropic → Responses/CC 协议转换、响应写回与 + // failover 错误信封都由该链完成,错误信封已是 Anthropic 风格,不再二次包装。 + // promptCacheKey 传 ""(内部按 cache_control / metadata 会话种子兜底); + // defaultMappedModel 与 OpenAI handler Messages 路径同源。 + openAIResult, delegateErr := h.openAIGatewayService.ForwardAsAnthropic( + requestCtx, c, account, attemptBody, "", + strings.TrimSpace(resolveOpenAIMessagesDispatchMappedModel(c, apiKey, reqModel))) + result = adaptOpenAIForwardResultToForwardResult(openAIResult) + err = delegateErr } else { result, err = h.gatewayService.Forward(requestCtx, c, account, attemptParsedReq) } @@ -960,7 +1027,12 @@ func (h *GatewayHandler) Messages(c *gin.Context) { // 使用量记录通过有界 worker 池提交,避免请求热路径创建无界 goroutine。 // ForceCacheBilling 提前拍成标量,避免 worker 闭包保活 failover 状态里的响应体。 forceCacheBilling := fs.ForceCacheBilling + // 池请求按选中平台计量 user×platform 配额(attempt ctx 携带 resolved + // 平台);非池保持准入语义不变。 quotaPlatform := service.QuotaPlatform(c.Request.Context(), currentAPIKey) + if isPoolAttempt { + quotaPlatform = service.QuotaPlatform(attemptPolicy.AttemptCtx, currentAPIKey) + } sessionID := service.ExtractClientSessionID(c) h.submitUsageRecordTask(c.Request.Context(), func(ctx context.Context) { if err := h.gatewayService.RecordUsage(ctx, &service.RecordUsageInput{ @@ -979,7 +1051,7 @@ func (h *GatewayHandler) Messages(c *gin.Context) { RequestPayloadHash: requestPayloadHash, ForceCacheBilling: forceCacheBilling, APIKeyService: h.apiKeyService, - ChannelUsageFields: clientRequestedUsageFields(c, channelMapping, reqModel, result.UpstreamModel), + ChannelUsageFields: clientRequestedUsageFields(c, attemptChannelMapping, reqModel, result.UpstreamModel), }); err != nil { logger.L().With( zap.String("component", "handler.gateway.messages"), @@ -2220,16 +2292,36 @@ func (h *GatewayHandler) CountTokens(c *gin.Context) { } sessionHash := h.gatewayService.GenerateSessionHash(parsedReq) - // 选择支持该模型的账号 - account, err := h.gatewayService.SelectAccountForModel(c.Request.Context(), apiKey.GroupID, sessionHash, parsedReq.Model) - if err != nil { - reqLog.Warn("gateway.count_tokens_select_account_failed", zap.Error(err)) - cls := classifyNoAccountErrorFromGin(c, h.gatewayService, apiKey, parsedReq.Model, parsedReq.Model, service.PlatformAnthropic) - if !cls.ModelNotFound { - markOpsRoutingCapacityLimitedIfNoAvailable(c, err) + // 选择支持该模型的账号。池请求(B1:generic CountTokens 最小池化)选中纯 + // OpenAI 族账号时该账号不可计数:跳过(记入排除集重选)而不是对 + // /v1/messages/count_tokens 报 500;可计数账号与单目标请求按既有语义直接转发。 + isPoolRequest := service.GenericCompositePoolActive(c.Request.Context()) + var excludedAccountIDs map[int64]struct{} + var account *service.Account + for { + account, err = h.gatewayService.SelectAccountForModelWithExclusions(c.Request.Context(), apiKey.GroupID, sessionHash, parsedReq.Model, excludedAccountIDs) + if err != nil { + reqLog.Warn("gateway.count_tokens_select_account_failed", zap.Error(err)) + cls := classifyNoAccountErrorFromGin(c, h.gatewayService, apiKey, parsedReq.Model, parsedReq.Model, service.PlatformAnthropic) + if !cls.ModelNotFound { + markOpsRoutingCapacityLimitedIfNoAvailable(c, err) + } + h.errorResponse(c, cls.Status, cls.ErrType, cls.Message) + return } - h.errorResponse(c, cls.Status, cls.ErrType, cls.Message) - return + if !isPoolRequest || service.GenericCompositePoolCountableAccount(account) { + break + } + reqLog.Info("gateway.count_tokens_pool_skip_uncountable_account", + zap.Int64("account_id", account.ID), + zap.String("account_platform", account.Platform), + ) + // 选号链可能已为该账号注册会话槽:排除前释放,再用排除集重选。 + h.gatewayService.ReleaseAccountSession(context.Background(), account, sessionHash) + if excludedAccountIDs == nil { + excludedAccountIDs = make(map[int64]struct{}) + } + excludedAccountIDs[account.ID] = struct{}{} } setOpsSelectedAccount(c, account.ID, account.Platform) diff --git a/backend/internal/handler/gateway_handler_chat_completions.go b/backend/internal/handler/gateway_handler_chat_completions.go index 561ed1bca0..60ce23f38e 100644 --- a/backend/internal/handler/gateway_handler_chat_completions.go +++ b/backend/internal/handler/gateway_handler_chat_completions.go @@ -180,6 +180,17 @@ func (h *GatewayHandler) ChatCompletions(c *gin.Context) { if groupPlatform == service.PlatformGemini && selectionSessionHash != "" { selectionSessionHash = "gemini:" + selectionSessionHash } + // composite 账号池请求状态(B2:generic CC 循环池化)。池激活判定与 generic + // 调度器共用同一谓词(ctx 携带候选池且无 resolved 平台);非池请求 poolDenials + // 恒为空、attempt 策略与委派分支不生效,整条路径零变化。 + isPoolRequest := service.GenericCompositePoolActive(c.Request.Context()) + poolDenials := newCompositePoolPlatformDenials() + // 委派 CC 链的 promptCacheKey 语义对齐 OpenAI handler CC 路径(headers → + // prompt_cache_key 提取,仅池激活时计算,非池请求不新增解析)。 + var poolPromptCacheKey string + if isPoolRequest { + poolPromptCacheKey = h.openAIGatewayService.ExtractSessionID(c, body) + } // 3. Account selection + failover loop fs := NewFailoverState(h.maxAccountSwitches, false) if groupPlatform == service.PlatformGemini { @@ -190,7 +201,16 @@ func (h *GatewayHandler) ChatCompletions(c *gin.Context) { if failoverClientGone(c) { return } - selection, err := h.gatewayService.SelectAccountWithLoadAwareness(c.Request.Context(), apiKey.GroupID, selectionSessionHash, reqModel, fs.FailedAccountIDs, "", int64(0)) + // 池请求把业务限制 deny 过的平台按 deniedPlatforms 整平台 mask 后重选 + //(候选池 immutable,mask 只叠加在当前请求 ctx 之上);无 deny 时 + // 返回原 ctx,非池请求不经此分支,选号 ctx 与原行为一致。 + selectCtx := c.Request.Context() + if isPoolRequest { + if maskedCtx, ok := compositePoolSelectionRetryContext(selectCtx, poolDenials); ok { + selectCtx = maskedCtx + } + } + selection, err := h.gatewayService.SelectAccountWithLoadAwareness(selectCtx, apiKey.GroupID, selectionSessionHash, reqModel, fs.FailedAccountIDs, "", int64(0)) if err != nil { if failoverClientGone(c) { reqLog.Info("gateway.cc.account_select_aborted_client_disconnected", zap.Error(err)) @@ -228,6 +248,41 @@ func (h *GatewayHandler) ChatCompletions(c *gin.Context) { account := selection.Account setOpsSelectedAccount(c, account.ID, account.Platform) + // composite 账号池 per-attempt 平台策略:对实际选中平台补做 user×platform + // 配额预检与渠道映射/限制(准入 CheckBillingEligibility 时池没有 resolved + // 平台、这两个维度被跳过;不得只后扣不预检)。检查为纯读,不写 RPM/计数, + // 放在槽位获取前:deny 不占并发槽。CC 循环无 previous_response_id 状态, + // 无 pinned 分支;deny 记入 poolDenials 后按 masked 候选池整平台重选, + // 候选全部被业务限制时按原语义终止,不误报 model unsupported。 + attemptPolicy := compositePoolAttemptPolicy{AttemptCtx: c.Request.Context(), Mapping: channelMapping} + isPoolAttempt := false + if isPoolRequest && compositePoolAttemptPolicyApplies(c, apiKey) { + attemptPolicy = evaluateCompositePoolAttemptPolicy( + c.Request.Context(), h.billingCacheService, h.openAIGatewayService, apiKey, subscription, account, reqModel, false) + isPoolAttempt = true + if attemptPolicy.Failure.denied() { + releaseCompositePoolSelection(selection) + // 选号链可能已为该账号注册会话槽(键与选号一致):排除前释放 + //(镜像 Messages 池分支)。 + h.gatewayService.ReleaseAccountSession(context.Background(), account, selectionSessionHash) + poolDenials.deny(account.Platform) + fs.FailedAccountIDs[account.ID] = struct{}{} + // 候选全部被业务限制:按 deny 原因明确终止(后续重选不再尝试)。 + if _, ok := compositePoolSelectionRetryContext(c.Request.Context(), poolDenials); !ok { + streamAwareWrite := func(cc *gin.Context, status int, code, message string) { + if streamStarted { + h.handleStreamingAwareError(cc, status, code, message, true) + return + } + h.chatCompletionsErrorResponse(cc, status, code, message) + } + respondCompositePoolAttemptPolicyFailure(c, attemptPolicy.Failure, streamAwareWrite) + return + } + continue + } + } + // 4. Acquire account concurrency slot accountReleaseFunc := selection.ReleaseFunc if !selection.Acquired { @@ -284,12 +339,24 @@ func (h *GatewayHandler) ChatCompletions(c *gin.Context) { // 5. Forward request writerSizeBeforeForward := c.Writer.Size() + // 渠道模型映射只作用于本次账号尝试:池请求按选中平台的渠道映射(attempt + // 策略产出,platform-scoped)派生,非池保持请求级映射语义不变。 + attemptChannelMapping := channelMapping + if isPoolAttempt { + attemptChannelMapping = attemptPolicy.Mapping + } forwardBody := body - if channelMapping.Mapped { - forwardBody = h.gatewayService.ReplaceModelInBody(body, channelMapping.MappedModel) + if attemptChannelMapping.Mapped { + forwardBody = h.gatewayService.ReplaceModelInBody(body, attemptChannelMapping.MappedModel) } var result *service.ForwardResult setActualUpstreamEndpoint(c, "") + // 池请求的 attempt 局部 ctx 携带选中平台(不写回 c.Request):forward 内的 + // 渠道定价作用域与计费 QuotaPlatform 跟随实际平台,对齐 Messages 池 attempt 语义。 + attemptCtx := c.Request.Context() + if isPoolRequest { + attemptCtx = compositePoolAttemptContext(attemptCtx, account) + } if account.Platform == service.PlatformGemini { if h.geminiCompatService == nil { h.chatCompletionsErrorResponse(c, http.StatusBadGateway, "upstream_error", "Gemini compatibility service is not configured") @@ -298,7 +365,7 @@ func (h *GatewayHandler) ChatCompletions(c *gin.Context) { } return } - result, err = h.geminiCompatService.ForwardAsChatCompletions(c.Request.Context(), c, account, forwardBody) + result, err = h.geminiCompatService.ForwardAsChatCompletions(attemptCtx, c, account, forwardBody) } else if shouldUseAntigravityCompat(account) { if h.antigravityGatewayService == nil { h.chatCompletionsErrorResponse(c, http.StatusBadGateway, "upstream_error", "Antigravity compatibility service is not configured") @@ -308,9 +375,18 @@ func (h *GatewayHandler) ChatCompletions(c *gin.Context) { return } setActualUpstreamEndpoint(c, EndpointAntigravityGenerateContent) - result, err = h.antigravityGatewayService.ForwardAsChatCompletions(c.Request.Context(), c, account, forwardBody, parsedReq) + result, err = h.antigravityGatewayService.ForwardAsChatCompletions(attemptCtx, c, account, forwardBody, parsedReq) + } else if isPoolRequest && compositePoolAccountDelegatesChatCompletionsToOpenAI(account) { + // OpenAI 兼容族账号在池激活时委派 OpenAI 网关 CC 链:入站同族优先 + //(零转换,adaptive 账号由该链直转供应商原生 CC 端点),响应写回与 + // failover 错误信封都由该链完成,错误信封已是 OpenAI CC 风格,不再二次 + // 包装。defaultMappedModel 传 "",与 OpenAI handler CC 路径一致。 + openAIResult, delegateErr := h.openAIGatewayService.ForwardAsChatCompletions( + attemptCtx, c, account, forwardBody, poolPromptCacheKey, "") + result = adaptOpenAIForwardResultToForwardResult(openAIResult) + err = delegateErr } else { - result, err = h.gatewayService.ForwardAsChatCompletions(c.Request.Context(), c, account, forwardBody, parsedReq) + result, err = h.gatewayService.ForwardAsChatCompletions(attemptCtx, c, account, forwardBody, parsedReq) } if accountReleaseFunc != nil { @@ -358,6 +434,11 @@ func (h *GatewayHandler) ChatCompletions(c *gin.Context) { upstreamEndpoint := GetUpstreamEndpoint(c, account.Platform) quotaPlatform := service.QuotaPlatform(c.Request.Context(), apiKey) + // 池请求按选中平台计量 user×platform 配额(attempt ctx 携带 resolved + // 平台);非池保持准入语义不变。 + if isPoolAttempt { + quotaPlatform = service.QuotaPlatform(attemptPolicy.AttemptCtx, apiKey) + } sessionID := service.ExtractClientSessionID(c) stampForwardRequestedReasoningEffort(result, service.RequestedReasoningEffortFromContext(c.Request.Context())) h.submitUsageRecordTask(c.Request.Context(), func(ctx context.Context) { @@ -376,7 +457,7 @@ func (h *GatewayHandler) ChatCompletions(c *gin.Context) { RequestPayloadHash: requestPayloadHash, APIKeyService: h.apiKeyService, SessionID: sessionID, - ChannelUsageFields: clientRequestedUsageFields(c, channelMapping, reqModel, result.UpstreamModel), + ChannelUsageFields: clientRequestedUsageFields(c, attemptChannelMapping, reqModel, result.UpstreamModel), }); err != nil { reqLog.Error("gateway.cc.record_usage_failed", zap.Int64("account_id", account.ID), diff --git a/backend/internal/handler/gateway_handler_responses.go b/backend/internal/handler/gateway_handler_responses.go index 5ef6bace91..be11cf2d3e 100644 --- a/backend/internal/handler/gateway_handler_responses.go +++ b/backend/internal/handler/gateway_handler_responses.go @@ -180,6 +180,12 @@ func (h *GatewayHandler) Responses(c *gin.Context) { } sessionHash := h.gatewayService.GenerateSessionHash(parsedReq) + // composite 账号池请求状态(B2:generic Responses 循环池化)。池激活判定与 + // generic 调度器共用同一谓词(ctx 携带候选池且无 resolved 平台);非池请求 + // poolDenials 恒为空、attempt 策略与委派分支不生效,整条路径零变化。 + isPoolRequest := service.GenericCompositePoolActive(requestCtx) + poolDenials := newCompositePoolPlatformDenials() + // 3. Account selection + failover loop fs := NewFailoverState(h.maxAccountSwitches, false) @@ -187,7 +193,16 @@ func (h *GatewayHandler) Responses(c *gin.Context) { if failoverClientGone(c) { return } - selection, err := h.gatewayService.SelectAccountWithLoadAwareness(requestCtx, apiKey.GroupID, sessionHash, reqModel, fs.FailedAccountIDs, "", int64(0)) + // 池请求把业务限制 deny 过的平台按 deniedPlatforms 整平台 mask 后重选 + //(候选池 immutable,mask 只叠加在当前请求 ctx 之上);无 deny 时 + // 返回原 ctx,非池请求不经此分支,选号 ctx 与原行为一致。 + selectCtx := requestCtx + if isPoolRequest { + if maskedCtx, ok := compositePoolSelectionRetryContext(selectCtx, poolDenials); ok { + selectCtx = maskedCtx + } + } + selection, err := h.gatewayService.SelectAccountWithLoadAwareness(selectCtx, apiKey.GroupID, sessionHash, reqModel, fs.FailedAccountIDs, "", int64(0)) if err != nil { if failoverClientGone(c) { reqLog.Info("gateway.responses.account_select_aborted_client_disconnected", zap.Error(err)) @@ -225,6 +240,41 @@ func (h *GatewayHandler) Responses(c *gin.Context) { account := selection.Account setOpsSelectedAccount(c, account.ID, account.Platform) + // composite 账号池 per-attempt 平台策略:对实际选中平台补做 user×platform + // 配额预检与渠道映射/限制(准入 CheckBillingEligibility 时池没有 resolved + // 平台、这两个维度被跳过;不得只后扣不预检)。检查为纯读,不写 RPM/计数, + // 放在槽位获取前:deny 不占并发槽。generic Responses 循环无 + // previous_response_id,无 pinned 分支;deny 记入 poolDenials 后按 masked + // 候选池整平台重选,候选全部被业务限制时按原语义终止,不误报 model + // unsupported。 + attemptPolicy := compositePoolAttemptPolicy{AttemptCtx: requestCtx, Mapping: channelMapping} + isPoolAttempt := false + if isPoolRequest && compositePoolAttemptPolicyApplies(c, apiKey) { + attemptPolicy = evaluateCompositePoolAttemptPolicy( + requestCtx, h.billingCacheService, h.openAIGatewayService, apiKey, subscription, account, reqModel, false) + isPoolAttempt = true + if attemptPolicy.Failure.denied() { + releaseCompositePoolSelection(selection) + // 选号链可能已为该账号注册会话槽:排除前释放(镜像 Messages 池分支)。 + h.gatewayService.ReleaseAccountSession(context.Background(), account, sessionHash) + poolDenials.deny(account.Platform) + fs.FailedAccountIDs[account.ID] = struct{}{} + // 候选全部被业务限制:按 deny 原因明确终止(后续重选不再尝试)。 + if _, ok := compositePoolSelectionRetryContext(requestCtx, poolDenials); !ok { + streamAwareWrite := func(cc *gin.Context, status int, code, message string) { + if streamStarted { + h.handleStreamingAwareError(cc, status, code, message, true) + return + } + h.responsesErrorResponse(cc, status, code, message) + } + respondCompositePoolAttemptPolicyFailure(c, attemptPolicy.Failure, streamAwareWrite) + return + } + continue + } + } + // 4. Acquire account concurrency slot accountReleaseFunc := selection.ReleaseFunc if !selection.Acquired { @@ -275,12 +325,25 @@ func (h *GatewayHandler) Responses(c *gin.Context) { // 5. Forward request writerSizeBeforeForward := c.Writer.Size() + // 渠道模型映射只作用于本次账号尝试:池请求按选中平台的渠道映射(attempt + // 策略产出,platform-scoped)派生,非池保持请求级映射语义不变。 + attemptChannelMapping := channelMapping + if isPoolAttempt { + attemptChannelMapping = attemptPolicy.Mapping + } forwardBody := body - if channelMapping.Mapped { - forwardBody = h.gatewayService.ReplaceModelInBody(body, channelMapping.MappedModel) + if attemptChannelMapping.Mapped { + forwardBody = h.gatewayService.ReplaceModelInBody(body, attemptChannelMapping.MappedModel) } var result *service.ForwardResult setActualUpstreamEndpoint(c, "") + // 池请求的 attempt 局部 ctx 携带选中平台(不写回 requestCtx,否则下一轮 + // 选号会被 resolved 平台截断池语义):forward 内的渠道定价作用域与计费 + // QuotaPlatform 跟随实际平台,对齐 Messages 池 attempt 语义。 + attemptCtx := requestCtx + if isPoolRequest { + attemptCtx = compositePoolAttemptContext(attemptCtx, account) + } if shouldUseAntigravityCompat(account) { if h.antigravityGatewayService == nil { h.responsesErrorResponse(c, http.StatusBadGateway, "upstream_error", "Antigravity compatibility service is not configured") @@ -290,9 +353,18 @@ func (h *GatewayHandler) Responses(c *gin.Context) { return } setActualUpstreamEndpoint(c, EndpointAntigravityGenerateContent) - result, err = h.antigravityGatewayService.ForwardAsResponses(requestCtx, c, account, forwardBody, parsedReq) + result, err = h.antigravityGatewayService.ForwardAsResponses(attemptCtx, c, account, forwardBody, parsedReq) + } else if isPoolRequest && compositePoolAccountDelegatesResponsesToOpenAI(account) { + // 纯 OpenAI 族 / 原生 Responses 账号在池激活时委派 OpenAI 网关 Responses + // 链:入站同族优先(零或近零转换),响应写回与 failover 错误信封都由该 + // 链完成,错误信封已是 OpenAI Responses 风格,不再二次包装。 + // promptCacheKey 由链内从 body 派生(与 OpenAI handler Responses 路径一致)。 + setOpenAIClientTransportHTTP(c) + openAIResult, delegateErr := h.openAIGatewayService.Forward(attemptCtx, c, account, forwardBody) + result = adaptOpenAIForwardResultToForwardResult(openAIResult) + err = delegateErr } else { - result, err = h.gatewayService.ForwardAsResponses(requestCtx, c, account, forwardBody, parsedReq) + result, err = h.gatewayService.ForwardAsResponses(attemptCtx, c, account, forwardBody, parsedReq) } if accountReleaseFunc != nil { @@ -341,6 +413,11 @@ func (h *GatewayHandler) Responses(c *gin.Context) { upstreamEndpoint := GetUpstreamEndpoint(c, account.Platform) quotaPlatform := service.QuotaPlatform(c.Request.Context(), apiKey) + // 池请求按选中平台计量 user×platform 配额(attempt ctx 携带 resolved + // 平台);非池保持准入语义不变。 + if isPoolAttempt { + quotaPlatform = service.QuotaPlatform(attemptPolicy.AttemptCtx, apiKey) + } sessionID := service.ExtractClientSessionID(c) stampForwardRequestedReasoningEffort(result, service.RequestedReasoningEffortFromContext(c.Request.Context())) h.submitUsageRecordTask(c.Request.Context(), func(ctx context.Context) { @@ -359,7 +436,7 @@ func (h *GatewayHandler) Responses(c *gin.Context) { RequestPayloadHash: requestPayloadHash, APIKeyService: h.apiKeyService, SessionID: sessionID, - ChannelUsageFields: clientRequestedUsageFields(c, channelMapping, reqModel, result.UpstreamModel), + ChannelUsageFields: clientRequestedUsageFields(c, attemptChannelMapping, reqModel, result.UpstreamModel), }); err != nil { reqLog.Error("gateway.responses.record_usage_failed", zap.Int64("account_id", account.ID), diff --git a/backend/internal/server/routes/gateway.go b/backend/internal/server/routes/gateway.go index e75ea51ad2..f27a172d03 100644 --- a/backend/internal/server/routes/gateway.go +++ b/backend/internal/server/routes/gateway.go @@ -566,8 +566,8 @@ func isCompositeOpenAIFamilyPool(candidates []string) bool { // isOpenAIResponsesCompatibleGatewayPlatform 报告请求是否应进入 OpenAI 兼容族 // handler。账号池请求没有单一目标平台:池候选全部属于兼容族才进入,混入其他 -// 族时返回 false,由 dispatchOpenAICompatibleGateway 显式拒绝,不允许按池大小 -// 或猜测选族。 +// 族的池返回 false 落通用网关(generic handler 按选中账号的协议能力分发, +// 不再显式拒绝),不允许按池大小或猜测选族。 func isOpenAIResponsesCompatibleGatewayPlatform(c *gin.Context) bool { if candidates, ok := compositePoolCandidatePlatforms(c); ok { return isCompositeOpenAIFamilyPool(candidates) @@ -577,15 +577,16 @@ func isOpenAIResponsesCompatibleGatewayPlatform(c *gin.Context) bool { // dispatchOpenAICompatibleGateway 把文本端点(messages/responses/chat // completions)路由进 OpenAI 兼容族:账号池候选全部属于兼容族 → OpenAI 网关; -// 跨族池 → 显式 400(点名候选,不落入通用网关的错误协议);单目标沿用既有族 -// 判断落通用网关。 +// 其余(跨族池 / 全原生协议族池)落通用网关——generic handler 在池激活时按 +// 选中账号的协议能力分发转发,不信任「一定有 anthropic 能力」;单目标沿用 +// 既有族判断落通用网关。 func dispatchOpenAICompatibleGateway(c *gin.Context, openAIHandler, genericHandler gin.HandlerFunc) { if candidates, ok := compositePoolCandidatePlatforms(c); ok { if isCompositeOpenAIFamilyPool(candidates) { openAIHandler(c) return } - rejectCompositeCrossFamilyPool(c, candidates) + genericHandler(c) return } if isOpenAICompatibleGatewayFamilyPlatform(getGroupPlatform(c)) { @@ -597,15 +598,15 @@ func dispatchOpenAICompatibleGateway(c *gin.Context, openAIHandler, genericHandl // dispatchOpenAICompatibleCountTokens 沿用 count_tokens 的既有语义:openai 与 // 国产兼容供应商走 OpenAI CountTokens,grok 走本地估算;账号池候选全部属于 -// 兼容族时进入 OpenAI CountTokens(沿用其原有端点能力/不支持语义),跨族池 -// 明确拒绝。 +// 兼容族时进入 OpenAI CountTokens(沿用其原有端点能力/不支持语义),其余池落 +// 通用 CountTokens(generic 链路对不可计数账号按排除重选处理)。 func dispatchOpenAICompatibleCountTokens(c *gin.Context, compatibleHandler, grokHandler, genericHandler gin.HandlerFunc) { if candidates, ok := compositePoolCandidatePlatforms(c); ok { if isCompositeOpenAIFamilyPool(candidates) { compatibleHandler(c) return } - rejectCompositeCrossFamilyPool(c, candidates) + genericHandler(c) return } switch getGroupPlatform(c) { @@ -618,23 +619,6 @@ func dispatchOpenAICompatibleCountTokens(c *gin.Context, compatibleHandler, grok } } -// rejectCompositeCrossFamilyPool 对混入非兼容族候选(或全部为原生协议族)的 -// 账号池写显式 400 并点名候选平台:这类请求没有统一的 handler 家族, -// 猜测单个平台或落入通用网关都会产生误导性错误。 -func rejectCompositeCrossFamilyPool(c *gin.Context, candidates []string) { - foreign := make([]string, 0, len(candidates)) - for _, platform := range candidates { - if !isOpenAICompatibleGatewayFamilyPlatform(platform) { - foreign = append(foreign, platform) - } - } - writeCompositeRouteAdmissionError(c, http.StatusBadRequest, fmt.Sprintf( - "Composite account pool for this model spans multiple protocol families (candidates: %s; unsupported for OpenAI-compatible endpoints: %s)", - strings.Join(candidates, ", "), - strings.Join(foreign, ", "), - )) -} - func compositeTargetPlatformMiddleware(resolver *service.CompositeRouteResolver) gin.HandlerFunc { if resolver == nil { resolver = service.NewCompositeRouteResolver(nil) diff --git a/backend/internal/server/routes/gateway_composite_pool_test.go b/backend/internal/server/routes/gateway_composite_pool_test.go index 97a2cf2c62..495c38c44c 100644 --- a/backend/internal/server/routes/gateway_composite_pool_test.go +++ b/backend/internal/server/routes/gateway_composite_pool_test.go @@ -157,9 +157,10 @@ func TestDispatchOpenAICompatibleGatewaySingleDeepSeekMatchesPoolFamily(t *testi require.Zero(t, generic) } -// 跨原生协议族池(兼容族混 anthropic/gemini/antigravity,或全部为原生族) -// 必须显式 400 并点名候选平台,不得落入通用 handler。 -func TestDispatchOpenAICompatibleGatewayRejectsCrossFamilyPool(t *testing.T) { +// 跨原生协议族池(兼容族混 anthropic/gemini/antigravity,或全部为原生族)不再 +// 显式 400:B1 起 routes 解除族门禁,落通用 handler,由 generic 网关按选中账号 +// 的协议能力分发转发。 +func TestDispatchOpenAICompatibleGatewayRoutesCrossFamilyPoolToGeneric(t *testing.T) { for _, subset := range [][]string{ {service.PlatformAnthropic, service.PlatformDeepseek}, {service.PlatformOpenAI, service.PlatformGrok, service.PlatformGemini}, @@ -168,20 +169,15 @@ func TestDispatchOpenAICompatibleGatewayRejectsCrossFamilyPool(t *testing.T) { {service.PlatformAnthropic, service.PlatformGemini, service.PlatformAntigravity}, } { var openAI, generic int - recorder := httptest.NewRecorder() - c, _ := gin.CreateTestContext(recorder) + c, _ := gin.CreateTestContext(httptest.NewRecorder()) c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", nil).WithContext( service.WithCompositeCandidatePlatforms(context.Background(), subset)) dispatchOpenAICompatibleGateway(c, func(c *gin.Context) { openAI++ }, func(c *gin.Context) { generic++ }) require.Zero(t, openAI, "subset=%v must not enter the OpenAI handler", subset) - require.Zero(t, generic, "subset=%v must not fall through to the generic handler", subset) - require.True(t, c.IsAborted(), "subset=%v must abort", subset) - require.Equal(t, http.StatusBadRequest, recorder.Code, "subset=%v", subset) - for _, platform := range subset { - require.Contains(t, recorder.Body.String(), platform, "subset=%v must name every candidate", subset) - } + require.Equal(t, 1, generic, "subset=%v must fall through to the generic handler", subset) + require.False(t, c.IsAborted(), "subset=%v must not be aborted", subset) } } @@ -216,8 +212,8 @@ func TestDispatchOpenAICompatibleGatewayKeepsGenericTargets(t *testing.T) { require.Equal(t, 1, generic) } -// count_tokens 沿用既有端点语义:兼容族池进 OpenAI CountTokens,跨族池 -// 明确拒绝,grok 单目标保留 GrokCountTokens。 +// count_tokens 沿用既有端点语义:兼容族池进 OpenAI CountTokens,跨族池落通用 +// CountTokens,grok 单目标保留 GrokCountTokens。 func TestDispatchOpenAICompatibleCountTokensPoolAndSingle(t *testing.T) { var compatible, grok, generic int handlers := []gin.HandlerFunc{ @@ -242,7 +238,7 @@ func TestDispatchOpenAICompatibleCountTokensPoolAndSingle(t *testing.T) { require.Zero(t, grok) require.Zero(t, generic) - // 跨族池拒绝,任何 handler 都不执行。 + // 跨族池落通用 CountTokens(generic 链路对不可计数账号按排除重选处理)。 c := newContext(func(c *gin.Context) { c.Request = c.Request.WithContext(service.WithCompositeCandidatePlatforms(c.Request.Context(), []string{service.PlatformAnthropic, service.PlatformDeepseek})) @@ -251,8 +247,8 @@ func TestDispatchOpenAICompatibleCountTokensPoolAndSingle(t *testing.T) { dispatchOpenAICompatibleCountTokens(c, handlers[0], handlers[1], handlers[2]) require.Zero(t, compatible) require.Zero(t, grok) - require.Zero(t, generic) - require.True(t, c.IsAborted()) + require.Equal(t, 1, generic) + require.False(t, c.IsAborted()) // grok 单目标保留本地估算路径。 compatible, grok, generic = 0, 0, 0 @@ -340,33 +336,86 @@ func TestCompositeTargetPlatformMiddlewareUsesAnthropicEnvelopeOnMessages(t *tes require.Contains(t, decoded.Error.Message, "totally-unknown-alias") } -// 跨族池在 /v1/messages 上同样返回 Anthropic 信封;CC 端点保持 OpenAI 信封。 -func TestCompositeCrossFamilyPoolEnvelopeFollowsInboundProtocol(t *testing.T) { +// 跨族池在 /v1/messages 上不再被 400 拒绝:混族池与全兼容族池一样按族归属 +// 分发(混族落通用 handler),信封由具体 handler 的错误路径决定。 +func TestCompositeCrossFamilyPoolFallsThroughOnMessagesAndChatCompletions(t *testing.T) { crossFamily := []string{service.PlatformAnthropic, service.PlatformDeepseek} - // /v1/messages:Anthropic 信封。 + // /v1/messages:混族池落通用 handler,不再 400。 recorder := httptest.NewRecorder() c, _ := gin.CreateTestContext(recorder) c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", nil).WithContext( service.WithCompositeCandidatePlatforms(context.Background(), crossFamily)) - dispatchOpenAICompatibleGateway(c, func(c *gin.Context) {}, func(c *gin.Context) {}) - require.True(t, c.IsAborted()) - var decoded struct { - Type string `json:"type"` - } - require.NoError(t, json.Unmarshal(recorder.Body.Bytes(), &decoded)) - require.Equal(t, "error", decoded.Type, "messages-family rejections must use the Anthropic envelope") + var openAI, generic int + dispatchOpenAICompatibleGateway(c, + func(c *gin.Context) { openAI++ }, + func(c *gin.Context) { generic++ }) + require.Zero(t, openAI) + require.Equal(t, 1, generic) + require.False(t, c.IsAborted()) + require.Equal(t, http.StatusOK, recorder.Code, "cross-family pool must reach the generic handler instead of being rejected") - // /v1/chat/completions:OpenAI 信封。 + // /v1/chat/completions:混族池同样落通用 handler(B2 再做池化循环)。 recorder2 := httptest.NewRecorder() c2, _ := gin.CreateTestContext(recorder2) c2.Request = httptest.NewRequest(http.MethodPost, "/v1/chat/completions", nil).WithContext( service.WithCompositeCandidatePlatforms(context.Background(), crossFamily)) - dispatchOpenAICompatibleGateway(c2, func(c *gin.Context) {}, func(c *gin.Context) {}) - require.True(t, c2.IsAborted()) - var decoded2 struct { - Type string `json:"type"` + var openAI2, generic2 int + dispatchOpenAICompatibleGateway(c2, + func(c *gin.Context) { openAI2++ }, + func(c *gin.Context) { generic2++ }) + require.Zero(t, openAI2) + require.Equal(t, 1, generic2) + require.False(t, c2.IsAborted()) +} + +// B1 解门禁后的完整路由行为(httptest engine + fake ownership resolver): +// 混族池(anthropic+kimi)POST /v1/messages 不再 400、进入 generic handler; +// 全 OpenAI 族池仍走 OpenAI handler(不回归)。 +func TestCompositePoolMessagesDispatchEndToEnd(t *testing.T) { + newRouter := func(ownership compositePoolOwnershipStub, openAI, generic gin.HandlerFunc) *gin.Engine { + t.Helper() + gin.SetMode(gin.TestMode) + router := gin.New() + router.Use(gin.HandlerFunc(servermiddleware.APIKeyAuthMiddleware(func(c *gin.Context) { + groupID := int64(1) + c.Set(string(servermiddleware.ContextKeyAPIKey), &service.APIKey{ + GroupID: &groupID, + Group: &service.Group{ID: groupID, Platform: service.PlatformComposite}, + }) + c.Next() + }))) + resolver := service.NewCompositeRouteResolver(compositeRouteRepoStub{}) + resolver.SetModelOwnershipResolver(ownership.ResolveModelOwnership) + router.Use(compositeTargetPlatformMiddleware(resolver)) + // 与 RegisterAPIGatewayRoutes 相同的 /v1/messages 分发闭包。 + router.POST("/v1/messages", func(c *gin.Context) { + dispatchOpenAICompatibleGateway(c, openAI, generic) + }) + return router } - require.NoError(t, json.Unmarshal(recorder2.Body.Bytes(), &decoded2)) - require.Empty(t, decoded2.Type, "chat completions rejections must keep the OpenAI envelope") + + // 混族池:进入 generic handler(不再 400)。 + genericCalled := false + router := newRouter(compositePoolOwnershipStub{platforms: []string{service.PlatformAnthropic, service.PlatformKimi}}, + func(c *gin.Context) { t.Fatal("mixed pool must not enter the OpenAI handler") }, + func(c *gin.Context) { genericCalled = true; c.Status(http.StatusNoContent) }) + req := httptest.NewRequest(http.MethodPost, "/v1/messages", strings.NewReader(`{"model":"cn-alias","max_tokens":1,"messages":[]}`)) + req.Header.Set("Content-Type", "application/json") + w := httptest.NewRecorder() + router.ServeHTTP(w, req) + require.True(t, genericCalled, "mixed pool /v1/messages must reach the generic handler") + require.Equal(t, http.StatusNoContent, w.Code) + + // 全 OpenAI 族池:仍走 OpenAI handler(不回归)。 + openAICalled := false + router2 := newRouter(compositePoolOwnershipStub{platforms: []string{service.PlatformDeepseek, service.PlatformKimi}}, + func(c *gin.Context) { openAICalled = true; c.Status(http.StatusNoContent) }, + func(c *gin.Context) { t.Fatal("all-OpenAI-family pool must not enter the generic handler") }) + req2 := httptest.NewRequest(http.MethodPost, "/v1/messages", strings.NewReader(`{"model":"cn-alias","messages":[]}`)) + req2.Header.Set("Content-Type", "application/json") + w2 := httptest.NewRecorder() + router2.ServeHTTP(w2, req2) + require.True(t, openAICalled, "all-OpenAI-family pool /v1/messages must keep the OpenAI handler") + require.Equal(t, http.StatusNoContent, w2.Code) } diff --git a/backend/internal/service/composite_generic_pool.go b/backend/internal/service/composite_generic_pool.go new file mode 100644 index 0000000000..48adffb25b --- /dev/null +++ b/backend/internal/service/composite_generic_pool.go @@ -0,0 +1,82 @@ +package service + +import ( + "context" + "strings" +) + +// composite 跨平台候选池(account_pool)在 generic(Anthropic 原生)网关侧的接入点。 +// +// 池上下文契约与能力谓词的所有权在 composite_platform.go / composite_account_claims.go; +// OpenAI 兼容族接入点镜像见 openai_gateway_scheduling.go。已定稿设计中 generic 网关 +// 是统一池执行器:按选中账号的协议能力自动分发转发,因此池成员资格只要求 +// 「平台 ∈ 候选池」且账号可被 generic messages 路径服务,具体协议分支(原生 +// Anthropic / anthropic-协议 / adaptive / OpenAI 兼容委派)由 handler 层分发决定。 +// 本文件能力判定全部走能力谓词,不引入新的平台硬编码清单——ollama_cloud 合入后 +// 凭账号协议能力自动继承,无需改这里。 + +// GenericCompositePoolActive 报告当前请求是否按「composite account_pool」进入 +// generic 调度器。语义镜像 openAICompositePoolActive:显式 resolved 平台优先于池 +// (ctx 已带 ResolvedTargetPlatform,含 Gemini pin 语义,此时即使 ctx 残留候选池 +// 也按单平台旧行为调度);池请求 ctx 携带候选池且无 resolved 平台。 +// 导出供 handler 层做池激活分发判定,与调度器共用同一谓词。 +func GenericCompositePoolActive(ctx context.Context) bool { + if _, resolved := ResolvedTargetPlatformFromContext(ctx); resolved { + return false + } + return len(CompositeCandidatePlatformsFromContext(ctx)) > 0 +} + +// genericCompositePoolAllowsAccount 判定账号是否属于本次请求的候选池,且账号可被 +// generic messages 路径服务。无池时恒为 false,调用方据此保持原平台相等门行为; +// 候选池 immutable,选号 / sticky / 抢槽后复检都必须重新经过本谓词,防止池外账号 +// 经复检路径混入(池塌缩)。 +func genericCompositePoolAllowsAccount(ctx context.Context, account *Account) bool { + if account == nil || !genericCompositePoolAccountServable(account) { + return false + } + for _, platform := range CompositeCandidatePlatformsFromContext(ctx) { + if platform == account.Platform { + return true + } + } + return false +} + +// genericCompositePoolAccountServable 报告账号能否被 generic messages 路径服务。 +// 纯能力判定,不依赖候选池: +// - PlatformAnthropic:generic 网关原生账号(OAuth/APIKey/ServiceAccount); +// - gemini / antigravity:既有 generic 调度支持的平台; +// - anthropic-协议 / adaptive 多协议账号:要求能解析出 Anthropic 协议上游 base +// (GetAnthropicProtocolBaseURL 非空,含 api_base_urls.anthropic 与供应商×模式 +// 默认端点),避免入池后转发期才发现无端点可用; +// - OpenAI 兼容账号(openai/grok/国产供应商/opencode_go):转发由 handler 层 +// 委派协议转换链服务,不因账号停留在 Chat Completions 协议而被池排除。 +func genericCompositePoolAccountServable(account *Account) bool { + if account == nil { + return false + } + switch account.Platform { + case PlatformAnthropic, PlatformGemini, PlatformAntigravity: + return true + } + if account.IsAnthropicProtocol() || account.IsAdaptiveAPIProtocol() { + return strings.TrimSpace(account.GetAnthropicProtocolBaseURL()) != "" + } + return account.IsOpenAICompatible() +} + +// GenericCompositePoolCountableAccount 报告账号可被 generic count_tokens 链路服务 +// (端点转发或本地估算兜底由 handler 分发决定):anthropic 原生 / anthropic-协议 / +// adaptive / gemini / antigravity 可计数;纯 OpenAI 族(无 Anthropic 协议能力)不算。 +// 导出供 handler 层在池请求跳过不可计数账号(重选而非 500)。 +func GenericCompositePoolCountableAccount(account *Account) bool { + if account == nil { + return false + } + switch account.Platform { + case PlatformAnthropic, PlatformGemini, PlatformAntigravity: + return true + } + return account.IsAnthropicProtocol() || account.IsAdaptiveAPIProtocol() +} diff --git a/backend/internal/service/composite_generic_pool_scheduling_test.go b/backend/internal/service/composite_generic_pool_scheduling_test.go new file mode 100644 index 0000000000..451089556f --- /dev/null +++ b/backend/internal/service/composite_generic_pool_scheduling_test.go @@ -0,0 +1,594 @@ +package service + +// generic(Anthropic 原生)网关侧 composite 跨平台候选池(account_pool)测试。 +// +// 镜像 openai_composite_pool_scheduling_test.go / composite_pool_contract_test.go +// 的构造手法(fake repo/cache + credentials 携带 model_mapping / api_protocol / +// api_base_urls)。覆盖: +// a. {anthropic, kimi(adaptive)} 双平台池按 priority/LRU 跨平台选中; +// b. claim 门:候选平台内不 claim 模型的账号不被选(非池请求保持 +// IsModelSupported 原语义); +// c. sticky 命中池外 / 已不 claim 账号时被池成员门拦下,绑定不清; +// d. failover 排除后跨平台选中并粘新账号,池不塌缩; +// e. 负载感知链路(SelectAccountWithLoadAwareness / resolvePlatform)放行池, +// 原 "composite candidate pool" 报错不再出现; +// f. 池谓词契约:servable / countable / resolved 平台 pin 优先。 +// g. 转发 base 协议化:adaptive / anthropic-协议账号经 generic 转发打 +// {base}/v1/messages(无 ?beta=true);classic anthropic 保持 +// base_url+/v1/messages?beta=true + x-api-key 不回归;count_tokens 与 +// passthrough 链同源。 + +import ( + "context" + "errors" + "net/http" + "net/http/httptest" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" + "github.com/tidwall/sjson" +) + +// ---- 测试专用 fake ---- + +// genericPoolTestGroupRepo 提供 composite 分组解析(GetByIDLite / GetByID)。 +type genericPoolTestGroupRepo struct { + GroupRepository + group *Group +} + +func (r *genericPoolTestGroupRepo) GetByID(context.Context, int64) (*Group, error) { + if r.group == nil { + return nil, errors.New("group not found") + } + return r.group, nil +} + +func (r *genericPoolTestGroupRepo) GetByIDLite(_ context.Context, _ int64) (*Group, error) { + if r.group == nil { + return nil, errors.New("group not found") + } + return r.group, nil +} + +// genericPoolTestAccountRepo 平台过滤语义与生产 repo 一致;组维度按 GroupIDs / +// AccountGroups 过滤(对齐生产 ListSchedulableByGroupIDAndPlatform 的 SQL 语义), +// 指针接收者支持用例中途改账号状态。 +type genericPoolTestAccountRepo struct { + AccountRepository + accounts []Account +} + +func (r *genericPoolTestAccountRepo) GetByID(_ context.Context, id int64) (*Account, error) { + for i := range r.accounts { + if r.accounts[i].ID == id { + return &r.accounts[i], nil + } + } + return nil, errors.New("account not found") +} + +func (r *genericPoolTestAccountRepo) listByPlatform(platform string) []Account { + var out []Account + for i := range r.accounts { + if r.accounts[i].Platform == platform { + out = append(out, r.accounts[i]) + } + } + return out +} + +func (r *genericPoolTestAccountRepo) ListSchedulableByGroupIDAndPlatform(_ context.Context, groupID int64, platform string) ([]Account, error) { + var out []Account + for i := range r.accounts { + if r.accounts[i].Platform != platform { + continue + } + for _, ag := range r.accounts[i].AccountGroups { + if ag.GroupID == groupID { + out = append(out, r.accounts[i]) + break + } + } + } + return out, nil +} + +func (r *genericPoolTestAccountRepo) ListSchedulableByPlatform(_ context.Context, platform string) ([]Account, error) { + return r.listByPlatform(platform), nil +} + +func (r *genericPoolTestAccountRepo) ListSchedulableUngroupedByPlatform(_ context.Context, platform string) ([]Account, error) { + var out []Account + for i := range r.accounts { + if r.accounts[i].Platform == platform && len(r.accounts[i].AccountGroups) == 0 { + out = append(out, r.accounts[i]) + } + } + return out, nil +} + +// genericPoolTestAccount 构造池用 APIKey 账号:credentials 携带 model_mapping 与 +// 多协议字段(api_protocol / api_base_urls),extra 透传(认证 scheme 覆写等)。 +func genericPoolTestAccount(id int64, platform string, groupID int64, priority int, credentials map[string]any, extra map[string]any) Account { + account := Account{ + ID: id, + Platform: platform, + Type: AccountTypeAPIKey, + Status: StatusActive, + Schedulable: true, + Concurrency: 1, + Priority: priority, + AccountGroups: []AccountGroup{{AccountID: id, GroupID: groupID}}, + Credentials: credentials, + } + if extra != nil { + account.Extra = extra + } + return account +} + +func newGenericPoolTestService(accounts []Account, group *Group, cache GatewayCache, cfg *config.Config) (*GatewayService, *genericPoolTestAccountRepo) { + repo := &genericPoolTestAccountRepo{accounts: accounts} + if cfg == nil { + cfg = &config.Config{} + } + svc := &GatewayService{ + accountRepo: repo, + groupRepo: &genericPoolTestGroupRepo{group: group}, + cache: cache, + cfg: cfg, + } + return svc, repo +} + +func newGenericPoolTestGroup(id int64) *Group { + return &Group{ + ID: id, + Platform: PlatformComposite, + Status: "active", + Hydrated: true, + } +} + +func genericPoolTestContext(pool []string) context.Context { + return WithCompositeCandidatePlatforms(context.Background(), pool) +} + +// ---- a. 跨平台按 priority / LRU 选中 ---- + +func TestGenericCompositePool_SelectsAcrossPlatformsByPriorityAndLoad(t *testing.T) { + groupID := int64(41001) + group := newGenericPoolTestGroup(groupID) + // 公开模型 my-model 由两个平台账号分别经显式映射 claim(claims 规则 A)。 + model := "my-model" + pool := []string{PlatformAnthropic, PlatformKimi} + ctx := genericPoolTestContext(pool) + + build := func(anthropicPriority, kimiPriority int, anthropicUsed, kimiUsed *time.Time) *GatewayService { + anthropic := genericPoolTestAccount(44001, PlatformAnthropic, groupID, anthropicPriority, + map[string]any{"model_mapping": map[string]any{"my-model": "claude-sonnet-4-5"}}, nil) + kimi := genericPoolTestAccount(44002, PlatformKimi, groupID, kimiPriority, + map[string]any{ + "model_mapping": map[string]any{"my-model": "kimi-k3"}, + "api_protocol": APIProtocolAdaptive, + }, nil) + anthropic.LastUsedAt = anthropicUsed + kimi.LastUsedAt = kimiUsed + svc, _ := newGenericPoolTestService([]Account{anthropic, kimi}, group, &compositePoolTestCache{}, nil) + return svc + } + + // priority 更小者跨平台获胜:kimi(0) 压过 anthropic(5)。 + selected, err := build(5, 0, nil, nil).SelectAccountForModelWithExclusions(ctx, &groupID, "", model, nil) + require.NoError(t, err) + require.EqualValues(t, 44002, selected.ID) + + // 反转 priority:anthropic(0) 获胜。 + selected, err = build(0, 5, nil, nil).SelectAccountForModelWithExclusions(ctx, &groupID, "", model, nil) + require.NoError(t, err) + require.EqualValues(t, 44001, selected.ID) + + // 同 priority 时 LRU:从未使用的账号获胜。 + now := time.Now() + selected, err = build(0, 0, &now, nil).SelectAccountForModelWithExclusions(ctx, &groupID, "", model, nil) + require.NoError(t, err) + require.EqualValues(t, 44002, selected.ID) + + // 更久未用(或从未使用)的账号获胜。 + stale := now.Add(-2 * time.Hour) + recent := now.Add(-1 * time.Hour) + selected, err = build(0, 0, &stale, &recent).SelectAccountForModelWithExclusions(ctx, &groupID, "", model, nil) + require.NoError(t, err) + require.EqualValues(t, 44001, selected.ID) + + // 池 immutable:ctx 候选池完整、未写 ResolvedTargetPlatform(不塌缩)。 + require.ElementsMatch(t, pool, CompositeCandidatePlatformsFromContext(ctx)) + _, resolved := ResolvedTargetPlatformFromContext(ctx) + require.False(t, resolved) +} + +// ---- b. claim 门:候选平台内不 claim 模型的账号不被选 ---- + +func TestGenericCompositePool_ClaimGateFiltersNonClaimingAccounts(t *testing.T) { + groupID := int64(41002) + group := newGenericPoolTestGroup(groupID) + model := "my-model" + pool := []string{PlatformAnthropic, PlatformKimi, PlatformZhipu} + ctx := genericPoolTestContext(pool) + + // zhipu 在候选池中但不 claim my-model(mapping 未命中)→ 被 claims 谓词过滤。 + accounts := []Account{ + genericPoolTestAccount(44101, PlatformAnthropic, groupID, 5, + map[string]any{"model_mapping": map[string]any{"my-model": "claude-sonnet-4-5"}}, nil), + genericPoolTestAccount(44102, PlatformKimi, groupID, 1, + map[string]any{"model_mapping": map[string]any{"my-model": "kimi-k3"}}, nil), + genericPoolTestAccount(44103, PlatformZhipu, groupID, 0, + map[string]any{"model_mapping": map[string]any{"other-model": "glm-5.2"}}, nil), + } + svc, _ := newGenericPoolTestService(accounts, group, &compositePoolTestCache{}, nil) + + selected, err := svc.SelectAccountForModelWithExclusions(ctx, &groupID, "", model, nil) + require.NoError(t, err) + require.EqualValues(t, 44102, selected.ID, "最低 priority 的 zhipu 不 claim 模型,应由 claim 命中的 kimi 入选") + + // 谓词直测:池请求用 claims(防 IsModelSupported 的 allow-all 冒领),非池请求 + // 保持 IsModelSupported 原语义。 + poolCtx := genericPoolTestContext([]string{PlatformKimi, PlatformZhipu}) + // 空 mapping 的 kimi 账号对无关平台模型是 allow-all(旧语义),但 claims 规则 B + // 下 detector 平台不一致 → 池路径不得入选。 + kimiEmpty := genericPoolTestAccount(44104, PlatformKimi, groupID, 0, nil, nil) + require.True(t, kimiEmpty.IsModelSupported("deepseek-chat"), "旧语义 allow-all 仍成立,池路径必须改用 claims 谓词") + require.False(t, svc.gatewaySchedulingModelSupported(poolCtx, &kimiEmpty, "deepseek-chat")) + require.True(t, svc.gatewaySchedulingModelSupported(context.Background(), &kimiEmpty, "deepseek-chat")) + // 池内平台 + 显式 mapping 命中:claims 通过。 + require.True(t, svc.gatewaySchedulingModelSupported(poolCtx, &accounts[2], "other-model")) +} + +// ---- c. sticky 命中池外 / 已不 claim 账号时被池成员门拦下 ---- + +func TestGenericCompositePool_StickyBlockedOutsidePoolOrClaimless(t *testing.T) { + groupID := int64(41003) + group := newGenericPoolTestGroup(groupID) + sessionHash := "sessgenericpool01" + model := "my-model" + pool := []string{PlatformAnthropic, PlatformKimi} + ctx := genericPoolTestContext(pool) + + // 池外账号(openai)也声明 my-model:仅池成员门能拦下它。 + accounts := []Account{ + genericPoolTestAccount(44201, PlatformAnthropic, groupID, 0, + map[string]any{"model_mapping": map[string]any{"my-model": "claude-sonnet-4-5"}}, nil), + genericPoolTestAccount(44202, PlatformKimi, groupID, 0, + map[string]any{ + "model_mapping": map[string]any{"my-model": "kimi-k3"}, + "api_protocol": APIProtocolAdaptive, + }, nil), + genericPoolTestAccount(44203, PlatformOpenAI, groupID, 0, + map[string]any{"model_mapping": map[string]any{"my-model": "gpt-5.5"}}, nil), + } + cache := &compositePoolTestCache{} + svc, _ := newGenericPoolTestService(accounts, group, cache, nil) + + // Case 1:绑定指向池外 openai 账号 → 池成员门拦下,改选池内账号;随后按既有 + // 选号绑定行为把绑定更新到新选中的账号(与 OpenAI 族 failover 语义一致)。 + require.NoError(t, svc.BindStickySession(ctx, &groupID, sessionHash, 44203)) + selected, err := svc.SelectAccountForModelWithExclusions(ctx, &groupID, sessionHash, model, nil) + require.NoError(t, err) + require.NotEqualValues(t, 44203, selected.ID) + require.EqualValues(t, 44201, selected.ID) + bound, ok := cache.binding(groupID, sessionHash) + require.True(t, ok) + require.EqualValues(t, 44201, bound) + + // Case 2:绑定指向 anthropic,但账号 mapping 已不 claim my-model → sticky miss, + // 改选 claim 命中的池内账号(kimi)。 + require.NoError(t, svc.BindStickySession(ctx, &groupID, sessionHash, 44201)) + accounts[0].Credentials = map[string]any{"model_mapping": map[string]any{"other-model": "claude-sonnet-4-5"}} + selected, err = svc.SelectAccountForModelWithExclusions(ctx, &groupID, sessionHash, model, nil) + require.NoError(t, err) + require.EqualValues(t, 44202, selected.ID) +} + +// ---- d. failover 排除后跨平台选中并粘新账号,池不塌缩 ---- + +func TestGenericCompositePool_FailoverExcludesFailedAccountAndSticksToNewPlatform(t *testing.T) { + groupID := int64(41004) + group := newGenericPoolTestGroup(groupID) + sessionHash := "sessgenericpool02" + model := "my-model" + pool := []string{PlatformAnthropic, PlatformKimi} + ctx := genericPoolTestContext(pool) + + accounts := []Account{ + genericPoolTestAccount(44301, PlatformAnthropic, groupID, 0, + map[string]any{"model_mapping": map[string]any{"my-model": "claude-sonnet-4-5"}}, nil), + genericPoolTestAccount(44302, PlatformKimi, groupID, 0, + map[string]any{ + "model_mapping": map[string]any{"my-model": "kimi-k3"}, + "api_protocol": APIProtocolAdaptive, + }, nil), + } + cache := &compositePoolTestCache{} + svc, _ := newGenericPoolTestService(accounts, group, cache, nil) + + first, err := svc.SelectAccountForModelWithExclusions(ctx, &groupID, sessionHash, model, nil) + require.NoError(t, err) + require.EqualValues(t, 44301, first.ID) + + // 排除失败账号后跨平台选中 kimi,并更新同组绑定。 + excluded := map[int64]struct{}{44301: {}} + second, err := svc.SelectAccountForModelWithExclusions(ctx, &groupID, sessionHash, model, excluded) + require.NoError(t, err) + require.EqualValues(t, 44302, second.ID) + bound, ok := cache.binding(groupID, sessionHash) + require.True(t, ok) + require.EqualValues(t, 44302, bound) + + // 后续请求粘新账号;原报错文案不再出现。 + third, err := svc.SelectAccountForModelWithExclusions(ctx, &groupID, sessionHash, model, nil) + require.NoError(t, err) + require.EqualValues(t, 44302, third.ID) + require.ElementsMatch(t, pool, CompositeCandidatePlatformsFromContext(ctx)) +} + +// ---- e. 负载感知链路放行池(resolvePlatform 池分支不再报错) ---- + +func TestGenericCompositePool_LoadAwareSelectsAcrossPlatforms(t *testing.T) { + groupID := int64(41005) + group := newGenericPoolTestGroup(groupID) + model := "my-model" + pool := []string{PlatformAnthropic, PlatformKimi} + ctx := genericPoolTestContext(pool) + + cfg := &config.Config{} + cfg.Gateway.Scheduling.LoadBatchEnabled = true + accounts := []Account{ + genericPoolTestAccount(44401, PlatformAnthropic, groupID, 5, + map[string]any{"model_mapping": map[string]any{"my-model": "claude-sonnet-4-5"}}, nil), + genericPoolTestAccount(44402, PlatformKimi, groupID, 0, + map[string]any{ + "model_mapping": map[string]any{"my-model": "kimi-k3"}, + "api_protocol": APIProtocolAdaptive, + }, nil), + } + svc, _ := newGenericPoolTestService(accounts, group, &compositePoolTestCache{}, cfg) + svc.concurrencyService = NewConcurrencyService(schedulerTestConcurrencyCache{}) + + selection, err := svc.SelectAccountWithLoadAwareness(ctx, &groupID, "", model, nil, "", 0) + require.NoError(t, err) + require.NotNil(t, selection) + require.EqualValues(t, 44402, selection.Account.ID, "priority 更小的 kimi 跨平台获胜,resolvePlatform 池分支不再报 candidate pool 错误") + + // sticky 命中池内账号时正常复检通过。 + sessionHash := "sessgenericpool05" + require.NoError(t, svc.BindStickySession(ctx, &groupID, sessionHash, 44401)) + selection, err = svc.SelectAccountWithLoadAwareness(ctx, &groupID, sessionHash, model, nil, "", 0) + require.NoError(t, err) + require.EqualValues(t, 44401, selection.Account.ID, "池内 sticky 正常命中") + + // sticky 命中的账号不再 claim 模型:Layer 1.5 模型门拦下,回退负载感知选中 + // 仍在 claim 的池内账号。 + accounts[0].Credentials = map[string]any{"model_mapping": map[string]any{"other-model": "claude-sonnet-4-5"}} + selection, err = svc.SelectAccountWithLoadAwareness(ctx, &groupID, sessionHash, model, nil, "", 0) + require.NoError(t, err) + require.EqualValues(t, 44402, selection.Account.ID) +} + +// ---- e2. 显式 resolved 平台 pin 优先于池(单平台旧行为保持) ---- + +func TestGenericCompositePool_ResolvedPlatformPinBeatsPool(t *testing.T) { + groupID := int64(41006) + group := newGenericPoolTestGroup(groupID) + model := "my-model" + + accounts := []Account{ + genericPoolTestAccount(44501, PlatformAnthropic, groupID, 0, + map[string]any{"model_mapping": map[string]any{"my-model": "claude-sonnet-4-5"}}, nil), + genericPoolTestAccount(44502, PlatformKimi, groupID, 5, + map[string]any{ + "model_mapping": map[string]any{"my-model": "kimi-k3"}, + "api_protocol": APIProtocolAdaptive, + }, nil), + } + svc, _ := newGenericPoolTestService(accounts, group, &compositePoolTestCache{}, nil) + + // pin 到 kimi:即便 anthropic priority 更高也按单平台旧行为选中 kimi。 + pinnedCtx := WithResolvedTargetPlatform(genericPoolTestContext([]string{PlatformAnthropic, PlatformKimi}), PlatformKimi) + selected, err := svc.SelectAccountForModelWithExclusions(pinnedCtx, &groupID, "", model, nil) + require.NoError(t, err) + require.EqualValues(t, 44502, selected.ID) +} + +// ---- f. 池谓词契约:servable / countable / pin 判定 ---- + +func TestCompositeGenericPoolPredicates(t *testing.T) { + poolCtx := genericPoolTestContext([]string{PlatformAnthropic, PlatformKimi, PlatformOpenAI}) + + anthropicNative := genericPoolTestAccount(1, PlatformAnthropic, 7, 0, nil, nil) + anthropicOAuth := Account{ID: 2, Platform: PlatformAnthropic, Type: AccountTypeOAuth, Status: StatusActive, Schedulable: true} + kimiAdaptive := genericPoolTestAccount(3, PlatformKimi, 7, 0, + map[string]any{"api_protocol": APIProtocolAdaptive}, nil) + kimiChat := genericPoolTestAccount(4, PlatformKimi, 7, 0, + map[string]any{"api_protocol": APIProtocolChatCompletions}, nil) + zhipuAnthropic := genericPoolTestAccount(5, PlatformZhipu, 7, 0, + map[string]any{"api_protocol": APIProtocolAnthropic}, nil) + openai := genericPoolTestAccount(6, PlatformOpenAI, 7, 0, nil, nil) + gemini := Account{ID: 7, Platform: PlatformGemini, Type: AccountTypeAPIKey, Status: StatusActive, Schedulable: true} + antigravity := Account{ID: 8, Platform: PlatformAntigravity, Type: AccountTypeAPIKey, Status: StatusActive, Schedulable: true} + + // servable:anthropic 原生(含 OAuth)/ adaptive / anthropic-协议 / gemini / + // antigravity / OpenAI 兼容(委派)均可入池。 + require.True(t, genericCompositePoolAccountServable(&anthropicNative)) + require.True(t, genericCompositePoolAccountServable(&anthropicOAuth)) + require.True(t, genericCompositePoolAccountServable(&kimiAdaptive)) + require.True(t, genericCompositePoolAccountServable(&zhipuAnthropic)) + require.True(t, genericCompositePoolAccountServable(&kimiChat), "纯 OpenAI 协议国产账号由 handler 委派转发,池成员资格保留") + require.True(t, genericCompositePoolAccountServable(&openai)) + require.True(t, genericCompositePoolAccountServable(&gemini)) + require.True(t, genericCompositePoolAccountServable(&antigravity)) + + // 池成员资格:平台 ∈ 候选池为准;池外平台一律拒绝。 + require.True(t, genericCompositePoolAllowsAccount(poolCtx, &kimiAdaptive)) + require.True(t, genericCompositePoolAllowsAccount(poolCtx, &anthropicNative)) + require.True(t, genericCompositePoolAllowsAccount(poolCtx, &openai)) + require.False(t, genericCompositePoolAllowsAccount(poolCtx, &gemini), "gemini 不在候选池") + require.False(t, genericCompositePoolAllowsAccount(context.Background(), &kimiAdaptive), "无池恒 false") + + // countable:anthropic 原生 / anthropic-协议 / adaptive / gemini / antigravity + // 可计数;纯 OpenAI 族(chat_completions 国产 / openai)不算。 + require.True(t, GenericCompositePoolCountableAccount(&anthropicNative)) + require.True(t, GenericCompositePoolCountableAccount(&anthropicOAuth)) + require.True(t, GenericCompositePoolCountableAccount(&kimiAdaptive)) + require.True(t, GenericCompositePoolCountableAccount(&zhipuAnthropic)) + require.True(t, GenericCompositePoolCountableAccount(&gemini)) + require.True(t, GenericCompositePoolCountableAccount(&antigravity)) + require.False(t, GenericCompositePoolCountableAccount(&kimiChat)) + require.False(t, GenericCompositePoolCountableAccount(&openai)) + + // 池激活判定:resolved 平台优先于池;无池恒 false。 + require.True(t, GenericCompositePoolActive(poolCtx)) + require.False(t, GenericCompositePoolActive(WithResolvedTargetPlatform(poolCtx, PlatformKimi))) + require.False(t, GenericCompositePoolActive(context.Background())) +} + +// ---- g. 转发 base 协议化 ---- + +// newAdaptiveAnthropicBaseAccount 构造多协议 APIKey 账号,api_base_urls.anthropic +// 指向给定上游 base(adaptive),或 base_url + api_protocol=anthropic。 +func newAdaptiveAnthropicBaseAccount(id int64, platform string, credentials map[string]any, extra map[string]any) *Account { + account := genericPoolTestAccount(id, platform, 0, 0, credentials, extra) + return &account +} + +func newForwardTestContext() (*gin.Context, *httptest.ResponseRecorder) { + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", nil) + return c, rec +} + +func newForwardTestService(allowInsecureHTTP bool) *GatewayService { + cfg := &config.Config{} + cfg.Security.URLAllowlist.AllowInsecureHTTP = allowInsecureHTTP + return &GatewayService{cfg: cfg} +} + +// TestAnthropicProtocolUpstreamTargetURL_AdaptiveAndAnthropicProtocolNoBeta: +// adaptive / anthropic-协议账号经 generic 转发打 {base}/v1/messages,无 ?beta=true; +// 认证与实际 base 同源(默认 x-api-key,opt-in Bearer / ollama base 强制 Bearer)。 +func TestAnthropicProtocolUpstreamTargetURL_AdaptiveAndAnthropicProtocolNoBeta(t *testing.T) { + upstreamURL := "http://127.0.0.1:45991/anthropic" + svc := newForwardTestService(true) + body := []byte(`{"model":"claude-sonnet-4-5","max_tokens":100}`) + + build := func(credentials map[string]any, extra map[string]any) (*http.Request, error) { + account := newAdaptiveAnthropicBaseAccount(46001, PlatformKimi, credentials, extra) + c, _ := newForwardTestContext() + req, _, err := svc.buildUpstreamRequest(context.Background(), c, account, body, "upstream-key", "apikey", "claude-sonnet-4-5", false, false) + return req, err + } + + // adaptive:api_base_urls.anthropic 生效,{base}/v1/messages 无 beta 参数。 + req, err := build(map[string]any{ + "api_key": "upstream-key", + "api_protocol": APIProtocolAdaptive, + "api_base_urls": map[string]any{"anthropic": upstreamURL}, + }, nil) + require.NoError(t, err) + require.Equal(t, upstreamURL+"/v1/messages", req.URL.String()) + require.Empty(t, req.URL.RawQuery) + require.Equal(t, "upstream-key", req.Header.Get("x-api-key"), "Kimi 默认保持 x-api-key 认证") + require.Empty(t, req.Header.Get("Authorization")) + + // adaptive + opt-in Bearer:认证仍与同一 base 同源。 + req, err = build(map[string]any{ + "api_key": "upstream-key", + "api_protocol": APIProtocolAdaptive, + "api_base_urls": map[string]any{"anthropic": upstreamURL}, + }, map[string]any{anthropicAPIKeyAuthSchemeExtraKey: AnthropicAPIKeyAuthSchemeAuthorizationBearer}) + require.NoError(t, err) + require.Equal(t, upstreamURL+"/v1/messages", req.URL.String()) + require.Equal(t, "Bearer upstream-key", req.Header.Get("Authorization")) + require.Empty(t, req.Header.Get("x-api-key")) + + // anthropic-protocol:credential base_url 即 Anthropic 端点,朴素拼接无 beta。 + req, err = build(map[string]any{ + "api_key": "upstream-key", + "api_protocol": APIProtocolAnthropic, + "base_url": upstreamURL, + }, nil) + require.NoError(t, err) + require.Equal(t, upstreamURL+"/v1/messages", req.URL.String()) + require.Empty(t, req.URL.RawQuery) + + // 协议化 base 指向 ollama.com:clamp 与认证判定同源(Bearer + max_tokens 压到 cap)。 + ollamaBody, _ := sjson.SetBytes(body, "model", "deepseek-v4") + ollamaBody, _ = sjson.SetBytes(ollamaBody, "max_tokens", 200000) + account := newAdaptiveAnthropicBaseAccount(46002, PlatformDeepseek, map[string]any{ + "api_key": "upstream-key", + "api_protocol": APIProtocolAdaptive, + "api_base_urls": map[string]any{"anthropic": "https://ollama.com"}, + }, nil) + c, _ := newForwardTestContext() + req, wireBody, err := svc.buildUpstreamRequest(context.Background(), c, account, ollamaBody, "upstream-key", "apikey", "deepseek-v4", false, false) + require.NoError(t, err) + require.Equal(t, "https://ollama.com/v1/messages", req.URL.String()) + require.Empty(t, req.URL.RawQuery) + require.Equal(t, "Bearer upstream-key", req.Header.Get("Authorization"), "ollama 上游按实际 base 强制 Bearer") + require.EqualValues(t, 65535, gjson.GetBytes(wireBody, "max_tokens").Int(), "clamp 与协议化 base 同源判定") +} + +// TestAnthropicProtocolUpstreamTargetURL_ClassicAnthropicKeepsBeta:classic +// anthropic 账号保持 base_url+/v1/messages?beta=true + x-api-key 不回归; +// count_tokens 与 passthrough 链同源。 +func TestAnthropicProtocolUpstreamTargetURL_ClassicAnthropicKeepsBeta(t *testing.T) { + upstreamURL := "https://relay.example.com" + svc := newForwardTestService(false) + account := newAdaptiveAnthropicBaseAccount(46003, PlatformAnthropic, map[string]any{ + "api_key": "anthropic-key", + "base_url": upstreamURL, + }, nil) + body := []byte(`{"model":"claude-sonnet-4-5","max_tokens":100}`) + + // messages:beta=true + x-api-key。 + c, _ := newForwardTestContext() + req, _, err := svc.buildUpstreamRequest(context.Background(), c, account, body, "anthropic-key", "apikey", "claude-sonnet-4-5", false, false) + require.NoError(t, err) + require.Equal(t, upstreamURL+"/v1/messages?beta=true", req.URL.String()) + require.Equal(t, "beta=true", req.URL.RawQuery) + require.Equal(t, "anthropic-key", req.Header.Get("x-api-key")) + require.Empty(t, req.Header.Get("Authorization")) + + // count_tokens:beta=true + x-api-key。 + c, _ = newForwardTestContext() + ctReq, _, err := svc.buildCountTokensRequest(context.Background(), c, account, body, "anthropic-key", "apikey", "claude-sonnet-4-5", false) + require.NoError(t, err) + require.Equal(t, upstreamURL+"/v1/messages/count_tokens?beta=true", ctReq.URL.String()) + require.Equal(t, "anthropic-key", ctReq.Header.Get("x-api-key")) + + // passthrough 链:classic 账号不回归。 + c, _ = newForwardTestContext() + ptReq, _, err := svc.buildUpstreamRequestAnthropicAPIKeyPassthrough(context.Background(), c, account, body, "anthropic-key") + require.NoError(t, err) + require.Equal(t, upstreamURL+"/v1/messages?beta=true", ptReq.URL.String()) + require.Equal(t, "anthropic-key", ptReq.Header.Get("x-api-key")) + + // count_tokens 协议化 base:{base}/v1/messages/count_tokens,无 beta 参数, + // 认证与同一 base 同源(opt-in Bearer)。 + adaptiveAccount := newAdaptiveAnthropicBaseAccount(46004, PlatformKimi, map[string]any{ + "api_key": "upstream-key", + "api_protocol": APIProtocolAdaptive, + "api_base_urls": map[string]any{"anthropic": upstreamURL}, + }, map[string]any{anthropicAPIKeyAuthSchemeExtraKey: AnthropicAPIKeyAuthSchemeAuthorizationBearer}) + c, _ = newForwardTestContext() + adaptiveCTReq, _, err := svc.buildCountTokensRequest(context.Background(), c, adaptiveAccount, body, "upstream-key", "apikey", "my-model", false) + require.NoError(t, err) + require.Equal(t, upstreamURL+"/v1/messages/count_tokens", adaptiveCTReq.URL.String()) + require.Empty(t, adaptiveCTReq.URL.RawQuery) + require.Equal(t, "Bearer upstream-key", adaptiveCTReq.Header.Get("Authorization")) +} diff --git a/backend/internal/service/gateway_anthropic_passthrough.go b/backend/internal/service/gateway_anthropic_passthrough.go index 31df1cb77c..16a4d7d032 100644 --- a/backend/internal/service/gateway_anthropic_passthrough.go +++ b/backend/internal/service/gateway_anthropic_passthrough.go @@ -300,14 +300,19 @@ func (s *GatewayService) buildUpstreamRequestAnthropicAPIKeyPassthrough( token string, ) (*http.Request, []byte, error) { body = stripDeferredToolCacheControl(body) + // 与 buildUpstreamRequest 同源的 base 协议化:CN/多协议账号按协议 base 拼 + // /v1/messages(无 ?beta=true);classic anthropic 保持 + // GetBaseURL()+"/v1/messages?beta=true"。认证 / clamp 与本次实际选用的 base 同源。 targetURL := claudeAPIURL - baseURL := account.GetBaseURL() - if baseURL != "" { - validatedURL, err := s.validateUpstreamBaseURL(baseURL) + anthropicBase := anthropicUpstreamBaseForAuth(account) + if account.Type == AccountTypeAPIKey { + protocolTargetURL, err := s.anthropicUpstreamTargetURL(account, "/v1/messages") if err != nil { return nil, nil, err } - targetURL = validatedURL + "/v1/messages?beta=true" + if protocolTargetURL != "" { + targetURL = protocolTargetURL + } } // 能力维度 body sanitize:透传路径上 anthropic-beta header 原样透传客户端值, @@ -326,8 +331,8 @@ func (s *GatewayService) buildUpstreamRequestAnthropicAPIKeyPassthrough( } // Ollama Cloud DeepSeek 出站 max_tokens clamp:判定与上方 targetURL 的 - // base 取值同源(GetBaseURL),详见 helper 注释。 - body = clampOllamaCloudAnthropicMessagesMaxTokens(account, account.GetBaseURL(), body) + // 协议化 base 取值同源,详见 helper 注释。 + body = clampOllamaCloudAnthropicMessagesMaxTokens(account, anthropicBase, body) req, err := http.NewRequestWithContext(ctx, http.MethodPost, targetURL, bytes.NewReader(body)) if err != nil { @@ -353,8 +358,8 @@ func (s *GatewayService) buildUpstreamRequestAnthropicAPIKeyPassthrough( req.Header.Del("x-goog-api-key") req.Header.Del("cookie") // Ollama Cloud Anthropic 兼容端点按实际 base_url 强制 Bearer(同上方 - // targetURL 的 base 取值),其余保持 extra/default 行为。 - setAnthropicAPIKeyAuthHeader(req.Header, account, token, account.GetBaseURL()) + // targetURL 的协议化 base 取值),其余保持 extra/default 行为。 + setAnthropicAPIKeyAuthHeader(req.Header, account, token, anthropicBase) if getHeaderRaw(req.Header, "content-type") == "" { setHeaderRaw(req.Header, "content-type", "application/json") diff --git a/backend/internal/service/gateway_count_tokens.go b/backend/internal/service/gateway_count_tokens.go index 2a5f4a0401..93c544d16c 100644 --- a/backend/internal/service/gateway_count_tokens.go +++ b/backend/internal/service/gateway_count_tokens.go @@ -394,14 +394,19 @@ func (s *GatewayService) buildCountTokensRequestAnthropicAPIKeyPassthrough( token string, ) (*http.Request, error) { body = stripDeferredToolCacheControl(body) + // 与 buildUpstreamRequestAnthropicAPIKeyPassthrough 同源的 base 协议化: + // CN/多协议账号按协议 base 拼 /v1/messages/count_tokens(无 ?beta=true); + // classic anthropic 保持 GetBaseURL()+"/v1/messages/count_tokens?beta=true"。 targetURL := claudeAPICountTokensURL - baseURL := account.GetBaseURL() - if baseURL != "" { - validatedURL, err := s.validateUpstreamBaseURL(baseURL) + anthropicBase := anthropicUpstreamBaseForAuth(account) + if account.Type == AccountTypeAPIKey { + protocolTargetURL, err := s.anthropicUpstreamTargetURL(account, "/v1/messages/count_tokens") if err != nil { return nil, err } - targetURL = validatedURL + "/v1/messages/count_tokens?beta=true" + if protocolTargetURL != "" { + targetURL = protocolTargetURL + } } body = sanitizeCountTokensRequestBody(body) @@ -441,8 +446,8 @@ func (s *GatewayService) buildCountTokensRequestAnthropicAPIKeyPassthrough( req.Header.Del("x-goog-api-key") req.Header.Del("cookie") // Ollama Cloud Anthropic 兼容端点按实际 base_url 强制 Bearer(同上方 - // targetURL 的 base 取值),其余保持 extra/default 行为。 - setAnthropicAPIKeyAuthHeader(req.Header, account, token, account.GetBaseURL()) + // targetURL 的协议化 base 取值),其余保持 extra/default 行为。 + setAnthropicAPIKeyAuthHeader(req.Header, account, token, anthropicBase) if req.Header.Get("content-type") == "" { req.Header.Set("content-type", "application/json") @@ -461,16 +466,19 @@ func (s *GatewayService) buildCountTokensRequestAnthropicAPIKeyPassthrough( // buildCountTokensRequest 构建 count_tokens 上游请求 func (s *GatewayService) buildCountTokensRequest(ctx context.Context, c *gin.Context, account *Account, body []byte, token, tokenType, modelID string, mimicClaudeCode bool) (*http.Request, []byte, error) { body = stripDeferredToolCacheControl(body) - // 确定目标 URL + // 确定目标 URL。base 协议化与 buildUpstreamRequest 同源:CN/多协议账号 + //(api_protocol=anthropic/adaptive)按 {base}/v1/messages/count_tokens 拼、 + // 不带 ?beta=true;classic anthropic 保持 GetBaseURL()+...?beta=true。认证与 + // 本次实际选用的 base 同源(anthropicUpstreamBaseForAuth)。 targetURL := claudeAPICountTokensURL + anthropicBase := anthropicUpstreamBaseForAuth(account) if account.Type == AccountTypeAPIKey { - baseURL := account.GetBaseURL() - if baseURL != "" { - validatedURL, err := s.validateUpstreamBaseURL(baseURL) - if err != nil { - return nil, nil, err - } - targetURL = validatedURL + "/v1/messages/count_tokens?beta=true" + protocolTargetURL, err := s.anthropicUpstreamTargetURL(account, "/v1/messages/count_tokens") + if err != nil { + return nil, nil, err + } + if protocolTargetURL != "" { + targetURL = protocolTargetURL } } else if account.IsCustomBaseURLEnabled() { customURL := account.GetCustomBaseURL() @@ -553,8 +561,8 @@ func (s *GatewayService) buildCountTokensRequest(ctx context.Context, c *gin.Con setHeaderRaw(req.Header, "authorization", "Bearer "+token) } else { // Ollama Cloud Anthropic 兼容端点按实际 base_url 强制 Bearer(同上方 - // targetURL 的 base 取值),其余保持 extra/default 行为。 - setAnthropicAPIKeyAuthHeader(req.Header, account, token, account.GetBaseURL()) + // targetURL 的协议化 base 取值),其余保持 extra/default 行为。 + setAnthropicAPIKeyAuthHeader(req.Header, account, token, anthropicBase) } // 白名单透传 headers(恢复真实 wire casing) diff --git a/backend/internal/service/gateway_scheduling.go b/backend/internal/service/gateway_scheduling.go index 8acd70519c..a21bee25ae 100644 --- a/backend/internal/service/gateway_scheduling.go +++ b/backend/internal/service/gateway_scheduling.go @@ -57,13 +57,17 @@ func (s *GatewayService) SelectAccountForModelWithExclusions(ctx context.Context return nil, fmt.Errorf("%w supporting model: %s (composite target platform unknown)", ErrNoAvailableAccounts, requestedModel) } if isCompositePoolDecision(decision) { - // 多平台候选池由统一 OpenAI 兼容 selector 选择(openai_gateway_scheduling - // 链路);generic 调度器不消费池,显式失败避免以空平台误调度。 - return nil, fmt.Errorf("%w supporting model: %s (composite candidate pool %s)", ErrNoAvailableAccounts, requestedModel, strings.Join(decision.CandidatePlatforms, ",")) + // 多平台候选池:generic 网关成为统一池执行器,按候选平台跨平台选号。 + // 平台保持 composite 哨兵(仅用于日志/诊断,下游门按 ctx 候选池判定); + // 池不改写请求体模型,最终平台由选号结果决定。候选池写回 ctx + //(immutable),供 listSchedulableAccounts 与 sticky/模型门使用。 + ctx = WithCompositeRouteDecision(ctx, decision) + platform = PlatformComposite + } else { + platform = decision.TargetPlatform + requestedModel = decision.UpstreamModel + ctx = WithCompositeRouteDecision(ctx, decision) } - platform = decision.TargetPlatform - requestedModel = decision.UpstreamModel - ctx = WithCompositeRouteDecision(ctx, decision) } } else { // 无分组时只使用原生 anthropic 平台 @@ -216,7 +220,7 @@ func (s *GatewayService) SelectAccountWithLoadAwareness(ctx context.Context, gro } } - platform, hasForcePlatform, err := s.resolvePlatform(ctx, groupID, group, requestedModel) + ctx, platform, hasForcePlatform, err := s.resolvePlatform(ctx, groupID, group, requestedModel) if err != nil { return nil, err } @@ -301,11 +305,11 @@ func (s *GatewayService) SelectAccountWithLoadAwareness(ctx context.Context, gro if !s.isGatewayAccountProfitEligible(ctx, account) { continue } - if !s.isAccountAllowedForPlatform(account, platform, useMixed) { + if !s.gatewaySchedulingPlatformMatchesAccount(ctx, account, platform, useMixed) { filteredPlatform++ continue } - if requestedModel != "" && !s.isModelSupportedByAccountWithContext(ctx, account, requestedModel) { + if requestedModel != "" && !s.gatewaySchedulingModelSupported(ctx, account, requestedModel) { filteredModelMapping++ continue } @@ -361,8 +365,8 @@ func (s *GatewayService) SelectAccountWithLoadAwareness(ctx context.Context, gro gatePass := s.isAccountSchedulableForSelection(stickyAccount) && s.isGatewayAccountProfitEligible(ctx, stickyAccount) && - s.isAccountAllowedForPlatform(stickyAccount, platform, useMixed) && - (requestedModel == "" || s.isModelSupportedByAccountWithContext(ctx, stickyAccount, requestedModel)) && + s.gatewaySchedulingPlatformMatchesAccount(ctx, stickyAccount, platform, useMixed) && + (requestedModel == "" || s.gatewaySchedulingModelSupported(ctx, stickyAccount, requestedModel)) && !isChannelRestricted(stickyAccount) && s.isAccountSchedulableForModelSelection(ctx, stickyAccount, requestedModel) && s.isAccountSchedulableForQuota(stickyAccount) && @@ -545,9 +549,9 @@ func (s *GatewayService) SelectAccountWithLoadAwareness(ctx context.Context, gro // 注意:不再检查 isAccountInGroup,因为 accountByID 已经从按分组过滤的 // accounts 列表构建,账号一定在分组内。而 scheduler snapshot 缓存 // 反序列化后 AccountGroups 字段为空,导致 isAccountInGroup 永远返回 false。 - platformOK := s.isAccountAllowedForPlatform(account, platform, useMixed) + platformOK := s.gatewaySchedulingPlatformMatchesAccount(ctx, account, platform, useMixed) profitOK := s.isGatewayAccountProfitEligible(ctx, account) - modelSupported := requestedModel == "" || s.isModelSupportedByAccountWithContext(ctx, account, requestedModel) + modelSupported := requestedModel == "" || s.gatewaySchedulingModelSupported(ctx, account, requestedModel) channelOK := !isChannelRestricted(account) modelSchedulable := s.isAccountSchedulableForModelSelection(ctx, account, requestedModel) quotaOK := s.isAccountSchedulableForQuota(account) @@ -670,10 +674,10 @@ func (s *GatewayService) SelectAccountWithLoadAwareness(ctx context.Context, gro if !s.isGatewayAccountProfitEligible(ctx, acc) { continue } - if !s.isAccountAllowedForPlatform(acc, platform, useMixed) { + if !s.gatewaySchedulingPlatformMatchesAccount(ctx, acc, platform, useMixed) { continue } - if requestedModel != "" && !s.isModelSupportedByAccountWithContext(ctx, acc, requestedModel) { + if requestedModel != "" && !s.gatewaySchedulingModelSupported(ctx, acc, requestedModel) { continue } if isChannelRestricted(acc) { @@ -975,54 +979,68 @@ func (s *GatewayService) checkClaudeCodeRestriction(ctx context.Context, groupID return group, resolvedID, nil } -func (s *GatewayService) resolvePlatform(ctx context.Context, groupID *int64, group *Group, requestedModel string) (string, bool, error) { +// resolvePlatform 解析本次请求的调度平台。返回值携带可能被池决策写回的 ctx: +// composite account_pool 决策在此把 immutable 候选池写入 ctx(供 listSchedulableAccounts +// 与 sticky/模型门使用),平台返回 composite 哨兵(仅用于日志/诊断);单平台请求 +// 保持原语义,不写任何池值。 +func (s *GatewayService) resolvePlatform(ctx context.Context, groupID *int64, group *Group, requestedModel string) (context.Context, string, bool, error) { forcePlatform, hasForcePlatform := ctx.Value(ctxkey.ForcePlatform).(string) if hasForcePlatform && forcePlatform != "" { - return forcePlatform, true, nil + return ctx, forcePlatform, true, nil } if platform, ok := ResolvedTargetPlatformFromContext(ctx); ok { - return platform, false, nil + return ctx, platform, false, nil } if group != nil { if group.Platform == PlatformComposite { decision, ok, err := s.resolveCompositeRouteDecision(ctx, group, requestedModel, CompositeRouteEndpointAny) if err != nil { - return "", false, err + return ctx, "", false, err } if !ok { - return "", false, fmt.Errorf("%w supporting model: %s (composite target platform unknown)", ErrNoAvailableAccounts, requestedModel) + return ctx, "", false, fmt.Errorf("%w supporting model: %s (composite target platform unknown)", ErrNoAvailableAccounts, requestedModel) } if isCompositePoolDecision(decision) { - return "", false, fmt.Errorf("%w supporting model: %s (composite candidate pool %s)", ErrNoAvailableAccounts, requestedModel, strings.Join(decision.CandidatePlatforms, ",")) + // 池决策写回 ctx(immutable 候选池),平台保持 composite 哨兵用于日志。 + return WithCompositeRouteDecision(ctx, decision), PlatformComposite, false, nil } - return decision.TargetPlatform, false, nil + return ctx, decision.TargetPlatform, false, nil } - return group.Platform, false, nil + return ctx, group.Platform, false, nil } if groupID != nil { group, err := s.resolveGroupByID(ctx, *groupID) if err != nil { - return "", false, err + return ctx, "", false, err } if group.Platform == PlatformComposite { decision, ok, err := s.resolveCompositeRouteDecision(ctx, group, requestedModel, CompositeRouteEndpointAny) if err != nil { - return "", false, err + return ctx, "", false, err } if !ok { - return "", false, fmt.Errorf("%w supporting model: %s (composite target platform unknown)", ErrNoAvailableAccounts, requestedModel) + return ctx, "", false, fmt.Errorf("%w supporting model: %s (composite target platform unknown)", ErrNoAvailableAccounts, requestedModel) } if isCompositePoolDecision(decision) { - return "", false, fmt.Errorf("%w supporting model: %s (composite candidate pool %s)", ErrNoAvailableAccounts, requestedModel, strings.Join(decision.CandidatePlatforms, ",")) + // 池决策写回 ctx(immutable 候选池),平台保持 composite 哨兵用于日志。 + return WithCompositeRouteDecision(ctx, decision), PlatformComposite, false, nil } - return decision.TargetPlatform, false, nil + return ctx, decision.TargetPlatform, false, nil } - return group.Platform, false, nil + return ctx, group.Platform, false, nil } - return PlatformAnthropic, false, nil + return ctx, PlatformAnthropic, false, nil } func (s *GatewayService) listSchedulableAccounts(ctx context.Context, groupID *int64, platform string, hasForcePlatform bool) ([]Account, bool, error) { + // composite account_pool:跨候选平台逐平台查询合并去重(镜像 OpenAI 族 + // listSchedulableAccountsForCompositePool)。池请求不走 composite 哨兵平台的 + // snapshot/repo 查询(该桶不存在);池请求不做混合调度展开,候选平台各自的 + // 账号经独立桶进入既有选号算法。 + if GenericCompositePoolActive(ctx) { + accounts, err := s.listSchedulableAccountsForCompositePool(ctx, groupID, CompositeCandidatePlatformsFromContext(ctx)) + return accounts, false, err + } if s.schedulerSnapshot != nil { accounts, useMixed, err := s.schedulerSnapshot.ListSchedulableAccounts(ctx, groupID, platform, hasForcePlatform) if err == nil { @@ -1094,16 +1112,7 @@ func (s *GatewayService) listSchedulableAccounts(ctx context.Context, groupID *i return s.filterAccountsBySchedulingThreshold(ctx, filtered), useMixed, nil } - var accounts []Account - var err error - if s.cfg != nil && s.cfg.RunMode == config.RunModeSimple { - accounts, err = s.accountRepo.ListSchedulableByPlatform(ctx, platform) - } else if groupID != nil { - accounts, err = s.accountRepo.ListSchedulableByGroupIDAndPlatform(ctx, *groupID, platform) - // 分组内无账号则返回空列表,由上层处理错误,不再回退到全平台查询 - } else { - accounts, err = s.accountRepo.ListSchedulableUngroupedByPlatform(ctx, platform) - } + accounts, err := s.listSchedulableAccountsSinglePlatform(ctx, groupID, platform, hasForcePlatform) if err != nil { slog.Debug("account_scheduling_list_failed", "group_id", derefGroupID(groupID), @@ -1126,11 +1135,74 @@ func (s *GatewayService) listSchedulableAccounts(ctx context.Context, groupID *i "tls_fingerprint", acc.IsTLSFingerprintEnabled()) } } + return accounts, useMixed, nil +} + +// listSchedulableAccountsForCompositePool 逐候选 platform 读取既有单平台桶并把结果 +// 复制进新 slice、按账号 ID 去重(镜像 OpenAI 族同名做法)。每个桶经独立的 +// snapshot→DB fallback 链路,语义与单平台完全等价;池 immutable,这里不就地修改 +// 任何共享缓存元素,也不对桶做排序(priority/load/LRU 排序留给下游既有选号算法)。 +// excludedIDs 由调用方按账号 ID 传递,跨平台天然通用;所有候选健康但均不合格时 +// 由下游 filter 产出无容量错误(ErrNoAvailableAccounts)。 +func (s *GatewayService) listSchedulableAccountsForCompositePool(ctx context.Context, groupID *int64, platforms []string) ([]Account, error) { + merged := make([]Account, 0, len(platforms)*4) + seen := make(map[int64]struct{}, len(platforms)*4) + for _, platform := range platforms { + // 本次请求被策略 deny 的平台:整平台跳过(候选池本身不变)。 + if compositePoolPlatformDenied(ctx, platform) { + continue + } + // 池桶强制单平台语义(hasForcePlatform=true):避免 snapshot 把 anthropic + // 候选桶展开成 mixed 桶、混入非候选平台的 antigravity 账号。 + bucket, err := s.listSchedulableAccountsSinglePlatform(ctx, groupID, platform, true) + if err != nil { + return nil, err + } + for i := range bucket { + if _, duplicate := seen[bucket[i].ID]; duplicate { + continue + } + seen[bucket[i].ID] = struct{}{} + merged = append(merged, bucket[i]) + } + } + return merged, nil +} + +// listSchedulableAccountsSinglePlatform 单平台可调度桶:snapshot → DB fallback, +// 附调度阈值过滤与 grok 免费配额过滤。与 listSchedulableAccounts 的非混合分支 +// 同源,供其与 composite 池桶(listSchedulableAccountsForCompositePool)复用。 +func (s *GatewayService) listSchedulableAccountsSinglePlatform(ctx context.Context, groupID *int64, platform string, hasForcePlatform bool) ([]Account, error) { + if s.schedulerSnapshot != nil { + accounts, _, err := s.schedulerSnapshot.ListSchedulableAccounts(ctx, groupID, platform, hasForcePlatform) + if err != nil { + return accounts, err + } + accounts = s.filterAccountsBySchedulingThreshold(ctx, accounts) + if platform == PlatformGrok || strings.EqualFold(platform, PlatformGrok) { + accounts = s.filterGrokFreeQuotaAccountsForGateway(ctx, accounts) + } + return accounts, nil + } + var accounts []Account + var err error + if s.cfg != nil && s.cfg.RunMode == config.RunModeSimple { + accounts, err = s.accountRepo.ListSchedulableByPlatform(ctx, platform) + } else if groupID != nil { + accounts, err = s.accountRepo.ListSchedulableByGroupIDAndPlatform(ctx, *groupID, platform) + // 分组内无账号则返回空列表,由上层处理错误,不再回退到全平台查询 + } else { + accounts, err = s.accountRepo.ListSchedulableUngroupedByPlatform(ctx, platform) + } + if err != nil { + // 保持原样返回原始错误(调用方按 debug 日志记录),不额外包装。 + return nil, err + } accounts = s.filterAccountsBySchedulingThreshold(ctx, accounts) if platform == PlatformGrok || strings.EqualFold(platform, PlatformGrok) { accounts = s.filterGrokFreeQuotaAccountsForGateway(ctx, accounts) } - return accounts, useMixed, nil + return accounts, nil } // IsSingleAntigravityAccountGroup 检查指定分组是否只有一个 antigravity 平台的可调度账号。 @@ -1157,6 +1229,31 @@ func (s *GatewayService) isAccountAllowedForPlatform(account *Account, platform return account.Platform == platform } +// gatewaySchedulingPlatformMatchesAccount 是 generic 调度选号/sticky/抢槽后复检的 +// 账号平台门:composite account_pool 激活时改用候选池成员校验(池 immutable, +// 防止 sticky 命中池外账号导致池塌缩),单平台请求保持 +// isAccountAllowedForPlatform 原语义(含混合调度展开)。 +func (s *GatewayService) gatewaySchedulingPlatformMatchesAccount(ctx context.Context, account *Account, platform string, useMixed bool) bool { + if GenericCompositePoolActive(ctx) { + return genericCompositePoolAllowsAccount(ctx, account) + } + return s.isAccountAllowedForPlatform(account, platform, useMixed) +} + +// gatewaySchedulingModelSupported 是 generic 调度选号/sticky 的模型能力门: +// 池请求使用契约共享谓词 CompositeAccountClaimsModel(与构池一致,任意强度命中 +// 均算,防 IsModelSupported 的 allow-all 语义冒领其他平台模型),单平台请求保持 +// isModelSupportedByAccountWithContext 原语义不变。 +func (s *GatewayService) gatewaySchedulingModelSupported(ctx context.Context, account *Account, requestedModel string) bool { + if account == nil || requestedModel == "" { + return true + } + if GenericCompositePoolActive(ctx) { + return CompositeAccountClaimsModel(account, requestedModel) + } + return s.isModelSupportedByAccountWithContext(ctx, account, requestedModel) +} + func (s *GatewayService) isAccountSchedulableForSelection(account *Account) bool { if account == nil { return false @@ -1933,7 +2030,7 @@ func (s *GatewayService) selectAccountForModelWithPlatform(ctx context.Context, if clearSticky { _ = s.cache.DeleteSessionAccountID(ctx, derefGroupID(groupID), sessionHash) } - if !clearSticky && s.isGatewayAccountProfitEligible(ctx, account) && s.isAccountInGroup(account, groupID) && account.Platform == platform && (requestedModel == "" || s.isModelSupportedByAccountWithContext(ctx, account, requestedModel)) && s.isAccountSchedulableForModelSelection(ctx, account, requestedModel) && s.isAccountSchedulableForQuota(account) && s.isAccountSchedulableForWindowCost(ctx, account, true) && s.isAccountSchedulableForRPM(ctx, account, true) && !s.isStickyAccountUpstreamRestricted(ctx, groupID, account, requestedModel) { + if !clearSticky && s.isGatewayAccountProfitEligible(ctx, account) && s.isAccountInGroup(account, groupID) && s.gatewaySchedulingPlatformMatchesAccount(ctx, account, platform, false) && (requestedModel == "" || s.gatewaySchedulingModelSupported(ctx, account, requestedModel)) && s.isAccountSchedulableForModelSelection(ctx, account, requestedModel) && s.isAccountSchedulableForQuota(account) && s.isAccountSchedulableForWindowCost(ctx, account, true) && s.isAccountSchedulableForRPM(ctx, account, true) && !s.isStickyAccountUpstreamRestricted(ctx, groupID, account, requestedModel) { if s.debugModelRoutingEnabled() { logger.LegacyPrintf("service.gateway", "[ModelRoutingDebug] legacy routed sticky hit: group_id=%v model=%s session=%s account=%d", derefGroupID(groupID), requestedModel, shortSessionHash(sessionHash), accountID) } @@ -1990,7 +2087,7 @@ func (s *GatewayService) selectAccountForModelWithPlatform(ctx context.Context, fmt.Sprintf("Privacy not set, required by group [%s]", schedGroup.Name)) continue } - if requestedModel != "" && !s.isModelSupportedByAccountWithContext(ctx, acc, requestedModel) { + if requestedModel != "" && !s.gatewaySchedulingModelSupported(ctx, acc, requestedModel) { continue } if !s.isAccountSchedulableForModelSelection(ctx, acc, requestedModel) { @@ -2055,7 +2152,7 @@ func (s *GatewayService) selectAccountForModelWithPlatform(ctx context.Context, if clearSticky { _ = s.cache.DeleteSessionAccountID(ctx, derefGroupID(groupID), sessionHash) } - if !clearSticky && s.isGatewayAccountProfitEligible(ctx, account) && s.isAccountInGroup(account, groupID) && account.Platform == platform && (requestedModel == "" || s.isModelSupportedByAccountWithContext(ctx, account, requestedModel)) && s.isAccountSchedulableForModelSelection(ctx, account, requestedModel) && s.isAccountSchedulableForQuota(account) && s.isAccountSchedulableForWindowCost(ctx, account, true) && s.isAccountSchedulableForRPM(ctx, account, true) { + if !clearSticky && s.isGatewayAccountProfitEligible(ctx, account) && s.isAccountInGroup(account, groupID) && s.gatewaySchedulingPlatformMatchesAccount(ctx, account, platform, false) && (requestedModel == "" || s.gatewaySchedulingModelSupported(ctx, account, requestedModel)) && s.isAccountSchedulableForModelSelection(ctx, account, requestedModel) && s.isAccountSchedulableForQuota(account) && s.isAccountSchedulableForWindowCost(ctx, account, true) && s.isAccountSchedulableForRPM(ctx, account, true) { return account, nil } } @@ -2104,7 +2201,7 @@ func (s *GatewayService) selectAccountForModelWithPlatform(ctx context.Context, fmt.Sprintf("Privacy not set, required by group [%s]", schedGroup.Name)) continue } - if requestedModel != "" && !s.isModelSupportedByAccountWithContext(ctx, acc, requestedModel) { + if requestedModel != "" && !s.gatewaySchedulingModelSupported(ctx, acc, requestedModel) { continue } if needsUpstreamCheck && s.isUpstreamModelRestrictedByChannel(ctx, *groupID, acc, requestedModel) { diff --git a/backend/internal/service/gateway_upstream_request.go b/backend/internal/service/gateway_upstream_request.go index 0215a86085..5e11d5af93 100644 --- a/backend/internal/service/gateway_upstream_request.go +++ b/backend/internal/service/gateway_upstream_request.go @@ -25,16 +25,21 @@ func (s *GatewayService) buildUpstreamRequest(ctx context.Context, c *gin.Contex return req, body, err } - // 确定目标URL + // 确定目标URL。Anthropic 上游 base 协议化(仅 APIKey 账号有自定义 base 语义): + // CN/多协议账号(api_protocol=anthropic/adaptive)用 GetAnthropicProtocolBaseURL + // 拼 {base}/v1/messages,不带 ?beta=true(第三方端点不接受该参数,与 OpenAI 族 + // nativeAnthropicTargetURL 对齐);classic anthropic 账号保持 + // GetBaseURL()+"/v1/messages?beta=true" 现状。认证 / max_tokens clamp 与本次 + // 实际选用的 base 同源(anthropicUpstreamBaseForAuth)。 targetURL := claudeAPIURL + anthropicBase := anthropicUpstreamBaseForAuth(account) if account.Type == AccountTypeAPIKey { - baseURL := account.GetBaseURL() - if baseURL != "" { - validatedURL, err := s.validateUpstreamBaseURL(baseURL) - if err != nil { - return nil, nil, err - } - targetURL = validatedURL + "/v1/messages?beta=true" + protocolTargetURL, err := s.anthropicUpstreamTargetURL(account, "/v1/messages") + if err != nil { + return nil, nil, err + } + if protocolTargetURL != "" { + targetURL = protocolTargetURL } } else if account.IsCustomBaseURLEnabled() { customURL := account.GetCustomBaseURL() @@ -124,9 +129,9 @@ func (s *GatewayService) buildUpstreamRequest(ctx context.Context, c *gin.Contex } // Ollama Cloud DeepSeek 出站 max_tokens clamp:判定与上方 targetURL 的 - // base 取值同源(GetBaseURL),仅实际上游为 ollama.com 且映射后出站模型 - // 为 DeepSeek 系时压到 cap,详见 helper 注释。 - body = clampOllamaCloudAnthropicMessagesMaxTokens(account, account.GetBaseURL(), body) + // base 取值同源(GetAnthropicProtocolBaseURL / GetBaseURL 协议化解析),仅 + // 实际上游为 ollama.com 且映射后出站模型为 DeepSeek 系时压到 cap,详见 helper 注释。 + body = clampOllamaCloudAnthropicMessagesMaxTokens(account, anthropicBase, body) req, err := http.NewRequestWithContext(ctx, "POST", targetURL, bytes.NewReader(body)) if err != nil { @@ -138,8 +143,8 @@ func (s *GatewayService) buildUpstreamRequest(ctx context.Context, c *gin.Contex setHeaderRaw(req.Header, "authorization", "Bearer "+token) } else { // Ollama Cloud Anthropic 兼容端点按实际 base_url 强制 Bearer(同上方 - // targetURL 的 base 取值),其余保持 extra/default 行为。 - setAnthropicAPIKeyAuthHeader(req.Header, account, token, account.GetBaseURL()) + // targetURL 的协议化 base 取值),其余保持 extra/default 行为。 + setAnthropicAPIKeyAuthHeader(req.Header, account, token, anthropicBase) } // 白名单透传 headers @@ -993,3 +998,42 @@ func (s *GatewayService) validateUpstreamBaseURL(raw string) (string, error) { } return normalized, nil } + +// anthropicUpstreamBaseForAuth 返回账号本次实际选用的 Anthropic 上游 base(与出站 +// URL 组装、认证强制 Bearer 判定、max_tokens clamp 判定同源):CN/多协议账号 +// (api_protocol=anthropic/adaptive)取 GetAnthropicProtocolBaseURL(含 +// api_base_urls.anthropic 与供应商×模式默认端点),classic anthropic / 官方默认 +// 账号取 GetBaseURL(OAuth 等无 base 语义时为空串)。认证与 clamp 必须使用本 +// 返回值而非各自再取 base,保证与真实出站 URL 判定一致。 +func anthropicUpstreamBaseForAuth(account *Account) string { + if base := strings.TrimSpace(account.GetAnthropicProtocolBaseURL()); base != "" { + return base + } + return account.GetBaseURL() +} + +// anthropicUpstreamTargetURL 组装 Anthropic 上游端点(path 以 "/" 开头,如 +// "/v1/messages"、"/v1/messages/count_tokens")。CN/多协议账号( +// GetAnthropicProtocolBaseURL 非空)按 {base}{path} 朴素拼接、不附加 ?beta=true +// (第三方端点不接受该参数,与 OpenAI 族 nativeAnthropicTargetURL 对齐); +// classic anthropic 账号保持 {base}{path}?beta=true 现状。返回空串表示无自定义 +// base(走官方默认 claudeAPIURL / claudeAPICountTokensURL),由调用方保持默认。 +func (s *GatewayService) anthropicUpstreamTargetURL(account *Account, path string) (string, error) { + protocolBase := strings.TrimSpace(account.GetAnthropicProtocolBaseURL()) + if protocolBase != "" { + validatedURL, err := s.validateUpstreamBaseURL(protocolBase) + if err != nil { + return "", err + } + return strings.TrimRight(validatedURL, "/") + path, nil + } + baseURL := account.GetBaseURL() + if baseURL == "" { + return "", nil + } + validatedURL, err := s.validateUpstreamBaseURL(baseURL) + if err != nil { + return "", err + } + return validatedURL + path + "?beta=true", nil +} From 110958f77a9e45191dd101728e2183cd0eeb866d Mon Sep 17 00:00:00 2001 From: alfadb Date: Sat, 12 Sep 2026 21:15:58 +0800 Subject: [PATCH 05/81] feat(platform): add ollama_cloud platform skeleton MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 新增 PlatformOllamaCloud 常量与 AllowedQuotaPlatforms 白名单 - 同步 ent schema 平台校验(user_platform_quota / channel_monitor / channel_monitor_request_template)及生成物 - 新增迁移 239:4 类 CHECK 放宽至 238 的超集(含 ollama_cloud),零 DML 回填 - 新增迁移测试断言 239 为 238 严格超集 - 前端:平台目录、类型联合、配色、图标、i18n 文案 --- backend/ent/channelmonitor/channelmonitor.go | 3 +- .../channelmonitorrequesttemplate.go | 3 +- backend/ent/migrate/schema.go | 4 +- backend/ent/schema/channel_monitor.go | 2 +- .../channel_monitor_request_template.go | 2 +- backend/ent/schema/user_platform_quota.go | 3 +- backend/internal/domain/constants.go | 4 +- backend/internal/service/domain_constants.go | 5 +- .../migrations/239_ollama_cloud_platform.sql | 67 +++++++++++++++++++ .../ollama_cloud_platform_migration_test.go | 30 +++++++++ .../src/components/common/PlatformIcon.vue | 6 ++ frontend/src/components/keys/UseKeyModal.vue | 1 + .../src/constants/__tests__/platforms.spec.ts | 3 +- frontend/src/constants/platforms.ts | 3 +- .../src/i18n/locales/en/admin/accounts.ts | 1 + .../src/i18n/locales/zh/admin/accounts.ts | 1 + frontend/src/types/index.ts | 4 +- frontend/src/utils/platformColors.ts | 16 +++++ 18 files changed, 145 insertions(+), 13 deletions(-) create mode 100644 backend/migrations/239_ollama_cloud_platform.sql create mode 100644 backend/migrations/ollama_cloud_platform_migration_test.go diff --git a/backend/ent/channelmonitor/channelmonitor.go b/backend/ent/channelmonitor/channelmonitor.go index 5fa6966c45..552b2ec3a4 100644 --- a/backend/ent/channelmonitor/channelmonitor.go +++ b/backend/ent/channelmonitor/channelmonitor.go @@ -184,6 +184,7 @@ const ( ProviderDeepseek Provider = "deepseek" ProviderMinimax Provider = "minimax" ProviderOpencodeGo Provider = "opencode_go" + ProviderOllamaCloud Provider = "ollama_cloud" ) func (pr Provider) String() string { @@ -193,7 +194,7 @@ func (pr Provider) String() string { // ProviderValidator is a validator for the "provider" field enum values. It is called by the builders before save. func ProviderValidator(pr Provider) error { switch pr { - case ProviderOpenai, ProviderAnthropic, ProviderGemini, ProviderGrok, ProviderAntigravity, ProviderKimi, ProviderZhipu, ProviderDeepseek, ProviderMinimax, ProviderOpencodeGo: + case ProviderOpenai, ProviderAnthropic, ProviderGemini, ProviderGrok, ProviderAntigravity, ProviderKimi, ProviderZhipu, ProviderDeepseek, ProviderMinimax, ProviderOpencodeGo, ProviderOllamaCloud: return nil default: return fmt.Errorf("channelmonitor: invalid enum value for provider field: %q", pr) diff --git a/backend/ent/channelmonitorrequesttemplate/channelmonitorrequesttemplate.go b/backend/ent/channelmonitorrequesttemplate/channelmonitorrequesttemplate.go index d5ce2cc890..b9528672ff 100644 --- a/backend/ent/channelmonitorrequesttemplate/channelmonitorrequesttemplate.go +++ b/backend/ent/channelmonitorrequesttemplate/channelmonitorrequesttemplate.go @@ -110,6 +110,7 @@ const ( ProviderDeepseek Provider = "deepseek" ProviderMinimax Provider = "minimax" ProviderOpencodeGo Provider = "opencode_go" + ProviderOllamaCloud Provider = "ollama_cloud" ) func (pr Provider) String() string { @@ -119,7 +120,7 @@ func (pr Provider) String() string { // ProviderValidator is a validator for the "provider" field enum values. It is called by the builders before save. func ProviderValidator(pr Provider) error { switch pr { - case ProviderOpenai, ProviderAnthropic, ProviderGemini, ProviderGrok, ProviderAntigravity, ProviderKimi, ProviderZhipu, ProviderDeepseek, ProviderMinimax, ProviderOpencodeGo: + case ProviderOpenai, ProviderAnthropic, ProviderGemini, ProviderGrok, ProviderAntigravity, ProviderKimi, ProviderZhipu, ProviderDeepseek, ProviderMinimax, ProviderOpencodeGo, ProviderOllamaCloud: return nil default: return fmt.Errorf("channelmonitorrequesttemplate: invalid enum value for provider field: %q", pr) diff --git a/backend/ent/migrate/schema.go b/backend/ent/migrate/schema.go index 17ee59bdca..96c229f578 100644 --- a/backend/ent/migrate/schema.go +++ b/backend/ent/migrate/schema.go @@ -623,7 +623,7 @@ var ( {Name: "created_at", Type: field.TypeTime, SchemaType: map[string]string{"postgres": "timestamptz"}}, {Name: "updated_at", Type: field.TypeTime, SchemaType: map[string]string{"postgres": "timestamptz"}}, {Name: "name", Type: field.TypeString, Size: 100}, - {Name: "provider", Type: field.TypeEnum, Enums: []string{"openai", "anthropic", "gemini", "grok", "antigravity", "kimi", "zhipu", "deepseek", "minimax", "opencode_go"}}, + {Name: "provider", Type: field.TypeEnum, Enums: []string{"openai", "anthropic", "gemini", "grok", "antigravity", "kimi", "zhipu", "deepseek", "minimax", "opencode_go", "ollama_cloud"}}, {Name: "check_mode", Type: field.TypeString, Size: 32, Default: "probe"}, {Name: "account_id", Type: field.TypeInt64, Nullable: true}, {Name: "api_mode", Type: field.TypeString, Size: 32, Default: "chat_completions"}, @@ -776,7 +776,7 @@ var ( {Name: "created_at", Type: field.TypeTime, SchemaType: map[string]string{"postgres": "timestamptz"}}, {Name: "updated_at", Type: field.TypeTime, SchemaType: map[string]string{"postgres": "timestamptz"}}, {Name: "name", Type: field.TypeString, Size: 100}, - {Name: "provider", Type: field.TypeEnum, Enums: []string{"openai", "anthropic", "gemini", "grok", "antigravity", "kimi", "zhipu", "deepseek", "minimax", "opencode_go"}}, + {Name: "provider", Type: field.TypeEnum, Enums: []string{"openai", "anthropic", "gemini", "grok", "antigravity", "kimi", "zhipu", "deepseek", "minimax", "opencode_go", "ollama_cloud"}}, {Name: "api_mode", Type: field.TypeString, Size: 32, Default: "chat_completions"}, {Name: "description", Type: field.TypeString, Nullable: true, Size: 500, Default: ""}, {Name: "extra_headers", Type: field.TypeJSON}, diff --git a/backend/ent/schema/channel_monitor.go b/backend/ent/schema/channel_monitor.go index 0e0330fe5e..ab1203fd77 100644 --- a/backend/ent/schema/channel_monitor.go +++ b/backend/ent/schema/channel_monitor.go @@ -36,7 +36,7 @@ func (ChannelMonitor) Fields() []ent.Field { MaxLen(100), field.Enum("provider"). Values("openai", "anthropic", "gemini", "grok", - "antigravity", "kimi", "zhipu", "deepseek", "minimax", "opencode_go"), + "antigravity", "kimi", "zhipu", "deepseek", "minimax", "opencode_go", "ollama_cloud"), // check_mode: 'probe' | 'quota' | 'quota_probe' // probe - LLM 探活(默认,原有行为) // quota - 仅查关联账号的用量/余额(零 LLM 成本;endpoint/api_key 可空) diff --git a/backend/ent/schema/channel_monitor_request_template.go b/backend/ent/schema/channel_monitor_request_template.go index 3fe78fe3e2..ed2bdea90c 100644 --- a/backend/ent/schema/channel_monitor_request_template.go +++ b/backend/ent/schema/channel_monitor_request_template.go @@ -40,7 +40,7 @@ func (ChannelMonitorRequestTemplate) Fields() []ent.Field { MaxLen(100), field.Enum("provider"). Values("openai", "anthropic", "gemini", "grok", - "antigravity", "kimi", "zhipu", "deepseek", "minimax", "opencode_go"), + "antigravity", "kimi", "zhipu", "deepseek", "minimax", "opencode_go", "ollama_cloud"), field.String("api_mode"). Default("chat_completions"). MaxLen(32). diff --git a/backend/ent/schema/user_platform_quota.go b/backend/ent/schema/user_platform_quota.go index 663be0a6ec..9744f189d5 100644 --- a/backend/ent/schema/user_platform_quota.go +++ b/backend/ent/schema/user_platform_quota.go @@ -42,7 +42,8 @@ func (UserPlatformQuota) Fields() []ent.Field { // 此处为 ent 构建期约束,需与 service.AllowedQuotaPlatforms 保持同步。 switch s { case "anthropic", "openai", "gemini", "antigravity", "grok", - "kimi", "zhipu", "deepseek", "minimax", "opencode_go", "typesafe": + "kimi", "zhipu", "deepseek", "minimax", "opencode_go", "typesafe", + "ollama_cloud": return nil default: return fmt.Errorf("platform %q is not allowed", s) diff --git a/backend/internal/domain/constants.go b/backend/internal/domain/constants.go index 37cb3a738f..56d3ad121b 100644 --- a/backend/internal/domain/constants.go +++ b/backend/internal/domain/constants.go @@ -32,7 +32,9 @@ const ( // PlatformOpenCodeGo 是 OpenCode 平台(账号类型 Zen 按量 / Go 订阅)。 // 值保持 opencode_go 以兼容已落库的分组、配额与 Composite 路由 CHECK。 PlatformOpenCodeGo = "opencode_go" - PlatformComposite = "composite" + // PlatformOllamaCloud 是 Ollama Cloud 订阅制聚合上游(多协议 API Key 网关)。 + PlatformOllamaCloud = "ollama_cloud" + PlatformComposite = "composite" ) // Account mode constants 区分国产供应商的「按量付费(余额)」与「Coding Plan」两种接入方式。 diff --git a/backend/internal/service/domain_constants.go b/backend/internal/service/domain_constants.go index e29b4639c0..02a6c87490 100644 --- a/backend/internal/service/domain_constants.go +++ b/backend/internal/service/domain_constants.go @@ -50,7 +50,9 @@ const ( PlatformMiniMax = domain.PlatformMiniMax PlatformTypeSafe = domain.PlatformTypeSafe PlatformOpenCodeGo = domain.PlatformOpenCodeGo - PlatformComposite = domain.PlatformComposite + // PlatformOllamaCloud 是 Ollama Cloud 订阅制聚合上游。 + PlatformOllamaCloud = domain.PlatformOllamaCloud + PlatformComposite = domain.PlatformComposite // PlatformKiro is retained for unsupported-platform threshold tests and legacy // account rows. Scheduling-threshold evaluation never pauses kiro accounts. PlatformKiro = "kiro" @@ -137,6 +139,7 @@ var AllowedQuotaPlatforms = []string{ PlatformMiniMax, PlatformOpenCodeGo, PlatformTypeSafe, + PlatformOllamaCloud, } // AllowedSchedulingThresholdPlatforms 是允许设置账号自动停调阈值的平台列表。 diff --git a/backend/migrations/239_ollama_cloud_platform.sql b/backend/migrations/239_ollama_cloud_platform.sql new file mode 100644 index 0000000000..2aada9bd09 --- /dev/null +++ b/backend/migrations/239_ollama_cloud_platform.sql @@ -0,0 +1,67 @@ +-- Add Ollama Cloud as a first-class platform. +-- +-- 1. user_platform_quotas.platform CHECK +-- 2. composite_model_routes.target_platform CHECK +-- 3. channel_monitors / channel_monitor_request_templates provider CHECK +-- +-- Runs after 238_opencode_go_platform.sql. DROP ... IF EXISTS + 幂等守卫保证可重入; +-- 新约束是 238 的超集,必须同时保留 MiniMax 与 OpenCode Go。 +-- 零 DML 回填:与 157/224/237/238 一致,只放宽约束,不写任何 DML。 + +ALTER TABLE user_platform_quotas + DROP CONSTRAINT IF EXISTS user_platform_quotas_platform_check; + +ALTER TABLE user_platform_quotas + ADD CONSTRAINT user_platform_quotas_platform_check + CHECK (platform IN ('anthropic', 'openai', 'gemini', 'antigravity', 'grok', + 'kimi', 'zhipu', 'deepseek', 'minimax', 'opencode_go', + 'ollama_cloud')); + +ALTER TABLE composite_model_routes + DROP CONSTRAINT IF EXISTS composite_model_routes_target_platform_check; + +ALTER TABLE composite_model_routes + ADD CONSTRAINT composite_model_routes_target_platform_check + CHECK (target_platform IN ('anthropic', 'openai', 'gemini', 'antigravity', 'grok', + 'kimi', 'zhipu', 'deepseek', 'minimax', 'opencode_go', + 'ollama_cloud')); + +DO $$ +DECLARE + monitor_constraint_def TEXT; + template_constraint_def TEXT; +BEGIN + SELECT pg_get_constraintdef(c.oid) + INTO monitor_constraint_def + FROM pg_constraint c + JOIN pg_class t ON t.oid = c.conrelid + WHERE t.relname = 'channel_monitors' + AND c.conname = 'channel_monitors_provider_check'; + + IF monitor_constraint_def IS NULL OR position('ollama_cloud' IN monitor_constraint_def) = 0 THEN + ALTER TABLE channel_monitors + DROP CONSTRAINT IF EXISTS channel_monitors_provider_check; + ALTER TABLE channel_monitors + ADD CONSTRAINT channel_monitors_provider_check + CHECK (provider IN ('openai', 'anthropic', 'gemini', 'grok', + 'antigravity', 'kimi', 'zhipu', 'deepseek', 'minimax', 'opencode_go', + 'ollama_cloud')); + END IF; + + SELECT pg_get_constraintdef(c.oid) + INTO template_constraint_def + FROM pg_constraint c + JOIN pg_class t ON t.oid = c.conrelid + WHERE t.relname = 'channel_monitor_request_templates' + AND c.conname = 'channel_monitor_request_templates_provider_check'; + + IF template_constraint_def IS NULL OR position('ollama_cloud' IN template_constraint_def) = 0 THEN + ALTER TABLE channel_monitor_request_templates + DROP CONSTRAINT IF EXISTS channel_monitor_request_templates_provider_check; + ALTER TABLE channel_monitor_request_templates + ADD CONSTRAINT channel_monitor_request_templates_provider_check + CHECK (provider IN ('openai', 'anthropic', 'gemini', 'grok', + 'antigravity', 'kimi', 'zhipu', 'deepseek', 'minimax', 'opencode_go', + 'ollama_cloud')); + END IF; +END $$; diff --git a/backend/migrations/ollama_cloud_platform_migration_test.go b/backend/migrations/ollama_cloud_platform_migration_test.go new file mode 100644 index 0000000000..ab5362f775 --- /dev/null +++ b/backend/migrations/ollama_cloud_platform_migration_test.go @@ -0,0 +1,30 @@ +package migrations + +import ( + "strings" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestOllamaCloudPlatformMigration(t *testing.T) { + content, err := FS.ReadFile("239_ollama_cloud_platform.sql") + require.NoError(t, err) + + sql := strings.Join(strings.Fields(string(content)), " ") + require.Contains(t, sql, "user_platform_quotas_platform_check") + require.Contains(t, sql, "composite_model_routes_target_platform_check") + require.Contains(t, sql, "channel_monitors_provider_check") + require.Contains(t, sql, "channel_monitor_request_templates_provider_check") + require.Contains(t, sql, "'ollama_cloud'") + require.Contains(t, sql, "'minimax'") + require.Contains(t, sql, "'opencode_go'") + require.Contains(t, sql, "position('ollama_cloud' IN monitor_constraint_def) = 0") + require.Contains(t, sql, "position('ollama_cloud' IN template_constraint_def) = 0") + require.Contains(t, sql, + "CHECK (platform IN ('anthropic', 'openai', 'gemini', 'antigravity', 'grok', 'kimi', 'zhipu', 'deepseek', 'minimax', 'opencode_go', 'ollama_cloud'))") + require.Contains(t, sql, + "CHECK (target_platform IN ('anthropic', 'openai', 'gemini', 'antigravity', 'grok', 'kimi', 'zhipu', 'deepseek', 'minimax', 'opencode_go', 'ollama_cloud'))") + require.Contains(t, sql, + "CHECK (provider IN ('openai', 'anthropic', 'gemini', 'grok', 'antigravity', 'kimi', 'zhipu', 'deepseek', 'minimax', 'opencode_go', 'ollama_cloud'))") +} diff --git a/frontend/src/components/common/PlatformIcon.vue b/frontend/src/components/common/PlatformIcon.vue index df1ec46db3..a17c72e337 100644 --- a/frontend/src/components/common/PlatformIcon.vue +++ b/frontend/src/components/common/PlatformIcon.vue @@ -48,6 +48,12 @@ + + + + { diff --git a/frontend/src/constants/platforms.ts b/frontend/src/constants/platforms.ts index 048ecfc57b..8076a8b916 100644 --- a/frontend/src/constants/platforms.ts +++ b/frontend/src/constants/platforms.ts @@ -21,7 +21,8 @@ export const CONCRETE_PLATFORM_OPTIONS = [ { value: 'deepseek', label: 'DeepSeek' }, { value: 'minimax', label: 'MiniMax' }, { value: 'opencode_go', label: 'OpenCode' }, - { value: 'typesafe', label: 'TypeSafe / Jev' } + { value: 'typesafe', label: 'TypeSafe / Jev' }, + { value: 'ollama_cloud', label: 'Ollama Cloud' } ] as const satisfies readonly PlatformOption[] /** Platforms that can own a group. */ diff --git a/frontend/src/i18n/locales/en/admin/accounts.ts b/frontend/src/i18n/locales/en/admin/accounts.ts index e995eb5e0a..dfd5d7bf79 100644 --- a/frontend/src/i18n/locales/en/admin/accounts.ts +++ b/frontend/src/i18n/locales/en/admin/accounts.ts @@ -118,6 +118,7 @@ export default { minimax: 'MiniMax', opencode_go: 'OpenCode', typesafe: 'TypeSafe / Jev', + ollama_cloud: 'Ollama Cloud', }, cnProviders: { accountMode: { diff --git a/frontend/src/i18n/locales/zh/admin/accounts.ts b/frontend/src/i18n/locales/zh/admin/accounts.ts index d233f9f538..3aa407e6a5 100644 --- a/frontend/src/i18n/locales/zh/admin/accounts.ts +++ b/frontend/src/i18n/locales/zh/admin/accounts.ts @@ -321,6 +321,7 @@ export default { minimax: 'MiniMax', opencode_go: 'OpenCode', typesafe: 'TypeSafe / Jev', + ollama_cloud: 'Ollama Cloud', }, cnProviders: { accountMode: { diff --git a/frontend/src/types/index.ts b/frontend/src/types/index.ts index 7764284dfd..96ec2bcb0c 100644 --- a/frontend/src/types/index.ts +++ b/frontend/src/types/index.ts @@ -538,7 +538,7 @@ export interface PaginationConfig { // ==================== API Key & Group Types ==================== -export type GroupPlatform = 'anthropic' | 'openai' | 'gemini' | 'antigravity' | 'grok' | 'kimi' | 'zhipu' | 'deepseek' | 'minimax' | 'opencode_go' | 'typesafe' | 'composite' +export type GroupPlatform = 'anthropic' | 'openai' | 'gemini' | 'antigravity' | 'grok' | 'kimi' | 'zhipu' | 'deepseek' | 'minimax' | 'opencode_go' | 'typesafe' | 'ollama_cloud' | 'composite' export type VideoModelPrices = Record> @@ -918,7 +918,7 @@ export interface UpdateGroupRequest { // ==================== Account & Proxy Types ==================== -export type AccountPlatform = 'anthropic' | 'openai' | 'gemini' | 'antigravity' | 'grok' | 'kimi' | 'zhipu' | 'deepseek' | 'minimax' | 'opencode_go' | 'typesafe' +export type AccountPlatform = 'anthropic' | 'openai' | 'gemini' | 'antigravity' | 'grok' | 'kimi' | 'zhipu' | 'deepseek' | 'minimax' | 'opencode_go' | 'typesafe' | 'ollama_cloud' export type AccountType = 'oauth' | 'setup-token' | 'apikey' | 'upstream' | 'bedrock' | 'service_account' export type OAuthAddMethod = 'oauth' | 'setup-token' export type ProxyProtocol = 'http' | 'https' | 'socks5' | 'socks5h' diff --git a/frontend/src/utils/platformColors.ts b/frontend/src/utils/platformColors.ts index 7c206ee46d..406eced124 100644 --- a/frontend/src/utils/platformColors.ts +++ b/frontend/src/utils/platformColors.ts @@ -17,6 +17,7 @@ export type Platform = | 'minimax' | 'opencode_go' | 'typesafe' + | 'ollama_cloud' | 'composite' // ── Badge (bg + text + border, for inline badges with border) ─────── @@ -32,6 +33,7 @@ const BADGE: Record = { minimax: 'bg-rose-500/10 text-rose-600 border-rose-500/30 dark:text-rose-400', opencode_go: 'bg-amber-500/10 text-amber-700 border-amber-500/30 dark:text-amber-300', typesafe: 'bg-sky-500/10 text-sky-700 border-sky-500/30 dark:text-sky-300', + ollama_cloud: 'bg-stone-500/10 text-stone-600 border-stone-500/30 dark:text-stone-300', composite: 'bg-cyan-500/10 text-cyan-700 border-cyan-500/30 dark:text-cyan-300', } const BADGE_DEFAULT = 'bg-slate-500/10 text-slate-600 border-slate-500/30 dark:text-slate-400' @@ -49,6 +51,7 @@ const BADGE_LIGHT: Record = { minimax: 'bg-rose-500/10 text-rose-600 dark:bg-rose-500/10 dark:text-rose-300', opencode_go: 'bg-amber-500/10 text-amber-700 dark:bg-amber-500/10 dark:text-amber-300', typesafe: 'bg-sky-500/10 text-sky-700 dark:bg-sky-500/10 dark:text-sky-300', + ollama_cloud: 'bg-stone-500/10 text-stone-600 dark:bg-stone-500/10 dark:text-stone-300', composite: 'bg-cyan-500/10 text-cyan-700 dark:bg-cyan-500/10 dark:text-cyan-300', } @@ -65,6 +68,7 @@ const BORDER: Record = { minimax: 'border-rose-500/20 dark:border-rose-500/20', opencode_go: 'border-amber-500/20 dark:border-amber-500/20', typesafe: 'border-sky-500/20 dark:border-sky-500/20', + ollama_cloud: 'border-stone-500/20 dark:border-stone-500/20', composite: 'border-cyan-500/20 dark:border-cyan-500/20', } const BORDER_DEFAULT = 'border-gray-200 dark:border-dark-700' @@ -82,6 +86,7 @@ const BORDER_STRONG: Record = { minimax: 'border-rose-500/35 dark:border-rose-500/30', opencode_go: 'border-amber-500/35 dark:border-amber-500/30', typesafe: 'border-sky-500/35 dark:border-sky-500/30', + ollama_cloud: 'border-stone-500/35 dark:border-stone-500/30', composite: 'border-cyan-500/35 dark:border-cyan-500/30', } const BORDER_STRONG_DEFAULT = 'border-gray-300 dark:border-dark-600' @@ -100,6 +105,7 @@ const ACCENT: Record = { minimax: '#f43f5e', // rose-500 opencode_go: '#f59e0b', // amber-500 typesafe: '#0ea5e9', // sky-500 + ollama_cloud: '#78716c', // stone-500 composite: '#06b6d4', // cyan-500 } const ACCENT_DEFAULT = '#14b8a6' // primary-500 (teal) @@ -117,6 +123,7 @@ const ACCENT_BAR: Record = { minimax: 'bg-gradient-to-r from-rose-400 to-rose-500', opencode_go: 'bg-gradient-to-r from-amber-400 to-amber-500', typesafe: 'bg-gradient-to-r from-sky-400 to-sky-500', + ollama_cloud: 'bg-gradient-to-r from-stone-400 to-stone-500', composite: 'bg-gradient-to-r from-slate-500 to-cyan-500', } const ACCENT_BAR_DEFAULT = 'bg-gradient-to-r from-primary-400 to-primary-500' @@ -134,6 +141,7 @@ const TEXT: Record = { minimax: 'text-rose-600 dark:text-rose-400', opencode_go: 'text-amber-700 dark:text-amber-300', typesafe: 'text-sky-700 dark:text-sky-300', + ollama_cloud: 'text-stone-600 dark:text-stone-300', composite: 'text-cyan-700 dark:text-cyan-300', } const TEXT_DEFAULT = 'text-primary-600 dark:text-primary-400' @@ -151,6 +159,7 @@ const ICON: Record = { minimax: 'text-rose-500 dark:text-rose-400', opencode_go: 'text-amber-500 dark:text-amber-300', typesafe: 'text-sky-500 dark:text-sky-300', + ollama_cloud: 'text-stone-500 dark:text-stone-300', composite: 'text-cyan-600 dark:text-cyan-300', } const ICON_DEFAULT = 'text-primary-500 dark:text-primary-400' @@ -168,6 +177,7 @@ const BUTTON: Record = { minimax: 'bg-rose-500 text-white hover:bg-rose-600 active:bg-rose-700 dark:bg-rose-500/80 dark:hover:bg-rose-500', opencode_go: 'bg-amber-500 text-white hover:bg-amber-600 active:bg-amber-700 dark:bg-amber-500/80 dark:hover:bg-amber-500', typesafe: 'bg-sky-600 text-white hover:bg-sky-700 active:bg-sky-800 dark:bg-sky-600/80 dark:hover:bg-sky-600', + ollama_cloud: 'bg-stone-600 text-white hover:bg-stone-700 active:bg-stone-800 dark:bg-stone-600/80 dark:hover:bg-stone-600', composite: 'bg-cyan-700 text-white hover:bg-cyan-800 active:bg-cyan-900 dark:bg-cyan-600 dark:hover:bg-cyan-500', } const BUTTON_DEFAULT = 'bg-primary-500 text-white hover:bg-primary-600 dark:bg-primary-600 dark:hover:bg-primary-500' @@ -185,6 +195,7 @@ const DISCOUNT: Record = { minimax: 'bg-rose-100 text-rose-700 dark:bg-rose-900/40 dark:text-rose-300', opencode_go: 'bg-amber-100 text-amber-800 dark:bg-amber-900/40 dark:text-amber-300', typesafe: 'bg-sky-100 text-sky-800 dark:bg-sky-900/40 dark:text-sky-300', + ollama_cloud: 'bg-stone-100 text-stone-800 dark:bg-stone-900/40 dark:text-stone-300', composite: 'bg-cyan-100 text-cyan-800 dark:bg-cyan-900/40 dark:text-cyan-300', } const DISCOUNT_DEFAULT = 'bg-red-100 text-red-700 dark:bg-red-900/40 dark:text-red-300' @@ -202,6 +213,7 @@ const GRADIENT: Record = { minimax: 'from-rose-500 to-rose-600', opencode_go: 'from-amber-500 to-amber-600', typesafe: 'from-sky-500 to-sky-600', + ollama_cloud: 'from-stone-600 to-stone-800', composite: 'from-slate-600 to-cyan-600', } const GRADIENT_DEFAULT = 'from-primary-500 to-primary-600' @@ -219,6 +231,7 @@ const GRADIENT_TEXT: Record = { minimax: 'text-rose-100', opencode_go: 'text-amber-100', typesafe: 'text-sky-100', + ollama_cloud: 'text-stone-100', composite: 'text-cyan-100', } const GRADIENT_TEXT_DEFAULT = 'text-primary-100' @@ -235,6 +248,7 @@ const GRADIENT_SUBTEXT: Record = { minimax: 'text-rose-200', opencode_go: 'text-amber-200', typesafe: 'text-sky-200', + ollama_cloud: 'text-stone-200', composite: 'text-cyan-200', } const GRADIENT_SUBTEXT_DEFAULT = 'text-primary-200' @@ -254,6 +268,7 @@ function isPlatform(p: string): p is Platform { p === 'minimax' || p === 'opencode_go' || p === 'typesafe' || + p === 'ollama_cloud' || p === 'composite' ) } @@ -323,6 +338,7 @@ export function platformLabel(p: string): string { case 'minimax': return 'MiniMax' case 'opencode_go': return 'OpenCode' case 'typesafe': return 'TypeSafe / Jev' + case 'ollama_cloud': return 'Ollama Cloud' case 'composite': return 'Composite' default: return p || 'API' } From 0ec37bd26b4b2510cb71c5c887993facdc9b1a76 Mon Sep 17 00:00:00 2001 From: alfadb Date: Tue, 8 Sep 2026 14:54:50 +0800 Subject: [PATCH 06/81] fix(ollama): normalize DeepSeek reasoning by upstream endpoint, not platform --- .../openai_gateway_chat_completions_raw.go | 6 +- ...penai_gateway_ollama_cloud_cc_reasoning.go | 28 +++++-- ..._gateway_ollama_cloud_cc_reasoning_test.go | 82 ++++++++++++++++++- ...ai_gateway_ollama_cloud_max_tokens_test.go | 18 ++-- 4 files changed, 114 insertions(+), 20 deletions(-) diff --git a/backend/internal/service/openai_gateway_chat_completions_raw.go b/backend/internal/service/openai_gateway_chat_completions_raw.go index 25005986a5..d3295a0648 100644 --- a/backend/internal/service/openai_gateway_chat_completions_raw.go +++ b/backend/internal/service/openai_gateway_chat_completions_raw.go @@ -173,7 +173,7 @@ func (s *OpenAIGatewayService) forwardAsRawChatCompletions( return nil, fmt.Errorf("sanitize Grok unsupported fields: %w", err) } } - upstreamBody = applyOllamaCloudRawChatCompletionsRequest(account, upstreamBody) + upstreamBody = applyOllamaCloudRawChatCompletionsRequest(account, upstreamModel, upstreamBody) upstreamBody = clampOllamaCloudUpstreamMaxTokens(account, upstreamBody) logger.L().Debug("openai chat_completions raw: forwarding without protocol conversion", @@ -365,7 +365,7 @@ func (s *OpenAIGatewayService) streamRawChatCompletions( } } } - line = applyOllamaCloudRawChatCompletionsSSELine(account, line) + line = applyOllamaCloudRawChatCompletionsSSELine(account, upstreamModel, line) line = stripEmptyChatToolCallIdentityFromSSELine(line) line = s.replaceModelInSSELine(line, upstreamModel, originalModel) @@ -538,7 +538,7 @@ func (s *OpenAIGatewayService) bufferRawChatCompletions( upstreamRequestID := firstNonEmpty(requestID, resp.Header.Get("xai-request-id")) return nil, newGrokMissingUsageFailoverError(c, account, upstreamRequestID) } - respBody = applyOllamaCloudRawChatCompletionsResponse(account, respBody) + respBody = applyOllamaCloudRawChatCompletionsResponse(account, upstreamModel, respBody) respBody = s.replaceModelInResponseBody(respBody, upstreamModel, originalModel) if s.responseHeaderFilter != nil { diff --git a/backend/internal/service/openai_gateway_ollama_cloud_cc_reasoning.go b/backend/internal/service/openai_gateway_ollama_cloud_cc_reasoning.go index 4fd1c317b6..fb79b8bf4b 100644 --- a/backend/internal/service/openai_gateway_ollama_cloud_cc_reasoning.go +++ b/backend/internal/service/openai_gateway_ollama_cloud_cc_reasoning.go @@ -47,24 +47,40 @@ func accountHasOllamaCloudUsageExtra(account *Account) bool { return false } +// isOllamaCloudDeepSeekUpstream 判断本次出站是否命中 Ollama Cloud 上托管的 +// DeepSeek 模型:出站 base_url 是 Ollama Cloud(GetOpenAIBaseURL,与 +// clampOllamaCloudUpstreamMaxTokens 的取值一致)且映射后的出站模型是 DeepSeek 系。 +// 不看 platform / account.Type / responses-mode,不读 usage extra;同一分组内 +// 官方 DeepSeek 账号(api.deepseek.com)不命中,保持字节级透传。后续其它出站 +// 路径复用同一判定。nil account / 空模型返回 false。 +func isOllamaCloudDeepSeekUpstream(account *Account, upstreamModel string) bool { + if account == nil { + return false + } + if !isOllamaCloudBaseURL(account.GetOpenAIBaseURL()) { + return false + } + return isDeepSeekModel(upstreamModel) +} + // applyOllamaCloudRawChatCompletionsRequest 只做 Ollama Cloud reasoning 归一化; // max_tokens clamp 已解耦到独立钩子 clampOllamaCloudUpstreamMaxTokens,由出站方依次调用。 -func applyOllamaCloudRawChatCompletionsRequest(account *Account, body []byte) []byte { - if !isOllamaCloudRawChatCompletionsAccount(account) || len(body) == 0 { +func applyOllamaCloudRawChatCompletionsRequest(account *Account, upstreamModel string, body []byte) []byte { + if !isOllamaCloudDeepSeekUpstream(account, upstreamModel) || len(body) == 0 { return body } return normalizeOllamaCloudChatCompletionsRequest(body) } -func applyOllamaCloudRawChatCompletionsResponse(account *Account, body []byte) []byte { - if !isOllamaCloudRawChatCompletionsAccount(account) || len(body) == 0 { +func applyOllamaCloudRawChatCompletionsResponse(account *Account, upstreamModel string, body []byte) []byte { + if !isOllamaCloudDeepSeekUpstream(account, upstreamModel) || len(body) == 0 { return body } return normalizeOllamaCloudChatCompletionsResponseJSON(body) } -func applyOllamaCloudRawChatCompletionsSSELine(account *Account, line string) string { - if !isOllamaCloudRawChatCompletionsAccount(account) || line == "" { +func applyOllamaCloudRawChatCompletionsSSELine(account *Account, upstreamModel string, line string) string { + if !isOllamaCloudDeepSeekUpstream(account, upstreamModel) || line == "" { return line } return normalizeOllamaCloudChatCompletionsSSELine(line) diff --git a/backend/internal/service/openai_gateway_ollama_cloud_cc_reasoning_test.go b/backend/internal/service/openai_gateway_ollama_cloud_cc_reasoning_test.go index ba8bdf714c..808c732660 100644 --- a/backend/internal/service/openai_gateway_ollama_cloud_cc_reasoning_test.go +++ b/backend/internal/service/openai_gateway_ollama_cloud_cc_reasoning_test.go @@ -174,9 +174,11 @@ func TestApplyOllamaCloudRawChatCompletionsLeavesForeignAccountsUnchanged(t *tes } for _, account := range []*Account{official, opencode} { - require.Equal(t, reqBody, applyOllamaCloudRawChatCompletionsRequest(account, reqBody)) - require.Equal(t, respBody, applyOllamaCloudRawChatCompletionsResponse(account, respBody)) - require.Equal(t, sseLine, applyOllamaCloudRawChatCompletionsSSELine(account, sseLine)) + // 出站 base_url 都不是 ollama.com,即使模型是 DeepSeek 系、即使带残留 + // usage extra,reasoning 归一化门控不命中,字节级不变。 + require.Equal(t, reqBody, applyOllamaCloudRawChatCompletionsRequest(account, "deepseek-v4-flash", reqBody)) + require.Equal(t, respBody, applyOllamaCloudRawChatCompletionsResponse(account, "deepseek-v4-flash", respBody)) + require.Equal(t, sseLine, applyOllamaCloudRawChatCompletionsSSELine(account, "deepseek-v4-flash", sseLine)) } } @@ -267,3 +269,77 @@ func TestForwardAsRawChatCompletions_OllamaCloudThinkingAliasNonStreaming(t *tes require.Equal(t, "final answer", gjson.Get(rec.Body.String(), "choices.0.message.content").String()) require.Equal(t, int64(4), gjson.Get(rec.Body.String(), "usage.completion_tokens_details.reasoning_tokens").Int()) } + +// TestIsOllamaCloudDeepSeekUpstream 验证唯一判据:出站 base_url 是 Ollama Cloud && +// 出站模型是 DeepSeek 系,不看 platform / account.Type / responses-mode / usage extra。 +func TestIsOllamaCloudDeepSeekUpstream(t *testing.T) { + t.Parallel() + + t.Run("ollama.com + deepseek model regardless of platform", func(t *testing.T) { + t.Parallel() + for _, platform := range []string{PlatformDeepseek, PlatformZhipu, PlatformOpenAI} { + require.True(t, isOllamaCloudDeepSeekUpstream(ollamaUpstreamTestAccount(platform, 410), "deepseek-v4-flash"), + "platform %s should be recognized", platform) + } + }) + + t.Run("ollama.com + non-deepseek model", func(t *testing.T) { + t.Parallel() + require.False(t, isOllamaCloudDeepSeekUpstream(ollamaUpstreamTestAccount(PlatformDeepseek, 411), "glm-5.3-flash")) + }) + + t.Run("official deepseek upstream is untouched", func(t *testing.T) { + t.Parallel() + require.False(t, isOllamaCloudDeepSeekUpstream(officialDeepSeekTestAccount(412), "deepseek-v4-flash")) + }) + + t.Run("nil account", func(t *testing.T) { + t.Parallel() + require.False(t, isOllamaCloudDeepSeekUpstream(nil, "deepseek-v4-flash")) + }) +} + +// TestApplyOllamaCloudRawChatCompletionsByUpstream 验证三个 apply* 包装函数按唯一 +// 判据(出站 base_url 是 Ollama Cloud && 出站模型是 DeepSeek 系)生效,不看 +// platform / account.Type / responses-mode / usage extra;官方 DeepSeek 字节级不变。 +func TestApplyOllamaCloudRawChatCompletionsByUpstream(t *testing.T) { + t.Parallel() + + reqBody := []byte(`{"messages":[{"role":"assistant","reasoning_content":"prev","content":""}]}`) + respBody := []byte(`{"choices":[{"delta":{"reasoning":"abc"}}]}`) + sseLine := `data: {"choices":[{"delta":{"reasoning":"abc"}}]}` + + t.Run("deepseek platform ollama account + deepseek model is normalized", func(t *testing.T) { + t.Parallel() + account := ollamaUpstreamTestAccount(PlatformDeepseek, 401) + normalizedReq := applyOllamaCloudRawChatCompletionsRequest(account, "deepseek-v4-flash", reqBody) + require.Equal(t, "prev", gjson.GetBytes(normalizedReq, "messages.0.reasoning").String()) + require.Equal(t, "prev", gjson.GetBytes(normalizedReq, "messages.0.reasoning_content").String()) + + normalizedResp := applyOllamaCloudRawChatCompletionsResponse(account, "deepseek-v4-flash", respBody) + require.Equal(t, "abc", gjson.GetBytes(normalizedResp, "choices.0.delta.reasoning").String()) + require.Equal(t, "abc", gjson.GetBytes(normalizedResp, "choices.0.delta.reasoning_content").String()) + + normalizedLine := applyOllamaCloudRawChatCompletionsSSELine(account, "deepseek-v4-flash", sseLine) + require.True(t, strings.HasPrefix(normalizedLine, "data: ")) + payload := strings.TrimPrefix(normalizedLine, "data: ") + require.Equal(t, "abc", gjson.Get(payload, "choices.0.delta.reasoning").String()) + require.Equal(t, "abc", gjson.Get(payload, "choices.0.delta.reasoning_content").String()) + }) + + t.Run("official deepseek account is byte-identical", func(t *testing.T) { + t.Parallel() + official := officialDeepSeekTestAccount(402) + require.Equal(t, reqBody, applyOllamaCloudRawChatCompletionsRequest(official, "deepseek-v4-flash", reqBody)) + require.Equal(t, respBody, applyOllamaCloudRawChatCompletionsResponse(official, "deepseek-v4-flash", respBody)) + require.Equal(t, sseLine, applyOllamaCloudRawChatCompletionsSSELine(official, "deepseek-v4-flash", sseLine)) + }) + + t.Run("ollama account with non-deepseek model is byte-identical", func(t *testing.T) { + t.Parallel() + account := ollamaUpstreamTestAccount(PlatformDeepseek, 403) + require.Equal(t, reqBody, applyOllamaCloudRawChatCompletionsRequest(account, "glm-5.3-flash", reqBody)) + require.Equal(t, respBody, applyOllamaCloudRawChatCompletionsResponse(account, "glm-5.3-flash", respBody)) + require.Equal(t, sseLine, applyOllamaCloudRawChatCompletionsSSELine(account, "glm-5.3-flash", sseLine)) + }) +} diff --git a/backend/internal/service/openai_gateway_ollama_cloud_max_tokens_test.go b/backend/internal/service/openai_gateway_ollama_cloud_max_tokens_test.go index f818c37973..56bf922b3c 100644 --- a/backend/internal/service/openai_gateway_ollama_cloud_max_tokens_test.go +++ b/backend/internal/service/openai_gateway_ollama_cloud_max_tokens_test.go @@ -140,9 +140,10 @@ func TestOllamaCloudMaxTokensCap(t *testing.T) { func TestApplyOllamaCloudRawChatCompletionsRequestClampsMaxTokens(t *testing.T) { body := []byte(`{"model":"deepseek-chat","max_tokens":100000}`) - // Ollama Cloud 账号:reasoning 钩子不再 clamp,字节级原样。 + // Ollama Cloud 账号:reasoning 钩子命中(ollama.com + deepseek-chat),但 body + // 无可归一化的 reasoning 结构,字节级原样;max_tokens 不再由 reasoning 钩子 clamp。 ollama := ollamaCloudRawChatCompletionsTestAccount() - require.Equal(t, string(body), string(applyOllamaCloudRawChatCompletionsRequest(ollama, body))) + require.Equal(t, string(body), string(applyOllamaCloudRawChatCompletionsRequest(ollama, "deepseek-chat", body))) // 独立 token 钩子接续 clamp 到既有默认 cap。 require.JSONEq(t, `{"model":"deepseek-chat","max_tokens":65535}`, string(clampOllamaCloudUpstreamMaxTokens(ollama, body))) @@ -153,20 +154,21 @@ func TestApplyOllamaCloudRawChatCompletionsRequestClampsMaxTokens(t *testing.T) official.Extra = map[string]any{ openai_compat.ExtraKeyResponsesMode: string(openai_compat.ResponsesSupportModeForceChatCompletions), } - require.Equal(t, body, applyOllamaCloudRawChatCompletionsRequest(official, body)) + require.Equal(t, body, applyOllamaCloudRawChatCompletionsRequest(official, "deepseek-chat", body)) require.Equal(t, string(body), string(clampOllamaCloudUpstreamMaxTokens(official, body))) - // ollama.com 但无 force_chat_completions:reasoning 钩子不生效;独立钩子按 - // DeepSeek 系模型判定仍 clamp(DeepSeek 覆盖不依赖 responses_mode extra)。 + // ollama.com 但无 force_chat_completions:reasoning 钩子按新判据命中(判定不看 + // responses-mode),body 无可归一化内容故仍字节不变;独立钩子按 DeepSeek 系模型 + // 判定仍 clamp(DeepSeek 覆盖不依赖 responses_mode extra)。 noForce := ollamaCloudRawChatCompletionsTestAccount() noForce.Extra = nil - require.Equal(t, body, applyOllamaCloudRawChatCompletionsRequest(noForce, body)) + require.Equal(t, body, applyOllamaCloudRawChatCompletionsRequest(noForce, "deepseek-chat", body)) require.JSONEq(t, `{"model":"deepseek-chat","max_tokens":65535}`, string(clampOllamaCloudUpstreamMaxTokens(noForce, body))) // 空 body → 原样返回。 - require.Equal(t, []byte(nil), applyOllamaCloudRawChatCompletionsRequest(ollama, nil)) - require.Equal(t, []byte{}, applyOllamaCloudRawChatCompletionsRequest(ollama, []byte{})) + require.Equal(t, []byte(nil), applyOllamaCloudRawChatCompletionsRequest(ollama, "deepseek-chat", nil)) + require.Equal(t, []byte{}, applyOllamaCloudRawChatCompletionsRequest(ollama, "deepseek-chat", []byte{})) } // ollamaUpstreamTestAccount 构造挂在实际 ollama.com 上游的 APIKey 账号。平台标签 From fb8408029d6bc5f4290fac3030a35d5811a71669 Mon Sep 17 00:00:00 2001 From: alfadb Date: Tue, 8 Sep 2026 15:34:29 +0800 Subject: [PATCH 07/81] fix(ollama): apply DeepSeek reasoning/max_tokens adapter on CC bridge paths --- .../service/openai_gateway_cc_pipeline.go | 19 ++- .../openai_gateway_messages_chat_fallback.go | 17 +- ...eway_messages_chat_fallback_ollama_test.go | 145 +++++++++++++++++ .../openai_gateway_responses_chat_fallback.go | 13 +- ...way_responses_chat_fallback_ollama_test.go | 148 ++++++++++++++++++ 5 files changed, 332 insertions(+), 10 deletions(-) create mode 100644 backend/internal/service/openai_gateway_messages_chat_fallback_ollama_test.go create mode 100644 backend/internal/service/openai_gateway_responses_chat_fallback_ollama_test.go diff --git a/backend/internal/service/openai_gateway_cc_pipeline.go b/backend/internal/service/openai_gateway_cc_pipeline.go index 0fe504a6f8..aa65f842eb 100644 --- a/backend/internal/service/openai_gateway_cc_pipeline.go +++ b/backend/internal/service/openai_gateway_cc_pipeline.go @@ -263,10 +263,13 @@ type ccStreamScanState struct { // scanCCStream 驱动两条 CC 回退路径共享的 SSE 读循环:提取 data 行、在 [DONE] // 哨兵处停止、保留最新 usage、记录首 token 时延,并把每个解析成功的 chunk 交给 // emit 回调做各自的协议转换与写出。读错误按既有约定过滤 context 取消类噪声后 -// 记入 Warn 日志。 +// 记入 Warn 日志。account 与 upstreamModel 用于在解析成 chunk 之前对原始 SSE 行 +// 做 Ollama Cloud DeepSeek reasoning 归一化(未命中时字节级透传,语义等同不挂)。 func (s *OpenAIGatewayService) scanCCStream( c *gin.Context, resp *http.Response, + account *Account, + upstreamModel string, logPrefix string, requestID string, startTime time.Time, @@ -277,6 +280,9 @@ func (s *OpenAIGatewayService) scanCCStream( scanner := s.newUpstreamSSEScanner(resp.Body) for scanner.Scan() { line := scanner.Text() + // Ollama Cloud DeepSeek 出站:在解析成 chunk 之前把 reasoning/thinking 归一化 + // 成 reasoning_content,让协议转换器看到与官方 DeepSeek 完全一致的形态。 + line = applyOllamaCloudRawChatCompletionsSSELine(account, upstreamModel, line) payload, ok := extractOpenAISSEDataLine(line) if !ok { continue @@ -335,10 +341,14 @@ func logCCStreamMissingDoneSentinel(logPrefix, requestID string) { } // readCCUpstreamJSONResponse 读取并解析 CC 非流式 JSON 响应,失败时以调用方 -// 端点格式回写错误;成功时顺带提取 usage。 +// 端点格式回写错误;成功时顺带提取 usage。account 与 upstreamModel 用于在解析 +// 成结构体之前对原始响应体做 Ollama Cloud DeepSeek reasoning 归一化(未命中时 +// 字节级透传,语义等同不挂)。 func (s *OpenAIGatewayService) readCCUpstreamJSONResponse( c *gin.Context, resp *http.Response, + account *Account, + upstreamModel string, writeError compatErrorWriter, ) (*apicompat.ChatCompletionsResponse, OpenAIUsage, error) { respBody, err := ReadUpstreamResponseBody(resp.Body, s.cfg, c, openAITooLargeError) @@ -349,6 +359,11 @@ func (s *OpenAIGatewayService) readCCUpstreamJSONResponse( return nil, OpenAIUsage{}, fmt.Errorf("read upstream body: %w", err) } + // Ollama Cloud DeepSeek 出站:在解析成结构体之前把 message/delta 里的 + // reasoning/thinking 归一化成 reasoning_content,让协议转换器看到与官方 + // DeepSeek 完全一致的形态。 + respBody = applyOllamaCloudRawChatCompletionsResponse(account, upstreamModel, respBody) + var ccResp apicompat.ChatCompletionsResponse if err := json.Unmarshal(respBody, &ccResp); err != nil { writeError(c, http.StatusBadGateway, "api_error", "Failed to parse upstream response") diff --git a/backend/internal/service/openai_gateway_messages_chat_fallback.go b/backend/internal/service/openai_gateway_messages_chat_fallback.go index 47e612cb45..779d1fe041 100644 --- a/backend/internal/service/openai_gateway_messages_chat_fallback.go +++ b/backend/internal/service/openai_gateway_messages_chat_fallback.go @@ -107,6 +107,13 @@ func (s *OpenAIGatewayService) forwardAnthropicViaRawChatCompletions( // so the converted Chat Completions body never contains one and the policy // would always be a no-op on this path. + // Ollama Cloud → DeepSeek 出站(chatReq.Model 已是模型映射后的 upstreamModel): + // 与 raw 路径同序——先归一化 request(历史 assistant 消息 + // reasoning_content → reasoning)、再 clamp max_tokens(>65535 → 65535)。 + // 官方 DeepSeek/glm 等未命中时字节级透传。 + chatBody = applyOllamaCloudRawChatCompletionsRequest(account, upstreamModel, chatBody) + chatBody = clampOllamaCloudUpstreamMaxTokens(account, chatBody) + logger.L().Debug("openai messages: forwarding via raw chat completions", zap.Int64("account_id", account.ID), zap.String("original_model", originalModel), @@ -142,14 +149,15 @@ func (s *OpenAIGatewayService) forwardAnthropicViaRawChatCompletions( // 5. Convert response if clientStream { - return s.streamChatCompletionsAsAnthropic(c, resp, originalModel, billingModel, upstreamModel, reasoningEffort, serviceTier, startTime) + return s.streamChatCompletionsAsAnthropic(c, resp, account, originalModel, billingModel, upstreamModel, reasoningEffort, serviceTier, startTime) } - return s.bufferChatCompletionsAsAnthropic(c, resp, originalModel, billingModel, upstreamModel, reasoningEffort, serviceTier, startTime) + return s.bufferChatCompletionsAsAnthropic(c, resp, account, originalModel, billingModel, upstreamModel, reasoningEffort, serviceTier, startTime) } func (s *OpenAIGatewayService) bufferChatCompletionsAsAnthropic( c *gin.Context, resp *http.Response, + account *Account, originalModel string, billingModel string, upstreamModel string, @@ -158,7 +166,7 @@ func (s *OpenAIGatewayService) bufferChatCompletionsAsAnthropic( startTime time.Time, ) (*OpenAIForwardResult, error) { requestID := resp.Header.Get("x-request-id") - ccResp, usage, err := s.readCCUpstreamJSONResponse(c, resp, writeAnthropicError) + ccResp, usage, err := s.readCCUpstreamJSONResponse(c, resp, account, upstreamModel, writeAnthropicError) if err != nil { return nil, err } @@ -187,6 +195,7 @@ func (s *OpenAIGatewayService) bufferChatCompletionsAsAnthropic( func (s *OpenAIGatewayService) streamChatCompletionsAsAnthropic( c *gin.Context, resp *http.Response, + account *Account, originalModel string, billingModel string, upstreamModel string, @@ -224,7 +233,7 @@ func (s *OpenAIGatewayService) streamChatCompletionsAsAnthropic( } } - scan := s.scanCCStream(c, resp, "openai messages chat fallback", requestID, startTime, emitChunk) + scan := s.scanCCStream(c, resp, account, upstreamModel, "openai messages chat fallback", requestID, startTime, emitChunk) usage := scan.Usage if scan.Err != nil { diff --git a/backend/internal/service/openai_gateway_messages_chat_fallback_ollama_test.go b/backend/internal/service/openai_gateway_messages_chat_fallback_ollama_test.go new file mode 100644 index 0000000000..4410b6f36f --- /dev/null +++ b/backend/internal/service/openai_gateway_messages_chat_fallback_ollama_test.go @@ -0,0 +1,145 @@ +//go:build unit + +package service + +import ( + "bytes" + "context" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" +) + +// runOllamaMessagesChatFallback 直接走 /v1/messages → raw CC 降级桥 +// forwardAnthropicViaRawChatCompletions(与 messages 桥既有测试同风格,直接调桥函数)。 +func runOllamaMessagesChatFallback(t *testing.T, account *Account, body []byte, upstreamBody string, stream bool) (*httptest.ResponseRecorder, *httpUpstreamRecorder) { + t.Helper() + gin.SetMode(gin.TestMode) + contentType := "application/json" + if stream { + contentType = "text/event-stream" + } + upstreamResp := &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{ + "Content-Type": []string{contentType}, + "x-request-id": []string{"rid_ollama_messages_fallback"}, + }, + Body: io.NopCloser(strings.NewReader(upstreamBody)), + } + upstream := &httpUpstreamRecorder{resp: upstreamResp} + svc := &OpenAIGatewayService{ + cfg: rawChatCompletionsTestConfig(), + httpUpstream: upstream, + } + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", bytes.NewReader(body)) + c.Request.Header.Set("Content-Type", "application/json") + result, err := svc.forwardAnthropicViaRawChatCompletions(context.Background(), c, account, body, "") + require.NoError(t, err) + require.NotNil(t, result) + return rec, upstream +} + +func TestMessagesChatFallback_OllamaDeepSeek_ClampMaxTokens(t *testing.T) { + account := ollamaUpstreamTestAccount(PlatformDeepseek, 701) + + t.Run("256000 clamps to 65535", func(t *testing.T) { + body := []byte(`{"model":"deepseek-v4-flash","max_tokens":256000,"messages":[{"role":"user","content":"hello"}],"stream":false}`) + upstreamJSON := `{"id":"chatcmpl_ollama","object":"chat.completion","model":"deepseek-v4-flash","choices":[{"index":0,"message":{"role":"assistant","content":"hi"},"finish_reason":"stop"}],"usage":{"prompt_tokens":3,"completion_tokens":5,"total_tokens":8}}` + _, upstream := runOllamaMessagesChatFallback(t, account, body, upstreamJSON, false) + require.Equal(t, "deepseek-v4-flash", gjson.GetBytes(upstream.lastBody, "model").String()) + require.Equal(t, int64(65535), gjson.GetBytes(upstream.lastBody, "max_completion_tokens").Int()) + }) + + t.Run("1000 stays 1000", func(t *testing.T) { + body := []byte(`{"model":"deepseek-v4-flash","max_tokens":1000,"messages":[{"role":"user","content":"hello"}],"stream":false}`) + upstreamJSON := `{"id":"chatcmpl_ollama","object":"chat.completion","model":"deepseek-v4-flash","choices":[{"index":0,"message":{"role":"assistant","content":"hi"},"finish_reason":"stop"}],"usage":{"prompt_tokens":3,"completion_tokens":5,"total_tokens":8}}` + _, upstream := runOllamaMessagesChatFallback(t, account, body, upstreamJSON, false) + require.Equal(t, int64(1000), gjson.GetBytes(upstream.lastBody, "max_completion_tokens").Int()) + }) +} + +// TestMessagesChatFallback_OllamaDeepSeek_ReasoningAliasStreaming 验证流式响应侧 +// 归一化:上游 delta.reasoning / delta.thinking 与官方形态 delta.reasoning_content +// 在归一化之后产出完全相同的 thinking 输出(同一转换路径跑多个输入对比)。 +func TestMessagesChatFallback_OllamaDeepSeek_ReasoningAliasStreaming(t *testing.T) { + account := ollamaUpstreamTestAccount(PlatformDeepseek, 702) + body := []byte(`{"model":"deepseek-v4-flash","max_tokens":1000,"messages":[{"role":"user","content":"hello"}],"stream":true}`) + + run := func(reasoningField string) string { + upstreamBody := strings.Join([]string{ + `data: {"id":"chatcmpl_ollama","object":"chat.completion.chunk","model":"deepseek-v4-flash","choices":[{"index":0,"delta":{"role":"assistant"},"finish_reason":null}]}`, + "", + `data: {"id":"chatcmpl_ollama","object":"chat.completion.chunk","model":"deepseek-v4-flash","choices":[{"index":0,"delta":{` + reasoningField + `},"finish_reason":null}]}`, + "", + `data: {"id":"chatcmpl_ollama","object":"chat.completion.chunk","model":"deepseek-v4-flash","choices":[{"index":0,"delta":{"content":"final answer"},"finish_reason":null}]}`, + "", + `data: {"id":"chatcmpl_ollama","object":"chat.completion.chunk","model":"deepseek-v4-flash","choices":[],"usage":{"prompt_tokens":3,"completion_tokens":5,"total_tokens":8}}`, + "", + "data: [DONE]", + "", + }, "\n") + rec, _ := runOllamaMessagesChatFallback(t, account, body, upstreamBody, true) + return rec.Body.String() + } + + baseline := run(`"reasoning_content":"abc"`) + for _, tc := range []struct { + name string + field string + }{ + {name: "delta.reasoning alias", field: `"reasoning":"abc"`}, + {name: "delta.thinking alias", field: `"thinking":"abc"`}, + } { + t.Run(tc.name, func(t *testing.T) { + out := run(tc.field) + require.Equal(t, baseline, out, "归一化后输出必须与 reasoning_content 基线完全一致") + require.Contains(t, out, "event: content_block_start") + require.Contains(t, out, `"type":"thinking"`) + require.Contains(t, out, `"thinking":"abc"`) + require.Contains(t, out, `"type":"text"`) + require.Contains(t, out, `"text":"final answer"`) + }) + } +} + +func TestMessagesChatFallback_OllamaDeepSeek_ThinkingAliasNonStreaming(t *testing.T) { + account := ollamaUpstreamTestAccount(PlatformDeepseek, 703) + body := []byte(`{"model":"deepseek-v4-flash","max_tokens":1000,"messages":[{"role":"user","content":"hello"}],"stream":false}`) + upstreamJSON := `{"id":"chatcmpl_ollama","object":"chat.completion","model":"deepseek-v4-flash","choices":[{"index":0,"message":{"role":"assistant","thinking":"abc","content":"final answer"},"finish_reason":"stop"}],"usage":{"prompt_tokens":3,"completion_tokens":5,"total_tokens":8}}` + rec, _ := runOllamaMessagesChatFallback(t, account, body, upstreamJSON, false) + require.Equal(t, "thinking", gjson.Get(rec.Body.String(), "content.0.type").String()) + require.Equal(t, "abc", gjson.Get(rec.Body.String(), "content.0.thinking").String()) + require.Equal(t, "text", gjson.Get(rec.Body.String(), "content.1.type").String()) + require.Equal(t, "final answer", gjson.Get(rec.Body.String(), "content.1.text").String()) +} + +func TestMessagesChatFallback_OfficialDeepSeek_Untouched(t *testing.T) { + official := officialDeepSeekTestAccount(704) + body := []byte(`{"model":"deepseek-v4-flash","max_tokens":256000,"messages":[{"role":"user","content":"hello"}],"stream":false}`) + // thinking 不归一化:转换器只认 reasoning_content/reasoning,thinking 被丢弃, + // 输出不出现 thinking 块(与不挂钩子的原始路径行为一致)。 + upstreamJSON := `{"id":"chatcmpl_official","object":"chat.completion","model":"deepseek-v4-flash","choices":[{"index":0,"message":{"role":"assistant","thinking":"abc","content":"final answer"},"finish_reason":"stop"}],"usage":{"prompt_tokens":3,"completion_tokens":5,"total_tokens":8}}` + rec, upstream := runOllamaMessagesChatFallback(t, official, body, upstreamJSON, false) + require.Equal(t, int64(256000), gjson.GetBytes(upstream.lastBody, "max_completion_tokens").Int()) + require.NotContains(t, rec.Body.String(), `"type":"thinking"`) + require.Equal(t, "final answer", gjson.Get(rec.Body.String(), "content.0.text").String()) +} + +func TestMessagesChatFallback_OllamaGLM_Untouched(t *testing.T) { + account := ollamaUpstreamTestAccount(PlatformDeepseek, 705) + body := []byte(`{"model":"glm-5.3-flash","max_tokens":256000,"messages":[{"role":"user","content":"hello"}],"stream":false}`) + upstreamJSON := `{"id":"chatcmpl_ollama","object":"chat.completion","model":"glm-5.3-flash","choices":[{"index":0,"message":{"role":"assistant","thinking":"abc","content":"final answer"},"finish_reason":"stop"}],"usage":{"prompt_tokens":3,"completion_tokens":5,"total_tokens":8}}` + rec, upstream := runOllamaMessagesChatFallback(t, account, body, upstreamJSON, false) + require.Equal(t, int64(256000), gjson.GetBytes(upstream.lastBody, "max_completion_tokens").Int()) + require.NotContains(t, rec.Body.String(), `"type":"thinking"`) + require.Equal(t, "final answer", gjson.Get(rec.Body.String(), "content.0.text").String()) +} diff --git a/backend/internal/service/openai_gateway_responses_chat_fallback.go b/backend/internal/service/openai_gateway_responses_chat_fallback.go index fabbcbc156..8b07a8f9d9 100644 --- a/backend/internal/service/openai_gateway_responses_chat_fallback.go +++ b/backend/internal/service/openai_gateway_responses_chat_fallback.go @@ -103,6 +103,9 @@ func (s *OpenAIGatewayService) forwardResponsesViaRawChatCompletions( } // /v1/responses 降级到 raw CC 的出站与 forwardAsRawChatCompletions 共用同一个 // 独立 Ollama Cloud token 钩子;chatReq.Model 已是模型映射后的 upstreamModel。 + // reasoning 归一化与 raw 路径同序:先归一化 request(历史 assistant 消息的 + // reasoning_content → reasoning)再 clamp max_tokens。 + chatBody = applyOllamaCloudRawChatCompletionsRequest(account, upstreamModel, chatBody) chatBody = clampOllamaCloudUpstreamMaxTokens(account, chatBody) // Keep the final outbound tier for usage-time reconciliation. A policy // filter that removes the field therefore leaves this nil. @@ -137,14 +140,15 @@ func (s *OpenAIGatewayService) forwardResponsesViaRawChatCompletions( } if clientStream { - return s.streamChatCompletionsAsResponses(c, resp, originalModel, customTools, functionTools, toolSearch, namespaceTools, billingModel, upstreamModel, reasoningEffort, serviceTier, startTime) + return s.streamChatCompletionsAsResponses(c, resp, account, originalModel, customTools, functionTools, toolSearch, namespaceTools, billingModel, upstreamModel, reasoningEffort, serviceTier, startTime) } - return s.bufferChatCompletionsAsResponses(c, resp, originalModel, customTools, functionTools, toolSearch, namespaceTools, billingModel, upstreamModel, reasoningEffort, serviceTier, startTime) + return s.bufferChatCompletionsAsResponses(c, resp, account, originalModel, customTools, functionTools, toolSearch, namespaceTools, billingModel, upstreamModel, reasoningEffort, serviceTier, startTime) } func (s *OpenAIGatewayService) bufferChatCompletionsAsResponses( c *gin.Context, resp *http.Response, + account *Account, originalModel string, customTools map[string]bool, functionTools map[string]bool, @@ -157,7 +161,7 @@ func (s *OpenAIGatewayService) bufferChatCompletionsAsResponses( startTime time.Time, ) (*OpenAIForwardResult, error) { requestID := resp.Header.Get("x-request-id") - ccResp, usage, err := s.readCCUpstreamJSONResponse(c, resp, writeOpenAIResponsesFallbackError) + ccResp, usage, err := s.readCCUpstreamJSONResponse(c, resp, account, upstreamModel, writeOpenAIResponsesFallbackError) if err != nil { return nil, err } @@ -187,6 +191,7 @@ func (s *OpenAIGatewayService) bufferChatCompletionsAsResponses( func (s *OpenAIGatewayService) streamChatCompletionsAsResponses( c *gin.Context, resp *http.Response, + account *Account, originalModel string, customTools map[string]bool, functionTools map[string]bool, @@ -234,7 +239,7 @@ func (s *OpenAIGatewayService) streamChatCompletionsAsResponses( c.Writer.Flush() } - scan := s.scanCCStream(c, resp, "openai responses chat fallback", requestID, startTime, func(chunk *apicompat.ChatCompletionsChunk) { + scan := s.scanCCStream(c, resp, account, upstreamModel, "openai responses chat fallback", requestID, startTime, func(chunk *apicompat.ChatCompletionsChunk) { events := apicompat.ChatCompletionsChunkToResponsesEvents(chunk, state) s.cacheReasoningItemsFromEvents(events) writeEvents(events) diff --git a/backend/internal/service/openai_gateway_responses_chat_fallback_ollama_test.go b/backend/internal/service/openai_gateway_responses_chat_fallback_ollama_test.go new file mode 100644 index 0000000000..9b3ff2fde1 --- /dev/null +++ b/backend/internal/service/openai_gateway_responses_chat_fallback_ollama_test.go @@ -0,0 +1,148 @@ +//go:build unit + +package service + +import ( + "bytes" + "context" + "io" + "net/http" + "net/http/httptest" + "regexp" + "strings" + "testing" + + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" +) + +// runOllamaResponsesChatFallback 直接走 /v1/responses → raw CC 降级桥 +// forwardResponsesViaRawChatCompletions(与 raw 路径测试同风格,直接调桥函数)。 +func runOllamaResponsesChatFallback(t *testing.T, account *Account, body []byte, upstreamBody string, stream bool) (*httptest.ResponseRecorder, *httpUpstreamRecorder) { + t.Helper() + gin.SetMode(gin.TestMode) + contentType := "application/json" + if stream { + contentType = "text/event-stream" + } + upstreamResp := &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{ + "Content-Type": []string{contentType}, + "x-request-id": []string{"rid_ollama_responses_fallback"}, + }, + Body: io.NopCloser(strings.NewReader(upstreamBody)), + } + upstream := &httpUpstreamRecorder{resp: upstreamResp} + svc := &OpenAIGatewayService{ + cfg: rawChatCompletionsTestConfig(), + httpUpstream: upstream, + } + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", bytes.NewReader(body)) + c.Request.Header.Set("Content-Type", "application/json") + result, err := svc.forwardResponsesViaRawChatCompletions(context.Background(), c, account, body) + require.NoError(t, err) + require.NotNil(t, result) + return rec, upstream +} + +func TestResponsesChatFallback_OllamaDeepSeek_ClampMaxOutputTokens(t *testing.T) { + account := ollamaUpstreamTestAccount(PlatformDeepseek, 601) + + t.Run("256000 clamps to 65535", func(t *testing.T) { + body := []byte(`{"model":"deepseek-v4-flash","input":"hello","max_output_tokens":256000,"stream":false}`) + upstreamJSON := `{"id":"chatcmpl_ollama","object":"chat.completion","model":"deepseek-v4-flash","choices":[{"index":0,"message":{"role":"assistant","content":"hi"},"finish_reason":"stop"}],"usage":{"prompt_tokens":3,"completion_tokens":5,"total_tokens":8}}` + _, upstream := runOllamaResponsesChatFallback(t, account, body, upstreamJSON, false) + require.Equal(t, "deepseek-v4-flash", gjson.GetBytes(upstream.lastBody, "model").String()) + require.Equal(t, int64(65535), gjson.GetBytes(upstream.lastBody, "max_completion_tokens").Int()) + }) + + t.Run("1000 stays 1000", func(t *testing.T) { + body := []byte(`{"model":"deepseek-v4-flash","input":"hello","max_output_tokens":1000,"stream":false}`) + upstreamJSON := `{"id":"chatcmpl_ollama","object":"chat.completion","model":"deepseek-v4-flash","choices":[{"index":0,"message":{"role":"assistant","content":"hi"},"finish_reason":"stop"}],"usage":{"prompt_tokens":3,"completion_tokens":5,"total_tokens":8}}` + _, upstream := runOllamaResponsesChatFallback(t, account, body, upstreamJSON, false) + require.Equal(t, int64(1000), gjson.GetBytes(upstream.lastBody, "max_completion_tokens").Int()) + }) +} + +// TestResponsesChatFallback_OllamaDeepSeek_ReasoningAliasStreaming 验证流式响应侧 +// 归一化:上游 delta.reasoning / delta.thinking 与官方形态 delta.reasoning_content +// 在归一化之后产出完全相同的 reasoning 输出(同一转换路径跑多个输入对比)。 +// normalizeStreamIDs 抹平响应里每次运行随机生成的 item id 与 created_at 时间戳, +// 使两条输入路径的 SSE 输出可做语义级字节比较。 +var normalizeStreamIDs = regexp.MustCompile(`("item_[0-9a-f]+"|"created_at":[0-9]+)`) + +func TestResponsesChatFallback_OllamaDeepSeek_ReasoningAliasStreaming(t *testing.T) { + account := ollamaUpstreamTestAccount(PlatformDeepseek, 602) + body := []byte(`{"model":"deepseek-v4-flash","input":"hello","max_output_tokens":1000,"stream":true}`) + + run := func(reasoningField string) string { + upstreamBody := strings.Join([]string{ + `data: {"id":"chatcmpl_ollama","object":"chat.completion.chunk","model":"deepseek-v4-flash","choices":[{"index":0,"delta":{"role":"assistant"},"finish_reason":null}]}`, + "", + `data: {"id":"chatcmpl_ollama","object":"chat.completion.chunk","model":"deepseek-v4-flash","choices":[{"index":0,"delta":{` + reasoningField + `},"finish_reason":null}]}`, + "", + `data: {"id":"chatcmpl_ollama","object":"chat.completion.chunk","model":"deepseek-v4-flash","choices":[{"index":0,"delta":{"content":"final answer"},"finish_reason":null}]}`, + "", + `data: {"id":"chatcmpl_ollama","object":"chat.completion.chunk","model":"deepseek-v4-flash","choices":[],"usage":{"prompt_tokens":3,"completion_tokens":5,"total_tokens":8}}`, + "", + "data: [DONE]", + "", + }, "\n") + rec, _ := runOllamaResponsesChatFallback(t, account, body, upstreamBody, true) + return normalizeStreamIDs.ReplaceAllString(rec.Body.String(), `"item_x"`) + } + + baseline := run(`"reasoning_content":"abc"`) + require.Contains(t, baseline, "response.reasoning_summary_text.delta") + require.Contains(t, baseline, `"delta":"abc"`) + require.Contains(t, baseline, `"delta":"final answer"`) + for _, tc := range []struct { + name string + field string + }{ + {name: "delta.reasoning alias", field: `"reasoning":"abc"`}, + {name: "delta.thinking alias", field: `"thinking":"abc"`}, + } { + t.Run(tc.name, func(t *testing.T) { + require.Equal(t, baseline, run(tc.field), "归一化后输出必须与 reasoning_content 基线完全一致") + }) + } +} + +func TestResponsesChatFallback_OllamaDeepSeek_ThinkingAliasNonStreaming(t *testing.T) { + account := ollamaUpstreamTestAccount(PlatformDeepseek, 603) + body := []byte(`{"model":"deepseek-v4-flash","input":"hello","max_output_tokens":1000,"stream":false}`) + upstreamJSON := `{"id":"chatcmpl_ollama","object":"chat.completion","model":"deepseek-v4-flash","choices":[{"index":0,"message":{"role":"assistant","thinking":"abc","content":"final answer"},"finish_reason":"stop"}],"usage":{"prompt_tokens":3,"completion_tokens":5,"total_tokens":8}}` + rec, _ := runOllamaResponsesChatFallback(t, account, body, upstreamJSON, false) + require.Equal(t, "reasoning", gjson.Get(rec.Body.String(), "output.0.type").String()) + require.Equal(t, "abc", gjson.Get(rec.Body.String(), "output.0.summary.0.text").String()) + require.Equal(t, "final answer", gjson.Get(rec.Body.String(), "output.1.content.0.text").String()) +} + +func TestResponsesChatFallback_OfficialDeepSeek_Untouched(t *testing.T) { + official := officialDeepSeekTestAccount(604) + body := []byte(`{"model":"deepseek-v4-flash","input":"hello","max_output_tokens":256000,"stream":false}`) + // thinking 不归一化:转换器只认 reasoning_content/reasoning,thinking 被丢弃, + // 输出不出现 reasoning item(与不挂钩子的原始路径行为一致)。 + upstreamJSON := `{"id":"chatcmpl_official","object":"chat.completion","model":"deepseek-v4-flash","choices":[{"index":0,"message":{"role":"assistant","thinking":"abc","content":"final answer"},"finish_reason":"stop"}],"usage":{"prompt_tokens":3,"completion_tokens":5,"total_tokens":8}}` + rec, upstream := runOllamaResponsesChatFallback(t, official, body, upstreamJSON, false) + // 请求侧不被 clamp:max_completion_tokens 保持 256000。 + require.Equal(t, int64(256000), gjson.GetBytes(upstream.lastBody, "max_completion_tokens").Int()) + // 响应侧不归一化:输出只有 message item,没有 reasoning item。 + require.NotContains(t, rec.Body.String(), `"type":"reasoning"`) + require.Equal(t, "final answer", gjson.Get(rec.Body.String(), "output.0.content.0.text").String()) +} + +func TestResponsesChatFallback_OllamaGLM_Untouched(t *testing.T) { + account := ollamaUpstreamTestAccount(PlatformDeepseek, 605) + body := []byte(`{"model":"glm-5.3-flash","input":"hello","max_output_tokens":256000,"stream":false}`) + upstreamJSON := `{"id":"chatcmpl_ollama","object":"chat.completion","model":"glm-5.3-flash","choices":[{"index":0,"message":{"role":"assistant","thinking":"abc","content":"final answer"},"finish_reason":"stop"}],"usage":{"prompt_tokens":3,"completion_tokens":5,"total_tokens":8}}` + rec, upstream := runOllamaResponsesChatFallback(t, account, body, upstreamJSON, false) + require.Equal(t, int64(256000), gjson.GetBytes(upstream.lastBody, "max_completion_tokens").Int()) + require.NotContains(t, rec.Body.String(), `"type":"reasoning"`) + require.Equal(t, "final answer", gjson.Get(rec.Body.String(), "output.0.content.0.text").String()) +} From 3182f6d1ccaa8347cf93975f2a77d45369f72897 Mon Sep 17 00:00:00 2001 From: alfadb Date: Tue, 8 Sep 2026 16:26:26 +0800 Subject: [PATCH 08/81] fix(ollama): clamp DeepSeek max_output_tokens on all native Responses paths --- .../openai_gateway_chat_completions.go | 6 + .../service/openai_gateway_forward.go | 7 +- .../service/openai_gateway_messages.go | 6 + .../openai_gateway_ollama_cloud_max_tokens.go | 46 +++- ...ai_gateway_ollama_cloud_max_tokens_test.go | 203 ++++++++++++++++++ 5 files changed, 258 insertions(+), 10 deletions(-) diff --git a/backend/internal/service/openai_gateway_chat_completions.go b/backend/internal/service/openai_gateway_chat_completions.go index 7ffd20916f..ceba3252c6 100644 --- a/backend/internal/service/openai_gateway_chat_completions.go +++ b/backend/internal/service/openai_gateway_chat_completions.go @@ -371,6 +371,12 @@ func (s *OpenAIGatewayService) forwardAsChatCompletions( responsesBody = updatedBody responsesReq.ServiceTier = normalizedOpenAIServiceTierValue(gjson.GetBytes(responsesBody, "service_tier").String()) + // Ollama Cloud 原生 Responses 出站 clamp:与 /v1/responses 入站路径(Forward)同一 + // 判据(实际 Responses 上游为 ollama.com + 映射后的出站模型为 DeepSeek 系),在此 + // 转换路径(Chat Completions 入站 → Responses 出站)独立补齐,模型映射与服务层 + // 改写全部完成后、构建上游请求前最后一次改写 body。 + responsesBody = ollamaCloudClampResponsesMaxOutputTokensBody(account, upstreamModel, responsesBody) + // 5. Get access token token, _, err := s.GetAccessToken(ctx, account) if err != nil { diff --git a/backend/internal/service/openai_gateway_forward.go b/backend/internal/service/openai_gateway_forward.go index 78dd47afe6..131fd5a169 100644 --- a/backend/internal/service/openai_gateway_forward.go +++ b/backend/internal/service/openai_gateway_forward.go @@ -636,8 +636,13 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco // ollama.com 以 400 拒绝)。在 `!isCodexCLI` 归一化块之后独立调用:非 Codex 时 // 位于平台字段归一化之后,不跳过原有平台 switch(patch 按追加顺序应用,set 在 // 先前的 delete/set 之后生效);Codex 请求不做归一化,直接按 body 现值判定。 - if clampedCap, ok := ollamaCloudResponsesMaxOutputTokensClamp(account, upstreamModel, body); ok { + // 生效值来自 max_tokens(无 max_output_tokens 的非 openai 平台)时, + // markPatchDelete("max_tokens") 与第 601 行一样按追加顺序在 set 之后应用。 + if clampedCap, ok, sourceField := ollamaCloudResponsesMaxOutputTokensClamp(account, upstreamModel, body); ok { markPatchSet("max_output_tokens", clampedCap) + if sourceField == "max_tokens" { + markPatchDelete("max_tokens") + } } if wsDecision.Transport != OpenAIUpstreamTransportResponsesWebsocketV2 && !account.IsOpenAIApiKey() && gjson.GetBytes(body, "previous_response_id").Exists() { diff --git a/backend/internal/service/openai_gateway_messages.go b/backend/internal/service/openai_gateway_messages.go index a1ce80fc9d..307dabc274 100644 --- a/backend/internal/service/openai_gateway_messages.go +++ b/backend/internal/service/openai_gateway_messages.go @@ -348,6 +348,12 @@ func (s *OpenAIGatewayService) ForwardAsAnthropic( } } + // Ollama Cloud 原生 Responses 出站 clamp:与 /v1/responses 入站路径(Forward)同一 + // 判据(实际 Responses 上游为 ollama.com + 映射后的出站模型为 DeepSeek 系),在此 + // 转换路径(Anthropic Messages 入站 → Responses 出站)独立补齐,模型映射与服务层 + // 改写全部完成后、构建上游请求前最后一次改写 body。 + responsesBody = ollamaCloudClampResponsesMaxOutputTokensBody(account, upstreamModel, responsesBody) + // 5. Get access token token, _, err := s.getRequestCredential(ctx, c, account) if err != nil { diff --git a/backend/internal/service/openai_gateway_ollama_cloud_max_tokens.go b/backend/internal/service/openai_gateway_ollama_cloud_max_tokens.go index 4c69a32b23..bead0cf4fc 100644 --- a/backend/internal/service/openai_gateway_ollama_cloud_max_tokens.go +++ b/backend/internal/service/openai_gateway_ollama_cloud_max_tokens.go @@ -51,26 +51,54 @@ func ollamaCloudResponsesUpstreamBaseURL(account *Account) string { // ollamaCloudResponsesMaxOutputTokensClamp 是原生 /v1/responses 路径的 clamp:在 // 平台字段归一化之后独立调用,不改写原有的 max_output_tokens 平台 switch。判定: // 实际 Responses 上游(ollamaCloudResponsesUpstreamBaseURL)为 ollama.com 的 -// APIKey 账号 + 映射后的出站模型是 DeepSeek 系;openai 平台 max_tokens 刚被归一化 -// patch 到 max_output_tokens 时取 max_tokens 为生效值。未命中返回 ok=false。 +// APIKey 账号 + 映射后的出站模型是 DeepSeek 系;body 无 max_output_tokens 时回退读 +// max_tokens 为生效值(不限定平台——客户端按 Chat Completions 习惯只发 max_tokens +// 时,任何平台的 ollama+deepseek 命中判据都要 clamp)。返回 (cap, ok, sourceField), +// sourceField 为生效字段名("max_tokens" / ""),供调用方在值来自 max_tokens 时清除 +// 残留的 max_tokens。未命中返回 ok=false。 // 实测:ollama.com/v1/responses max_output_tokens=256000 被上游以 "max_tokens // (256000) exceeds model's maximum output tokens (65536)" 400 拒绝(DeepSeek 模型)。 -func ollamaCloudResponsesMaxOutputTokensClamp(account *Account, upstreamModel string, body []byte) (int64, bool) { +func ollamaCloudResponsesMaxOutputTokensClamp(account *Account, upstreamModel string, body []byte) (int64, bool, string) { if account == nil || account.Type != AccountTypeAPIKey || !isDeepSeekModel(upstreamModel) { - return 0, false + return 0, false, "" } if !isOllamaCloudBaseURL(ollamaCloudResponsesUpstreamBaseURL(account)) { - return 0, false + return 0, false, "" } value := gjson.GetBytes(body, "max_output_tokens") - if !value.Exists() && account.Platform == PlatformOpenAI { - value = gjson.GetBytes(body, "max_tokens") + sourceField := "" + if !value.Exists() { + if fallback := gjson.GetBytes(body, "max_tokens"); fallback.Exists() { + value = fallback + sourceField = "max_tokens" + } } cap := ollamaCloudMaxTokensCap(account) if cap <= 0 || !value.Exists() || value.Type != gjson.Number || value.Int() <= cap { - return 0, false + return 0, false, "" } - return cap, true + return cap, true, sourceField +} + +// ollamaCloudClampResponsesMaxOutputTokensBody 是原生 /v1/responses 出站 body 的 +// 字节级 clamp 应用(供 CC→Responses、Messages→Responses 转换路径使用):命中 +// ollama.com + DeepSeek 时把 max_output_tokens 改写为 cap,生效值来自 max_tokens 时 +// 一并清除残留的 max_tokens。未命中或改写失败时原样返回。 +func ollamaCloudClampResponsesMaxOutputTokensBody(account *Account, upstreamModel string, body []byte) []byte { + cap, ok, sourceField := ollamaCloudResponsesMaxOutputTokensClamp(account, upstreamModel, body) + if !ok { + return body + } + out, err := sjson.SetBytes(body, "max_output_tokens", cap) + if err != nil { + return body + } + if sourceField == "max_tokens" { + if stripped, err := sjson.DeleteBytes(out, "max_tokens"); err == nil { + out = stripped + } + } + return out } // ollamaCloudMaxTokensCap 返回账号配置的 max_tokens 上限。账号为 nil 或 extra 中 diff --git a/backend/internal/service/openai_gateway_ollama_cloud_max_tokens_test.go b/backend/internal/service/openai_gateway_ollama_cloud_max_tokens_test.go index 56bf922b3c..731cc03ea6 100644 --- a/backend/internal/service/openai_gateway_ollama_cloud_max_tokens_test.go +++ b/backend/internal/service/openai_gateway_ollama_cloud_max_tokens_test.go @@ -553,3 +553,206 @@ func TestForwardResponsesClampsOllamaCloudMaxOutputTokensForCodexClients(t *test }) } } + +// TestForwardResponses_DeepseekOllamaCloudClampsClientMaxTokensFallback 覆盖问题 1: +// 原生 /v1/responses 入站只带 max_tokens(无 max_output_tokens)的 deepseek 平台 +// ollama 账号,clamp 判据不限定平台——出站 patch 为 max_output_tokens=cap,并清除 +// 残留的 max_tokens。 +func TestForwardResponses_DeepseekOllamaCloudClampsClientMaxTokensFallback(t *testing.T) { + gin.SetMode(gin.TestMode) + + newAccount := func(id int64) *Account { + account := ollamaUpstreamTestAccount(PlatformDeepseek, id) + account.Credentials["api_protocol"] = APIProtocolResponses + return account + } + run := func(account *Account, body []byte) (*httpUpstreamRecorder, error) { + upstream := &httpUpstreamRecorder{err: errors.New("stop after capture")} + svc := &OpenAIGatewayService{cfg: rawChatCompletionsTestConfig(), httpUpstream: upstream} + _, err := svc.Forward(context.Background(), adaptiveProtocolTestContext("/v1/responses", body), account, body) + return upstream, err + } + + t.Run("max_tokens above cap is clamped and removed", func(t *testing.T) { + account := newAccount(351) + body := []byte(`{"model":"deepseek-v4-flash","input":"Reply with exactly OK and nothing else.","max_tokens":256000,"stream":false}`) + upstream, err := run(account, body) + require.Error(t, err) + require.Equal(t, "https://ollama.com/v1/responses", upstream.lastReq.URL.String()) + require.Equal(t, int64(65535), gjson.GetBytes(upstream.lastBody, "max_output_tokens").Int()) + require.False(t, gjson.GetBytes(upstream.lastBody, "max_tokens").Exists()) + }) + + t.Run("max_tokens at or below cap is not rewritten", func(t *testing.T) { + account := newAccount(352) + body := []byte(`{"model":"deepseek-v4-flash","input":"Reply with exactly OK and nothing else.","max_tokens":1000,"stream":false}`) + upstream, err := run(account, body) + require.Error(t, err) + require.False(t, gjson.GetBytes(upstream.lastBody, "max_output_tokens").Exists()) + // 既有行为:非 openai 平台只发 max_tokens(≤cap)时残留 max_tokens,本次不处理。 + require.Equal(t, int64(1000), gjson.GetBytes(upstream.lastBody, "max_tokens").Int()) + }) +} + +// TestForwardAsChatCompletions_DeepseekOllamaCloudClampsMaxOutputTokens 覆盖问题 2 的 +// CC 入站路径:/v1/chat/completions 入站、账号出站协议为原生 Responses 时,转换生成的 +// max_output_tokens 在发出前被 clamp;≤cap 保持转换后的原值。 +func TestForwardAsChatCompletions_DeepseekOllamaCloudClampsMaxOutputTokens(t *testing.T) { + gin.SetMode(gin.TestMode) + + newAccount := func(id int64) *Account { + account := ollamaUpstreamTestAccount(PlatformDeepseek, id) + account.Credentials["api_protocol"] = APIProtocolResponses + return account + } + run := func(account *Account, body []byte) (*httpUpstreamRecorder, error) { + upstream := &httpUpstreamRecorder{err: errors.New("stop after capture")} + svc := &OpenAIGatewayService{cfg: rawChatCompletionsTestConfig(), httpUpstream: upstream} + _, err := svc.ForwardAsChatCompletions(context.Background(), adaptiveProtocolTestContext("/v1/chat/completions", body), account, body, "", "") + return upstream, err + } + + t.Run("max_tokens above cap is clamped", func(t *testing.T) { + account := newAccount(361) + body := []byte(`{"model":"deepseek-chat","max_tokens":256000,"messages":[{"role":"user","content":"hi"}],"stream":false}`) + upstream, err := run(account, body) + require.Error(t, err) + require.Equal(t, "https://ollama.com/v1/responses", upstream.lastReq.URL.String()) + require.Equal(t, "deepseek-chat", gjson.GetBytes(upstream.lastBody, "model").String()) + require.Equal(t, int64(65535), gjson.GetBytes(upstream.lastBody, "max_output_tokens").Int()) + }) + + t.Run("max_tokens at or below cap is preserved", func(t *testing.T) { + account := newAccount(362) + body := []byte(`{"model":"deepseek-chat","max_tokens":1000,"messages":[{"role":"user","content":"hi"}],"stream":false}`) + upstream, err := run(account, body) + require.Error(t, err) + require.Equal(t, int64(1000), gjson.GetBytes(upstream.lastBody, "max_output_tokens").Int()) + }) +} + +// TestForwardAsAnthropic_DeepseekOllamaCloudClampsMaxOutputTokens 覆盖问题 2 的 +// Messages 入站路径:/v1/messages 入站、账号出站协议为原生 Responses 时,转换生成的 +// max_output_tokens 在发出前被 clamp;≤cap 保持转换后的原值。 +func TestForwardAsAnthropic_DeepseekOllamaCloudClampsMaxOutputTokens(t *testing.T) { + gin.SetMode(gin.TestMode) + + newAccount := func(id int64) *Account { + account := ollamaUpstreamTestAccount(PlatformDeepseek, id) + account.Credentials["api_protocol"] = APIProtocolResponses + return account + } + run := func(account *Account, body []byte) (*httpUpstreamRecorder, error) { + upstream := &httpUpstreamRecorder{err: errors.New("stop after capture")} + svc := &OpenAIGatewayService{cfg: rawChatCompletionsTestConfig(), httpUpstream: upstream} + _, err := svc.ForwardAsAnthropic(context.Background(), adaptiveProtocolTestContext("/v1/messages", body), account, body, "", "") + return upstream, err + } + + t.Run("max_tokens above cap is clamped", func(t *testing.T) { + account := newAccount(371) + body := []byte(`{"model":"deepseek-chat","max_tokens":256000,"messages":[{"role":"user","content":"hi"}],"stream":false}`) + upstream, err := run(account, body) + require.Error(t, err) + require.Equal(t, "https://ollama.com/v1/responses", upstream.lastReq.URL.String()) + require.Equal(t, "deepseek-chat", gjson.GetBytes(upstream.lastBody, "model").String()) + require.Equal(t, int64(65535), gjson.GetBytes(upstream.lastBody, "max_output_tokens").Int()) + }) + + t.Run("max_tokens at or below cap is preserved", func(t *testing.T) { + account := newAccount(372) + body := []byte(`{"model":"deepseek-chat","max_tokens":1000,"messages":[{"role":"user","content":"hi"}],"stream":false}`) + upstream, err := run(account, body) + require.Error(t, err) + require.Equal(t, int64(1000), gjson.GetBytes(upstream.lastBody, "max_output_tokens").Int()) + }) +} + +// TestResponsesPathNotClampedForOfficialDeepseekOrNonDeepSeekModel 对照用例(问题 1/2): +// 官方 deepseek(api.deepseek.com)与 ollama.com + 非 DeepSeek 模型的账号,同一判据不 +// 命中——三个出站入口的出站 body 保持 256000、不做任何改写。 +func TestResponsesPathNotClampedForOfficialDeepseekOrNonDeepSeekModel(t *testing.T) { + gin.SetMode(gin.TestMode) + + type entry struct { + name string + path string + body []byte + forward func(*OpenAIGatewayService, *gin.Context, *Account, []byte) error + } + entries := []entry{ + { + name: "responses ingress", + path: "/v1/responses", + body: []byte(`{"model":"deepseek-v4-flash","input":"Reply with exactly OK and nothing else.","max_tokens":256000,"stream":false}`), + forward: func(svc *OpenAIGatewayService, c *gin.Context, account *Account, body []byte) error { + _, err := svc.Forward(context.Background(), c, account, body) + return err + }, + }, + { + name: "chat completions ingress", + path: "/v1/chat/completions", + body: []byte(`{"model":"deepseek-chat","max_tokens":256000,"messages":[{"role":"user","content":"hi"}],"stream":false}`), + forward: func(svc *OpenAIGatewayService, c *gin.Context, account *Account, body []byte) error { + _, err := svc.ForwardAsChatCompletions(context.Background(), c, account, body, "", "") + return err + }, + }, + { + name: "messages ingress", + path: "/v1/messages", + body: []byte(`{"model":"deepseek-chat","max_tokens":256000,"messages":[{"role":"user","content":"hi"}],"stream":false}`), + forward: func(svc *OpenAIGatewayService, c *gin.Context, account *Account, body []byte) error { + _, err := svc.ForwardAsAnthropic(context.Background(), c, account, body, "", "") + return err + }, + }, + } + + run := func(account *Account, e entry) *httpUpstreamRecorder { + upstream := &httpUpstreamRecorder{err: errors.New("stop after capture")} + svc := &OpenAIGatewayService{cfg: rawChatCompletionsTestConfig(), httpUpstream: upstream} + err := e.forward(svc, adaptiveProtocolTestContext(e.path, e.body), account, e.body) + require.Error(t, err) + return upstream + } + + t.Run("official deepseek keeps 256000", func(t *testing.T) { + account := officialDeepSeekTestAccount(381) + account.Credentials["api_protocol"] = APIProtocolResponses + for _, e := range entries { + t.Run(e.name, func(t *testing.T) { + upstream := run(account, e) + require.Equal(t, "https://api.deepseek.com/responses", upstream.lastReq.URL.String()) + // 原生 Responses 入站只发 max_tokens 时保持原样(无 max_output_tokens); + // 转换路径经转换器生成 max_output_tokens=256000,均不做 clamp。 + if out := gjson.GetBytes(upstream.lastBody, "max_output_tokens"); out.Exists() { + require.Equal(t, int64(256000), out.Int()) + } else { + require.Equal(t, int64(256000), gjson.GetBytes(upstream.lastBody, "max_tokens").Int()) + } + }) + } + }) + + t.Run("ollama account with non-deepseek model keeps 256000", func(t *testing.T) { + account := ollamaUpstreamTestAccount(PlatformDeepseek, 382) + account.Credentials["api_protocol"] = APIProtocolResponses + glmEntries := entries + glmEntries[0].body = []byte(`{"model":"glm-5.3-flash","input":"Reply with exactly OK and nothing else.","max_tokens":256000,"stream":false}`) + glmEntries[1].body = []byte(`{"model":"glm-5.3-flash","max_tokens":256000,"messages":[{"role":"user","content":"hi"}],"stream":false}`) + glmEntries[2].body = []byte(`{"model":"glm-5.3-flash","max_tokens":256000,"messages":[{"role":"user","content":"hi"}],"stream":false}`) + for _, e := range glmEntries { + t.Run(e.name, func(t *testing.T) { + upstream := run(account, e) + require.Equal(t, "https://ollama.com/v1/responses", upstream.lastReq.URL.String()) + if out := gjson.GetBytes(upstream.lastBody, "max_output_tokens"); out.Exists() { + require.Equal(t, int64(256000), out.Int()) + } else { + require.Equal(t, int64(256000), gjson.GetBytes(upstream.lastBody, "max_tokens").Int()) + } + }) + } + }) +} From 0d22f90e04909b17f3efb4324633570409b9e1f4 Mon Sep 17 00:00:00 2001 From: alfadb Date: Sat, 12 Sep 2026 21:38:33 +0800 Subject: [PATCH 09/81] feat(platform): wire ollama_cloud into scheduling and routing MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 增量 2(⑥ 组 + ⑨ 组,严格同批): ⑥ adaptive 准入 / 协议路由 / base 守卫: - A9/A13: IsOllamaCloud 谓词 + Account.IsOllamaCloud(); IsMultiProtocolAPIKeyProvider 纳入 ollama_cloud(adaptive 总开关) - A11: GetAPIProtocol 缺省档扩为 opencode_go || ollama_cloud → adaptive - A7/A10 + C30/Q2-3: DefaultOllamaCloudBaseURL(https://ollama.com/v1) / DefaultOllamaCloudAnthropicBaseURL(https://ollama.com),并补 GetOpenAIBaseURL 与 defaultCNProtocolBaseURL 的平台分支 - C33/Q2-4 + S6 层 1: GetOpenAIBaseURL 平台守卫纳入 ollama_cloud; 多协议账号缺省端点不再回落 https://api.openai.com - C32: shouldForwardOpenAIResponsesViaRawChatCompletions 新增 ollama_cloud 分支(不复用 opencode 的恒 false) - S5: nativeAnthropicTargetURL 改用版本感知 buildOpenAIEndpointURL, 删除 opencode_go 特判(消灭 /v1/v1/messages) - S6 层 2: CC / Responses / passthrough 三处 OpenAI 官方域名兜底 对多协议账号改为显式报错(防凭据外泄) ⑨ count_tokens(必须与 C40 同批): - findings B1: openai_gateway_count_tokens.go 本地估算分支加入 IsOllamaCloud()(命中时不产生任何出站请求) - C40: routes/gateway.go 的 responses 兼容白名单与 count_tokens 分派白名单加入 service.PlatformOllamaCloud 新增单测 ollama_cloud_platform_routing_test.go: 默认协议/base、nativeAnthropicTargetURL 带与不带 /v1 双向、C32 分流、 count_tokens 本地估算零出站。 --- backend/internal/server/routes/gateway.go | 6 +- backend/internal/service/account.go | 31 ++- backend/internal/service/domain_constants.go | 13 +- .../ollama_cloud_platform_routing_test.go | 217 ++++++++++++++++++ .../service/openai_gateway_cc_pipeline.go | 5 + .../service/openai_gateway_count_tokens.go | 7 +- .../service/openai_gateway_forward.go | 17 ++ ...penai_gateway_messages_anthropic_native.go | 9 +- .../service/openai_gateway_passthrough.go | 4 + 9 files changed, 291 insertions(+), 18 deletions(-) create mode 100644 backend/internal/service/ollama_cloud_platform_routing_test.go diff --git a/backend/internal/server/routes/gateway.go b/backend/internal/server/routes/gateway.go index f27a172d03..b3bfd9cba4 100644 --- a/backend/internal/server/routes/gateway.go +++ b/backend/internal/server/routes/gateway.go @@ -46,6 +46,8 @@ func RegisterGatewayRoutes( // 保证校验发生在合成路由改写与调度之前,且只看客户端书写的模型名。 groupModelAllowlist := middleware.GroupModelAllowlist() + // 单目标与账号池统一走 dispatcher:池候选全属 OpenAI 兼容族进 OpenAI + // CountTokens,其余(跨族池 / 非兼容族单目标)落通用网关。 countTokensHandler := func(c *gin.Context) { dispatchOpenAICompatibleCountTokens(c, h.OpenAIGateway.CountTokens, h.OpenAIGateway.GrokCountTokens, h.Gateway.CountTokens) } @@ -511,7 +513,7 @@ func isOpenAICompatibleGatewayFamilyPlatform(platform string) bool { switch platform { case service.PlatformOpenAI, service.PlatformGrok, service.PlatformKimi, service.PlatformZhipu, service.PlatformDeepseek, - service.PlatformMiniMax, service.PlatformOpenCodeGo: + service.PlatformMiniMax, service.PlatformOpenCodeGo, service.PlatformOllamaCloud: // 国产 OpenAI 兼容供应商与 openai/grok 一样经 OpenAI 网关转发。 return true default: @@ -610,7 +612,7 @@ func dispatchOpenAICompatibleCountTokens(c *gin.Context, compatibleHandler, grok return } switch getGroupPlatform(c) { - case service.PlatformOpenAI, service.PlatformKimi, service.PlatformZhipu, service.PlatformDeepseek, service.PlatformMiniMax, service.PlatformOpenCodeGo: + case service.PlatformOpenAI, service.PlatformKimi, service.PlatformZhipu, service.PlatformDeepseek, service.PlatformMiniMax, service.PlatformOpenCodeGo, service.PlatformOllamaCloud: compatibleHandler(c) case service.PlatformGrok: grokHandler(c) diff --git a/backend/internal/service/account.go b/backend/internal/service/account.go index 5262134a2b..2e628cff4d 100644 --- a/backend/internal/service/account.go +++ b/backend/internal/service/account.go @@ -299,6 +299,11 @@ func (a *Account) IsCNProvider() bool { return a != nil && IsCNProvider(a.Platform) } +// IsOllamaCloud 报告账号平台是否为 Ollama Cloud。 +func (a *Account) IsOllamaCloud() bool { + return a != nil && IsOllamaCloud(a.Platform) +} + // IsOpenAICompatible 报告账号是否走 OpenAI 网关(OpenAI 协议族)。 // openai/grok 原生走 OpenAI 网关;国产供应商同为 OpenAI Chat Completions // 兼容上游,也经 OpenAI 网关转发。OpenCode 同样经 OpenAI 网关按模型分流。 @@ -1381,10 +1386,10 @@ func (a *Account) IsOpenAIApiKey() bool { } // GetOpenAIBaseURL 解析 OpenAI 协议族账号的上游 base_url。 -// 适用 openai、国产 OpenAI 兼容供应商(kimi/zhipu/deepseek)与 OpenCode Go; -// grok 走 GetGrokBaseURL,此处对 grok 返回 "" 以保持原有行为。 +// 适用 openai、国产 OpenAI 兼容供应商(kimi/zhipu/deepseek)、OpenCode Go 与 +// Ollama Cloud;grok 走 GetGrokBaseURL,此处对 grok 返回 "" 以保持原有行为。 func (a *Account) GetOpenAIBaseURL() string { - if !a.IsOpenAI() && !a.IsCNProvider() && !a.IsOpenCodeGo() { + if !a.IsOpenAI() && !a.IsCNProvider() && !a.IsOpenCodeGo() && !a.IsOllamaCloud() { return "" } if a.IsMultiProtocolAPIKey() && a.IsAdaptiveAPIProtocol() { @@ -1417,7 +1422,14 @@ func (a *Account) GetOpenAIBaseURL() string { return DefaultMiniMaxBaseURL case PlatformOpenCodeGo: return a.openCodeDefaultChatBaseURL() + case PlatformOllamaCloud: + return DefaultOllamaCloudBaseURL default: + if a.IsMultiProtocolAPIKey() { + // 多协议网关(CN / OpenCode / Ollama Cloud)的缺省端点必须由上面的平台 + // 分支显式给出:回落官方域名会把第三方 key 明文发到 api.openai.com。 + return "" + } return "https://api.openai.com" } } @@ -1440,10 +1452,11 @@ func (a *Account) IsCodingPlan() bool { return a.GetAccountMode() == AccountModeCoding } -// GetAPIProtocol 返回国产供应商账号的上游 API 协议。存储于 +// GetAPIProtocol 返回多协议 API Key 账号的上游 API 协议。存储于 // credentials["api_protocol"];缺失或与平台不匹配时回退 chat_completions -// (与既有行为完全一致)。responses 协议仅 deepseek / kimi / minimax 支持(官方原生 -// Responses 端点,适配 Codex);zhipu 无此端点。 +// (与既有行为完全一致),opencode_go / ollama_cloud 例外:缺省为 adaptive +// (按入站协议选择供应商原生端点)。responses 协议仅 deepseek / kimi / minimax 支持 +// (官方原生 Responses 端点,适配 Codex);zhipu 无此端点。 func (a *Account) GetAPIProtocol() string { if a == nil || !a.IsMultiProtocolAPIKey() { return APIProtocolChatCompletions @@ -1460,7 +1473,7 @@ func (a *Account) GetAPIProtocol() string { case APIProtocolChatCompletions: return APIProtocolChatCompletions } - if a.IsOpenCodeGo() { + if a.IsOpenCodeGo() || a.IsOllamaCloud() { return APIProtocolAdaptive } return APIProtocolChatCompletions @@ -1539,6 +1552,8 @@ func (a *Account) defaultCNProtocolBaseURL(protocol string) string { return DefaultMiniMaxAnthropicBaseURL case PlatformOpenCodeGo: return a.openCodeDefaultAnthropicBaseURL() + case PlatformOllamaCloud: + return DefaultOllamaCloudAnthropicBaseURL } case APIProtocolChatCompletions, APIProtocolResponses: switch a.Platform { @@ -1558,6 +1573,8 @@ func (a *Account) defaultCNProtocolBaseURL(protocol string) string { return DefaultMiniMaxBaseURL case PlatformOpenCodeGo: return a.openCodeDefaultChatBaseURL() + case PlatformOllamaCloud: + return DefaultOllamaCloudBaseURL } } return "" diff --git a/backend/internal/service/domain_constants.go b/backend/internal/service/domain_constants.go index 02a6c87490..df3396a66a 100644 --- a/backend/internal/service/domain_constants.go +++ b/backend/internal/service/domain_constants.go @@ -88,6 +88,8 @@ const ( DefaultOpenCodeGoBaseURL = "https://opencode.ai/zen/go/v1" // OpenCode Zen:按量付费网关,模型列表为 /zen/v1/models。 DefaultOpenCodeZenBaseURL = "https://opencode.ai/zen/v1" + // Ollama Cloud:Chat Completions / Responses 共用带 /v1 的基址。 + DefaultOllamaCloudBaseURL = "https://ollama.com/v1" ) // 国产供应商 Anthropic 协议端点的默认 base_url(上游路径为 {base}/v1/messages)。 @@ -101,6 +103,8 @@ const ( // OpenCode Go Anthropic 基址不含 /v1:nativeAnthropicTargetURL 会再拼 /v1/messages。 DefaultOpenCodeGoAnthropicBaseURL = "https://opencode.ai/zen/go" DefaultOpenCodeZenAnthropicBaseURL = "https://opencode.ai/zen" + // Ollama Cloud Anthropic 基址不含 /v1:nativeAnthropicTargetURL 会再拼 /v1/messages。 + DefaultOllamaCloudAnthropicBaseURL = "https://ollama.com" ) // IsCNProvider 报告 platform 是否为国产 OpenAI 兼容供应商(kimi/zhipu/deepseek/minimax)。 @@ -118,10 +122,15 @@ func IsOpenCodeGo(platform string) bool { return platform == PlatformOpenCodeGo } +// IsOllamaCloud 报告 platform 是否为 Ollama Cloud 多协议 API Key 网关。 +func IsOllamaCloud(platform string) bool { + return platform == PlatformOllamaCloud +} + // IsMultiProtocolAPIKeyProvider 报告 platform 是否为多协议 API Key 网关 -// (国产供应商 + OpenCode):走 OpenAI 网关、支持 adaptive 协议分流。 +// (国产供应商 + OpenCode + Ollama Cloud):走 OpenAI 网关、支持 adaptive 协议分流。 func IsMultiProtocolAPIKeyProvider(platform string) bool { - return IsCNProvider(platform) || platform == PlatformOpenCodeGo + return IsCNProvider(platform) || platform == PlatformOpenCodeGo || IsOllamaCloud(platform) } // AllowedQuotaPlatforms 是允许设置 user × platform quota 的平台列表(单一权威来源)。 diff --git a/backend/internal/service/ollama_cloud_platform_routing_test.go b/backend/internal/service/ollama_cloud_platform_routing_test.go new file mode 100644 index 0000000000..01222e2ee7 --- /dev/null +++ b/backend/internal/service/ollama_cloud_platform_routing_test.go @@ -0,0 +1,217 @@ +package service + +import ( + "bytes" + "context" + "errors" + "net/http" + "net/http/httptest" + "testing" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" +) + +// ollamaCloudRoutingTestService 返回仅配置宽松 URL 白名单的 service,用于只验证 +// 出站 URL 组装,不发起真实请求。 +func ollamaCloudRoutingTestService() *OpenAIGatewayService { + return &OpenAIGatewayService{ + cfg: &config.Config{Security: config.SecurityConfig{URLAllowlist: config.URLAllowlistConfig{ + Enabled: false, + AllowInsecureHTTP: true, + }}}, + } +} + +// TestOllamaCloudDefaultProtocolAndBaseURLs 覆盖 A9/A11/A13 + C30/Q2-3 + C33/Q2-4: +// ollama_cloud 属多协议网关、api_protocol 缺省为 adaptive,且 anthropic 默认 base +// 不带 /v1 而 cc/responses 带 /v1;任何情况下都不得回落到 api.openai.com。 +func TestOllamaCloudDefaultProtocolAndBaseURLs(t *testing.T) { + account := &Account{ + ID: 900, + Name: "ollama-cloud-default", + Platform: PlatformOllamaCloud, + Type: AccountTypeAPIKey, + Credentials: map[string]any{"api_key": "sk-test"}, + Extra: map[string]any{}, + } + + require.True(t, account.IsOllamaCloud()) + require.True(t, IsOllamaCloud(PlatformOllamaCloud)) + require.True(t, IsMultiProtocolAPIKeyProvider(PlatformOllamaCloud)) + require.True(t, account.IsMultiProtocolAPIKey()) + + // A11:api_protocol 缺失时 ollama_cloud 缺省 adaptive(不是 CC)。 + require.Equal(t, APIProtocolAdaptive, account.GetAPIProtocol()) + require.True(t, account.IsAdaptiveAPIProtocol()) + + // C30/Q2-3:anthropic 默认 base 不带 /v1;cc/responses 带 /v1。 + require.Equal(t, "https://ollama.com", account.defaultCNProtocolBaseURL(APIProtocolAnthropic)) + require.Equal(t, "https://ollama.com/v1", account.defaultCNProtocolBaseURL(APIProtocolChatCompletions)) + require.Equal(t, "https://ollama.com/v1", account.defaultCNProtocolBaseURL(APIProtocolResponses)) + + // 同一结论经 adaptive 解析链(api_base_urls / base_url 均缺失)。 + require.Equal(t, "https://ollama.com", account.GetCNProtocolBaseURL(APIProtocolAnthropic)) + require.Equal(t, "https://ollama.com/v1", account.GetCNProtocolBaseURL(APIProtocolChatCompletions)) + require.Equal(t, "https://ollama.com/v1", account.GetCNProtocolBaseURL(APIProtocolResponses)) + require.Equal(t, "https://ollama.com", account.GetAnthropicProtocolBaseURL()) + + // C33/Q2-4 + S6 层 1:OpenAI 协议 base 守卫必须接受 ollama_cloud, + // 且缺省端点绝不是官方域名。 + require.Equal(t, DefaultOllamaCloudBaseURL, account.GetOpenAIBaseURL()) + require.NotEqual(t, "https://api.openai.com", account.GetOpenAIBaseURL()) + + // adaptive 下 anthropic 段没有 credentials.base_url 回退,CC 段有。 + withBase := &Account{ + ID: 901, + Name: "ollama-cloud-base-url", + Platform: PlatformOllamaCloud, + Type: AccountTypeAPIKey, + Credentials: map[string]any{ + "api_key": "sk-test", + "base_url": "https://proxy.example/v1", + }, + Extra: map[string]any{}, + } + require.Equal(t, "https://proxy.example/v1", withBase.GetOpenAIBaseURL()) + require.Equal(t, "https://proxy.example/v1", withBase.GetCNProtocolBaseURL(APIProtocolChatCompletions)) + require.Equal(t, "https://ollama.com", withBase.GetCNProtocolBaseURL(APIProtocolAnthropic)) + require.Equal(t, "https://ollama.com/v1", withBase.GetCNProtocolBaseURL(APIProtocolResponses)) +} + +// TestNativeAnthropicTargetURLOllamaCloudVersionAware 覆盖 S5:nativeAnthropicTargetURL +// 改用版本感知拼接后,base 带 /v1 与不带 /v1 都得到同一个 {base}/v1/messages。 +func TestNativeAnthropicTargetURLOllamaCloudVersionAware(t *testing.T) { + svc := ollamaCloudRoutingTestService() + + cases := []struct { + name string + apiProtocol string + baseURL string + anthropicBase string + want string + }{ + { + name: "explicit anthropic base without version suffix", + apiProtocol: APIProtocolAnthropic, + baseURL: "https://ollama.com", + want: "https://ollama.com/v1/messages", + }, + { + name: "explicit anthropic base with version suffix", + apiProtocol: APIProtocolAnthropic, + baseURL: "https://ollama.com/v1", + want: "https://ollama.com/v1/messages", + }, + { + name: "explicit anthropic base trailing slash", + apiProtocol: APIProtocolAnthropic, + baseURL: "https://ollama.com/", + want: "https://ollama.com/v1/messages", + }, + { + name: "adaptive api_base_urls anthropic with version suffix", + apiProtocol: APIProtocolAdaptive, + anthropicBase: "https://ollama.com/v1", + want: "https://ollama.com/v1/messages", + }, + { + name: "adaptive api_base_urls anthropic without version suffix", + apiProtocol: APIProtocolAdaptive, + anthropicBase: "https://ollama.com", + want: "https://ollama.com/v1/messages", + }, + } + + for _, tt := range cases { + t.Run(tt.name, func(t *testing.T) { + credentials := map[string]any{ + "api_key": "sk-test", + "api_protocol": tt.apiProtocol, + } + if tt.baseURL != "" { + credentials["base_url"] = tt.baseURL + } + if tt.anthropicBase != "" { + credentials["api_base_urls"] = map[string]any{APIProtocolAnthropic: tt.anthropicBase} + } + account := &Account{ + ID: 902, + Name: "ollama-cloud-anthropic", + Platform: PlatformOllamaCloud, + Type: AccountTypeAPIKey, + Credentials: credentials, + Extra: map[string]any{}, + } + + targetURL, err := svc.nativeAnthropicTargetURL(account) + require.NoError(t, err) + require.Equal(t, tt.want, targetURL) + }) + } + + // 双向钉住 buildOpenAIEndpointURL 在 messages 场景的边界行为。 + require.Equal(t, "https://ollama.com/v1/messages", buildOpenAIEndpointURL("https://ollama.com", "/v1/messages")) + require.Equal(t, "https://ollama.com/v1/messages", buildOpenAIEndpointURL("https://ollama.com/v1", "/v1/messages")) + require.Equal(t, "https://opencode.ai/zen/go/v1/messages", buildOpenAIEndpointURL("https://opencode.ai/zen/go", "/v1/messages")) + require.Equal(t, "https://opencode.ai/zen/go/v1/messages", buildOpenAIEndpointURL("https://opencode.ai/zen/go/v1", "/v1/messages")) +} + +// TestShouldForwardOpenAIResponsesViaRawChatCompletions_OllamaCloud 覆盖 C32: +// ollama_cloud 不能被 opencode 的「恒 false」复用,显式 CC 必须走 raw CC。 +func TestShouldForwardOpenAIResponsesViaRawChatCompletions_OllamaCloud(t *testing.T) { + account := func(protocol string) *Account { + return &Account{ + ID: 903, + Name: "ollama-cloud-cc", + Platform: PlatformOllamaCloud, + Type: AccountTypeAPIKey, + Credentials: map[string]any{ + "api_key": "sk-test", + "api_protocol": protocol, + }, + Extra: map[string]any{}, + } + } + + require.True(t, shouldForwardOpenAIResponsesViaRawChatCompletions(account(APIProtocolChatCompletions))) + require.False(t, shouldForwardOpenAIResponsesViaRawChatCompletions(account(APIProtocolAnthropic))) + // adaptive / responses 的取值跟随 SupportsNativeCNResponses()(该谓词的 ollama + // 分支属增量 3,本增量按现状断言结构一致)。 + require.Equal(t, !account(APIProtocolAdaptive).SupportsNativeCNResponses(), + shouldForwardOpenAIResponsesViaRawChatCompletions(account(APIProtocolAdaptive))) +} + +// TestForwardCountTokensAsAnthropic_OllamaCloudEstimatesLocally 覆盖 ⑨ findings B1: +// ollama_cloud 账号命中本地估算分支,返回 200 且不产生任何出站请求。 +func TestForwardCountTokensAsAnthropic_OllamaCloudEstimatesLocally(t *testing.T) { + gin.SetMode(gin.TestMode) + + body := []byte(`{"model":"claude-sonnet-4-5","system":"You are helpful.","messages":[{"role":"user","content":"hello"}]}`) + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages/count_tokens", bytes.NewReader(body)) + c.Request.Header.Set("Content-Type", "application/json") + + upstream := &httpUpstreamRecorder{err: errors.New("local estimate must not hit upstream")} + svc := ollamaCloudRoutingTestService() + svc.httpUpstream = upstream + + account := &Account{ + ID: 904, + Name: "ollama-cloud-count-tokens", + Platform: PlatformOllamaCloud, + Type: AccountTypeAPIKey, + Credentials: map[string]any{"api_key": "sk-test"}, + Extra: map[string]any{}, + } + + err := svc.ForwardCountTokensAsAnthropic(context.Background(), c, account, body, "claude-sonnet-4-5") + require.NoError(t, err) + require.Equal(t, http.StatusOK, rec.Code) + require.Greater(t, gjson.Get(rec.Body.String(), "input_tokens").Int(), int64(0)) + require.Nil(t, upstream.lastReq) + require.Empty(t, upstream.requests) +} diff --git a/backend/internal/service/openai_gateway_cc_pipeline.go b/backend/internal/service/openai_gateway_cc_pipeline.go index aa65f842eb..e5ed68c499 100644 --- a/backend/internal/service/openai_gateway_cc_pipeline.go +++ b/backend/internal/service/openai_gateway_cc_pipeline.go @@ -142,6 +142,11 @@ func (s *OpenAIGatewayService) failoverOpenAIUpstreamHTTPError( func (s *OpenAIGatewayService) openAIChatCompletionsTargetURL(account *Account) (string, error) { baseURL := account.GetOpenAIBaseURL() if baseURL == "" { + if account.IsMultiProtocolAPIKey() { + // 多协议网关缺 base 时必须显式失败:回落官方域名会把第三方 key + // 明文发到 api.openai.com。 + return "", fmt.Errorf("account %d has no openai base url", account.ID) + } baseURL = "https://api.openai.com" } validatedURL, err := s.validateUpstreamBaseURL(baseURL) diff --git a/backend/internal/service/openai_gateway_count_tokens.go b/backend/internal/service/openai_gateway_count_tokens.go index 9ece2430c8..d01338a2fc 100644 --- a/backend/internal/service/openai_gateway_count_tokens.go +++ b/backend/internal/service/openai_gateway_count_tokens.go @@ -264,14 +264,17 @@ func (s *OpenAIGatewayService) ForwardCountTokensAsAnthropic( return fmt.Errorf("count_tokens: missing account") } - // 国产供应商与 OpenCode(全部协议,含 anthropic):一律本地估算,不发上游请求。 + // 国产供应商、OpenCode 与 Ollama Cloud(全部协议,含 anthropic):一律本地估算, + // 不发上游请求。 // 依据(2026-08 核实):三家的 Anthropic 兼容层均未提供 // /v1/messages/count_tokens——DeepSeek 官方 anthropic_api 文档无此端点 // (且注明 anthropic-version 头被忽略),聚合网关 OpenModel 明确标注 // count_tokens 为 "Anthropic only",Kimi/智谱亦无任何文档承诺。转发上游 // 只会常态 404,且错误还会流入账号处置逻辑误伤整账号调度;Claude Code // 高频调用此端点,本地 tiktoken 估算是与 Grok 一致的既有方案。 - if account.IsCNProvider() || account.IsOpenCodeGo() { + // Ollama Cloud 同因:其 Anthropic 兼容层同样未提供该端点(上游只有 + // /v1/responses/input_tokens),转发同样只会得到 404。 + if account.IsCNProvider() || account.IsOpenCodeGo() || account.IsOllamaCloud() { estimated, err := estimateAnthropicCountTokensLocally(body) if err != nil { writeAnthropicCountTokensError(c, http.StatusBadRequest, "invalid_request_error", "Failed to parse request body") diff --git a/backend/internal/service/openai_gateway_forward.go b/backend/internal/service/openai_gateway_forward.go index 131fd5a169..14b7ac988f 100644 --- a/backend/internal/service/openai_gateway_forward.go +++ b/backend/internal/service/openai_gateway_forward.go @@ -1377,6 +1377,18 @@ func shouldForwardOpenAIResponsesViaRawChatCompletions(account *Account) bool { return false } } + if account.IsOllamaCloud() { + // Ollama Cloud 无 protocol_rules:显式 CC 锁 CC,adaptive / responses + // 走平台原生 Responses 端点(探针 Extra 不得把协议决策带偏)。 + switch account.GetAPIProtocol() { + case APIProtocolChatCompletions: + return true + case APIProtocolAdaptive, APIProtocolResponses: + return !account.SupportsNativeCNResponses() + default: + return false + } + } return !openai_compat.ShouldUseResponsesAPI(account.Extra) } @@ -1400,6 +1412,11 @@ func (s *OpenAIGatewayService) buildUpstreamRequest(ctx context.Context, c *gin. baseURL = account.GetCNProtocolBaseURL(APIProtocolResponses) } if baseURL == "" { + if account.IsMultiProtocolAPIKey() { + // 多协议网关缺 base 时必须显式失败:回落官方域名会把第三方 key + // 明文发到 api.openai.com。 + return nil, fmt.Errorf("account %d has no openai responses base url", account.ID) + } targetURL = openaiPlatformAPIURL } else { validatedURL, err := s.validateUpstreamBaseURL(baseURL) diff --git a/backend/internal/service/openai_gateway_messages_anthropic_native.go b/backend/internal/service/openai_gateway_messages_anthropic_native.go index baabaaa34d..740da84c65 100644 --- a/backend/internal/service/openai_gateway_messages_anthropic_native.go +++ b/backend/internal/service/openai_gateway_messages_anthropic_native.go @@ -139,11 +139,10 @@ func (s *OpenAIGatewayService) nativeAnthropicTargetURL(account *Account) (strin if err != nil { return "", fmt.Errorf("invalid base_url: %w", err) } - if account.IsOpenCodeGo() { - // OpenCode Go 的 Chat Completions base 带 /v1;用版本感知拼接避免 /v1/v1/messages。 - return buildOpenAIEndpointURL(validatedURL, "/v1/messages"), nil - } - return strings.TrimRight(validatedURL, "/") + "/v1/messages", nil + // 版本感知拼接:base 已带 /v1 时不再追加,避免拼出 /v1/v1/messages + //(OpenCode Go 的 Chat Completions base 带 /v1,Ollama Cloud 的 anthropic + // 默认 base 不带)。 + return buildOpenAIEndpointURL(validatedURL, "/v1/messages"), nil } func resolveOpenCodeGoMappedModel(account *Account, body []byte, defaultMappedModel string) string { diff --git a/backend/internal/service/openai_gateway_passthrough.go b/backend/internal/service/openai_gateway_passthrough.go index a24ae4a007..54ce5131d7 100644 --- a/backend/internal/service/openai_gateway_passthrough.go +++ b/backend/internal/service/openai_gateway_passthrough.go @@ -601,6 +601,10 @@ func (s *OpenAIGatewayService) buildUpstreamRequestOpenAIPassthrough( return nil, err } targetURL = buildOpenAIResponsesURLForPlatform(account.Platform, validatedURL) + } else if account.IsMultiProtocolAPIKey() { + // 多协议网关缺 base 时必须显式失败:targetURL 初值即官方域名, + // 回落它会把第三方 key 明文发到 api.openai.com。 + return nil, fmt.Errorf("account %d has no openai responses base url", account.ID) } } targetURL = appendOpenAIResponsesRequestPathSuffix(targetURL, openAIResponsesRequestPathSuffix(c)) From 3b0e4f792c6f9ac4420b8fd7e31091bc5d70a9d1 Mon Sep 17 00:00:00 2001 From: alfadb Date: Sun, 13 Sep 2026 00:06:35 +0800 Subject: [PATCH 10/81] feat(platform): admit ollama_cloud to scheduling pool and composite routes --- .../internal/handler/admin/group_handler.go | 6 +- .../admin/group_handler_platform_test.go | 11 +- .../internal/model/error_passthrough_rule.go | 2 + .../model/error_passthrough_rule_test.go | 1 + backend/internal/service/account.go | 5 +- .../service/account_header_override.go | 2 +- backend/internal/service/account_service.go | 5 +- backend/internal/service/cn_providers_test.go | 3 + .../internal/service/composite_platform.go | 2 +- .../service/composite_platform_test.go | 16 +- .../service/ollama_cloud_scheduling_test.go | 144 ++++++++++++++++++ .../service/openai_gateway_scheduling.go | 4 +- backend/internal/service/ratelimit_service.go | 8 +- .../ratelimit_service_403_html_test.go | 14 ++ .../service/scheduler_snapshot_service.go | 9 +- .../service/upstream_billing_probe.go | 2 +- backend/internal/service/upstream_models.go | 8 +- 17 files changed, 213 insertions(+), 29 deletions(-) create mode 100644 backend/internal/service/ollama_cloud_scheduling_test.go diff --git a/backend/internal/handler/admin/group_handler.go b/backend/internal/handler/admin/group_handler.go index 774a00f882..3ccbbe2531 100644 --- a/backend/internal/handler/admin/group_handler.go +++ b/backend/internal/handler/admin/group_handler.go @@ -184,7 +184,7 @@ func sanitizeUpdateGroupRequestForSimpleMode(req *UpdateGroupRequest) { type CreateGroupRequest struct { Name string `json:"name" binding:"required"` Description string `json:"description"` - Platform string `json:"platform" binding:"omitempty,oneof=anthropic openai gemini antigravity grok kimi zhipu deepseek minimax opencode_go typesafe composite"` + Platform string `json:"platform" binding:"omitempty,oneof=anthropic openai gemini antigravity grok kimi zhipu deepseek minimax opencode_go typesafe ollama_cloud composite"` RateMultiplier float64 `json:"rate_multiplier"` IsExclusive bool `json:"is_exclusive"` SubscriptionType string `json:"subscription_type" binding:"omitempty,oneof=standard subscription"` @@ -258,7 +258,7 @@ type CreateGroupRequest struct { type UpdateGroupRequest struct { Name string `json:"name"` Description *string `json:"description"` - Platform string `json:"platform" binding:"omitempty,oneof=anthropic openai gemini antigravity grok kimi zhipu deepseek minimax opencode_go typesafe composite"` + Platform string `json:"platform" binding:"omitempty,oneof=anthropic openai gemini antigravity grok kimi zhipu deepseek minimax opencode_go typesafe ollama_cloud composite"` RateMultiplier *float64 `json:"rate_multiplier"` IsExclusive *bool `json:"is_exclusive"` Status string `json:"status" binding:"omitempty,oneof=active inactive"` @@ -332,7 +332,7 @@ type UpdateGroupRequest struct { type CompositeRouteRequest struct { PublicModel string `json:"public_model" binding:"required"` MatchType string `json:"match_type" binding:"omitempty,oneof=exact prefix"` - TargetPlatform string `json:"target_platform" binding:"required,oneof=anthropic openai gemini antigravity grok kimi zhipu deepseek minimax opencode_go typesafe"` + TargetPlatform string `json:"target_platform" binding:"required,oneof=anthropic openai gemini antigravity grok kimi zhipu deepseek minimax opencode_go typesafe ollama_cloud"` UpstreamModel string `json:"upstream_model"` Endpoint string `json:"endpoint" binding:"omitempty,oneof=any messages count_tokens responses chat_completions embeddings images gemini"` Priority int `json:"priority"` diff --git a/backend/internal/handler/admin/group_handler_platform_test.go b/backend/internal/handler/admin/group_handler_platform_test.go index d5d48845e1..a44115d36f 100644 --- a/backend/internal/handler/admin/group_handler_platform_test.go +++ b/backend/internal/handler/admin/group_handler_platform_test.go @@ -12,9 +12,9 @@ import ( "github.com/stretchr/testify/require" ) -// 回归分组平台枚举:kimi/zhipu/deepseek/opencode_go 必须能通过 Create/Update 的 -// binding 校验(历史 bug:调度/路由链路已支持这些平台,但 oneof 白名单漏加, -// 导致平台分组无法创建、账号"无可用分组");非法值仍须被拒。 +// 回归分组平台枚举:kimi/zhipu/deepseek/opencode_go/ollama_cloud 必须能通过 +// Create/Update 的 binding 校验(历史 bug:调度/路由链路已支持这些平台,但 oneof +// 白名单漏加,导致平台分组无法创建、账号"无可用分组");非法值仍须被拒。 func bindGroupPlatformJSON(t *testing.T, target any, body string) error { t.Helper() gin.SetMode(gin.TestMode) @@ -27,8 +27,7 @@ func bindGroupPlatformJSON(t *testing.T, target any, body string) error { func TestGroupPlatformBinding_AllowedPlatforms(t *testing.T) { allowed := []string{ "anthropic", "openai", "gemini", "antigravity", "grok", - "kimi", "zhipu", "deepseek", "minimax", "opencode_go", "composite", - "typesafe", + "kimi", "zhipu", "deepseek", "minimax", "opencode_go", "typesafe", "ollama_cloud", "composite", } for _, platform := range allowed { t.Run("create_"+platform, func(t *testing.T) { @@ -73,7 +72,7 @@ func TestGroupPlatformBinding_RejectsInvalidPlatforms(t *testing.T) { } func TestCompositeRouteTargetPlatform_AllowsConcreteProviders(t *testing.T) { - for _, platform := range []string{"kimi", "zhipu", "deepseek", "minimax", "opencode_go", "typesafe"} { + for _, platform := range []string{"kimi", "zhipu", "deepseek", "minimax", "opencode_go", "typesafe", "ollama_cloud"} { var req CompositeRouteRequest body := fmt.Sprintf(`{"public_model":"m","target_platform":%q}`, platform) require.NoError(t, bindGroupPlatformJSON(t, &req, body)) diff --git a/backend/internal/model/error_passthrough_rule.go b/backend/internal/model/error_passthrough_rule.go index da928125f2..ffc4cf6771 100644 --- a/backend/internal/model/error_passthrough_rule.go +++ b/backend/internal/model/error_passthrough_rule.go @@ -47,6 +47,7 @@ const ( PlatformMiniMax = domain.PlatformMiniMax PlatformOpenCodeGo = domain.PlatformOpenCodeGo PlatformTypeSafe = domain.PlatformTypeSafe + PlatformOllamaCloud = domain.PlatformOllamaCloud ) // AllPlatforms 返回所有支持的平台列表 @@ -63,6 +64,7 @@ func AllPlatforms() []string { PlatformMiniMax, PlatformOpenCodeGo, PlatformTypeSafe, + PlatformOllamaCloud, } } diff --git a/backend/internal/model/error_passthrough_rule_test.go b/backend/internal/model/error_passthrough_rule_test.go index 17e6fdcbf2..0c3f0469e7 100644 --- a/backend/internal/model/error_passthrough_rule_test.go +++ b/backend/internal/model/error_passthrough_rule_test.go @@ -19,5 +19,6 @@ func TestAllPlatformsIncludesEveryConcretePlatform(t *testing.T) { "minimax", "opencode_go", "typesafe", + "ollama_cloud", }, AllPlatforms()) } diff --git a/backend/internal/service/account.go b/backend/internal/service/account.go index 2e628cff4d..d9f37bba52 100644 --- a/backend/internal/service/account.go +++ b/backend/internal/service/account.go @@ -306,9 +306,10 @@ func (a *Account) IsOllamaCloud() bool { // IsOpenAICompatible 报告账号是否走 OpenAI 网关(OpenAI 协议族)。 // openai/grok 原生走 OpenAI 网关;国产供应商同为 OpenAI Chat Completions -// 兼容上游,也经 OpenAI 网关转发。OpenCode 同样经 OpenAI 网关按模型分流。 +// 兼容上游,也经 OpenAI 网关转发。OpenCode 与 Ollama Cloud 同样经 OpenAI +// 网关按模型/协议分流。 func (a *Account) IsOpenAICompatible() bool { - return a != nil && (a.Platform == PlatformOpenAI || a.Platform == PlatformGrok || a.IsCNProvider() || a.IsOpenCodeGo()) + return a != nil && (a.Platform == PlatformOpenAI || a.Platform == PlatformGrok || a.IsCNProvider() || a.IsOpenCodeGo() || a.IsOllamaCloud()) } func (a *Account) GeminiOAuthType() string { diff --git a/backend/internal/service/account_header_override.go b/backend/internal/service/account_header_override.go index 7f05e253ac..5ffeecf8ac 100644 --- a/backend/internal/service/account_header_override.go +++ b/backend/internal/service/account_header_override.go @@ -78,7 +78,7 @@ func (a *Account) IsHeaderOverrideEligible() bool { return false } switch a.Platform { - case PlatformAnthropic, PlatformOpenAI, PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo: + case PlatformAnthropic, PlatformOpenAI, PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo, PlatformOllamaCloud: return a.Type == AccountTypeAPIKey case PlatformGrok: return a.Type == AccountTypeAPIKey || a.Type == AccountTypeOAuth diff --git a/backend/internal/service/account_service.go b/backend/internal/service/account_service.go index bbf668eaff..ba5aebca07 100644 --- a/backend/internal/service/account_service.go +++ b/backend/internal/service/account_service.go @@ -522,8 +522,9 @@ func (s *AccountService) TestCredentials(ctx context.Context, id int64) error { case PlatformTypeSafe: // TypeSafe credentials are API keys; inference failures drive health and cooldown state. return nil - case PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo: - // 国产 OpenAI 兼容供应商与 OpenCode:凭证为 API Key,实际可用性经余额/额度探测与转发路径验证。 + case PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo, PlatformOllamaCloud: + // 国产 OpenAI 兼容供应商、OpenCode 与 Ollama Cloud:凭证为 API Key, + // 实际可用性经余额/额度探测与转发路径验证。 return nil default: return fmt.Errorf("unsupported platform: %s", account.Platform) diff --git a/backend/internal/service/cn_providers_test.go b/backend/internal/service/cn_providers_test.go index 44becd4e5b..9e62ca3534 100644 --- a/backend/internal/service/cn_providers_test.go +++ b/backend/internal/service/cn_providers_test.go @@ -531,6 +531,9 @@ func TestNormalizeOpenAICompatiblePlatform_SchedulerExactMatch(t *testing.T) { require.Equal(t, PlatformZhipu, NormalizeOpenAICompatiblePlatform(PlatformZhipu)) require.Equal(t, PlatformDeepseek, NormalizeOpenAICompatiblePlatform(PlatformDeepseek)) require.Equal(t, PlatformOpenCodeGo, NormalizeOpenAICompatiblePlatform(PlatformOpenCodeGo)) + // ollama_cloud 同样保留原值:归一为 openai 会让 ollama_cloud 分组查 openai + // 候选桶 → 静默空池(调度不到账号)。 + require.Equal(t, PlatformOllamaCloud, NormalizeOpenAICompatiblePlatform(PlatformOllamaCloud)) // 其他平台(含空、anthropic、未知)一律归一为 openai。 require.Equal(t, PlatformOpenAI, NormalizeOpenAICompatiblePlatform("")) require.Equal(t, PlatformOpenAI, NormalizeOpenAICompatiblePlatform(PlatformAnthropic)) diff --git a/backend/internal/service/composite_platform.go b/backend/internal/service/composite_platform.go index bd6a8fe733..0e394bcf7f 100644 --- a/backend/internal/service/composite_platform.go +++ b/backend/internal/service/composite_platform.go @@ -285,7 +285,7 @@ func (s *GatewayService) resolveCompositeRouteDecision(ctx context.Context, grou func isConcreteRequestPlatform(platform string) bool { switch platform { case PlatformAnthropic, PlatformOpenAI, PlatformGemini, PlatformAntigravity, PlatformGrok, - PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo, PlatformTypeSafe: + PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo, PlatformTypeSafe, PlatformOllamaCloud: return true default: return false diff --git a/backend/internal/service/composite_platform_test.go b/backend/internal/service/composite_platform_test.go index 56189f4048..c7d398422b 100644 --- a/backend/internal/service/composite_platform_test.go +++ b/backend/internal/service/composite_platform_test.go @@ -234,7 +234,7 @@ func TestCompositeGroupSchedulerHasAllCanonicalPlatformBuckets(t *testing.T) { platforms = append(platforms, platform) } require.ElementsMatch(t, - []string{PlatformAnthropic, PlatformGemini, PlatformOpenAI, PlatformAntigravity, PlatformGrok, PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo, PlatformTypeSafe}, + []string{PlatformAnthropic, PlatformGemini, PlatformOpenAI, PlatformAntigravity, PlatformGrok, PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo, PlatformTypeSafe, PlatformOllamaCloud}, platforms, ) } @@ -245,3 +245,17 @@ func TestCompositeConcretePlatformsIncludeCNProviders(t *testing.T) { require.True(t, canCopyAccountsFromGroupPlatform(PlatformComposite, platform)) } } + +// 组合路由准入:ollama_cloud 必须被视为具体请求平台,组合路由才能指向它 +// (迁移 239 已放宽 DB CHECK;代码侧缺这一条会出现「数据库允许、代码不放行」)。 +func TestCompositeConcretePlatformsIncludeOllamaCloud(t *testing.T) { + require.True(t, isConcreteRequestPlatform(PlatformOllamaCloud)) + require.True(t, canCopyAccountsFromGroupPlatform(PlatformComposite, PlatformOllamaCloud)) + + route, err := compositeRouteFromInput(101, CompositeRouteInput{ + PublicModel: "qwen3-coder", + TargetPlatform: PlatformOllamaCloud, + }) + require.NoError(t, err) + require.Equal(t, PlatformOllamaCloud, route.TargetPlatform) +} diff --git a/backend/internal/service/ollama_cloud_scheduling_test.go b/backend/internal/service/ollama_cloud_scheduling_test.go new file mode 100644 index 0000000000..341cb78441 --- /dev/null +++ b/backend/internal/service/ollama_cloud_scheduling_test.go @@ -0,0 +1,144 @@ +package service + +import ( + "context" + "testing" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/stretchr/testify/require" +) + +// 本文件覆盖 §11.3 ② 组(C1 + C2 + C6 + C7)与 C10:让 ollama_cloud 分组能 +// 真正调度到账号。缺任一条的表现都是静默空池(候选池按 platform 精确匹配)。 + +// C2:漏了 IsOllamaCloud() 会被 openai_account_scheduler.go 的 +// !IsOpenAICompatible() 过滤掉(filterStats: platform_mismatch)。 +func TestOllamaCloudPlatform_IsOpenAICompatible(t *testing.T) { + t.Parallel() + + acc := &Account{Platform: PlatformOllamaCloud, Type: AccountTypeAPIKey} + require.True(t, acc.IsOpenAICompatible(), "ollama_cloud 账号必须进入 OpenAI 网关候选池") + require.True(t, acc.IsOllamaCloud()) + + // 其他平台的既有语义不变。 + require.True(t, (&Account{Platform: PlatformOpenAI}).IsOpenAICompatible()) + require.False(t, (&Account{Platform: PlatformAnthropic}).IsOpenAICompatible()) + require.False(t, (*Account)(nil).IsOpenAICompatible()) +} + +// C6 + F2:canonical 桶必须覆盖 ollama_cloud,否则 rebuild 不写该桶、缓存永不命中。 +func TestOllamaCloudPlatform_SchedulerSnapshotPlatforms(t *testing.T) { + t.Parallel() + + platforms := schedulerSnapshotPlatforms() + require.Len(t, platforms, 11) + require.Contains(t, platforms[:], PlatformOllamaCloud) + + seen := make(map[string]struct{}, len(platforms)) + for _, platform := range platforms { + require.NotEmpty(t, platform) + _, dup := seen[platform] + require.Falsef(t, dup, "duplicate platform in schedulerSnapshotPlatforms: %s", platform) + seen[platform] = struct{}{} + } + + // 桶数必须与平台数组长度一致:每平台 single+forced,anthropic/gemini 各多一个 mixed。 + const groupID int64 = 7701 + require.Equal(t, len(platforms)*2+2, schedulerCanonicalBucketCount()) + require.Equal(t, 24, schedulerCanonicalBucketCount()) + + buckets := schedulerCanonicalBuckets(groupID) + require.Len(t, buckets, schedulerCanonicalBucketCount()) + require.Contains(t, buckets, SchedulerBucket{GroupID: groupID, Platform: PlatformOllamaCloud, Mode: SchedulerModeSingle}) + require.Contains(t, buckets, SchedulerBucket{GroupID: groupID, Platform: PlatformOllamaCloud, Mode: SchedulerModeForced}) +} + +// C1 + C2 端到端:ollama_cloud 分组的请求必须能在候选池里选中 ollama_cloud 账号。 +// 若 C1 回退(归一为 openai),mock repo 按 platform 查询会返回空池 → +// ErrNoAvailableAccounts;若 C2 回退,候选过滤会以 platform_mismatch 排除。 +func TestOllamaCloudPlatform_EntersOpenAISchedulerCandidatePool(t *testing.T) { + resetOpenAIAdvancedSchedulerSettingCacheForTest() + + ctx := context.Background() + groupID := int64(7702) + accounts := []Account{ + { + ID: 77021, + Platform: PlatformOllamaCloud, + Type: AccountTypeAPIKey, + Status: StatusActive, + Schedulable: true, + Concurrency: 1, + Credentials: map[string]any{"api_key": "ollama-key", "base_url": "https://ollama.com/v1"}, + }, + { + ID: 77022, + Platform: PlatformOpenAI, + Type: AccountTypeAPIKey, + Status: StatusActive, + Schedulable: true, + Concurrency: 1, + }, + } + cfg := &config.Config{} + cfg.Gateway.Scheduling.LoadBatchEnabled = false + svc := &OpenAIGatewayService{ + accountRepo: schedulerTestOpenAIAccountRepo{accounts: accounts}, + cache: &schedulerTestGatewayCache{}, + cfg: cfg, + concurrencyService: NewConcurrencyService(schedulerTestConcurrencyCache{}), + } + + selection, decision, err := svc.SelectAccountWithSchedulerForCapability( + ctx, + &groupID, + "", + "", + "gpt-oss:120b", + nil, + OpenAIUpstreamTransportAny, + OpenAIEndpointCapabilityChatCompletions, + false, + false, + false, + PlatformOllamaCloud, + ) + require.NoError(t, err) + require.NotNil(t, selection) + require.NotNil(t, selection.Account) + require.Equal(t, int64(77021), selection.Account.ID, "ollama_cloud 分组必须命中 ollama_cloud 账号而不是 openai 账号") + require.Equal(t, openAIAccountScheduleLayerLoadBalance, decision.Layer) + + // 反向控制:openai 分组的池里不得出现 ollama_cloud 账号(平台精确匹配)。 + openAISelection, _, err := svc.SelectAccountWithSchedulerForCapability( + ctx, + &groupID, + "", + "", + "gpt-oss:120b", + nil, + OpenAIUpstreamTransportAny, + OpenAIEndpointCapabilityChatCompletions, + false, + false, + false, + PlatformOpenAI, + ) + require.NoError(t, err) + require.NotNil(t, openAISelection) + require.NotNil(t, openAISelection.Account) + require.Equal(t, int64(77022), openAISelection.Account.ID, "openai 分组不得命中 ollama_cloud 账号") +} + +// C10:TestCredentials 的 default 分支会返回 unsupported platform → 管理端 +// 「测试凭证」对新平台必定失败。 +func TestOllamaCloudPlatform_TestCredentialsSupported(t *testing.T) { + t.Parallel() + + svc := &AccountService{ + accountRepo: schedulerTestOpenAIAccountRepo{accounts: []Account{ + {ID: 77031, Platform: PlatformOllamaCloud, Type: AccountTypeAPIKey}, + }}, + } + require.NoError(t, svc.TestCredentials(context.Background(), 77031)) +} diff --git a/backend/internal/service/openai_gateway_scheduling.go b/backend/internal/service/openai_gateway_scheduling.go index b8295ad0a0..03c528a78c 100644 --- a/backend/internal/service/openai_gateway_scheduling.go +++ b/backend/internal/service/openai_gateway_scheduling.go @@ -288,11 +288,13 @@ func (s *OpenAIGatewayService) SelectAccountForTokenCount( // NormalizeOpenAICompatiblePlatform 保留 grok 与国产 OpenAI 兼容供应商(kimi/zhipu/ // deepseek)的原值,其他值一律归一为 openai。调度器据此对账号与请求做精确平台匹配: // kimi 分组请求只命中 kimi 账号,语义与 openai/grok 一致。 +// Ollama Cloud 同样必须保留原值:归一为 openai 会让 ollama_cloud 分组去查 +// openai 候选桶,表现为静默空池。 // (upstream 曾将本函数改为未导出 normalizeOpenAICompatiblePlatform,本分支的 // handler 调度入口仍需导出,保持导出名。) func NormalizeOpenAICompatiblePlatform(platform string) string { switch platform { - case PlatformGrok, PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo: + case PlatformGrok, PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo, PlatformOllamaCloud: return platform default: return PlatformOpenAI diff --git a/backend/internal/service/ratelimit_service.go b/backend/internal/service/ratelimit_service.go index 6438efc3e2..8d9cc85f09 100644 --- a/backend/internal/service/ratelimit_service.go +++ b/backend/internal/service/ratelimit_service.go @@ -1000,10 +1000,10 @@ func (s *RateLimitService) handle403(ctx context.Context, account *Account, upst s.handleCNProviderQuotaExhausted403(ctx, account, upstreamMsg) return true } - // 国产供应商与 openai 同口径:HTML 403(CDN/代理拦截页)不构成账号失效证据, - // 且 403 在 failover 状态集里会被逐账号重放——直接 SetError 会让一个坏请求/ - // 一层坏代理连环永久禁用整组账号。走 HTML 豁免 + N 次累计 + 临时冷却。 - if account.Platform == PlatformOpenAI || IsCNProvider(account.Platform) || account.IsOpenCodeGo() { + // 国产供应商、openai 与 ollama_cloud 同口径:HTML 403(CDN/代理拦截页)不构成账号 + // 失效证据,且 403 在 failover 状态集里会被逐账号重放——直接 SetError 会让一个 + // 坏请求/一层坏代理连环永久禁用整组账号。走 HTML 豁免 + N 次累计 + 临时冷却。 + if account.Platform == PlatformOpenAI || IsCNProvider(account.Platform) || account.IsOpenCodeGo() || account.IsOllamaCloud() { return s.handleOpenAI403(ctx, account, upstreamMsg, responseBody) } // 非 Antigravity 平台:保持原有行为 diff --git a/backend/internal/service/ratelimit_service_403_html_test.go b/backend/internal/service/ratelimit_service_403_html_test.go index 8768b41fea..1dde53a9a3 100644 --- a/backend/internal/service/ratelimit_service_403_html_test.go +++ b/backend/internal/service/ratelimit_service_403_html_test.go @@ -179,6 +179,20 @@ func TestHandleUpstreamError_HTML403OnOtherPlatformsUnchanged(t *testing.T) { } } +// ollama_cloud 迁到独立 platform 后必须继续命中 HTML 403 豁免:与 openai/ +// 国产/opencode_go 同为多协议 API Key 网关,链路级 403 同样不构成账号失效 +// 证据;漏加会在迁移后掉进默认 SetError 永久禁号路径。 +func TestHandleUpstreamError_OllamaCloudHTML403DoesNotPenalizeAccount(t *testing.T) { + h := newOpenAI403TestHarness(t, 507, 1) + h.account.Platform = PlatformOllamaCloud + h.account.Type = AccountTypeAPIKey + + shouldDisable := h.handle(openAI403HTMLBody) + + require.False(t, shouldDisable, "ollama_cloud 的 HTML 403 不得判定账号应下线") + h.requireNoAccountPenalty(t) +} + func TestIsHTMLResponse(t *testing.T) { cases := []struct { name string diff --git a/backend/internal/service/scheduler_snapshot_service.go b/backend/internal/service/scheduler_snapshot_service.go index 6f999c189c..2850a4884f 100644 --- a/backend/internal/service/scheduler_snapshot_service.go +++ b/backend/internal/service/scheduler_snapshot_service.go @@ -609,7 +609,7 @@ func (s *SchedulerSnapshotService) handleBulkAccountEvent(ctx context.Context, p } accountGroupIDs := s.normalizeGroupIDs(account.GroupIDs) switch account.Platform { - case PlatformAnthropic, PlatformGemini, PlatformOpenAI, PlatformGrok, PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo, PlatformTypeSafe: + case PlatformAnthropic, PlatformGemini, PlatformOpenAI, PlatformGrok, PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo, PlatformTypeSafe, PlatformOllamaCloud: addPlatformGroups(account.Platform, accountGroupIDs) case PlatformAntigravity: // 批量更新可能刚关闭 mixed_scheduling,仍需清理两个兼容平台的旧快照。 @@ -824,8 +824,11 @@ func (s *SchedulerSnapshotService) rebuildByAccount(ctx context.Context, account return s.rebuildBuckets(ctx, buckets, reason) } -func schedulerSnapshotPlatforms() [11]string { - return [11]string{PlatformAnthropic, PlatformGemini, PlatformOpenAI, PlatformAntigravity, PlatformGrok, PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo, PlatformTypeSafe} +// schedulerSnapshotPlatforms 是 canonical 桶覆盖的平台全集:新增 concrete +// platform 必须同时扩展本数组与 scheduler_snapshot 的批量变更 switch(否则 +// 桶不在 canonical 集里、rebuild 不覆盖 → 缓存永不命中)。 +func schedulerSnapshotPlatforms() [12]string { + return [12]string{PlatformAnthropic, PlatformGemini, PlatformOpenAI, PlatformAntigravity, PlatformGrok, PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo, PlatformTypeSafe, PlatformOllamaCloud} } // 生命周期辅助函数有意排除 group0;full rebuild 构造 group0 canonical 集时必须显式调用 canonical helper。 diff --git a/backend/internal/service/upstream_billing_probe.go b/backend/internal/service/upstream_billing_probe.go index b34900f4f5..91639c8573 100644 --- a/backend/internal/service/upstream_billing_probe.go +++ b/backend/internal/service/upstream_billing_probe.go @@ -1014,7 +1014,7 @@ func IsUpstreamBillingProbeIdentity(platform, accountType string) bool { switch platform { case PlatformOpenAI, PlatformAnthropic, PlatformGemini, PlatformAntigravity, PlatformGrok, PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo, - PlatformTypeSafe: + PlatformTypeSafe, PlatformOllamaCloud: return true default: return false diff --git a/backend/internal/service/upstream_models.go b/backend/internal/service/upstream_models.go index 7596dea131..48722efefc 100644 --- a/backend/internal/service/upstream_models.go +++ b/backend/internal/service/upstream_models.go @@ -625,7 +625,7 @@ func upstreamModelRegistryBaseURL(account *Account) string { return "" } switch { - case account.IsOpenAI() || account.IsCNProvider() || account.IsOpenCodeGo(): + case account.IsOpenAI() || account.IsCNProvider() || account.IsOpenCodeGo() || account.IsOllamaCloud(): return account.GetOpenAIFormatBaseURL() case account.IsGrok(): return account.GetGrokBaseURL() @@ -792,9 +792,9 @@ func (s *AccountTestService) buildUpstreamModelsRequest(ctx context.Context, acc return s.buildAntigravityAPIKeyModelsRequest(ctx, account) case account.IsGrok(): return s.buildGrokUpstreamModelsRequest(ctx, account) - case account.IsOpenAI() || account.IsCNProvider() || account.IsOpenCodeGo(): - // 国产 OpenAI 兼容供应商(kimi/zhipu/deepseek)与 OpenCode Go - // 复用 OpenAI /v1/models 探测。 + case account.IsOpenAI() || account.IsCNProvider() || account.IsOpenCodeGo() || account.IsOllamaCloud(): + // 国产 OpenAI 兼容供应商(kimi/zhipu/deepseek)、OpenCode Go 与 + // Ollama Cloud 复用 OpenAI /v1/models 探测。 return s.buildOpenAIUpstreamModelsRequest(ctx, account) case account.IsGemini(): return s.buildGeminiUpstreamModelsRequest(ctx, account) From b868e94c152764820f199a5e7ccd02acb5d2146e Mon Sep 17 00:00:00 2001 From: alfadb Date: Sun, 13 Sep 2026 00:20:42 +0800 Subject: [PATCH 11/81] feat(platform): align ollama_cloud platform lists for composite routing and pricing - C11: matchingPlatforms composite branch includes ollama_cloud so channel pricing/mapping cache lookups stay consistent with isConcreteRequestPlatform - C20: openAICompatibleTextTargetAllowed allows ollama_cloud resolved targets - C21: compositeAvailableModels aggregates ollama_cloud account mapping keys (claude default-list fallback already gated off by IsMultiProtocolAPIKeyProvider) - test sync: composite matchingPlatforms expectation, bulk account event rebuild coverage for the ollama_cloud bucket, ollama_cloud text-target case --- .../internal/handler/composite_platform_test.go | 16 ++++++++++++++++ backend/internal/handler/gateway_handler.go | 2 +- .../internal/handler/openai_gateway_handler.go | 2 +- backend/internal/service/channel_service.go | 2 +- backend/internal/service/channel_service_test.go | 2 +- .../scheduler_snapshot_bulk_event_test.go | 2 +- 6 files changed, 21 insertions(+), 5 deletions(-) diff --git a/backend/internal/handler/composite_platform_test.go b/backend/internal/handler/composite_platform_test.go index 7704a129a0..322439a2b4 100644 --- a/backend/internal/handler/composite_platform_test.go +++ b/backend/internal/handler/composite_platform_test.go @@ -51,6 +51,22 @@ func TestOpenAICompatibleTextTargetAllowsCompositeProviders(t *testing.T) { } } +// ollama_cloud 目标不会经 DetectModelPlatform 的模型名前缀产生(无 ollama 前缀, +// fail closed),只能来自 composite 路由已解析的 context;这里预置解析结果后 +// 断言文本目标白名单放行 ollama_cloud。 +func TestOpenAICompatibleTextTargetAllowsOllamaCloudResolvedRoute(t *testing.T) { + gin.SetMode(gin.TestMode) + + for _, path := range []string{"/v1/messages", "/v1/chat/completions", "/v1/responses", "/v1/responses/input_tokens", "/v1/messages/count_tokens"} { + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + c.Request = httptest.NewRequest("POST", path, nil) + c.Request = c.Request.WithContext(service.WithResolvedTargetPlatform(c.Request.Context(), service.PlatformOllamaCloud)) + apiKey := &service.APIKey{Group: &service.Group{Platform: service.PlatformComposite}} + + require.True(t, openAICompatibleTextTargetAllowed(c, apiKey, "gpt-oss:20b"), "path=%s", path) + } +} + // WS ingress 对 CN 账号既过不了 transport 过滤、HTTP 桥也没有 Responses 转换, // 放行只会把明确的策略拒绝换成 "no available account",因此 WS 白名单保持 openai+grok。 func TestResponsesWebSocketCompositePlatformGuardKeepsOpenAIAndGrokOnly(t *testing.T) { diff --git a/backend/internal/handler/gateway_handler.go b/backend/internal/handler/gateway_handler.go index 8bb38292a2..2770a183ab 100644 --- a/backend/internal/handler/gateway_handler.go +++ b/backend/internal/handler/gateway_handler.go @@ -1373,7 +1373,7 @@ func (h *GatewayHandler) compositeAvailableModels(ctx context.Context, groupID * seen := make(map[string]struct{}) models := make([]string, 0) schedulablePlatforms := h.gatewayService.GetSchedulablePlatforms(ctx, groupID) - for _, platform := range []string{service.PlatformAnthropic, service.PlatformGemini, service.PlatformOpenAI, service.PlatformAntigravity, service.PlatformGrok, service.PlatformKimi, service.PlatformZhipu, service.PlatformDeepseek, service.PlatformMiniMax, service.PlatformOpenCodeGo, service.PlatformTypeSafe} { + for _, platform := range []string{service.PlatformAnthropic, service.PlatformGemini, service.PlatformOpenAI, service.PlatformAntigravity, service.PlatformGrok, service.PlatformKimi, service.PlatformZhipu, service.PlatformDeepseek, service.PlatformMiniMax, service.PlatformOpenCodeGo, service.PlatformTypeSafe, service.PlatformOllamaCloud} { if platform == service.PlatformTypeSafe && !includeSystemOne { continue } diff --git a/backend/internal/handler/openai_gateway_handler.go b/backend/internal/handler/openai_gateway_handler.go index 097d824f18..35cdb7301d 100644 --- a/backend/internal/handler/openai_gateway_handler.go +++ b/backend/internal/handler/openai_gateway_handler.go @@ -356,7 +356,7 @@ func openAICompatibleTextTargetAllowed(c *gin.Context, apiKey *service.APIKey, m return compositeTargetPlatformAllowed(c, apiKey, model, service.PlatformOpenAI, service.PlatformGrok, service.PlatformKimi, service.PlatformZhipu, service.PlatformDeepseek, - service.PlatformMiniMax, service.PlatformOpenCodeGo) + service.PlatformMiniMax, service.PlatformOpenCodeGo, service.PlatformOllamaCloud) } // isResponsesWebSocketCompositePlatform 限定 composite 分组在 Responses WebSocket diff --git a/backend/internal/service/channel_service.go b/backend/internal/service/channel_service.go index b2c605cd80..1987e90a98 100644 --- a/backend/internal/service/channel_service.go +++ b/backend/internal/service/channel_service.go @@ -368,7 +368,7 @@ func isPlatformPricingMatch(groupPlatform, pricingPlatform string) bool { // fallback used before a request target has been resolved. func matchingPlatforms(groupPlatform string) []string { if groupPlatform == PlatformComposite { - return []string{PlatformAnthropic, PlatformGemini, PlatformOpenAI, PlatformAntigravity, PlatformGrok, PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo, PlatformTypeSafe} + return []string{PlatformAnthropic, PlatformGemini, PlatformOpenAI, PlatformAntigravity, PlatformGrok, PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo, PlatformTypeSafe, PlatformOllamaCloud} } return []string{groupPlatform} } diff --git a/backend/internal/service/channel_service_test.go b/backend/internal/service/channel_service_test.go index 62ba8e0b9a..9b96903324 100644 --- a/backend/internal/service/channel_service_test.go +++ b/backend/internal/service/channel_service_test.go @@ -2127,7 +2127,7 @@ func TestMatchingPlatforms(t *testing.T) { {"anthropic returns itself", PlatformAnthropic, []string{PlatformAnthropic}}, {"gemini returns itself", PlatformGemini, []string{PlatformGemini}}, {"openai returns itself", PlatformOpenAI, []string{PlatformOpenAI}}, - {"composite returns concrete platforms", PlatformComposite, []string{PlatformAnthropic, PlatformGemini, PlatformOpenAI, PlatformAntigravity, PlatformGrok, PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo, PlatformTypeSafe}}, + {"composite returns concrete platforms", PlatformComposite, []string{PlatformAnthropic, PlatformGemini, PlatformOpenAI, PlatformAntigravity, PlatformGrok, PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo, PlatformTypeSafe, PlatformOllamaCloud}}, } for _, tt := range tests { diff --git a/backend/internal/service/scheduler_snapshot_bulk_event_test.go b/backend/internal/service/scheduler_snapshot_bulk_event_test.go index 17bfec7c9f..49feb5aacb 100644 --- a/backend/internal/service/scheduler_snapshot_bulk_event_test.go +++ b/backend/internal/service/scheduler_snapshot_bulk_event_test.go @@ -115,7 +115,7 @@ func TestSchedulerBulkAccountEventScopesOpenAIRebuildToFreshPlatform(t *testing. } func TestSchedulerBulkAccountEventScopesCNRebuildToFreshPlatform(t *testing.T) { - for _, platform := range []string{PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo} { + for _, platform := range []string{PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo, PlatformOllamaCloud} { t.Run(platform, func(t *testing.T) { cache := newBulkEventSnapshotCache() repo := newBulkEventAccountRepo(&Account{ID: 1, Platform: platform, GroupIDs: []int64{12}}) From 551797e24f76344813a78585079ba3ff4d6bd25e Mon Sep 17 00:00:00 2001 From: alfadb Date: Sun, 13 Sep 2026 00:57:04 +0800 Subject: [PATCH 12/81] feat(ollama): platform-ize ollama_cloud usage service - D1(u): usage platform whitelist now admits platform=ollama_cloud via authoritative OllamaCloudUsagePlatforms (ollama_cloud + legacy host platforms); host gate (official ollama.com) untouched - D3(u): repository SQL platform whitelist derived from the service list (const -> var via ollamaCloudPlatformsSQLLiteral) instead of a hand mirrored literal - drift now structurally impossible - D4(u)+F3: TestOllamaCloudUsagePlatformsMirror locks the derivation (parse count, ElementsMatch, eligible SQL contains every platform); existing predicate test covers ollama_cloud and dynamically sized list - D2(u): ErrOllamaCloudUsageAccountInvalid message derived from the whitelist (code unchanged - external contract) - D6(u): doc comment on IsOllamaCloudUsageAccount (three conditions, reverse-proxy eligible=false is expected) - D8(u): decision record on ollamaCloudUsageSettingsURL (hardcoded official settings page, not configurable - host gate / SSRF surface) - D9(u): OllamaCloudUsageState.EligibleReason distinguishes platform_not_eligible / wrong_account_type / unsupported_base_url - F5: service usage tests cover ollama_cloud platform (official host pass, reverse-proxy fail, oauth reject) and reason codes --- .../account_repo_ollama_cloud_usage.go | 25 +++-- .../account_repo_ollama_cloud_usage_test.go | 37 +++++-- .../proxy_repo_upstream_billing_probe_test.go | 4 +- .../internal/service/ollama_cloud_usage.go | 99 +++++++++++++++---- .../service/ollama_cloud_usage_test.go | 75 +++++++++++++- 5 files changed, 201 insertions(+), 39 deletions(-) diff --git a/backend/internal/repository/account_repo_ollama_cloud_usage.go b/backend/internal/repository/account_repo_ollama_cloud_usage.go index d5b506ab7a..2be8bae189 100644 --- a/backend/internal/repository/account_repo_ollama_cloud_usage.go +++ b/backend/internal/repository/account_repo_ollama_cloud_usage.go @@ -4,6 +4,7 @@ import ( "context" "encoding/json" "errors" + "strings" "time" dbent "github.com/Wei-Shaw/sub2api/ent" @@ -15,17 +16,29 @@ const ( ollamaCloudBaseURLRegexSQL = `^[hH][tT][tT][pP][sS]://([wW][wW][wW]\.)?[oO][lL][lL][aA][mM][aA]\.[cC][oO][mM](:443)?(/v1)?$` ollamaCloudBaseURLMatchSQLPrefix = "btrim(" ollamaCloudBaseURLMatchSQLSuffix = ") ~ '" + ollamaCloudBaseURLRegexSQL + "'" - // ollamaCloudUsagePlatformsSQL 是 service.isOllamaCloudUsagePlatform 的 SQL - // 镜像:Ollama Cloud key 允许挂在 openai/anthropic 与国产 OpenAI 兼容平台 - // 下复用。所有平台白名单 SQL 只允许引用本常量,不得各处重写字面量,防止漂移。 - ollamaCloudUsagePlatformsSQL = "'openai', 'anthropic', 'kimi', 'zhipu', 'deepseek', 'minimax'" - ollamaCloudUsageEligibleSQL = ` +) + +// ollamaCloudUsagePlatformsSQL 是 service.OllamaCloudUsagePlatforms(权威平台 +// 白名单,含 platform=ollama_cloud 本体与 legacy 宿主平台)派生的 SQL IN +// 字面量。派生自同一列表,两侧结构上不可能漂移;原先的手工镜像注释随之作废。 +// 所有平台白名单 SQL 只允许引用本变量,不得各处重写字面量。 +var ollamaCloudUsagePlatformsSQL = ollamaCloudPlatformsSQLLiteral(service.OllamaCloudUsagePlatforms) + +var ollamaCloudUsageEligibleSQL = ` platform IN (` + ollamaCloudUsagePlatformsSQL + `) AND type = 'apikey' AND ` + ollamaCloudBaseURLMatchSQLPrefix + `credentials ->> 'base_url'` + ollamaCloudBaseURLMatchSQLSuffix + ` AND jsonb_typeof(credentials -> 'api_key') = 'string' ` -) + +// ollamaCloudPlatformsSQLLiteral 把平台列表渲染为 SQL IN 字面量('a', 'b')。 +func ollamaCloudPlatformsSQLLiteral(platforms []string) string { + quoted := make([]string, len(platforms)) + for i, platform := range platforms { + quoted[i] = "'" + platform + "'" + } + return strings.Join(quoted, ", ") +} func ollamaCloudBaseURLMatchesSQL(expression string) string { return ollamaCloudBaseURLMatchSQLPrefix + expression + ollamaCloudBaseURLMatchSQLSuffix diff --git a/backend/internal/repository/account_repo_ollama_cloud_usage_test.go b/backend/internal/repository/account_repo_ollama_cloud_usage_test.go index 6891eb7b80..42617672b3 100644 --- a/backend/internal/repository/account_repo_ollama_cloud_usage_test.go +++ b/backend/internal/repository/account_repo_ollama_cloud_usage_test.go @@ -4,6 +4,7 @@ import ( "context" "encoding/json" "regexp" + "slices" "strings" "testing" "time" @@ -179,7 +180,7 @@ func TestListOllamaCloudUsageGroupAccountsUsesOneStrictBatchQuery(t *testing.T) require.Empty(t, accounts) query := normalizeSQLWhitespace(capturedSQL) require.Contains(t, query, "credentials ->> 'api_key' = ANY($1)") - require.Contains(t, query, "platform IN ('openai', 'anthropic', 'kimi', 'zhipu', 'deepseek', 'minimax')") + require.Contains(t, query, "platform IN ("+ollamaCloudUsagePlatformsSQL+")") require.Contains(t, query, "jsonb_typeof(credentials -> 'api_key') = 'string'") require.Contains(t, query, ollamaCloudBaseURLMatchesSQL("credentials ->> 'base_url'")) require.NotContains(t, query, "~*") @@ -207,7 +208,7 @@ func TestListDueOllamaCloudUsageAccountsFiltersOrdersAndLimits(t *testing.T) { for _, clause := range []string{ "deleted_at IS NULL", "status = 'active'", - "platform IN ('openai', 'anthropic', 'kimi', 'zhipu', 'deepseek', 'minimax')", + "platform IN (" + ollamaCloudUsagePlatformsSQL + ")", "type = 'apikey'", ollamaCloudBaseURLMatchesSQL("credentials ->> 'base_url'"), "jsonb_typeof(extra -> 'ollama_cloud_usage_session') = 'string'", @@ -251,7 +252,7 @@ func TestBulkUpdateOllamaIdentityCleanupIsValueConditional(t *testing.T) { require.Contains(t, query, "NOT ("+ollamaCloudBaseURLMatchesSQL("credentials ->> 'base_url'")) require.Contains(t, query, ollamaCloudBaseURLMatchesSQL("$1::jsonb ->> 'base_url'")) require.NotContains(t, query, "~*") - require.Contains(t, query, "platform IN ('openai', 'anthropic', 'kimi', 'zhipu', 'deepseek', 'minimax') AND type = 'apikey'") + require.Contains(t, query, "platform IN ("+ollamaCloudUsagePlatformsSQL+") AND type = 'apikey'") require.Contains(t, query, "- 'ollama_cloud_usage_session' - 'ollama_cloud_usage_auto_refresh' - 'ollama_cloud_usage_snapshot'") payload, ok := exec.execArgs[0][0].([]byte) require.True(t, ok) @@ -317,7 +318,7 @@ func TestUpdateCredentialsCleanupBranchRequiresChangedCredentials(t *testing.T) require.NoError(t, mock.ExpectationsWereMet()) } -// SQL 平台白名单常量与 service 判定必须互为镜像:对每个已知平台,常量里的 +// SQL 平台白名单与 service 判定必须互为镜像:对每个已知平台,常量里的 // 成员关系都要与 IsOllamaCloudUsageAccount(apikey + 官方 ollama.com)一致, // 防止两侧平台列表各自漂移。 func TestOllamaCloudUsagePlatformWhitelistMatchesServicePredicate(t *testing.T) { @@ -326,13 +327,11 @@ func TestOllamaCloudUsagePlatformWhitelistMatchesServicePredicate(t *testing.T) for _, match := range matches { sqlPlatforms[match[1]] = struct{}{} } - require.Len(t, sqlPlatforms, 6) - for _, platform := range []string{ - service.PlatformOpenAI, service.PlatformAnthropic, - service.PlatformKimi, service.PlatformZhipu, service.PlatformDeepseek, service.PlatformMiniMax, + require.Len(t, sqlPlatforms, len(service.OllamaCloudUsagePlatforms)) + for _, platform := range append(slices.Clone(service.OllamaCloudUsagePlatforms), service.PlatformGemini, service.PlatformGrok, service.PlatformAntigravity, service.PlatformComposite, "kiro", - } { + ) { account := ollamaCloudUsageRepositoryAccount() account.Platform = platform _, inSQL := sqlPlatforms[platform] @@ -340,6 +339,24 @@ func TestOllamaCloudUsagePlatformWhitelistMatchesServicePredicate(t *testing.T) } } +// TestOllamaCloudUsagePlatformsMirror 锁定 SQL 平台白名单由 service 权威列表 +// (OllamaCloudUsagePlatforms,含 ollama_cloud 本体)派生这一事实:字面量可 +// 完整解析、成员一致、eligible 拼接结果包含全部平台项。若有人把派生改回手工 +// 字面量并漏掉/多写平台,本测试立即红。 +func TestOllamaCloudUsagePlatformsMirror(t *testing.T) { + matches := regexp.MustCompile(`'([^']+)'`).FindAllStringSubmatch(ollamaCloudUsagePlatformsSQL, -1) + sqlPlatforms := make([]string, 0, len(matches)) + for _, match := range matches { + sqlPlatforms = append(sqlPlatforms, match[1]) + } + require.Len(t, matches, len(service.OllamaCloudUsagePlatforms), "SQL 字面量解析出的平台项数量必须与权威列表一致") + require.ElementsMatch(t, service.OllamaCloudUsagePlatforms, sqlPlatforms) + require.Contains(t, sqlPlatforms, service.PlatformOllamaCloud) + for _, platform := range service.OllamaCloudUsagePlatforms { + require.Contains(t, ollamaCloudUsageEligibleSQL, "'"+platform+"'") + } +} + // 语义等价性:平台放开后,普通(非 ollama)kimi apikey 账号改凭证会从通用 // apikey 分支落到 Ollama 分支——多减三个它本来就不存在的 ollama 键。分支必须 // 仍然清掉 probe 快照,且不得减其它任何 extra 键。 @@ -373,7 +390,7 @@ func TestUpdateCredentialsPlainCNAPIKeyAccountCleanupStaysSemanticallyEquivalent require.NoError(t, err) query := normalizeSQLWhitespace(capturedSQL) require.Contains(t, query, - "platform IN ('openai', 'anthropic', 'kimi', 'zhipu', 'deepseek', 'minimax') AND type = 'apikey' AND credentials IS DISTINCT FROM $1::jsonb") + "platform IN ("+ollamaCloudUsagePlatformsSQL+") AND type = 'apikey' AND credentials IS DISTINCT FROM $1::jsonb") require.Contains(t, query, "THEN COALESCE(extra, '{}'::jsonb) - 'upstream_billing_probe' - 'ollama_cloud_usage_session' - 'ollama_cloud_usage_auto_refresh' - 'ollama_cloud_usage_snapshot'") require.NotContains(t, query, "- 'upstream_billing_probe_enabled'") diff --git a/backend/internal/repository/proxy_repo_upstream_billing_probe_test.go b/backend/internal/repository/proxy_repo_upstream_billing_probe_test.go index 7d0eb8957b..595a48ddfd 100644 --- a/backend/internal/repository/proxy_repo_upstream_billing_probe_test.go +++ b/backend/internal/repository/proxy_repo_upstream_billing_probe_test.go @@ -30,7 +30,7 @@ func TestProxyUpdateInvalidatesBoundProbeSnapshotsAndEnqueuesOutboxAtomically(t AddRow("http", "old.example", 8080, "user", "pass", service.StatusActive)) mock.ExpectExec(`(?s)UPDATE "proxies" SET`).WillReturnResult(sqlmock.NewResult(0, 1)) expectProxyUpdateReload(mock, 9, "new.example", "user", "pass") - mock.ExpectQuery(`(?s)UPDATE accounts.*- 'upstream_billing_probe'.*- 'ollama_cloud_usage_snapshot'.*type = 'apikey'.*extra \? 'upstream_billing_probe'.*platform IN \('openai', 'anthropic', 'kimi', 'zhipu', 'deepseek', 'minimax'\).*extra \? 'ollama_cloud_usage_snapshot'.*RETURNING id`). + mock.ExpectQuery(`(?s)UPDATE accounts.*- 'upstream_billing_probe'.*- 'ollama_cloud_usage_snapshot'.*type = 'apikey'.*extra \? 'upstream_billing_probe'.*platform IN \(` + regexp.QuoteMeta(ollamaCloudUsagePlatformsSQL) + `\).*extra \? 'ollama_cloud_usage_snapshot'.*RETURNING id`). WithArgs(int64(9)). WillReturnRows(sqlmock.NewRows([]string{"id"}).AddRow(int64(17)).AddRow(int64(18))) mock.ExpectExec(regexp.QuoteMeta("INSERT INTO scheduler_outbox (event_type, account_id, group_id, payload)")). @@ -70,7 +70,7 @@ func TestProxyUpdateRollsBackWhenProbeInvalidationOutboxFails(t *testing.T) { AddRow("http", "old.example", 8080, "", "", service.StatusActive)) mock.ExpectExec(`(?s)UPDATE "proxies" SET`).WillReturnResult(sqlmock.NewResult(0, 1)) expectProxyUpdateReload(mock, 9, "new.example", "", "") - mock.ExpectQuery(`(?s)UPDATE accounts.*- 'upstream_billing_probe'.*- 'ollama_cloud_usage_snapshot'.*type = 'apikey'.*extra \? 'upstream_billing_probe'.*platform IN \('openai', 'anthropic', 'kimi', 'zhipu', 'deepseek', 'minimax'\).*extra \? 'ollama_cloud_usage_snapshot'.*RETURNING id`). + mock.ExpectQuery(`(?s)UPDATE accounts.*- 'upstream_billing_probe'.*- 'ollama_cloud_usage_snapshot'.*type = 'apikey'.*extra \? 'upstream_billing_probe'.*platform IN \(` + regexp.QuoteMeta(ollamaCloudUsagePlatformsSQL) + `\).*extra \? 'ollama_cloud_usage_snapshot'.*RETURNING id`). WithArgs(int64(9)). WillReturnRows(sqlmock.NewRows([]string{"id"}).AddRow(int64(17))) mock.ExpectExec(regexp.QuoteMeta("INSERT INTO scheduler_outbox (event_type, account_id, group_id, payload)")). diff --git a/backend/internal/service/ollama_cloud_usage.go b/backend/internal/service/ollama_cloud_usage.go index a797246499..5fee972c36 100644 --- a/backend/internal/service/ollama_cloud_usage.go +++ b/backend/internal/service/ollama_cloud_usage.go @@ -13,6 +13,7 @@ import ( "math/rand/v2" "net/http" "net/url" + "slices" "strconv" "strings" "sync" @@ -39,6 +40,10 @@ const ( // floor inside the SQL due filter. OllamaCloudUsageMinFetchInterval = ollamaCloudUsageMinIntervalMinutes * time.Minute + // 决策记录:抓取目标恒为官方 settings 页,硬编码且不做可配置——保住 + // isExactOllamaCloudSettingsURL 的 host 门禁、不扩大 SSRF 面(请求发出前与 + // 重定向后都复核该 URL)。反代账号 eligible=false 是预期,见 + // IsOllamaCloudUsageAccount 注释。 ollamaCloudUsageSettingsURL = "https://ollama.com/settings" ollamaCloudUsageDefaultIntervalMinutes = 60 ollamaCloudUsageMinIntervalMinutes = 15 @@ -62,8 +67,13 @@ var ( ErrOllamaCloudUsageUnavailable = infraerrors.ServiceUnavailable( "OLLAMA_CLOUD_USAGE_UNAVAILABLE", "Ollama Cloud usage is unavailable", ) + // 文案由平台白名单(OllamaCloudUsagePlatforms)派生,白名单变化时不再漂移; + // 错误码 OLLAMA_CLOUD_USAGE_ACCOUNT_INVALID 是对外契约,不得改名。 + ollamaCloudUsageAccountInvalidMessage = "account must be an official Ollama Cloud API key account (platform " + + strings.Join(OllamaCloudUsagePlatforms, "/") + ") using https://ollama.com" + ErrOllamaCloudUsageAccountInvalid = infraerrors.BadRequest( - "OLLAMA_CLOUD_USAGE_ACCOUNT_INVALID", "account must be an OpenAI or Anthropic API key account using https://ollama.com", + "OLLAMA_CLOUD_USAGE_ACCOUNT_INVALID", ollamaCloudUsageAccountInvalidMessage, ) ErrOllamaCloudUsageSessionRequired = infraerrors.BadRequest( "OLLAMA_CLOUD_USAGE_SESSION_REQUIRED", "an Ollama web session must be configured first", @@ -148,8 +158,12 @@ type OllamaCloudUsageSnapshot struct { // OllamaCloudUsageState is the dedicated DTO exposed to administrators. type OllamaCloudUsageState struct { - AccountID int64 `json:"account_id"` - Eligible bool `json:"eligible"` + AccountID int64 `json:"account_id"` + Eligible bool `json:"eligible"` + // EligibleReason 说明 eligible=false 的具体原因("" 表示合格): + // platform_not_eligible / wrong_account_type / unsupported_base_url, + // 供管理端区分「平台不合规 / 类型不对 / base_url 反代」。 + EligibleReason string `json:"eligible_reason,omitempty"` Configured bool `json:"configured"` AutoRefreshEnabled bool `json:"auto_refresh_enabled"` EncryptionKeyConfigured bool `json:"encryption_key_configured"` @@ -1010,7 +1024,8 @@ func OllamaCloudUsageStateFromAccount(account *Account) *OllamaCloudUsageState { return state } state.AccountID = account.ID - state.Eligible = IsOllamaCloudUsageAccount(account) + state.EligibleReason = ollamaCloudUsageEligibilityReason(account) + state.Eligible = state.EligibleReason == "" if !state.Eligible { return state } @@ -1020,26 +1035,70 @@ func OllamaCloudUsageStateFromAccount(account *Account) *OllamaCloudUsageState { return state } -// isOllamaCloudUsagePlatform 收敛 Ollama Cloud 用量窗口的平台白名单。官方 -// ollama.com base_url 除官方两平台外,也允许挂在经 OpenAI 网关转发的国产 -// OpenAI 兼容平台下(用户把 Ollama Cloud key 挂在 kimi/zhipu/deepseek 分组 -// 里跑托管的 glm/kimi/deepseek 模型)。repository 侧 SQL 白名单 -// (ollamaCloudUsagePlatformsSQL)是本列表的镜像,两侧必须同步修改。 -func isOllamaCloudUsagePlatform(platform string) bool { - switch platform { - case PlatformOpenAI, PlatformAnthropic, PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax: - return true - default: - return false - } +// ollamaCloudUsageLegacyPlatforms 是 platform 化之前承载官方 ollama.com +// base_url 的宿主平台(openai/anthropic 与经 OpenAI 网关转发的国产 OpenAI +// 兼容平台——用户把 Ollama Cloud key 挂在 kimi/zhipu/deepseek 等分组里跑托管 +// 模型)。存量账号迁到 platform=ollama_cloud(增量 6 存量改写)之前仍靠它进入 +// 用量链路。 +var ollamaCloudUsageLegacyPlatforms = []string{ + PlatformOpenAI, PlatformAnthropic, PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, } -func IsOllamaCloudUsageAccount(account *Account) bool { - if account == nil || account.Type != AccountTypeAPIKey || !isOllamaCloudUsagePlatform(account.Platform) { - return false +// OllamaCloudUsagePlatforms 是 Ollama Cloud 用量平台白名单的权威列表 +// (legacy 宿主平台 + platform=ollama_cloud 本体)。repository 侧 SQL 白名单 +// ollamaCloudUsagePlatformsSQL 直接由本列表派生,新增平台只改这里。 +var OllamaCloudUsagePlatforms = append(slices.Clone(ollamaCloudUsageLegacyPlatforms), PlatformOllamaCloud) + +// ollamaCloudUsageIneligible* 是 EligibleReason 的取值(D9):与 +// ollamaCloudUsageEligibilityReason 的判定顺序一一对应。 +const ( + ollamaCloudUsageIneligiblePlatform = "platform_not_eligible" + ollamaCloudUsageIneligibleAccountType = "wrong_account_type" + ollamaCloudUsageIneligibleBaseURL = "unsupported_base_url" +) + +// isOllamaCloudUsagePlatform 收敛 Ollama Cloud 用量窗口的平台白名单:新 +// platform 本体 + platform 化之前的 legacy 宿主平台。 +func isOllamaCloudUsagePlatform(platform string) bool { + return platform == PlatformOllamaCloud || slices.Contains(ollamaCloudUsageLegacyPlatforms, platform) +} + +// ollamaCloudUsageEligibilityReason 返回账号进不了用量链路的具体原因("" +// 表示三条件全部通过)。IsOllamaCloudUsageAccount 与 +// OllamaCloudUsageStateFromAccount 共用本判定,避免两份条件各自漂移。 +func ollamaCloudUsageEligibilityReason(account *Account) string { + if account == nil { + return "" + } + if !isOllamaCloudUsagePlatform(account.Platform) { + return ollamaCloudUsageIneligiblePlatform + } + if account.Type != AccountTypeAPIKey { + return ollamaCloudUsageIneligibleAccountType } baseURL, _ := account.Credentials["base_url"].(string) - return isOllamaCloudBaseURL(baseURL) + if !isOllamaCloudBaseURL(baseURL) { + return ollamaCloudUsageIneligibleBaseURL + } + return "" +} + +// IsOllamaCloudUsageAccount 报告账号是否进入 Ollama Cloud 用量链路。三个条件 +// 全部满足才为 true: +// - 平台在白名单内(platform=ollama_cloud 或 legacy 宿主平台); +// - 类型为 apikey(用量身份复用账号的官方 API key,oauth 账号没有); +// - credentials.base_url 是官方 ollama.com host(严格 https、无多余 +// path/query,见 isOllamaCloudBaseURL)。 +// +// platform=ollama_cloud 账号同样受 host 门禁约束:反代域名即使平台合规也是 +// eligible=false——这是预期行为(抓取恒打官方 settings 页,见 +// ollamaCloudUsageSettingsURL 的决策记录),不是 bug。原因码见 +// OllamaCloudUsageState.EligibleReason。 +func IsOllamaCloudUsageAccount(account *Account) bool { + if account == nil { + return false + } + return ollamaCloudUsageEligibilityReason(account) == "" } func isOllamaCloudBaseURL(raw string) bool { diff --git a/backend/internal/service/ollama_cloud_usage_test.go b/backend/internal/service/ollama_cloud_usage_test.go index 5fcfd7e407..da1decb8ab 100644 --- a/backend/internal/service/ollama_cloud_usage_test.go +++ b/backend/internal/service/ollama_cloud_usage_test.go @@ -471,6 +471,12 @@ func TestIsOllamaCloudUsageAccountStrictOfficialHost(t *testing.T) { {"https://ollama.com", PlatformKimi, true}, {"https://www.ollama.com/v1", PlatformZhipu, true}, {"https://ollama.com:443", PlatformDeepseek, true}, + // platform=ollama_cloud 本体:官方 host 通过。 + {"https://ollama.com", PlatformOllamaCloud, true}, + {"https://www.ollama.com/v1", PlatformOllamaCloud, true}, + // platform=ollama_cloud 但 base_url 是反代域名:host 门禁不变,仍不合格。 + {"https://ollama.example.test", PlatformOllamaCloud, false}, + {"https://api.ollama-cloud.test/v1", PlatformOllamaCloud, false}, // 用量窗口不随 base_url 放开到其余平台。 {"https://ollama.com", PlatformGemini, false}, {"https://ollama.com", PlatformGrok, false}, @@ -497,7 +503,7 @@ func TestIsOllamaCloudUsageAccountStrictOfficialHost(t *testing.T) { // oauth 类型账号即使平台与 base_url 都命中也不进用量窗口(仅 apikey 账号)。 func TestIsOllamaCloudUsageAccountRejectsOAuthType(t *testing.T) { - for _, platform := range []string{PlatformOpenAI, PlatformAnthropic, PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax} { + for _, platform := range []string{PlatformOllamaCloud, PlatformOpenAI, PlatformAnthropic, PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax} { account := ollamaUsageAccount(1) account.Platform = platform account.Type = AccountTypeOAuth @@ -505,6 +511,73 @@ func TestIsOllamaCloudUsageAccountRejectsOAuthType(t *testing.T) { } } +// OllamaCloudUsageState.EligibleReason:三种不合格各自返回对应原因码,合格时 +// 原因为空;与 IsOllamaCloudUsageAccount 判定保持一致。 +func TestOllamaCloudUsageStateEligibleReason(t *testing.T) { + tests := []struct { + name string + mutate func(account *Account) + // eligible 期望值;reason 为 "" 时断言合格且原因码为空。 + reason string + }{ + { + name: "platform 不在白名单", + mutate: func(account *Account) { account.Platform = PlatformGemini }, + reason: "platform_not_eligible", + }, + { + name: "oauth 类型", + mutate: func(account *Account) { account.Type = AccountTypeOAuth }, + reason: "wrong_account_type", + }, + { + name: "反代 base_url", + mutate: func(account *Account) { account.Credentials["base_url"] = "https://ollama.example.test" }, + reason: "unsupported_base_url", + }, + { + name: "platform=ollama_cloud + 官方 host 合格", + mutate: func(account *Account) { + account.Platform = PlatformOllamaCloud + account.Extra[OllamaCloudUsageSessionExtraKey] = "cipher:wos-session=secret" + }, + reason: "", + }, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + account := ollamaUsageAccount(1) + account.Platform = PlatformOllamaCloud + test.mutate(account) + + state := OllamaCloudUsageStateFromAccount(account) + require.Equal(t, state.EligibleReason == "", state.Eligible) + require.Equal(t, test.reason, state.EligibleReason) + require.Equal(t, test.reason == "", IsOllamaCloudUsageAccount(account)) + if test.reason == "" { + require.True(t, state.Configured) + } + }) + } + + // nil 账号保持既有行为:空 state、不合格、无原因码。 + state := OllamaCloudUsageStateFromAccount(nil) + require.False(t, state.Eligible) + require.Empty(t, state.EligibleReason) +} + +// 错误文案由平台白名单派生(D2):platform 化后必须包含 ollama_cloud,不再 +// 残留「OpenAI or Anthropic」旧文案;错误码是对外契约,保持不变。 +func TestOllamaCloudUsageAccountInvalidMessageDerivedFromWhitelist(t *testing.T) { + message := ErrOllamaCloudUsageAccountInvalid.Error() + require.Contains(t, message, "OLLAMA_CLOUD_USAGE_ACCOUNT_INVALID") + require.Contains(t, message, "ollama_cloud") + for _, platform := range OllamaCloudUsagePlatforms { + require.Contains(t, message, platform) + } + require.NotContains(t, message, "OpenAI or Anthropic") +} + func TestNormalizeOllamaCloudUsageCookieAllowlist(t *testing.T) { normalized, err := normalizeOllamaCloudUsageCookie(" tracking=discard ; wos-session=secret ; __Secure-authjs.session-token.0=part-a ; device=discard ") require.NoError(t, err) From 61441ba44d4cac2959d578138ed34a9e02c23009 Mon Sep 17 00:00:00 2001 From: alfadb Date: Sun, 13 Sep 2026 01:02:16 +0800 Subject: [PATCH 13/81] feat(ui): render ollama_cloud usage cell E17: account for ollama_cloud explicitly in both usage-cell computeds. Empirically the cell already renders via the generic api-key root branch (eligible -> OllamaCloudUsageCell + today-stats, ineligible -> '-' placeholder), because eligibility itself is server-driven (ollama_cloud_usage.eligible, fixed backend-side in the previous commit); so the computeds pin that behavior instead of flipping to the scrolling-window root branch, which would drop today-stats rows and fire /usage calls the backend rejects for api-key accounts. - showUsageWindows: explicit ollama_cloud api-key branch -> false (generic api-key branch renders the Ollama cell) - shouldFetchUsage: document why ollama_cloud stays unfetched (backend /usage rejects api-key accounts; data arrives via account payload and the dedicated refresh endpoint, same shape as CN platforms) - tests: eligible renders OllamaCloudUsageCell without /usage fetch; missing/eligible=false renders placeholder, never CN quota cells --- .../components/account/AccountUsageCell.vue | 7 +++ .../__tests__/AccountUsageCell.spec.ts | 52 +++++++++++++++++++ 2 files changed, 59 insertions(+) diff --git a/frontend/src/components/account/AccountUsageCell.vue b/frontend/src/components/account/AccountUsageCell.vue index eb47cf8074..598064c036 100644 --- a/frontend/src/components/account/AccountUsageCell.vue +++ b/frontend/src/components/account/AccountUsageCell.vue @@ -752,6 +752,10 @@ let visibilityObserver: IntersectionObserver | null = null const showUsageWindows = computed(() => { // Gemini: we can always compute local usage windows from DB logs (simulated quotas). if (props.account.platform === 'gemini') return true + // Ollama Cloud(apikey):不进本根分支——由下方 apikey 根分支渲染 + // OllamaCloudUsageCell(数据随账号 payload 下发 + 专用刷新端点,还带 + // today-stats 行)。eligibility 由后端下发的 ollama_cloud_usage.eligible 决定。 + if (props.account.platform === 'ollama_cloud' && props.account.type === 'apikey') return false // CN providers: apikey 账号也有滚动用量窗口(coding plan)或余额(payg), // 由 CNProviderQuotaCell / CNProviderBalanceCell 自行探测与展示。 if ( @@ -782,6 +786,9 @@ const shouldFetchUsage = computed(() => { if (props.account.platform === 'openai') { return props.account.type === 'oauth' } + // ollama_cloud 与 CN 平台同构:/usage API 对 apikey 账号一律拒绝(后端只 + // 支持 oauth/setup-token 查询);Ollama Cloud 用量数据随账号 payload 下发、 + // 由 OllamaCloudUsageCell 专用刷新端点更新——不拉取通用 /usage。 return false }) diff --git a/frontend/src/components/account/__tests__/AccountUsageCell.spec.ts b/frontend/src/components/account/__tests__/AccountUsageCell.spec.ts index c961f1eda5..2daa85e6e9 100644 --- a/frontend/src/components/account/__tests__/AccountUsageCell.spec.ts +++ b/frontend/src/components/account/__tests__/AccountUsageCell.spec.ts @@ -264,6 +264,58 @@ describe('AccountUsageCell', () => { expect(wrapper.find('[data-test="embedded-ollama"]').exists()).toBe(false) }) + // ollama_cloud 本体平台:eligible 由后端下发,api key 账号走通用 apikey 根 + // 分支(OllamaCloudUsageCell + today-stats),不进滚动用量窗口根分支,也不 + // 拉取通用 /usage(后端对 apikey 账号一律拒绝)。 + it('ollama_cloud apikey eligible 渲染 OllamaCloudUsageCell 且不经 /usage 拉取', async () => { + const wrapper = mount(AccountUsageCell, { + props: { + account: makeAccount({ + id: 9100, + platform: 'ollama_cloud', + type: 'apikey', + ollama_cloud_usage: makeOllamaUsage(9100) + }) + }, + global: { + stubs: { ...cnUsageCellStubs, UsageProgressBar: true, AccountQuotaInfo: true } + } + }) + + await flushPromises() + + expect(wrapper.find('[data-test="embedded-ollama"]').exists()).toBe(true) + expect(wrapper.find('[data-test="cn-quota-cell"]').exists()).toBe(false) + expect(wrapper.find('[data-test="cn-balance-cell"]').exists()).toBe(false) + expect(getUsage).not.toHaveBeenCalled() + }) + + it.each([ + { name: '无 ollama_cloud_usage', usage: undefined }, + { name: 'eligible=false', usage: makeOllamaUsage(9101, { eligible: false }) } + ])('ollama_cloud apikey 账号($name)渲染占位而非 CN quota 格', async ({ usage }) => { + const wrapper = mount(AccountUsageCell, { + props: { + account: makeAccount({ + id: 9101, + platform: 'ollama_cloud', + type: 'apikey', + ollama_cloud_usage: usage + }) + }, + global: { + stubs: { ...cnUsageCellStubs, UsageProgressBar: true, AccountQuotaInfo: true } + } + }) + + await flushPromises() + + expect(wrapper.find('[data-test="embedded-ollama"]').exists()).toBe(false) + expect(wrapper.find('[data-test="cn-quota-cell"]').exists()).toBe(false) + expect(wrapper.find('[data-test="cn-balance-cell"]').exists()).toBe(false) + expect(getUsage).not.toHaveBeenCalled() + }) + it.each(['opencode_go', 'kimi', 'zhipu', 'deepseek', 'minimax'] as const)( '%s 平台 OpenCode Go eligible 时只渲染 OpenCode 用量单元格并跳过 CN 子单元格', async (platform) => { From 361e584bcf28e7a8952a201ee1c4285c142b0cc8 Mon Sep 17 00:00:00 2001 From: alfadb Date: Sun, 13 Sep 2026 01:32:46 +0800 Subject: [PATCH 14/81] feat(ollama): make responses and max_tokens hooks platform-aware - C31: include ollama_cloud in SupportsNativeCNResponses so /v1/responses ingress routes to the platform-native endpoint instead of degrading to raw CC, and the stateless normalize hook (store=false + strip previous_response_id) now applies to ollama accounts - D2/C37': reject the stateful conversation field with an explicit 400 invalid_request_error on native Responses accounts instead of silently dropping context; normalizeDeepSeekResponsesRequestBody now returns ([]byte, error) with all three production call sites propagating the typed error as a client-visible 400 - D1': clamp max_tokens for non-DeepSeek models too on ollama.com upstreams (raw CC, native Responses, Anthropic Messages); the host check is the boundary, the >65535 upstream 400 is model-independent; delete the now-dead isOllamaCloudRawChatCompletionsAccount predicate - C39: mark ollama_cloud accounts force_responses in the Responses probe (per-protocol, no network probe) and let the admin handler schedule the probe for ollama_cloud accounts --- .../internal/handler/admin/account_handler.go | 5 +- backend/internal/service/account.go | 5 +- .../account_test_service_cn_adaptive.go | 9 +- .../service/adaptive_api_protocol_test.go | 22 +++++ backend/internal/service/cn_providers_test.go | 68 +++++++++++++-- .../ollama_cloud_messages_max_tokens.go | 9 +- .../ollama_cloud_messages_max_tokens_test.go | 12 +-- .../ollama_cloud_platform_routing_test.go | 9 +- .../service/openai_apikey_responses_probe.go | 11 ++- .../openai_apikey_responses_probe_test.go | 47 +++++++++++ .../openai_gateway_conversation_guard_test.go | 83 +++++++++++++++++++ ...penai_gateway_deepseek_input_image_test.go | 16 ++-- .../service/openai_gateway_forward.go | 13 ++- ...eway_messages_chat_fallback_ollama_test.go | 8 +- ...penai_gateway_ollama_cloud_cc_reasoning.go | 35 -------- ..._gateway_ollama_cloud_cc_reasoning_test.go | 58 +------------ .../openai_gateway_ollama_cloud_max_tokens.go | 23 +++-- ...ai_gateway_ollama_cloud_max_tokens_test.go | 75 +++++++++-------- .../service/openai_gateway_passthrough.go | 12 ++- .../service/openai_gateway_request_body.go | 58 ++++++++++--- ...way_responses_chat_fallback_ollama_test.go | 7 +- 21 files changed, 385 insertions(+), 200 deletions(-) create mode 100644 backend/internal/service/openai_gateway_conversation_guard_test.go diff --git a/backend/internal/handler/admin/account_handler.go b/backend/internal/handler/admin/account_handler.go index 97ebd9ed35..f9eb1d483e 100644 --- a/backend/internal/handler/admin/account_handler.go +++ b/backend/internal/handler/admin/account_handler.go @@ -1220,13 +1220,14 @@ func (h *AccountHandler) Update(c *gin.Context) { // scheduleOpenAIResponsesProbe 异步触发 OpenAI APIKey 账号的 Responses API 能力探测。 // -// 仅对 platform=openai && type=apikey 账号生效;其他账号无操作。 +// 仅对 platform=openai / 国产供应商 / ollama_cloud && type=apikey 账号生效;其他账号 +// 无操作(国产与 ollama_cloud 在探针内按协议直接落标,不发网络请求)。 // 探测本身在 goroutine 中执行(会发一次 HTTP 请求到上游),不会阻塞 // 当前请求。探测错误仅记录日志,不向上下文传播:探测失败时标记保持缺失, // 网关会按"现状即证据"默认走 Responses。 func (h *AccountHandler) scheduleOpenAIResponsesProbe(account *service.Account) { if account == nil || account.Type != service.AccountTypeAPIKey || - (account.Platform != service.PlatformOpenAI && !service.IsCNProvider(account.Platform)) { + (account.Platform != service.PlatformOpenAI && !service.IsCNProvider(account.Platform) && !account.IsOllamaCloud()) { return } if h.accountTestService == nil { diff --git a/backend/internal/service/account.go b/backend/internal/service/account.go index d9f37bba52..ca08c4620f 100644 --- a/backend/internal/service/account.go +++ b/backend/internal/service/account.go @@ -1482,13 +1482,14 @@ func (a *Account) GetAPIProtocol() string { // SupportsNativeCNResponses 报告该国产供应商是否提供原生 Responses 端点。 // DeepSeek 官方为 /responses(无 /v1);Kimi 按量付费与 Coding Plan 均为 -// /v1/responses(moonshot.cn / kimi.com/coding);MiniMax 为 /v1/responses。 +// /v1/responses(moonshot.cn / kimi.com/coding);MiniMax 为 /v1/responses; +// Ollama Cloud 为 /v1/responses(non-stateful,见 normalizeDeepSeekResponsesRequestBody)。 func (a *Account) SupportsNativeCNResponses() bool { if a == nil { return false } switch a.Platform { - case PlatformDeepseek, PlatformKimi, PlatformMiniMax, PlatformOpenCodeGo: + case PlatformDeepseek, PlatformKimi, PlatformMiniMax, PlatformOpenCodeGo, PlatformOllamaCloud: return true default: return false diff --git a/backend/internal/service/account_test_service_cn_adaptive.go b/backend/internal/service/account_test_service_cn_adaptive.go index f56560d53d..991b53b02b 100644 --- a/backend/internal/service/account_test_service_cn_adaptive.go +++ b/backend/internal/service/account_test_service_cn_adaptive.go @@ -163,11 +163,14 @@ func (s *AccountTestService) testCNProviderAdaptiveResponsesConnection(c *gin.Co apiURL := buildOpenAIResponsesURLForPlatform(account.Platform, baseURL) payload := createOpenAITestPayload(testModelID, false) - // DeepSeek / Kimi native Responses endpoints are stateless and do not need - // the OpenAI probe's synthetic instructions. + // DeepSeek / Kimi / Ollama Cloud native Responses endpoints are stateless and + // do not need the OpenAI probe's synthetic instructions. delete(payload, "instructions") payloadBytes, _ := json.Marshal(payload) - payloadBytes = normalizeDeepSeekResponsesRequestBody(account, payloadBytes) + payloadBytes, payloadErr := normalizeDeepSeekResponsesRequestBody(account, payloadBytes) + if payloadErr != nil { + return s.sendErrorAndEnd(c, fmt.Sprintf("Adaptive Responses payload rejected: %s", payloadErr.Error())) + } s.sendEvent(c, TestEvent{Type: "status", Text: "正在通过原生 /responses 测试自适应 Responses 端点"}) req, err := http.NewRequestWithContext(ctx, http.MethodPost, apiURL, bytes.NewReader(payloadBytes)) diff --git a/backend/internal/service/adaptive_api_protocol_test.go b/backend/internal/service/adaptive_api_protocol_test.go index 3aef38698a..d7fe4da357 100644 --- a/backend/internal/service/adaptive_api_protocol_test.go +++ b/backend/internal/service/adaptive_api_protocol_test.go @@ -264,3 +264,25 @@ func TestFixedCNResponsesProtocolOverridesStaleChatMode(t *testing.T) { }) } } + +// TestAdaptiveProtocolRoutesOllamaCloudResponsesToNativeResponses 验证 C31 的连锁 +// 语义:SupportsNativeCNResponses 纳入 ollama_cloud 后,/v1/responses 入站不再被 +// C32 判定降级为 raw CC(https://ollama.com/v1/chat/completions),而是走平台原生 +// /v1/responses 端点;且 normalizeDeepSeekResponsesRequestBody 对 ollama 生效—— +// store 强制 false、previous_response_id 被剥离(Ollama /v1/responses 为 +// non-stateful,透传状态字段会被上游 400)。 +func TestAdaptiveProtocolRoutesOllamaCloudResponsesToNativeResponses(t *testing.T) { + gin.SetMode(gin.TestMode) + body := []byte(`{"model":"gpt-oss:120b-cloud","input":"hello","store":true,"previous_response_id":"resp_old","stream":false}`) + upstream := &httpUpstreamRecorder{err: errors.New("stop after capture")} + svc := &OpenAIGatewayService{cfg: rawChatCompletionsTestConfig(), httpUpstream: upstream} + // api_base_urls 为空 → adaptive 解析到平台默认端点 https://ollama.com/v1。 + account := adaptiveProtocolTestAccount(PlatformOllamaCloud, nil) + + _, err := svc.Forward(context.Background(), adaptiveProtocolTestContext("/v1/responses", body), account, body) + require.Error(t, err) + require.Equal(t, "https://ollama.com/v1/responses", upstream.lastReq.URL.String()) + require.False(t, gjson.GetBytes(upstream.lastBody, "store").Bool()) + require.False(t, gjson.GetBytes(upstream.lastBody, "previous_response_id").Exists()) + require.True(t, gjson.GetBytes(upstream.lastBody, "input").Exists()) +} diff --git a/backend/internal/service/cn_providers_test.go b/backend/internal/service/cn_providers_test.go index 9e62ca3534..bab823a433 100644 --- a/backend/internal/service/cn_providers_test.go +++ b/backend/internal/service/cn_providers_test.go @@ -645,6 +645,8 @@ func TestGetAPIProtocol(t *testing.T) { require.Equal(t, APIProtocolChatCompletions, (&Account{Platform: PlatformOpenAI, Type: AccountTypeAPIKey}).GetAPIProtocol(), "非 CN 供应商恒为默认") require.Equal(t, APIProtocolAdaptive, mk(PlatformOpenCodeGo, "").GetAPIProtocol(), "opencode go 默认 adaptive") require.Equal(t, APIProtocolResponses, mk(PlatformOpenCodeGo, APIProtocolResponses).GetAPIProtocol()) + require.Equal(t, APIProtocolAdaptive, mk(PlatformOllamaCloud, "").GetAPIProtocol(), "ollama cloud 默认 adaptive") + require.Equal(t, APIProtocolResponses, mk(PlatformOllamaCloud, APIProtocolResponses).GetAPIProtocol(), "ollama cloud 原生 Responses 端点,显式 responses 不被吞成 adaptive") } func TestSupportsNativeCNResponses(t *testing.T) { @@ -654,6 +656,7 @@ func TestSupportsNativeCNResponses(t *testing.T) { require.True(t, (&Account{Platform: PlatformKimi, Credentials: map[string]any{"account_mode": AccountModeCoding}}).SupportsNativeCNResponses()) require.True(t, (&Account{Platform: PlatformMiniMax}).SupportsNativeCNResponses()) require.True(t, (&Account{Platform: PlatformOpenCodeGo}).SupportsNativeCNResponses()) + require.True(t, (&Account{Platform: PlatformOllamaCloud, Type: AccountTypeAPIKey}).SupportsNativeCNResponses(), "ollama cloud 有原生 /v1/responses 端点") require.False(t, (&Account{Platform: PlatformZhipu}).SupportsNativeCNResponses()) require.False(t, (&Account{Platform: PlatformOpenAI}).SupportsNativeCNResponses()) } @@ -815,7 +818,8 @@ func TestBuildOpenAIResponsesURLForPlatform(t *testing.T) { } // TestNormalizeDeepSeekResponsesRequestBody 无状态适配:强制 store=false、 -// 清除 previous_response_id;非原生 CN Responses 协议原样返回。 +// 清除 previous_response_id;携带 conversation 显式报错且不改写 body; +// 非原生 CN Responses 协议原样返回(conversation 也不拦)。 func TestNormalizeDeepSeekResponsesRequestBody(t *testing.T) { t.Parallel() @@ -824,7 +828,8 @@ func TestNormalizeDeepSeekResponsesRequestBody(t *testing.T) { Credentials: map[string]any{"api_protocol": APIProtocolResponses}, } body := []byte(`{"model":"deepseek-v4-pro","store":true,"previous_response_id":"resp_123","input":"hi"}`) - normalized := normalizeDeepSeekResponsesRequestBody(deepseekResponses, body) + normalized, err := normalizeDeepSeekResponsesRequestBody(deepseekResponses, body) + require.NoError(t, err) require.False(t, gjson.GetBytes(normalized, "store").Bool()) require.False(t, gjson.GetBytes(normalized, "previous_response_id").Exists()) require.Equal(t, "deepseek-v4-pro", gjson.GetBytes(normalized, "model").String()) @@ -833,12 +838,14 @@ func TestNormalizeDeepSeekResponsesRequestBody(t *testing.T) { Platform: PlatformDeepseek, Type: AccountTypeAPIKey, Credentials: map[string]any{"api_protocol": APIProtocolAdaptive}, } - adaptiveNormalized := normalizeDeepSeekResponsesRequestBody(deepseekAdaptive, body) + adaptiveNormalized, err := normalizeDeepSeekResponsesRequestBody(deepseekAdaptive, body) + require.NoError(t, err) require.False(t, gjson.GetBytes(adaptiveNormalized, "store").Bool()) require.False(t, gjson.GetBytes(adaptiveNormalized, "previous_response_id").Exists()) mediaBody := []byte(`{"model":"deepseek-v4.1-flash","store":true,"input":[{"type":"function_call","call_id":"call_image","name":"view_image","arguments":"{}"},{"type":"function_call_output","call_id":"call_image","output":[{"type":"input_image","image_url":"data:image/png;base64,AQID"}]}]}`) - mediaNormalized := normalizeDeepSeekResponsesRequestBody(deepseekResponses, mediaBody) + mediaNormalized, err := normalizeDeepSeekResponsesRequestBody(deepseekResponses, mediaBody) + require.NoError(t, err) require.False(t, gjson.GetBytes(mediaNormalized, "store").Bool()) require.Equal(t, gjson.String, gjson.GetBytes(mediaNormalized, "input.1.output").Type) require.NotContains(t, gjson.GetBytes(mediaNormalized, "input.1.output").String(), "data:image/png") @@ -849,13 +856,16 @@ func TestNormalizeDeepSeekResponsesRequestBody(t *testing.T) { // 非 responses 协议(deepseek CC 账号)原样返回 deepseekCC := &Account{Platform: PlatformDeepseek, Type: AccountTypeAPIKey} - require.Equal(t, string(body), string(normalizeDeepSeekResponsesRequestBody(deepseekCC, body))) + untouched, err := normalizeDeepSeekResponsesRequestBody(deepseekCC, body) + require.NoError(t, err) + require.Equal(t, string(body), string(untouched)) kimiResponses := &Account{ Platform: PlatformKimi, Type: AccountTypeAPIKey, Credentials: map[string]any{"api_protocol": APIProtocolResponses}, } - kimiNormalized := normalizeDeepSeekResponsesRequestBody(kimiResponses, body) + kimiNormalized, err := normalizeDeepSeekResponsesRequestBody(kimiResponses, body) + require.NoError(t, err) require.False(t, gjson.GetBytes(kimiNormalized, "store").Bool()) require.False(t, gjson.GetBytes(kimiNormalized, "previous_response_id").Exists()) @@ -863,13 +873,55 @@ func TestNormalizeDeepSeekResponsesRequestBody(t *testing.T) { Platform: PlatformKimi, Type: AccountTypeAPIKey, Credentials: map[string]any{"api_protocol": APIProtocolAdaptive, "account_mode": AccountModeCoding}, } - kimiCodingNormalized := normalizeDeepSeekResponsesRequestBody(kimiCodingAdaptive, body) + kimiCodingNormalized, err := normalizeDeepSeekResponsesRequestBody(kimiCodingAdaptive, body) + require.NoError(t, err) require.False(t, gjson.GetBytes(kimiCodingNormalized, "store").Bool()) require.False(t, gjson.GetBytes(kimiCodingNormalized, "previous_response_id").Exists()) // openai 账号原样返回 openai := &Account{Platform: PlatformOpenAI, Type: AccountTypeAPIKey} - require.Equal(t, string(body), string(normalizeDeepSeekResponsesRequestBody(openai, body))) + untouched, err = normalizeDeepSeekResponsesRequestBody(openai, body) + require.NoError(t, err) + require.Equal(t, string(body), string(untouched)) + + // ollama cloud adaptive(原生 non-stateful /v1/responses): + // store=false + 剥离 previous_response_id。 + ollamaAdaptive := &Account{ + Platform: PlatformOllamaCloud, Type: AccountTypeAPIKey, + Credentials: map[string]any{"api_protocol": APIProtocolAdaptive}, + } + ollamaNormalized, err := normalizeDeepSeekResponsesRequestBody(ollamaAdaptive, body) + require.NoError(t, err) + require.False(t, gjson.GetBytes(ollamaNormalized, "store").Bool()) + require.False(t, gjson.GetBytes(ollamaNormalized, "previous_response_id").Exists()) + + // ollama cloud + conversation:显式报错(无状态端点不支持服务端状态字段), + // body 必须保持原样——不是静默剥离。 + conversationBody := []byte(`{"model":"gpt-oss:120b-cloud","conversation":"conv_x","input":"hi"}`) + rejected, err := normalizeDeepSeekResponsesRequestBody(ollamaAdaptive, conversationBody) + require.Error(t, err) + require.Contains(t, err.Error(), "conversation") + require.Equal(t, string(conversationBody), string(rejected), "conversation 字段不得被剥离") + + // conversation 与 previous_response_id 并存时同样报错,不做部分清洗。 + mixed := []byte(`{"model":"deepseek-v4-pro","store":true,"previous_response_id":"resp_1","conversation":"conv_x","input":"hi"}`) + rejected, err = normalizeDeepSeekResponsesRequestBody(deepseekResponses, mixed) + require.Error(t, err) + require.Equal(t, string(mixed), string(rejected)) + + // 无 conversation 时 err 恒为 nil(存量剥离语义不受签名变化影响)。 + _, err = normalizeDeepSeekResponsesRequestBody(deepseekAdaptive, body) + require.NoError(t, err) + + // 门禁只对原生 Responses 账号生效:zhipu(无 Responses 端点)带 + // conversation 原样返回、无错误。 + zhipu := &Account{ + Platform: PlatformZhipu, Type: AccountTypeAPIKey, + Credentials: map[string]any{"api_protocol": APIProtocolAdaptive}, + } + untouched, err = normalizeDeepSeekResponsesRequestBody(zhipu, conversationBody) + require.NoError(t, err) + require.Equal(t, string(conversationBody), string(untouched)) } // TestGetAnthropicAPIKeyAuthScheme_CNProvider CN 账号可经 extra 覆写鉴权方案, diff --git a/backend/internal/service/ollama_cloud_messages_max_tokens.go b/backend/internal/service/ollama_cloud_messages_max_tokens.go index d178488460..4bd1498930 100644 --- a/backend/internal/service/ollama_cloud_messages_max_tokens.go +++ b/backend/internal/service/ollama_cloud_messages_max_tokens.go @@ -2,8 +2,6 @@ package service import ( "strings" - - "github.com/tidwall/gjson" ) // clampOllamaCloudAnthropicMessagesMaxTokens 是 Anthropic Messages 出站 @@ -12,8 +10,8 @@ import ( // 传入本次实际选用的 Anthropic 上游 base_url(GetBaseURL 或 // GetAnthropicProtocolBaseURL,不用 GetOpenAIBaseURL——adaptive 时那是 CC/Responses // 地址),与真实出站组装一样先 TrimRight "/"(urlvalidator 与 -// nativeAnthropicTargetURL 同款归一化),仅当其为 ollama.com 且 body 中映射后出站 -// model 为 DeepSeek 系时压到 cap,否则原样返回。 +// nativeAnthropicTargetURL 同款归一化),命中 ollama.com 即按账号 cap 钳制,不看 +// 模型家族(DeepSeek 系与非 DeepSeek 模型统一 65535),否则原样返回。 func clampOllamaCloudAnthropicMessagesMaxTokens(account *Account, baseURL string, body []byte) []byte { if account == nil || len(body) == 0 { return body @@ -21,8 +19,5 @@ func clampOllamaCloudAnthropicMessagesMaxTokens(account *Account, baseURL string if !isOllamaCloudBaseURL(strings.TrimRight(strings.TrimSpace(baseURL), "/")) { return body } - if !isDeepSeekModel(gjson.GetBytes(body, "model").String()) { - return body - } return clampOllamaCloudMaxTokens(account, body) } diff --git a/backend/internal/service/ollama_cloud_messages_max_tokens_test.go b/backend/internal/service/ollama_cloud_messages_max_tokens_test.go index 66b3e6e157..2d5bb4320c 100644 --- a/backend/internal/service/ollama_cloud_messages_max_tokens_test.go +++ b/backend/internal/service/ollama_cloud_messages_max_tokens_test.go @@ -87,14 +87,16 @@ func TestBuildUpstreamRequest_ClampsOllamaCloudDeepSeekMaxTokens(t *testing.T) { require.Equal(t, int64(256000), gjson.GetBytes(wire, "max_tokens").Int()) }) - t.Run("non deepseek model untouched", func(t *testing.T) { + // D1′ 后 host 命中即钳制:非 DeepSeek 模型同样 clamp(此前该用例钉住 + // 「仅 DeepSeek 系 clamp」的旧行为,上游对 >65535 一律 400 与模型无关)。 + t.Run("non deepseek model is clamped too", func(t *testing.T) { nonDeepSeek := messagesClampBody("k3-256k", 256000) _, wire, err := svc.buildUpstreamRequest( context.Background(), c, account, nonDeepSeek, "sk-test", "api_key", "k3-256k", false, false, ) require.NoError(t, err) - require.Equal(t, int64(256000), gjson.GetBytes(wire, "max_tokens").Int()) + require.Equal(t, int64(65535), gjson.GetBytes(wire, "max_tokens").Int()) }) t.Run("at cap and extra cap zero untouched", func(t *testing.T) { @@ -229,8 +231,8 @@ func TestBuildNativeAnthropicUpstreamRequest_ClampsOllamaCloudDeepSeekMaxTokens( require.Equal(t, int64(256000), gjson.GetBytes(wireBody, "max_tokens").Int()) }) - // 非 DeepSeek 模型(映射后出站 model)不变。 - t.Run("non deepseek model untouched", func(t *testing.T) { + // 非 DeepSeek 模型(映射后出站 model)按 host 判定同样 clamp(D1′)。 + t.Run("non deepseek model is clamped too", func(t *testing.T) { account := messagesClampOllamaAccount(425, PlatformDeepseek) account.Credentials["api_protocol"] = APIProtocolAnthropic nonDeepSeek := messagesClampBody("glm-4.7", 256000) @@ -240,7 +242,7 @@ func TestBuildNativeAnthropicUpstreamRequest_ClampsOllamaCloudDeepSeekMaxTokens( context.Background(), c, account, nonDeepSeek, "sk-test", targetURL, ) require.NoError(t, err) - require.Equal(t, int64(256000), gjson.GetBytes(wireBody, "max_tokens").Int()) + require.Equal(t, int64(65535), gjson.GetBytes(wireBody, "max_tokens").Int()) }) } diff --git a/backend/internal/service/ollama_cloud_platform_routing_test.go b/backend/internal/service/ollama_cloud_platform_routing_test.go index 01222e2ee7..e8be9dd405 100644 --- a/backend/internal/service/ollama_cloud_platform_routing_test.go +++ b/backend/internal/service/ollama_cloud_platform_routing_test.go @@ -178,10 +178,11 @@ func TestShouldForwardOpenAIResponsesViaRawChatCompletions_OllamaCloud(t *testin require.True(t, shouldForwardOpenAIResponsesViaRawChatCompletions(account(APIProtocolChatCompletions))) require.False(t, shouldForwardOpenAIResponsesViaRawChatCompletions(account(APIProtocolAnthropic))) - // adaptive / responses 的取值跟随 SupportsNativeCNResponses()(该谓词的 ollama - // 分支属增量 3,本增量按现状断言结构一致)。 - require.Equal(t, !account(APIProtocolAdaptive).SupportsNativeCNResponses(), - shouldForwardOpenAIResponsesViaRawChatCompletions(account(APIProtocolAdaptive))) + // C31 落地后 SupportsNativeCNResponses() 对 ollama 为 true:adaptive / responses + // 不再降级 raw CC,改走平台原生 /v1/responses(连锁验证见 + // TestAdaptiveProtocolRoutesOllamaCloudResponsesToNativeResponses)。 + require.False(t, shouldForwardOpenAIResponsesViaRawChatCompletions(account(APIProtocolAdaptive))) + require.False(t, shouldForwardOpenAIResponsesViaRawChatCompletions(account(APIProtocolResponses))) } // TestForwardCountTokensAsAnthropic_OllamaCloudEstimatesLocally 覆盖 ⑨ findings B1: diff --git a/backend/internal/service/openai_apikey_responses_probe.go b/backend/internal/service/openai_apikey_responses_probe.go index d942afab08..0dffa97089 100644 --- a/backend/internal/service/openai_apikey_responses_probe.go +++ b/backend/internal/service/openai_apikey_responses_probe.go @@ -107,7 +107,8 @@ func selectResponsesProbeModel(account *Account) string { // ProbeOpenAIAPIKeyResponsesSupport 探测 OpenAI APIKey 账号上游是否支持 // /v1/responses 端点,并将结果持久化到 accounts.extra.openai_responses_supported。 // -// 调用时机:账号创建/更新后,且仅当 platform=openai && type=apikey 时。 +// 调用时机:账号创建/更新后,且仅当 platform=openai / 国产供应商 / ollama_cloud +// && type=apikey 时。 // // 探测策略(参见包文档 internal/pkg/openai_compat): // - 上游 404 / 405 → 端点不存在,写 false @@ -117,6 +118,8 @@ func selectResponsesProbeModel(account *Account) string { // - 网络层失败(连接错误、超时)→ 不写标记,保持 unknown // (后续请求仍按"现状即证据"默认走 Responses) // +// 例外:国产供应商与 ollama_cloud 不走网络探测,直接按协议落标(见分支内注释)。 +// // 该方法是幂等的:重复调用会以最新探测结果覆盖标记。 // // 关于失败处理:探测本身的失败不应阻塞账号创建——账号能创建/更新成功就够了, @@ -130,12 +133,16 @@ func (s *AccountTestService) ProbeOpenAIAPIKeyResponsesSupport(ctx context.Conte if account.Type != AccountTypeAPIKey { return } - if account.IsCNProvider() { + if account.IsCNProvider() || account.Platform == PlatformOllamaCloud { // 国产 OpenAI 兼容上游默认仅支持 /v1/chat/completions。直接落标 false // 走 Chat Completions 直转,跳过网络探测。 // 例外:deepseek / kimi 的固定 responses 和 adaptive 账号使用官方原生 // Responses 端点,落标 force_responses;其余协议显式重置为 auto,避免 // 切换后残留强制模式。 + // ollama_cloud 与 CN 分支同款:C31 落地后 ollama 有原生 Responses 端点 + // (/v1/responses,non-stateful),adaptive / responses 协议直接落标 + // force_responses,无需网络探测(探测的 2xx/404 判定对它无意义); + // 显式 chat_completions 锁 CC,重置为 auto 防残留强制模式。 if account.UsesNativeCNResponses() { _ = s.accountRepo.UpdateExtra(ctx, account.ID, map[string]any{ openai_compat.ExtraKeyResponsesMode: string(openai_compat.ResponsesSupportModeForceResponses), diff --git a/backend/internal/service/openai_apikey_responses_probe_test.go b/backend/internal/service/openai_apikey_responses_probe_test.go index 7da1da0055..0c33fd6df5 100644 --- a/backend/internal/service/openai_apikey_responses_probe_test.go +++ b/backend/internal/service/openai_apikey_responses_probe_test.go @@ -90,6 +90,53 @@ func TestProbeOpenAIAPIKeyResponsesSupportCNProviders(t *testing.T) { } } +// TestProbeOpenAIAPIKeyResponsesSupportOllamaCloud 验证 C39:ollama_cloud 账号与 +// CN 分支同款按协议直接落标,不走网络探测(C31 后 ollama 有原生 /v1/responses, +// 探测的 2xx/404 判定对它无意义);显式 CC 重置为 auto 防残留强制模式。 +func TestProbeOpenAIAPIKeyResponsesSupportOllamaCloud(t *testing.T) { + tests := []struct { + name string + id int64 + protocol string + wantMode string + wantSupport bool + }{ + {name: "adaptive marks force_responses", id: 221, protocol: APIProtocolAdaptive, wantMode: string(openai_compat.ResponsesSupportModeForceResponses), wantSupport: true}, + {name: "responses protocol marks force_responses", id: 222, protocol: APIProtocolResponses, wantMode: string(openai_compat.ResponsesSupportModeForceResponses), wantSupport: true}, + {name: "chat completions resets to auto", id: 223, protocol: APIProtocolChatCompletions, wantMode: string(openai_compat.ResponsesSupportModeAuto), wantSupport: false}, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + updateCalls := make(chan map[string]any, 1) + account := Account{ + ID: tc.id, Platform: PlatformOllamaCloud, Type: AccountTypeAPIKey, + Credentials: map[string]any{"api_key": "sk-test", "api_protocol": tc.protocol}, + Extra: map[string]any{ + // 预置与目标相反的残留标记,验证落标会覆盖。 + openai_compat.ExtraKeyResponsesMode: string(openai_compat.ResponsesSupportModeAuto), + openai_compat.ExtraKeyResponsesSupported: false, + }, + } + repo := &snapshotUpdateAccountRepo{ + stubOpenAIAccountRepo: stubOpenAIAccountRepo{accounts: []Account{account}}, + updateExtraCalls: updateCalls, + } + upstream := &httpUpstreamRecorder{} + svc := &AccountTestService{accountRepo: repo, httpUpstream: upstream} + + svc.ProbeOpenAIAPIKeyResponsesSupport(context.Background(), account.ID) + + updates := <-updateCalls + require.Equal(t, tc.wantSupport, updates[openai_compat.ExtraKeyResponsesSupported]) + require.Equal(t, tc.wantMode, updates[openai_compat.ExtraKeyResponsesMode]) + // 不发任何网络探测请求。 + require.Nil(t, upstream.lastReq) + require.Empty(t, upstream.requests) + }) + } +} + func TestDecideResponsesProbeSupport(t *testing.T) { fnCall := []byte(`{"output":[{"type":"reasoning"},{"type":"function_call","name":"probe_ping"}]}`) reasoningOnly := []byte(`{"output":[{"type":"reasoning"}]}`) diff --git a/backend/internal/service/openai_gateway_conversation_guard_test.go b/backend/internal/service/openai_gateway_conversation_guard_test.go new file mode 100644 index 0000000000..c9daa49bb4 --- /dev/null +++ b/backend/internal/service/openai_gateway_conversation_guard_test.go @@ -0,0 +1,83 @@ +//go:build unit + +package service + +import ( + "bytes" + "context" + "errors" + "net/http" + "net/http/httptest" + "testing" + + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" +) + +// conversationGuardRecorder 保留 *httptest.ResponseRecorder 的引用,以便在 Forward +// 返回后断言 client-visible 状态码与响应体。 +type conversationGuardRecorder struct { + rec *httptest.ResponseRecorder + c *gin.Context +} + +func newConversationGuardRecorder(path string, body []byte) *conversationGuardRecorder { + 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") + return &conversationGuardRecorder{rec: rec, c: c} +} + +// TestForwardConversationFieldRejectedWithBadRequest 验证 D2/C37′ 的端到端语义: +// 原生 Responses 账号(ollama_cloud adaptive / deepseek responses)的入站 body 携带 +// conversation 时,网关显式应答 400 invalid_request_error(client-visible 状态码断 +// 言),不向上游转发、不触发账号 failover;body 不携带 conversation 时同一账号正常 +// 出站(证明 400 只由 conversation 触发,而非签名改动引入的通用错误)。 +func TestForwardConversationFieldRejectedWithBadRequest(t *testing.T) { + gin.SetMode(gin.TestMode) + + body := []byte(`{"model":"gpt-oss:120b-cloud","conversation":"conv_x","input":"hi","stream":false}`) + + t.Run("ollama_cloud adaptive gets 400 and no upstream call", func(t *testing.T) { + upstream := &httpUpstreamRecorder{err: errors.New("must not reach upstream")} + svc := &OpenAIGatewayService{cfg: rawChatCompletionsTestConfig(), httpUpstream: upstream} + account := adaptiveProtocolTestAccount(PlatformOllamaCloud, nil) + + recorder := newConversationGuardRecorder("/v1/responses", body) + _, err := svc.Forward(context.Background(), recorder.c, account, body) + require.Error(t, err) + require.Nil(t, upstream.lastReq, "conversation 请求不得出站") + require.Equal(t, http.StatusBadRequest, recorder.rec.Code, "client-visible 状态码必须是 400") + require.Contains(t, gjson.Get(recorder.rec.Body.String(), "error.type").String(), "invalid_request_error") + require.Contains(t, recorder.rec.Body.String(), "conversation") + }) + + t.Run("deepseek responses gets 400 too", func(t *testing.T) { + upstream := &httpUpstreamRecorder{err: errors.New("must not reach upstream")} + svc := &OpenAIGatewayService{cfg: rawChatCompletionsTestConfig(), httpUpstream: upstream} + account := adaptiveProtocolTestAccount(PlatformDeepseek, nil) + account.Credentials["api_protocol"] = APIProtocolResponses + + recorder := newConversationGuardRecorder("/v1/responses", body) + _, err := svc.Forward(context.Background(), recorder.c, account, body) + require.Error(t, err) + require.Nil(t, upstream.lastReq) + require.Equal(t, http.StatusBadRequest, recorder.rec.Code) + require.Contains(t, recorder.rec.Body.String(), "conversation") + }) + + t.Run("same account without conversation is forwarded", func(t *testing.T) { + upstream := &httpUpstreamRecorder{err: errors.New("stop after capture")} + svc := &OpenAIGatewayService{cfg: rawChatCompletionsTestConfig(), httpUpstream: upstream} + account := adaptiveProtocolTestAccount(PlatformOllamaCloud, nil) + + cleanBody := []byte(`{"model":"gpt-oss:120b-cloud","input":"hi","store":true,"stream":false}`) + _, err := svc.Forward(context.Background(), adaptiveProtocolTestContext("/v1/responses", cleanBody), account, cleanBody) + require.Error(t, err) + require.NotNil(t, upstream.lastReq) + require.Equal(t, "https://ollama.com/v1/responses", upstream.lastReq.URL.String()) + require.False(t, gjson.GetBytes(upstream.lastBody, "store").Bool()) + }) +} diff --git a/backend/internal/service/openai_gateway_deepseek_input_image_test.go b/backend/internal/service/openai_gateway_deepseek_input_image_test.go index 61f75c1939..daf3600b11 100644 --- a/backend/internal/service/openai_gateway_deepseek_input_image_test.go +++ b/backend/internal/service/openai_gateway_deepseek_input_image_test.go @@ -60,7 +60,7 @@ func TestNormalizeDeepSeekResponsesRequestBodyAliasesInputImageURL(t *testing.T) t.Run("openai_image_url_string_gets_url", func(t *testing.T) { body := deepSeekUserImageBody(`{"type":"input_image","image_url":"` + deepSeekInputImageDataURI + `"}`) - got := normalizeDeepSeekResponsesRequestBody(mapped, body) + got, _ := normalizeDeepSeekResponsesRequestBody(mapped, body) require.Equal(t, "input_image", gjson.GetBytes(got, "input.0.content.1.type").String()) require.Equal(t, deepSeekInputImageDataURI, gjson.GetBytes(got, "input.0.content.1.image_url").String()) require.Equal(t, deepSeekInputImageDataURI, gjson.GetBytes(got, "input.0.content.1.url").String()) @@ -70,7 +70,7 @@ func TestNormalizeDeepSeekResponsesRequestBodyAliasesInputImageURL(t *testing.T) t.Run("nested_image_url_object_flattened", func(t *testing.T) { body := deepSeekUserImageBody(`{"type":"input_image","image_url":{"url":"` + deepSeekInputImageDataURI + `"}}`) - got := normalizeDeepSeekResponsesRequestBody(native, body) + got, _ := normalizeDeepSeekResponsesRequestBody(native, body) require.Equal(t, gjson.String, gjson.GetBytes(got, "input.0.content.1.image_url").Type) require.Equal(t, deepSeekInputImageDataURI, gjson.GetBytes(got, "input.0.content.1.image_url").String()) require.Equal(t, deepSeekInputImageDataURI, gjson.GetBytes(got, "input.0.content.1.url").String()) @@ -78,7 +78,7 @@ func TestNormalizeDeepSeekResponsesRequestBodyAliasesInputImageURL(t *testing.T) t.Run("chat_completions_image_url_part_converted", func(t *testing.T) { body := deepSeekUserImageBody(`{"type":"image_url","image_url":{"url":"` + deepSeekInputImageDataURI + `"}}`) - got := normalizeDeepSeekResponsesRequestBody(mapped, body) + got, _ := normalizeDeepSeekResponsesRequestBody(mapped, body) require.Equal(t, "input_image", gjson.GetBytes(got, "input.0.content.1.type").String()) require.Equal(t, deepSeekInputImageDataURI, gjson.GetBytes(got, "input.0.content.1.image_url").String()) require.Equal(t, deepSeekInputImageDataURI, gjson.GetBytes(got, "input.0.content.1.url").String()) @@ -86,7 +86,7 @@ func TestNormalizeDeepSeekResponsesRequestBodyAliasesInputImageURL(t *testing.T) t.Run("anthropic_source_becomes_data_uri", func(t *testing.T) { body := deepSeekUserImageBody(`{"type":"image","source":{"type":"base64","media_type":"image/png","data":"AQID"}}`) - got := normalizeDeepSeekResponsesRequestBody(native, body) + got, _ := normalizeDeepSeekResponsesRequestBody(native, body) require.Equal(t, "input_image", gjson.GetBytes(got, "input.0.content.1.type").String()) require.Equal(t, deepSeekInputImageDataURI, gjson.GetBytes(got, "input.0.content.1.image_url").String()) require.Equal(t, deepSeekInputImageDataURI, gjson.GetBytes(got, "input.0.content.1.url").String()) @@ -94,7 +94,7 @@ func TestNormalizeDeepSeekResponsesRequestBodyAliasesInputImageURL(t *testing.T) t.Run("lifted_tool_output_image_gets_url", func(t *testing.T) { body := []byte(`{"model":"deepseek-flash","input":[{"type":"function_call","call_id":"call_image","name":"view_image","arguments":"{}"},{"type":"function_call_output","call_id":"call_image","output":[{"type":"input_image","image_url":"` + deepSeekInputImageDataURI + `"}]}]}`) - got := normalizeDeepSeekResponsesRequestBody(mapped, body) + got, _ := normalizeDeepSeekResponsesRequestBody(mapped, body) require.Equal(t, gjson.String, gjson.GetBytes(got, "input.1.output").Type) require.Equal(t, "input_image", gjson.GetBytes(got, "input.2.content.1.type").String()) require.Equal(t, deepSeekInputImageDataURI, gjson.GetBytes(got, "input.2.content.1.image_url").String()) @@ -103,7 +103,7 @@ func TestNormalizeDeepSeekResponsesRequestBodyAliasesInputImageURL(t *testing.T) t.Run("file_id_only_does_not_gain_empty_url", func(t *testing.T) { body := deepSeekUserImageBody(`{"type":"input_image","file_id":"file-abc"}`) - got := normalizeDeepSeekResponsesRequestBody(native, body) + got, _ := normalizeDeepSeekResponsesRequestBody(native, body) require.Equal(t, "file-abc", gjson.GetBytes(got, "input.0.content.1.file_id").String()) require.False(t, gjson.GetBytes(got, "input.0.content.1.url").Exists()) require.False(t, gjson.GetBytes(got, "input.0.content.1.image_url").Exists()) @@ -111,14 +111,14 @@ func TestNormalizeDeepSeekResponsesRequestBodyAliasesInputImageURL(t *testing.T) t.Run("kimi_does_not_alias_url", func(t *testing.T) { body := deepSeekUserImageBody(`{"type":"input_image","image_url":"` + deepSeekInputImageDataURI + `"}`) - got := normalizeDeepSeekResponsesRequestBody(kimi, body) + got, _ := normalizeDeepSeekResponsesRequestBody(kimi, body) require.Equal(t, deepSeekInputImageDataURI, gjson.GetBytes(got, "input.0.content.1.image_url").String()) require.False(t, gjson.GetBytes(got, "input.0.content.1.url").Exists()) }) t.Run("openai_host_unchanged", func(t *testing.T) { body := deepSeekUserImageBody(`{"type":"input_image","image_url":"` + deepSeekInputImageDataURI + `"}`) - got := normalizeDeepSeekResponsesRequestBody(openai, body) + got, _ := normalizeDeepSeekResponsesRequestBody(openai, body) require.Equal(t, string(body), string(got)) require.False(t, gjson.GetBytes(got, "input.0.content.1.url").Exists()) }) diff --git a/backend/internal/service/openai_gateway_forward.go b/backend/internal/service/openai_gateway_forward.go index 14b7ac988f..30f028c522 100644 --- a/backend/internal/service/openai_gateway_forward.go +++ b/backend/internal/service/openai_gateway_forward.go @@ -1430,9 +1430,16 @@ func (s *OpenAIGatewayService) buildUpstreamRequest(ctx context.Context, c *gin. } targetURL = appendOpenAIResponsesRequestPathSuffix(targetURL, openAIResponsesRequestPathSuffix(c)) - // DeepSeek / Kimi 原生 Responses 端点为无状态实现:强制 store=false、清除 - // previous_response_id,避免携带状态字段被上游拒绝。 - body = normalizeDeepSeekResponsesRequestBody(account, body) + // DeepSeek / Kimi / Ollama Cloud 原生 Responses 端点为无状态实现:强制 + // store=false、清除 previous_response_id;携带 conversation 时显式 400。 + body, err := normalizeDeepSeekResponsesRequestBody(account, body) + if err != nil { + var statelessErr *openAIResponsesStatelessFieldError + if errors.As(err, &statelessErr) { + respondOpenAIStatelessFieldError(c, statelessErr) + } + return nil, err + } req, err := http.NewRequestWithContext(ctx, "POST", targetURL, bytes.NewReader(body)) if err != nil { diff --git a/backend/internal/service/openai_gateway_messages_chat_fallback_ollama_test.go b/backend/internal/service/openai_gateway_messages_chat_fallback_ollama_test.go index 4410b6f36f..d81f3c2652 100644 --- a/backend/internal/service/openai_gateway_messages_chat_fallback_ollama_test.go +++ b/backend/internal/service/openai_gateway_messages_chat_fallback_ollama_test.go @@ -134,12 +134,16 @@ func TestMessagesChatFallback_OfficialDeepSeek_Untouched(t *testing.T) { require.Equal(t, "final answer", gjson.Get(rec.Body.String(), "content.0.text").String()) } -func TestMessagesChatFallback_OllamaGLM_Untouched(t *testing.T) { +// TestMessagesChatFallback_OllamaGLM_ClampsMaxTokens 验证 D1′ 后非 DeepSeek 模型 +// (glm-5.3-flash)在 ollama host 上同样被 clamp(此前 max_tokens 透传 256000 会被 +// 上游 400);reasoning 钩子仍按 isOllamaCloudDeepSeekUpstream 判定,非 DeepSeek +// 模型不做归一化,输出不出现 thinking 块。 +func TestMessagesChatFallback_OllamaGLM_ClampsMaxTokens(t *testing.T) { account := ollamaUpstreamTestAccount(PlatformDeepseek, 705) body := []byte(`{"model":"glm-5.3-flash","max_tokens":256000,"messages":[{"role":"user","content":"hello"}],"stream":false}`) upstreamJSON := `{"id":"chatcmpl_ollama","object":"chat.completion","model":"glm-5.3-flash","choices":[{"index":0,"message":{"role":"assistant","thinking":"abc","content":"final answer"},"finish_reason":"stop"}],"usage":{"prompt_tokens":3,"completion_tokens":5,"total_tokens":8}}` rec, upstream := runOllamaMessagesChatFallback(t, account, body, upstreamJSON, false) - require.Equal(t, int64(256000), gjson.GetBytes(upstream.lastBody, "max_completion_tokens").Int()) + require.Equal(t, int64(65535), gjson.GetBytes(upstream.lastBody, "max_completion_tokens").Int()) require.NotContains(t, rec.Body.String(), `"type":"thinking"`) require.Equal(t, "final answer", gjson.Get(rec.Body.String(), "content.0.text").String()) } diff --git a/backend/internal/service/openai_gateway_ollama_cloud_cc_reasoning.go b/backend/internal/service/openai_gateway_ollama_cloud_cc_reasoning.go index fb79b8bf4b..8ac5d7b838 100644 --- a/backend/internal/service/openai_gateway_ollama_cloud_cc_reasoning.go +++ b/backend/internal/service/openai_gateway_ollama_cloud_cc_reasoning.go @@ -4,7 +4,6 @@ import ( "strconv" "strings" - "github.com/Wei-Shaw/sub2api/internal/pkg/openai_compat" "github.com/tidwall/gjson" "github.com/tidwall/sjson" ) @@ -13,40 +12,6 @@ import ( // 而 DeepSeek/OpenAI 客户端只认 reasoning_content。仅在 raw CC 直转路径上做 wire JSON // 双向补齐,不改 CC↔Responses / Anthropic / Grok 桥。 -func isOllamaCloudRawChatCompletionsAccount(account *Account) bool { - if account == nil || account.Platform != PlatformOpenAI || account.Type != AccountTypeAPIKey { - return false - } - mode, _ := account.Extra[openai_compat.ExtraKeyResponsesMode].(string) - if openai_compat.NormalizeResponsesSupportMode(mode) != openai_compat.ResponsesSupportModeForceChatCompletions { - return false - } - if accountHasOllamaCloudUsageExtra(account) { - return true - } - if account.Credentials == nil { - return false - } - baseURL, _ := account.Credentials["base_url"].(string) - return isOllamaCloudBaseURL(baseURL) -} - -func accountHasOllamaCloudUsageExtra(account *Account) bool { - if account == nil || account.Extra == nil { - return false - } - for _, key := range []string{ - OllamaCloudUsageSessionExtraKey, - OllamaCloudUsageAutoRefreshExtraKey, - OllamaCloudUsageSnapshotExtraKey, - } { - if _, ok := account.Extra[key]; ok { - return true - } - } - return false -} - // isOllamaCloudDeepSeekUpstream 判断本次出站是否命中 Ollama Cloud 上托管的 // DeepSeek 模型:出站 base_url 是 Ollama Cloud(GetOpenAIBaseURL,与 // clampOllamaCloudUpstreamMaxTokens 的取值一致)且映射后的出站模型是 DeepSeek 系。 diff --git a/backend/internal/service/openai_gateway_ollama_cloud_cc_reasoning_test.go b/backend/internal/service/openai_gateway_ollama_cloud_cc_reasoning_test.go index 808c732660..2c36d3c973 100644 --- a/backend/internal/service/openai_gateway_ollama_cloud_cc_reasoning_test.go +++ b/backend/internal/service/openai_gateway_ollama_cloud_cc_reasoning_test.go @@ -33,61 +33,9 @@ func ollamaCloudRawChatCompletionsTestAccount() *Account { } } -func TestIsOllamaCloudRawChatCompletionsAccount(t *testing.T) { - t.Parallel() - - t.Run("ollama.com + force_chat_completions", func(t *testing.T) { - t.Parallel() - require.True(t, isOllamaCloudRawChatCompletionsAccount(ollamaCloudRawChatCompletionsTestAccount())) - }) - - t.Run("extra usage signal without ollama host", func(t *testing.T) { - t.Parallel() - account := rawChatCompletionsTestAccount() - account.Credentials["base_url"] = "https://example.invalid/v1" - account.Extra = map[string]any{ - openai_compat.ExtraKeyResponsesMode: string(openai_compat.ResponsesSupportModeForceChatCompletions), - OllamaCloudUsageSnapshotExtraKey: map[string]any{"status": "ok"}, - } - require.True(t, isOllamaCloudRawChatCompletionsAccount(account)) - }) - - t.Run("official DeepSeek", func(t *testing.T) { - t.Parallel() - account := rawChatCompletionsTestAccount() - account.Name = "DeepSeek" - account.Credentials["base_url"] = "https://api.deepseek.com" - account.Extra = map[string]any{ - openai_compat.ExtraKeyResponsesMode: string(openai_compat.ResponsesSupportModeForceChatCompletions), - } - require.False(t, isOllamaCloudRawChatCompletionsAccount(account)) - }) - - t.Run("OpenCode Go extra", func(t *testing.T) { - t.Parallel() - account := rawChatCompletionsTestAccount() - account.Credentials["base_url"] = "https://opencode.ai/zen/go/v1" - account.Extra = map[string]any{ - openai_compat.ExtraKeyResponsesMode: string(openai_compat.ResponsesSupportModeForceChatCompletions), - "opencode_go_usage_auto_refresh": true, - } - require.False(t, isOllamaCloudRawChatCompletionsAccount(account)) - }) - - t.Run("ollama.com without force_chat_completions", func(t *testing.T) { - t.Parallel() - account := ollamaCloudRawChatCompletionsTestAccount() - account.Extra = nil - require.False(t, isOllamaCloudRawChatCompletionsAccount(account)) - }) - - t.Run("anthropic ollama.com", func(t *testing.T) { - t.Parallel() - account := ollamaCloudRawChatCompletionsTestAccount() - account.Platform = PlatformAnthropic - require.False(t, isOllamaCloudRawChatCompletionsAccount(account)) - }) -} +// TestIsOllamaCloudRawChatCompletionsAccount 已随谓词删除:reasoning 修复把 CC 钩子 +// 换成按 host + 模型判定的 isOllamaCloudDeepSeekUpstream(见下方同名测试),D1′ 又 +// 移除了 clamp 侧最后一个引用,平台 + responses_mode 双门禁判定退出仓库。 func TestNormalizeOllamaCloudChatCompletionsResponseJSON(t *testing.T) { t.Parallel() diff --git a/backend/internal/service/openai_gateway_ollama_cloud_max_tokens.go b/backend/internal/service/openai_gateway_ollama_cloud_max_tokens.go index bead0cf4fc..a30e39b77e 100644 --- a/backend/internal/service/openai_gateway_ollama_cloud_max_tokens.go +++ b/backend/internal/service/openai_gateway_ollama_cloud_max_tokens.go @@ -22,9 +22,8 @@ const ollamaCloudDefaultMaxTokensCap = 65535 // /v1/responses 降级 forwardResponsesViaRawChatCompletions 共用)的独立 token 钩子, // 与 reasoning 钩子解耦:只看本次请求实际选用的 CC 上游 base_url(GetOpenAIBaseURL, // 与 openAIChatCompletionsTargetURL 的取值一致)是否 ollama.com,不读 usage extra。 -// DeepSeek 系模型(用模型映射后的真实出站 model,body 中 model 已改写)任意平台均 -// clamp;非 DeepSeek 模型仅保留既有 openai 平台 Ollama 账号(force_chat_completions -// 判定)的 clamp,不扩展到其它平台。 +// host 命中即按账号 cap 钳制,不看模型家族(DeepSeek 系与非 DeepSeek 模型统一 +// 65535;Ollama Cloud 对 >65535 的输出预算一律 400,与模型无关)。 func clampOllamaCloudUpstreamMaxTokens(account *Account, body []byte) []byte { if account == nil || len(body) == 0 { return body @@ -32,9 +31,6 @@ func clampOllamaCloudUpstreamMaxTokens(account *Account, body []byte) []byte { if !isOllamaCloudBaseURL(account.GetOpenAIBaseURL()) { return body } - if !isDeepSeekModel(gjson.GetBytes(body, "model").String()) && !isOllamaCloudRawChatCompletionsAccount(account) { - return body - } return clampOllamaCloudMaxTokens(account, body) } @@ -51,15 +47,16 @@ func ollamaCloudResponsesUpstreamBaseURL(account *Account) string { // ollamaCloudResponsesMaxOutputTokensClamp 是原生 /v1/responses 路径的 clamp:在 // 平台字段归一化之后独立调用,不改写原有的 max_output_tokens 平台 switch。判定: // 实际 Responses 上游(ollamaCloudResponsesUpstreamBaseURL)为 ollama.com 的 -// APIKey 账号 + 映射后的出站模型是 DeepSeek 系;body 无 max_output_tokens 时回退读 -// max_tokens 为生效值(不限定平台——客户端按 Chat Completions 习惯只发 max_tokens -// 时,任何平台的 ollama+deepseek 命中判据都要 clamp)。返回 (cap, ok, sourceField), -// sourceField 为生效字段名("max_tokens" / ""),供调用方在值来自 max_tokens 时清除 -// 残留的 max_tokens。未命中返回 ok=false。 +// APIKey 账号即钳制,不按模型家族过滤(DeepSeek 系与非 DeepSeek 模型统一 +// 65535;upstreamModel 保留入参供后续分模型 cap 表使用);body 无 +// max_output_tokens 时回退读 max_tokens 为生效值(不限定平台——客户端按 Chat +// Completions 习惯只发 max_tokens 时,任何平台的 ollama 命中判据都要 clamp)。 +// 返回 (cap, ok, sourceField),sourceField 为生效字段名("max_tokens" / ""), +// 供调用方在值来自 max_tokens 时清除残留的 max_tokens。未命中返回 ok=false。 // 实测:ollama.com/v1/responses max_output_tokens=256000 被上游以 "max_tokens -// (256000) exceeds model's maximum output tokens (65536)" 400 拒绝(DeepSeek 模型)。 +// (256000) exceeds model's maximum output tokens (65536)" 400 拒绝。 func ollamaCloudResponsesMaxOutputTokensClamp(account *Account, upstreamModel string, body []byte) (int64, bool, string) { - if account == nil || account.Type != AccountTypeAPIKey || !isDeepSeekModel(upstreamModel) { + if account == nil || account.Type != AccountTypeAPIKey { return 0, false, "" } if !isOllamaCloudBaseURL(ollamaCloudResponsesUpstreamBaseURL(account)) { diff --git a/backend/internal/service/openai_gateway_ollama_cloud_max_tokens_test.go b/backend/internal/service/openai_gateway_ollama_cloud_max_tokens_test.go index 731cc03ea6..2940634737 100644 --- a/backend/internal/service/openai_gateway_ollama_cloud_max_tokens_test.go +++ b/backend/internal/service/openai_gateway_ollama_cloud_max_tokens_test.go @@ -230,18 +230,27 @@ func TestClampOllamaCloudUpstreamMaxTokens(t *testing.T) { want: `{"model":"deepseek-v4-flash","max_completion_tokens":65535}`, }, { - // 新增范围只限 DeepSeek 系模型:kimi/zhipu 平台挂 ollama.com 跑非 - // DeepSeek 模型的请求保持不变。 - name: "kimi platform non-deepseek model untouched", + // D1′ 后 host 命中即钳制、不按模型家族过滤:kimi/zhipu 平台挂 + // ollama.com 跑非 DeepSeek 模型同样被 clamp(上游对 >65535 一律 400, + // 与模型无关;这些用例此前钉住的是「仅 DeepSeek 系 clamp」的旧行为)。 + name: "kimi platform non-deepseek model is clamped", account: ollamaUpstreamTestAccount(PlatformKimi, 302), body: `{"model":"k3-256k","max_tokens":256000}`, - want: `{"model":"k3-256k","max_tokens":256000}`, + want: `{"model":"k3-256k","max_tokens":65535}`, }, { - name: "zhipu platform non-deepseek model untouched", + name: "zhipu platform non-deepseek model is clamped", account: ollamaUpstreamTestAccount(PlatformZhipu, 302), body: `{"model":"glm-4.7","max_tokens":256000}`, - want: `{"model":"glm-4.7","max_tokens":256000}`, + want: `{"model":"glm-4.7","max_tokens":65535}`, + }, + { + // platform=ollama_cloud + 非 DeepSeek 模型(真实名形态含 tag): + // D1′ 的目标场景,此前不 clamp 会被上游 400。 + name: "ollama_cloud platform non-deepseek tagged model is clamped", + account: ollamaUpstreamTestAccount(PlatformOllamaCloud, 306), + body: `{"model":"gpt-oss:120b-cloud","max_tokens":256000}`, + want: `{"model":"gpt-oss:120b-cloud","max_tokens":65535}`, }, { // 既有 openai 平台 Ollama 账号对 DeepSeek 模型的 clamp 幂等保持。 @@ -251,23 +260,24 @@ func TestClampOllamaCloudUpstreamMaxTokens(t *testing.T) { want: `{"model":"deepseek-v4-flash","max_tokens":65535}`, }, { - // 既有 openai 平台 Ollama(真实 ollama.com + force_chat_completions)对 - // 非 DeepSeek 模型的 clamp 保留。 - name: "openai platform ollama.com non-deepseek model keeps legacy clamp", + // 既有 openai 平台 Ollama(真实 ollama.com)对非 DeepSeek 模型的 clamp + // 保持(现按 host 判定命中,不再依赖 force_chat_completions extra)。 + name: "openai platform ollama.com non-deepseek model keeps clamp", account: ollamaCloudRawChatCompletionsTestAccount(), body: `{"model":"gpt-oss:120b-cloud","max_tokens":70000}`, want: `{"model":"gpt-oss:120b-cloud","max_tokens":65535}`, }, { - // 非 DeepSeek 模型不扩展到其它平台。 - name: "openai platform ollama.com non-deepseek model without force_cc untouched", + // 非 DeepSeek 模型不再豁免:openai 平台 + 无 force_cc extra 同样按 + // host 判定 clamp(旧行为「无 force_cc 不 clamp」已随 D1′ 移除)。 + name: "openai platform ollama.com non-deepseek model without force_cc is clamped", account: func() *Account { account := ollamaUpstreamTestAccount(PlatformOpenAI, 303) account.Extra = nil return account }(), body: `{"model":"gpt-oss:120b-cloud","max_tokens":70000}`, - want: `{"model":"gpt-oss:120b-cloud","max_tokens":70000}`, + want: `{"model":"gpt-oss:120b-cloud","max_tokens":65535}`, }, { // 残留 usage extra 不得把非 Ollama host 变成 Ollama(旧 reasoning 钩子内的 @@ -399,6 +409,17 @@ func TestForwardResponsesClampsOllamaCloudMaxOutputTokens(t *testing.T) { require.Equal(t, int64(65535), gjson.GetBytes(upstream.lastBody, "max_output_tokens").Int()) }) + // D1′:原生 Responses 路径不再按模型家族过滤,非 DeepSeek 模型同样 clamp。 + t.Run("non-deepseek model on native responses is clamped", func(t *testing.T) { + account := ollamaUpstreamTestAccount(PlatformOllamaCloud, 338) + account.Credentials["api_protocol"] = APIProtocolResponses + nonDeepSeekBody := []byte(`{"model":"gpt-oss:120b-cloud","input":"Reply with exactly OK and nothing else.","max_output_tokens":256000,"stream":false}`) + upstream, err := run(account, nonDeepSeekBody) + require.Error(t, err) + require.Equal(t, "https://ollama.com/v1/responses", upstream.lastReq.URL.String()) + require.Equal(t, int64(65535), gjson.GetBytes(upstream.lastBody, "max_output_tokens").Int()) + }) + t.Run("official deepseek with leftover usage extra is untouched", func(t *testing.T) { account := officialDeepSeekTestAccount(333) account.Credentials["api_protocol"] = APIProtocolResponses @@ -668,10 +689,12 @@ func TestForwardAsAnthropic_DeepseekOllamaCloudClampsMaxOutputTokens(t *testing. }) } -// TestResponsesPathNotClampedForOfficialDeepseekOrNonDeepSeekModel 对照用例(问题 1/2): -// 官方 deepseek(api.deepseek.com)与 ollama.com + 非 DeepSeek 模型的账号,同一判据不 -// 命中——三个出站入口的出站 body 保持 256000、不做任何改写。 -func TestResponsesPathNotClampedForOfficialDeepseekOrNonDeepSeekModel(t *testing.T) { +// TestResponsesPathNotClampedForOfficialDeepseek 对照用例(问题 1/2):官方 +// deepseek(api.deepseek.com)的账号同一判据不命中——三个出站入口的出站 body 保持 +// 256000、不做任何改写。(D1′ 后非 DeepSeek 模型在 ollama host 上同样 clamp, +// 对照只保留非 Ollama 上游场景;非 DeepSeek 的 clamp 断言见 +// TestForwardResponsesClampsOllamaCloudMaxOutputTokens 与 raw CC 表驱动用例。) +func TestResponsesPathNotClampedForOfficialDeepseek(t *testing.T) { gin.SetMode(gin.TestMode) type entry struct { @@ -735,24 +758,4 @@ func TestResponsesPathNotClampedForOfficialDeepseekOrNonDeepSeekModel(t *testing }) } }) - - t.Run("ollama account with non-deepseek model keeps 256000", func(t *testing.T) { - account := ollamaUpstreamTestAccount(PlatformDeepseek, 382) - account.Credentials["api_protocol"] = APIProtocolResponses - glmEntries := entries - glmEntries[0].body = []byte(`{"model":"glm-5.3-flash","input":"Reply with exactly OK and nothing else.","max_tokens":256000,"stream":false}`) - glmEntries[1].body = []byte(`{"model":"glm-5.3-flash","max_tokens":256000,"messages":[{"role":"user","content":"hi"}],"stream":false}`) - glmEntries[2].body = []byte(`{"model":"glm-5.3-flash","max_tokens":256000,"messages":[{"role":"user","content":"hi"}],"stream":false}`) - for _, e := range glmEntries { - t.Run(e.name, func(t *testing.T) { - upstream := run(account, e) - require.Equal(t, "https://ollama.com/v1/responses", upstream.lastReq.URL.String()) - if out := gjson.GetBytes(upstream.lastBody, "max_output_tokens"); out.Exists() { - require.Equal(t, int64(256000), out.Int()) - } else { - require.Equal(t, int64(256000), gjson.GetBytes(upstream.lastBody, "max_tokens").Int()) - } - }) - } - }) } diff --git a/backend/internal/service/openai_gateway_passthrough.go b/backend/internal/service/openai_gateway_passthrough.go index 54ce5131d7..95ccc781a7 100644 --- a/backend/internal/service/openai_gateway_passthrough.go +++ b/backend/internal/service/openai_gateway_passthrough.go @@ -609,8 +609,16 @@ func (s *OpenAIGatewayService) buildUpstreamRequestOpenAIPassthrough( } targetURL = appendOpenAIResponsesRequestPathSuffix(targetURL, openAIResponsesRequestPathSuffix(c)) - // DeepSeek / Kimi 原生 Responses 端点为无状态实现(见 normalizeDeepSeekResponsesRequestBody)。 - body = normalizeDeepSeekResponsesRequestBody(account, body) + // DeepSeek / Kimi / Ollama Cloud 原生 Responses 端点为无状态实现 + // (见 normalizeDeepSeekResponsesRequestBody);conversation 显式 400。 + body, normalizeErr := normalizeDeepSeekResponsesRequestBody(account, body) + if normalizeErr != nil { + var statelessErr *openAIResponsesStatelessFieldError + if errors.As(normalizeErr, &statelessErr) { + respondOpenAIStatelessFieldError(c, statelessErr) + } + return nil, normalizeErr + } req, err := http.NewRequestWithContext(ctx, http.MethodPost, targetURL, bytes.NewReader(body)) if err != nil { diff --git a/backend/internal/service/openai_gateway_request_body.go b/backend/internal/service/openai_gateway_request_body.go index b0e2dbf408..ae57a22d04 100644 --- a/backend/internal/service/openai_gateway_request_body.go +++ b/backend/internal/service/openai_gateway_request_body.go @@ -129,28 +129,38 @@ func deleteOpenAIResponsesNoneReasoningEffortFromObject(account *Account, body m } // normalizeDeepSeekResponsesRequestBody 适配无状态 CN Responses 端点: -// 强制 store=false 并清除 previous_response_id(DeepSeek / Kimi 官方 -// Responses 均不支持服务端状态存储,携带这些字段会被拒绝)。 +// 强制 store=false 并清除 previous_response_id(DeepSeek / Kimi / Ollama Cloud +// 官方 Responses 均不支持服务端状态存储,携带这些字段会被拒绝)。 // // DeepSeek 另需把 Codex/OpenAI 的 input_image.image_url 写成线上 serde // 要求的 url 字段;openai 平台但 base_url 指向 api.deepseek.com 的映射 // 账号同样走这条出站改写(Codex 贴图会 422 missing field url)。 // 非 CN / 非 DeepSeek 上游原样返回。 -func normalizeDeepSeekResponsesRequestBody(account *Account, body []byte) []byte { +// +// 请求体携带 conversation 时返回 *openAIResponsesStatelessFieldError 且不改写 +// body:一律 400 是产品选择——显式失败优于静默丢上下文——不是该用法不存在。 +// 依赖 conversation 的客户端把历史存在服务端、通常不重发 input,静默剥离等于 +// 静默丢上下文(回答质量下降且零错误信号)。已知代价是 conversation + 完整 +// input 的 non-stream 用法被误伤;出现真实此类客户端时按平台/账号开关显式 +// 放行,不得回退静默剥离。 +func normalizeDeepSeekResponsesRequestBody(account *Account, body []byte) ([]byte, error) { if account == nil { - return body + return body, nil } applyStateless := account.UsesNativeCNResponses() applyImages := shouldAliasDeepSeekResponsesInputImages(account) if !applyStateless && !applyImages { - return body + return body, nil + } + if applyStateless && gjson.GetBytes(body, "conversation").Exists() { + return body, &openAIResponsesStatelessFieldError{field: "conversation"} } normalized := body if applyStateless { patched, err := sjson.SetBytes(normalized, "store", false) if err != nil { - return body + return body, fmt.Errorf("force responses store=false: %w", err) } normalized = patched if stripped, err := sjson.DeleteBytes(normalized, "previous_response_id"); err == nil { @@ -160,11 +170,11 @@ func normalizeDeepSeekResponsesRequestBody(account *Account, body []byte) []byte var requestBody map[string]any if err := decodeOpenAIJSONUseNumber(normalized, &requestBody); err != nil { - return normalized + return normalized, nil } input, exists := requestBody["input"] if !exists { - return normalized + return normalized, nil } changed := false @@ -180,13 +190,39 @@ func normalizeDeepSeekResponsesRequestBody(account *Account, body []byte) []byte } } if !changed { - return normalized + return normalized, nil } rebuilt, err := marshalOpenAIUpstreamJSON(requestBody) if err != nil { - return normalized + return normalized, nil } - return rebuilt + normalized = rebuilt + return normalized, nil +} + +// openAIResponsesStatelessFieldError 标记请求体携带无状态 Responses 端点不支持 +// 的服务端状态字段(如 conversation)。网关必须把它应答为 400 +// invalid_request_error,不得向上游转发,也不得触发账号 failover。 +type openAIResponsesStatelessFieldError struct { + field string +} + +func (e *openAIResponsesStatelessFieldError) Error() string { + return fmt.Sprintf( + "%s is not supported on this stateless /responses endpoint: omit it and send the full input with store=false", + e.field, + ) +} + +// respondOpenAIStatelessFieldError 按 stripOpenAIResponsesInputNamespaces 的先例 +// 把无状态端点不支持的字段应答为 400 invalid_request_error(由服务层写出响应, +// handler 侧 ensureForwardErrorResponse 检测到响应已提交便不再追加 fallback)。 +func respondOpenAIStatelessFieldError(c *gin.Context, statelessErr *openAIResponsesStatelessFieldError) { + setOpsUpstreamError(c, http.StatusBadRequest, statelessErr.Error(), "") + c.JSON(http.StatusBadRequest, gin.H{"error": gin.H{ + "type": "invalid_request_error", + "message": statelessErr.Error(), + }}) } func shouldAliasDeepSeekResponsesInputImages(account *Account) bool { diff --git a/backend/internal/service/openai_gateway_responses_chat_fallback_ollama_test.go b/backend/internal/service/openai_gateway_responses_chat_fallback_ollama_test.go index 9b3ff2fde1..4991873d85 100644 --- a/backend/internal/service/openai_gateway_responses_chat_fallback_ollama_test.go +++ b/backend/internal/service/openai_gateway_responses_chat_fallback_ollama_test.go @@ -137,12 +137,15 @@ func TestResponsesChatFallback_OfficialDeepSeek_Untouched(t *testing.T) { require.Equal(t, "final answer", gjson.Get(rec.Body.String(), "output.0.content.0.text").String()) } -func TestResponsesChatFallback_OllamaGLM_Untouched(t *testing.T) { +// TestResponsesChatFallback_OllamaGLM_ClampsMaxTokens 验证 D1′ 后非 DeepSeek 模型 +// (glm-5.3-flash)在 ollama host 的 Responses→CC 降级桥上同样被 clamp;reasoning +// 钩子仍按模型判定,非 DeepSeek 模型不做归一化。 +func TestResponsesChatFallback_OllamaGLM_ClampsMaxTokens(t *testing.T) { account := ollamaUpstreamTestAccount(PlatformDeepseek, 605) body := []byte(`{"model":"glm-5.3-flash","input":"hello","max_output_tokens":256000,"stream":false}`) upstreamJSON := `{"id":"chatcmpl_ollama","object":"chat.completion","model":"glm-5.3-flash","choices":[{"index":0,"message":{"role":"assistant","thinking":"abc","content":"final answer"},"finish_reason":"stop"}],"usage":{"prompt_tokens":3,"completion_tokens":5,"total_tokens":8}}` rec, upstream := runOllamaResponsesChatFallback(t, account, body, upstreamJSON, false) - require.Equal(t, int64(256000), gjson.GetBytes(upstream.lastBody, "max_completion_tokens").Int()) + require.Equal(t, int64(65535), gjson.GetBytes(upstream.lastBody, "max_completion_tokens").Int()) require.NotContains(t, rec.Body.String(), `"type":"reasoning"`) require.Equal(t, "final answer", gjson.Get(rec.Body.String(), "output.0.content.0.text").String()) } From c42b7583726f1f94a7f45fbd3efaef13aaf8b84d Mon Sep 17 00:00:00 2001 From: alfadb Date: Sun, 13 Sep 2026 02:04:08 +0800 Subject: [PATCH 15/81] feat(billing): price ollama cloud models and resolve tagged model names MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit B2-②: add fallbackPrices entries for the 8 ollama-exclusive cloud models (gpt-oss:120b/20b, gemma4:31b, mistral-large-3:675b, qwen3.5:397b, nemotron-3-super/nano:30b/ultra) with official per-token rates, plus exact/prefix family rules in getFallbackPricing. gpt-oss tiers and the three nemotron tiers are matched precisely (no bare gpt-oss/nemotron prefix); models without a published cached-input tier bill cached input at the input rate instead of 0. B2-①: two-level pricing lookup for ":tag" model names. Shared helper normalizePricingModelNameForLookup yields the stripped candidate; wired into getModelPricingAt (full chain rerun, pricingAt preserved), matchGroupModelPricing (exact retry) and lookupChannelPricingNormalized (third retry after the codex normalization; applyChannelOverrides inherits it). Literal name always wins, so bedrock canonical keys like us.anthropic.claude-sonnet-4-5-20250929-v1:0 are never destructively stripped; normalizeChannelPricingModelName stays untouched. Tests: full /v1/models listing pinned with hit paths, tag-strip and fail-closed behavior, bedrock double-key regression at base/channel/ group layers. --- backend/internal/service/billing_service.go | 113 ++++++ .../service/model_pricing_resolver.go | 48 ++- .../service/ollama_cloud_pricing_test.go | 377 ++++++++++++++++++ 3 files changed, 535 insertions(+), 3 deletions(-) create mode 100644 backend/internal/service/ollama_cloud_pricing_test.go diff --git a/backend/internal/service/billing_service.go b/backend/internal/service/billing_service.go index 449acf1597..8ca87ed0d4 100644 --- a/backend/internal/service/billing_service.go +++ b/backend/internal/service/billing_service.go @@ -903,6 +903,69 @@ func (s *BillingService) initFallbackPricing() { SupportsCacheBreakdown: false, } + // ---- Ollama Cloud 托管模型(ollama 独占,别家无同名条目)---- + // Source: https://ollama.com/pricing(官方定价页,2026-09-12 检索)。 + // 与别家同名的 ollama 模型(glm-5.3 / kimi-k3 / minimax-m3 / deepseek-v4-pro + // 等)复用上方既有同名条目,不在此重复。键名用 /v1/models 的 API id 形态; + // 家族匹配规则见 getFallbackPricing 的 Ollama 分支。Ollama 无 priority tier + // 公布价,*Priority 字段一律不填;未列出的 ollama 模型名保持 nil(白名单 + // 语义,getFallbackPricing 末尾 return nil),显式拒绝而非误配。 + // gpt-oss 两档(120b / 20b)价差约 4 倍,匹配必须按完整 tag 前缀分开, + // 禁止裸 "gpt-oss" 前缀(见 getFallbackPricing)。 + s.fallbackPrices["gpt-oss:120b"] = &ModelPricing{ + InputPricePerToken: 0.15e-6, // $0.15 per MTok + OutputPricePerToken: 0.60e-6, // $0.60 per MTok + CacheReadPricePerToken: 0.014e-6, // $0.014 per MTok (cache hit) + SupportsCacheBreakdown: false, + } + s.fallbackPrices["gpt-oss:20b"] = &ModelPricing{ + InputPricePerToken: 0.07e-6, // $0.07 per MTok + OutputPricePerToken: 0.30e-6, // $0.30 per MTok + CacheReadPricePerToken: 0.035e-6, // $0.035 per MTok (cache hit) + SupportsCacheBreakdown: false, + } + s.fallbackPrices["gemma4:31b"] = &ModelPricing{ + InputPricePerToken: 0.14e-6, // $0.14 per MTok + OutputPricePerToken: 0.40e-6, // $0.40 per MTok + CacheReadPricePerToken: 0.05e-6, // $0.05 per MTok (cache hit) + SupportsCacheBreakdown: false, + } + // mistral-large-3 / qwen3.5 / nemotron-3-nano 官方未公布 cached-input 档 + // (定价页标注 "-",非 0)。CacheReadPricePerToken 为 0 的语义是把缓存输入 + // 按免费计(computeTokenBreakdown 直接乘该字段),为不低估成本,保守取输入价。 + s.fallbackPrices["mistral-large-3:675b"] = &ModelPricing{ + InputPricePerToken: 0.50e-6, // $0.50 per MTok + OutputPricePerToken: 1.50e-6, // $1.50 per MTok + CacheReadPricePerToken: 0.50e-6, // cached-input 未公布,保守按输入价 + SupportsCacheBreakdown: false, + } + s.fallbackPrices["qwen3.5:397b"] = &ModelPricing{ + InputPricePerToken: 0.60e-6, // $0.60 per MTok + OutputPricePerToken: 3.60e-6, // $3.60 per MTok + CacheReadPricePerToken: 0.60e-6, // cached-input 未公布,保守按输入价 + SupportsCacheBreakdown: false, + } + // nemotron 三款价差约 12 倍(输出 $0.24 vs $3.00 per MTok),逐款精确匹配, + // 禁止裸 "nemotron" 兜底前缀(见 getFallbackPricing)。 + s.fallbackPrices["nemotron-3-super"] = &ModelPricing{ + InputPricePerToken: 0.015e-6, // $0.015 per MTok + OutputPricePerToken: 0.60e-6, // $0.60 per MTok + CacheReadPricePerToken: 0.015e-6, // $0.015 per MTok (cache hit) + SupportsCacheBreakdown: false, + } + s.fallbackPrices["nemotron-3-nano:30b"] = &ModelPricing{ + InputPricePerToken: 0.06e-6, // $0.06 per MTok + OutputPricePerToken: 0.24e-6, // $0.24 per MTok + CacheReadPricePerToken: 0.06e-6, // cached-input 未公布,保守按输入价 + SupportsCacheBreakdown: false, + } + s.fallbackPrices["nemotron-3-ultra"] = &ModelPricing{ + InputPricePerToken: 0.10e-6, // $0.10 per MTok + OutputPricePerToken: 3.00e-6, // $3.00 per MTok + CacheReadPricePerToken: 0.10e-6, // $0.10 per MTok (cache hit) + SupportsCacheBreakdown: false, + } + // xAI Grok 4.5: $2 input / $0.30 cached input / $6 output below 200k; // long-context rates are $4 / $0.60 / $12 (>=200k prompt tokens). s.fallbackPrices["grok-4.5"] = &ModelPricing{ @@ -1186,6 +1249,37 @@ func (s *BillingService) getFallbackPricing(model string) *ModelPricing { return s.fallbackPrices["minimax-m2"] } + // ---- Ollama Cloud 托管模型(ollama 独占,Source: https://ollama.com/pricing)---- + // gpt-oss 两档(120b/20b)价差约 4 倍,必须按完整 tag 前缀分开匹配,禁止裸 + // "gpt-oss" 前缀;nemotron 三款价差约 12 倍,逐款精确匹配,禁止裸 "nemotron" + // 兜底。前缀/子串规则天然覆盖 "-cloud" 变体(真实请求形态,见 + // openai_gateway_ollama_cloud_max_tokens_test.go)与其它 tag 后缀。未列出的 + // ollama 模型名沿用白名单语义:落到函数末尾 return nil(拒绝计费)。 + if strings.HasPrefix(modelLower, "gpt-oss:120b") { + return s.fallbackPrices["gpt-oss:120b"] + } + if strings.HasPrefix(modelLower, "gpt-oss:20b") { + return s.fallbackPrices["gpt-oss:20b"] + } + if strings.Contains(modelLower, "gemma4") { + return s.fallbackPrices["gemma4:31b"] + } + if strings.Contains(modelLower, "mistral-large-3") { + return s.fallbackPrices["mistral-large-3:675b"] + } + if strings.HasPrefix(modelLower, "qwen3.5:397b") { + return s.fallbackPrices["qwen3.5:397b"] + } + if strings.Contains(modelLower, "nemotron-3-super") { + return s.fallbackPrices["nemotron-3-super"] + } + if strings.Contains(modelLower, "nemotron-3-nano") { + return s.fallbackPrices["nemotron-3-nano:30b"] + } + if strings.Contains(modelLower, "nemotron-3-ultra") { + return s.fallbackPrices["nemotron-3-ultra"] + } + // 火山方舟 豆包 Embedding(多模态向量化)。 // most-specific-first:放在未来任何 doubao-embedding / doubao 宽匹配之前。 // 覆盖带版本后缀的别名(如 doubao-embedding-vision-251215)。 @@ -1328,7 +1422,26 @@ func (s *BillingService) GetModelPricing(model string) (*ModelPricing, error) { // getModelPricingAt 是 GetModelPricing 的带计费时点内部变体:pricingAt 显式 // 驱动 DeepSeek pro→Flash 切换判定(切换点前 Pro 价、之后 Flash 价),使 // 展示/估算路径可与历史补账同刻复算,测试也能用固定时点钉住断言。 +// +// 两级查价:字面名完整跑一遍查找链(LiteLLM → fallback),未命中且名含 +// ":tag" 时用剥 tag 名重跑一次同一查找链(pricingAt 原样传递)。字面优先: +// bedrock canonical key(如 us.anthropic.claude-sonnet-4-5-20250929-v1:0) +// 本身含 ":0",字面命中时绝不剥;剥 tag 仅是 miss 后的第二级,见 +// normalizePricingModelNameForLookup。 func (s *BillingService) getModelPricingAt(model string, pricingAt time.Time) (*ModelPricing, error) { + pricing, err := s.getModelPricingAtOnce(model, pricingAt) + if err == nil { + return pricing, nil + } + if stripped, ok := normalizePricingModelNameForLookup(model); ok { + if retry, retryErr := s.getModelPricingAtOnce(stripped, pricingAt); retryErr == nil { + return retry, nil + } + } + return nil, err +} + +func (s *BillingService) getModelPricingAtOnce(model string, pricingAt time.Time) (*ModelPricing, error) { // 标准化模型名称(转小写) model = strings.ToLower(model) diff --git a/backend/internal/service/model_pricing_resolver.go b/backend/internal/service/model_pricing_resolver.go index 1d21e4cc15..3b2f555fcd 100644 --- a/backend/internal/service/model_pricing_resolver.go +++ b/backend/internal/service/model_pricing_resolver.go @@ -144,10 +144,40 @@ func (r *ModelPricingResolver) resolveConfiguredPricing(config *ChannelModelPric return resolved } +// normalizePricingModelNameForLookup 返回模型名的第二级查价备选:剥掉最后一个 +// ":tag" 后缀(如 "deepseek-v4-flash:0731" → "deepseek-v4-flash")。ok=false 表示 +// 没有可用备选(不含 ":"、":" 在首/末位或剥后为空)。 +// +// 只作字面名 miss 后的第二级 fallback,调用方必须先完成字面查找;严禁把本函数 +// 接入 normalizeChannelPricingModelName 之类的 cache key 归一化——bedrock 的 +// canonical key(如 us.anthropic.claude-sonnet-4-5-20250929-v1:0)本身含 ":0", +// 字面名与剥 tag 名塌缩成同一 cache key 会静默互覆渠道定价。 +func normalizePricingModelNameForLookup(model string) (string, bool) { + trimmed := strings.TrimSpace(model) + idx := strings.LastIndex(trimmed, ":") + if idx <= 0 || idx == len(trimmed)-1 { + return "", false + } + return trimmed[:idx], true +} + func matchGroupModelPricing(group *Group, model string) *ChannelModelPricing { if group == nil { return nil } + if cp := matchGroupModelPricingOnce(group, model); cp != nil { + return cp + } + // 字面名(含 ":tag")未命中时按剥 tag 名再跑一轮。通配 "prefix*" 本就能 + // 前缀命中带 tag 名,仅 exact 需要补;字面优先,配置名本身带 tag(如 + // bedrock 的 "-v1:0")时字面即命中,不会走到这里。 + if stripped, ok := normalizePricingModelNameForLookup(model); ok { + return matchGroupModelPricingOnce(group, stripped) + } + return nil +} + +func matchGroupModelPricingOnce(group *Group, model string) *ChannelModelPricing { model = normalizeChannelPricingModelName(model) var wildcard *ChannelModelPricing for i := range group.ModelPricing { @@ -188,6 +218,11 @@ func (r *ModelPricingResolver) resolveBasePricing(model string) (*ModelPricing, // // 字面名优先,保证管理员对具体变体的显式配价不被基名覆盖;非 OpenAI 模型 // normalizeKnownOpenAICodexModel 返回空串,此处天然 no-op。 +// +// 重试顺序钉死为:字面 → Codex 归一 → 剥 ":tag"。Codex 归一是官方兜底价已 +// 承认的变体名形状,优先级高于剥 tag;剥 tag 只作最后一级(ollama 的 +// /v1/models 返回名可带 tag,如 deepseek-v4-flash:0731)。字面命中时绝不剥: +// bedrock canonical key(us.anthropic.…-v1:0)本身含 ":0",字面第一步即返回。 func (r *ModelPricingResolver) lookupChannelPricingNormalized(ctx context.Context, groupID int64, model string) *ChannelModelPricing { if r.channelService == nil { return nil @@ -195,11 +230,18 @@ func (r *ModelPricingResolver) lookupChannelPricingNormalized(ctx context.Contex if pricing := r.channelService.GetChannelModelPricing(ctx, groupID, model); pricing != nil { return pricing } + // 第二级:OpenAI/Codex 归一重试(issue #5256,行为不变)。 normalized := normalizeKnownOpenAICodexModel(model) - if normalized == "" || strings.EqualFold(normalized, strings.TrimSpace(model)) { - return nil + if normalized != "" && !strings.EqualFold(normalized, strings.TrimSpace(model)) { + if pricing := r.channelService.GetChannelModelPricing(ctx, groupID, normalized); pricing != nil { + return pricing + } } - return r.channelService.GetChannelModelPricing(ctx, groupID, normalized) + // 第三级:剥 ":tag" 重试(剥后名必与字面名不同,无需再去重)。 + if stripped, ok := normalizePricingModelNameForLookup(model); ok { + return r.channelService.GetChannelModelPricing(ctx, groupID, stripped) + } + return nil } // applyChannelOverrides 应用渠道定价覆盖 diff --git a/backend/internal/service/ollama_cloud_pricing_test.go b/backend/internal/service/ollama_cloud_pricing_test.go new file mode 100644 index 0000000000..e933af54ec --- /dev/null +++ b/backend/internal/service/ollama_cloud_pricing_test.go @@ -0,0 +1,377 @@ +//go:build unit + +package service + +// 计费批 ⑧ 前半:Ollama Cloud 模型定价数据(B2-②)+ ":tag" 模型名两级查价 +// fallback(B2-①)。 +// +// 模型清单来源:curl -s https://ollama.com/v1/models(2026-09-12 实测 HTTP 200, +// 20 个模型,owned_by 全部为 ollama)。价格来源:https://ollama.com/pricing 官方 +// 定价页(见 /tmp/ollama-pricing-data.md 换算表)。 +// +// 命中路径钉死约定: +// - "literal":字面名直接命中(fallback 表精确键 + 专属前缀/子串规则); +// - "family":既有家族规则命中(tag 透明包含于子串/前缀规则); +// - "tag-stripped":字面 miss 后按剥 tag 名第二级命中(B2-① 新增路径)。 +// +// bedrock 回归护栏:bedrock canonical key(us.anthropic.claude-sonnet-4-5-20250929-v1:0) +// 本身含 ":0",字面名必须命中字面条目,剥 tag 只能是字面 miss 后的第二级。 + +import ( + "context" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/stretchr/testify/require" +) + +// ollamaPricingAt 固定为周一低谷(2026-08-24 12:00 UTC,DeepSeek 低谷时段), +// 使 applyModelSpecificPricingPolicyEx / deepseekPeakMultiplierAt 的输出确定。 +var ollamaPricingAt = time.Date(2026, 8, 24, 12, 0, 0, 0, time.UTC) + +// TestGetModelPricing_OllamaCloudRealModelList 覆盖 /v1/models 实测得到的全部 +// 20 个模型名:断言可定价(非 nil)且输入/输出单价均 > 0,并按上面的约定钉死 +// 每个名字的具体命中路径(期望值即该路径唯一解析到的价卡)。 +func TestGetModelPricing_OllamaCloudRealModelList(t *testing.T) { + bs := newTestBillingService() + + tests := []struct { + model string + path string + wantInput float64 // USD per token(低谷/标准档) + wantOut float64 + }{ + // --- ollama 独占 8 款(B2-② 新增,字面命中) --- + {"gpt-oss:120b", "literal", 0.15e-6, 0.60e-6}, + {"gpt-oss:20b", "literal", 0.07e-6, 0.30e-6}, + {"gemma4:31b", "literal", 0.14e-6, 0.40e-6}, + {"mistral-large-3:675b", "literal", 0.50e-6, 1.50e-6}, + {"qwen3.5:397b", "literal", 0.60e-6, 3.60e-6}, + {"nemotron-3-super", "literal", 0.015e-6, 0.60e-6}, + {"nemotron-3-nano:30b", "literal", 0.06e-6, 0.24e-6}, + {"nemotron-3-ultra", "literal", 0.10e-6, 3.00e-6}, + // --- 与别家同名、复用既有条目的 12 款(本批不改其数值) --- + {"glm-5.1", "literal", 1.4e-6, 4.4e-6}, + {"glm-5.2", "literal", 1.4e-6, 4.4e-6}, + {"glm-5.3", "literal", 1.4e-6, 4.4e-6}, + {"glm-5.3-flash", "literal", 0.15e-6, 0.5e-6}, + {"kimi-k3", "literal", 3e-6, 15e-6}, + {"kimi-k2.6", "literal", 0.95e-6, 4e-6}, + // 已知误配:kimi-k2.7-code 经 Contains("kimi-k2") 落 kimi-k2 卡, + // 与 Ollama 实收不符 —— 全局按名计费的独立议题,此处仅钉现状防漂移。 + {"kimi-k2.7-code", "family", 0.56e-6, 2.24e-6}, + {"minimax-m2.7", "literal", 0.30e-6, 1.20e-6}, + {"minimax-m3", "literal", 0.60e-6, 2.40e-6}, + {"deepseek-v4.1-flash", "family", 0.15e-6, 0.60e-6}, // HasPrefix("deepseek-") 兜底,恰好同价 + // 带 tag 名经既有子串规则命中(tag 透明包含,未剥 tag)。 + {"deepseek-v4-flash:0731", "family", 0.15e-6, 0.60e-6}, + {"deepseek-v4-pro:0813", "family", 0.66e-6, 1.98e-6}, + // --- 仓库测试里出现过的真实 "-cloud" 变体形态(前缀/子串规则一并覆盖) --- + {"gpt-oss:120b-cloud", "literal", 0.15e-6, 0.60e-6}, + {"gemma4:31b-cloud", "literal", 0.14e-6, 0.40e-6}, + {"qwen3.5:397b-cloud", "literal", 0.60e-6, 3.60e-6}, + } + + for _, tt := range tests { + t.Run(tt.model, func(t *testing.T) { + require.NotEmpty(t, tt.path, "hit path must be pinned explicitly") + + // 固定时点:值级断言,钉死命中路径解析到的唯一价卡。 + pricing, err := bs.getModelPricingAt(tt.model, ollamaPricingAt) + require.NoError(t, err, "model %s (path %s) must be priceable", tt.model, tt.path) + require.NotNil(t, pricing) + require.InDelta(t, tt.wantInput, pricing.InputPricePerToken, 1e-12, + "model %s input price must match its pinned hit path (%s)", tt.model, tt.path) + require.InDelta(t, tt.wantOut, pricing.OutputPricePerToken, 1e-12, + "model %s output price must match its pinned hit path (%s)", tt.model, tt.path) + + // 公开入口(无显式时点):验收口径 —— 非 nil 且输入/输出单价均 > 0。 + public, err := bs.GetModelPricing(tt.model) + require.NoError(t, err) + require.NotNil(t, public) + require.Greater(t, public.InputPricePerToken, 0.0, "model %s", tt.model) + require.Greater(t, public.OutputPricePerToken, 0.0, "model %s", tt.model) + }) + } +} + +// TestNormalizePricingModelNameForLookup 钉住剥 tag helper 的语义边界,并钉住 +// normalizeChannelPricingModelName(纯 cache key 变换)不做任何 tag 预变换。 +func TestNormalizePricingModelNameForLookup(t *testing.T) { + tests := []struct { + in string + want string + wantOK bool + wantSame string // normalizeChannelPricingModelName 的结果必须保持原样(cache key 不做变换) + }{ + {"deepseek-v4-flash:0731", "deepseek-v4-flash", true, "deepseek-v4-flash:0731"}, + {"gpt-oss:120b-cloud", "gpt-oss", true, "gpt-oss:120b-cloud"}, + {"nemotron-3-super", "", false, "nemotron-3-super"}, + {"", "", false, ""}, + {":0731", "", false, ":0731"}, // ":" 在首位,剥后为空 + {"foo:", "", false, "foo:"}, // 尾随 ":",无 tag 可剥 + {"a:b:c", "a:b", true, "a:b:c"}, // 只剥最后一个 ":" 后缀 + {"Foo:0731", "Foo", true, "foo:0731"}, + } + for _, tt := range tests { + got, ok := normalizePricingModelNameForLookup(tt.in) + require.Equal(t, tt.wantOK, ok, "input %q", tt.in) + require.Equal(t, tt.want, got, "input %q", tt.in) + // cache key 归一化禁止接入剥 tag:结果必须保留 ":"(bedrock "…-v1:0" 不塌缩)。 + require.Equal(t, tt.wantSame, normalizeChannelPricingModelName(tt.in), + "normalizeChannelPricingModelName must not transform tags (input %q)", tt.in) + } +} + +// TestGetModelPricing_LiteralTaggedKeyWinsOverStripped 字面优先:定价目录同时含 +// "foo:0" 与 "foo" 时,请求 "foo:0" 必须命中 "foo:0" 的价(不得剥成 "foo")。 +func TestGetModelPricing_LiteralTaggedKeyWinsOverStripped(t *testing.T) { + pricingSvc := newStubPricingServiceFromJSON(t, `{ + "foo:0": {"litellm_provider": "openai", "mode": "chat", + "input_cost_per_token": 1e-06, "output_cost_per_token": 2e-06}, + "foo": {"litellm_provider": "openai", "mode": "chat", + "input_cost_per_token": 3e-06, "output_cost_per_token": 4e-06} + }`) + bs := NewBillingService(&config.Config{}, pricingSvc) + + pricing, err := bs.getModelPricingAt("foo:0", ollamaPricingAt) + require.NoError(t, err) + require.InDelta(t, 1e-6, pricing.InputPricePerToken, 1e-12, + "literal tagged key must win over the stripped name") + require.InDelta(t, 2e-6, pricing.OutputPricePerToken, 1e-12) +} + +// TestGetModelPricing_TagStrippedFallbackHitsBaseCard 字面 miss 且名含 tag 时, +// 按剥 tag 名完整重跑一次查找链并命中基名价卡(spec 的 qwen3-coder:0731 场景)。 +func TestGetModelPricing_TagStrippedFallbackHitsBaseCard(t *testing.T) { + pricingSvc := newStubPricingServiceFromJSON(t, `{ + "qwen3-coder": {"litellm_provider": "openai", "mode": "chat", + "input_cost_per_token": 5e-07, "output_cost_per_token": 6e-06} + }`) + bs := NewBillingService(&config.Config{}, pricingSvc) + + pricing, err := bs.getModelPricingAt("qwen3-coder:0731", ollamaPricingAt) + require.NoError(t, err, "tagged name must fall back to the stripped base name") + require.InDelta(t, 5e-7, pricing.InputPricePerToken, 1e-12) + require.InDelta(t, 6e-6, pricing.OutputPricePerToken, 1e-12) +} + +// TestGetModelPricing_TagStrippedFallbackStillFailClosed 两个层级都 miss 时保持 +// fail-closed(ErrModelPricingUnavailable),不得因剥 tag 引入静默零价。 +func TestGetModelPricing_TagStrippedFallbackStillFailClosed(t *testing.T) { + bs := newTestBillingService() + + _, err := bs.GetModelPricing("qwen3-coder:0731") + require.ErrorIs(t, err, ErrModelPricingUnavailable) + + _, err = bs.GetModelPricing("nemotron-3-mini:9b") // 未列出的 nemotron 型号拒绝 + require.ErrorIs(t, err, ErrModelPricingUnavailable) +} + +// TestGetModelPricing_BedrockCanonicalKeyDoubleEntry bedrock 回归:canonical key +// (含 ":0")与剥后名双 key 并存时,各命中各自条目 —— 字面优先,不做破坏性剥离。 +func TestGetModelPricing_BedrockCanonicalKeyDoubleEntry(t *testing.T) { + pricingSvc := newStubPricingServiceFromJSON(t, `{ + "us.anthropic.claude-sonnet-4-5-20250929-v1:0": {"litellm_provider": "bedrock", "mode": "chat", + "input_cost_per_token": 1e-06, "output_cost_per_token": 2e-06}, + "us.anthropic.claude-sonnet-4-5-20250929-v1": {"litellm_provider": "bedrock", "mode": "chat", + "input_cost_per_token": 3e-06, "output_cost_per_token": 4e-06} + }`) + bs := NewBillingService(&config.Config{}, pricingSvc) + + tagged, err := bs.getModelPricingAt("us.anthropic.claude-sonnet-4-5-20250929-v1:0", ollamaPricingAt) + require.NoError(t, err) + require.InDelta(t, 1e-6, tagged.InputPricePerToken, 1e-12, + "bedrock canonical key with ':0' must hit its own entry, never the stripped one") + + bare, err := bs.getModelPricingAt("us.anthropic.claude-sonnet-4-5-20250929-v1", ollamaPricingAt) + require.NoError(t, err) + require.InDelta(t, 3e-6, bare.InputPricePerToken, 1e-12, + "bare bedrock name must hit its own entry") +} + +// TestGetModelPricing_BedrockFallbackFamilyUnaffected 无动态目录时,bedrock +// canonical key 经既有 Claude 家族规则命中 sonnet-4 卡,剥 tag 改动不得影响该路径。 +func TestGetModelPricing_BedrockFallbackFamilyUnaffected(t *testing.T) { + bs := newTestBillingService() + + pricing, err := bs.getModelPricingAt("us.anthropic.claude-sonnet-4-5-20250929-v1:0", ollamaPricingAt) + require.NoError(t, err) + require.InDelta(t, 3e-6, pricing.InputPricePerToken, 1e-12) // claude-sonnet-4 卡 + require.InDelta(t, 15e-6, pricing.OutputPricePerToken, 1e-12) +} + +// TestChannelPricing_TaggedModelFallsBackToStrippedKey 渠道价路径(B2-① 第 2 条): +// 渠道只配基名、请求名带 tag 时经剥 tag 重试命中渠道价,而不是落官方兜底价。 +func TestChannelPricing_TaggedModelFallsBackToStrippedKey(t *testing.T) { + groupID := int64(888) + cs := newChannelServiceWithPricings(groupID, []ChannelModelPricing{ + tokenPricingForModels([]string{"deepseek-v4-flash"}, 0.4), + }) + resolver := NewModelPricingResolver(cs, newTestBillingService()) + + resolved := resolver.Resolve(context.Background(), PricingInput{Model: "deepseek-v4-flash:0731", GroupID: &groupID}) + require.Equal(t, PricingSourceChannel, resolved.Source, + "tagged request name must reach the channel pricing configured on the bare name") + require.NotNil(t, resolved.BasePricing) + require.InDelta(t, 0.4e-6, resolved.BasePricing.InputPricePerToken, 1e-12) +} + +// TestChannelPricing_LiteralTaggedConfigWins 渠道价字面优先:同时配了带 tag 名与 +// 基名时,请求带 tag 名必须命中带 tag 名的显式配价。 +func TestChannelPricing_LiteralTaggedConfigWins(t *testing.T) { + groupID := int64(889) + cs := newChannelServiceWithPricings(groupID, []ChannelModelPricing{ + tokenPricingForModels([]string{"deepseek-v4-flash:0731"}, 0.9), + tokenPricingForModels([]string{"deepseek-v4-flash"}, 0.4), + }) + resolver := NewModelPricingResolver(cs, newTestBillingService()) + + resolved := resolver.Resolve(context.Background(), PricingInput{Model: "deepseek-v4-flash:0731", GroupID: &groupID}) + require.Equal(t, PricingSourceChannel, resolved.Source) + require.NotNil(t, resolved.BasePricing) + require.InDelta(t, 0.9e-6, resolved.BasePricing.InputPricePerToken, 1e-12, + "explicit per-tag channel pricing must win over the stripped base name") +} + +// TestChannelPricing_TagStripMustNotMatchUnrelated 反向保护:剥 tag 后的备选名 +// 不得命中渠道里不相关的配置,未命中时落回官方兜底价。 +func TestChannelPricing_TagStripMustNotMatchUnrelated(t *testing.T) { + groupID := int64(890) + cs := newChannelServiceWithPricings(groupID, []ChannelModelPricing{ + tokenPricingForModels([]string{"gpt-5.4"}, 0.9), + }) + resolver := NewModelPricingResolver(cs, newTestBillingService()) + + resolved := resolver.Resolve(context.Background(), PricingInput{Model: "deepseek-v4-flash:0731", GroupID: &groupID}) + require.NotEqual(t, PricingSourceChannel, resolved.Source, + "stripped lookup must not match an unrelated channel pricing entry") + require.NotNil(t, resolved.BasePricing) + require.InDelta(t, 0.15e-6, resolved.BasePricing.InputPricePerToken, 1e-12, + "should land on the official deepseek-v4-flash fallback card") +} + +// TestApplyChannelOverrides_TaggedModelInheritsLookup B2-① 第 4 条:渠道覆盖 +// applyChannelOverrides 内部走 lookupChannelPricingNormalized,自动继承剥 tag 重试。 +func TestApplyChannelOverrides_TaggedModelInheritsLookup(t *testing.T) { + groupID := int64(891) + cs := newChannelServiceWithPricings(groupID, []ChannelModelPricing{ + tokenPricingForModels([]string{"deepseek-v4-flash"}, 0.4), + }) + resolver := NewModelPricingResolver(cs, newTestBillingService()) + + resolved := &ResolvedPricing{Mode: BillingModeToken, Source: PricingSourceFallback} + resolved.BasePricing = &ModelPricing{InputPricePerToken: 0.15e-6, OutputPricePerToken: 0.6e-6} + resolver.applyChannelOverrides(context.Background(), groupID, "deepseek-v4-flash:0731", resolved) + + require.Equal(t, PricingSourceChannel, resolved.Source) + require.NotNil(t, resolved.BasePricing) + require.InDelta(t, 0.4e-6, resolved.BasePricing.InputPricePerToken, 1e-12) +} + +// TestMatchGroupModelPricing_TaggedModelExactFallback 分组价路径(B2-① 第 3 条): +// 精确配置 miss 后按剥 tag 名再跑一轮 exact 匹配。 +func TestMatchGroupModelPricing_TaggedModelExactFallback(t *testing.T) { + group := &Group{ + ModelPricing: []ChannelModelPricing{ + tokenPricingForModels([]string{"deepseek-v4-flash"}, 0.4), + }, + } + + cp := matchGroupModelPricing(group, "deepseek-v4-flash:0731") + require.NotNil(t, cp, "tagged request name must fall back to the exact bare-name group pricing") + require.NotNil(t, cp.InputPrice) + require.InDelta(t, 0.4e-6, *cp.InputPrice, 1e-12) +} + +// TestMatchGroupModelPricing_TaggedNilWhenUnmatched 分组价剥 tag 重试不得命中 +// 不相关配置:无任何可命中 pattern 时保持 nil。 +func TestMatchGroupModelPricing_TaggedNilWhenUnmatched(t *testing.T) { + group := &Group{ + ModelPricing: []ChannelModelPricing{ + tokenPricingForModels([]string{"gpt-5.4"}, 0.9), + }, + } + + require.Nil(t, matchGroupModelPricing(group, "deepseek-v4-flash:0731")) +} + +// TestMatchGroupModelPricing_WildcardStillMatchesTagged 通配 "prefix*" 本就能 +// 前缀命中带 tag 名,剥 tag 改动不得破坏该路径。 +func TestMatchGroupModelPricing_WildcardStillMatchesTagged(t *testing.T) { + group := &Group{ + ModelPricing: []ChannelModelPricing{ + tokenPricingForModels([]string{"gpt-oss:120b*"}, 0.2), + }, + } + + cp := matchGroupModelPricing(group, "gpt-oss:120b-cloud") + require.NotNil(t, cp) + require.NotNil(t, cp.InputPrice) + require.InDelta(t, 0.2e-6, *cp.InputPrice, 1e-12) +} + +// TestMatchGroupModelPricing_BedrockDoubleKey 分组价 bedrock 回归:带 ":0" 与 +// 不带的双 pattern 并存时,各自命中各自条目。 +func TestMatchGroupModelPricing_BedrockDoubleKey(t *testing.T) { + taggedEntry := tokenPricingForModels([]string{"us.anthropic.claude-sonnet-4-5-20250929-v1:0"}, 1.0) + bareEntry := tokenPricingForModels([]string{"us.anthropic.claude-sonnet-4-5-20250929-v1"}, 3.0) + group := &Group{ModelPricing: []ChannelModelPricing{taggedEntry, bareEntry}} + + tagged := matchGroupModelPricing(group, "us.anthropic.claude-sonnet-4-5-20250929-v1:0") + require.NotNil(t, tagged) + require.InDelta(t, 1e-6, *tagged.InputPrice, 1e-12) + + bare := matchGroupModelPricing(group, "us.anthropic.claude-sonnet-4-5-20250929-v1") + require.NotNil(t, bare) + require.InDelta(t, 3e-6, *bare.InputPrice, 1e-12) +} + +// TestOllamaTaggedModelPricingConsistentAcrossSources 一致性(spec 验收):同名 +// 模型在基础价 / 渠道价 / 分组价三种配置下命中同一价格档(0.15e-6 = 官方 +// deepseek-v4-flash 低谷卡)。 +func TestOllamaTaggedModelPricingConsistentAcrossSources(t *testing.T) { + const model = "deepseek-v4-flash:0731" + const tierInput = 0.15e-6 + groupID := int64(892) + bs := newTestBillingService() + + // 基础价(家族匹配) + base, err := bs.getModelPricingAt(model, ollamaPricingAt) + require.NoError(t, err) + require.InDelta(t, tierInput, base.InputPricePerToken, 1e-12) + + // 渠道价(剥 tag 命中) + cs := newChannelServiceWithPricings(groupID, []ChannelModelPricing{ + tokenPricingForModels([]string{"deepseek-v4-flash"}, 0.15), + }) + resolver := NewModelPricingResolver(cs, bs) + chResolved := resolver.Resolve(context.Background(), PricingInput{Model: model, GroupID: &groupID}) + require.NotNil(t, chResolved.BasePricing) + require.InDelta(t, tierInput, chResolved.BasePricing.InputPricePerToken, 1e-12) + + // 分组价(剥 tag exact 命中) + group := &Group{ModelPricing: []ChannelModelPricing{ + tokenPricingForModels([]string{"deepseek-v4-flash"}, 0.15), + }} + gp := matchGroupModelPricing(group, model) + require.NotNil(t, gp) + require.InDelta(t, tierInput, *gp.InputPrice, 1e-12) +} + +// TestGetModelPricing_OllamaModelsPublicEntryMatchesFixed 公开入口 GetModelPricing +// (内部 timezone.Now)与 getModelPricingAt(固定时点) 在非时点敏感的 ollama 模型上 +// 解析到同一价卡。 +func TestGetModelPricing_OllamaModelsPublicEntryMatchesFixed(t *testing.T) { + bs := newTestBillingService() + + for _, model := range []string{"gpt-oss:120b", "nemotron-3-ultra", "mistral-large-3:675b"} { + fixed, err := bs.getModelPricingAt(model, ollamaPricingAt) + require.NoError(t, err, "model %s", model) + nowPricing, err := bs.GetModelPricing(model) + require.NoError(t, err, "model %s", model) + require.Equal(t, fixed.InputPricePerToken, nowPricing.InputPricePerToken, "model %s", model) + require.Equal(t, fixed.OutputPricePerToken, nowPricing.OutputPricePerToken, "model %s", model) + } +} From a6f83e9d04af65d0c77bb00bf9fcb07ef65ceb91 Mon Sep 17 00:00:00 2001 From: alfadb Date: Sun, 13 Sep 2026 02:22:24 +0800 Subject: [PATCH 16/81] fix(billing): keep gpt-oss names out of the OpenAI pricing fallback chain MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 复现:动态目录含 gpt-5.4 时,gpt-oss:120b/20b 经 matchOpenAIModel 末端 catch-all 落到 DefaultTestModel(gpt-5.4) 价卡($2.5/$15 per MTok,实测 日志 "OpenAI fallback to default model gpt-oss:120b -> gpt-5.4"),绕过 fallbackPrices 的 ollama 价卡($0.15/$0.60 与 $0.07/$0.30),输入价 静默多收约 17~36 倍。 修复:GetModelPricing 第 5 步排除 gpt-oss 前缀进 OpenAI 回退链(返回 nil 交还 BillingService 走 fallbackPrices 的 ollama 价卡);不动任何其它匹配 规则与价格数值。gpt-oss-120b-medium(Antigravity 白名单同名族,仓库无其 定价条目)由误计 gpt-5.4 价转为 fail-closed,与无目录时行为一致。 回归护栏:ollama_cloud_dynamic_catalog_pricing_test.go 表驱动钉死 8 个 ollama 独占模型在目录已加载形态下的实际解析价,并钉住真实 OpenAI 名 (gpt-5.4 目录精确命中 / gpt-4o catch-all / gpt-5.5 静态兜底)不受影响。 --- ...lama_cloud_dynamic_catalog_pricing_test.go | 95 +++++++++++++++++++ backend/internal/service/pricing_service.go | 6 +- 2 files changed, 100 insertions(+), 1 deletion(-) create mode 100644 backend/internal/service/ollama_cloud_dynamic_catalog_pricing_test.go diff --git a/backend/internal/service/ollama_cloud_dynamic_catalog_pricing_test.go b/backend/internal/service/ollama_cloud_dynamic_catalog_pricing_test.go new file mode 100644 index 0000000000..86ce86508c --- /dev/null +++ b/backend/internal/service/ollama_cloud_dynamic_catalog_pricing_test.go @@ -0,0 +1,95 @@ +//go:build unit + +package service + +// 生产形态复现/回归:动态定价目录已加载(目录含 gpt-5.4)时,8 个 ollama 独占模型 +// 经 BillingService 两级查价的实际解析结果,逐名钉死。 +// +// 真实调用顺序(文件:行号 证据): +// - BillingService.getModelPricingAtOnce(billing_service.go:1351)先跑 +// PricingService.GetModelPricing(动态目录 + 模糊兜底,billing_service.go:1357), +// 命中即短路 fallbackPrices(billing_service.go:1366-1394);miss 才走 +// getFallbackPricing(billing_service.go:1398)。 +// - PricingService.GetModelPricing(pricing_service.go:1128)对任何 "gpt-" 前缀名 +// 进 matchOpenAIModel(pricing_service.go:1151-1153),其末端 catch-all 回落 +// pricingData[openai.DefaultTestModel] = "gpt-5.4"(pricing_service.go:1542-1547; +// internal/pkg/openai/constants.go:50)。 +// - gpt-oss 是开放权重模型、不是 OpenAI 模型:目录无其条目时,名字会被这条 +// catch-all 按 gpt-5.4 价卡($2.5/$15 per MTok)计费,而不是 fallbackPrices 的 +// ollama 价卡($0.15/$0.60 与 $0.07/$0.30,billing_service.go:848-859)。 +// +// 期望值与 TestGetModelPricing_OllamaCloudRealModelList 一致(来源 fallbackPrices +// 的 ollama 条目);差异仅在目录状态:这里模拟「动态目录已加载且含 gpt-5.4」的 +// 生产常态(openAILadderCatalogJSON 即真实目录同步形态)。 + +import ( + "testing" + + "github.com/stretchr/testify/require" +) + +func TestGetModelPricing_OllamaCloudModelsWithDynamicCatalogLoaded(t *testing.T) { + // 生产形态:动态目录已加载且含 gpt-5.4($2.5/$15 per MTok)。 + bs := newTestBillingServiceWithOpenAILadderCatalog(t) + + tests := []struct { + model string + wantInput float64 // USD per token,等于 fallbackPrices 里的 ollama 价卡 + wantOut float64 + }{ + {"gpt-oss:120b", 0.15e-6, 0.60e-6}, + {"gpt-oss:20b", 0.07e-6, 0.30e-6}, + {"gemma4:31b", 0.14e-6, 0.40e-6}, + {"mistral-large-3:675b", 0.50e-6, 1.50e-6}, + {"qwen3.5:397b", 0.60e-6, 3.60e-6}, + {"nemotron-3-super", 0.015e-6, 0.60e-6}, + {"nemotron-3-nano:30b", 0.06e-6, 0.24e-6}, + {"nemotron-3-ultra", 0.10e-6, 3.00e-6}, + } + + for _, tt := range tests { + t.Run(tt.model, func(t *testing.T) { + pricing, err := bs.getModelPricingAt(tt.model, ollamaPricingAt) + require.NoError(t, err, "model %s must be priceable with the dynamic catalog loaded", tt.model) + require.NotNil(t, pricing) + require.InDelta(t, tt.wantInput, pricing.InputPricePerToken, 1e-12, + "model %s must bill at its ollama card, not an OpenAI family catch-all", tt.model) + require.InDelta(t, tt.wantOut, pricing.OutputPricePerToken, 1e-12, + "model %s must bill at its ollama card, not an OpenAI family catch-all", tt.model) + }) + } +} + +// TestGetModelPricing_OpenAIChainUnaffectedByOllamaExclusion 回归护栏:把 gpt-oss* +// 排除出 OpenAI 回退链后,真实 OpenAI 名字的解析必须不受影响 —— 目录精确命中 / +// 家族 catch-all / 静态兜底三态各钉一例(值 = 目录 gpt-5.4 卡 $2.5/$15)。 +func TestGetModelPricing_OpenAIChainUnaffectedByOllamaExclusion(t *testing.T) { + bs := newTestBillingServiceWithOpenAILadderCatalog(t) + + tests := []struct { + model string + hit string + wantInput float64 + wantOut float64 + }{ + // 目录精确命中:gpt-5.4 本尊走目录价卡。 + {"gpt-5.4", "catalog-exact", 2.5e-6, 1.5e-5}, + // 目录无 gpt-4o 条目:经 OpenAI 链 catch-all 落 DefaultTestModel 目录卡 —— + // 该 catch-all 对真实 OpenAI 名必须保持可达。 + {"gpt-4o", "openai-catch-all", 2.5e-6, 1.5e-5}, + // gpt-5.5 → 业务静态 GPT-5.4 兜底价(openAIGPT54FallbackPricing,$2.5/$15)。 + {"gpt-5.5", "static-gpt54-fallback", 2.5e-6, 1.5e-5}, + } + + for _, tt := range tests { + t.Run(tt.model, func(t *testing.T) { + pricing, err := bs.getModelPricingAt(tt.model, ollamaPricingAt) + require.NoError(t, err, "model %s (hit %s)", tt.model, tt.hit) + require.NotNil(t, pricing) + require.InDelta(t, tt.wantInput, pricing.InputPricePerToken, 1e-12, + "model %s (hit %s) input price must stay on the OpenAI chain", tt.model, tt.hit) + require.InDelta(t, tt.wantOut, pricing.OutputPricePerToken, 1e-12, + "model %s (hit %s) output price must stay on the OpenAI chain", tt.model, tt.hit) + }) + } +} diff --git a/backend/internal/service/pricing_service.go b/backend/internal/service/pricing_service.go index f2a1eee9f7..fe4845383e 100644 --- a/backend/internal/service/pricing_service.go +++ b/backend/internal/service/pricing_service.go @@ -1216,7 +1216,11 @@ func (s *PricingService) GetModelPricing(modelName string) *LiteLLMModelPricing } // 5. OpenAI 模型回退策略 - if strings.HasPrefix(lookupCandidates[0], "gpt-") { + // gpt-oss* 是开放权重模型(ollama cloud 等托管),不属于 OpenAI 模型家族: + // 不进本回退链 —— 否则 matchOpenAIModel 的末端 catch-all 会把它落到 + // DefaultTestModel("gpt-5.4") 的价卡($2.5/$15 per MTok)上静默误计。 + // 返回 nil 交还 BillingService 走 fallbackPrices 的 ollama 专属价卡。 + if strings.HasPrefix(lookupCandidates[0], "gpt-") && !strings.HasPrefix(lookupCandidates[0], "gpt-oss") { return s.matchOpenAIModel(lookupCandidates[0]) } From 6995a6226d0a7a38aab12e422604393ee711b30c Mon Sep 17 00:00:00 2001 From: alfadb Date: Sun, 13 Sep 2026 03:02:35 +0800 Subject: [PATCH 17/81] 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 --- backend/cmd/server/wire_gen.go | 2 +- .../internal/handler/admin/channel_handler.go | 5 + .../handler/admin/channel_handler_test.go | 29 ++ backend/internal/server/api_contract_test.go | 2 +- ...t_codex_fingerprint_seed_lifecycle_test.go | 2 +- .../account_ollama_cloud_pricing_gate.go | 110 ++++++++ .../account_ollama_cloud_pricing_gate_test.go | 254 ++++++++++++++++++ backend/internal/service/account_service.go | 19 +- backend/internal/service/admin_account.go | 11 + backend/internal/service/admin_service.go | 5 + .../service/ollama_cloud_usage_test.go | 2 +- ..._gateway_ollama_cloud_billing_gate_test.go | 160 +++++++++++ .../internal/service/openai_gateway_usage.go | 48 +++- .../service/upstream_billing_probe.go | 8 +- 14 files changed, 641 insertions(+), 16 deletions(-) create mode 100644 backend/internal/service/account_ollama_cloud_pricing_gate.go create mode 100644 backend/internal/service/account_ollama_cloud_pricing_gate_test.go create mode 100644 backend/internal/service/openai_gateway_ollama_cloud_billing_gate_test.go diff --git a/backend/cmd/server/wire_gen.go b/backend/cmd/server/wire_gen.go index 1eda60da76..04d029aeee 100644 --- a/backend/cmd/server/wire_gen.go +++ b/backend/cmd/server/wire_gen.go @@ -191,7 +191,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) diff --git a/backend/internal/handler/admin/channel_handler.go b/backend/internal/handler/admin/channel_handler.go index 065aedb2f4..4d0ca315d1 100644 --- a/backend/internal/handler/admin/channel_handler.go +++ b/backend/internal/handler/admin/channel_handler.go @@ -633,6 +633,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", diff --git a/backend/internal/handler/admin/channel_handler_test.go b/backend/internal/handler/admin/channel_handler_test.go index 0c01631ecc..62e10459c4 100644 --- a/backend/internal/handler/admin/channel_handler_test.go +++ b/backend/internal/handler/admin/channel_handler_test.go @@ -582,6 +582,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() diff --git a/backend/internal/server/api_contract_test.go b/backend/internal/server/api_contract_test.go index 95010937c7..b2d2633964 100644 --- a/backend/internal/server/api_contract_test.go +++ b/backend/internal/server/api_contract_test.go @@ -1494,7 +1494,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) diff --git a/backend/internal/service/account_codex_fingerprint_seed_lifecycle_test.go b/backend/internal/service/account_codex_fingerprint_seed_lifecycle_test.go index 029b4fb009..6668c0b554 100644 --- a/backend/internal/service/account_codex_fingerprint_seed_lifecycle_test.go +++ b/backend/internal/service/account_codex_fingerprint_seed_lifecycle_test.go @@ -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", diff --git a/backend/internal/service/account_ollama_cloud_pricing_gate.go b/backend/internal/service/account_ollama_cloud_pricing_gate.go new file mode 100644 index 0000000000..ba8caaae95 --- /dev/null +++ b/backend/internal/service/account_ollama_cloud_pricing_gate.go @@ -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 +} diff --git a/backend/internal/service/account_ollama_cloud_pricing_gate_test.go b/backend/internal/service/account_ollama_cloud_pricing_gate_test.go new file mode 100644 index 0000000000..95e1ad01c6 --- /dev/null +++ b/backend/internal/service/account_ollama_cloud_pricing_gate_test.go @@ -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)) +} diff --git a/backend/internal/service/account_service.go b/backend/internal/service/account_service.go index ba5aebca07..8524e12fa0 100644 --- a/backend/internal/service/account_service.go +++ b/backend/internal/service/account_service.go @@ -208,6 +208,8 @@ type UpdateAccountRequest struct { type AccountService struct { accountRepo AccountRepository groupRepo GroupRepository + // B2-③ 保存期无价门禁用:ollama_cloud 账号保存时断言可出站模型名全部可定价。 + billingService *BillingService } type groupExistenceBatchChecker interface { @@ -215,10 +217,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, } } @@ -254,6 +257,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) } @@ -378,6 +386,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) diff --git a/backend/internal/service/admin_account.go b/backend/internal/service/admin_account.go index ef4a47fa1f..47ef449acb 100644 --- a/backend/internal/service/admin_account.go +++ b/backend/internal/service/admin_account.go @@ -532,6 +532,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 } @@ -861,6 +865,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 { diff --git a/backend/internal/service/admin_service.go b/backend/internal/service/admin_service.go index 1c90cffc22..7573bf27fd 100644 --- a/backend/internal/service/admin_service.go +++ b/backend/internal/service/admin_service.go @@ -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, } diff --git a/backend/internal/service/ollama_cloud_usage_test.go b/backend/internal/service/ollama_cloud_usage_test.go index da1decb8ab..f15c30f2b4 100644 --- a/backend/internal/service/ollama_cloud_usage_test.go +++ b/backend/internal/service/ollama_cloud_usage_test.go @@ -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", 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 new file mode 100644 index 0000000000..c63bab092e --- /dev/null +++ b/backend/internal/service/openai_gateway_ollama_cloud_billing_gate_test.go @@ -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) +} diff --git a/backend/internal/service/openai_gateway_usage.go b/backend/internal/service/openai_gateway_usage.go index 84e6fd49f5..04f5696d52 100644 --- a/backend/internal/service/openai_gateway_usage.go +++ b/backend/internal/service/openai_gateway_usage.go @@ -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), @@ -924,19 +957,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)) diff --git a/backend/internal/service/upstream_billing_probe.go b/backend/internal/service/upstream_billing_probe.go index 91639c8573..a09e482871 100644 --- a/backend/internal/service/upstream_billing_probe.go +++ b/backend/internal/service/upstream_billing_probe.go @@ -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. From df0199fbdd5e88b1a818f66a147bac376e88173a Mon Sep 17 00:00:00 2001 From: alfadb Date: Sun, 13 Sep 2026 03:24:12 +0800 Subject: [PATCH 18/81] feat(scheduling): suspend exhausted legacy ollama cloud accounts MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 增量 4a(③ 组 A6+C25+E9 + ⑤ 组 A2 + F4,同批落地): - A2: 新增 AccountModeOllamaLegacy/OllamaCredits 常量与 Account.GetOllamaCloudAccountMode 解析器(非 ollama_cloud/非 apikey 返回空串;未设置或值不认识默认 legacy,存量账号保持受阈值保护) - A6: AllowedSchedulingThresholdPlatforms 纳入 ollama_cloud(4 个消费点 同步生效:评估器门禁、设置校验、存储解析、设置审计 diff) - C25: 评估器新增 ollama 分支 + ollamaCloudThresholdCandidates,仅 legacy 产生 5h/weekly 停调候选(credits 型月度信用池候选恒空);快照缺失/ status!=ok/无窗口数据不停调;取最晚 reset(与 openai/anthropic 同类) - E9: 前端 SchedulingThresholdPlatformType union 与 SCHEDULING_THRESHOLD_PLATFORMS 数组加 ollama_cloud(与后端白名单两侧同步) - F4: 评估器表驱动用例(legacy 停/credits 不停/默认 legacy/坏快照不停)、 ApplyAccountSchedulingThreshold 端到端(temp_unschedulable 落库断言)、 mode 解析器用例、设置校验 ollama_cloud 往返用例 无迁移、无 DTO 变更(account_mode 为自由 JSONB,无 CHECK 约束)。 --- backend/internal/domain/constants.go | 6 + backend/internal/service/account.go | 15 ++ .../service/account_ollama_cloud_mode_test.go | 92 +++++++++++ .../account_scheduling_threshold_eval.go | 36 +++++ .../account_scheduling_threshold_eval_test.go | 144 ++++++++++++++++++ backend/internal/service/domain_constants.go | 6 + ...limit_service_scheduling_threshold_test.go | 78 ++++++++++ ...setting_service_platform_threshold_test.go | 28 ++++ frontend/src/api/admin/settings.ts | 5 +- 9 files changed, 409 insertions(+), 1 deletion(-) create mode 100644 backend/internal/service/account_ollama_cloud_mode_test.go diff --git a/backend/internal/domain/constants.go b/backend/internal/domain/constants.go index 56d3ad121b..3e0d65c3ef 100644 --- a/backend/internal/domain/constants.go +++ b/backend/internal/domain/constants.go @@ -39,11 +39,17 @@ const ( // Account mode constants 区分国产供应商的「按量付费(余额)」与「Coding Plan」两种接入方式。 // 存储于 credentials["account_mode"],决定 base_url 预设与额度监控方式。 +// ollama_cloud 的两代额度语义同存于此键:legacy 是 5h/7d 滚动窗口(与 Go 订阅同类, +// 受阈值停调保护);credits 是 2026-08-31 新定价后的月度美元信用池(无滚动窗口, +// 用完不硬停,不走阈值停调)。 const ( AccountModePayG = "payg" // 按量付费:消耗余额,做余额检测冷却 AccountModeCoding = "coding" // Coding Plan:滚动用量窗口冷却(5h / weekly) AccountModeZen = "zen" // OpenCode Zen:按量付费,https://opencode.ai/zen/v1 AccountModeGo = "go" // OpenCode Go:订阅额度窗口,https://opencode.ai/zen/go/v1 + + AccountModeOllamaLegacy = "ollama_legacy" // Ollama Cloud legacy:5h / 7d 滚动窗口 + AccountModeOllamaCredits = "ollama_credits" // Ollama Cloud 月度美元信用池 ) // API protocol constants 国产供应商的上游 API 协议维度。存储于 diff --git a/backend/internal/service/account.go b/backend/internal/service/account.go index ca08c4620f..911c0ade5f 100644 --- a/backend/internal/service/account.go +++ b/backend/internal/service/account.go @@ -304,6 +304,21 @@ func (a *Account) IsOllamaCloud() bool { return a != nil && IsOllamaCloud(a.Platform) } +// GetOllamaCloudAccountMode 返回 Ollama Cloud 账号的额度模式 +// (AccountModeOllamaLegacy / AccountModeOllamaCredits)。非 ollama_cloud 平台 +// 或非 apikey 类型返回空串;credentials 未设置或值不认识时默认 legacy +// (保守:legacy 有 5h/7d 滚动窗口 → 受阈值停调保护,默认 credits 会让存量 +// legacy 账号失去保护)。与 GetAccountMode(国产 payg/coding 白名单)互不影响。 +func (a *Account) GetOllamaCloudAccountMode() string { + if a == nil || !a.IsOllamaCloud() || a.Type != AccountTypeAPIKey { + return "" + } + if strings.TrimSpace(a.GetCredential("account_mode")) == AccountModeOllamaCredits { + return AccountModeOllamaCredits + } + return AccountModeOllamaLegacy +} + // IsOpenAICompatible 报告账号是否走 OpenAI 网关(OpenAI 协议族)。 // openai/grok 原生走 OpenAI 网关;国产供应商同为 OpenAI Chat Completions // 兼容上游,也经 OpenAI 网关转发。OpenCode 与 Ollama Cloud 同样经 OpenAI diff --git a/backend/internal/service/account_ollama_cloud_mode_test.go b/backend/internal/service/account_ollama_cloud_mode_test.go new file mode 100644 index 0000000000..511bd99ab5 --- /dev/null +++ b/backend/internal/service/account_ollama_cloud_mode_test.go @@ -0,0 +1,92 @@ +//go:build unit + +package service + +import ( + "testing" + + "github.com/stretchr/testify/require" +) + +func TestGetOllamaCloudAccountMode(t *testing.T) { + t.Parallel() + + cases := []struct { + name string + platform string + accountType string + credentials map[string]any + want string + }{ + { + name: "defaults to legacy when unset", + platform: PlatformOllamaCloud, + accountType: AccountTypeAPIKey, + credentials: nil, + want: AccountModeOllamaLegacy, + }, + { + name: "explicit legacy", + platform: PlatformOllamaCloud, + accountType: AccountTypeAPIKey, + credentials: map[string]any{"account_mode": AccountModeOllamaLegacy}, + want: AccountModeOllamaLegacy, + }, + { + name: "explicit credits", + platform: PlatformOllamaCloud, + accountType: AccountTypeAPIKey, + credentials: map[string]any{"account_mode": AccountModeOllamaCredits}, + want: AccountModeOllamaCredits, + }, + { + name: "unknown value falls back to legacy", + platform: PlatformOllamaCloud, + accountType: AccountTypeAPIKey, + credentials: map[string]any{"account_mode": "bogus"}, + want: AccountModeOllamaLegacy, + }, + { + name: "oauth account returns empty", + platform: PlatformOllamaCloud, + accountType: AccountTypeOAuth, + credentials: map[string]any{"account_mode": AccountModeOllamaCredits}, + want: "", + }, + { + name: "non ollama platform returns empty", + platform: PlatformOpenAI, + accountType: AccountTypeAPIKey, + credentials: map[string]any{"account_mode": AccountModeOllamaCredits}, + want: "", + }, + } + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + account := &Account{ + Platform: tc.platform, + Type: tc.accountType, + Credentials: tc.credentials, + } + require.Equal(t, tc.want, account.GetOllamaCloudAccountMode()) + }) + } +} + +func TestGetAccountMode_IgnoresOllamaCloudModes(t *testing.T) { + t.Parallel() + + // 防回归:GetAccountMode 是国产 payg/coding 的白名单解析器, + // 不得被 ollama_cloud 的新 mode 值污染。 + for _, mode := range []string{AccountModeOllamaLegacy, AccountModeOllamaCredits} { + account := &Account{ + Platform: PlatformOllamaCloud, + Type: AccountTypeAPIKey, + Credentials: map[string]any{"account_mode": mode}, + } + require.Empty(t, account.GetAccountMode()) + } +} diff --git a/backend/internal/service/account_scheduling_threshold_eval.go b/backend/internal/service/account_scheduling_threshold_eval.go index 0e1a40934c..cd9361190b 100644 --- a/backend/internal/service/account_scheduling_threshold_eval.go +++ b/backend/internal/service/account_scheduling_threshold_eval.go @@ -60,6 +60,8 @@ func EvaluateAccountSchedulingThreshold(account *Account, thresholds map[string] winner = pickLatestResetSchedulingCandidate(grokThresholdCandidates(account), threshold, now) case PlatformKimi, PlatformZhipu, PlatformMiniMax, PlatformOpenCodeGo: winner = pickLatestResetSchedulingCandidate(cnProviderThresholdCandidates(account, decision.Platform), threshold, now) + case PlatformOllamaCloud: + winner = pickLatestResetSchedulingCandidate(ollamaCloudThresholdCandidates(account), threshold, now) default: return decision } @@ -399,6 +401,40 @@ func cnThresholdCandidate(extra map[string]any, provider, window string) *accoun } } +// ollamaCloudThresholdCandidates 读取 ollama_cloud 账号 5h / 7d 滚动窗口的用量快照 +// (由 OllamaCloudUsageService 写入 account.Extra,经 decodeOllamaCloudUsageSnapshot +// 解出嵌套 struct —— 与 CN 的扁平 extra 键不同构,不复用 cnThresholdCandidate)。 +// +// 仅 legacy 账号有滚动窗口;credits 型是月度美元信用池、没有窗口 reset 可等, +// 候选恒空(credits 赗欠告警走余额告警通道,不写 TempUnschedulableUntil)。 +// 快照缺失 / status != ok / 无窗口数据时同样返回 nil —— 宁可不停调也不基于 +// 坏快照误停。窗口语义与 openai/anthropic/kimi 同类:取最晚 reset。 +func ollamaCloudThresholdCandidates(account *Account) []*accountSchedulingThresholdCandidate { + if account == nil || account.GetOllamaCloudAccountMode() != AccountModeOllamaLegacy { + return nil + } + snapshot := decodeOllamaCloudUsageSnapshot(account.Extra) + if snapshot == nil || snapshot.Status != OllamaCloudUsageStatusOK || snapshot.Data == nil { + return nil + } + return []*accountSchedulingThresholdCandidate{ + ollamaCloudThresholdCandidate(snapshot.Data.FiveHour, "5h"), + ollamaCloudThresholdCandidate(snapshot.Data.SevenDay, "weekly"), + } +} + +func ollamaCloudThresholdCandidate(window *OllamaCloudUsageWindow, label string) *accountSchedulingThresholdCandidate { + if window == nil { + return nil + } + return &accountSchedulingThresholdCandidate{ + window: label, + scope: PlatformOllamaCloud, + usedPercent: window.UsedPercent, + until: cloneTimePtr(window.ResetAt), + } +} + func pickLatestResetSchedulingCandidate(candidates []*accountSchedulingThresholdCandidate, threshold int, now time.Time) *accountSchedulingThresholdCandidate { var winner *accountSchedulingThresholdCandidate for _, candidate := range candidates { diff --git a/backend/internal/service/account_scheduling_threshold_eval_test.go b/backend/internal/service/account_scheduling_threshold_eval_test.go index 5e39de87de..6456ec6894 100644 --- a/backend/internal/service/account_scheduling_threshold_eval_test.go +++ b/backend/internal/service/account_scheduling_threshold_eval_test.go @@ -528,3 +528,147 @@ func TestEvaluateAccountSchedulingThreshold_GrokUsesOnlyHeaderQuotaWindow(t *tes require.NotNil(t, decision.Until) require.True(t, headerUntil.Equal(*decision.Until)) } + +// ollamaCloudSnapshotExtra 构造 account.Extra 里 ollama_cloud 用量快照的测试夹具, +// 形状与 DB JSONB 反序列化后的嵌套 map 一致(decodeOllamaCloudUsageSnapshot 走 +// marshal/unmarshal 往返,map 形式即生产读取路径)。 +func ollamaCloudSnapshotExtra(status string, data map[string]any) map[string]any { + snapshot := map[string]any{"status": status} + if data != nil { + snapshot["data"] = data + } + return map[string]any{OllamaCloudUsageSnapshotExtraKey: snapshot} +} + +func ollamaCloudUsageWindowFixture(usedPercent float64, resetAt time.Time) map[string]any { + return map[string]any{ + "used_percent": usedPercent, + "reset_at": resetAt.Format(time.RFC3339), + } +} + +func TestEvaluateAccountSchedulingThreshold_OllamaCloud(t *testing.T) { + t.Parallel() + + now := time.Date(2026, 6, 3, 12, 0, 0, 0, time.UTC) + fiveHourReset := now.Add(2 * time.Hour) + sevenDayReset := now.Add(5 * 24 * time.Hour) + newSnapshotAccount := func(mode string, extra map[string]any) *Account { + account := &Account{ + Platform: PlatformOllamaCloud, + Type: AccountTypeAPIKey, + Extra: extra, + } + if mode != "" { + account.Credentials = map[string]any{"account_mode": mode} + } + return account + } + okExtra := ollamaCloudSnapshotExtra(OllamaCloudUsageStatusOK, map[string]any{ + "five_hour": ollamaCloudUsageWindowFixture(95, fiveHourReset), + "seven_day": ollamaCloudUsageWindowFixture(40, sevenDayReset), + }) + + cases := []struct { + name string + account *Account + shouldPause bool + wantWindow string + wantUntil time.Time + }{ + { + name: "legacy pauses at exhausted five hour window", + account: newSnapshotAccount("ollama_legacy", okExtra), + shouldPause: true, + wantWindow: "5h", + wantUntil: fiveHourReset, + }, + { + name: "mode unset defaults to legacy and pauses", + account: newSnapshotAccount("", okExtra), + shouldPause: true, + wantWindow: "5h", + wantUntil: fiveHourReset, + }, + { + name: "unknown mode value falls back to legacy and pauses", + account: newSnapshotAccount("bogus", okExtra), + shouldPause: true, + wantWindow: "5h", + wantUntil: fiveHourReset, + }, + { + // 防回归护栏:credits 型是月度美元信用池、没有滚动窗口 reset, + // 即使快照里解析出 5h/7d 数据也绝不停调。 + name: "credits never pauses despite fully populated snapshot", + account: newSnapshotAccount("ollama_credits", okExtra), + shouldPause: false, + }, + { + name: "failed snapshot does not pause", + account: newSnapshotAccount("ollama_legacy", ollamaCloudSnapshotExtra(OllamaCloudUsageStatusFailed, nil)), + shouldPause: false, + }, + { + name: "ok snapshot without window data does not pause", + account: newSnapshotAccount("ollama_legacy", ollamaCloudSnapshotExtra(OllamaCloudUsageStatusOK, map[string]any{})), + shouldPause: false, + }, + { + // 防回归护栏:A6 纳入白名单后,无快照的账号同样不得停调。 + name: "missing snapshot does not pause", + account: newSnapshotAccount("ollama_legacy", map[string]any{}), + shouldPause: false, + }, + } + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + decision := EvaluateAccountSchedulingThreshold(tc.account, map[string]int{ + PlatformOllamaCloud: 80, + }, now) + + require.Equal(t, tc.shouldPause, decision.ShouldPause) + if !tc.shouldPause { + return + } + require.Equal(t, PlatformOllamaCloud, decision.Platform) + require.Equal(t, tc.wantWindow, decision.Window) + require.Equal(t, PlatformOllamaCloud, decision.Scope) + require.NotNil(t, decision.Until) + require.True(t, tc.wantUntil.Equal(*decision.Until)) + }) + } +} + +func TestEvaluateAccountSchedulingThreshold_OllamaCloudPicksLatestResetWindow(t *testing.T) { + t.Parallel() + + // 与 openai/anthropic/kimi 同类取最晚 reset(不是 CN 供应商的最早 reset)。 + now := time.Date(2026, 6, 3, 12, 0, 0, 0, time.UTC) + fiveHourReset := now.Add(2 * time.Hour) + sevenDayReset := now.Add(5 * 24 * time.Hour) + account := &Account{ + Platform: PlatformOllamaCloud, + Type: AccountTypeAPIKey, + Credentials: map[string]any{ + "account_mode": "ollama_legacy", + }, + Extra: ollamaCloudSnapshotExtra(OllamaCloudUsageStatusOK, map[string]any{ + "five_hour": ollamaCloudUsageWindowFixture(95, fiveHourReset), + "seven_day": ollamaCloudUsageWindowFixture(90, sevenDayReset), + }), + } + + decision := EvaluateAccountSchedulingThreshold(account, map[string]int{ + PlatformOllamaCloud: 80, + }, now) + + require.True(t, decision.ShouldPause) + require.Equal(t, "weekly", decision.Window) + require.Equal(t, PlatformOllamaCloud, decision.Scope) + require.NotNil(t, decision.Until) + require.True(t, sevenDayReset.Equal(*decision.Until)) +} diff --git a/backend/internal/service/domain_constants.go b/backend/internal/service/domain_constants.go index df3396a66a..ecd5442eeb 100644 --- a/backend/internal/service/domain_constants.go +++ b/backend/internal/service/domain_constants.go @@ -64,6 +64,9 @@ const ( AccountModeCoding = domain.AccountModeCoding AccountModeZen = domain.AccountModeZen AccountModeGo = domain.AccountModeGo + + AccountModeOllamaLegacy = domain.AccountModeOllamaLegacy // Ollama Cloud legacy:5h / 7d 滚动窗口 + AccountModeOllamaCredits = domain.AccountModeOllamaCredits // Ollama Cloud 月度美元信用池 ) // 上游 API 协议(国产供应商):决定转发端点与格式,与接入模式正交。 @@ -154,6 +157,8 @@ var AllowedQuotaPlatforms = []string{ // AllowedSchedulingThresholdPlatforms 是允许设置账号自动停调阈值的平台列表。 // openai/anthropic/grok 有原生用量窗口;kimi/zhipu/minimax 的 Coding Plan 同样暴露 // 5h/weekly 滚动窗口,纳入阈值评估。deepseek 为余额型,走余额检测而非阈值。 +// ollama_cloud 仅 legacy 账号有 5h/7d 滚动窗口可等 reset;credits 型是月度美元 +// 信用池、没有窗口 reset,评估器候选恒空(见 ollamaCloudThresholdCandidates)。 var AllowedSchedulingThresholdPlatforms = []string{ PlatformOpenAI, PlatformAnthropic, @@ -162,6 +167,7 @@ var AllowedSchedulingThresholdPlatforms = []string{ PlatformZhipu, PlatformMiniMax, PlatformOpenCodeGo, + PlatformOllamaCloud, } // IsAllowedQuotaPlatform 报告 s 是否为合法的 quota platform 标识。 diff --git a/backend/internal/service/ratelimit_service_scheduling_threshold_test.go b/backend/internal/service/ratelimit_service_scheduling_threshold_test.go index 2af50086ae..fc3154e76f 100644 --- a/backend/internal/service/ratelimit_service_scheduling_threshold_test.go +++ b/backend/internal/service/ratelimit_service_scheduling_threshold_test.go @@ -228,3 +228,81 @@ func TestRateLimitService_ApplyAccountSchedulingThreshold_UnsupportedPlatformDoe require.Nil(t, account.TempUnschedulableUntil) require.Empty(t, account.TempUnschedulableReason) } + +func TestRateLimitService_ApplyAccountSchedulingThreshold_OllamaCloudLegacySetsTempUnschedulable(t *testing.T) { + accountSchedulingThresholdsSF.Forget(SettingKeyAccountSchedulingThresholds) + accountSchedulingThresholdsCache.Store(&cachedAccountSchedulingThresholds{}) + + settingsRepo := newMockSettingRepo() + settingsRepo.data[SettingKeyAccountSchedulingThresholds] = `{"ollama_cloud":80}` + + accountRepo := &rateLimitAccountRepoStub{} + rl := NewRateLimitService(accountRepo, nil, &config.Config{}, nil, nil) + rl.SetSettingService(NewSettingService(settingsRepo, &config.Config{})) + + until := time.Now().UTC().Add(2 * time.Hour) + account := &Account{ + ID: 3001, + Platform: PlatformOllamaCloud, + Type: AccountTypeAPIKey, + Status: StatusActive, + Schedulable: true, + Credentials: map[string]any{ + "account_mode": "ollama_legacy", + }, + Extra: ollamaCloudSnapshotExtra(OllamaCloudUsageStatusOK, map[string]any{ + "five_hour": ollamaCloudUsageWindowFixture(95, until), + "seven_day": ollamaCloudUsageWindowFixture(40, until.Add(5*24*time.Hour)), + }), + } + + blocked := rl.ApplyAccountSchedulingThreshold(context.Background(), account) + + require.True(t, blocked) + require.Equal(t, 1, accountRepo.tempCalls) + require.NotNil(t, account.TempUnschedulableUntil) + require.WithinDuration(t, until, *account.TempUnschedulableUntil, time.Second) + require.True(t, IsAccountSchedulingThresholdReason(accountRepo.lastTempReason)) + + var payload map[string]any + require.NoError(t, json.Unmarshal([]byte(accountRepo.lastTempReason), &payload)) + require.Equal(t, PlatformOllamaCloud, payload["platform"]) + require.Equal(t, "5h", payload["window"]) + require.Equal(t, float64(80), payload["threshold_percent"]) + require.Equal(t, float64(95), payload["used_percent"]) +} + +func TestRateLimitService_ApplyAccountSchedulingThreshold_OllamaCloudCreditsDoesNotBlock(t *testing.T) { + accountSchedulingThresholdsSF.Forget(SettingKeyAccountSchedulingThresholds) + accountSchedulingThresholdsCache.Store(&cachedAccountSchedulingThresholds{}) + + settingsRepo := newMockSettingRepo() + settingsRepo.data[SettingKeyAccountSchedulingThresholds] = `{"ollama_cloud":80}` + + accountRepo := &rateLimitAccountRepoStub{} + rl := NewRateLimitService(accountRepo, nil, &config.Config{}, nil, nil) + rl.SetSettingService(NewSettingService(settingsRepo, &config.Config{})) + + until := time.Now().UTC().Add(2 * time.Hour) + account := &Account{ + ID: 3002, + Platform: PlatformOllamaCloud, + Type: AccountTypeAPIKey, + Status: StatusActive, + Schedulable: true, + Credentials: map[string]any{ + "account_mode": "ollama_credits", + }, + Extra: ollamaCloudSnapshotExtra(OllamaCloudUsageStatusOK, map[string]any{ + "five_hour": ollamaCloudUsageWindowFixture(100, until), + "seven_day": ollamaCloudUsageWindowFixture(100, until.Add(5*24*time.Hour)), + }), + } + + blocked := rl.ApplyAccountSchedulingThreshold(context.Background(), account) + + require.False(t, blocked) + require.Equal(t, 0, accountRepo.tempCalls) + require.Nil(t, account.TempUnschedulableUntil) + require.Empty(t, account.TempUnschedulableReason) +} diff --git a/backend/internal/service/setting_service_platform_threshold_test.go b/backend/internal/service/setting_service_platform_threshold_test.go index 3e4543e0e0..b8281cd6db 100644 --- a/backend/internal/service/setting_service_platform_threshold_test.go +++ b/backend/internal/service/setting_service_platform_threshold_test.go @@ -169,3 +169,31 @@ func TestGetAccountSchedulingThresholds_NilRepoReturnsDefaults(t *testing.T) { PlatformGrok: 100, }, got) } + +func TestValidateAndNormalizeAccountSchedulingThresholds_AcceptsOllamaCloud(t *testing.T) { + normalized, err := validateAndNormalizeAccountSchedulingThresholds(map[string]int{ + PlatformOllamaCloud: 80, + }) + require.NoError(t, err) + require.Equal(t, 80, normalized[PlatformOllamaCloud]) +} + +func TestAccountSchedulingThresholds_OllamaCloudRoundTrip(t *testing.T) { + svc := newSettingServiceForPlatformThresholdTest(nil) + + // A6 验收的服务层等价路径:PUT account_scheduling_thresholds {"ollama_cloud":80} + // 必须被接受并回读 —— 白名单未纳入 ollama_cloud 时这里被 + // validateAndNormalizeAccountSchedulingThresholds 拒为 unknown platform(400)。 + err := svc.UpdateSettings(context.Background(), &SystemSettings{ + AccountSchedulingThresholds: map[string]int{ + PlatformOllamaCloud: 80, + }, + }) + require.NoError(t, err) + + stored := svc.settingRepo.(*mockSettingRepo).data[SettingKeyAccountSchedulingThresholds] + require.Contains(t, stored, `"ollama_cloud":80`) + + cached := svc.GetAccountSchedulingThresholds(context.Background()) + require.Equal(t, 80, cached[PlatformOllamaCloud]) +} diff --git a/frontend/src/api/admin/settings.ts b/frontend/src/api/admin/settings.ts index 1a9c24103c..3118d2e17d 100644 --- a/frontend/src/api/admin/settings.ts +++ b/frontend/src/api/admin/settings.ts @@ -41,11 +41,13 @@ export type SchedulingThresholdPlatformType = | "zhipu" | "minimax" | "opencode_go" + | "ollama_cloud" export type AccountSchedulingThresholdsMap = Record // 与后端 AllowedSchedulingThresholdPlatforms 保持一致(deepseek 为余额型, -// 走余额检测而非用量阈值;minimax Coding/Token Plan 与 OpenCode GO 有滚动窗口)。 +// 走余额检测而非用量阈值;minimax Coding/Token Plan 与 OpenCode GO 有滚动窗口; +// ollama_cloud 仅 legacy 账号有 5h/7d 滚动窗口,credits 型月度信用池无窗口不停调)。 export const SCHEDULING_THRESHOLD_PLATFORMS: SchedulingThresholdPlatformType[] = [ "openai", "anthropic", @@ -54,6 +56,7 @@ export const SCHEDULING_THRESHOLD_PLATFORMS: SchedulingThresholdPlatformType[] = "zhipu", "minimax", "opencode_go", + "ollama_cloud", ] export function normalizeAccountSchedulingThresholdsMap( From 625f7b0d23c0f5f7d377014132ecc7b43fa9197d Mon Sep 17 00:00:00 2001 From: alfadb Date: Sun, 13 Sep 2026 04:05:44 +0800 Subject: [PATCH 19/81] 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), From e5f75b7b0244c3cef8d69e61e01a73a083dec667 Mon Sep 17 00:00:00 2001 From: alfadb Date: Sun, 13 Sep 2026 04:31:49 +0800 Subject: [PATCH 20/81] fix(ollama): enforce the ollama cloud model whitelist at runtime --- backend/internal/handler/gateway_handler.go | 12 ++ ...ateway_handler_ollama_cloud_models_test.go | 85 ++++++++++ .../internal/repository/scheduler_cache.go | 5 + .../scheduler_cache_ollama_cloud_test.go | 39 +++++ backend/internal/service/account.go | 20 +++ .../account_ollama_cloud_whitelist_test.go | 159 ++++++++++++++++++ backend/internal/service/gateway_service.go | 28 ++- .../service/ollama_cloud_scheduling_test.go | 3 + 8 files changed, 343 insertions(+), 8 deletions(-) create mode 100644 backend/internal/handler/gateway_handler_ollama_cloud_models_test.go create mode 100644 backend/internal/repository/scheduler_cache_ollama_cloud_test.go create mode 100644 backend/internal/service/account_ollama_cloud_whitelist_test.go diff --git a/backend/internal/handler/gateway_handler.go b/backend/internal/handler/gateway_handler.go index 2770a183ab..1a9f69a4a5 100644 --- a/backend/internal/handler/gateway_handler.go +++ b/backend/internal/handler/gateway_handler.go @@ -1287,6 +1287,13 @@ func (h *GatewayHandler) Models(c *gin.Context) { return } + // ollama_cloud 无静态默认模型列表(defaultModelIDsForPlatform 返回空): + // 账号侧清单缺失时返回空列表,不得回落 Claude 默认模型。 + if platform == service.PlatformOllamaCloud { + writeModelsListResponse(c, []claude.Model{}) + return + } + writeModelsListResponse(c, claude.DefaultModels) } @@ -1572,6 +1579,11 @@ func defaultModelIDsForPlatform(platform string) []string { return service.DefaultOpenCodeGoModelIDs() case service.PlatformTypeSafe: return []string{"jev-latest"} + case service.PlatformOllamaCloud: + // ollama_cloud 没有静态默认模型列表:可服务模型完全来自账号侧的 + // model_mapping / extra.allowed_models(缺失时 IsModelSupported 为 + // deny-all)。default 分支的 Claude 列表对它只会造成虚假广告。 + return nil case service.PlatformComposite: ids := make([]string, 0) seen := make(map[string]struct{}) diff --git a/backend/internal/handler/gateway_handler_ollama_cloud_models_test.go b/backend/internal/handler/gateway_handler_ollama_cloud_models_test.go new file mode 100644 index 0000000000..56931d21d6 --- /dev/null +++ b/backend/internal/handler/gateway_handler_ollama_cloud_models_test.go @@ -0,0 +1,85 @@ +package handler + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "testing" + + middleware2 "github.com/Wei-Shaw/sub2api/internal/server/middleware" + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +// ollama_cloud 没有静态默认模型列表:defaultModelIDsForPlatform 不得回落 +// Claude 列表(default 分支),/models 在账号侧清单缺失时返回空列表。 +func TestDefaultModelIDsForPlatform_OllamaCloudReturnsEmpty(t *testing.T) { + require.Empty(t, defaultModelIDsForPlatform(service.PlatformOllamaCloud)) + require.NotEmpty(t, defaultModelIDsForPlatform(service.PlatformAnthropic)) +} + +func TestGatewayModels_OllamaCloudGroupListsAllowedModels(t *testing.T) { + gin.SetMode(gin.TestMode) + + groupID := int64(9201) + h := newGatewayModelsHandlerForTest( + &gatewayModelsAccountRepoStub{ + byGroup: map[int64][]service.Account{ + groupID: { + { + ID: 1, + Platform: service.PlatformOllamaCloud, + Credentials: map[string]any{}, + Extra: map[string]any{service.OllamaCloudAllowedModelsExtraKey: []any{"gpt-oss:120b"}}, + }, + }, + }, + }, + ) + + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodGet, "/v1/models", nil) + c.Set(string(middleware2.ContextKeyAPIKey), &service.APIKey{ + Group: &service.Group{ID: groupID, Platform: service.PlatformOllamaCloud}, + }) + + h.Models(c) + + require.Equal(t, http.StatusOK, rec.Code) + var got gatewayModelsResponseForTest + require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &got)) + require.Equal(t, []string{"gpt-oss:120b"}, modelIDsForTest(got.Data)) +} + +// 账号侧清单缺失(deny-all)时 /models 必须返回空,而不是回落 Claude 列表。 +func TestGatewayModels_OllamaCloudGroupWithoutListReturnsEmpty(t *testing.T) { + gin.SetMode(gin.TestMode) + + groupID := int64(9202) + h := newGatewayModelsHandlerForTest( + &gatewayModelsAccountRepoStub{ + byGroup: map[int64][]service.Account{ + groupID: { + {ID: 1, Platform: service.PlatformOllamaCloud, Credentials: map[string]any{}}, + }, + }, + }, + ) + + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodGet, "/v1/models", nil) + c.Set(string(middleware2.ContextKeyAPIKey), &service.APIKey{ + Group: &service.Group{ID: groupID, Platform: service.PlatformOllamaCloud}, + }) + + h.Models(c) + + require.Equal(t, http.StatusOK, rec.Code) + var got gatewayModelsResponseForTest + require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &got)) + require.Empty(t, got.Data, "ollama_cloud 不得回落 Claude 默认模型列表") + require.NotContains(t, modelIDsForTest(got.Data), "claude-sonnet-4-6") +} diff --git a/backend/internal/repository/scheduler_cache.go b/backend/internal/repository/scheduler_cache.go index e3715f678e..eab94cc723 100644 --- a/backend/internal/repository/scheduler_cache.go +++ b/backend/internal/repository/scheduler_cache.go @@ -1021,6 +1021,11 @@ func filterSchedulerExtra(extra map[string]any) map[string]any { // 走网关报 no available accounts"。 "openai_passthrough", "openai_oauth_passthrough", + // ollama_cloud 空 mapping 的出站白名单必须进投影:候选过滤的 + // Account.IsModelSupported 以它为白名单(无清单即 deny-all)。 + // 裁掉它,白名单账号会在选号阶段被整体误判为 model_not_supported, + // 表现为 ollama_cloud 分组恒 no available accounts。 + service.OllamaCloudAllowedModelsExtraKey, "codex_fingerprint_mode", "codex_fingerprint_seed", "codex_5h_used_percent", diff --git a/backend/internal/repository/scheduler_cache_ollama_cloud_test.go b/backend/internal/repository/scheduler_cache_ollama_cloud_test.go new file mode 100644 index 0000000000..63473073b3 --- /dev/null +++ b/backend/internal/repository/scheduler_cache_ollama_cloud_test.go @@ -0,0 +1,39 @@ +//go:build unit + +package repository + +import ( + "encoding/json" + "testing" + + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/stretchr/testify/require" +) + +// ollama_cloud 空 mapping 的出站白名单(extra.allowed_models)必须穿过调度投影: +// 候选过滤的 Account.IsModelSupported 以它为白名单(无清单即 deny-all)。裁掉它, +// 白名单账号会在选号阶段被整体误判为 model_not_supported(#4936 同款投影缺失)。 +func TestFilterSchedulerExtra_KeepsOllamaCloudAllowedModels(t *testing.T) { + extra := map[string]any{ + service.OllamaCloudAllowedModelsExtraKey: []any{"gpt-oss:120b", "qwen3:32b"}, + "unknown_key": "must-be-dropped", + } + + filtered := filterSchedulerExtra(extra) + require.Len(t, filtered, 1) + + kept, ok := filtered[service.OllamaCloudAllowedModelsExtraKey] + require.True(t, ok, "allowed_models 必须保留在调度投影中") + require.Contains(t, kept, "gpt-oss:120b") + + // 走真实的序列化/反序列化路径:sched:meta 里的 []string 会以 []any 读回, + // ollamaCloudOutboundModelNames 两种形态都必须能解析。 + payload, err := json.Marshal(filtered) + require.NoError(t, err) + var decoded map[string]any + require.NoError(t, json.Unmarshal(payload, &decoded)) + + account := service.Account{ID: 1, Platform: service.PlatformOllamaCloud, Extra: decoded} + require.True(t, account.IsModelSupported("gpt-oss:120b")) + require.False(t, account.IsModelSupported("totally-unpriced-model")) +} diff --git a/backend/internal/service/account.go b/backend/internal/service/account.go index 911c0ade5f..151647fdca 100644 --- a/backend/internal/service/account.go +++ b/backend/internal/service/account.go @@ -894,6 +894,26 @@ func (a *Account) IsModelSupported(requestedModel string) bool { if a.Platform == PlatformDeepseek { return isDeepseekServableModel(requestedModel) } + // ollama_cloud 运行时白名单:空映射时 extra.allowed_models 清单就是 + // 唯一可出站白名单;既无映射也无清单则 deny-all(不支持任何模型)。 + // 与保存期门禁 validateOllamaCloudAccountModelPricingGate 的「mapping + // 或清单至少其一」语义对齐。空映射下请求的公开模型名即出站名 + // (ResolveMappedModel 原样透传),清单项又是按出站名断言过定价的, + // 因此对公开名做精确匹配即可;保存期门禁已确保清单不含通配符 + // (通配符串无法解析到定价,保存即被拒)。 + if a.IsOllamaCloud() { + allowed := ollamaCloudOutboundModelNames(a) + if len(allowed) == 0 { + return false + } + trimmed := strings.TrimSpace(requestedModel) + for _, model := range allowed { + if model == trimmed { + return true + } + } + return false + } return true // 无映射 = 允许所有 } if mappingSupportsRequestedModel(mapping, requestedModel) { diff --git a/backend/internal/service/account_ollama_cloud_whitelist_test.go b/backend/internal/service/account_ollama_cloud_whitelist_test.go new file mode 100644 index 0000000000..1ca7d6e873 --- /dev/null +++ b/backend/internal/service/account_ollama_cloud_whitelist_test.go @@ -0,0 +1,159 @@ +package service + +// ollama_cloud 运行时白名单回归测试(钉死独立评审的探针场景): +// - 空 model_mapping + extra.allowed_models 清单 → IsModelSupported 只放行 +// 清单内模型,清单外(含未定价模型名)一律拒绝、调度不选中; +// - 空 mapping 且无清单 → deny-all; +// - 非 ollama 平台空 mapping 仍放行所有(回归护栏); +// - /models 列表路径(GetAvailableModels)并入 allowed_models 清单。 +// +// 与保存期门禁(account_ollama_cloud_pricing_gate_test.go)合起来形成闭环: +// 白名单决定能发什么,预检决定发出去的东西是否有价。 + +import ( + "context" + "testing" + + "github.com/stretchr/testify/require" +) + +func newOllamaCloudWhitelistAccount(credentials map[string]any, extra map[string]any) *Account { + return &Account{ + ID: 9101, + Platform: PlatformOllamaCloud, + Type: AccountTypeAPIKey, + Status: StatusActive, + Schedulable: true, + Credentials: credentials, + Extra: extra, + } +} + +// 评审探针场景:空 mapping + 清单只含 gpt-oss:120b → totally-unpriced-model +// 必须不被支持、不被调度选中(评审当前观测到「仍 supported」)。 +func TestOllamaCloudWhitelist_ProbeUnpricedModelNotSupported(t *testing.T) { + t.Parallel() + + // Extra 走 JSON 反序列化的真实形态([]any 元素为 string)。 + account := newOllamaCloudWhitelistAccount( + map[string]any{}, + map[string]any{OllamaCloudAllowedModelsExtraKey: []any{"gpt-oss:120b"}}, + ) + + require.False(t, account.IsModelSupported("totally-unpriced-model"), + "清单外未定价模型名不得放行(评审探针场景)") + require.False(t, account.IsModelSupported("claude-sonnet-4-6"), + "其它平台默认模型名同样在清单外") + require.True(t, account.IsModelSupported("gpt-oss:120b"), "清单内模型必须放行") + + // 程序化构造形态([]string)语义一致。 + stringListAccount := newOllamaCloudWhitelistAccount( + nil, + map[string]any{OllamaCloudAllowedModelsExtraKey: []string{"gpt-oss:120b"}}, + ) + require.False(t, stringListAccount.IsModelSupported("totally-unpriced-model")) + require.True(t, stringListAccount.IsModelSupported("gpt-oss:120b")) + + // 调度候选过滤同样拒绝:不被选中。 + ctx := context.Background() + reason := openAICompatibleAccountEligibilityFailureReasonBeforeProfit( + ctx, account, PlatformOllamaCloud, "totally-unpriced-model", false, OpenAIEndpointCapabilityChatCompletions) + require.Equal(t, "model_not_supported", reason) + reason = openAICompatibleAccountEligibilityFailureReasonBeforeProfit( + ctx, account, PlatformOllamaCloud, "gpt-oss:120b", false, OpenAIEndpointCapabilityChatCompletions) + require.Empty(t, reason, "清单内模型必须保持可选中") +} + +func TestOllamaCloudWhitelist_EmptyMappingNoListDeniesAll(t *testing.T) { + t.Parallel() + + account := newOllamaCloudWhitelistAccount(map[string]any{}, map[string]any{}) + for _, model := range []string{"gpt-oss:120b", "totally-unpriced-model", "claude-sonnet-4-6", ""} { + require.False(t, account.IsModelSupported(model), + "空 mapping 且无清单必须 deny-all: %q", model) + } + + // 清单存在但全为空白项:视同未提供,仍然 deny-all(与保存期门禁的 + // 「清单缺失即拒绝」语义一致)。 + blankAccount := newOllamaCloudWhitelistAccount( + nil, + map[string]any{OllamaCloudAllowedModelsExtraKey: []any{" ", ""}}, + ) + require.False(t, blankAccount.IsModelSupported("gpt-oss:120b")) +} + +func TestOllamaCloudWhitelist_NonEmptyMappingKeepsMappingSemantics(t *testing.T) { + t.Parallel() + + account := newOllamaCloudWhitelistAccount( + map[string]any{"model_mapping": map[string]any{"alias:latest": "gpt-oss:120b"}}, + nil, + ) + require.True(t, account.IsModelSupported("alias:latest"), "mapping 键即公开白名单") + require.False(t, account.IsModelSupported("totally-unpriced-model")) + // 既有语义:非 ollama 也一样——mapping 目标值不是公开名,不因本次改动改变。 + require.False(t, account.IsModelSupported("gpt-oss:120b"), "mapping 目标值不是公开名") +} + +// 回归护栏:非 ollama 平台的空 mapping 仍放行所有(钉住 4 处风险面语义)。 +// 不含 antigravity / grok:这两个平台空 mapping 的既有语义是注入平台默认映射 +// (resolveModelMapping),从来不是「放行所有」,与本次改动无关。 +func TestOllamaCloudWhitelist_NonOllamaEmptyMappingStillAllowsAll(t *testing.T) { + t.Parallel() + + for _, platform := range []string{ + "", PlatformAnthropic, PlatformOpenAI, PlatformGemini, + PlatformDeepseek, PlatformKimi, PlatformMiniMax, PlatformZhipu, PlatformOpenCodeGo, + } { + account := &Account{ID: 1, Platform: platform, Type: AccountTypeAPIKey, Credentials: map[string]any{}} + require.Truef(t, account.IsModelSupported("totally-unpriced-model"), + "平台 %s 空 mapping 必须仍放行所有模型", platform) + } +} + +// /models 列表路径:GetAvailableModels 并入 ollama_cloud 的 allowed_models 清单。 +func TestGetAvailableModels_MergesOllamaCloudAllowedModels(t *testing.T) { + t.Parallel() + + groupID := int64(9102) + repo := &modelsListAccountRepoStub{ + byGroup: map[int64][]Account{ + groupID: { + { + ID: 1, + Platform: PlatformOllamaCloud, + Credentials: map[string]any{}, + Extra: map[string]any{OllamaCloudAllowedModelsExtraKey: []any{"gpt-oss:120b", "qwen3:32b"}}, + }, + { + ID: 2, + Platform: PlatformOllamaCloud, + Credentials: map[string]any{"model_mapping": map[string]any{"alias:latest": "gpt-oss:120b"}}, + }, + { + ID: 3, + Platform: PlatformOllamaCloud, + Credentials: map[string]any{}, + }, + }, + }, + } + svc := &GatewayService{accountRepo: repo} + + models := svc.GetAvailableModels(context.Background(), &groupID, PlatformOllamaCloud) + require.Equal(t, []string{"alias:latest", "gpt-oss:120b", "qwen3:32b"}, models) + + // 全部账号都是 deny-all(无 mapping 无清单)→ 无可用模型列表。 + denyAllGroup := int64(9103) + repo.byGroup[denyAllGroup] = []Account{ + {ID: 4, Platform: PlatformOllamaCloud, Credentials: map[string]any{}}, + } + require.Nil(t, svc.GetAvailableModels(context.Background(), &denyAllGroup, PlatformOllamaCloud)) + + // 非 ollama 平台的既有语义不变:无任何 mapping → 仍返回 nil(用默认列表)。 + nonOllamaGroup := int64(9104) + repo.byGroup[nonOllamaGroup] = []Account{ + {ID: 5, Platform: PlatformDeepseek, Credentials: map[string]any{}}, + } + require.Nil(t, svc.GetAvailableModels(context.Background(), &nonOllamaGroup, PlatformDeepseek)) +} diff --git a/backend/internal/service/gateway_service.go b/backend/internal/service/gateway_service.go index 1eaeea250f..f08038a454 100644 --- a/backend/internal/service/gateway_service.go +++ b/backend/internal/service/gateway_service.go @@ -1438,15 +1438,27 @@ func (s *GatewayService) GetAvailableModels(ctx context.Context, groupID *int64, } mapping := acc.GetModelMapping() - for model := range mapping { - // Accounts pulled in through mixed scheduling only contribute the - // models that belong to the listing platform (e.g. an antigravity - // account's claude-* mappings must not surface on a gemini group). - if platform != "" && acc.Platform != platform && !mixedListingModelAllowed(platform, model) { - continue + if len(mapping) > 0 { + for model := range mapping { + // Accounts pulled in through mixed scheduling only contribute the + // models that belong to the listing platform (e.g. an antigravity + // account's claude-* mappings must not surface on a gemini group). + if platform != "" && acc.Platform != platform && !mixedListingModelAllowed(platform, model) { + continue + } + modelSet[model] = struct{}{} + hasAnyMapping = true + } + } else if acc.IsOllamaCloud() { + // ollama_cloud 空 mapping:extra.allowed_models 清单即公开模型 + // 列表(空映射下公开名=出站名);无清单(deny-all)账号不贡献 + // 任何模型名,与 IsModelSupported 的运行时白名单语义一致。 + if allowed := ollamaCloudOutboundModelNames(&acc); len(allowed) > 0 { + hasAnyMapping = true + for _, model := range allowed { + modelSet[model] = struct{}{} + } } - modelSet[model] = struct{}{} - hasAnyMapping = true } } diff --git a/backend/internal/service/ollama_cloud_scheduling_test.go b/backend/internal/service/ollama_cloud_scheduling_test.go index 341cb78441..0eab300679 100644 --- a/backend/internal/service/ollama_cloud_scheduling_test.go +++ b/backend/internal/service/ollama_cloud_scheduling_test.go @@ -70,6 +70,9 @@ func TestOllamaCloudPlatform_EntersOpenAISchedulerCandidatePool(t *testing.T) { Schedulable: true, Concurrency: 1, Credentials: map[string]any{"api_key": "ollama-key", "base_url": "https://ollama.com/v1"}, + // 运行时白名单生效后,空 mapping 且无清单的 ollama_cloud 账号是 + // deny-all(保存期门禁本就拒绝该配置),夹具必须声明清单才能入选。 + Extra: map[string]any{OllamaCloudAllowedModelsExtraKey: []any{"gpt-oss:120b"}}, }, { ID: 77022, From 4a53d497174d662ae815b7393101c342a9f3fdd7 Mon Sep 17 00:00:00 2001 From: alfadb Date: Sun, 13 Sep 2026 05:05:39 +0800 Subject: [PATCH 21/81] fix(ollama): narrow the gpt-oss pricing exclusion and unblock legacy account updates MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 三处独立小修(来自 T0 评审): 1. gpt-oss 排除收窄为冒号命名空间(pricing_service.go GetModelPricing)。 此前的全局前缀排除误伤 Antigravity 默认模型映射目标名 gpt-oss-120b-medium (连字符形态):它被拦在 OpenAI 回退链外 → GetModelPricing 返回 unavailable → 非 Ollama 路径 fail-open 成 0 元记账。收窄后 ollama 侧(gpt-oss:120b / gpt-oss:20b / gpt-oss:120b-cloud)照修不误,Antigravity 恢复既有行为 (OpenAI catch-all → gpt-5.4 价卡,与 main 一致)。 2. 保存期无价门禁改为只在会改变「可出站模型集合」或影响调度准入时重验 (AccountService.Update / adminServiceImpl.UpdateAccount):platform、 model_mapping、allowed_models 集合实际变化,或从不可调度改为可调度时校验; name、notes、并发数、状态等维护性更新放行——存量 legacy 账号(无 mapping/ 清单)此前连改 name 都被 MODEL_PRICING_MISSING 拒绝。全对象 PUT 原样带回 credentials/extra 时集合未变同样放行。Create 与 BulkUpdate/Duplicate/ SetAccountSchedulable 三条写路径门禁不变。 3. respondOpenAIStatelessFieldError 补 MarkResponseCommitted(照 bcfef18ae 给 定价预检 400 的先例):conversation 400 的错误消息不在 openAIForwardErrorAlreadyCommunicated 识别的前缀内,不置位时 handler 会向 完整 400 JSON body 尾部追加 SSE 终止帧。三入站路径实测:仅 Responses 入站 可触发该 400(CC/Messages 转换不透传 conversation 字段)。 --- .../account_ollama_cloud_pricing_gate.go | 36 +++++ .../account_ollama_cloud_pricing_gate_test.go | 140 ++++++++++++++++++ backend/internal/service/account_service.go | 14 +- backend/internal/service/admin_account.go | 14 +- ...lama_cloud_dynamic_catalog_pricing_test.go | 57 +++++++ .../service/openai_gateway_request_body.go | 5 + ...enai_gateway_stateless_field_error_test.go | 114 ++++++++++++++ backend/internal/service/pricing_service.go | 6 +- 8 files changed, 380 insertions(+), 6 deletions(-) create mode 100644 backend/internal/service/openai_gateway_stateless_field_error_test.go diff --git a/backend/internal/service/account_ollama_cloud_pricing_gate.go b/backend/internal/service/account_ollama_cloud_pricing_gate.go index ba8caaae95..48dd5b6e50 100644 --- a/backend/internal/service/account_ollama_cloud_pricing_gate.go +++ b/backend/internal/service/account_ollama_cloud_pricing_gate.go @@ -2,6 +2,7 @@ package service import ( "fmt" + "slices" "strings" infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors" @@ -62,6 +63,41 @@ func validateOllamaCloudAccountModelPricingGate(lookup accountModelPricingLookup return nil } +// ollamaCloudPricingGateRevalidationNeeded 报告一次账号更新是否需要重跑保存期无价门禁。 +// +// 门禁只拦「可能改变可出站模型集合或影响调度准入」的更新: +// - platform 变化(可出站模型集合的判定语义随平台切换); +// - 可出站模型集合的实际输入变化(prevOutboundSet 是更新前 +// ollamaCloudOutboundModelNames 的快照,覆盖 credentials.model_mapping 与 +// extra.allowed_models 两条来源); +// - 从不可调度改为可调度(启用):存量 legacy 账号(无 mapping/清单)的维护性 +// 编辑平时放行,但启用调度前必须补齐并通过门禁。 +// +// name、notes、并发数、优先级、状态停用等维护性更新放行 —— 否则迁移过来的存量 +// 账号连改备注都会被 MODEL_PRICING_MISSING 锁死。调用方必须在应用本次请求的 +// 字段变更**之前**采集 prevPlatform / prevOutboundSet / prevSchedulable 快照。 +func ollamaCloudPricingGateRevalidationNeeded(prevPlatform string, prevOutboundSet []string, prevSchedulable bool, next *Account) bool { + if next == nil || !next.IsOllamaCloud() { + return false + } + if prevPlatform != next.Platform { + return true + } + nextSet := append([]string(nil), ollamaCloudOutboundModelNames(next)...) + slices.Sort(prevOutboundSet) + slices.Sort(nextSet) + if !slices.Equal(prevOutboundSet, nextSet) { + return true + } + return !prevSchedulable && ollamaCloudSchedulableBySave(next) +} + +// ollamaCloudSchedulableBySave 只看保存路径能改变的两个调度准入开关 +// (status 是否 active、手动 Schedulable 开关),不含时间窗等运行态。 +func ollamaCloudSchedulableBySave(a *Account) bool { + return a != nil && a.IsActive() && a.Schedulable +} + // ollamaCloudOutboundModelNames 收集 ollama_cloud 账号的可出站模型名集合 // (去重、去空)。空 mapping 且无有效清单时返回 nil。 // 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 95e1ad01c6..1e53ff3cdf 100644 --- a/backend/internal/service/account_ollama_cloud_pricing_gate_test.go +++ b/backend/internal/service/account_ollama_cloud_pricing_gate_test.go @@ -252,3 +252,143 @@ func TestOllamaCloudOutboundModelNames(t *testing.T) { account = &Account{Platform: PlatformOpenAI} require.Nil(t, ollamaCloudOutboundModelNames(account)) } + +// 门禁触发收窄回归:缺 mapping/清单的存量 legacy 账号不得被维护性更新锁死, +// 只有可能改变「可出站模型集合」或影响调度准入的更新才重验。 +func TestAccountServiceUpdateOllamaCloudPricingGateOnlyOnModelSetOrSchedulingChange(t *testing.T) { + ctx := context.Background() + + seedLegacyAccount := func(t *testing.T) (*upstreamBillingProbeAccountRepo, *AccountService, *Account) { + t.Helper() + repo := &upstreamBillingProbeAccountRepo{accounts: make(map[int64]*Account)} + svc := newOllamaGateAccountService(repo) + // legacy 形态:无 model_mapping、无 allowed_models 清单。Create 路径有门禁, + // 直接经 repo 落库模拟迁移过来的存量账号。 + account := &Account{ + Platform: PlatformOllamaCloud, + Type: AccountTypeAPIKey, + Name: "ollama-legacy", + Status: StatusActive, + Schedulable: true, + Credentials: map[string]any{"api_key": "k"}, + } + require.NoError(t, repo.Create(ctx, account)) + return repo, svc, account + } + + t.Run("legacy账号仅改name_必须成功", func(t *testing.T) { + _, svc, account := seedLegacyAccount(t) + updated, err := svc.Update(ctx, account.ID, UpdateAccountRequest{Name: strPtr("ollama-legacy-renamed")}) + require.NoError(t, err, "维护性更新(仅改 name)不得被 MODEL_PRICING_MISSING 拦截") + require.Equal(t, "ollama-legacy-renamed", updated.Name) + }) + + t.Run("legacy账号改notes与并发数_放行", func(t *testing.T) { + _, svc, account := seedLegacyAccount(t) + concurrency := 5 + updated, err := svc.Update(ctx, account.ID, UpdateAccountRequest{ + Notes: strPtr("migrated account"), + Concurrency: &concurrency, + }) + require.NoError(t, err) + require.Equal(t, "migrated account", *updated.Notes) + require.Equal(t, 5, updated.Concurrency) + }) + + t.Run("legacy账号加未定价mapping_仍400", func(t *testing.T) { + _, svc, account := seedLegacyAccount(t) + _, err := svc.Update(ctx, account.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("legacy账号加未定价清单_仍400", func(t *testing.T) { + _, svc, account := seedLegacyAccount(t) + _, err := svc.Update(ctx, account.ID, UpdateAccountRequest{ + Extra: &map[string]any{OllamaCloudAllowedModelsExtraKey: []any{"totally-unpriced-model"}}, + }) + requireModelPricingMissing(t, err, "totally-unpriced-model") + }) + + t.Run("不可调度改可调度_必须校验", func(t *testing.T) { + repo, svc, account := seedLegacyAccount(t) + // 停用态(手动开关仍开):经 Update 把 status 改回 active 即「启用」, + // 必须先通过门禁。 + repo.accounts[account.ID].Status = StatusDisabled + _, err := svc.Update(ctx, account.ID, UpdateAccountRequest{Status: strPtr(StatusActive)}) + requireModelPricingMissing(t, err) + }) + + t.Run("停用legacy账号_放行", func(t *testing.T) { + _, svc, account := seedLegacyAccount(t) + updated, err := svc.Update(ctx, account.ID, UpdateAccountRequest{Status: strPtr(StatusDisabled)}) + require.NoError(t, err, "停用(退出调度准入)属于维护性更新,不得被拦截") + require.Equal(t, StatusDisabled, updated.Status) + }) + + 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-legacy-update", + Platform: PlatformKimi, + Type: AccountTypeAPIKey, + Credentials: map[string]any{"api_key": "k"}, + }) + require.NoError(t, err) + updated, err := svc.Update(ctx, created.ID, UpdateAccountRequest{ + Name: strPtr("kimi-renamed"), + Notes: strPtr("notes only"), + }) + require.NoError(t, err, "非 ollama 平台的维护性更新行为必须保持不变") + require.Equal(t, "kimi-renamed", updated.Name) + }) +} + +// 门禁触发收窄在生产 admin handler 路径(adminServiceImpl.UpdateAccount)同样生效: +// 全对象 PUT 编辑会原样带回 credentials/extra,集合未变时不得重验锁死 legacy 账号。 +func TestAdminUpdateAccountOllamaCloudPricingGateOnlyOnModelSetOrSchedulingChange(t *testing.T) { + ctx := context.Background() + repo := &upstreamBillingProbeAccountRepo{accounts: make(map[int64]*Account)} + svc := &adminServiceImpl{accountRepo: repo, billingService: NewBillingService(&config.Config{}, nil)} + + account := &Account{ + Platform: PlatformOllamaCloud, + Type: AccountTypeAPIKey, + Name: "ollama-admin-legacy", + Status: StatusActive, + Schedulable: true, + Credentials: map[string]any{"api_key": "k"}, + } + require.NoError(t, repo.Create(ctx, account)) + + t.Run("仅改name_必须成功", func(t *testing.T) { + updated, err := svc.UpdateAccount(ctx, account.ID, &UpdateAccountInput{Name: "ollama-admin-legacy-renamed"}) + require.NoError(t, err, "admin 路径维护性更新(仅改 name)不得被拦截") + require.Equal(t, "ollama-admin-legacy-renamed", updated.Name) + }) + + t.Run("全对象PUT带回原credentials与extra_不重验放行", func(t *testing.T) { + updated, err := svc.UpdateAccount(ctx, account.ID, &UpdateAccountInput{ + Name: "ollama-admin-legacy", + Credentials: map[string]any{"api_key": "k"}, + Extra: map[string]any{"remark": "unchanged set"}, + }) + require.NoError(t, err, "可出站集合未变的全对象 PUT 不得触发门禁") + require.NotNil(t, updated) + }) + + t.Run("加未定价mapping_仍400", func(t *testing.T) { + _, err := svc.UpdateAccount(ctx, account.ID, &UpdateAccountInput{ + Credentials: map[string]any{"api_key": "k", "model_mapping": map[string]any{"alias": "totally-unpriced-model"}}, + }) + requireModelPricingMissing(t, err, "totally-unpriced-model") + }) + + t.Run("不可调度改可调度_必须校验", func(t *testing.T) { + repo.accounts[account.ID].Status = StatusDisabled + _, err := svc.UpdateAccount(ctx, account.ID, &UpdateAccountInput{Status: StatusActive}) + requireModelPricingMissing(t, err) + }) +} diff --git a/backend/internal/service/account_service.go b/backend/internal/service/account_service.go index 8524e12fa0..13e095a200 100644 --- a/backend/internal/service/account_service.go +++ b/backend/internal/service/account_service.go @@ -332,6 +332,11 @@ func (s *AccountService) Update(ctx context.Context, id int64, req UpdateAccount return nil, fmt.Errorf("get account: %w", err) } + // B2-③ 保存期无价门禁的触发判定快照:必须在应用本次请求的变更之前采集。 + prevPlatform := account.Platform + prevOutboundSet := append([]string(nil), ollamaCloudOutboundModelNames(account)...) + prevSchedulable := ollamaCloudSchedulableBySave(account) + // 更新字段 if req.Name != nil { account.Name = *req.Name @@ -387,8 +392,13 @@ 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 + // 只在可能改变可出站模型集合(platform / model_mapping / allowed_models) + // 或影响调度准入(启用)的更新上重验;name、notes、并发数、状态等维护性 + // 更新放行,避免锁死缺 mapping/清单的存量账号。 + if ollamaCloudPricingGateRevalidationNeeded(prevPlatform, prevOutboundSet, prevSchedulable, account) { + if err := validateOllamaCloudAccountModelPricingGate(s.billingService, account); err != nil { + return nil, err + } } // 执行更新 diff --git a/backend/internal/service/admin_account.go b/backend/internal/service/admin_account.go index 47ef449acb..e84bf0f385 100644 --- a/backend/internal/service/admin_account.go +++ b/backend/internal/service/admin_account.go @@ -586,6 +586,10 @@ func (s *adminServiceImpl) UpdateAccount(ctx context.Context, id int64, input *U if account.Platform == PlatformTypeSafe && input.Type != "" && input.Type != AccountTypeAPIKey { return nil, errors.New("typesafe accounts only support apikey credentials") } + // B2-③ 保存期无价门禁的触发判定快照:必须在应用本次请求的变更之前采集。 + prevPlatform := account.Platform + prevOutboundSet := append([]string(nil), ollamaCloudOutboundModelNames(account)...) + prevSchedulable := ollamaCloudSchedulableBySave(account) var normalizedExtra map[string]any if input.Extra != nil { normalizedExtra, err = normalizeOpenAILongContextBillingUpdateExtra(account, input) @@ -868,8 +872,14 @@ 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 + // 只在可能改变可出站模型集合(platform / model_mapping / allowed_models) + // 或影响调度准入(启用)的更新上重验;name、notes、并发数、状态等维护性 + // 更新放行,避免锁死缺 mapping/清单的存量账号(全对象 PUT 编辑会原样带回 + // credentials/extra,集合未变时不重验)。 + if ollamaCloudPricingGateRevalidationNeeded(prevPlatform, prevOutboundSet, prevSchedulable, account) { + if err := validateOllamaCloudAccountModelPricingGate(s.billingService, account); err != nil { + return nil, err + } } billingSettingsAppliedAtomically := false diff --git a/backend/internal/service/ollama_cloud_dynamic_catalog_pricing_test.go b/backend/internal/service/ollama_cloud_dynamic_catalog_pricing_test.go index 86ce86508c..0566ea4f06 100644 --- a/backend/internal/service/ollama_cloud_dynamic_catalog_pricing_test.go +++ b/backend/internal/service/ollama_cloud_dynamic_catalog_pricing_test.go @@ -93,3 +93,60 @@ func TestGetModelPricing_OpenAIChainUnaffectedByOllamaExclusion(t *testing.T) { }) } } + +// TestGetModelPricing_GptOssExclusionNarrowedToColonNamespace 回归护栏:gpt-oss 的 +// OpenAI 链排除只覆盖冒号命名空间(ollama 命名形态),不得误伤连字符形态。 +// +// - ollama 侧("gpt-oss:120b" / "gpt-oss:20b" / "gpt-oss:120b-cloud"):仍被排除出 +// OpenAI 回退链(PricingService 返回 nil),经 BillingService fallbackPrices 命中 +// ollama 专属价卡($0.15/$0.60 与 $0.07/$0.30 per MTok)。 +// - Antigravity 侧("gpt-oss-120b-medium",domain/constants.go 默认模型映射目标名): +// 不在排除内,恢复进 OpenAI 链的既有行为 —— 经 matchOpenAIModel 末端 catch-all +// 解析到 DefaultTestModel("gpt-5.4") 的目录卡 $2.5/$15 per MTok。收窄前该名被 +// 全局前缀排除拦下,非 Ollama 路径 fail-open 成 0 元记账。 +func TestGetModelPricing_GptOssExclusionNarrowedToColonNamespace(t *testing.T) { + bs := newTestBillingServiceWithOpenAILadderCatalog(t) + + t.Run("ollama colon names still on ollama cards", func(t *testing.T) { + tests := []struct { + model string + wantInput float64 + wantOut float64 + }{ + {"gpt-oss:120b", 0.15e-6, 0.60e-6}, + {"gpt-oss:20b", 0.07e-6, 0.30e-6}, + {"gpt-oss:120b-cloud", 0.15e-6, 0.60e-6}, + } + for _, tt := range tests { + t.Run(tt.model, func(t *testing.T) { + // 排除生效:PricingService 层对冒号形态仍返回 nil。 + require.Nil(t, bs.pricingService.GetModelPricing(tt.model), + "colon-form gpt-oss name must stay excluded from the OpenAI fallback chain") + pricing, err := bs.getModelPricingAt(tt.model, ollamaPricingAt) + require.NoError(t, err) + require.NotNil(t, pricing) + require.InDelta(t, tt.wantInput, pricing.InputPricePerToken, 1e-12, + "model %s must bill at its ollama card", tt.model) + require.InDelta(t, tt.wantOut, pricing.OutputPricePerToken, 1e-12, + "model %s must bill at its ollama card", tt.model) + }) + } + }) + + t.Run("hyphen form back on the OpenAI chain", func(t *testing.T) { + const antigravityModel = "gpt-oss-120b-medium" + // PricingService 层直接命中 OpenAI 链 catch-all 的 gpt-5.4 目录卡。 + ps := bs.pricingService.GetModelPricing(antigravityModel) + require.NotNil(t, ps, "hyphen-form name must re-enter the OpenAI fallback chain") + require.InDelta(t, 2.5e-6, ps.InputCostPerToken, 1e-12) + require.InDelta(t, 1.5e-5, ps.OutputCostPerToken, 1e-12) + + pricing, err := bs.getModelPricingAt(antigravityModel, ollamaPricingAt) + require.NoError(t, err) + require.NotNil(t, pricing) + require.InDelta(t, 2.5e-6, pricing.InputPricePerToken, 1e-12, + "antigravity hyphen-form name must resolve via the OpenAI catch-all (gpt-5.4), not fail open") + require.InDelta(t, 1.5e-5, pricing.OutputPricePerToken, 1e-12, + "antigravity hyphen-form name must resolve via the OpenAI catch-all (gpt-5.4), not fail open") + }) +} diff --git a/backend/internal/service/openai_gateway_request_body.go b/backend/internal/service/openai_gateway_request_body.go index ae57a22d04..4b1cb058d9 100644 --- a/backend/internal/service/openai_gateway_request_body.go +++ b/backend/internal/service/openai_gateway_request_body.go @@ -217,8 +217,13 @@ func (e *openAIResponsesStatelessFieldError) Error() string { // respondOpenAIStatelessFieldError 按 stripOpenAIResponsesInputNamespaces 的先例 // 把无状态端点不支持的字段应答为 400 invalid_request_error(由服务层写出响应, // handler 侧 ensureForwardErrorResponse 检测到响应已提交便不再追加 fallback)。 +// 写前 MarkResponseCommitted 与 cyber_policy / grok content 拒绝及 ollama_cloud +// 定价预检 400 同款:本 400 的错误消息("%s is not supported ...")不在 +// openAIForwardErrorAlreadyCommunicated 识别的消息前缀里,不置位的话 handler 会因 +// Writer 已写出而向 JSON body 尾部追加 SSE 终止帧,污染响应体。 func respondOpenAIStatelessFieldError(c *gin.Context, statelessErr *openAIResponsesStatelessFieldError) { setOpsUpstreamError(c, http.StatusBadRequest, statelessErr.Error(), "") + MarkResponseCommitted(c) c.JSON(http.StatusBadRequest, gin.H{"error": gin.H{ "type": "invalid_request_error", "message": statelessErr.Error(), diff --git a/backend/internal/service/openai_gateway_stateless_field_error_test.go b/backend/internal/service/openai_gateway_stateless_field_error_test.go new file mode 100644 index 0000000000..c5fe678fcf --- /dev/null +++ b/backend/internal/service/openai_gateway_stateless_field_error_test.go @@ -0,0 +1,114 @@ +//go:build unit + +package service + +// conversation 400 响应体洁净度回归。 +// +// respondOpenAIStatelessFieldError 由服务层直接写出 400 invalid_request_error,但 +// 其错误消息("conversation is not supported ...")不在 handler 侧 +// openAIForwardErrorAlreadyCommunicated 识别的两条消息前缀内:不置位 +// ResponseCommitted 的话,Forward 返回错误后 handler 走 ensureForwardErrorResponse, +// 因 Writer.Written() 已为 true 而向完整 400 JSON body 尾部追加 SSE 终止帧 +// (responses 入站追加 response.failed),body 变脏、JSON 不完整。 +// 修复:写前 MarkResponseCommitted(同 cyber_policy / grok 与 ollama_cloud 定价 +// 预检 400 的既有先例),handler 检测到响应已提交便不再追加。 + +import ( + "errors" + "net/http" + "testing" + + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" + "github.com/tidwall/sjson" +) + +func TestConversationStatelessFieldError400BodyStaysClean(t *testing.T) { + gin.SetMode(gin.TestMode) + + upstream := &httpUpstreamRecorder{err: errors.New("must not reach upstream")} + svc := &OpenAIGatewayService{cfg: rawChatCompletionsTestConfig(), httpUpstream: upstream} + // adaptive 协议 → UsesNativeCNResponses 为真,normalizeDeepSeekResponsesRequestBody 生效。 + account := adaptiveProtocolTestAccount(PlatformOllamaCloud, nil) + + body := []byte(`{"model":"gpt-oss:120b-cloud","conversation":"conv_x","input":"hi","store":true,"stream":false}`) + c, rec, ctx := pricingPreflightContext("/v1/responses", body, nil) + _, err := svc.Forward(ctx, c, account, body) + + require.Error(t, err) + require.Nil(t, upstream.lastReq, "conversation 400 必须发生在任何上游 I/O 之前") + require.Equal(t, http.StatusBadRequest, rec.Code) + + raw := rec.Body.String() + require.Equal(t, "invalid_request_error", gjson.Get(raw, "error.type").String()) + require.Contains(t, raw, "conversation is not supported") + + // body 洁净度(核心验收断言):服务层写出的 400 不得被追加任何 SSE 帧。 + require.NotContains(t, raw, "response.failed", "400 JSON body 不得被追加 response.failed SSE 帧") + require.NotContains(t, raw, "data:", "400 JSON body 不得被追加任何 SSE 帧") + require.NotContains(t, raw, "Upstream request failed", "handler fallback 错误不得混入 400 body") + require.True(t, gjson.Parse(raw).IsObject(), "400 body 必须是单个完整 JSON 对象") + + // 机制断言:响应已提交标记必须置位 —— ensureForwardErrorResponse 的第一道检查 + // 读它,置位即跳过追加 fallback(与定价预检 400 的验收口径一致)。 + require.True(t, IsResponseCommitted(c), "ResponseCommitted 必须置位,handler 才不会追加 fallback 错误") +} + +// 三入站路径覆盖:conversation 是 Responses 协议字段,只有 Responses 入站能携带。 +// CC / Messages 入站的转换分支构造全新的 Responses body(协议里不存在该字段, +// 转换不会透传未知键),因此不会触发该 400 —— 这里用真实转换路径实证,而非假定: +// 强制原生 Responses 出站后,CC / Messages 各自转换出的 outbound body 均无 +// conversation,请求正常走到上游(不存在 400 短路);Responses 入站为对照组, +// 同字段直接 400。 +func TestConversationStateless400OnlyReachableFromResponsesIngress(t *testing.T) { + gin.SetMode(gin.TestMode) + + newForcedResponsesAccount := func() *Account { + account := adaptiveProtocolTestAccount(PlatformDeepseek, nil) + account.Credentials["api_protocol"] = APIProtocolResponses + account.Credentials["base_url"] = "http://responses.example" + return account + } + + // CC / Messages 入站:conversation 被转换丢弃,请求照常出站。 + for _, tc := range cnProtocolIngressCases() { + if tc.name == "responses" { + continue + } + t.Run(tc.name, func(t *testing.T) { + upstream := &httpUpstreamRecorder{err: errors.New("stop after capture")} + svc := &OpenAIGatewayService{cfg: rawChatCompletionsTestConfig(), httpUpstream: upstream} + + // 向入站 body 硬塞 conversation(客户端异常/恶意形态)。 + body, err := sjson.SetBytes(tc.body, "conversation", "conv_x") + require.NoError(t, err) + + forwardErr := tc.forward(svc, adaptiveProtocolTestContext(tc.path, body), newForcedResponsesAccount(), body) + + // 到达上游(transport 短路错误)= 未被 conversation 400 拦截。 + var statelessErr *openAIResponsesStatelessFieldError + require.False(t, errors.As(forwardErr, &statelessErr), + "%s 入站不得触发 conversation 400", tc.name) + require.NotNil(t, upstream.lastReq, "%s 入站必须照常出站", tc.name) + require.False(t, gjson.GetBytes(upstream.lastBody, "conversation").Exists(), + "%s 入站转换出的 Responses body 不得携带 conversation 字段(即该入站永远到不了这个 400)", tc.name) + }) + } + + // Responses 入站(对照):conversation 直达 normalize,显式 400。 + t.Run("responses", func(t *testing.T) { + upstream := &httpUpstreamRecorder{err: errors.New("must not reach upstream")} + svc := &OpenAIGatewayService{cfg: rawChatCompletionsTestConfig(), httpUpstream: upstream} + + body := []byte(`{"model":"deepseek-v4.1-flash","conversation":"conv_x","input":"hi","stream":false}`) + c, rec, ctx := pricingPreflightContext("/v1/responses", body, nil) + _, err := svc.Forward(ctx, c, newForcedResponsesAccount(), body) + + var statelessErr *openAIResponsesStatelessFieldError + require.ErrorAs(t, err, &statelessErr) + require.Nil(t, upstream.lastReq) + require.Equal(t, http.StatusBadRequest, rec.Code) + require.True(t, IsResponseCommitted(c)) + }) +} diff --git a/backend/internal/service/pricing_service.go b/backend/internal/service/pricing_service.go index fe4845383e..e3938763dd 100644 --- a/backend/internal/service/pricing_service.go +++ b/backend/internal/service/pricing_service.go @@ -1216,11 +1216,13 @@ func (s *PricingService) GetModelPricing(modelName string) *LiteLLMModelPricing } // 5. OpenAI 模型回退策略 - // gpt-oss* 是开放权重模型(ollama cloud 等托管),不属于 OpenAI 模型家族: + // gpt-oss: 是开放权重模型(ollama cloud 等托管),不属于 OpenAI 模型家族: // 不进本回退链 —— 否则 matchOpenAIModel 的末端 catch-all 会把它落到 // DefaultTestModel("gpt-5.4") 的价卡($2.5/$15 per MTok)上静默误计。 // 返回 nil 交还 BillingService 走 fallbackPrices 的 ollama 专属价卡。 - if strings.HasPrefix(lookupCandidates[0], "gpt-") && !strings.HasPrefix(lookupCandidates[0], "gpt-oss") { + // 排除只收窄到 "gpt-oss:"(冒号命名空间,ollama 命名形态);连字符形态如 + // Antigravity 的 "gpt-oss-120b-medium" 不在排除内,保持进 OpenAI 链的既有行为。 + if strings.HasPrefix(lookupCandidates[0], "gpt-") && !strings.HasPrefix(lookupCandidates[0], "gpt-oss:") { return s.matchOpenAIModel(lookupCandidates[0]) } From ea8489cd41999cf3da2d5b4db46cc67f3db50f3e Mon Sep 17 00:00:00 2001 From: alfadb Date: Sun, 13 Sep 2026 05:19:02 +0800 Subject: [PATCH 22/81] fix(admin): mirror the full quota platform list in the frontend MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 后端对 default_platform_quotas(setting_update.go)与用户平台配额 (user_handler.go PUT)都是整体替换语义,且以 AllowedQuotaPlatforms (11 平台)为白名单。前端配额平台镜像此前只硬编码 5 平台 (anthropic/openai/gemini/antigravity/grok),导致: - 保存 Settings 会静默丢弃 kimi/zhipu/deepseek/minimax/opencode_go/ ollama_cloud 六个平台的默认配额; - 管理员在用户配额弹窗不做修改直接保存,就会软删该用户经 API 配置的 ollama_cloud 等平台配额行(缺行等价于不限额 → 限额 fail-open)。 - settings.ts 新增单一常量 QUOTA_PLATFORMS(对齐后端 AllowedQuotaPlatforms 全部 11 平台),PlatformType/PlatformQuotaPlatform 由它派生,删除其余 5 平台硬编码副本(users.ts、配额弹窗、 UserPlatformQuotaCell、SettingsView 两处模板字面量); - normalizePlatformQuotasMap / sanitizePlatformQuotasMap 保留输入中 前端未知(后端新加)的平台 key;用户配额弹窗保留响应中的未知平台行, 避免后端先行加平台时再次静默删数据; - 测试:用户配额弹窗预置 ollama_cloud 不修改直接保存仍包含该配额; Settings 同路径覆盖;kimi/zhipu/deepseek/minimax/opencode_go 不再 被丢;未知平台 key 保留。 --- .../settings.authSourceDefaults.spec.ts | 66 ++++++++++--- frontend/src/api/admin/settings.ts | 73 +++++++++++---- frontend/src/api/admin/users.ts | 10 +- .../admin/user/UserPlatformQuotaModal.vue | 28 +++++- .../__tests__/UserPlatformQuotaModal.spec.ts | 93 ++++++++++++++++--- .../components/user/UserPlatformQuotaCell.vue | 6 +- frontend/src/views/admin/SettingsView.vue | 5 +- .../admin/__tests__/SettingsView.spec.ts | 37 +++++++- 8 files changed, 264 insertions(+), 54 deletions(-) diff --git a/frontend/src/api/__tests__/settings.authSourceDefaults.spec.ts b/frontend/src/api/__tests__/settings.authSourceDefaults.spec.ts index deeb758250..67ae218e47 100644 --- a/frontend/src/api/__tests__/settings.authSourceDefaults.spec.ts +++ b/frontend/src/api/__tests__/settings.authSourceDefaults.spec.ts @@ -5,18 +5,15 @@ import { buildAuthSourceDefaultsState, normalizePlatformQuotasMap, sanitizePlatformQuotasMap, + QUOTA_PLATFORMS, type UpdateSettingsRequest, type DefaultPlatformQuotasMap, } from "@/api/admin/settings"; -/** 全 null 的 5 平台 map,用于断言归一化默认值 */ -const allNullQuotas: DefaultPlatformQuotasMap = { - anthropic: { daily: null, weekly: null, monthly: null }, - openai: { daily: null, weekly: null, monthly: null }, - gemini: { daily: null, weekly: null, monthly: null }, - antigravity: { daily: null, weekly: null, monthly: null }, - grok: { daily: null, weekly: null, monthly: null }, -} +/** 全 null 的全平台 map,用于断言归一化默认值 */ +const allNullQuotas: DefaultPlatformQuotasMap = Object.fromEntries( + QUOTA_PLATFORMS.map((p) => [p, { daily: null, weekly: null, monthly: null }] as const), +); describe("admin settings auth source defaults helpers", () => { it("builds auth source defaults state from flat settings fields", () => { @@ -240,14 +237,47 @@ describe("normalizePlatformQuotasMap", () => { expect(result.grok).toEqual({ daily: null, weekly: null, monthly: null }); }); - it("无参数时返回全 5 平台全 null", () => { + it("无参数时返回全平台(对齐后端 AllowedQuotaPlatforms)全 null", () => { const result = normalizePlatformQuotasMap(); - expect(Object.keys(result)).toHaveLength(5); + expect(Object.keys(result)).toHaveLength(QUOTA_PLATFORMS.length); for (const v of Object.values(result)) { expect(v).toEqual({ daily: null, weekly: null, monthly: null }); } }); + it("预置 ollama_cloud 配额在 normalize 后保留(不再被旧 5 平台列表丢弃)", () => { + const result = normalizePlatformQuotasMap({ + ollama_cloud: { daily: 3, weekly: 30, monthly: 300 }, + kimi: { daily: 1, weekly: null, monthly: null }, + zhipu: { daily: null, weekly: 2, monthly: null }, + deepseek: { daily: null, weekly: null, monthly: 4 }, + minimax: { daily: 0.5, weekly: null, monthly: null }, + opencode_go: { daily: null, weekly: null, monthly: null }, + }); + expect(result.ollama_cloud).toEqual({ daily: 3, weekly: 30, monthly: 300 }); + expect(result.kimi).toEqual({ daily: 1, weekly: null, monthly: null }); + expect(result.zhipu).toEqual({ daily: null, weekly: 2, monthly: null }); + expect(result.deepseek).toEqual({ daily: null, weekly: null, monthly: 4 }); + expect(result.minimax).toEqual({ daily: 0.5, weekly: null, monthly: null }); + expect(result.opencode_go).toEqual({ daily: null, weekly: null, monthly: null }); + }); + + it("保留未知平台 key(后端新加、前端未收录)", () => { + const result = normalizePlatformQuotasMap({ + anthropic: { daily: 5, weekly: null, monthly: null }, + some_future_platform: { daily: 7, weekly: 8, monthly: 9 }, + } as DefaultPlatformQuotasMap); + expect(result.some_future_platform).toEqual({ daily: 7, weekly: 8, monthly: 9 }); + expect(result.anthropic).toEqual({ daily: 5, weekly: null, monthly: null }); + }); + + it("未知平台的非 number 值归一化为 null", () => { + const result = normalizePlatformQuotasMap({ + some_future_platform: { daily: "50" as unknown as number, weekly: undefined as unknown as number, monthly: null }, + } as DefaultPlatformQuotasMap); + expect(result.some_future_platform).toEqual({ daily: null, weekly: null, monthly: null }); + }); + it("非 number 类型的值归一化为 null", () => { const result = normalizePlatformQuotasMap({ anthropic: { daily: "50" as unknown as number, weekly: undefined as unknown as number, monthly: null }, @@ -288,9 +318,23 @@ describe("sanitizePlatformQuotasMap", () => { expect(result.gemini?.weekly).toBe(null); }); + it("预置 ollama_cloud 配额清洗后保留(提交 payload 不再丢行)", () => { + const result = sanitizePlatformQuotasMap({ + ollama_cloud: { daily: 3, weekly: 0, monthly: null }, + }); + expect(result.ollama_cloud).toEqual({ daily: 3, weekly: 0, monthly: null }); + }); + + it("保留未知平台 key 且同样清洗其值", () => { + const result = sanitizePlatformQuotasMap({ + some_future_platform: { daily: 7, weekly: -3, monthly: "x" as unknown as number }, + } as DefaultPlatformQuotasMap); + expect(result.some_future_platform).toEqual({ daily: 7, weekly: null, monthly: null }); + }); + it("缺失平台填充为全 null", () => { const result = sanitizePlatformQuotasMap({}); - expect(Object.keys(result)).toHaveLength(5); + expect(Object.keys(result)).toHaveLength(QUOTA_PLATFORMS.length); for (const v of Object.values(result)) { expect(v).toEqual({ daily: null, weekly: null, monthly: null }); } diff --git a/frontend/src/api/admin/settings.ts b/frontend/src/api/admin/settings.ts index 3118d2e17d..701411f734 100644 --- a/frontend/src/api/admin/settings.ts +++ b/frontend/src/api/admin/settings.ts @@ -18,7 +18,27 @@ export interface DefaultSubscriptionSetting { } // ── 平台限额类型 ────────────────────────────────────────────────── -export type PlatformType = "anthropic" | "openai" | "gemini" | "antigravity" | "grok" | "typesafe" + +// 配额平台镜像:与后端 service.AllowedQuotaPlatforms 保持一致(单一权威来源: +// backend/internal/service/domain_constants.go)。后端对 default_platform_quotas +// 与用户平台配额均为整体替换语义:这份列表缺一个平台,保存时就会静默丢弃 +// 该平台的配额行(缺行等价于不限额 → 限额 fail-open)。新增平台必须同步此列表。 +export const QUOTA_PLATFORMS = [ + "anthropic", + "openai", + "gemini", + "antigravity", + "grok", + "kimi", + "zhipu", + "deepseek", + "minimax", + "opencode_go", + "typesafe", + "ollama_cloud", +] as const + +export type PlatformType = (typeof QUOTA_PLATFORMS)[number] export type QuotaWindowType = "daily" | "weekly" | "monthly" /** 单平台三档限额;null = 不限制,undefined = 未填(等价 null) */ @@ -28,10 +48,13 @@ export interface PlatformQuotaLimits { monthly: number | null } -/** 全平台默认限额 map(key = PlatformType) */ -export type DefaultPlatformQuotasMap = Partial> - -const PLATFORMS: PlatformType[] = ["anthropic", "openai", "gemini", "antigravity", "grok", "typesafe"] +/** + * 全平台默认限额 map(key = PlatformType)。 + * 可能额外含后端新加、前端尚未收录的平台 key:整体替换语义下 normalize/sanitize + * 必须原样保留这些 key,否则一次保存就会静默删除该平台的默认配额。 + */ +export type DefaultPlatformQuotasMap = Partial> & + Record export type SchedulingThresholdPlatformType = | "openai" @@ -78,27 +101,45 @@ export function sanitizeAccountSchedulingThresholdsMap( return normalizeAccountSchedulingThresholdsMap(input) } -/** 归一化为全 4 平台 × 3 窗口(缺失填 null),供模板非空绑定 */ +/** 归一化为全平台 × 3 窗口(缺失填 null),供模板非空绑定;保留输入中的未知平台 key */ export function normalizePlatformQuotasMap(input?: DefaultPlatformQuotasMap | null): DefaultPlatformQuotasMap { + const normalizeOne = (src?: PlatformQuotaLimits): PlatformQuotaLimits => ({ + daily: typeof src?.daily === "number" ? src.daily : null, + weekly: typeof src?.weekly === "number" ? src.weekly : null, + monthly: typeof src?.monthly === "number" ? src.monthly : null, + }) const result: DefaultPlatformQuotasMap = {} - for (const p of PLATFORMS) { - const src = input?.[p] - result[p] = { - daily: typeof src?.daily === "number" ? src.daily : null, - weekly: typeof src?.weekly === "number" ? src.weekly : null, - monthly: typeof src?.monthly === "number" ? src.monthly : null, + for (const p of QUOTA_PLATFORMS) { + result[p] = normalizeOne(input?.[p]) + } + // 稳健性护栏:后端新加、前端尚未收录的平台 key 原样保留(整体替换语义下 + // 丢弃 = 静默删除该平台的默认配额)。 + if (input) { + for (const [key, value] of Object.entries(input)) { + if (!(QUOTA_PLATFORMS as readonly string[]).includes(key)) { + result[key] = normalizeOne(value) + } } } return result } -/** 提交前清洗:非有限数/负数/空字符串 → null(保留 0 = 显式禁用),返回全 4 平台嵌套 map */ +/** 提交前清洗:非有限数/负数/空字符串 → null(保留 0 = 显式禁用),返回全平台嵌套 map;保留未知平台 key */ export function sanitizePlatformQuotasMap(input?: DefaultPlatformQuotasMap | null): DefaultPlatformQuotasMap { const clean = (v: unknown): number | null => (typeof v === "number" && Number.isFinite(v) && v >= 0 ? v : null) + const sanitizeOne = (src?: PlatformQuotaLimits): PlatformQuotaLimits => ({ + daily: clean(src?.daily), weekly: clean(src?.weekly), monthly: clean(src?.monthly), + }) const result: DefaultPlatformQuotasMap = {} - for (const p of PLATFORMS) { - const src = input?.[p] - result[p] = { daily: clean(src?.daily), weekly: clean(src?.weekly), monthly: clean(src?.monthly) } + for (const p of QUOTA_PLATFORMS) { + result[p] = sanitizeOne(input?.[p]) + } + if (input) { + for (const [key, value] of Object.entries(input)) { + if (!(QUOTA_PLATFORMS as readonly string[]).includes(key)) { + result[key] = sanitizeOne(value) + } + } } return result } diff --git a/frontend/src/api/admin/users.ts b/frontend/src/api/admin/users.ts index 5e2140857c..be05db89c5 100644 --- a/frontend/src/api/admin/users.ts +++ b/frontend/src/api/admin/users.ts @@ -5,6 +5,7 @@ import { apiClient } from '../client' import type { AdminUser, UpdateUserRequest, PaginatedResponse, ApiKey } from '@/types' +import type { PlatformType } from './settings' export interface AdminBindAuthIdentityChannelRequest { channel: string @@ -330,12 +331,9 @@ export async function bindUserAuthIdentity( /** * Platform quota types */ -// Keep aligned with backend/internal/service/domain_constants.go AllowedQuotaPlatforms. -export const PLATFORM_QUOTA_PLATFORMS = [ - 'anthropic', 'openai', 'gemini', 'antigravity', 'grok', - 'kimi', 'zhipu', 'deepseek', 'minimax', 'opencode_go', 'typesafe', -] as const -export type PlatformQuotaPlatform = typeof PLATFORM_QUOTA_PLATFORMS[number] +// 与后端 AllowedQuotaPlatforms 对齐;单一来源为 settings.ts 的 QUOTA_PLATFORMS +// (后端用户平台配额 PUT 是整体替换语义,前端列表缺平台 = 保存即静默删行)。 +export type PlatformQuotaPlatform = PlatformType export type PlatformQuotaWindow = 'daily' | 'weekly' | 'monthly' export interface PlatformQuotaItem { diff --git a/frontend/src/components/admin/user/UserPlatformQuotaModal.vue b/frontend/src/components/admin/user/UserPlatformQuotaModal.vue index b1c5e799db..1a7bfa00e5 100644 --- a/frontend/src/components/admin/user/UserPlatformQuotaModal.vue +++ b/frontend/src/components/admin/user/UserPlatformQuotaModal.vue @@ -119,7 +119,7 @@ import { ref, reactive, watch, computed } from 'vue' import { useI18n } from 'vue-i18n' import { useAppStore } from '@/stores/app' import { adminAPI } from '@/api/admin' -import { PLATFORM_QUOTA_PLATFORMS } from '@/api/admin/users' +import { QUOTA_PLATFORMS } from '@/api/admin/settings' import type { AdminUser, PlatformQuotaItem, PlatformQuotaPlatform, PlatformQuotaWindow } from '@/types' import BaseDialog from '@/components/common/BaseDialog.vue' @@ -129,6 +129,10 @@ const emit = defineEmits(['close', 'success']) const { t } = useI18n() const appStore = useAppStore() +// 配额平台镜像,单一来源 settings.ts 的 QUOTA_PLATFORMS(对齐后端 AllowedQuotaPlatforms)。 +// PUT /admin/users/:id/platform-quotas 是整体替换语义:列表缺平台 = 保存即静默删行。 +const PLATFORMS = QUOTA_PLATFORMS + interface QuotaRow { platform: PlatformQuotaPlatform daily_limit_usd: number | null @@ -173,9 +177,9 @@ function emptyRow(p: PlatformQuotaPlatform): QuotaRow { } function normalize(items: PlatformQuotaItem[]): QuotaRow[] { - const byPlatform = new Map() + const byPlatform = new Map() for (const it of items) byPlatform.set(it.platform, it) - return PLATFORM_QUOTA_PLATFORMS.map((p) => { + const rows = PLATFORMS.map((p) => { const it = byPlatform.get(p) if (!it) return emptyRow(p) return { @@ -188,6 +192,22 @@ function normalize(items: PlatformQuotaItem[]): QuotaRow[] { monthly_usage_usd: it.monthly_usage_usd ?? 0, } }) + // 稳健性护栏:保留响应中前端未收录(后端新加)的平台行。整体替换语义下丢弃 + // 这些行,管理员不做任何修改直接保存也会软删其配额(限额 fail-open)。 + // platform 在前端收录前以服务端返回值透传(服务端返回即其白名单成员)。 + for (const it of items) { + if (PLATFORMS.includes(it.platform)) continue + rows.push({ + platform: it.platform as PlatformQuotaPlatform, + daily_limit_usd: it.daily_limit_usd ?? null, + weekly_limit_usd: it.weekly_limit_usd ?? null, + monthly_limit_usd: it.monthly_limit_usd ?? null, + daily_usage_usd: it.daily_usage_usd ?? 0, + weekly_usage_usd: it.weekly_usage_usd ?? 0, + monthly_usage_usd: it.monthly_usage_usd ?? 0, + }) + } + return rows } function formatUsage(n: number): string { @@ -204,7 +224,7 @@ async function load() { savedConfigured.value = configuredPlatforms(data.platform_quotas || []) } catch { appStore.showError(t('admin.users.platformQuota.loadFailed')) - quotas.value = PLATFORM_QUOTA_PLATFORMS.map(emptyRow) + quotas.value = PLATFORMS.map(emptyRow) savedConfigured.value = new Set() } finally { loading.value = false diff --git a/frontend/src/components/admin/user/__tests__/UserPlatformQuotaModal.spec.ts b/frontend/src/components/admin/user/__tests__/UserPlatformQuotaModal.spec.ts index 9651153151..901efe9132 100644 --- a/frontend/src/components/admin/user/__tests__/UserPlatformQuotaModal.spec.ts +++ b/frontend/src/components/admin/user/__tests__/UserPlatformQuotaModal.spec.ts @@ -50,6 +50,7 @@ vi.mock('@/components/common/BaseDialog.vue', () => ({ })) import UserPlatformQuotaModal from '../UserPlatformQuotaModal.vue' +import { QUOTA_PLATFORMS } from '@/api/admin/settings' import type { PlatformQuotaUpdateItem, UserSubscription } from '@/types' function makeUser(overrides: { subscriptions?: UserSubscription[] } = {}) { @@ -101,19 +102,19 @@ describe('UserPlatformQuotaModal', () => { expect(apiMocks.getPlatformQuotas).toHaveBeenCalledWith(99) }) - it('renders all eleven supported platforms with empty limits', async () => { + it('空数据渲染全平台(对齐后端 AllowedQuotaPlatforms)行', async () => { const w = await mountAndOpen() + const html = w.html() + for (const p of QUOTA_PLATFORMS) { + expect(html).toContain(p) + } const rows = w.findAll('tbody tr') - expect(rows.map(row => row.find('td').text())).toEqual([ - 'anthropic', 'openai', 'gemini', 'antigravity', 'grok', - 'kimi', 'zhipu', 'deepseek', 'minimax', 'opencode_go', 'typesafe', - ]) + expect(rows.map(row => row.find('td').text())).toEqual([...QUOTA_PLATFORMS]) for (const row of rows) { const inputs = row.findAll('input[type=number]') expect(inputs).toHaveLength(3) expect(inputs.map(input => input.element.value)).toEqual(['', '', '']) } - w.unmount() }) it.each(['kimi', 'zhipu', 'deepseek', 'minimax', 'opencode_go', 'typesafe'] as const)( @@ -137,7 +138,7 @@ describe('UserPlatformQuotaModal', () => { : item) expect(apiMocks.updatePlatformQuotas).toHaveBeenCalledTimes(1) expect(apiMocks.updatePlatformQuotas).toHaveBeenCalledWith(99, expect.arrayContaining(expected)) - expect(apiMocks.updatePlatformQuotas.mock.calls[0][1]).toHaveLength(11) + expect(apiMocks.updatePlatformQuotas.mock.calls[0][1]).toHaveLength(QUOTA_PLATFORMS.length) expect(w.emitted('success')).toHaveLength(1) w.unmount() }, @@ -152,13 +153,13 @@ describe('UserPlatformQuotaModal', () => { }) const w = await mountAndOpen() const inputs = w.findAll('input[type=number]') - // 11 platforms × 3 windows = 33 inputs - expect(inputs.length).toBe(33) + // 全平台 × 3 windows = QUOTA_PLATFORMS.length × 3 inputs + expect(inputs.length).toBe(QUOTA_PLATFORMS.length * 3) // 第一个 input 是 anthropic.daily = 10 expect((inputs[0].element as HTMLInputElement).value).toBe('10') }) - it('保存提交完整 11 platform payload', async () => { + it('保存提交完整全平台 payload', async () => { apiMocks.getPlatformQuotas.mockResolvedValueOnce({ platform_quotas: [ { platform: 'openai', daily_limit_usd: null, weekly_limit_usd: 20, monthly_limit_usd: null, @@ -175,11 +176,79 @@ describe('UserPlatformQuotaModal', () => { expect(apiMocks.updatePlatformQuotas).toHaveBeenCalledTimes(1) const [uid, payload] = apiMocks.updatePlatformQuotas.mock.calls[0] expect(uid).toBe(99) - expect(payload).toHaveLength(11) // 11 platforms always submitted + expect(payload).toHaveLength(QUOTA_PLATFORMS.length) // 全平台总是提交(整体替换语义) const openai = payload.find((p: any) => p.platform === 'openai') expect(openai.weekly_limit_usd).toBe(20) }) + it('预置 ollama_cloud 配额后不做修改直接保存,payload 仍包含该配额(整体替换不丢行)', async () => { + apiMocks.getPlatformQuotas.mockResolvedValueOnce({ + platform_quotas: [ + { platform: 'ollama_cloud', daily_limit_usd: 3, weekly_limit_usd: 30, monthly_limit_usd: 300, + daily_usage_usd: 0.5, weekly_usage_usd: 2, monthly_usage_usd: 10 }, + ], + }) + const w = await mountAndOpen() + const saveBtn = w.findAll('button').find((b) => b.text() === 'admin.users.platformQuota.save') + await saveBtn!.trigger('click') + await flushPromises() + expect(apiMocks.updatePlatformQuotas).toHaveBeenCalledTimes(1) + const [, payload] = apiMocks.updatePlatformQuotas.mock.calls[0] + const ollama = payload.find((p: any) => p.platform === 'ollama_cloud') + expect(ollama).toEqual({ + platform: 'ollama_cloud', + daily_limit_usd: 3, + weekly_limit_usd: 30, + monthly_limit_usd: 300, + }) + }) + + it('kimi/zhipu/deepseek/minimax/opencode_go 预置配额保存后不丢', async () => { + apiMocks.getPlatformQuotas.mockResolvedValueOnce({ + platform_quotas: (['kimi', 'zhipu', 'deepseek', 'minimax', 'opencode_go'] as const).map((platform, i) => ({ + platform, + daily_limit_usd: i + 1, + weekly_limit_usd: null, + monthly_limit_usd: null, + daily_usage_usd: 0, + weekly_usage_usd: 0, + monthly_usage_usd: 0, + })), + }) + const w = await mountAndOpen() + const saveBtn = w.findAll('button').find((b) => b.text() === 'admin.users.platformQuota.save') + await saveBtn!.trigger('click') + await flushPromises() + const [, payload] = apiMocks.updatePlatformQuotas.mock.calls[0] + for (const platform of ['kimi', 'zhipu', 'deepseek', 'minimax', 'opencode_go']) { + const row = payload.find((p: any) => p.platform === platform) + expect(row).toBeDefined() + expect(row.daily_limit_usd).not.toBeNull() + } + }) + + it('响应中的未知平台 key 被保留并随保存提交', async () => { + apiMocks.getPlatformQuotas.mockResolvedValueOnce({ + platform_quotas: [ + { platform: 'some_future_platform', daily_limit_usd: 7, weekly_limit_usd: null, monthly_limit_usd: 9, + daily_usage_usd: 0, weekly_usage_usd: 0, monthly_usage_usd: 0 }, + ], + }) + const w = await mountAndOpen() + expect(w.html()).toContain('some_future_platform') + const saveBtn = w.findAll('button').find((b) => b.text() === 'admin.users.platformQuota.save') + await saveBtn!.trigger('click') + await flushPromises() + const [, payload] = apiMocks.updatePlatformQuotas.mock.calls[0] + const row = payload.find((p: any) => p.platform === 'some_future_platform') + expect(row).toEqual({ + platform: 'some_future_platform', + daily_limit_usd: 7, + weekly_limit_usd: null, + monthly_limit_usd: 9, + }) + }) + it('全部清空把所有 limit 置 null(确认通过)', async () => { const confirmSpy = vi.spyOn(window, 'confirm').mockReturnValue(true) apiMocks.getPlatformQuotas.mockResolvedValueOnce({ @@ -240,7 +309,7 @@ describe('UserPlatformQuotaModal', () => { it('未配置限额的平台重置按钮禁用并提示不可用', async () => { const w = await mountAndOpen() const resetBtns = w.findAll('button').filter((b) => b.text() === '↻') - expect(resetBtns.length).toBe(33) // 11 平台 × 3 窗口 + expect(resetBtns.length).toBe(QUOTA_PLATFORMS.length * 3) // 全平台 × 3 窗口 for (const b of resetBtns) { expect((b.element as HTMLButtonElement).disabled).toBe(true) expect(b.attributes('title')).toBe('admin.users.platformQuota.reset.unavailable') diff --git a/frontend/src/components/user/UserPlatformQuotaCell.vue b/frontend/src/components/user/UserPlatformQuotaCell.vue index f59d262904..e042ed5343 100644 --- a/frontend/src/components/user/UserPlatformQuotaCell.vue +++ b/frontend/src/components/user/UserPlatformQuotaCell.vue @@ -29,12 +29,14 @@ {{ p }} @@ -4390,7 +4390,7 @@ - + {{ p }} @@ -8985,6 +8985,7 @@ import { normalizePlatformQuotasMap, sanitizeAccountSchedulingThresholdsMap, sanitizePlatformQuotasMap, + QUOTA_PLATFORMS, SCHEDULING_THRESHOLD_PLATFORMS, defaultWeChatConnectScopesForMode, deriveWeChatConnectStoredMode, diff --git a/frontend/src/views/admin/__tests__/SettingsView.spec.ts b/frontend/src/views/admin/__tests__/SettingsView.spec.ts index 399088f42a..4f1ea0ec74 100644 --- a/frontend/src/views/admin/__tests__/SettingsView.spec.ts +++ b/frontend/src/views/admin/__tests__/SettingsView.spec.ts @@ -2032,7 +2032,7 @@ describe("admin SettingsView platform quota matrix", () => { expect(html).toContain("typesafe"); }); - it("保存时 updateSettings payload 应包含嵌套 default_platform_quotas 对象(含全 6 平台)", async () => { + it("保存时 updateSettings payload 应包含嵌套 default_platform_quotas 对象(含全平台)", async () => { const wrapper = mountView(); await flushPromises(); await openUsersTab(wrapper); @@ -2062,6 +2062,41 @@ describe("admin SettingsView platform quota matrix", () => { expect(payload).not.toHaveProperty("default_platform_quota_openai_weekly"); }); + it("预置 ollama_cloud/kimi 等新平台默认配额后不做修改直接保存,payload 仍包含(整体替换不丢行)", async () => { + getSettings.mockResolvedValueOnce({ + ...baseSettingsResponse, + default_platform_quotas: { + anthropic: { daily: 5, weekly: null, monthly: null }, + ollama_cloud: { daily: 3, weekly: 30, monthly: 300 }, + kimi: { daily: 1, weekly: null, monthly: null }, + zhipu: { daily: null, weekly: 2, monthly: null }, + deepseek: { daily: null, weekly: null, monthly: 4 }, + minimax: { daily: 0.5, weekly: null, monthly: null }, + opencode_go: { daily: 0.6, weekly: 6, monthly: 60 }, + }, + }); + + const wrapper = mountView(); + await flushPromises(); + await openUsersTab(wrapper); + + await wrapper.find("form").trigger("submit.prevent"); + await flushPromises(); + + const payload = updateSettings.mock.calls.at(-1)![0] as Record; + const quotas = payload["default_platform_quotas"] as Record>; + + // 整体替换语义下,这些平台配额行必须原样出现在提交 payload 中 + expect(quotas["ollama_cloud"]).toEqual({ daily: 3, weekly: 30, monthly: 300 }); + expect(quotas["kimi"]).toEqual({ daily: 1, weekly: null, monthly: null }); + expect(quotas["zhipu"]).toEqual({ daily: null, weekly: 2, monthly: null }); + expect(quotas["deepseek"]).toEqual({ daily: null, weekly: null, monthly: 4 }); + expect(quotas["minimax"]).toEqual({ daily: 0.5, weekly: null, monthly: null }); + expect(quotas["opencode_go"]).toEqual({ daily: 0.6, weekly: 6, monthly: 60 }); + // 已知平台不受影响 + expect(quotas["anthropic"]).toEqual({ daily: 5, weekly: null, monthly: null }); + }); + it("加载后 form.default_platform_quotas 含全 6 平台,从嵌套 JSON 正确读取数值", async () => { getSettings.mockResolvedValueOnce({ ...baseSettingsResponse, From 6b9eb0a651cb47c034050fcd038a5bd0c82f7e1e Mon Sep 17 00:00:00 2001 From: alfadb Date: Sun, 13 Sep 2026 05:38:31 +0800 Subject: [PATCH 23/81] fix(ollama): validate the ollama cloud pricing gate on all account write paths MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 评审确认三条 admin 写路径绕过保存期无价门禁 (validateOllamaCloudAccountModelPricingGate),本修复把同一门禁与同一触发 收窄判定复用到这三条路径,不另写判定规则: - BulkUpdateAccounts:对每个受影响的 ollama_cloud 账号,按仓库 BulkUpdate 的实际生效方式(credentials/extra JSONB 顶层 key 合并、status/schedulable 列覆盖)先算出「变更后的账号」再校验;任一账号不合规即整批拒绝、不落库, 错误信息点名账号 ID/名称与未定价模型名,便于批量操作定位。 - DuplicateAccount:用「将要创建的账号」(深拷贝后的最终 credentials/extra) 校验,不合规拒绝;复制产物保持暂停语义不变。 - SetAccountSchedulable:只在启用方向(当前不满足 active+Schedulable → true) 且账号是 ollama_cloud 时校验,判定复用 ollamaCloudSchedulableBySave;停用 放行。 定位说明:运行时模型白名单(IsModelSupported)与转发前定价预检已经落地, 即使绕过保存期门禁也不会再产生「成功但不计费」的流量(最坏是账号 deny-all 或对客户端返 400)。因此这是「门禁不可绕过」的一致性与运维反馈修复,不是 计费漏损修复。 非 ollama 平台行为不变:门禁短路 + 触发收窄(维护性更新放行)均有回归测试 覆盖(bulk 改名/停用、kimi 平台的同样操作全部放行)。 --- .../account_ollama_cloud_pricing_gate_test.go | 279 ++++++++++++++++++ backend/internal/service/admin_account.go | 78 ++++- 2 files changed, 355 insertions(+), 2 deletions(-) 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 1e53ff3cdf..bd0eee2acc 100644 --- a/backend/internal/service/account_ollama_cloud_pricing_gate_test.go +++ b/backend/internal/service/account_ollama_cloud_pricing_gate_test.go @@ -392,3 +392,282 @@ func TestAdminUpdateAccountOllamaCloudPricingGateOnlyOnModelSetOrSchedulingChang requireModelPricingMissing(t, err) }) } + +// ───────────────────────────────────────────────────────────────────────────── +// 评审收口回归:三条此前绕过门禁的 admin 写路径(BulkUpdateAccounts / +// DuplicateAccount / SetAccountSchedulable)。定位是「门禁不可绕过」的一致性—— +// 运行时白名单与转发前定价预检已兜底最坏情形,本组测试锁的是保存期拦截行为 +// 本身:不合规整批拒绝且不落库、错误点名账号、维护性更新与非 ollama 平台放行。 +// ───────────────────────────────────────────────────────────────────────────── + +// ollamaGateSchedulableCall 记录一次 SetSchedulable 调用,用于断言「拒绝时未触达 DB」。 +type ollamaGateSchedulableCall struct { + accountID int64 + schedulable bool +} + +// ollamaGateAdminRepoStub 在 upstreamBillingProbeAccountRepo 之上补齐本组回归所需的 +// 两个写入口:SetSchedulable(记录调用)与 CreateWithAccountGroups(复制路径的原子创建)。 +type ollamaGateAdminRepoStub struct { + *upstreamBillingProbeAccountRepo + schedulableCalls []ollamaGateSchedulableCall +} + +func newOllamaGateAdminRepoStub() *ollamaGateAdminRepoStub { + return &ollamaGateAdminRepoStub{ + upstreamBillingProbeAccountRepo: &upstreamBillingProbeAccountRepo{accounts: make(map[int64]*Account)}, + } +} + +func (r *ollamaGateAdminRepoStub) SetSchedulable(_ context.Context, id int64, schedulable bool) error { + r.mu.Lock() + defer r.mu.Unlock() + if account := r.accounts[id]; account != nil { + account.Schedulable = schedulable + } + r.schedulableCalls = append(r.schedulableCalls, ollamaGateSchedulableCall{accountID: id, schedulable: schedulable}) + return nil +} + +func (r *ollamaGateAdminRepoStub) CreateWithAccountGroups(ctx context.Context, account *Account, _ []AccountGroup) error { + return r.Create(ctx, account) +} + +// seedOllamaGateAccount 直接经 repo 落库一个账号(绕过 Create 路径门禁), +// 用于模拟「门禁上线前迁移过来的存量账号」。 +func seedOllamaGateAccount(t *testing.T, repo *ollamaGateAdminRepoStub, mutate func(*Account)) *Account { + t.Helper() + account := &Account{ + Platform: PlatformOllamaCloud, + Type: AccountTypeAPIKey, + Name: "ollama-gate-seed", + Status: StatusActive, + Schedulable: false, + Credentials: map[string]any{"api_key": "k"}, + } + if mutate != nil { + mutate(account) + } + require.NoError(t, repo.Create(context.Background(), account)) + return account +} + +func TestAdminBulkUpdateAccountsOllamaCloudPricingGate(t *testing.T) { + ctx := context.Background() + newSvc := func(t *testing.T) (*ollamaGateAdminRepoStub, *adminServiceImpl) { + t.Helper() + repo := newOllamaGateAdminRepoStub() + svc := &adminServiceImpl{accountRepo: repo, billingService: NewBillingService(&config.Config{}, nil)} + return repo, svc + } + + t.Run("bulk写入未定价mapping_整批拒绝点名账号且不落库", func(t *testing.T) { + repo, svc := newSvc(t) + first := seedOllamaGateAccount(t, repo, func(a *Account) { a.Name = "ollama-bulk-a" }) + second := seedOllamaGateAccount(t, repo, func(a *Account) { + a.Name = "ollama-bulk-b" + a.Extra = map[string]any{OllamaCloudAllowedModelsExtraKey: []any{"gpt-oss:120b-cloud"}} + }) + _, err := svc.BulkUpdateAccounts(ctx, &BulkUpdateAccountsInput{ + AccountIDs: []int64{first.ID, second.ID}, + Credentials: map[string]any{"api_key": "k", "model_mapping": map[string]any{"alias": "totally-unpriced-model"}}, + }) + requireModelPricingMissing(t, err, "totally-unpriced-model") + // 批量操作要能定位:错误信息必须点名每个不合规账号。 + require.Contains(t, infraerrors.Message(err), first.Name) + require.Contains(t, infraerrors.Message(err), second.Name) + // 整批拒绝:任何账号都不得写入。 + require.Empty(t, repo.bulkUpdates, "被拒绝的批量更新不得触达 DB") + }) + + t.Run("bulk写入已定价mapping_通过", func(t *testing.T) { + repo, svc := newSvc(t) + account := seedOllamaGateAccount(t, repo, nil) + _, err := svc.BulkUpdateAccounts(ctx, &BulkUpdateAccountsInput{ + AccountIDs: []int64{account.ID}, + Credentials: map[string]any{"api_key": "k", "model_mapping": map[string]any{"big": "gpt-oss:120b"}}, + }) + require.NoError(t, err) + require.Len(t, repo.bulkUpdates, 1) + }) + + t.Run("bulk启用legacy无配置账号_拒绝且不落库", func(t *testing.T) { + repo, svc := newSvc(t) + first := seedOllamaGateAccount(t, repo, func(a *Account) { a.Name = "ollama-bulk-legacy-a" }) + second := seedOllamaGateAccount(t, repo, func(a *Account) { a.Name = "ollama-bulk-legacy-b" }) + _, err := svc.BulkUpdateAccounts(ctx, &BulkUpdateAccountsInput{ + AccountIDs: []int64{first.ID, second.ID}, + Schedulable: boolPtr(true), + }) + requireModelPricingMissing(t, err) + require.Contains(t, infraerrors.Message(err), first.Name) + require.Contains(t, infraerrors.Message(err), second.Name) + require.Empty(t, repo.bulkUpdates) + }) + + t.Run("bulk停用_放行", func(t *testing.T) { + repo, svc := newSvc(t) + account := seedOllamaGateAccount(t, repo, func(a *Account) { + a.Name = "ollama-bulk-disable" + a.Schedulable = true + }) + _, err := svc.BulkUpdateAccounts(ctx, &BulkUpdateAccountsInput{ + AccountIDs: []int64{account.ID}, + Schedulable: boolPtr(false), + }) + require.NoError(t, err, "停用(退出调度准入)属于维护性更新,不得被拦截") + require.Len(t, repo.bulkUpdates, 1) + }) + + t.Run("bulk仅改name_legacy账号放行", func(t *testing.T) { + repo, svc := newSvc(t) + account := seedOllamaGateAccount(t, repo, func(a *Account) { a.Name = "ollama-bulk-legacy" }) + _, err := svc.BulkUpdateAccounts(ctx, &BulkUpdateAccountsInput{ + AccountIDs: []int64{account.ID}, + Name: "ollama-bulk-legacy-renamed", + }) + require.NoError(t, err, "维护性更新(仅改 name)不得被 MODEL_PRICING_MISSING 锁死") + require.Len(t, repo.bulkUpdates, 1) + }) + + t.Run("非ollama平台bulk不受影响_回归", func(t *testing.T) { + repo, svc := newSvc(t) + account := seedOllamaGateAccount(t, repo, func(a *Account) { + a.Name = "kimi-bulk" + a.Platform = PlatformKimi + a.Schedulable = false + }) + _, err := svc.BulkUpdateAccounts(ctx, &BulkUpdateAccountsInput{ + AccountIDs: []int64{account.ID}, + Credentials: map[string]any{ + "api_key": "k", + "model_mapping": map[string]any{"k2": "totally-unpriced-model"}, + }, + Schedulable: boolPtr(true), + }) + require.NoError(t, err, "非 ollama 平台的批量更新行为必须保持不变") + require.Len(t, repo.bulkUpdates, 1) + }) +} + +func TestAdminDuplicateAccountOllamaCloudPricingGate(t *testing.T) { + ctx := context.Background() + newSvc := func(t *testing.T) (*ollamaGateAdminRepoStub, *adminServiceImpl) { + t.Helper() + repo := newOllamaGateAdminRepoStub() + svc := &adminServiceImpl{accountRepo: repo, accountDuplicateRepo: repo, billingService: NewBillingService(&config.Config{}, nil)} + return repo, svc + } + + t.Run("复制不合规账号_拒绝且不落库", func(t *testing.T) { + repo, svc := newSvc(t) + source := seedOllamaGateAccount(t, repo, func(a *Account) { + a.Name = "ollama-dup-bad" + a.Credentials = map[string]any{"api_key": "k", "model_mapping": map[string]any{"alias": "totally-unpriced-model"}} + }) + _, err := svc.DuplicateAccount(ctx, source.ID, "", "") + requireModelPricingMissing(t, err, "totally-unpriced-model") + require.Len(t, repo.accounts, 1, "被拒绝的复制不得落库") + }) + + t.Run("复制无配置legacy账号_拒绝", func(t *testing.T) { + repo, svc := newSvc(t) + source := seedOllamaGateAccount(t, repo, func(a *Account) { a.Name = "ollama-dup-legacy" }) + _, err := svc.DuplicateAccount(ctx, source.ID, "", "") + requireModelPricingMissing(t, err) + require.Len(t, repo.accounts, 1) + }) + + t.Run("复制已配置清单账号_通过且保持暂停", func(t *testing.T) { + repo, svc := newSvc(t) + source := seedOllamaGateAccount(t, repo, func(a *Account) { + a.Name = "ollama-dup-good" + a.Extra = map[string]any{OllamaCloudAllowedModelsExtraKey: []any{"gpt-oss:120b-cloud"}} + }) + duplicate, err := svc.DuplicateAccount(ctx, source.ID, "", "") + require.NoError(t, err) + require.NotNil(t, duplicate) + require.Len(t, repo.accounts, 2) + require.False(t, duplicate.Schedulable, "复制产物必须保持暂停,等人工复核后再启用") + }) + + t.Run("非ollama平台复制不受影响_回归", func(t *testing.T) { + repo, svc := newSvc(t) + source := seedOllamaGateAccount(t, repo, func(a *Account) { + a.Name = "kimi-dup" + a.Platform = PlatformKimi + a.Credentials = map[string]any{"api_key": "k", "model_mapping": map[string]any{"k2": "totally-unpriced-model"}} + }) + duplicate, err := svc.DuplicateAccount(ctx, source.ID, "", "") + require.NoError(t, err, "非 ollama 平台的复制行为必须保持不变") + require.NotNil(t, duplicate) + require.Len(t, repo.accounts, 2) + }) +} + +func TestAdminSetAccountSchedulableOllamaCloudPricingGate(t *testing.T) { + ctx := context.Background() + newSvc := func(t *testing.T) (*ollamaGateAdminRepoStub, *adminServiceImpl) { + t.Helper() + repo := newOllamaGateAdminRepoStub() + svc := &adminServiceImpl{accountRepo: repo, billingService: NewBillingService(&config.Config{}, nil)} + return repo, svc + } + + t.Run("启用无配置legacy账号_拒绝且不落库", func(t *testing.T) { + repo, svc := newSvc(t) + account := seedOllamaGateAccount(t, repo, func(a *Account) { a.Name = "ollama-enable-legacy" }) + _, err := svc.SetAccountSchedulable(ctx, account.ID, true) + requireModelPricingMissing(t, err) + require.Empty(t, repo.schedulableCalls, "被拒绝的启用不得触达 DB") + }) + + t.Run("停用_放行", func(t *testing.T) { + repo, svc := newSvc(t) + account := seedOllamaGateAccount(t, repo, func(a *Account) { + a.Name = "ollama-disable" + a.Schedulable = true + }) + updated, err := svc.SetAccountSchedulable(ctx, account.ID, false) + require.NoError(t, err, "停用(true→false)属于维护性操作,不得被拦截") + require.NotNil(t, updated) + require.Len(t, repo.schedulableCalls, 1) + require.False(t, repo.schedulableCalls[0].schedulable) + }) + + t.Run("启用未定价mapping账号_拒绝", func(t *testing.T) { + repo, svc := newSvc(t) + account := seedOllamaGateAccount(t, repo, func(a *Account) { + a.Name = "ollama-enable-unpriced" + a.Credentials = map[string]any{"api_key": "k", "model_mapping": map[string]any{"alias": "totally-unpriced-model"}} + }) + _, err := svc.SetAccountSchedulable(ctx, account.ID, true) + requireModelPricingMissing(t, err, "totally-unpriced-model") + require.Empty(t, repo.schedulableCalls) + }) + + t.Run("启用已定价账号_通过", func(t *testing.T) { + repo, svc := newSvc(t) + account := seedOllamaGateAccount(t, repo, func(a *Account) { + a.Name = "ollama-enable-priced" + a.Extra = map[string]any{OllamaCloudAllowedModelsExtraKey: []any{"gpt-oss:120b-cloud"}} + }) + updated, err := svc.SetAccountSchedulable(ctx, account.ID, true) + require.NoError(t, err) + require.NotNil(t, updated) + require.Len(t, repo.schedulableCalls, 1) + }) + + t.Run("非ollama平台启用不受影响_回归", func(t *testing.T) { + repo, svc := newSvc(t) + account := seedOllamaGateAccount(t, repo, func(a *Account) { + a.Name = "kimi-enable" + a.Platform = PlatformKimi + a.Credentials = map[string]any{"api_key": "k", "model_mapping": map[string]any{"k2": "totally-unpriced-model"}} + }) + updated, err := svc.SetAccountSchedulable(ctx, account.ID, true) + require.NoError(t, err, "非 ollama 平台的手动启用行为必须保持不变") + require.NotNil(t, updated) + require.Len(t, repo.schedulableCalls, 1) + }) +} diff --git a/backend/internal/service/admin_account.go b/backend/internal/service/admin_account.go index e84bf0f385..4dd0f24827 100644 --- a/backend/internal/service/admin_account.go +++ b/backend/internal/service/admin_account.go @@ -332,6 +332,12 @@ func (s *adminServiceImpl) DuplicateAccount(ctx context.Context, id int64, actor } // A copied credential must be reviewed before it can share live traffic with its source. duplicate.Schedulable = false + // B2-③ 保存期无价门禁:复制是创建路径的变体,产物与手工创建同样必须过门禁 + // (评审收口)——否则不合规的存量账号可以被无限复制放大。用「将要创建的账号」 + // 校验,credentials/extra 此时已是深拷贝后的最终形态。 + if err := validateOllamaCloudAccountModelPricingGate(s.billingService, duplicate); err != nil { + return nil, err + } if s.accountDuplicateRepo == nil { return nil, errors.New("account duplicate repository is not configured") } @@ -1019,9 +1025,11 @@ func (s *adminServiceImpl) BulkUpdateAccounts(ctx context.Context, input *BulkUp needMixedChannelCheck := input.GroupIDs != nil && !input.SkipMixedChannelCheck - // 预取所有目标账号,供凭据守卫/代理守卫/混合渠道检查共用,避免多次 DB 查询。 + // 预取所有目标账号,供凭据守卫/代理守卫/混合渠道检查/ollama_cloud 保存期门禁共用, + // 避免多次 DB 查询。ollama_cloud 门禁需要读到「变更后状态」(credentials/extra 合并、 + // status/schedulable 切换),所以携带这些输入时也必须预取。 var cachedTargets []*Account - if len(input.Credentials) > 0 || input.ProxyID != nil || needMixedChannelCheck || openAISettings.any() || input.ProbeEnabled != nil || input.RateMultiplier != nil { + if len(input.Credentials) > 0 || input.ProxyID != nil || needMixedChannelCheck || openAISettings.any() || input.ProbeEnabled != nil || input.RateMultiplier != nil || input.Schedulable != nil || input.Status != "" || len(input.Extra) > 0 { loaded, err := s.accountRepo.GetByIDs(ctx, input.AccountIDs) if err != nil { return nil, err @@ -1187,6 +1195,15 @@ func (s *adminServiceImpl) BulkUpdateAccounts(ctx context.Context, input *BulkUp repoUpdates.Schedulable = input.Schedulable } + // B2-③ 保存期无价门禁:批量路径同样不可绕过(评审收口)。先按仓库的同款合并 + // 语义(JSONB 顶层 key 合并 + 列覆盖)算出每个受影响 ollama_cloud 账号「本次 + // 请求生效后的状态」,再复用与单账号 UpdateAccount 相同的门禁与触发收窄判定。 + // 任何账号不合规即整批拒绝、不落库,错误信息点名账号与未定价模型,便于批量 + // 操作定位。 + if err := s.validateOllamaCloudPricingGateForBulkUpdate(input.AccountIDs, targetsByID, repoUpdates); err != nil { + return nil, err + } + // Run bulk update for column/jsonb fields first. if _, err := s.accountRepo.BulkUpdate(ctx, input.AccountIDs, repoUpdates); err != nil { return nil, err @@ -1229,6 +1246,48 @@ func (s *adminServiceImpl) BulkUpdateAccounts(ctx context.Context, input *BulkUp return result, nil } +// validateOllamaCloudPricingGateForBulkUpdate 把保存期无价门禁应用到批量更新: +// 对每个受影响的 ollama_cloud 账号,先把 AccountBulkUpdate 按仓库 BulkUpdate 的 +// 实际生效方式模拟到「变更后的账号」上(credentials/extra 顶层 key 合并,status/ +// schedulable 列覆盖),再复用 ollamaCloudPricingGateRevalidationNeeded + 门禁本体, +// 与单账号 UpdateAccount 保持同一判定,不另写一份规则。命中不合规时收集全部 +// 违规项,由调用方整批拒绝(不产生任何写入)。 +func (s *adminServiceImpl) validateOllamaCloudPricingGateForBulkUpdate(accountIDs []int64, targetsByID map[int64]*Account, updates AccountBulkUpdate) error { + var failures []string + for _, id := range accountIDs { + current, ok := targetsByID[id] + if !ok || !current.IsOllamaCloud() { + continue + } + next := *current + next.Credentials = mergeMap(nil, current.Credentials) + for key, value := range updates.Credentials { + next.Credentials[key] = value + } + next.Extra = mergeMap(nil, current.Extra) + for key, value := range updates.Extra { + next.Extra[key] = value + } + if updates.Status != nil { + next.Status = *updates.Status + } + if updates.Schedulable != nil { + next.Schedulable = *updates.Schedulable + } + if !ollamaCloudPricingGateRevalidationNeeded(current.Platform, ollamaCloudOutboundModelNames(current), ollamaCloudSchedulableBySave(current), &next) { + continue + } + if err := validateOllamaCloudAccountModelPricingGate(s.billingService, &next); err != nil { + failures = append(failures, fmt.Sprintf("#%d(%s): %s", id, current.Name, infraerrors.Message(err))) + } + } + if len(failures) == 0 { + return nil + } + return infraerrors.BadRequest("MODEL_PRICING_MISSING", + fmt.Sprintf("批量更新被 ollama_cloud 保存期门禁拒绝,整批未写入(不合规账号: %s)", strings.Join(failures, "; "))) +} + func updatesUpstreamBillingProbeIdentity(credentials map[string]any) bool { for _, key := range []string{"api_key", "base_url", credKeyHeaderOverrideEnabled, credKeyHeaderOverrides} { if _, ok := credentials[key]; ok { @@ -1356,6 +1415,21 @@ func (s *adminServiceImpl) SetAccountError(ctx context.Context, id int64, errorM } func (s *adminServiceImpl) SetAccountSchedulable(ctx context.Context, id int64, schedulable bool) (*Account, error) { + // B2-③ 保存期无价门禁:手动启用调度(false→true)与保存路径的「启用」是同一 + // 调度准入开关,ollama_cloud 账号必须先过门禁,否则存量不合规账号可被一键放量 + // (评审收口)。判定复用 ollamaCloudSchedulableBySave(active + Schedulable), + // 与单账号 Update 的启用语义一致;停用(true→false)属维护性操作,放行不校验。 + if schedulable { + account, err := s.accountRepo.GetByID(ctx, id) + if err != nil { + return nil, err + } + if account.IsOllamaCloud() && !ollamaCloudSchedulableBySave(account) { + if err := validateOllamaCloudAccountModelPricingGate(s.billingService, account); err != nil { + return nil, err + } + } + } if err := s.accountRepo.SetSchedulable(ctx, id, schedulable); err != nil { return nil, err } From 96223b157fc68303b05a93804ded473455ba7208 Mon Sep 17 00:00:00 2001 From: alfadb Date: Sun, 13 Sep 2026 05:48:47 +0800 Subject: [PATCH 24/81] fix(ollama): stop swallowing protocol marker persist errors MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 探针的协议 marker 后台落标(国产供应商 / ollama_cloud 分支)此前用 _ = UpdateExtra(...) 把错误完全吞掉:协议更新可以「成功」而旧的 force_responses / auto marker 静默残留,且与函数注释「所有错误都会记录 日志」直接矛盾。现改为结构化 slog 告警(openai_responses_probe_marker_ persist_failed,含 account_id / account_name / platform / responses_mode / err),两个落标分支(force_responses 与重置 auto)都覆盖。 为什么只做可观测性、不引入原子保存/改路由权威(第 2 层评估结论): 实读路由决策后确认,ollama_cloud 的请求路由以 credentials.api_protocol 为权威,探针 marker 不是权威输入—— - shouldForwardOpenAIResponsesViaRawChatCompletions 的 IsOllamaCloud() 分支只读 GetAPIProtocol(),在 ShouldUseResponsesAPI(Extra) 之前返回; - 调度能力过滤只在请求平台归一为 openai 时才要求 responses 能力 (ollama_cloud 归一化后保持原值),marker 不会被用于排除 ollama 账号; - CC→Responses 的 404/405 兜底分支要求 marker 解析为 unknown,残留值 解析为 yes/no,不会触发误兜底。 因此残留 marker 对 ollama_cloud 生产路由不构成错投,原子保存的额外复杂度 不值得引入;新增测试锁住「落标失败必须产生可观测信号」(对旧代码该测试 失败:无任何日志输出)。 --- .../service/openai_apikey_responses_probe.go | 26 +++++++-- .../openai_apikey_responses_probe_test.go | 57 +++++++++++++++++++ 2 files changed, 79 insertions(+), 4 deletions(-) diff --git a/backend/internal/service/openai_apikey_responses_probe.go b/backend/internal/service/openai_apikey_responses_probe.go index 0dffa97089..a2e1ee135d 100644 --- a/backend/internal/service/openai_apikey_responses_probe.go +++ b/backend/internal/service/openai_apikey_responses_probe.go @@ -143,17 +143,35 @@ func (s *AccountTestService) ProbeOpenAIAPIKeyResponsesSupport(ctx context.Conte // (/v1/responses,non-stateful),adaptive / responses 协议直接落标 // force_responses,无需网络探测(探测的 2xx/404 判定对它无意义); // 显式 chat_completions 锁 CC,重置为 auto 防残留强制模式。 + // 落标失败必须结构化告警(openai_responses_probe_marker_persist_failed): + // 静默吞掉会让旧 marker 残留且无任何可观测信号,与运维预期相悖。 if account.UsesNativeCNResponses() { - _ = s.accountRepo.UpdateExtra(ctx, account.ID, map[string]any{ + if err := s.accountRepo.UpdateExtra(ctx, account.ID, map[string]any{ openai_compat.ExtraKeyResponsesMode: string(openai_compat.ResponsesSupportModeForceResponses), openai_compat.ExtraKeyResponsesSupported: true, - }) + }); err != nil { + slog.Warn("openai_responses_probe_marker_persist_failed", + "account_id", account.ID, + "account_name", account.Name, + "platform", account.Platform, + "responses_mode", string(openai_compat.ResponsesSupportModeForceResponses), + "err", err, + ) + } return } - _ = s.accountRepo.UpdateExtra(ctx, account.ID, map[string]any{ + if err := s.accountRepo.UpdateExtra(ctx, account.ID, map[string]any{ openai_compat.ExtraKeyResponsesMode: string(openai_compat.ResponsesSupportModeAuto), openai_compat.ExtraKeyResponsesSupported: false, - }) + }); err != nil { + slog.Warn("openai_responses_probe_marker_persist_failed", + "account_id", account.ID, + "account_name", account.Name, + "platform", account.Platform, + "responses_mode", string(openai_compat.ResponsesSupportModeAuto), + "err", err, + ) + } return } if account.Platform != PlatformOpenAI { diff --git a/backend/internal/service/openai_apikey_responses_probe_test.go b/backend/internal/service/openai_apikey_responses_probe_test.go index 0c33fd6df5..e89d4bdfe7 100644 --- a/backend/internal/service/openai_apikey_responses_probe_test.go +++ b/backend/internal/service/openai_apikey_responses_probe_test.go @@ -1,8 +1,11 @@ package service import ( + "bytes" "context" + "errors" "io" + "log/slog" "net/http" "strings" "testing" @@ -137,6 +140,60 @@ func TestProbeOpenAIAPIKeyResponsesSupportOllamaCloud(t *testing.T) { } } +// failingMarkerRepo 使协议 marker 落标(UpdateExtra)返回错误,用于断言失败会产生 +// 可观测信号。 +type failingMarkerRepo struct { + stubOpenAIAccountRepo + err error +} + +func (r *failingMarkerRepo) UpdateExtra(_ context.Context, _ int64, _ map[string]any) error { + return r.err +} + +// TestProbeOpenAIAPIKeyResponsesSupportMarkerPersistFailureLogsWarning 评审证伪回归: +// 协议 marker 落标失败必须有可观测信号。此前 _ = UpdateExtra 把错误完全吞掉—— +// 协议更新「成功」而旧 force_responses / auto marker 静默残留,且没有任何日志。 +// 注意:ollama_cloud / CN 的请求路由以 credentials.api_protocol 为权威(探针 Extra +// 不得带偏协议决策),因此本修复锁的是可观测性,不是路由正确性。 +func TestProbeOpenAIAPIKeyResponsesSupportMarkerPersistFailureLogsWarning(t *testing.T) { + for _, tc := range []struct { + name string + protocol string + }{ + {name: "force_responses落标失败_告警", protocol: APIProtocolAdaptive}, + {name: "重置auto落标失败_告警", protocol: APIProtocolChatCompletions}, + } { + t.Run(tc.name, func(t *testing.T) { + var logs bytes.Buffer + previousLogger := slog.Default() + slog.SetDefault(slog.New(slog.NewTextHandler(&logs, nil))) + defer slog.SetDefault(previousLogger) + + account := Account{ + ID: 231, + Platform: PlatformOllamaCloud, + Type: AccountTypeAPIKey, + Name: "ollama-marker-fail", + Credentials: map[string]any{"api_key": "sk-test", "api_protocol": tc.protocol}, + } + repo := &failingMarkerRepo{ + stubOpenAIAccountRepo: stubOpenAIAccountRepo{accounts: []Account{account}}, + err: errors.New("db write failed"), + } + svc := &AccountTestService{accountRepo: repo} + + svc.ProbeOpenAIAPIKeyResponsesSupport(context.Background(), account.ID) + + output := logs.String() + require.Contains(t, output, "openai_responses_probe_marker_persist_failed", + "UpdateExtra 失败必须产生结构化告警") + require.Contains(t, output, "account_id=231") + require.Contains(t, output, "db write failed") + }) + } +} + func TestDecideResponsesProbeSupport(t *testing.T) { fnCall := []byte(`{"output":[{"type":"reasoning"},{"type":"function_call","name":"probe_ping"}]}`) reasoningOnly := []byte(`{"output":[{"type":"reasoning"}]}`) From ae2e4385896a7e3a98d82ffecbf43c69d060916a Mon Sep 17 00:00:00 2001 From: alfadb Date: Sun, 13 Sep 2026 06:34:04 +0800 Subject: [PATCH 25/81] test(contract): refresh settings goldens and fix ollama conversation null handling - api_contract_test: default_platform_quotas goldens now include ollama_cloud (actual settings response is correct; goldens were stale) - api_contract_test: stubAccountRepo.GetByIDs returns the bulk-update fixture accounts (101/102) required by the BulkUpdateAccounts prefetch - openai_gateway: conversation gate rejects only non-null values (gjson Type != Null); conversation: null is treated as an omitted field and forwarded, with a Forward-layer regression test covering both paths - ollama_cloud pricing gate: message now states the global base pricing requirement and that channel/group-only pricing is not accepted; doc comment records the deliberate stricter-than-runtime design limitation --- backend/internal/server/api_contract_test.go | 20 +++++++-- .../account_ollama_cloud_pricing_gate.go | 10 ++++- .../openai_gateway_conversation_guard_test.go | 42 +++++++++++++++++++ .../service/openai_gateway_request_body.go | 14 ++++--- 4 files changed, 76 insertions(+), 10 deletions(-) diff --git a/backend/internal/server/api_contract_test.go b/backend/internal/server/api_contract_test.go index b2d2633964..9a9f8771c2 100644 --- a/backend/internal/server/api_contract_test.go +++ b/backend/internal/server/api_contract_test.go @@ -863,7 +863,7 @@ func TestAPIContracts(t *testing.T) { "force_email_on_third_party_signup": false, "default_concurrency": 5, "default_balance": 1.25, - "default_platform_quotas": {"anthropic":{"daily":null,"weekly":null,"monthly":null},"antigravity":{"daily":null,"weekly":null,"monthly":null},"deepseek":{"daily":null,"weekly":null,"monthly":null},"gemini":{"daily":null,"weekly":null,"monthly":null},"grok":{"daily":null,"weekly":null,"monthly":null},"kimi":{"daily":null,"weekly":null,"monthly":null},"minimax":{"daily":null,"weekly":null,"monthly":null},"openai":{"daily":null,"weekly":null,"monthly":null},"opencode_go":{"daily":null,"weekly":null,"monthly":null},"typesafe":{"daily":null,"weekly":null,"monthly":null},"zhipu":{"daily":null,"weekly":null,"monthly":null}}, + "default_platform_quotas": {"anthropic":{"daily":null,"weekly":null,"monthly":null},"antigravity":{"daily":null,"weekly":null,"monthly":null},"deepseek":{"daily":null,"weekly":null,"monthly":null},"gemini":{"daily":null,"weekly":null,"monthly":null},"grok":{"daily":null,"weekly":null,"monthly":null},"kimi":{"daily":null,"weekly":null,"monthly":null},"minimax":{"daily":null,"weekly":null,"monthly":null},"ollama_cloud":{"daily":null,"weekly":null,"monthly":null},"openai":{"daily":null,"weekly":null,"monthly":null},"opencode_go":{"daily":null,"weekly":null,"monthly":null},"typesafe":{"daily":null,"weekly":null,"monthly":null},"zhipu":{"daily":null,"weekly":null,"monthly":null}}, "auth_source_default_email_platform_quotas": null, "auth_source_default_github_platform_quotas": null, "auth_source_default_google_platform_quotas": null, @@ -1189,7 +1189,7 @@ func TestAPIContracts(t *testing.T) { "purchase_subscription_url": "", "table_default_page_size": 20, "table_page_size_options": [10, 20, 50], - "default_platform_quotas": {"anthropic":{"daily":null,"weekly":null,"monthly":null},"antigravity":{"daily":null,"weekly":null,"monthly":null},"deepseek":{"daily":null,"weekly":null,"monthly":null},"gemini":{"daily":null,"weekly":null,"monthly":null},"grok":{"daily":null,"weekly":null,"monthly":null},"kimi":{"daily":null,"weekly":null,"monthly":null},"minimax":{"daily":null,"weekly":null,"monthly":null},"openai":{"daily":null,"weekly":null,"monthly":null},"opencode_go":{"daily":null,"weekly":null,"monthly":null},"typesafe":{"daily":null,"weekly":null,"monthly":null},"zhipu":{"daily":null,"weekly":null,"monthly":null}}, + "default_platform_quotas": {"anthropic":{"daily":null,"weekly":null,"monthly":null},"antigravity":{"daily":null,"weekly":null,"monthly":null},"deepseek":{"daily":null,"weekly":null,"monthly":null},"gemini":{"daily":null,"weekly":null,"monthly":null},"grok":{"daily":null,"weekly":null,"monthly":null},"kimi":{"daily":null,"weekly":null,"monthly":null},"minimax":{"daily":null,"weekly":null,"monthly":null},"ollama_cloud":{"daily":null,"weekly":null,"monthly":null},"openai":{"daily":null,"weekly":null,"monthly":null},"opencode_go":{"daily":null,"weekly":null,"monthly":null},"typesafe":{"daily":null,"weekly":null,"monthly":null},"zhipu":{"daily":null,"weekly":null,"monthly":null}}, "auth_source_default_email_platform_quotas": null, "auth_source_default_github_platform_quotas": null, "auth_source_default_google_platform_quotas": null, @@ -1468,7 +1468,12 @@ func newContractDeps(t *testing.T) *contractDeps { apiKeyCache := stubApiKeyCache{} groupRepo := &stubGroupRepo{} userSubRepo := &stubUserSubscriptionRepo{} - accountRepo := stubAccountRepo{} + accountRepo := stubAccountRepo{ + accounts: map[int64]*service.Account{ + 101: {ID: 101, Name: "bulk-anthropic-1", Platform: service.PlatformAnthropic, Status: service.StatusActive, Schedulable: true}, + 102: {ID: 102, Name: "bulk-anthropic-2", Platform: service.PlatformAnthropic, Status: service.StatusActive, Schedulable: true}, + }, + } proxyRepo := stubProxyRepo{} redeemRepo := &stubRedeemCodeRepo{} @@ -1868,6 +1873,7 @@ func (stubGroupRepo) CreateFromSource(ctx context.Context, group *service.Group, type stubAccountRepo struct { bulkUpdateIDs []int64 + accounts map[int64]*service.Account } func (s *stubAccountRepo) Create(ctx context.Context, account *service.Account) error { @@ -1883,7 +1889,13 @@ func (s *stubAccountRepo) GetByID(ctx context.Context, id int64) (*service.Accou } func (s *stubAccountRepo) GetByIDs(ctx context.Context, ids []int64) ([]*service.Account, error) { - return nil, errors.New("not implemented") + out := make([]*service.Account, 0, len(ids)) + for _, id := range ids { + if account, ok := s.accounts[id]; ok { + out = append(out, account) + } + } + return out, nil } func (s *stubAccountRepo) ExistsByID(ctx context.Context, id int64) (bool, error) { diff --git a/backend/internal/service/account_ollama_cloud_pricing_gate.go b/backend/internal/service/account_ollama_cloud_pricing_gate.go index 48dd5b6e50..5a81b87935 100644 --- a/backend/internal/service/account_ollama_cloud_pricing_gate.go +++ b/backend/internal/service/account_ollama_cloud_pricing_gate.go @@ -37,6 +37,14 @@ type accountModelPricingLookup interface { // openai_gateway_usage.go 的 pricing_missing_record_zero_cost 分支)。 // lookup 为 nil 时跳过(生产 wire 必然注入 *BillingService;仅直接构造 // struct 的单元测试/内部调用会出现)。 +// +// 与请求期转发前预检的刻意不对称(设计限制,非缺陷):请求期预检走完整定价 +// 解析链(Group → Channel → LiteLLM → fallback),「只有渠道价/分组价」的模型 +// 运行时允许出站;本门禁只查全局基础价(GetModelPricing,LiteLLM → fallback), +// 因此仅在渠道/分组层配置定价的模型会在保存时被 MODEL_PRICING_MISSING 拒绝。 +// 这是刻意比运行时更严格的策略:账号与分组是多对多,保存时拿不到确定的 +// channel/group 上下文,「门禁查渠道价」在语义上不成立;而 ollama 的真实模型 +// 全部有全局基础价,实践中不会误拒。 func validateOllamaCloudAccountModelPricingGate(lookup accountModelPricingLookup, account *Account) error { if lookup == nil || account == nil || !account.IsOllamaCloud() { return nil @@ -57,7 +65,7 @@ func validateOllamaCloudAccountModelPricingGate(lookup accountModelPricingLookup } if len(unpriced) > 0 { return infraerrors.BadRequest("MODEL_PRICING_MISSING", - fmt.Sprintf("以下 ollama_cloud 模型缺少定价,无法保证计费(请先补价或调整 model_mapping/%s): %s", + fmt.Sprintf("以下 ollama_cloud 模型缺少全局基础定价,无法保证计费。此校验要求每个可出站模型都有全局基础价(LiteLLM 或内置 fallback),仅在渠道/分组层配置的定价不会被接受:请先在全局模型定价中补价,或调整 model_mapping/extra.%s。缺价模型: %s", OllamaCloudAllowedModelsExtraKey, strings.Join(unpriced, ", "))) } return nil diff --git a/backend/internal/service/openai_gateway_conversation_guard_test.go b/backend/internal/service/openai_gateway_conversation_guard_test.go index c9daa49bb4..6e7bc9e9fa 100644 --- a/backend/internal/service/openai_gateway_conversation_guard_test.go +++ b/backend/internal/service/openai_gateway_conversation_guard_test.go @@ -81,3 +81,45 @@ func TestForwardConversationFieldRejectedWithBadRequest(t *testing.T) { require.False(t, gjson.GetBytes(upstream.lastBody, "store").Bool()) }) } + +// TestForwardConversationNullTreatedAsStateless 是 conversation 门禁的兼容性回归: +// gjson 的 Exists() 对 JSON null 也返回 true,若据此判定会把「客户端把可选字段 +// 序列化成 null」这一常见形态误拒为 400。conversation: null 语义上与省略字段 +// 等价,必须按无会话依赖正常出站;非 null 值仍 400 且不出站(对照,门禁对 +// 显式会话依赖的拒绝语义不放松)。 +func TestForwardConversationNullTreatedAsStateless(t *testing.T) { + gin.SetMode(gin.TestMode) + + t.Run("conversation null is forwarded like an omitted field", func(t *testing.T) { + upstream := &httpUpstreamRecorder{err: errors.New("stop after capture")} + svc := &OpenAIGatewayService{cfg: rawChatCompletionsTestConfig(), httpUpstream: upstream} + account := adaptiveProtocolTestAccount(PlatformOllamaCloud, nil) + + body := []byte(`{"model":"gpt-oss:120b-cloud","conversation":null,"input":"full standalone input","stream":false}`) + recorder := newConversationGuardRecorder("/v1/responses", body) + _, err := svc.Forward(context.Background(), recorder.c, account, body) + require.Error(t, err) + var statelessErr *openAIResponsesStatelessFieldError + require.NotErrorAs(t, err, &statelessErr, "conversation:null 不得触发无状态字段 400") + require.NotNil(t, upstream.lastReq, "conversation:null 必须正常出站") + require.Equal(t, "https://ollama.com/v1/responses", upstream.lastReq.URL.String()) + require.False(t, gjson.GetBytes(upstream.lastBody, "store").Bool()) + require.NotEqual(t, http.StatusBadRequest, recorder.rec.Code, "client-visible 状态码不得是 400") + }) + + t.Run("non-null conversation still gets 400 and no upstream call", func(t *testing.T) { + upstream := &httpUpstreamRecorder{err: errors.New("must not reach upstream")} + svc := &OpenAIGatewayService{cfg: rawChatCompletionsTestConfig(), httpUpstream: upstream} + account := adaptiveProtocolTestAccount(PlatformOllamaCloud, nil) + + body := []byte(`{"model":"gpt-oss:120b-cloud","conversation":"conv_x","input":"hi","stream":false}`) + recorder := newConversationGuardRecorder("/v1/responses", body) + _, err := svc.Forward(context.Background(), recorder.c, account, body) + require.Error(t, err) + var statelessErr *openAIResponsesStatelessFieldError + require.ErrorAs(t, err, &statelessErr) + require.Nil(t, upstream.lastReq, "非 null conversation 请求不得出站") + require.Equal(t, http.StatusBadRequest, recorder.rec.Code, "client-visible 状态码必须是 400") + require.Contains(t, gjson.Get(recorder.rec.Body.String(), "error.type").String(), "invalid_request_error") + }) +} diff --git a/backend/internal/service/openai_gateway_request_body.go b/backend/internal/service/openai_gateway_request_body.go index 4b1cb058d9..0ab3074c72 100644 --- a/backend/internal/service/openai_gateway_request_body.go +++ b/backend/internal/service/openai_gateway_request_body.go @@ -137,12 +137,16 @@ func deleteOpenAIResponsesNoneReasoningEffortFromObject(account *Account, body m // 账号同样走这条出站改写(Codex 贴图会 422 missing field url)。 // 非 CN / 非 DeepSeek 上游原样返回。 // -// 请求体携带 conversation 时返回 *openAIResponsesStatelessFieldError 且不改写 -// body:一律 400 是产品选择——显式失败优于静默丢上下文——不是该用法不存在。 -// 依赖 conversation 的客户端把历史存在服务端、通常不重发 input,静默剥离等于 -// 静默丢上下文(回答质量下降且零错误信号)。已知代价是 conversation + 完整 +// 请求体携带非 null 的 conversation 时返回 *openAIResponsesStatelessFieldError +// 且不改写 body:一律 400 是产品选择——显式失败优于静默丢上下文——不是该用法 +// 不存在。依赖 conversation 的客户端把历史存在服务端、通常不重发 input,静默剥离 +// 等于静默丢上下文(回答质量下降且零错误信号)。已知代价是 conversation + 完整 // input 的 non-stream 用法被误伤;出现真实此类客户端时按平台/账号开关显式 // 放行,不得回退静默剥离。 +// +// 判定用 Type != gjson.Null 而非 Exists():gjson 对 JSON null 也返回 +// Exists()==true(Raw 非空),而 conversation: null 语义上与「省略该字段」等价 +// (很多客户端会把可选字段序列化成 null),必须按无会话依赖正常出站。 func normalizeDeepSeekResponsesRequestBody(account *Account, body []byte) ([]byte, error) { if account == nil { return body, nil @@ -152,7 +156,7 @@ func normalizeDeepSeekResponsesRequestBody(account *Account, body []byte) ([]byt if !applyStateless && !applyImages { return body, nil } - if applyStateless && gjson.GetBytes(body, "conversation").Exists() { + if applyStateless && gjson.GetBytes(body, "conversation").Type != gjson.Null { return body, &openAIResponsesStatelessFieldError{field: "conversation"} } From 7590ada360124a9c0b2152c6595859c41c5bf63e Mon Sep 17 00:00:00 2001 From: alfadb Date: Sun, 13 Sep 2026 07:31:34 +0800 Subject: [PATCH 26/81] feat(monitor): support ollama_cloud in channel monitors and account diagnostics Increment 5-2a of the ollama_cloud plan (backend half): - M-1: accept provider=ollama_cloud for channel monitors (create/update binding oneof) and request templates (create binding oneof, historical short list intentionally not extended to the CN platforms); add the service-side monitorProviders/probeCapableProviders entries, an OpenAI- compatible chat adapter and merge-mode denylist entry; replace-mode body validation intentionally stays lenient (opencode_go precedent). - C36: route ollama_cloud accounts in TestAccountConnection to protocol- aware probes (adaptive = CC + Anthropic + native Responses; pinned protocols = single endpoint) instead of the Claude tester that appended ?beta=true; default the empty model to the account's first outbound model; share the native Responses probe with opencode_go; resolve the platform-default Anthropic base for pinned-anthropic accounts. - C29: quota-mode monitors read the OllamaCloudUsageService snapshot from account extra (no live fetch) and map windows/balance/plan to MonitorQuotaSnapshot; ineligible accounts (e.g. reverse-proxy base_url) and missing/failed snapshots yield explainable errors with the snapshot fetched_at instead of the generic usage-query error. - C28: verified no change needed - monitorAccountQuotaCapability already allows ollama_cloud via its default branch. - Pin the composite default-model candidate list: ollama_cloud explicitly contributes no static default list (admin_group.go), aligning with gateway_handler. --- .../handler/admin/channel_monitor_handler.go | 4 +- .../admin/channel_monitor_template_handler.go | 6 +- backend/internal/service/account.go | 5 + .../internal/service/account_test_service.go | 48 +++- .../account_test_service_ollama_cloud_test.go | 132 ++++++++++ backend/internal/service/admin_group.go | 6 + .../service/channel_monitor_checker.go | 9 + .../internal/service/channel_monitor_const.go | 5 +- .../channel_monitor_ollama_cloud_test.go | 243 ++++++++++++++++++ .../service/channel_monitor_quota_fetcher.go | 116 +++++++++ .../service/channel_monitor_template_types.go | 2 +- .../service/channel_monitor_validate.go | 3 + 12 files changed, 571 insertions(+), 8 deletions(-) create mode 100644 backend/internal/service/account_test_service_ollama_cloud_test.go create mode 100644 backend/internal/service/channel_monitor_ollama_cloud_test.go diff --git a/backend/internal/handler/admin/channel_monitor_handler.go b/backend/internal/handler/admin/channel_monitor_handler.go index 3cb8d4c1d5..9854e65355 100644 --- a/backend/internal/handler/admin/channel_monitor_handler.go +++ b/backend/internal/handler/admin/channel_monitor_handler.go @@ -40,7 +40,7 @@ func NewChannelMonitorHandler(monitorService *service.ChannelMonitorService) *Ch type channelMonitorCreateRequest struct { Name string `json:"name" binding:"required,max=100"` - Provider string `json:"provider" binding:"required,oneof=openai anthropic gemini grok antigravity kimi zhipu deepseek minimax opencode_go"` + Provider string `json:"provider" binding:"required,oneof=openai anthropic gemini grok antigravity kimi zhipu deepseek minimax opencode_go ollama_cloud"` APIMode string `json:"api_mode" binding:"omitempty,oneof=chat_completions responses"` Endpoint string `json:"endpoint" binding:"omitempty,max=500"` APIKey string `json:"api_key" binding:"omitempty,max=2000"` @@ -64,7 +64,7 @@ type channelMonitorCreateRequest struct { type channelMonitorUpdateRequest struct { Name *string `json:"name" binding:"omitempty,max=100"` - Provider *string `json:"provider" binding:"omitempty,oneof=openai anthropic gemini grok antigravity kimi zhipu deepseek minimax opencode_go"` + Provider *string `json:"provider" binding:"omitempty,oneof=openai anthropic gemini grok antigravity kimi zhipu deepseek minimax opencode_go ollama_cloud"` APIMode *string `json:"api_mode" binding:"omitempty,oneof=chat_completions responses"` Endpoint *string `json:"endpoint" binding:"omitempty,max=500"` APIKey *string `json:"api_key" binding:"omitempty,max=2000"` diff --git a/backend/internal/handler/admin/channel_monitor_template_handler.go b/backend/internal/handler/admin/channel_monitor_template_handler.go index 497e3d195b..e820a57db0 100644 --- a/backend/internal/handler/admin/channel_monitor_template_handler.go +++ b/backend/internal/handler/admin/channel_monitor_template_handler.go @@ -25,8 +25,10 @@ func NewChannelMonitorRequestTemplateHandler(templateService *service.ChannelMon // --- DTO --- type channelMonitorTemplateCreateRequest struct { - Name string `json:"name" binding:"required,max=100"` - Provider string `json:"provider" binding:"required,oneof=openai anthropic gemini grok"` + Name string `json:"name" binding:"required,max=100"` + // Provider 为历史短列表:CN 5 平台缺失属历史债(本批不扩),仅补 ollama_cloud + // 与监控/模板的 service 层放行对齐。模板按 provider 与监控匹配(应用时校验一致)。 + Provider string `json:"provider" binding:"required,oneof=openai anthropic gemini grok ollama_cloud"` APIMode string `json:"api_mode" binding:"omitempty,oneof=chat_completions responses"` Description string `json:"description" binding:"max=500"` ExtraHeaders map[string]string `json:"extra_headers"` diff --git a/backend/internal/service/account.go b/backend/internal/service/account.go index 151647fdca..7ba8b76d0b 100644 --- a/backend/internal/service/account.go +++ b/backend/internal/service/account.go @@ -1652,6 +1652,11 @@ func (a *Account) GetAnthropicProtocolBaseURL() string { return DefaultMiniMaxAnthropicBaseURL case PlatformOpenCodeGo: return a.openCodeDefaultAnthropicBaseURL() + case PlatformOllamaCloud: + // 与 adaptive 分支(defaultCNProtocolBaseURL)同源:官方 Anthropic + // 兼容端点不带 /v1 前缀。缺失时 pinned-anthropic 的 ollama_cloud 账号 + // 会拿到空 base,转发与连接测试都报「no anthropic protocol base url」。 + return DefaultOllamaCloudAnthropicBaseURL default: return "" } diff --git a/backend/internal/service/account_test_service.go b/backend/internal/service/account_test_service.go index 3b84bd2690..2830dfa452 100644 --- a/backend/internal/service/account_test_service.go +++ b/backend/internal/service/account_test_service.go @@ -422,6 +422,10 @@ func (s *AccountTestService) TestAccountConnection(c *gin.Context, accountID int return s.testTypeSafeAccountConnection(c, account, prompt) } + if account.IsOllamaCloud() { + return s.testOllamaCloudAccountConnection(c, account, modelID, prompt) + } + return s.testClaudeAccountConnection(c, account, modelID) } @@ -451,13 +455,16 @@ func (s *AccountTestService) testOpenCodeGoAccountConnection(c *gin.Context, acc case APIProtocolAnthropic: return s.testCNProviderAnthropicConnection(c, account, testModelID) case APIProtocolResponses: - return s.testOpenCodeGoResponsesConnection(c, account, testModelID) + return s.testNativeResponsesConnection(c, account, testModelID) default: return s.testCNProviderChatCompletionsConnection(c, account, testModelID, prompt) } } -func (s *AccountTestService) testOpenCodeGoResponsesConnection(c *gin.Context, account *Account, testModelID string) error { +// testNativeResponsesConnection probes a multi-protocol API-key account's +// native Responses endpoint (the same probe the adaptive path uses, including +// the stateless body normalization). Shared by OpenCode Go and Ollama Cloud. +func (s *AccountTestService) testNativeResponsesConnection(c *gin.Context, account *Account, testModelID string) error { authToken := strings.TrimSpace(account.GetOpenAIProtocolAPIKey()) if authToken == "" { return s.sendErrorAndEnd(c, "No API key available") @@ -471,6 +478,43 @@ func (s *AccountTestService) testOpenCodeGoResponsesConnection(c *gin.Context, a return s.testCNProviderAdaptiveResponsesConnection(c, account, testModelID, authToken) } +// testOllamaCloudAccountConnection probes an Ollama Cloud account's native +// endpoints per GetAPIProtocol. Falling through to the generic Claude tester +// sent Claude Code payloads to {base}/v1/messages?beta=true, so ollama accounts +// always failed the connection test regardless of account health. Adaptive +// (the default protocol for ollama_cloud) probes Chat Completions + Anthropic +// + native Responses in sequence; a pinned protocol probes that single endpoint. +func (s *AccountTestService) testOllamaCloudAccountConnection(c *gin.Context, account *Account, modelID string, prompt string) error { + testModelID := strings.TrimSpace(modelID) + if testModelID == "" { + // 无静态目录:默认探测账号自身的第一个可出站模型(保存期门禁保证 + // mapping 或 allowed_models 至少其一非空)。 + testModelID = defaultOllamaCloudTestModel(account) + } + switch account.GetAPIProtocol() { + case APIProtocolAdaptive: + // 复用 CN adaptive 三端点探针:base_url 解析、Anthropic Bearer 头与 + // Responses 无状态归一化均已按 ollama_cloud 适配。 + return s.testCNProviderAdaptiveConnection(c, account, testModelID, prompt) + case APIProtocolAnthropic: + return s.testCNProviderAnthropicConnection(c, account, testModelID) + case APIProtocolResponses: + return s.testNativeResponsesConnection(c, account, testModelID) + default: + return s.testCNProviderChatCompletionsConnection(c, account, testModelID, prompt) + } +} + +// defaultOllamaCloudTestModel 返回 ollama_cloud 账号连接测试的默认模型: +// model_mapping 目标优先,其次 extra.allowed_models 首项;两者皆空时退回 +// OpenAI 测试模型(仅出现在未过保存期门禁的账号上,由上游报错暴露)。 +func defaultOllamaCloudTestModel(account *Account) string { + if models := ollamaCloudOutboundModelNames(account); len(models) > 0 { + return models[0] + } + return openai.DefaultTestModel +} + func (s *AccountTestService) testCNProviderChatCompletionsConnection(c *gin.Context, account *Account, modelID string, prompt string) error { testModelID := strings.TrimSpace(modelID) if testModelID == "" { diff --git a/backend/internal/service/account_test_service_ollama_cloud_test.go b/backend/internal/service/account_test_service_ollama_cloud_test.go new file mode 100644 index 0000000000..da56d2dd76 --- /dev/null +++ b/backend/internal/service/account_test_service_ollama_cloud_test.go @@ -0,0 +1,132 @@ +//go:build unit + +package service + +import ( + "strings" + "testing" + + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" +) + +// ollamaCloudTestAccount 构造官方默认 base_url(credentials 不带 base_url)的 +// ollama_cloud 账号,让测试同时钉住「正确回落平台默认端点」这件事。 +func ollamaCloudTestAccount(id int64, credentials map[string]any) *Account { + base := map[string]any{ + "api_key": "sk-ollama-test", + } + for key, value := range credentials { + base[key] = value + } + return &Account{ + ID: id, + Name: "ollama-cloud-test", + Platform: PlatformOllamaCloud, + Type: AccountTypeAPIKey, + Status: StatusActive, + Concurrency: 1, + Credentials: base, + Extra: map[string]any{ + OllamaCloudAllowedModelsExtraKey: []any{"gpt-oss:120b-cloud"}, + }, + } +} + +// C36 核心验收:adaptive(ollama_cloud 默认协议)账号依次探测 CC → Anthropic → +// Responses 三个原生端点,URL 正确、无 ?beta=true,不再落入 Claude 测试路径。 +func TestAccountTestService_OllamaCloudAdaptiveProbesAllThreeEndpoints(t *testing.T) { + account := ollamaCloudTestAccount(501, map[string]any{"api_protocol": APIProtocolAdaptive}) + svc, upstream := adaptiveCNAccountTestService( + account, + adaptiveCNChatTestResponse(), + adaptiveCNAnthropicTestResponse(), + adaptiveCNResponsesTestResponse(), + ) + c, recorder := newTestContext() + + err := svc.TestAccountConnection(c, account.ID, "gpt-oss:120b-cloud", "hi", AccountTestModeDefault) + + require.NoError(t, err) + require.Len(t, upstream.requests, 3) + require.Equal(t, "https://ollama.com/v1/chat/completions", upstream.requests[0].URL.String()) + require.Equal(t, "https://ollama.com/v1/messages", upstream.requests[1].URL.String()) + require.Equal(t, "https://ollama.com/v1/responses", upstream.requests[2].URL.String()) + for i, req := range upstream.requests { + require.Empty(t, req.URL.RawQuery, "request %d must not carry the Claude tester ?beta=true suffix", i) + } + // ollama 官方 host 的 Anthropic 端点强制 Bearer(非 CN 的 x-api-key)。 + require.Equal(t, "Bearer sk-ollama-test", upstream.requests[1].Header.Get("Authorization")) + require.Empty(t, upstream.requests[1].Header.Get("x-api-key")) + // Responses 探针按无状态端点归一化:store=false。 + require.False(t, gjson.GetBytes(upstream.bodies[2], "store").Bool()) + + require.Equal(t, 1, strings.Count(recorder.Body.String(), `"type":"test_start"`)) + require.Equal(t, 1, strings.Count(recorder.Body.String(), `"type":"test_complete"`)) + require.Contains(t, recorder.Body.String(), "已通过原生 /responses 验证") +} + +// 空模型默认取账号 allowed_models 首项(保存期门禁保证非空清单存在)。 +func TestAccountTestService_OllamaCloudEmptyModelDefaultsToAllowedModels(t *testing.T) { + account := ollamaCloudTestAccount(502, map[string]any{"api_protocol": APIProtocolChatCompletions}) + svc, upstream := adaptiveCNAccountTestService(account, adaptiveCNChatTestResponse()) + c, recorder := newTestContext() + + err := svc.TestAccountConnection(c, account.ID, "", "hi", AccountTestModeDefault) + + require.NoError(t, err) + require.Len(t, upstream.requests, 1) + require.Equal(t, "gpt-oss:120b-cloud", gjson.GetBytes(upstream.lastBody, "model").String()) + require.Contains(t, recorder.Body.String(), "gpt-oss:120b-cloud") +} + +// 钉 chat_completions:单端点探测,不触发 Anthropic/Responses。 +func TestAccountTestService_OllamaCloudPinnedChatProtocol(t *testing.T) { + account := ollamaCloudTestAccount(503, map[string]any{"api_protocol": APIProtocolChatCompletions}) + svc, upstream := adaptiveCNAccountTestService(account, adaptiveCNChatTestResponse()) + c, recorder := newTestContext() + + err := svc.TestAccountConnection(c, account.ID, "gpt-oss:120b-cloud", "hi", AccountTestModeDefault) + + require.NoError(t, err) + require.Len(t, upstream.requests, 1) + require.Equal(t, "https://ollama.com/v1/chat/completions", upstream.requests[0].URL.String()) + require.Equal(t, "Bearer sk-ollama-test", upstream.requests[0].Header.Get("Authorization")) + require.NotContains(t, upstream.requests[0].URL.Path, "/messages") + require.Contains(t, recorder.Body.String(), `"type":"test_complete"`) +} + +// 钉 anthropic:官方默认 Anthropic base(https://ollama.com)+ /v1/messages, +// 无 ?beta=true,Bearer 鉴权。 +func TestAccountTestService_OllamaCloudPinnedAnthropicProtocol(t *testing.T) { + account := ollamaCloudTestAccount(504, map[string]any{"api_protocol": APIProtocolAnthropic}) + svc, upstream := adaptiveCNAccountTestService(account, adaptiveCNAnthropicTestResponse()) + c, recorder := newTestContext() + + err := svc.TestAccountConnection(c, account.ID, "", "", AccountTestModeDefault) + + require.NoError(t, err) + require.Len(t, upstream.requests, 1) + req := upstream.requests[0] + require.Equal(t, "https://ollama.com/v1/messages", req.URL.String()) + 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"`) +} + +// 钉 responses:单端点 /v1/responses + 无状态归一化(store=false)。 +func TestAccountTestService_OllamaCloudPinnedResponsesProtocol(t *testing.T) { + account := ollamaCloudTestAccount(505, map[string]any{"api_protocol": APIProtocolResponses}) + svc, upstream := adaptiveCNAccountTestService(account, adaptiveCNResponsesTestResponse()) + c, recorder := newTestContext() + + err := svc.TestAccountConnection(c, account.ID, "gpt-oss:120b-cloud", "", AccountTestModeDefault) + + require.NoError(t, err) + require.Len(t, upstream.requests, 1) + req := upstream.requests[0] + require.Equal(t, "https://ollama.com/v1/responses", req.URL.String()) + require.Equal(t, HTTPUpstreamProfileOpenAI, HTTPUpstreamProfileFromContext(req.Context())) + require.False(t, gjson.GetBytes(upstream.lastBody, "store").Bool()) + require.Contains(t, recorder.Body.String(), `"type":"test_complete"`) +} diff --git a/backend/internal/service/admin_group.go b/backend/internal/service/admin_group.go index 103c9edc25..909c08bfce 100644 --- a/backend/internal/service/admin_group.go +++ b/backend/internal/service/admin_group.go @@ -299,6 +299,12 @@ func defaultModelsListCandidateIDs(platform string) []string { return DefaultOpenCodeGoModelIDs() case PlatformTypeSafe: return []string{typesafe.JevLatestModel} + case PlatformOllamaCloud: + // ollama_cloud 没有静态默认模型列表:可服务模型完全来自账号侧的 + // model_mapping / extra.allowed_models(缺失时 IsModelSupported 为 + // deny-all)。default 分支的 Claude 列表对它只会造成虚假广告; + // 显式返回空,与 gateway_handler.defaultModelIDsForPlatform 对齐。 + return nil case PlatformComposite: return compositeDefaultModelsListCandidateIDs() default: diff --git a/backend/internal/service/channel_monitor_checker.go b/backend/internal/service/channel_monitor_checker.go index ddb5e78317..fceef2434a 100644 --- a/backend/internal/service/channel_monitor_checker.go +++ b/backend/internal/service/channel_monitor_checker.go @@ -176,6 +176,10 @@ var providerAdapters = map[string]providerAdapter{ MonitorProviderZhipu: providerZhipuChatAdapter, MonitorProviderDeepseek: providerDeepseekChatAdapter, MonitorProviderMiniMax: providerMiniMaxChatAdapter, + // ollama_cloud:官方 OpenAI 兼容 Chat Completions(/v1/chat/completions), + // 与国产 3 家同构;api_mode 仍只支持 chat_completions(responses 探活 + // 仅 openai,见 validateAPIMode)。 + MonitorProviderOllamaCloud: providerOllamaCloudChatAdapter, MonitorProviderAnthropic: { buildPath: func(string) string { return providerAnthropicPath }, buildBody: func(model, prompt string) ([]byte, error) { @@ -230,6 +234,9 @@ var providerDeepseekChatAdapter = newOpenAICompatibleChatAdapter(providerOpenAIP //nolint:gochecknoglobals // 适配器表是只读静态数据,初始化后不变更。 var providerMiniMaxChatAdapter = newOpenAICompatibleChatAdapter(providerOpenAIPath) +//nolint:gochecknoglobals // 适配器表是只读静态数据,初始化后不变更。 +var providerOllamaCloudChatAdapter = newOpenAICompatibleChatAdapter(providerOpenAIPath) + func newOpenAICompatibleChatAdapter(path string) providerAdapter { return providerAdapter{ buildPath: func(string) string { return path }, @@ -463,6 +470,8 @@ var bodyMergeKeyDenyList = map[string]map[string]bool{ MonitorProviderZhipu: {"model": true, "messages": true, "stream": true}, MonitorProviderDeepseek: {"model": true, "messages": true, "stream": true}, MonitorProviderMiniMax: {"model": true, "messages": true, "stream": true}, + // ollama_cloud 同为 OpenAI Chat Completions 同构。 + MonitorProviderOllamaCloud: {"model": true, "messages": true, "stream": true}, } func checkAPIMode(opts *CheckOptions) string { diff --git a/backend/internal/service/channel_monitor_const.go b/backend/internal/service/channel_monitor_const.go index 447581ddb2..36af368e98 100644 --- a/backend/internal/service/channel_monitor_const.go +++ b/backend/internal/service/channel_monitor_const.go @@ -70,6 +70,9 @@ const ( MonitorProviderZhipu = "zhipu" MonitorProviderDeepseek = "deepseek" MonitorProviderMiniMax = "minimax" + // MonitorProviderOllamaCloud:官方提供 OpenAI 兼容 /v1/chat/completions, + // 探活复用通用 OpenAI 兼容 adapter(与国产 3 家同构)。 + MonitorProviderOllamaCloud = "ollama_cloud" // MonitorCheckMode 检测模式(channel_monitors.check_mode)。 // probe - LLM 探活(默认,原有行为) @@ -152,7 +155,7 @@ var ( "CHANNEL_MONITOR_NOT_FOUND", "channel monitor not found", ) ErrChannelMonitorInvalidProvider = infraerrors.BadRequest( - "CHANNEL_MONITOR_INVALID_PROVIDER", "provider must be one of openai/anthropic/gemini/grok/antigravity/kimi/zhipu/deepseek/minimax", + "CHANNEL_MONITOR_INVALID_PROVIDER", "provider must be one of openai/anthropic/gemini/grok/antigravity/kimi/zhipu/deepseek/minimax/ollama_cloud", ) ErrChannelMonitorInvalidCheckMode = infraerrors.BadRequest( "CHANNEL_MONITOR_INVALID_CHECK_MODE", "check_mode must be one of probe/quota/quota_probe; antigravity only supports quota", diff --git a/backend/internal/service/channel_monitor_ollama_cloud_test.go b/backend/internal/service/channel_monitor_ollama_cloud_test.go new file mode 100644 index 0000000000..5acb3c95bf --- /dev/null +++ b/backend/internal/service/channel_monitor_ollama_cloud_test.go @@ -0,0 +1,243 @@ +//go:build unit + +package service + +import ( + "context" + "encoding/json" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/domain" + "github.com/stretchr/testify/require" +) + +// --- provider 放行(M-1 的 service 层一半) --- + +func TestOllamaCloudMonitorProviderAllowlists(t *testing.T) { + require.NoError(t, validateProvider(MonitorProviderOllamaCloud)) + require.NoError(t, validateAPIMode(MonitorProviderOllamaCloud, "")) + require.NoError(t, validateAPIMode(MonitorProviderOllamaCloud, MonitorAPIModeChatCompletions)) + // responses 探活仍仅 openai(与所有非 openai provider 一致)。 + require.ErrorIs(t, validateAPIMode(MonitorProviderOllamaCloud, MonitorAPIModeResponses), ErrChannelMonitorInvalidAPIMode) + + // ollama_cloud 官方有 OpenAI 兼容 Chat Completions → 三种模式全部放行 + //(对比 antigravity 只允许 quota)。 + require.True(t, providerSupportsProbe(MonitorProviderOllamaCloud)) + require.NoError(t, validateCheckMode(MonitorProviderOllamaCloud, MonitorCheckModeProbe)) + require.NoError(t, validateCheckMode(MonitorProviderOllamaCloud, MonitorCheckModeQuota)) + require.NoError(t, validateCheckMode(MonitorProviderOllamaCloud, MonitorCheckModeQuotaProbe)) +} + +// 行为钉:opencode_go 在 handler binding 里放行、但 service 层 monitorProviders +// 没有(upstream 有单独修复,本分支尚未合入)——钉住现状,防止被误认为本批回归。 +func TestOpenCodeGoMonitorProviderStillMissingFromServiceAllowlist(t *testing.T) { + require.ErrorIs(t, validateProvider("opencode_go"), ErrChannelMonitorInvalidProvider) +} + +// --- 探活 adapter --- + +func TestOllamaCloudMonitorAdapterProbesOpenAIChatCompletions(t *testing.T) { + h := &openAICaptureHandler{} + endpoint := setupFakeOpenAI(t, h) + + res := runCheckForModel(context.Background(), MonitorProviderOllamaCloud, endpoint+"/v1", "sk-ollama", "gpt-oss:120b-cloud", nil) + + require.Equal(t, MonitorStatusOperational, res.Status) + require.Equal(t, providerOpenAIPath, h.lastPath) + require.Equal(t, "gpt-oss:120b-cloud", h.lastBody["model"]) + require.Equal(t, "Bearer sk-ollama", h.lastHeaders.Get("Authorization")) +} + +func TestOllamaCloudMonitorMergeDenyListProtectsChallenge(t *testing.T) { + adapter, apiMode, ok := providerAdapterFor(MonitorProviderOllamaCloud, "") + require.True(t, ok) + require.Equal(t, MonitorAPIModeChatCompletions, apiMode) + + body, err := buildRequestBody(adapter, MonitorProviderOllamaCloud, apiMode, "gpt-oss:120b-cloud", "2+2=?", &CheckOptions{ + BodyOverrideMode: MonitorBodyOverrideModeMerge, + BodyOverride: map[string]any{"model": "evil", "temperature": 0.5}, + }) + require.NoError(t, err) + + var parsed map[string]any + require.NoError(t, json.Unmarshal(body, &parsed)) + require.Equal(t, "gpt-oss:120b-cloud", parsed["model"], "model 命中黑名单不得被覆盖") + require.InDelta(t, 0.5, parsed["temperature"], 0.0001, "非黑名单 key 应正常合并") +} + +// --- quota 取数(C29) --- + +func ollamaCloudQuotaTestAccount(id int64, extra map[string]any) *Account { + return &Account{ + ID: id, + Name: "ollama-quota-test", + Platform: domain.PlatformOllamaCloud, + Type: AccountTypeAPIKey, + Status: StatusActive, + Concurrency: 1, + Credentials: map[string]any{ + "api_key": "sk-ollama", + "base_url": "https://ollama.com/v1", + }, + Extra: extra, + } +} + +func ollamaCloudUsageSnapshotExtra(status string, fetchedAt time.Time, data *OllamaCloudUsageData, lastError string) map[string]any { + snapshot := map[string]any{ + "status": status, + "last_attempt_at": fetchedAt, + "next_refresh_at": fetchedAt, + "fetched_at": fetchedAt, + } + if data != nil { + snapshot["data"] = data + } + if lastError != "" { + snapshot["last_error"] = lastError + } + return map[string]any{ + OllamaCloudUsageSnapshotExtraKey: snapshot, + } +} + +func TestQuotaFetcher_OllamaCloudOkSnapshotMapsTiersAndBalance(t *testing.T) { + fetcher, usage, cnQuota, cnBalance, accounts := newQuotaFetcherTestSetup(t) + fetchedAt := time.Now().Add(-2 * time.Hour).UTC().Truncate(time.Second) + accounts.accounts[31] = ollamaCloudQuotaTestAccount(31, ollamaCloudUsageSnapshotExtra( + OllamaCloudUsageStatusOK, fetchedAt, + &OllamaCloudUsageData{ + Plan: "pro", + FiveHour: &OllamaCloudUsageWindow{UsedPercent: 42.5}, + SevenDay: &OllamaCloudUsageWindow{UsedPercent: 10}, + Balance: "$9.50", + }, + "", + )) + + snapshot := fetcher.Fetch(context.Background(), 31) + + require.True(t, snapshot.Success) + require.Equal(t, "ollama_quota", snapshot.Source) + require.Equal(t, "pro", snapshot.PlanLevel) + require.False(t, snapshot.CredentialInvalid) + require.Empty(t, snapshot.Error) + // 快照是被动抓取的历史值:FetchedAt 沿用真实抓取时间。 + require.True(t, fetchedAt.Equal(snapshot.FetchedAt)) + + require.Len(t, snapshot.Tiers, 2) + require.Equal(t, "5h", snapshot.Tiers[0].Window) + require.InDelta(t, 42.5, snapshot.Tiers[0].UsedPercent, 0.001) + require.Equal(t, "7d", snapshot.Tiers[1].Window) + require.InDelta(t, 10, snapshot.Tiers[1].UsedPercent, 0.001) + + require.NotNil(t, snapshot.Balance) + require.InDelta(t, 9.5, *snapshot.Balance, 0.001) + require.Equal(t, "USD", snapshot.Currency) + + require.Equal(t, 0, usage.getCalls(), "ollama 走快照读取,不得打海外 usage 服务") + require.Equal(t, 0, cnQuota.calls) + require.Equal(t, 0, cnBalance.calls) + require.Equal(t, MonitorStatusOperational, deriveQuotaCheckResult(snapshot, "quota", time.Now()).Status) +} + +// credits 类账号:只有余额没有窗口 → only-balance 降级(余额文本可解析时透出)。 +func TestQuotaFetcher_OllamaCloudBalanceOnlySnapshot(t *testing.T) { + fetcher, _, _, _, accounts := newQuotaFetcherTestSetup(t) + accounts.accounts[32] = ollamaCloudQuotaTestAccount(32, ollamaCloudUsageSnapshotExtra( + OllamaCloudUsageStatusOK, time.Now(), + &OllamaCloudUsageData{Balance: "USD$12"}, + "", + )) + + snapshot := fetcher.Fetch(context.Background(), 32) + + require.True(t, snapshot.Success) + require.Empty(t, snapshot.Tiers) + require.NotNil(t, snapshot.Balance) + require.InDelta(t, 12, *snapshot.Balance, 0.001) +} + +// 无法解析的余额文本跳过(余额仅展示,不做停调判定)。 +func TestQuotaFetcher_OllamaCloudUnparsableBalanceSkipped(t *testing.T) { + _, ok := parseOllamaCloudBalanceUSD("") + require.False(t, ok) + _, ok = parseOllamaCloudBalanceUSD("$9.50 / $20.00") + require.False(t, ok) + + value, ok := parseOllamaCloudBalanceUSD("USD$1,234.50") + require.True(t, ok) + require.InDelta(t, 1234.5, value, 0.001) +} + +// status!=ok(unauthorized/failed)→ 错误快照,带 last_error 与 fetched_at; +// unauthorized 是抓取通道(settings 页会话)过期,不判凭据失效 → 推导 error 而非 failed。 +func TestQuotaFetcher_OllamaCloudFailedSnapshotsYieldErrors(t *testing.T) { + cases := []struct { + name string + status string + wantSub string + }{ + {name: "unauthorized session", status: OllamaCloudUsageStatusUnauthorized, wantSub: "session expired"}, + {name: "scrape failed", status: OllamaCloudUsageStatusFailed, wantSub: "usage page unreachable"}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + fetcher, _, _, _, accounts := newQuotaFetcherTestSetup(t) + fetchedAt := time.Now().Add(-3 * time.Hour).UTC() + accounts.accounts[33] = ollamaCloudQuotaTestAccount(33, ollamaCloudUsageSnapshotExtra( + tc.status, fetchedAt, nil, tc.wantSub, + )) + + snapshot := fetcher.Fetch(context.Background(), 33) + + require.False(t, snapshot.Success) + require.False(t, snapshot.CredentialInvalid) + require.Contains(t, snapshot.Error, tc.wantSub) + require.Contains(t, snapshot.Error, "fetched at") + require.Contains(t, snapshot.Error, fetchedAt.Format("2006-01-02")) + require.Equal(t, MonitorStatusError, deriveQuotaCheckResult(snapshot, "quota", time.Now()).Status) + }) + } +} + +// eligible=false(host 门禁:反代域名)→ 带原因码的可解释错误,不是笼统报错。 +func TestQuotaFetcher_OllamaCloudIneligibleBaseURLYieldsExplainableError(t *testing.T) { + fetcher, usage, _, _, accounts := newQuotaFetcherTestSetup(t) + account := ollamaCloudQuotaTestAccount(34, nil) + account.Credentials["base_url"] = "https://proxy.example.com/v1" + accounts.accounts[34] = account + + snapshot := fetcher.Fetch(context.Background(), 34) + + require.False(t, snapshot.Success) + require.Contains(t, snapshot.Error, "unsupported_base_url") + require.Equal(t, 0, usage.getCalls()) +} + +// 尚无快照(未配置会话或还没有请求活动)→ 可解释错误。 +func TestQuotaFetcher_OllamaCloudNoSnapshotYieldsExplainableError(t *testing.T) { + fetcher, _, _, _, accounts := newQuotaFetcherTestSetup(t) + accounts.accounts[35] = ollamaCloudQuotaTestAccount(35, nil) + + snapshot := fetcher.Fetch(context.Background(), 35) + + require.False(t, snapshot.Success) + require.Contains(t, snapshot.Error, "no ollama cloud usage snapshot yet") +} + +// 回归:opencode_go 仍走 CN quota 路由,kimi coding 仍走 CN quota(kimi 已有 +// 独立用例,这里钉 opencode_go 与 ollama 互不串线)。 +func TestQuotaFetcher_OpenCodeGoStillRoutesToCNQuota(t *testing.T) { + fetcher, usage, cnQuota, _, accounts := newQuotaFetcherTestSetup(t) + accounts.accounts[36] = &Account{ID: 36, Platform: domain.PlatformOpenCodeGo, Type: AccountTypeAPIKey} + cnQuota.result = &CNProviderQuotaProbeResult{Success: true} + + snapshot := fetcher.Fetch(context.Background(), 36) + + require.True(t, snapshot.Success) + require.Equal(t, "cn_quota", snapshot.Source) + require.Equal(t, 1, cnQuota.calls) + require.Equal(t, 0, usage.getCalls()) +} diff --git a/backend/internal/service/channel_monitor_quota_fetcher.go b/backend/internal/service/channel_monitor_quota_fetcher.go index 868def18d3..ade5e760c5 100644 --- a/backend/internal/service/channel_monitor_quota_fetcher.go +++ b/backend/internal/service/channel_monitor_quota_fetcher.go @@ -23,6 +23,8 @@ import ( // - 国产 coding plan(kimi/zhipu/deepseek)→ CNProviderQuotaService.QueryUsageForAccount // - 国产 payg(kimi/deepseek)→ CNProviderBalanceService.QueryBalanceForAccount // (zhipu payg 无公开余额端点,探测会返回该错误,原样透出) +// - ollama_cloud → 账号 extra 里的官方用量快照(OllamaCloudUsageService 随请求 +// 活动被动维护,此处只读取、不实时探测;数据可能陈旧,FetchedAt 如实透出) // 数据源统一接受已加载的 *Account:fetchUncached 路由前 GetByID 一次并传下去, // 下游服务不再各自重载(每次 GetByID 含 proxies/groups 联查)。 // @@ -223,6 +225,8 @@ func (f *ChannelMonitorQuotaFetcher) fetchUncached(ctx context.Context, accountI return f.fetchCNBalance(ctx, account, now) case domain.PlatformOpenCodeGo: return f.fetchCNQuota(ctx, account, now) + case domain.PlatformOllamaCloud: + return f.fetchOllamaCloudQuota(account, now) default: return f.fetchUsage(ctx, account, now) } @@ -455,6 +459,118 @@ func (f *ChannelMonitorQuotaFetcher) fetchCNBalance(ctx context.Context, account return snapshot } +// fetchOllamaCloudQuota ollama_cloud:读取 OllamaCloudUsageService 维护在账号 +// extra 里的官方用量快照(请求活动驱动的被动抓取,此处不做实时探测),映射为 +// 配额快照;FetchedAt 沿用快照真实抓取时间——静默账号的数据会陈旧,时间戳 +// 如实透出,不伪装成刚刚抓取。eligible=false(如 base_url 为反代域名)或 +// 快照缺失/失败时返回带可解释原因的错误快照,而不是笼统的「不支持用量查询」。 +func (f *ChannelMonitorQuotaFetcher) fetchOllamaCloudQuota(account *Account, now time.Time) *domain.MonitorQuotaSnapshot { + if reason := ollamaCloudUsageEligibilityReason(account); reason != "" { + return quotaErrorSnapshot("ollama_quota", "ollama cloud usage unavailable: "+ollamaCloudUsageReasonHint(reason), now) + } + snapshot := decodeOllamaCloudUsageSnapshot(account.Extra) + if snapshot == nil { + return quotaErrorSnapshot("ollama_quota", + "no ollama cloud usage snapshot yet; snapshots are captured from the official ollama.com usage page on request activity", now) + } + fetchedAt := now + if snapshot.FetchedAt != nil { + fetchedAt = *snapshot.FetchedAt + } + if snapshot.Status != OllamaCloudUsageStatusOK { + return &domain.MonitorQuotaSnapshot{ + Source: "ollama_quota", + // 401 是 settings 页会话过期(抓取通道凭据),不是账号 API key 失效, + // 不置 CredentialInvalid——渠道本身可能仍然健康。 + Success: false, + Error: truncateMessage(sanitizeErrorMessage(fmt.Sprintf( + "ollama cloud usage snapshot status %s (fetched at %s): %s", + snapshot.Status, formatOllamaCloudFetchedAt(snapshot.FetchedAt), + firstNonEmpty(snapshot.LastError, "unknown error")))), + FetchedAt: now, + } + } + if snapshot.Data == nil { + return quotaErrorSnapshot("ollama_quota", + fmt.Sprintf("ollama cloud usage snapshot has no data (fetched at %s)", formatOllamaCloudFetchedAt(snapshot.FetchedAt)), now) + } + out := &domain.MonitorQuotaSnapshot{ + Source: "ollama_quota", + Success: true, + PlanLevel: snapshot.Data.Plan, + FetchedAt: fetchedAt, + } + out.Tiers = ollamaCloudQuotaTiers(snapshot.Data) + if balance, ok := parseOllamaCloudBalanceUSD(snapshot.Data.Balance); ok { + out.Balance = &balance + out.Currency = "USD" + } + return out +} + +// ollamaCloudQuotaTiers 把官方用量窗口归一为 tier 列表(窗口缺失时跳过)。 +func ollamaCloudQuotaTiers(data *OllamaCloudUsageData) []domain.MonitorQuotaTier { + if data == nil { + return nil + } + tiers := make([]domain.MonitorQuotaTier, 0, 2) + appendOllamaCloudQuotaTier(&tiers, "5h", data.FiveHour) + appendOllamaCloudQuotaTier(&tiers, "7d", data.SevenDay) + if len(tiers) == 0 { + return nil + } + return tiers +} + +func appendOllamaCloudQuotaTier(tiers *[]domain.MonitorQuotaTier, window string, w *OllamaCloudUsageWindow) { + if w == nil { + return + } + tier := domain.MonitorQuotaTier{Window: window, UsedPercent: w.UsedPercent} + if w.ResetAt != nil { + tier.ResetAt = w.ResetAt.UTC().Format(time.RFC3339) + } + *tiers = append(*tiers, tier) +} + +// parseOllamaCloudBalanceUSD 把官方页面抓到的余额文本(如 "$9.50" / "USD$9.50") +// 解析为美元数值;解析失败返回 false(余额仅作展示,无月度信用总额可用于 +// 派生百分比,故 credits 账号只透出余额,不参与 used_percent 告警)。 +func parseOllamaCloudBalanceUSD(raw string) (float64, bool) { + raw = strings.TrimSpace(raw) + raw = strings.TrimPrefix(raw, "USD") + raw = strings.TrimPrefix(raw, "$") + raw = strings.ReplaceAll(strings.TrimSpace(raw), ",", "") + if raw == "" { + return 0, false + } + value, err := strconv.ParseFloat(raw, 64) + if err != nil { + return 0, false + } + return value, true +} + +// ollamaCloudUsageReasonHint 把 EligibleReason 原因码翻译成运维可读的提示 +// (原因码语义见 OllamaCloudUsageState.EligibleReason)。 +func ollamaCloudUsageReasonHint(reason string) string { + switch reason { + case ollamaCloudUsageIneligibleBaseURL: + return "unsupported_base_url (base_url is not the official ollama.com host; usage snapshots are only captured for official-host accounts)" + case ollamaCloudUsageIneligibleAccountType: + return "wrong_account_type (usage snapshots require an apikey account)" + default: + return reason + } +} + +func formatOllamaCloudFetchedAt(t *time.Time) string { + if t == nil { + return "unknown" + } + return t.UTC().Format(time.RFC3339) +} + // quotaErrorSnapshot 构造统一错误快照。 func quotaErrorSnapshot(source, message string, now time.Time) *domain.MonitorQuotaSnapshot { return &domain.MonitorQuotaSnapshot{ diff --git a/backend/internal/service/channel_monitor_template_types.go b/backend/internal/service/channel_monitor_template_types.go index 0b824d577d..99c586ff43 100644 --- a/backend/internal/service/channel_monitor_template_types.go +++ b/backend/internal/service/channel_monitor_template_types.go @@ -55,7 +55,7 @@ var ( "CHANNEL_MONITOR_TEMPLATE_NOT_FOUND", "channel monitor request template not found", ) ErrChannelMonitorTemplateInvalidProvider = infraerrors.BadRequest( - "CHANNEL_MONITOR_TEMPLATE_INVALID_PROVIDER", "template provider must be one of openai/anthropic/gemini/grok", + "CHANNEL_MONITOR_TEMPLATE_INVALID_PROVIDER", "template provider must be one of openai/anthropic/gemini/grok/ollama_cloud", ) ErrChannelMonitorTemplateInvalidAPIMode = infraerrors.BadRequest( "CHANNEL_MONITOR_TEMPLATE_INVALID_API_MODE", "template api_mode must be chat_completions or responses; responses is only supported for openai", diff --git a/backend/internal/service/channel_monitor_validate.go b/backend/internal/service/channel_monitor_validate.go index 0aa1c248d4..309d3d2269 100644 --- a/backend/internal/service/channel_monitor_validate.go +++ b/backend/internal/service/channel_monitor_validate.go @@ -23,6 +23,7 @@ var monitorProviders = map[string]struct{}{ MonitorProviderZhipu: {}, MonitorProviderDeepseek: {}, MonitorProviderMiniMax: {}, + MonitorProviderOllamaCloud: {}, } // probeCapableProviders 支持探活(probe / quota_probe)的 provider。 @@ -38,6 +39,8 @@ var probeCapableProviders = map[string]struct{}{ MonitorProviderZhipu: {}, MonitorProviderDeepseek: {}, MonitorProviderMiniMax: {}, + // ollama_cloud 官方提供 OpenAI 兼容 /v1/chat/completions,可真实探活。 + MonitorProviderOllamaCloud: {}, } // validateProvider 校验 provider 字符串。 From 8782a53bb51e3610eca38d8d21d619d8b75b114e Mon Sep 17 00:00:00 2001 From: alfadb Date: Sun, 13 Sep 2026 07:45:12 +0800 Subject: [PATCH 27/81] feat(monitor): support ollama_cloud in the channel monitor UI Frontend half of increment 5-2 (mirrors backend 39b8649df): - Add ollama_cloud to the Provider union, channelMonitor constants (PROVIDER_OLLAMA_CLOUD, PROVIDERS, DEFAULT_OLLAMA_CLOUD_ENDPOINT = https://ollama.com; the probe adapter appends /v1/chat/completions, same source as the backend DefaultOllamaCloudBaseURL), the monitor form provider grid / endpoint preset, the filter bar, and the template manager tabs. ollama_cloud supports all three check modes and chat_completions only, so no antigravity-style restriction and no default-model preset (backend only defaults grok's model). - Extend providerLabel/badge/picker/gradient (stone palette, aligned with utils/platformColors.ts), the user MonitorCard icon tint, and the ProviderIcon exhaustive map with the official llama mark. - i18n: monitorCommon.providers.ollama_cloud and admin.groups.platforms.ollama_cloud in en+zh. - ChannelsView: add ollama_cloud to platformOrder and compositePlatforms (backend isConcreteRequestPlatform already includes it); no per-platform extra config needed - matching opencode_go, which also carries none in the channel form. - Update the stale ChannelMonitorView.grok.spec.ts provider count 8 -> 11 (the grid already had 10 before this change and the spec was failing on the clean baseline). --- frontend/src/api/admin/channelMonitor.ts | 1 + .../components/admin/monitor/MonitorFiltersBar.vue | 2 ++ .../components/admin/monitor/MonitorFormDialog.vue | 4 ++++ .../admin/monitor/MonitorTemplateManagerDialog.vue | 2 ++ frontend/src/components/user/monitor/MonitorCard.vue | 3 ++- frontend/src/components/user/monitor/ProviderIcon.vue | 6 ++++++ frontend/src/composables/useChannelMonitorFormat.ts | 11 ++++++++++- frontend/src/constants/channelMonitor.ts | 5 +++++ frontend/src/i18n/locales/en/admin/overview.ts | 1 + frontend/src/i18n/locales/en/dashboard.ts | 3 ++- frontend/src/i18n/locales/zh/admin/overview.ts | 1 + frontend/src/i18n/locales/zh/dashboard.ts | 3 ++- frontend/src/views/admin/ChannelsView.vue | 5 +++-- .../admin/__tests__/ChannelMonitorView.grok.spec.ts | 5 ++++- 14 files changed, 45 insertions(+), 7 deletions(-) diff --git a/frontend/src/api/admin/channelMonitor.ts b/frontend/src/api/admin/channelMonitor.ts index 7ddd5697e5..6ac25d15ec 100644 --- a/frontend/src/api/admin/channelMonitor.ts +++ b/frontend/src/api/admin/channelMonitor.ts @@ -16,6 +16,7 @@ export type Provider = | 'deepseek' | 'minimax' | 'opencode_go' + | 'ollama_cloud' export type MonitorStatus = 'operational' | 'degraded' | 'failed' | 'error' export type BodyOverrideMode = 'off' | 'merge' | 'replace' export type APIMode = 'chat_completions' | 'responses' diff --git a/frontend/src/components/admin/monitor/MonitorFiltersBar.vue b/frontend/src/components/admin/monitor/MonitorFiltersBar.vue index c489738eef..46cfdedd85 100644 --- a/frontend/src/components/admin/monitor/MonitorFiltersBar.vue +++ b/frontend/src/components/admin/monitor/MonitorFiltersBar.vue @@ -77,6 +77,7 @@ import { PROVIDER_DEEPSEEK, PROVIDER_MINIMAX, PROVIDER_OPENCODE_GO, + PROVIDER_OLLAMA_CLOUD, } from '@/constants/channelMonitor' defineProps<{ @@ -108,6 +109,7 @@ const providerFilterOptions = computed(() => [ { value: PROVIDER_DEEPSEEK, label: t('monitorCommon.providers.deepseek') }, { value: PROVIDER_MINIMAX, label: t('monitorCommon.providers.minimax') }, { value: PROVIDER_OPENCODE_GO, label: t('monitorCommon.providers.opencode_go') }, + { value: PROVIDER_OLLAMA_CLOUD, label: t('monitorCommon.providers.ollama_cloud') }, ]) const enabledFilterOptions = computed(() => [ diff --git a/frontend/src/components/admin/monitor/MonitorFormDialog.vue b/frontend/src/components/admin/monitor/MonitorFormDialog.vue index 3ec29f0dcb..cdef6fd638 100644 --- a/frontend/src/components/admin/monitor/MonitorFormDialog.vue +++ b/frontend/src/components/admin/monitor/MonitorFormDialog.vue @@ -271,6 +271,7 @@ import { PROVIDER_DEEPSEEK, PROVIDER_MINIMAX, PROVIDER_OPENCODE_GO, + PROVIDER_OLLAMA_CLOUD, API_MODE_CHAT_COMPLETIONS, API_MODE_RESPONSES, CHECK_MODE_PROBE, @@ -283,6 +284,7 @@ import { DEFAULT_DEEPSEEK_ENDPOINT, DEFAULT_MINIMAX_ENDPOINT, DEFAULT_OPENCODE_GO_ENDPOINT, + DEFAULT_OLLAMA_CLOUD_ENDPOINT, DEFAULT_INTERVAL_SECONDS, } from '@/constants/channelMonitor' @@ -479,6 +481,7 @@ const providerOptions = computed(() => [ { value: PROVIDER_DEEPSEEK, label: t('monitorCommon.providers.deepseek') }, { value: PROVIDER_MINIMAX, label: t('monitorCommon.providers.minimax') }, { value: PROVIDER_OPENCODE_GO, label: t('monitorCommon.providers.opencode_go') }, + { value: PROVIDER_OLLAMA_CLOUD, label: t('monitorCommon.providers.ollama_cloud') }, ]) // 国产 provider 预填的官方 endpoint(仅探活侧;配额模式 endpoint 可留空)。 @@ -488,6 +491,7 @@ const PROVIDER_DEFAULT_ENDPOINTS: Partial> = { [PROVIDER_DEEPSEEK]: DEFAULT_DEEPSEEK_ENDPOINT, [PROVIDER_MINIMAX]: DEFAULT_MINIMAX_ENDPOINT, [PROVIDER_OPENCODE_GO]: DEFAULT_OPENCODE_GO_ENDPOINT, + [PROVIDER_OLLAMA_CLOUD]: DEFAULT_OLLAMA_CLOUD_ENDPOINT, } interface CheckModeOption { diff --git a/frontend/src/components/admin/monitor/MonitorTemplateManagerDialog.vue b/frontend/src/components/admin/monitor/MonitorTemplateManagerDialog.vue index f4943b375d..22205cd91d 100644 --- a/frontend/src/components/admin/monitor/MonitorTemplateManagerDialog.vue +++ b/frontend/src/components/admin/monitor/MonitorTemplateManagerDialog.vue @@ -255,6 +255,7 @@ import { PROVIDER_DEEPSEEK, PROVIDER_MINIMAX, PROVIDER_OPENCODE_GO, + PROVIDER_OLLAMA_CLOUD, PROVIDERS, API_MODE_CHAT_COMPLETIONS, API_MODE_RESPONSES, @@ -282,6 +283,7 @@ const providerTabs = computed<{ value: Provider; label: string }[]>(() => [ { value: PROVIDER_DEEPSEEK, label: t('monitorCommon.providers.deepseek') }, { value: PROVIDER_MINIMAX, label: t('monitorCommon.providers.minimax') }, { value: PROVIDER_OPENCODE_GO, label: t('monitorCommon.providers.opencode_go') }, + { value: PROVIDER_OLLAMA_CLOUD, label: t('monitorCommon.providers.ollama_cloud') }, ]) const activeProvider = ref(PROVIDER_ANTHROPIC) diff --git a/frontend/src/components/user/monitor/MonitorCard.vue b/frontend/src/components/user/monitor/MonitorCard.vue index 268790794c..424b6b9adb 100644 --- a/frontend/src/components/user/monitor/MonitorCard.vue +++ b/frontend/src/components/user/monitor/MonitorCard.vue @@ -91,7 +91,7 @@ import MonitorAvailabilityRow from './MonitorAvailabilityRow.vue' import MonitorTimeline from './MonitorTimeline.vue' import MonitorQuotaView from '@/components/common/MonitorQuotaView.vue' -// 图标配色与 utils/platformColors.ts 的平台色对齐(新 4 家)。 +// 图标配色与 utils/platformColors.ts 的平台色对齐(新 4 家 + ollama_cloud)。 const PROVIDER_TINT: Record = { openai: 'text-emerald-600 dark:text-emerald-300', anthropic: 'text-orange-600 dark:text-orange-300', @@ -102,6 +102,7 @@ const PROVIDER_TINT: Record = { zhipu: 'text-indigo-600 dark:text-indigo-300', deepseek: 'text-teal-600 dark:text-teal-300', opencode_go: 'text-amber-700 dark:text-amber-300', + ollama_cloud: 'text-stone-600 dark:text-stone-300', } const props = defineProps<{ diff --git a/frontend/src/components/user/monitor/ProviderIcon.vue b/frontend/src/components/user/monitor/ProviderIcon.vue index b6f4c4f7c4..4e6e566ee9 100644 --- a/frontend/src/components/user/monitor/ProviderIcon.vue +++ b/frontend/src/components/user/monitor/ProviderIcon.vue @@ -88,6 +88,12 @@ const PROVIDER_ICONS: Record = { 'M16 6H8v12h8V6zm4 16H4V2h16v20z', ], }, + // ollama_cloud 官方 logo mark(llama)搬自 PlatformIcon.vue / ModelIcon.vue,保持同步。 + ollama_cloud: { + paths: [ + 'M7.905 1.09c.216.085.411.225.588.41.295.306.544.744.734 1.263.191.522.315 1.1.362 1.68a5.054 5.054 0 012.049-.636l.051-.004c.87-.07 1.73.087 2.48.474.101.053.2.11.297.17.05-.569.172-1.134.36-1.644.19-.52.439-.957.733-1.264a1.67 1.67 0 01.589-.41c.257-.1.53-.118.796-.042.401.114.745.368 1.016.737.248.337.434.769.561 1.287.23.934.27 2.163.115 3.645l.053.04.026.019c.757.576 1.284 1.397 1.563 2.35.435 1.487.216 3.155-.534 4.088l-.018.021.002.003c.417.762.67 1.567.724 2.4l.002.03c.064 1.065-.2 2.137-.814 3.19l-.007.01.01.024c.472 1.157.62 2.322.438 3.486l-.006.039a.651.651 0 01-.747.536.648.648 0 01-.54-.742c.167-1.033.01-2.069-.48-3.123a.643.643 0 01.04-.617l.004-.006c.604-.924.854-1.83.8-2.72-.046-.779-.325-1.544-.8-2.273a.644.644 0 01.18-.886l.009-.006c.243-.159.467-.565.58-1.12a4.229 4.229 0 00-.095-1.974c-.205-.7-.58-1.284-1.105-1.683-.595-.454-1.383-.673-2.38-.61a.653.653 0 01-.632-.371c-.314-.665-.772-1.141-1.343-1.436a3.288 3.288 0 00-1.772-.332c-1.245.099-2.343.801-2.67 1.686a.652.652 0 01-.61.425c-1.067.002-1.893.252-2.497.703-.522.39-.878.935-1.066 1.588a4.07 4.07 0 00-.068 1.886c.112.558.331 1.02.582 1.269l.008.007c.212.207.257.53.109.785-.36.622-.629 1.549-.673 2.44-.05 1.018.186 1.902.719 2.536l.016.019a.643.643 0 01.095.69c-.576 1.236-.753 2.252-.562 3.052a.652.652 0 01-1.269.298c-.243-1.018-.078-2.184.473-3.498l.014-.035-.008-.012a4.339 4.339 0 01-.598-1.309l-.005-.019a5.764 5.764 0 01-.177-1.785c.044-.91.278-1.842.622-2.59l.012-.026-.002-.002c-.293-.418-.51-.953-.63-1.545l-.005-.024a5.352 5.352 0 01.093-2.49c.262-.915.777-1.701 1.536-2.269.06-.045.123-.09.186-.132-.159-1.493-.119-2.73.112-3.67.127-.518.314-.95.562-1.287.27-.368.614-.622 1.015-.737.266-.076.54-.059.797.042zm4.116 9.09c.936 0 1.8.313 2.446.855.63.527 1.005 1.235 1.005 1.94 0 .888-.406 1.58-1.133 2.022-.62.375-1.451.557-2.403.557-1.009 0-1.871-.259-2.493-.734-.617-.47-.963-1.13-.963-1.845 0-.707.398-1.417 1.056-1.946.668-.537 1.55-.849 2.485-.849zm0 .896a3.07 3.07 0 00-1.916.65c-.461.37-.722.835-.722 1.25 0 .428.21.829.61 1.134.455.347 1.124.548 1.943.548.799 0 1.473-.147 1.932-.426.463-.28.7-.686.7-1.257 0-.423-.246-.89-.683-1.256-.484-.405-1.14-.643-1.864-.643zm.662 1.21l.004.004c.12.151.095.37-.056.49l-.292.23v.446a.375.375 0 01-.376.373.375.375 0 01-.376-.373v-.46l-.271-.218a.347.347 0 01-.052-.49.353.353 0 01.494-.051l.215.172.22-.174a.353.353 0 01.49.051zm-5.04-1.919c.478 0 .867.39.867.871a.87.87 0 01-.868.871.87.87 0 01-.867-.87.87.87 0 01.867-.872zm8.706 0c.48 0 .868.39.868.871a.87.87 0 01-.868.871.87.87 0 01-.867-.87.87.87 0 01.867-.872zM7.44 2.3l-.003.002a.659.659 0 00-.285.238l-.005.006c-.138.189-.258.467-.348.832-.17.692-.216 1.631-.124 2.782.43-.128.899-.208 1.404-.237l.01-.001.019-.034c.046-.082.095-.161.148-.239.123-.771.022-1.692-.253-2.444-.134-.364-.297-.65-.453-.813a.628.628 0 00-.107-.09L7.44 2.3zm9.174.04l-.002.001a.628.628 0 00-.107.09c-.156.163-.32.45-.453.814-.29.794-.387 1.776-.23 2.572l.058.097.008.014h.03a5.184 5.184 0 011.466.212c.086-1.124.038-2.043-.128-2.722-.09-.365-.21-.643-.349-.832l-.004-.006a.659.659 0 00-.285-.239h-.004z', + ], + }, } const props = withDefaults(defineProps<{ diff --git a/frontend/src/composables/useChannelMonitorFormat.ts b/frontend/src/composables/useChannelMonitorFormat.ts index 2fb5d324df..b3afaa5de6 100644 --- a/frontend/src/composables/useChannelMonitorFormat.ts +++ b/frontend/src/composables/useChannelMonitorFormat.ts @@ -23,6 +23,7 @@ import { PROVIDER_DEEPSEEK, PROVIDER_MINIMAX, PROVIDER_OPENCODE_GO, + PROVIDER_OLLAMA_CLOUD, PROVIDERS, STATUS_OPERATIONAL, STATUS_DEGRADED, @@ -107,7 +108,7 @@ export function useChannelMonitorFormat() { case PROVIDER_GROK: return 'bg-zinc-100 text-zinc-700 dark:bg-zinc-500/15 dark:text-zinc-300' // 配色与 utils/platformColors.ts 的平台色对齐:antigravity=purple / - // kimi=pink / zhipu=indigo / deepseek=teal。 + // kimi=pink / zhipu=indigo / deepseek=teal / ollama_cloud=stone。 case PROVIDER_ANTIGRAVITY: return 'bg-purple-100 text-purple-700 dark:bg-purple-500/15 dark:text-purple-300' case PROVIDER_KIMI: @@ -120,6 +121,8 @@ export function useChannelMonitorFormat() { return 'bg-rose-100 text-rose-700 dark:bg-rose-500/15 dark:text-rose-300' case PROVIDER_OPENCODE_GO: return 'bg-amber-100 text-amber-800 dark:bg-amber-500/15 dark:text-amber-300' + case PROVIDER_OLLAMA_CLOUD: + return 'bg-stone-100 text-stone-700 dark:bg-stone-500/15 dark:text-stone-300' default: return NEUTRAL_BADGE } @@ -188,6 +191,10 @@ export function useChannelMonitorFormat() { return active ? 'border-amber-500 bg-amber-50 text-amber-800 dark:bg-amber-500/15 dark:text-amber-300 dark:border-amber-400' : 'border-gray-200 bg-white text-gray-600 hover:border-amber-300 hover:text-amber-700 dark:border-dark-700 dark:bg-dark-800 dark:text-gray-400 dark:hover:border-amber-500/50' + case PROVIDER_OLLAMA_CLOUD: + return active + ? 'border-stone-500 bg-stone-50 text-stone-700 dark:bg-stone-500/15 dark:text-stone-300 dark:border-stone-400' + : 'border-gray-200 bg-white text-gray-600 hover:border-stone-300 hover:text-stone-700 dark:border-dark-700 dark:bg-dark-800 dark:text-gray-400 dark:hover:border-stone-500/50' default: return active ? 'border-gray-400 bg-gray-50 text-gray-700 dark:border-dark-500 dark:bg-dark-700 dark:text-gray-200' @@ -276,6 +283,8 @@ export function providerGradient(provider: string): string { return 'bg-gradient-to-br from-rose-50 to-rose-100 dark:from-rose-500/10 dark:to-rose-500/20' case PROVIDER_OPENCODE_GO: return 'bg-gradient-to-br from-amber-50 to-amber-100 dark:from-amber-500/10 dark:to-amber-500/20' + case PROVIDER_OLLAMA_CLOUD: + return 'bg-gradient-to-br from-stone-50 to-stone-200 dark:from-stone-500/10 dark:to-stone-500/20' default: return 'bg-gradient-to-br from-gray-100 to-gray-200 dark:from-dark-700 dark:to-dark-600' } diff --git a/frontend/src/constants/channelMonitor.ts b/frontend/src/constants/channelMonitor.ts index 1f05acb0e3..5b33910e85 100644 --- a/frontend/src/constants/channelMonitor.ts +++ b/frontend/src/constants/channelMonitor.ts @@ -19,6 +19,7 @@ export const PROVIDER_ZHIPU: Provider = 'zhipu' export const PROVIDER_DEEPSEEK: Provider = 'deepseek' export const PROVIDER_MINIMAX: Provider = 'minimax' export const PROVIDER_OPENCODE_GO: Provider = 'opencode_go' +export const PROVIDER_OLLAMA_CLOUD: Provider = 'ollama_cloud' export const DEFAULT_GROK_ENDPOINT = 'https://api.x.ai' export const DEFAULT_GROK_MODEL = 'grok-4.5' @@ -29,6 +30,9 @@ export const DEFAULT_ZHIPU_ENDPOINT = 'https://open.bigmodel.cn' export const DEFAULT_DEEPSEEK_ENDPOINT = 'https://api.deepseek.com' export const DEFAULT_MINIMAX_ENDPOINT = 'https://api.minimaxi.com' export const DEFAULT_OPENCODE_GO_ENDPOINT = 'https://opencode.ai/zen/go/v1' +// ollama_cloud 官方 OpenAI 兼容端点:探活 adapter 追加 /v1/chat/completions, +// 与后端 DefaultOllamaCloudBaseURL (https://ollama.com/v1) 同源。 +export const DEFAULT_OLLAMA_CLOUD_ENDPOINT = 'https://ollama.com' export const CHECK_MODE_PROBE: CheckMode = 'probe' export const CHECK_MODE_QUOTA: CheckMode = 'quota' @@ -48,6 +52,7 @@ export const PROVIDERS: readonly Provider[] = [ PROVIDER_DEEPSEEK, PROVIDER_MINIMAX, PROVIDER_OPENCODE_GO, + PROVIDER_OLLAMA_CLOUD, ] /** 仅支持配额模式(无探活 adapter)的 provider。 */ diff --git a/frontend/src/i18n/locales/en/admin/overview.ts b/frontend/src/i18n/locales/en/admin/overview.ts index e6e07ddd65..67d21ee3e4 100644 --- a/frontend/src/i18n/locales/en/admin/overview.ts +++ b/frontend/src/i18n/locales/en/admin/overview.ts @@ -1046,6 +1046,7 @@ export default { minimax: 'MiniMax', opencode_go: 'OpenCode', typesafe: 'TypeSafe / Jev', + ollama_cloud: 'Ollama Cloud', composite: 'Composite', }, deleteConfirm: diff --git a/frontend/src/i18n/locales/en/dashboard.ts b/frontend/src/i18n/locales/en/dashboard.ts index d43bed531c..9b61dd93ab 100644 --- a/frontend/src/i18n/locales/en/dashboard.ts +++ b/frontend/src/i18n/locales/en/dashboard.ts @@ -513,7 +513,8 @@ export default { zhipu: 'Zhipu GLM', deepseek: 'DeepSeek', minimax: 'MiniMax', - opencode_go: 'OpenCode' + opencode_go: 'OpenCode', + ollama_cloud: 'Ollama Cloud' }, // Check modes (how a monitor performs its checks) checkMode: { diff --git a/frontend/src/i18n/locales/zh/admin/overview.ts b/frontend/src/i18n/locales/zh/admin/overview.ts index 85426f04b6..83b9469f8a 100644 --- a/frontend/src/i18n/locales/zh/admin/overview.ts +++ b/frontend/src/i18n/locales/zh/admin/overview.ts @@ -979,6 +979,7 @@ export default { minimax: 'MiniMax', opencode_go: 'OpenCode', typesafe: 'TypeSafe / Jev', + ollama_cloud: 'Ollama Cloud', composite: 'Composite', }, saving: '保存中...', diff --git a/frontend/src/i18n/locales/zh/dashboard.ts b/frontend/src/i18n/locales/zh/dashboard.ts index 15c276d6e6..079e974e8f 100644 --- a/frontend/src/i18n/locales/zh/dashboard.ts +++ b/frontend/src/i18n/locales/zh/dashboard.ts @@ -518,7 +518,8 @@ export default { zhipu: '智谱 GLM', deepseek: 'DeepSeek', minimax: 'MiniMax', - opencode_go: 'OpenCode' + opencode_go: 'OpenCode', + ollama_cloud: 'Ollama Cloud' }, // 检查模式(监控条目的工作方式) checkMode: { diff --git a/frontend/src/views/admin/ChannelsView.vue b/frontend/src/views/admin/ChannelsView.vue index 0a0b227d4d..a65dc0a2d0 100644 --- a/frontend/src/views/admin/ChannelsView.vue +++ b/frontend/src/views/admin/ChannelsView.vue @@ -763,9 +763,10 @@ const form = reactive({ let abortController: AbortController | null = null // ── Platform config ── -const platformOrder: GroupPlatform[] = ['anthropic', 'openai', 'gemini', 'antigravity', 'grok', 'kimi', 'zhipu', 'deepseek', 'minimax', 'opencode_go', 'typesafe'] +const platformOrder: GroupPlatform[] = ['anthropic', 'openai', 'gemini', 'antigravity', 'grok', 'kimi', 'zhipu', 'deepseek', 'minimax', 'opencode_go', 'typesafe', 'ollama_cloud'] // Composite pricing/mapping may target every concrete schedulable provider. -const compositePlatforms: GroupPlatform[] = ['anthropic', 'openai', 'gemini', 'antigravity', 'grok', 'kimi', 'zhipu', 'deepseek', 'minimax', 'opencode_go', 'typesafe'] +// (Backend isConcreteRequestPlatform includes ollama_cloud.) +const compositePlatforms: GroupPlatform[] = ['anthropic', 'openai', 'gemini', 'antigravity', 'grok', 'kimi', 'zhipu', 'deepseek', 'minimax', 'opencode_go', 'ollama_cloud'] // ── Helpers ── function formatDate(value: string): string { diff --git a/frontend/src/views/admin/__tests__/ChannelMonitorView.grok.spec.ts b/frontend/src/views/admin/__tests__/ChannelMonitorView.grok.spec.ts index 5b581811d7..3ffdc00a6a 100644 --- a/frontend/src/views/admin/__tests__/ChannelMonitorView.grok.spec.ts +++ b/frontend/src/views/admin/__tests__/ChannelMonitorView.grok.spec.ts @@ -100,8 +100,11 @@ describe('channel monitor Grok provider', () => { await flushPromises() expect(PROVIDERS).toContain(PROVIDER_GROK) + // Provider grid mirrors the full backend oneof list (migration 239 CHECK): + // openai/anthropic/gemini/grok/antigravity/kimi/zhipu/deepseek/minimax/ + // opencode_go/ollama_cloud. const providerButtons = wrapper.findAll('[data-testid^="monitor-provider-"]') - expect(providerButtons).toHaveLength(10) + expect(providerButtons).toHaveLength(11) expect(providerButtons[0].element.parentElement?.className).toContain('grid-cols-2') expect(providerButtons[0].element.parentElement?.className).toContain('sm:grid-cols-4') From f3a40c7219d38f1a94e5855e000bb3413bd1aac5 Mon Sep 17 00:00:00 2001 From: alfadb Date: Sun, 13 Sep 2026 07:58:54 +0800 Subject: [PATCH 28/81] feat(account): support ollama_cloud protocol and quota mode in the create form --- .../components/account/CreateAccountModal.vue | 151 +++++++++++++++++- .../__tests__/CreateAccountModal.spec.ts | 121 ++++++++++++++ .../credentialsBuilder.cnAdaptive.spec.ts | 37 ++++- .../components/account/credentialsBuilder.ts | 19 ++- .../src/i18n/locales/en/admin/accounts.ts | 9 ++ .../src/i18n/locales/zh/admin/accounts.ts | 9 ++ 6 files changed, 333 insertions(+), 13 deletions(-) diff --git a/frontend/src/components/account/CreateAccountModal.vue b/frontend/src/components/account/CreateAccountModal.vue index 64cea06900..3d0114e01f 100644 --- a/frontend/src/components/account/CreateAccountModal.vue +++ b/frontend/src/components/account/CreateAccountModal.vue @@ -241,6 +241,19 @@ TypeSafe / Jev + @@ -545,6 +558,94 @@ + +
+ +
+ + +
+ +
+ + +
+ + +
+
+
+
@@ -3974,6 +4075,7 @@ import { type CnNativeApiProtocol, type CnProviderPlatform, type HeaderOverrideRow, + type OllamaCloudAccountMode, type OpenCodeAccountMode, type OpenCodeGoProtocolRule } from '@/components/account/credentialsBuilder' @@ -4176,6 +4278,10 @@ const upstreamBillingAutoProbeEnabled = ref(true) // ── 国产供应商(Kimi / Zhipu / DeepSeek)账号类型、API 协议与端点 ── const accountMode = ref('payg') const openCodeAccountMode = ref('zen') +// Ollama Cloud 双额度模式:legacy(5h/7d 滚动窗口)/ credits(月度美元信用池)。 +const ollamaAccountMode = ref('ollama_legacy') +// credits 模式的月度信用额度录入(USD);提交时解析,仅 credits 模式写入凭据。 +const ollamaMonthlyCreditUsdInput = ref('60') // API 协议决定转发端点与格式:cc=现有转换链,anthropic=原生直通(Claude Code), // responses=deepseek / kimi 原生 Responses 端点(Codex)。与账号类型正交。 const apiProtocol = ref('adaptive') @@ -4192,7 +4298,7 @@ const adaptiveBaseUrls = ref>({ }) const isCNPlatform = computed(() => isCNProviderPlatform(form.platform)) const isOpenCodeGoPlatform = computed(() => form.platform === 'opencode_go') -const isMultiProtocolPlatform = computed(() => isCNPlatform.value || isOpenCodeGoPlatform.value) +const isMultiProtocolPlatform = computed(() => isCNPlatform.value || isOpenCodeGoPlatform.value || form.platform === 'ollama_cloud') function currentOpenCodeOrCNMode(): CnAccountMode | OpenCodeAccountMode { return isOpenCodeGoPlatform.value ? openCodeAccountMode.value : accountMode.value } @@ -4204,8 +4310,9 @@ const cnPresetPlatform = computed(() => { } return 'kimi' }) -const adaptivePresetPlatform = computed(() => { +const adaptivePresetPlatform = computed(() => { if (form.platform === 'opencode_go') return 'opencode_go' + if (form.platform === 'ollama_cloud') return 'ollama_cloud' return cnPresetPlatform.value }) // 当前平台可选的协议档(responses 仅 deepseek / kimi)。 @@ -4230,7 +4337,7 @@ const cnAdaptiveProtocolOptions = computed { return 'border-rose-500 bg-rose-50 dark:bg-rose-900/20' case 'opencode_go': return 'border-amber-500 bg-amber-50 dark:bg-amber-900/20' + case 'ollama_cloud': + return 'border-stone-500 bg-stone-50 dark:bg-stone-900/20' default: return 'border-primary-500 bg-primary-50 dark:bg-primary-900/20' } @@ -4264,6 +4373,8 @@ const cnAccentIconClass = computed(() => { return 'bg-rose-500 text-white' case 'opencode_go': return 'bg-amber-500 text-white' + case 'ollama_cloud': + return 'bg-stone-500 text-white' default: return 'bg-primary-500 text-white' } @@ -4298,6 +4409,17 @@ function selectTypeSafePlatform() { apiKeyBaseUrl.value = 'https://api.typesafe.ai' allowedModels.value = ['jev-latest'] } +// 切换到 Ollama Cloud:强制 apikey 类型,账号模式回落 legacy,协议回落 adaptive, +// 端点重置为平台默认(ollama 的 base url 预设不区分账号模式,mode 参数仅为满足签名)。 +function selectOllamaCloudPlatform() { + form.platform = 'ollama_cloud' + form.type = 'apikey' + accountCategory.value = 'apikey' + apiProtocol.value = 'adaptive' + ollamaAccountMode.value = 'ollama_legacy' + apiKeyBaseUrl.value = defaultCNBaseUrl('ollama_cloud', accountMode.value, 'adaptive') + resetAdaptiveBaseUrls('ollama_cloud', accountMode.value) +} // 账号类型 / 协议变更时同步默认 base url。 watch(openCodeAccountMode, (mode, previousMode) => { if (!isOpenCodeGoPlatform.value) return @@ -5345,6 +5467,8 @@ const resetForm = () => { addMethod.value = 'oauth' accountMode.value = 'payg' openCodeAccountMode.value = 'zen' + ollamaAccountMode.value = 'ollama_legacy' + ollamaMonthlyCreditUsdInput.value = '60' apiProtocol.value = 'adaptive' openCodeGoProtocolRules.value = cloneOpenCodeGoProtocolRules(defaultOpenCodeProtocolRules('zen')) adaptiveBaseUrls.value = { chat_completions: '', anthropic: '', responses: '' } @@ -5820,11 +5944,22 @@ const handleSubmit = async () => { credentials.tier_id = geminiTierAIStudio.value } - // 国产供应商:账号模式 + 协议 + 对应端点写入凭据;后端按 account_mode 路由 - // 额度/余额探测,按 api_protocol 路由转发端点与格式。注意 CN apikey 走本函数 - // 的通用路径(直接 doCreateAccount),不经过 createAccountAndFinish。 - if (isCNProviderPlatform(form.platform) || form.platform === 'opencode_go') { - credentials.account_mode = form.platform === 'opencode_go' ? openCodeAccountMode.value : accountMode.value + // 国产供应商 / OpenCode / Ollama Cloud:账号模式 + 协议 + 对应端点写入凭据;后端按 + // account_mode 路由额度/余额探测,按 api_protocol 路由转发端点与格式。注意这些 apikey + // 平台走本函数的通用路径(直接 doCreateAccount),不经过 createAccountAndFinish。 + if (isCNProviderPlatform(form.platform) || form.platform === 'opencode_go' || form.platform === 'ollama_cloud') { + if (form.platform === 'ollama_cloud') { + // Ollama Cloud 双额度模式:credits 需同时录入月度信用额度(USD)作为分母。 + credentials.account_mode = ollamaAccountMode.value + if (ollamaAccountMode.value === 'ollama_credits') { + const monthlyCreditUsd = Number.parseFloat(ollamaMonthlyCreditUsdInput.value) + if (Number.isFinite(monthlyCreditUsd) && monthlyCreditUsd > 0) { + credentials.monthly_credit_usd = monthlyCreditUsd + } + } + } else { + credentials.account_mode = form.platform === 'opencode_go' ? openCodeAccountMode.value : accountMode.value + } credentials.api_protocol = apiProtocol.value if (apiProtocol.value === 'adaptive') { const defaults = defaultCNAdaptiveBaseUrls( diff --git a/frontend/src/components/account/__tests__/CreateAccountModal.spec.ts b/frontend/src/components/account/__tests__/CreateAccountModal.spec.ts index f9cf78675a..02c1dd9d3b 100644 --- a/frontend/src/components/account/__tests__/CreateAccountModal.spec.ts +++ b/frontend/src/components/account/__tests__/CreateAccountModal.spec.ts @@ -712,3 +712,124 @@ describe('CreateAccountModal OpenAI long-context billing', () => { expect(createOpenAICodexPATMock.mock.calls[0]?.[0]?.extra?.openai_long_context_billing_enabled).toBe(false) }) }) + +describe('CreateAccountModal Ollama Cloud protocol and quota mode', () => { + beforeEach(() => { + createAccountMock.mockReset().mockResolvedValue({ id: 42, platform: 'ollama_cloud', type: 'apikey' }) + }) + + afterEach(() => { + vi.clearAllMocks() + }) + + async function selectOllamaCloudPlatform(wrapper: ReturnType) { + await selectButtonByText(wrapper, 'Ollama') + } + + it('shows the protocol selector with adaptive defaults when Ollama Cloud is selected', async () => { + const wrapper = mountModal() + await selectOllamaCloudPlatform(wrapper) + + // 协议选择器出现且默认 adaptive(adaptive 区渲染三个原生端点输入框) + expect(wrapper.findAll('button').some((b) => b.text().includes('admin.accounts.cnProviders.apiProtocol.adaptive'))).toBe(true) + expect(wrapper.find('[data-testid="cn-adaptive-base-url-chat_completions"]').exists()).toBe(true) + expect((wrapper.get('[data-testid="cn-adaptive-base-url-chat_completions"]').element as HTMLInputElement).value).toBe('https://ollama.com/v1') + // anthropic 端点预设不带 /v1(/v1/v1 静默 404 坑) + const anthropicUrl = (wrapper.get('[data-testid="cn-adaptive-base-url-anthropic"]').element as HTMLInputElement).value + expect(anthropicUrl).toBe('https://ollama.com') + expect(anthropicUrl.includes('/v1')).toBe(false) + expect((wrapper.get('[data-testid="cn-adaptive-base-url-responses"]').element as HTMLInputElement).value).toBe('https://ollama.com/v1') + }) + + it('submits adaptive ollama_cloud credentials with api_protocol and api_base_urls', async () => { + const wrapper = mountModal() + await selectOllamaCloudPlatform(wrapper) + await wrapper.get('form#create-account-form input[type="text"]').setValue('ollama cloud') + await wrapper.get('form#create-account-form input[type="password"]').setValue('sk-ollama') + await wrapper.get('form#create-account-form').trigger('submit.prevent') + await flushPromises() + + expect(createAccountMock).toHaveBeenCalledTimes(1) + const credentials = createAccountMock.mock.calls[0]?.[0]?.credentials + expect(credentials).toMatchObject({ + account_mode: 'ollama_legacy', + api_protocol: 'adaptive', + base_url: 'https://ollama.com/v1', + api_base_urls: { + chat_completions: 'https://ollama.com/v1', + anthropic: 'https://ollama.com', + responses: 'https://ollama.com/v1' + } + }) + expect('monthly_credit_usd' in credentials).toBe(false) + }) + + it('prefills the locked anthropic protocol endpoint without the /v1 suffix', async () => { + const wrapper = mountModal() + await selectOllamaCloudPlatform(wrapper) + await selectButtonByText(wrapper, 'admin.accounts.cnProviders.apiProtocol.anthropic') + + const baseUrlInput = wrapper + .findAll('form#create-account-form input[type="text"]') + .map((input) => input.element as HTMLInputElement) + .find((input) => input.value.startsWith('https://ollama.com')) + expect(baseUrlInput).toBeDefined() + expect(baseUrlInput?.value).toBe('https://ollama.com') + expect(baseUrlInput?.value.includes('/v1')).toBe(false) + }) + + it('submits ollama_credits mode with the monthly credit amount', async () => { + const wrapper = mountModal() + await selectOllamaCloudPlatform(wrapper) + await selectButtonByText(wrapper, 'admin.accounts.ollamaCloud.accountMode.credits') + await wrapper.get('form#create-account-form input[type="text"]').setValue('ollama credits') + await wrapper.get('form#create-account-form input[type="password"]').setValue('sk-ollama') + await wrapper.get('form#create-account-form').trigger('submit.prevent') + await flushPromises() + + expect(createAccountMock).toHaveBeenCalledTimes(1) + const credentials = createAccountMock.mock.calls[0]?.[0]?.credentials + expect(credentials).toMatchObject({ + account_mode: 'ollama_credits', + api_protocol: 'adaptive', + monthly_credit_usd: 60 + }) + }) + + it('applies the 300 USD quick preset to the monthly credit input', async () => { + const wrapper = mountModal() + await selectOllamaCloudPlatform(wrapper) + await selectButtonByText(wrapper, 'admin.accounts.ollamaCloud.accountMode.credits') + await wrapper.get('[data-testid="ollama-credit-preset-300"]').trigger('click') + await wrapper.get('form#create-account-form input[type="text"]').setValue('ollama credits 300') + await wrapper.get('form#create-account-form input[type="password"]').setValue('sk-ollama') + await wrapper.get('form#create-account-form').trigger('submit.prevent') + await flushPromises() + + const credentials = createAccountMock.mock.calls[0]?.[0]?.credentials + expect(credentials).toMatchObject({ + account_mode: 'ollama_credits', + monthly_credit_usd: 300 + }) + }) + + it('submits a locked protocol with the legacy mode and no credit field', async () => { + const wrapper = mountModal() + await selectOllamaCloudPlatform(wrapper) + await selectButtonByText(wrapper, 'admin.accounts.cnProviders.apiProtocol.chatCompletions') + await wrapper.get('form#create-account-form input[type="text"]').setValue('ollama cc') + await wrapper.get('form#create-account-form input[type="password"]').setValue('sk-ollama') + await wrapper.get('form#create-account-form').trigger('submit.prevent') + await flushPromises() + + expect(createAccountMock).toHaveBeenCalledTimes(1) + const credentials = createAccountMock.mock.calls[0]?.[0]?.credentials + expect(credentials).toMatchObject({ + account_mode: 'ollama_legacy', + api_protocol: 'chat_completions', + base_url: 'https://ollama.com/v1' + }) + expect('monthly_credit_usd' in credentials).toBe(false) + expect('api_base_urls' in credentials).toBe(false) + }) +}) diff --git a/frontend/src/components/account/__tests__/credentialsBuilder.cnAdaptive.spec.ts b/frontend/src/components/account/__tests__/credentialsBuilder.cnAdaptive.spec.ts index caadfa3fa9..6a390c8c39 100644 --- a/frontend/src/components/account/__tests__/credentialsBuilder.cnAdaptive.spec.ts +++ b/frontend/src/components/account/__tests__/credentialsBuilder.cnAdaptive.spec.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from 'vitest' -import { cnSupportsNativeResponses, defaultCNAdaptiveBaseUrls } from '../credentialsBuilder' +import { cnSupportsNativeResponses, defaultCNAdaptiveBaseUrls, defaultCNBaseUrl, isMultiProtocolApiKeyPlatform } from '../credentialsBuilder' describe('cnSupportsNativeResponses', () => { it('is true for DeepSeek, Kimi, and MiniMax', () => { @@ -57,3 +57,38 @@ describe('defaultCNAdaptiveBaseUrls', () => { expect(defaultCNAdaptiveBaseUrls('minimax', 'coding')).toEqual(expected) }) }) + +describe('ollama_cloud base url presets (E11 + E12)', () => { + it('advertises native responses support', () => { + expect(cnSupportsNativeResponses('ollama_cloud')).toBe(true) + }) + + it('is recognized as a multi-protocol apikey platform', () => { + expect(isMultiProtocolApiKeyPlatform('ollama_cloud')).toBe(true) + }) + + // anthropic 预设不带 /v1:出站由后端拼 /v1/messages,预设带 /v1 会拼成 + // /v1/v1/messages 静默 404(本分支早前修过的真实缺陷)。 + it.each([ + ['anthropic', 'https://ollama.com'], + ['chat_completions', 'https://ollama.com/v1'], + ['responses', 'https://ollama.com/v1'] + ])('resolves the %s preset without depending on account mode', (protocol, expected) => { + expect(defaultCNBaseUrl('ollama_cloud', 'payg', protocol)).toBe(expected) + expect(defaultCNBaseUrl('ollama_cloud', 'coding', protocol)).toBe(expected) + }) + + it('keeps the anthropic preset free of the /v1 suffix', () => { + const anthropicPreset = defaultCNBaseUrl('ollama_cloud', 'payg', 'anthropic') + expect(anthropicPreset).toBe('https://ollama.com') + expect(anthropicPreset.includes('/v1')).toBe(false) + }) + + it('fills all three native endpoints for adaptive mode', () => { + expect(defaultCNAdaptiveBaseUrls('ollama_cloud', 'payg')).toEqual({ + chat_completions: 'https://ollama.com/v1', + anthropic: 'https://ollama.com', + responses: 'https://ollama.com/v1' + }) + }) +}) diff --git a/frontend/src/components/account/credentialsBuilder.ts b/frontend/src/components/account/credentialsBuilder.ts index 43c487c927..ec21294ed6 100644 --- a/frontend/src/components/account/credentialsBuilder.ts +++ b/frontend/src/components/account/credentialsBuilder.ts @@ -260,6 +260,7 @@ export const GROK_BASE_URL_PRESETS: GrokBaseUrlPreset[] = [ export type CnAccountMode = 'payg' | 'coding' export type OpenCodeAccountMode = 'zen' | 'go' +export type OllamaCloudAccountMode = 'ollama_legacy' | 'ollama_credits' export type CnProviderPlatform = 'kimi' | 'zhipu' | 'deepseek' | 'minimax' /** deepseek / kimi / minimax 支持原生 responses;adaptive 会按入站协议选择原生端点。 */ @@ -270,9 +271,9 @@ export function isCNProviderPlatform(platform: string): platform is CnProviderPl return platform === 'kimi' || platform === 'zhipu' || platform === 'deepseek' || platform === 'minimax' } -/** DeepSeek、Kimi 与 MiniMax 提供原生 Responses 端点。 */ +/** DeepSeek、Kimi 与 MiniMax 提供原生 Responses 端点;Ollama Cloud 自适应支持 /v1/responses。 */ export function cnSupportsNativeResponses(platform: string): boolean { - return platform === 'deepseek' || platform === 'kimi' || platform === 'minimax' || platform === 'opencode_go' + return platform === 'deepseek' || platform === 'kimi' || platform === 'minimax' || platform === 'opencode_go' || platform === 'ollama_cloud' } export const OPENCODE_GO_BASE_URL = 'https://opencode.ai/zen/go/v1' @@ -280,6 +281,12 @@ export const OPENCODE_GO_ANTHROPIC_BASE_URL = 'https://opencode.ai/zen/go' export const OPENCODE_ZEN_BASE_URL = 'https://opencode.ai/zen/v1' export const OPENCODE_ZEN_ANTHROPIC_BASE_URL = 'https://opencode.ai/zen' +// Ollama Cloud 默认端点(与后端 service/domain_constants.go 的 DefaultOllamaCloudBaseURL / +// DefaultOllamaCloudAnthropicBaseURL 一字不差)。anthropic 档不带 /v1:后端按协议拼接 +// /v1/messages,预设若带 /v1 会拼出 /v1/v1/messages 静默 404。 +export const OLLAMA_BASE_URL = 'https://ollama.com/v1' +export const OLLAMA_ANTHROPIC_BASE_URL = 'https://ollama.com' + export function isOpenCodeGoPlatform(platform: string): boolean { return platform === 'opencode_go' } @@ -359,7 +366,7 @@ export function applyOpenCodeGoProtocolRules( } export function isMultiProtocolApiKeyPlatform(platform: string): boolean { - return platform === 'kimi' || platform === 'zhipu' || platform === 'deepseek' || platform === 'minimax' || platform === 'opencode_go' + return platform === 'kimi' || platform === 'zhipu' || platform === 'deepseek' || platform === 'minimax' || platform === 'opencode_go' || platform === 'ollama_cloud' } export interface CnBaseUrlPreset { @@ -425,6 +432,8 @@ export function defaultCNBaseUrl( return 'https://api.minimaxi.com/anthropic' case 'opencode_go': return mode === 'zen' ? OPENCODE_ZEN_ANTHROPIC_BASE_URL : OPENCODE_GO_ANTHROPIC_BASE_URL + case 'ollama_cloud': + return OLLAMA_ANTHROPIC_BASE_URL default: return '' } @@ -443,6 +452,8 @@ export function defaultCNBaseUrl( return 'https://api.minimaxi.com/v1' case 'opencode_go': return mode === 'zen' ? OPENCODE_ZEN_BASE_URL : OPENCODE_GO_BASE_URL + case 'ollama_cloud': + return OLLAMA_BASE_URL default: return '' } @@ -450,7 +461,7 @@ export function defaultCNBaseUrl( /** 返回自适应模式下需要配置的原生协议及其默认端点。 */ export function defaultCNAdaptiveBaseUrls( - platform: CnProviderPlatform | 'opencode_go', + platform: CnProviderPlatform | 'opencode_go' | 'ollama_cloud', mode: CnAccountMode | OpenCodeAccountMode ): Record { return { diff --git a/frontend/src/i18n/locales/en/admin/accounts.ts b/frontend/src/i18n/locales/en/admin/accounts.ts index dfd5d7bf79..2cb0ee110c 100644 --- a/frontend/src/i18n/locales/en/admin/accounts.ts +++ b/frontend/src/i18n/locales/en/admin/accounts.ts @@ -288,6 +288,15 @@ export default { usageWindowsHint: '"5h / 7d" are the upstream account\'s official rolling usage windows (e.g. OpenAI ChatGPT, Claude). They are imposed by the upstream provider on the account itself — not configured by sub2api, and unrelated to the models you map. Usage resets automatically once each window rolls over, and the limit cannot be lifted from within sub2api.', ollamaCloud: { title: 'Ollama Cloud usage', + accountMode: { + title: 'Account mode', + legacy: 'Legacy (rolling window)', + legacyDesc: 'Metered and monitored via the official 5h / 7d rolling windows', + credits: 'Credits (monthly pool)', + creditsDesc: 'Metered and monitored via a monthly USD credit pool', + monthlyCreditUsd: 'Monthly credit (USD)', + monthlyCreditUsdPlaceholder: 'e.g. 60' + }, sessionSecurityHint: 'The browser session is encrypted at rest and sent only to the fixed official settings URL.', configured: 'Configured', notConfigured: 'Not configured', diff --git a/frontend/src/i18n/locales/zh/admin/accounts.ts b/frontend/src/i18n/locales/zh/admin/accounts.ts index 3aa407e6a5..3217f89fc8 100644 --- a/frontend/src/i18n/locales/zh/admin/accounts.ts +++ b/frontend/src/i18n/locales/zh/admin/accounts.ts @@ -136,6 +136,15 @@ export default { usageWindowsHint: '“5h / 7d”是上游账号(如 OpenAI ChatGPT、Claude)官方的滚动用量窗口限制,由上游对账号设定,并非 sub2api 配置,也与你映射的模型无关。窗口滚动到期后用量会自动重置,无法在 sub2api 端解除该限制。', ollamaCloud: { title: 'Ollama Cloud 用量', + accountMode: { + title: '账号模式', + legacy: 'Legacy(滚动窗口)', + legacyDesc: '按官方 5h / 7d 滚动窗口配额计费与监控', + credits: 'Credits(月度信用池)', + creditsDesc: '按月度美元信用额度计费与监控', + monthlyCreditUsd: '月度信用额度(USD)', + monthlyCreditUsdPlaceholder: '例如 60' + }, sessionSecurityHint: '浏览器会话会加密落库,且只发送到固定的 Ollama 官方设置页。', configured: '已配置', notConfigured: '未配置', From c6c2c0733f75a95c8bfee9f4506658e8b4bd808d Mon Sep 17 00:00:00 2001 From: alfadb Date: Sun, 13 Sep 2026 08:21:03 +0800 Subject: [PATCH 29/81] feat(usage): expose ollama cloud quota mode and monthly credit MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit D7+E3+E26:把 ollama_cloud 双额度模式(legacy 滚动窗口 / credits 月度 信用池)在用量展示上打通。 - 后端 OllamaCloudUsageState 新增 mode(复用 GetOllamaCloudAccountMode 解析 credentials.account_mode,非 ollama_cloud 平台留空)与 monthly_credit_usd(*float64,读 credentials.monthly_credit_usd, 缺失/非法/非正数时为 nil,不报错不填假值) - dto mapper 对 platform=ollama_cloud 一律下发 state:不合格账号也要把 eligible_reason 送到前端用量格;legacy 宿主平台维持仅 eligible 下发 - 前端类型补 eligible_reason / mode / monthly_credit_usd 声明 - 用量格按 mode 分支:legacy 渲染 5h/7d 窗口 + 追加余额文本;credits 隐藏窗口条、渲染月池进度((pool-balance)/pool clamp,前端派生)+ 余额/分母文本 + 快照时间;池缺失时只显示原始余额文本 - 不合格账号展示 eligible_reason 可解释提示(不再空白占位) - AccountUsageCell 对 ollama_cloud 本体平台按 state 存在与否挂载 cell 派生展示百分比按规格放前端(D7 二选一);未动建号表单、渠道监控、 ratelimit_service 与迁移。 --- .../account_mapper_ollama_cloud_usage_test.go | 57 ++++++++++ backend/internal/handler/dto/mappers.go | 6 +- backend/internal/service/account.go | 30 ++++++ .../internal/service/ollama_cloud_usage.go | 20 +++- .../service/ollama_cloud_usage_test.go | 91 ++++++++++++++++ .../components/account/AccountUsageCell.vue | 7 +- .../account/OllamaCloudUsageCell.vue | 101 +++++++++++++++--- .../__tests__/AccountUsageCell.spec.ts | 33 +++++- .../__tests__/OllamaCloudUsageCell.spec.ts | 73 ++++++++++++- .../src/i18n/locales/en/admin/accounts.ts | 6 ++ .../src/i18n/locales/zh/admin/accounts.ts | 6 ++ frontend/src/types/index.ts | 6 ++ 12 files changed, 412 insertions(+), 24 deletions(-) create mode 100644 backend/internal/handler/dto/account_mapper_ollama_cloud_usage_test.go diff --git a/backend/internal/handler/dto/account_mapper_ollama_cloud_usage_test.go b/backend/internal/handler/dto/account_mapper_ollama_cloud_usage_test.go new file mode 100644 index 0000000000..5257cb5ec9 --- /dev/null +++ b/backend/internal/handler/dto/account_mapper_ollama_cloud_usage_test.go @@ -0,0 +1,57 @@ +package dto + +import ( + "testing" + + "github.com/stretchr/testify/require" + + "github.com/Wei-Shaw/sub2api/internal/service" +) + +// ollama_cloud 平台账号无论合格与否都下发 ollama_cloud_usage state:不合格 +// 时管理端要靠 EligibleReason 解释「为什么没有窗口/余额」。legacy 宿主平台 +// (openai/kimi 等)无法与普通同平台账号区分,不合格时不挂 state。 +func TestAccountFromServiceShallow_OllamaCloudUsageAttachment(t *testing.T) { + t.Parallel() + + ollamaCloud := func() *service.Account { + return &service.Account{ + ID: 1, + Platform: service.PlatformOllamaCloud, + Type: service.AccountTypeAPIKey, + Credentials: map[string]any{ + "base_url": "https://ollama.example.test", // 反代 → 不合格 + "api_key": "key-1", + }, + } + } + + ineligible := AccountFromServiceShallow(ollamaCloud()) + require.NotNil(t, ineligible.OllamaCloudUsage) + require.False(t, ineligible.OllamaCloudUsage.Eligible) + require.Equal(t, "unsupported_base_url", ineligible.OllamaCloudUsage.EligibleReason) + + eligibleAccount := ollamaCloud() + eligibleAccount.Credentials["base_url"] = "https://ollama.com" + eligible := AccountFromServiceShallow(eligibleAccount) + require.NotNil(t, eligible.OllamaCloudUsage) + require.True(t, eligible.OllamaCloudUsage.Eligible) + + // legacy 宿主平台不合格账号:不挂 state(普通 openai 账号不受影响)。 + cnHost := &service.Account{ + ID: 2, + Platform: service.PlatformKimi, + Type: service.AccountTypeAPIKey, + Credentials: map[string]any{"base_url": "https://api.kimi.com", "api_key": "key-2"}, + } + require.Nil(t, AccountFromServiceShallow(cnHost).OllamaCloudUsage) + + // 完全无关平台(如 gemini):照旧不挂 state。 + gemini := &service.Account{ + ID: 3, + Platform: service.PlatformGemini, + Type: service.AccountTypeOAuth, + Credentials: map[string]any{}, + } + require.Nil(t, AccountFromServiceShallow(gemini).OllamaCloudUsage) +} diff --git a/backend/internal/handler/dto/mappers.go b/backend/internal/handler/dto/mappers.go index 42a1d82594..6ff1858b51 100644 --- a/backend/internal/handler/dto/mappers.go +++ b/backend/internal/handler/dto/mappers.go @@ -238,7 +238,11 @@ func AccountFromServiceShallow(a *service.Account) *Account { redactedCreds, credsStatus := RedactCredentials(a.Credentials) extra := redactAccountManagedExtra(a.Extra) var ollamaCloudUsage *service.OllamaCloudUsageState - if state := service.OllamaCloudUsageStateFromAccount(a); state.Eligible { + // platform=ollama_cloud 一律下发 state:不合格账号(反代 base_url、oauth + // 类型)也要把 EligibleReason 送到前端用量格做可解释提示。legacy 宿主 + // 平台(openai/anthropic/国产)无法与普通同平台账号区分,维持仅在 + // eligible 时下发,避免给正常 CN/OpenAI 账号挂上无意义的 ineligible 状态。 + if state := service.OllamaCloudUsageStateFromAccount(a); state.Eligible || a.Platform == service.PlatformOllamaCloud { ollamaCloudUsage = state } var openCodeGoUsage *service.OpenCodeGoUsageState diff --git a/backend/internal/service/account.go b/backend/internal/service/account.go index 7ba8b76d0b..b08f2cad5a 100644 --- a/backend/internal/service/account.go +++ b/backend/internal/service/account.go @@ -443,6 +443,36 @@ func (a *Account) GetCredentialAsInt64(key string) int64 { return 0 } +// GetCredentialAsFloat64 返回浮点型凭据值,缺失或无法解析时返回 0。与 +// GetCredentialAsInt64 同样的类型容忍(JSONB 数字为 float64/json.Number, +// 运营也可能手写成字符串),供 Ollama Cloud monthly_credit_usd 等金额键读取。 +func (a *Account) GetCredentialAsFloat64(key string) float64 { + if a == nil || a.Credentials == nil { + return 0 + } + val, ok := a.Credentials[key] + if !ok || val == nil { + return 0 + } + switch v := val.(type) { + case float64: + return v + case int64: + return float64(v) + case int: + return float64(v) + case json.Number: + if f, err := v.Float64(); err == nil { + return f + } + case string: + if f, err := strconv.ParseFloat(strings.TrimSpace(v), 64); err == nil { + return f + } + } + return 0 +} + func (a *Account) IsTempUnschedulableEnabled() bool { if a.Credentials == nil { return false diff --git a/backend/internal/service/ollama_cloud_usage.go b/backend/internal/service/ollama_cloud_usage.go index 5fee972c36..f9abc53c83 100644 --- a/backend/internal/service/ollama_cloud_usage.go +++ b/backend/internal/service/ollama_cloud_usage.go @@ -163,7 +163,17 @@ type OllamaCloudUsageState struct { // EligibleReason 说明 eligible=false 的具体原因("" 表示合格): // platform_not_eligible / wrong_account_type / unsupported_base_url, // 供管理端区分「平台不合规 / 类型不对 / base_url 反代」。 - EligibleReason string `json:"eligible_reason,omitempty"` + EligibleReason string `json:"eligible_reason,omitempty"` + // Mode 是 Ollama Cloud 双额度模式:ollama_legacy(5h/7d 滚动窗口)/ + // ollama_credits(月度美元信用池),由 GetOllamaCloudAccountMode 解析 + // credentials.account_mode,未设置或值不认识时保守默认 legacy。 + // 非 ollama_cloud 平台(含用量白名单里的 legacy 宿主平台)留空。 + Mode string `json:"mode,omitempty"` + // MonthlyCreditUSD 是 credits 模式的月度信用池分母(USD),读 + // credentials.monthly_credit_usd(建号表单录入)。凭据缺失、无法解析或 + // 非正数时为 nil——表示「无该字段」,不报错也不填假值,前端回落为只 + // 展示原始余额文本。 + MonthlyCreditUSD *float64 `json:"monthly_credit_usd,omitempty"` Configured bool `json:"configured"` AutoRefreshEnabled bool `json:"auto_refresh_enabled"` EncryptionKeyConfigured bool `json:"encryption_key_configured"` @@ -1024,6 +1034,14 @@ func OllamaCloudUsageStateFromAccount(account *Account) *OllamaCloudUsageState { return state } state.AccountID = account.ID + // mode / monthly credit 在资格判定之前填充:不合格的 ollama_cloud 账号 + // (反代 base_url、oauth 类型)同样带着额度模式与原因码下发,供管理端 + // 解释「为什么没有窗口/余额」。GetOllamaCloudAccountMode 对非 + // ollama_cloud 平台返回空串,Mode 随 omitempty 留空。 + state.Mode = account.GetOllamaCloudAccountMode() + if credit := account.GetCredentialAsFloat64("monthly_credit_usd"); credit > 0 { + state.MonthlyCreditUSD = &credit + } state.EligibleReason = ollamaCloudUsageEligibilityReason(account) state.Eligible = state.EligibleReason == "" if !state.Eligible { diff --git a/backend/internal/service/ollama_cloud_usage_test.go b/backend/internal/service/ollama_cloud_usage_test.go index f15c30f2b4..d8857e6b48 100644 --- a/backend/internal/service/ollama_cloud_usage_test.go +++ b/backend/internal/service/ollama_cloud_usage_test.go @@ -566,6 +566,97 @@ func TestOllamaCloudUsageStateEligibleReason(t *testing.T) { require.Empty(t, state.EligibleReason) } +// OllamaCloudUsageState 的双额度字段(D7):mode 由 GetOllamaCloudAccountMode +// 解析(缺省/不认识 → legacy,非 ollama_cloud 平台留空),monthly_credit_usd +// 缺失或非法时为 nil(无该字段语义,不报错不填假值)。 +func TestOllamaCloudUsageStateModeAndMonthlyCredit(t *testing.T) { + tests := []struct { + name string + credentials map[string]any + wantMode string + wantMonthlyCredit *float64 + }{ + { + name: "未设置 account_mode 默认 legacy,无月度信用池", + credentials: map[string]any{}, + wantMode: AccountModeOllamaLegacy, + }, + { + name: "显式 legacy", + credentials: map[string]any{"account_mode": AccountModeOllamaLegacy}, + wantMode: AccountModeOllamaLegacy, + }, + { + name: "credits + 月度信用池 60(JSONB 数字为 float64)", + credentials: map[string]any{"account_mode": AccountModeOllamaCredits, "monthly_credit_usd": float64(60)}, + wantMode: AccountModeOllamaCredits, + wantMonthlyCredit: float64Ptr(60), + }, + { + name: "月度信用池手写字符串也可解析", + credentials: map[string]any{"account_mode": AccountModeOllamaCredits, "monthly_credit_usd": "300"}, + wantMode: AccountModeOllamaCredits, + wantMonthlyCredit: float64Ptr(300), + }, + { + name: "credits 但信用池缺失 → 只透出 mode", + credentials: map[string]any{"account_mode": AccountModeOllamaCredits}, + wantMode: AccountModeOllamaCredits, + }, + { + name: "信用池为 0 / 负数 / 垃圾值 → 视为无该字段", + credentials: map[string]any{"account_mode": AccountModeOllamaCredits, "monthly_credit_usd": float64(0)}, + wantMode: AccountModeOllamaCredits, + }, + { + name: "不认识的 mode 值保守回落 legacy", + credentials: map[string]any{"account_mode": "ollama_turbo"}, + wantMode: AccountModeOllamaLegacy, + }, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + account := ollamaUsageAccount(1) + account.Platform = PlatformOllamaCloud + account.Credentials = map[string]any{"base_url": "https://ollama.com", "api_key": "key-1"} + for key, value := range test.credentials { + account.Credentials[key] = value + } + + state := OllamaCloudUsageStateFromAccount(account) + require.True(t, state.Eligible) + require.Equal(t, test.wantMode, state.Mode) + if test.wantMonthlyCredit == nil { + require.Nil(t, state.MonthlyCreditUSD) + } else { + require.NotNil(t, state.MonthlyCreditUSD) + require.InDelta(t, *test.wantMonthlyCredit, *state.MonthlyCreditUSD, 1e-9) + } + }) + } + + // 非 ollama_cloud 平台(legacy 宿主平台)mode 留空,JSON 随 omitempty 缺省。 + hostAccount := ollamaUsageAccount(2) + hostAccount.Credentials["account_mode"] = AccountModeOllamaCredits + hostState := OllamaCloudUsageStateFromAccount(hostAccount) + require.Empty(t, hostState.Mode) + + payload, err := json.Marshal(hostState) + require.NoError(t, err) + require.NotContains(t, string(payload), `"mode"`) + + // credits 账号的 JSON 形状:mode + monthly_credit_usd 均按 tag 透出。 + creditsAccount := ollamaUsageAccount(3) + creditsAccount.Platform = PlatformOllamaCloud + creditsAccount.Credentials["account_mode"] = AccountModeOllamaCredits + creditsAccount.Credentials["monthly_credit_usd"] = float64(60) + creditsState := OllamaCloudUsageStateFromAccount(creditsAccount) + payload, err = json.Marshal(creditsState) + require.NoError(t, err) + require.Contains(t, string(payload), `"mode":"ollama_credits"`) + require.Contains(t, string(payload), `"monthly_credit_usd":60`) +} + // 错误文案由平台白名单派生(D2):platform 化后必须包含 ollama_cloud,不再 // 残留「OpenAI or Anthropic」旧文案;错误码是对外契约,保持不变。 func TestOllamaCloudUsageAccountInvalidMessageDerivedFromWhitelist(t *testing.T) { diff --git a/frontend/src/components/account/AccountUsageCell.vue b/frontend/src/components/account/AccountUsageCell.vue index 598064c036..5a5770fea9 100644 --- a/frontend/src/components/account/AccountUsageCell.vue +++ b/frontend/src/components/account/AccountUsageCell.vue @@ -596,8 +596,11 @@
+ @@ -666,7 +669,7 @@
-
diff --git a/frontend/src/components/account/OllamaCloudUsageCell.vue b/frontend/src/components/account/OllamaCloudUsageCell.vue index 17c09050c0..9935f0a94b 100644 --- a/frontend/src/components/account/OllamaCloudUsageCell.vue +++ b/frontend/src/components/account/OllamaCloudUsageCell.vue @@ -4,22 +4,50 @@ class="min-w-0 max-w-full space-y-1" data-testid="ollama-cloud-usage-cell" > + + + - +
+ {{ balanceLabel }} +
+ +
+ {{ snapshotTimeLabel }} +
+ + {{ eligibleReasonLabel }} - @@ -62,6 +97,44 @@ const { t } = useI18n() const state = ref(props.account.ollama_cloud_usage) const refreshing = ref(false) const snapshot = computed(() => state.value?.snapshot) +const isCredits = computed(() => state.value?.mode === 'ollama_credits') + +// balance 是官方文本(如 "$12.00"),派生池进度需要数值:剥掉货币符号与 +// 千分位后 parseFloat;解析不了返回 null(回落为只显示原始文本)。 +const balanceNumber = computed(() => { + const raw = snapshot.value?.data?.balance + if (!raw) return null + const parsed = Number.parseFloat(raw.replace(/[^0-9.]/g, '')) + return Number.isFinite(parsed) ? parsed : null +}) + +// credits 模式的月度信用池已用百分比:(pool - balance) / pool,clamp 0-100。 +const creditsPoolUtilization = computed(() => { + const pool = state.value?.monthly_credit_usd + if (!isCredits.value || !pool || pool <= 0 || balanceNumber.value === null) return null + const used = ((pool - balanceNumber.value) / pool) * 100 + return Math.min(Math.max(used, 0), 100) +}) + +const balanceText = computed(() => snapshot.value?.data?.balance ?? '') +const balanceLabel = computed(() => { + const prefix = `${t('admin.accounts.ollamaCloud.balance')}: ${balanceText.value}` + const pool = state.value?.monthly_credit_usd + return isCredits.value && pool && pool > 0 ? `${prefix} / $${pool}` : prefix +}) + +const eligibleReasonLabel = computed(() => { + const reason = state.value?.eligible_reason + return reason ? t(`admin.accounts.ollamaCloud.eligibleReason.${reason}`) : '' +}) + +const snapshotTimeLabel = computed(() => { + const raw = snapshot.value?.fetched_at + if (!raw) return '' + const date = new Date(raw) + const formatted = Number.isNaN(date.getTime()) ? raw : date.toLocaleString() + return `${t('admin.accounts.ollamaCloud.updatedAt')}: ${formatted}` +}) watch(() => props.account.ollama_cloud_usage, (next) => { state.value = next diff --git a/frontend/src/components/account/__tests__/AccountUsageCell.spec.ts b/frontend/src/components/account/__tests__/AccountUsageCell.spec.ts index 2daa85e6e9..56e60d467a 100644 --- a/frontend/src/components/account/__tests__/AccountUsageCell.spec.ts +++ b/frontend/src/components/account/__tests__/AccountUsageCell.spec.ts @@ -290,17 +290,14 @@ describe('AccountUsageCell', () => { expect(getUsage).not.toHaveBeenCalled() }) - it.each([ - { name: '无 ollama_cloud_usage', usage: undefined }, - { name: 'eligible=false', usage: makeOllamaUsage(9101, { eligible: false }) } - ])('ollama_cloud apikey 账号($name)渲染占位而非 CN quota 格', async ({ usage }) => { + it('ollama_cloud apikey 账号(无 ollama_cloud_usage)渲染占位而非 CN quota 格', async () => { const wrapper = mount(AccountUsageCell, { props: { account: makeAccount({ id: 9101, platform: 'ollama_cloud', type: 'apikey', - ollama_cloud_usage: usage + ollama_cloud_usage: undefined }) }, global: { @@ -316,6 +313,32 @@ describe('AccountUsageCell', () => { expect(getUsage).not.toHaveBeenCalled() }) + // 不合格(如反代 base_url):后端也下发 state(带 eligible_reason),cell + // 照常挂载以展示可解释提示,而不是空白占位。 + it('ollama_cloud apikey 账号(eligible=false)仍渲染 OllamaCloudUsageCell 展示原因', async () => { + const wrapper = mount(AccountUsageCell, { + props: { + account: makeAccount({ + id: 9102, + platform: 'ollama_cloud', + type: 'apikey', + ollama_cloud_usage: makeOllamaUsage(9102, { + eligible: false, + eligible_reason: 'unsupported_base_url' + }) + }) + }, + global: { + stubs: { ...cnUsageCellStubs, UsageProgressBar: true, AccountQuotaInfo: true } + } + }) + + await flushPromises() + + expect(wrapper.find('[data-test="embedded-ollama"]').exists()).toBe(true) + expect(getUsage).not.toHaveBeenCalled() + }) + it.each(['opencode_go', 'kimi', 'zhipu', 'deepseek', 'minimax'] as const)( '%s 平台 OpenCode Go eligible 时只渲染 OpenCode 用量单元格并跳过 CN 子单元格', async (platform) => { diff --git a/frontend/src/components/account/__tests__/OllamaCloudUsageCell.spec.ts b/frontend/src/components/account/__tests__/OllamaCloudUsageCell.spec.ts index e38f3d3729..49febab9a8 100644 --- a/frontend/src/components/account/__tests__/OllamaCloudUsageCell.spec.ts +++ b/frontend/src/components/account/__tests__/OllamaCloudUsageCell.spec.ts @@ -27,6 +27,7 @@ vi.mock('vue-i18n', async () => { const usageState = (): OllamaCloudUsageState => ({ account_id: 7, eligible: true, + mode: 'ollama_legacy', configured: true, auto_refresh_enabled: false, encryption_key_configured: true, @@ -104,8 +105,55 @@ describe('OllamaCloudUsageCell', () => { expect(query.classes()).toEqual(expect.arrayContaining(['text-blue-600', 'hover:bg-blue-50'])) expect(query.text()).toContain('admin.accounts.usageWindow.activeQuery') expect(wrapper.text()).not.toContain('max') - expect(wrapper.text()).not.toContain('$0') expect(wrapper.text()).not.toContain('gpt-oss:120b-cloud') + // legacy 模式追加 balance 文本(不含信用池分母)。 + const balance = wrapper.get('[data-testid="ollama-cloud-balance"]') + expect(balance.text()).toBe('admin.accounts.ollamaCloud.balance: $0') + }) + + it('renders legacy 5h/7d window bars and skips the pool bar', () => { + const wrapper = mount(OllamaCloudUsageCell, { props: { account: account() } }) + + expect(wrapper.find('[data-testid="ollama-cloud-monthly-pool"]').exists()).toBe(false) + const bars = wrapper.findAllComponents(UsageProgressBar) + expect(bars.map(bar => bar.props('label'))).toEqual(['5h', '7d']) + expect(wrapper.find('[data-testid="ollama-cloud-snapshot-time"]').exists()).toBe(false) + }) + + it('renders the monthly pool bar for credits mode instead of window bars', () => { + const state = usageState() + state.mode = 'ollama_credits' + state.monthly_credit_usd = 60 + state.snapshot!.data!.balance = '$12.00' + + const wrapper = mount(OllamaCloudUsageCell, { props: { account: account(state) } }) + + expect(wrapper.find('[data-testid="ollama-cloud-five-hour"]').exists()).toBe(false) + expect(wrapper.find('[data-testid="ollama-cloud-seven-day"]').exists()).toBe(false) + const bars = wrapper.findAllComponents(UsageProgressBar) + expect(bars).toHaveLength(1) + expect(bars[0].props()).toMatchObject({ + // (60 - 12) / 60 = 80% + label: 'admin.accounts.ollamaCloud.monthlyPoolShort', + utilization: 80, + color: 'amber' + }) + expect(wrapper.get('[data-testid="ollama-cloud-balance"]').text()) + .toBe('admin.accounts.ollamaCloud.balance: $12.00 / $60') + expect(wrapper.get('[data-testid="ollama-cloud-snapshot-time"]').text()) + .toContain('admin.accounts.ollamaCloud.updatedAt') + }) + + it('falls back to the raw balance text when the credits pool is missing', () => { + const state = usageState() + state.mode = 'ollama_credits' + state.snapshot!.data!.balance = '$12.00' + + const wrapper = mount(OllamaCloudUsageCell, { props: { account: account(state) } }) + + expect(wrapper.find('[data-testid="ollama-cloud-monthly-pool"]').exists()).toBe(false) + expect(wrapper.get('[data-testid="ollama-cloud-balance"]').text()) + .toBe('admin.accounts.ollamaCloud.balance: $12.00') }) it('reacts to an account snapshot update', async () => { @@ -140,4 +188,27 @@ describe('OllamaCloudUsageCell', () => { expect(wrapper.find('[data-testid="ollama-cloud-usage-query"]').exists()).toBe(false) }) + + it('explains an ineligible account via the backend reason code', () => { + const state = usageState() + state.eligible = false + state.eligible_reason = 'unsupported_base_url' + state.snapshot = undefined + + const wrapper = mount(OllamaCloudUsageCell, { props: { account: account(state) } }) + + const hint = wrapper.get('[data-testid="ollama-cloud-usage-ineligible"]') + expect(hint.text()).toBe('admin.accounts.ollamaCloud.eligibleReason.unsupported_base_url') + expect(hint.attributes('title')).toBe('admin.accounts.ollamaCloud.eligibleReason.unsupported_base_url') + }) + + it('keeps the dash placeholder when no state is available', () => { + const wrapper = mount(OllamaCloudUsageCell, { + props: { account: account(null as unknown as OllamaCloudUsageState) } + }) + + expect(wrapper.find('[data-testid="ollama-cloud-usage-ineligible"]').exists()).toBe(false) + expect(wrapper.find('[data-testid="ollama-cloud-usage-cell"]').exists()).toBe(false) + expect(wrapper.get('span').classes()).toContain('text-sm') + }) }) diff --git a/frontend/src/i18n/locales/en/admin/accounts.ts b/frontend/src/i18n/locales/en/admin/accounts.ts index 2cb0ee110c..ab366c1283 100644 --- a/frontend/src/i18n/locales/en/admin/accounts.ts +++ b/frontend/src/i18n/locales/en/admin/accounts.ts @@ -316,6 +316,7 @@ export default { sevenDay: '7 day', sevenDayShort: '7d', balance: 'Balance', + monthlyPoolShort: 'Pool', models: 'Models', status: 'Status', updatedAt: 'Updated', @@ -323,6 +324,11 @@ export default { unauthorized: 'Session expired', failed: 'Refresh failed', windowWithReset: '{percent} used, resets {reset}', + eligibleReason: { + platform_not_eligible: 'Platform is not in the Ollama Cloud usage allowlist', + wrong_account_type: 'Only API key accounts support usage queries', + unsupported_base_url: 'base_url is not the official ollama.com host; usage is unavailable' + }, loadFailed: 'Failed to load Ollama Cloud usage settings', sessionSaved: 'Ollama browser session saved', sessionSaveFailed: 'Failed to save Ollama browser session', diff --git a/frontend/src/i18n/locales/zh/admin/accounts.ts b/frontend/src/i18n/locales/zh/admin/accounts.ts index 3217f89fc8..3e5c9d6d65 100644 --- a/frontend/src/i18n/locales/zh/admin/accounts.ts +++ b/frontend/src/i18n/locales/zh/admin/accounts.ts @@ -164,6 +164,7 @@ export default { sevenDay: '7 天', sevenDayShort: '7d', balance: '余额', + monthlyPoolShort: '月池', models: '模型', status: '状态', updatedAt: '更新时间', @@ -171,6 +172,11 @@ export default { unauthorized: '会话已过期', failed: '刷新失败', windowWithReset: '已用 {percent},{reset} 重置', + eligibleReason: { + platform_not_eligible: '平台不在 Ollama Cloud 用量白名单内', + wrong_account_type: '仅 API Key 账号支持用量查询', + unsupported_base_url: 'base_url 非官方 ollama.com,无法查询用量' + }, loadFailed: '加载 Ollama Cloud 用量设置失败', sessionSaved: 'Ollama 浏览器会话已保存', sessionSaveFailed: '保存 Ollama 浏览器会话失败', diff --git a/frontend/src/types/index.ts b/frontend/src/types/index.ts index 96ec2bcb0c..db5076e8e3 100644 --- a/frontend/src/types/index.ts +++ b/frontend/src/types/index.ts @@ -1141,6 +1141,12 @@ export interface OllamaCloudUsageSnapshot { export interface OllamaCloudUsageState { account_id: number eligible: boolean + /** eligible=false 的原因码(后端 EligibleReason,"" 缺省表示合格)。 */ + eligible_reason?: 'platform_not_eligible' | 'wrong_account_type' | 'unsupported_base_url' + /** 双额度模式:legacy=5h/7d 滚动窗口,credits=月度美元信用池;非 ollama_cloud 平台缺省。 */ + mode?: 'ollama_legacy' | 'ollama_credits' + /** credits 模式的月度信用池(USD,credentials.monthly_credit_usd);未录入时缺省。 */ + monthly_credit_usd?: number configured: boolean auto_refresh_enabled: boolean encryption_key_configured: boolean From c6125d8d01a8f0a794493c3753424ff8a792cd0e Mon Sep 17 00:00:00 2001 From: alfadb Date: Sun, 13 Sep 2026 08:38:38 +0800 Subject: [PATCH 30/81] feat(models): give ollama cloud a default model list C15/E18/E19: add the authoritative ollama_cloud default model catalog (DefaultOllamaCloudModelIDs, /v1/models measured 2026-09-12, 20 entries incl. the two tagged snapshots) and wire it into every default-model path: - service: defaultModelsListCandidateIDs ollama case + composite candidates - handler: defaultModelIDsForPlatform ollama case + composite array, and the /v1/models end-of-chain guard now falls back to the catalog instead of an empty list (Claude leak guard kept) - frontend: getModelsByPlatform 'ollama_cloud' case mirrors the same static table (cross-referencing comments both sides, pinning tests on both sides), and upstreamSyncPlatforms opens real upstream sync E20/E28 verified already done in 656accae0 (ChannelsView arrays + ChannelMonitorView.grok.spec provider count 11). --- backend/internal/handler/gateway_handler.go | 13 ++-- ...ateway_handler_ollama_cloud_models_test.go | 50 +++++++++++-- backend/internal/service/admin_group.go | 8 +- .../internal/service/ollama_cloud_models.go | 36 +++++++++ .../service/ollama_cloud_models_test.go | 73 +++++++++++++++++++ .../account/ModelWhitelistSelector.vue | 5 +- .../__tests__/useModelWhitelist.spec.ts | 44 ++++++++++- frontend/src/composables/useModelWhitelist.ts | 25 +++++++ 8 files changed, 230 insertions(+), 24 deletions(-) create mode 100644 backend/internal/service/ollama_cloud_models.go create mode 100644 backend/internal/service/ollama_cloud_models_test.go diff --git a/backend/internal/handler/gateway_handler.go b/backend/internal/handler/gateway_handler.go index 1a9f69a4a5..ade087fc49 100644 --- a/backend/internal/handler/gateway_handler.go +++ b/backend/internal/handler/gateway_handler.go @@ -1287,10 +1287,10 @@ func (h *GatewayHandler) Models(c *gin.Context) { return } - // ollama_cloud 无静态默认模型列表(defaultModelIDsForPlatform 返回空): - // 账号侧清单缺失时返回空列表,不得回落 Claude 默认模型。 + // ollama_cloud 账号侧清单缺失时回落实测默认目录(DefaultOllamaCloudModelIDs), + // 不得回落 Claude 默认模型。 if platform == service.PlatformOllamaCloud { - writeModelsListResponse(c, []claude.Model{}) + writeModelsList(c, platform, service.DefaultOllamaCloudModelIDs()) return } @@ -1580,17 +1580,14 @@ func defaultModelIDsForPlatform(platform string) []string { case service.PlatformTypeSafe: return []string{"jev-latest"} case service.PlatformOllamaCloud: - // ollama_cloud 没有静态默认模型列表:可服务模型完全来自账号侧的 - // model_mapping / extra.allowed_models(缺失时 IsModelSupported 为 - // deny-all)。default 分支的 Claude 列表对它只会造成虚假广告。 - return nil + return service.DefaultOllamaCloudModelIDs() case service.PlatformComposite: ids := make([]string, 0) seen := make(map[string]struct{}) // TypeSafe is deliberately absent: jev-latest only works through // /v1/systemone, so the static fallback never advertises it to LLM // clients. compositeAvailableModels lists it when the group can serve it. - for _, concretePlatform := range []string{service.PlatformAnthropic, service.PlatformGemini, service.PlatformOpenAI, service.PlatformAntigravity, service.PlatformGrok, service.PlatformKimi, service.PlatformZhipu, service.PlatformDeepseek, service.PlatformMiniMax, service.PlatformOpenCodeGo} { + for _, concretePlatform := range []string{service.PlatformAnthropic, service.PlatformGemini, service.PlatformOpenAI, service.PlatformAntigravity, service.PlatformGrok, service.PlatformKimi, service.PlatformZhipu, service.PlatformDeepseek, service.PlatformMiniMax, service.PlatformOpenCodeGo, service.PlatformOllamaCloud} { for _, id := range defaultModelIDsForPlatform(concretePlatform) { if _, ok := seen[id]; ok { continue diff --git a/backend/internal/handler/gateway_handler_ollama_cloud_models_test.go b/backend/internal/handler/gateway_handler_ollama_cloud_models_test.go index 56931d21d6..a1d63ebd09 100644 --- a/backend/internal/handler/gateway_handler_ollama_cloud_models_test.go +++ b/backend/internal/handler/gateway_handler_ollama_cloud_models_test.go @@ -12,11 +12,14 @@ import ( "github.com/stretchr/testify/require" ) -// ollama_cloud 没有静态默认模型列表:defaultModelIDsForPlatform 不得回落 -// Claude 列表(default 分支),/models 在账号侧清单缺失时返回空列表。 -func TestDefaultModelIDsForPlatform_OllamaCloudReturnsEmpty(t *testing.T) { - require.Empty(t, defaultModelIDsForPlatform(service.PlatformOllamaCloud)) +// ollama_cloud 的默认模型目录 = DefaultOllamaCloudModelIDs:defaultModelIDsForPlatform +// 不得回落 Claude 列表(default 分支),/models 在账号侧清单缺失时回落该目录。 +func TestDefaultModelIDsForPlatform_OllamaCloudReturnsDefaultCatalog(t *testing.T) { + require.Equal(t, service.DefaultOllamaCloudModelIDs(), defaultModelIDsForPlatform(service.PlatformOllamaCloud)) require.NotEmpty(t, defaultModelIDsForPlatform(service.PlatformAnthropic)) + for _, id := range defaultModelIDsForPlatform(service.PlatformOllamaCloud) { + require.NotContains(t, id, "claude") + } } func TestGatewayModels_OllamaCloudGroupListsAllowedModels(t *testing.T) { @@ -53,8 +56,8 @@ func TestGatewayModels_OllamaCloudGroupListsAllowedModels(t *testing.T) { require.Equal(t, []string{"gpt-oss:120b"}, modelIDsForTest(got.Data)) } -// 账号侧清单缺失(deny-all)时 /models 必须返回空,而不是回落 Claude 列表。 -func TestGatewayModels_OllamaCloudGroupWithoutListReturnsEmpty(t *testing.T) { +// 账号侧清单缺失(deny-all)时 /models 回落 ollama 默认目录,而不是 Claude 列表。 +func TestGatewayModels_OllamaCloudGroupWithoutListFallsBackToDefaultCatalog(t *testing.T) { gin.SetMode(gin.TestMode) groupID := int64(9202) @@ -80,6 +83,37 @@ func TestGatewayModels_OllamaCloudGroupWithoutListReturnsEmpty(t *testing.T) { require.Equal(t, http.StatusOK, rec.Code) var got gatewayModelsResponseForTest require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &got)) - require.Empty(t, got.Data, "ollama_cloud 不得回落 Claude 默认模型列表") - require.NotContains(t, modelIDsForTest(got.Data), "claude-sonnet-4-6") + require.Equal(t, service.DefaultOllamaCloudModelIDs(), modelIDsForTest(got.Data), + "ollama_cloud 不得回落 Claude 默认模型列表,应回落实测默认目录") +} + +// ollama_cloud 分组的 composite 白名单来源不串入 Claude 目录之外的默认回落。 +func TestGatewayModels_CompositeIncludesOllamaDefaultCatalog(t *testing.T) { + gin.SetMode(gin.TestMode) + + groupID := int64(9203) + h := newGatewayModelsHandlerForTest( + &gatewayModelsAccountRepoStub{byGroup: map[int64][]service.Account{groupID: {}}}, + ) + + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodGet, "/v1/models", nil) + c.Set(string(middleware2.ContextKeyAPIKey), &service.APIKey{ + Group: &service.Group{ID: groupID, Platform: service.PlatformComposite}, + }) + + h.Models(c) + + require.Equal(t, http.StatusOK, rec.Code) + var got gatewayModelsResponseForTest + require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &got)) + ids := modelIDsForTest(got.Data) + idsSet := make(map[string]struct{}, len(ids)) + for _, id := range ids { + idsSet[id] = struct{}{} + } + for _, id := range service.DefaultOllamaCloudModelIDs() { + require.Contains(t, idsSet, id, "composite /v1/models 兜底须含 ollama 目录条目 %q", id) + } } diff --git a/backend/internal/service/admin_group.go b/backend/internal/service/admin_group.go index 909c08bfce..56297543d5 100644 --- a/backend/internal/service/admin_group.go +++ b/backend/internal/service/admin_group.go @@ -300,11 +300,7 @@ func defaultModelsListCandidateIDs(platform string) []string { case PlatformTypeSafe: return []string{typesafe.JevLatestModel} case PlatformOllamaCloud: - // ollama_cloud 没有静态默认模型列表:可服务模型完全来自账号侧的 - // model_mapping / extra.allowed_models(缺失时 IsModelSupported 为 - // deny-all)。default 分支的 Claude 列表对它只会造成虚假广告; - // 显式返回空,与 gateway_handler.defaultModelIDsForPlatform 对齐。 - return nil + return DefaultOllamaCloudModelIDs() case PlatformComposite: return compositeDefaultModelsListCandidateIDs() default: @@ -328,7 +324,7 @@ func compositeDefaultModelsListCandidateIDs() []string { // TypeSafe stays out of the static composite candidates (jev-latest only works // through /v1/systemone); groups with TypeSafe accounts still get it from the // account model mappings collected by GetGroupModelsListCandidates. - for _, platform := range []string{PlatformAnthropic, PlatformGemini, PlatformOpenAI, PlatformAntigravity, PlatformGrok, PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo} { + for _, platform := range []string{PlatformAnthropic, PlatformGemini, PlatformOpenAI, PlatformAntigravity, PlatformGrok, PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo, PlatformOllamaCloud} { for _, id := range defaultModelsListCandidateIDs(platform) { if _, ok := seen[id]; ok { continue diff --git a/backend/internal/service/ollama_cloud_models.go b/backend/internal/service/ollama_cloud_models.go new file mode 100644 index 0000000000..a4e462e70d --- /dev/null +++ b/backend/internal/service/ollama_cloud_models.go @@ -0,0 +1,36 @@ +package service + +// DefaultOllamaCloudModelIDs 是 Ollama Cloud 的默认模型目录:实测 +// GET https://ollama.com/v1/models(2026-09-12,HTTP 200,20 个模型, +// owned_by 全部为 ollama,含两个带 tag 的快照名)。供分组默认模型列表、 +// composite 候选与 /v1/models 末尾兜底使用;条目均可被计费价目命中 +// (见 ollama_cloud_pricing_test.go 的逐名钉测)。 +// +// 前端同源静态表:frontend/src/composables/useModelWhitelist.ts 的 +// getModelsByPlatform 'ollama_cloud' case 必须与这里保持同一集合, +// 两侧各有测试钉住(ollama_cloud_models_test.go / useModelWhitelist.spec.ts), +// 改动任一侧须同步另一侧。 +func DefaultOllamaCloudModelIDs() []string { + return []string{ + "nemotron-3-super", + "glm-5.3", + "gpt-oss:120b", + "glm-5.3-flash", + "kimi-k2.6", + "kimi-k3", + "deepseek-v4.1-flash", + "minimax-m2.7", + "mistral-large-3:675b", + "glm-5.1", + "glm-5.2", + "gpt-oss:20b", + "qwen3.5:397b", + "kimi-k2.7-code", + "nemotron-3-nano:30b", + "minimax-m3", + "gemma4:31b", + "nemotron-3-ultra", + "deepseek-v4-flash:0731", + "deepseek-v4-pro:0813", + } +} diff --git a/backend/internal/service/ollama_cloud_models_test.go b/backend/internal/service/ollama_cloud_models_test.go new file mode 100644 index 0000000000..b2e536bbf1 --- /dev/null +++ b/backend/internal/service/ollama_cloud_models_test.go @@ -0,0 +1,73 @@ +//go:build unit + +package service + +// C15/C14/C22:ollama_cloud 默认模型清单的数据源钉测。 +// +// 权威数据:GET https://ollama.com/v1/models 实测(2026-09-12,HTTP 200, +// 20 个模型,含 deepseek-v4-flash:0731 / deepseek-v4-pro:0813 两个带 tag 快照名)。 +// +// 前端同源静态表:frontend/src/composables/useModelWhitelist.ts 的 +// getModelsByPlatform 'ollama_cloud' case 必须与 DefaultOllamaCloudModelIDs() +// 保持同一集合,两侧各有测试钉住(对侧:useModelWhitelist.spec.ts), +// 改动任一侧须同步另一侧。 + +import ( + "testing" + + "github.com/stretchr/testify/require" +) + +// TestDefaultOllamaCloudModelIDs 钉住目录的形状:数量、去重、无 claude 串入、 +// 带 tag 快照名与各家族代表条目不得缺失。 +func TestDefaultOllamaCloudModelIDs(t *testing.T) { + ids := DefaultOllamaCloudModelIDs() + + require.Len(t, ids, 20) + + seen := make(map[string]struct{}, len(ids)) + for _, id := range ids { + require.NotEmpty(t, id) + require.NotContains(t, seen, id, "duplicate model id %q", id) + seen[id] = struct{}{} + require.NotContains(t, id, "claude", "claude 模型不得串入 ollama_cloud 目录: %q", id) + } + + for _, key := range []string{ + "deepseek-v4-flash:0731", + "deepseek-v4-pro:0813", + "gpt-oss:120b", + "gpt-oss:20b", + "glm-5.3", + "kimi-k3", + "minimax-m3", + "qwen3.5:397b", + } { + require.Contains(t, ids, key) + } +} + +// C15 验收:defaultModelsListCandidateIDs 的 ollama case 返回目录本身; +// C14/C22 验收:composite 候选包含全部 ollama 条目。 +func TestDefaultModelsListCandidateIDs_OllamaCloud(t *testing.T) { + ollama := defaultModelsListCandidateIDs(PlatformOllamaCloud) + require.Equal(t, DefaultOllamaCloudModelIDs(), ollama) + + composite := defaultModelsListCandidateIDs(PlatformComposite) + for _, id := range DefaultOllamaCloudModelIDs() { + require.Contains(t, composite, id) + } +} + +// B2-② 联动断言:目录内每个模型都必须可计费(两级查价非 nil 且单价为正), +// 防止清单与价目表漂移后出现「默认列表 ∩ 定价表 = 空」与保存期门禁打架。 +func TestDefaultOllamaCloudModelIDsAllPriceable(t *testing.T) { + bs := newTestBillingService() + for _, id := range DefaultOllamaCloudModelIDs() { + pricing, err := bs.getModelPricingAt(id, ollamaPricingAt) + require.NoError(t, err, "model %s", id) + require.NotNil(t, pricing, "model %s must be priceable", id) + require.Positive(t, pricing.InputPricePerToken, "model %s", id) + require.Positive(t, pricing.OutputPricePerToken, "model %s", id) + } +} diff --git a/frontend/src/components/account/ModelWhitelistSelector.vue b/frontend/src/components/account/ModelWhitelistSelector.vue index d1e7e557cb..10b372faad 100644 --- a/frontend/src/components/account/ModelWhitelistSelector.vue +++ b/frontend/src/components/account/ModelWhitelistSelector.vue @@ -211,7 +211,10 @@ const upstreamSyncPlatforms = new Set([ 'zhipu', 'deepseek', 'minimax', - 'opencode_go' + 'opencode_go', + // ollama_cloud:后端探测路径已就绪(upstream_models.go 的 IsOllamaCloud 谓词), + // 打开真实 /v1/models 上游同步。 + 'ollama_cloud' ]) const canSyncUpstream = computed(() => { if (props.accountId) { diff --git a/frontend/src/composables/__tests__/useModelWhitelist.spec.ts b/frontend/src/composables/__tests__/useModelWhitelist.spec.ts index 9cd3ec3648..99a2a8ab13 100644 --- a/frontend/src/composables/__tests__/useModelWhitelist.spec.ts +++ b/frontend/src/composables/__tests__/useModelWhitelist.spec.ts @@ -4,9 +4,51 @@ vi.mock('@/api/admin/accounts', () => ({ getAntigravityDefaultModelMapping: vi.fn() })) -import { buildModelMappingObject, getModelsByPlatform, getPresetMappingsByPlatform, splitModelMappingObject } from '../useModelWhitelist' +import { buildModelMappingObject, claudeModels, getModelsByPlatform, getPresetMappingsByPlatform, splitModelMappingObject } from '../useModelWhitelist' describe('useModelWhitelist', () => { + // ollama_cloud 与后端同源静态表(backend/internal/service/ollama_cloud_models.go + // DefaultOllamaCloudModelIDs(),/v1/models 实测目录)——集合必须与后端一致, + // 两侧各有测试钉住(对侧:ollama_cloud_models_test.go),改任一侧须同步另一侧。 + const ollamaCloudBackendCatalog = [ + 'nemotron-3-super', + 'glm-5.3', + 'gpt-oss:120b', + 'glm-5.3-flash', + 'kimi-k2.6', + 'kimi-k3', + 'deepseek-v4.1-flash', + 'minimax-m2.7', + 'mistral-large-3:675b', + 'glm-5.1', + 'glm-5.2', + 'gpt-oss:20b', + 'qwen3.5:397b', + 'kimi-k2.7-code', + 'nemotron-3-nano:30b', + 'minimax-m3', + 'gemma4:31b', + 'nemotron-3-ultra', + 'deepseek-v4-flash:0731', + 'deepseek-v4-pro:0813' + ] + + it('ollama_cloud 模型列表与后端 DefaultOllamaCloudModelIDs 同一集合', () => { + const models = getModelsByPlatform('ollama_cloud') + + expect(models).toEqual(ollamaCloudBackendCatalog) + }) + + it('ollama_cloud 模型列表不是 Claude 列表且不含 claude 模型', () => { + const models = getModelsByPlatform('ollama_cloud') + + expect(models).not.toBe(claudeModels) + expect(models).not.toEqual(claudeModels) + for (const model of models) { + expect(model).not.toContain('claude') + } + }) + it('openai 模型列表包含 GPT-5.4 官方快照', () => { const models = getModelsByPlatform('openai') diff --git a/frontend/src/composables/useModelWhitelist.ts b/frontend/src/composables/useModelWhitelist.ts index 765ef379c4..d3c9241ab8 100644 --- a/frontend/src/composables/useModelWhitelist.ts +++ b/frontend/src/composables/useModelWhitelist.ts @@ -476,6 +476,31 @@ export function getModelsByPlatform(platform: string): string[] { 'hy4-preview', 'hy3', 'omen-alpha' ] case 'typesafe': return ['jev-latest'] + // 与后端同源静态表:backend/internal/service/ollama_cloud_models.go 的 + // DefaultOllamaCloudModelIDs()(/v1/models 实测目录)——两侧集合必须一致, + // 各有测试钉住(对侧:ollama_cloud_models_test.go),改任一侧须同步另一侧。 + case 'ollama_cloud': return [ + 'nemotron-3-super', + 'glm-5.3', + 'gpt-oss:120b', + 'glm-5.3-flash', + 'kimi-k2.6', + 'kimi-k3', + 'deepseek-v4.1-flash', + 'minimax-m2.7', + 'mistral-large-3:675b', + 'glm-5.1', + 'glm-5.2', + 'gpt-oss:20b', + 'qwen3.5:397b', + 'kimi-k2.7-code', + 'nemotron-3-nano:30b', + 'minimax-m3', + 'gemma4:31b', + 'nemotron-3-ultra', + 'deepseek-v4-flash:0731', + 'deepseek-v4-pro:0813' + ] case 'doubao': return doubaoModels case 'minimax': return minimaxModels case 'baidu': return baiduModels From 340ff7ffad1b37ed65fd8add737afc040ebf523e Mon Sep 17 00:00:00 2001 From: alfadb Date: Sun, 13 Sep 2026 09:03:31 +0800 Subject: [PATCH 31/81] chore(ollama): close the remaining increment-5 items - DetectModelPlatform: document why ollama_cloud intentionally has no branch (model-name-only input, resold families collide with existing prefixes such as gpt- -> openai; adding one would silently misroute) and pin current behaviour with table-driven tests - match models.dev provider by host for ollama.com using the measured registry id "ollama-cloud" - include ollama_cloud (and opencode_go) in the codex model catalog platform list - let reverse-proxy ollama_cloud accounts pick the anthropic auth scheme via extra (official host still forces Bearer) - use the adaptive chat-protocol base url in the upstream billing probe - add ollama_cloud to the remaining admin UI badges and spec expectations --- .../internal/service/anthropic_apikey_auth.go | 7 ++- .../anthropic_apikey_auth_ollama_test.go | 54 +++++++++++++++++++ .../internal/service/composite_platform.go | 6 +++ .../service/composite_platform_test.go | 35 ++++++++++++ .../service/openai_codex_models_service.go | 3 ++ .../openai_codex_models_service_test.go | 1 + .../service/upstream_billing_probe.go | 4 +- .../service/upstream_billing_probe_test.go | 34 ++++++++++++ backend/internal/service/upstream_models.go | 6 +++ .../internal/service/upstream_models_test.go | 44 +++++++++++++++ frontend/src/views/admin/GroupsView.vue | 4 ++ .../__tests__/channelPlatformOptions.spec.ts | 1 + 12 files changed, 196 insertions(+), 3 deletions(-) diff --git a/backend/internal/service/anthropic_apikey_auth.go b/backend/internal/service/anthropic_apikey_auth.go index 8bd8c4ba8f..f1d666438a 100644 --- a/backend/internal/service/anthropic_apikey_auth.go +++ b/backend/internal/service/anthropic_apikey_auth.go @@ -16,12 +16,15 @@ const ( // Anthropic API-key accounts. Missing or invalid values keep the historical // x-api-key behavior. CN providers using their native Anthropic endpoints // (api_protocol=anthropic) share the same override knob — Kimi/DeepSeek default -// to x-api-key, Zhipu can opt into Authorization: Bearer. +// to x-api-key, Zhipu can opt into Authorization: Bearer. Ollama Cloud accounts +// may read the knob too: it only matters for relay bases (the official +// ollama.com base is forced to Bearer by host in setAnthropicAPIKeyAuthHeader +// regardless of this value). func (a *Account) GetAnthropicAPIKeyAuthScheme() string { if a == nil || a.Type != AccountTypeAPIKey { return AnthropicAPIKeyAuthSchemeXAPIKey } - if a.Platform != PlatformAnthropic && !a.IsCNProvider() { + if a.Platform != PlatformAnthropic && !a.IsCNProvider() && a.Platform != PlatformOllamaCloud { return AnthropicAPIKeyAuthSchemeXAPIKey } diff --git a/backend/internal/service/anthropic_apikey_auth_ollama_test.go b/backend/internal/service/anthropic_apikey_auth_ollama_test.go index 6870d7e299..a935dba490 100644 --- a/backend/internal/service/anthropic_apikey_auth_ollama_test.go +++ b/backend/internal/service/anthropic_apikey_auth_ollama_test.go @@ -142,6 +142,60 @@ func TestSetAnthropicAPIKeyAuthHeader_OllamaCloudForcesBearer(t *testing.T) { } } +// TestGetAnthropicAPIKeyAuthScheme_OllamaCloudRelayOverride:C34 残余——平台化 +// 的 ollama_cloud 账号挂反代 base 时可经 extra 显式选 Bearer;缺省仍 x-api-key; +// 官方 ollama.com base 的强制 Bearer 不经本函数、不受影响(host 分支先行)。 +func TestGetAnthropicAPIKeyAuthScheme_OllamaCloudRelayOverride(t *testing.T) { + tests := []struct { + name string + base string + extra map[string]any + want string + }{ + { + name: "反代 base + extra 显式 Bearer → Bearer", + base: "https://relay.example.com", + extra: map[string]any{anthropicAPIKeyAuthSchemeExtraKey: AnthropicAPIKeyAuthSchemeAuthorizationBearer}, + want: AnthropicAPIKeyAuthSchemeAuthorizationBearer, + }, + { + name: "反代 base 无 extra → 保持 x-api-key", + base: "https://relay.example.com", + want: AnthropicAPIKeyAuthSchemeXAPIKey, + }, + { + name: "官方 ollama.com base 也读 extra(强制 Bearer 由 host 分支保证)", + base: "https://ollama.com", + extra: map[string]any{anthropicAPIKeyAuthSchemeExtraKey: AnthropicAPIKeyAuthSchemeAuthorizationBearer}, + want: AnthropicAPIKeyAuthSchemeAuthorizationBearer, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + account := newOllamaCloudAnthropicAuthAccount(tt.base, tt.extra) + account.Platform = PlatformOllamaCloud + require.Equal(t, tt.want, account.GetAnthropicAPIKeyAuthScheme()) + }) + } + + // 官方 base 恒 Bearer 不受 extra 影响:ollama_cloud 账号 + 显式 x_api_key + // extra,host 分支仍强制 Bearer。 + account := newOllamaCloudAnthropicAuthAccount("https://ollama.com", map[string]any{ + anthropicAPIKeyAuthSchemeExtraKey: AnthropicAPIKeyAuthSchemeXAPIKey, + }) + account.Platform = PlatformOllamaCloud + header := http.Header{} + setAnthropicAPIKeyAuthHeader(header, account, "ollama-cloud-key", "https://ollama.com") + require.Equal(t, "Bearer ollama-cloud-key", header.Get("Authorization")) + require.Empty(t, header.Get("x-api-key")) + + // Anthropic 平台回归:显式 x_api_key extra → x-api-key 不变。 + anthropicAccount := newOllamaCloudAnthropicAuthAccount("https://api.anthropic.com", map[string]any{ + anthropicAPIKeyAuthSchemeExtraKey: AnthropicAPIKeyAuthSchemeXAPIKey, + }) + require.Equal(t, AnthropicAPIKeyAuthSchemeXAPIKey, anthropicAccount.GetAnthropicAPIKeyAuthScheme()) +} + // TestSetAnthropicAPIKeyAuthHeader_CNAdaptiveBaseURLResolution:adaptive 账号经 // GetCNProtocolBaseURL(anthropic) / GetAnthropicProtocolBaseURL 选出的分协议地址 // 才是判定依据,Chat Completions 地址(GetOpenAIBaseURL 选到的 CC base)不参与。 diff --git a/backend/internal/service/composite_platform.go b/backend/internal/service/composite_platform.go index 0e394bcf7f..9d8e6d6425 100644 --- a/backend/internal/service/composite_platform.go +++ b/backend/internal/service/composite_platform.go @@ -149,6 +149,12 @@ func CompositeRouteSourceFromContext(ctx context.Context) (string, bool) { // DetectModelPlatform maps common public model IDs to the concrete provider // platform used by sub2api. It intentionally returns false for ambiguous model // names so composite groups fail closed instead of guessing. +// +// ollama_cloud(与 opencode_go 同理)刻意不在本表:本函数只有模型名入参、没有 +// host 入参,而 ollama 转售的模型家族(gpt-oss / kimi-k2 / glm / deepseek / +// qwen)与上方前缀规则直接冲突(如 gpt- 已映射 openai)——在这里加 ollama +// 分支等于按名字前缀静默错投。ollama_cloud 进入 composite 只走显式 route 与 +// ownership resolver(账号目录),不要给本函数加 ollama 分支。 func DetectModelPlatform(model string) (string, bool) { normalized := strings.ToLower(strings.TrimSpace(model)) if normalized == "" { diff --git a/backend/internal/service/composite_platform_test.go b/backend/internal/service/composite_platform_test.go index c7d398422b..94924b380f 100644 --- a/backend/internal/service/composite_platform_test.go +++ b/backend/internal/service/composite_platform_test.go @@ -201,6 +201,41 @@ func TestDetectModelPlatform(t *testing.T) { {name: "abab unrelated namespace", model: "abab-other", ok: false}, {name: "unknown k3 alias", model: "k3-preview", ok: false}, {name: "unknown", model: "llama-4-maverick", ok: false}, + // --- 行为钉(设计决策,不是漏配)--- + // DetectModelPlatform 刻意不加 ollama 分支(无 host 入参,ollama 转售 + // gpt-oss/kimi-k2/glm/deepseek 家族与上方前缀规则直接冲突,按字面加 + // 分支 = 静默错投)。以下用例钉住 ollama_cloud 默认目录 + // (DefaultOllamaCloudModelIDs)中的典型模型名的当前返回:将来有人 + // 「顺手加 ollama 分支」时这些用例会红灯,提示先回到该决策。 + { + name: "ollama-cloud resale gpt-oss pins to openai (intentional: no ollama branch)", + model: "gpt-oss:120b", + platform: PlatformOpenAI, + ok: true, + }, + { + name: "ollama-cloud resale glm pins to zhipu (intentional: no ollama branch)", + model: "glm-5.3", + platform: PlatformZhipu, + ok: true, + }, + { + name: "ollama-cloud resale kimi pins to kimi (intentional: no ollama branch)", + model: "kimi-k2.6", + platform: PlatformKimi, + ok: true, + }, + { + name: "ollama-cloud resale deepseek pins to deepseek (intentional: no ollama branch)", + model: "deepseek-v4.1-flash", + platform: PlatformDeepseek, + ok: true, + }, + { + name: "ollama-cloud qwen stays unmatched (intentional: fail closed)", + model: "qwen3.5:397b", + ok: false, + }, } for _, tt := range tests { diff --git a/backend/internal/service/openai_codex_models_service.go b/backend/internal/service/openai_codex_models_service.go index 934f770979..1f7409636d 100644 --- a/backend/internal/service/openai_codex_models_service.go +++ b/backend/internal/service/openai_codex_models_service.go @@ -263,6 +263,9 @@ func loadCodexGroupCatalogAccounts(ctx context.Context, repo AccountRepository, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, + PlatformOllamaCloud, + // PlatformOpenCodeGo 是方案标注的同类历史漏点:同为转售型平台, + // 不进目录则 Codex 客户端同样看不到其映射模型,随本行一并补上。 PlatformOpenCodeGo, }, false, diff --git a/backend/internal/service/openai_codex_models_service_test.go b/backend/internal/service/openai_codex_models_service_test.go index a825ba2208..9a3ab57337 100644 --- a/backend/internal/service/openai_codex_models_service_test.go +++ b/backend/internal/service/openai_codex_models_service_test.go @@ -1120,6 +1120,7 @@ func TestBuildCodexModelsManifestForGroupLoadsAccountsOnce(t *testing.T) { require.Contains(t, repo.platforms, PlatformGrok) require.Contains(t, repo.platforms, PlatformDeepseek) require.Contains(t, repo.platforms, PlatformMiniMax) + require.Contains(t, repo.platforms, PlatformOllamaCloud) require.Contains(t, repo.platforms, PlatformOpenCodeGo) require.NotContains(t, repo.platforms, PlatformComposite) } diff --git a/backend/internal/service/upstream_billing_probe.go b/backend/internal/service/upstream_billing_probe.go index a09e482871..366553d745 100644 --- a/backend/internal/service/upstream_billing_probe.go +++ b/backend/internal/service/upstream_billing_probe.go @@ -626,7 +626,9 @@ func (s *UpstreamBillingProbeService) probeLoadedAccount(ctx context.Context, ac return s.persistProbeFailure(ctx, account, intervalMinutes, now, 0, "missing_api_key", 0) } baseURL := account.GetCredential("base_url") - if account.IsCNProvider() && account.IsAdaptiveAPIProtocol() { + // 多协议 adaptive 账号(CN 供应商 / ollama_cloud)的探测 base 与出站 + // base 同源:优先读 api_base_urls 分协议地址,而不是 legacy credentials.base_url。 + if (account.IsCNProvider() || account.IsOllamaCloud()) && account.IsAdaptiveAPIProtocol() { baseURL = account.GetCNProtocolBaseURL(APIProtocolChatCompletions) } if account.Platform == PlatformOpenAI { diff --git a/backend/internal/service/upstream_billing_probe_test.go b/backend/internal/service/upstream_billing_probe_test.go index 68df096efe..15a1c84f59 100644 --- a/backend/internal/service/upstream_billing_probe_test.go +++ b/backend/internal/service/upstream_billing_probe_test.go @@ -372,6 +372,40 @@ func TestUpstreamBillingProbeAdaptiveCNUsesChatProtocolBaseURL(t *testing.T) { require.Equal(t, "https://chat-relay.example/v1/sub2api/billing", upstream.lastReq.URL.String()) } +// Scenario: ollama_cloud adaptive 账号配置 api_base_urls[chat_completions] 时, +// 探测 base 与出站 base 同源(读分协议地址,而非 legacy credentials.base_url)。 +func TestUpstreamBillingProbeAdaptiveOllamaCloudUsesChatProtocolBaseURL(t *testing.T) { + account := &Account{ + ID: 19, + Platform: PlatformOllamaCloud, + Type: AccountTypeAPIKey, + Status: StatusActive, + Concurrency: 1, + Credentials: map[string]any{ + "api_key": "sk-sensitive", + "api_protocol": APIProtocolAdaptive, + "base_url": "https://legacy-relay.example/v1", + "api_base_urls": map[string]any{ + APIProtocolChatCompletions: "https://chat.example/v1", + }, + }, + Extra: map[string]any{UpstreamBillingProbeEnabledExtraKey: true}, + } + repo := &upstreamBillingProbeAccountRepo{accounts: map[int64]*Account{account.ID: account}} + upstream := &httpUpstreamRecorder{resp: &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{"application/json"}}, + Body: upstreamBillingProbeValidBody(), + }} + svc := newUpstreamBillingProbeTestService(repo, upstream, &upstreamBillingProbeSettingRepo{}) + + snapshot, err := svc.ProbeAccount(context.Background(), account.ID) + + require.NoError(t, err) + require.Equal(t, UpstreamBillingProbeStatusOK, snapshot.Status) + require.Equal(t, "https://chat.example/v1/sub2api/billing", upstream.lastReq.URL.String()) +} + func TestUpstreamBillingProbeSyncsResolvedRateForAllAPIKeyPlatforms(t *testing.T) { for _, platform := range []string{ PlatformOpenAI, diff --git a/backend/internal/service/upstream_models.go b/backend/internal/service/upstream_models.go index 48722efefc..6d5265cd98 100644 --- a/backend/internal/service/upstream_models.go +++ b/backend/internal/service/upstream_models.go @@ -687,6 +687,12 @@ func matchModelsDevProviderByKnownHost(registry map[string]modelsDevProvider, ac providerID = "openai" case "opencode.ai": providerID = "opencode-go" + case "ollama.com": + // 实测 models.dev registry(api.json):provider ID 是 `ollama-cloud` + // (不是 "ollama"),且其 api 字段为 https://ollama.com/v1 —— 常规 + // base 走上方 API-URL 匹配即可命中;本 case 兜底 registry 形态漂移 + // (api 字段缺失/变更)或非常规路径形式,避免官方 host 静默丢元数据。 + providerID = "ollama-cloud" default: return modelsDevProvider{}, false } diff --git a/backend/internal/service/upstream_models_test.go b/backend/internal/service/upstream_models_test.go index e0e9f263ec..016e87f76b 100644 --- a/backend/internal/service/upstream_models_test.go +++ b/backend/internal/service/upstream_models_test.go @@ -929,6 +929,50 @@ func TestMatchModelsDevProviderFallsBackToOpenAIProviderWithoutAPIField(t *testi require.Equal(t, "opencode", provider.ID) } +// Scenario: ollama.com 账号的模型 registry 元数据能匹配到 models.dev 的 +// ollama-cloud provider(实测 provider ID 为 `ollama-cloud`,非 "ollama")。 +// registry 带 api 字段(当前真实形态 https://ollama.com/v1)时走 API-URL +// 匹配;api 字段缺失(registry 形态漂移)时 known-host 兜底仍命中; +// 反代 host 不继承官方 provider,避免跨厂商错误归因。 +func TestMatchModelsDevProviderOllamaCloud(t *testing.T) { + t.Parallel() + + newRegistry := func(withAPI bool) map[string]modelsDevProvider { + provider := modelsDevProvider{ + ID: "ollama-cloud", + Name: "Ollama Cloud", + Models: map[string]modelsDevModel{ + "gpt-oss:120b": {ID: "gpt-oss:120b", Name: "GPT-OSS 120B"}, + }, + } + if withAPI { + provider.API = "https://ollama.com/v1" + } + return map[string]modelsDevProvider{"ollama-cloud": provider} + } + + // registry 带 api 字段:API-URL 匹配直接命中。 + for _, baseURL := range []string{ + "https://ollama.com/v1", + "https://ollama.com", + } { + provider, ok := matchModelsDevProvider(newRegistry(true), baseURL) + require.True(t, ok, baseURL) + require.Equal(t, "ollama-cloud", provider.ID, baseURL) + require.Contains(t, provider.Models, "gpt-oss:120b", baseURL) + } + + // registry api 字段缺失(形态漂移):known-host 兜底命中官方 host。 + provider, ok := matchModelsDevProvider(newRegistry(false), "https://ollama.com/v1") + require.True(t, ok) + require.Equal(t, "ollama-cloud", provider.ID) + require.Contains(t, provider.Models, "gpt-oss:120b") + + // 反代/自定义 host 不命中:同前缀名字不得跨厂商归因到 ollama-cloud。 + _, ok = matchModelsDevProvider(newRegistry(true), "https://relay.example.com/v1") + require.False(t, ok, "custom hosts must not inherit the official ollama-cloud provider by name") +} + // Scenario: 官方 OpenAI ID-only /models + 无 api 字段的 models.dev openai 条目仍能补齐并落库。 func TestSyncUpstreamModelCatalogEnrichesOfficialOpenAIHostWithoutRegistryAPIField(t *testing.T) { upstream := &httpUpstreamRecorder{responses: []*http.Response{ diff --git a/frontend/src/views/admin/GroupsView.vue b/frontend/src/views/admin/GroupsView.vue index 66febc8bda..d2585eddc3 100644 --- a/frontend/src/views/admin/GroupsView.vue +++ b/frontend/src/views/admin/GroupsView.vue @@ -158,6 +158,8 @@ ? 'bg-rose-100 text-rose-700 dark:bg-rose-900/30 dark:text-rose-400' : value === 'opencode_go' ? 'bg-amber-100 text-amber-800 dark:bg-amber-900/30 dark:text-amber-300' + : value === 'ollama_cloud' + ? 'bg-stone-100 text-stone-800 dark:bg-stone-900/30 dark:text-stone-300' : 'bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-400', ]" > @@ -3835,6 +3837,8 @@ ? 'bg-rose-100 text-rose-700 dark:bg-rose-900/30 dark:text-rose-400' : group.platform === 'opencode_go' ? 'bg-amber-100 text-amber-800 dark:bg-amber-900/30 dark:text-amber-300' + : group.platform === 'ollama_cloud' + ? 'bg-stone-100 text-stone-800 dark:bg-stone-900/30 dark:text-stone-300' : 'bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-400', ]" > diff --git a/frontend/src/views/admin/__tests__/channelPlatformOptions.spec.ts b/frontend/src/views/admin/__tests__/channelPlatformOptions.spec.ts index a259234874..dc1641eda2 100644 --- a/frontend/src/views/admin/__tests__/channelPlatformOptions.spec.ts +++ b/frontend/src/views/admin/__tests__/channelPlatformOptions.spec.ts @@ -12,5 +12,6 @@ describe('Composite channel platform options', () => { expect(declaration).toContain("'deepseek'") expect(declaration).toContain("'minimax'") expect(declaration).toContain("'opencode_go'") + expect(declaration).toContain("'ollama_cloud'") }) }) From fc9512ab6e6e35a802b1dc0e0ca9713503ebb9f4 Mon Sep 17 00:00:00 2001 From: alfadb Date: Sun, 13 Sep 2026 09:11:29 +0800 Subject: [PATCH 32/81] docs(ollama): correct the operational preflight SQL in the usage gate comment MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The old comment block had a placeholder model set (<已定价模型名集合>) and a second query that flagged every empty-mapping account, including compliant ones with a valid extra.allowed_models list, while missing accounts whose list contains unpriced models. Replace with three directly executable queries (substituted 22-name priced set, tag-stripping second-level match, new allowed_models list scan, rewritten empty-mapping check) per the migration runbook; comment-only change. --- .../internal/service/openai_gateway_usage.go | 64 +++++++++++++++---- 1 file changed, 53 insertions(+), 11 deletions(-) diff --git a/backend/internal/service/openai_gateway_usage.go b/backend/internal/service/openai_gateway_usage.go index d71823161f..e97226cfad 100644 --- a/backend/internal/service/openai_gateway_usage.go +++ b/backend/internal/service/openai_gateway_usage.go @@ -152,21 +152,63 @@ func groupBillsOpenAIFastAtStandard(apiKey *APIKey, account *Account, serviceTie // 运营 preflight SQL(B2-④,上线/放量前人工执行;是一次性运营检查,不是迁移, // 不要放进 migrations/)。用于在放量前扫出「保存期门禁(B2-③)生效前就已存在、 -// 或绕过门禁写入」的无价 ollama_cloud 账号;两条都期望 0 行: +// 或绕过门禁写入」的无价 ollama_cloud 账号;三条都期望 0 行,均为可直接执行的 +// 完整语句,在【业务主库】accounts 表跑;命中处置与存量盘点(第 0 条)见完整 +// 迁移手册(运营文档)。已定价模型集合(22 名)取自 billing_service.go +// fallbackPrices 的 ollama 条目:18 条字面名 + 家族兜底可计费的 +// kimi-k2.7-code / deepseek-v4.1-flash;查询里 regexp_replace 剥 :tag 的二级 +// 比对与两级查价同源。 // -// -- 1) model_mapping 目标值必须全部有价(<已定价模型名集合> 取 -// -- billing_service.go fallbackPrices 的 ollama 条目 + 复用同名条目的模型; -// -- 注意 :tag 名靠两级查价 fallback 命中,集合里放裸名即可);期望 0 行 -// SELECT a.id, kv.value AS target_model FROM accounts a, +// -- 1) model_mapping 目标值必须全部有价;期望 0 行(命中先甄别家族兜底 +// -- 误报,再补价或改 mapping) +// WITH priced(model) AS (VALUES +// ('nemotron-3-super'),('glm-5.3'),('gpt-oss:120b'),('glm-5.3-flash'), +// ('kimi-k2.6'),('kimi-k3'),('deepseek-v4.1-flash'),('minimax-m2.7'), +// ('mistral-large-3:675b'),('glm-5.1'),('glm-5.2'),('gpt-oss:20b'), +// ('qwen3.5:397b'),('kimi-k2.7-code'),('nemotron-3-nano:30b'),('minimax-m3'), +// ('gemma4:31b'),('nemotron-3-ultra'),('deepseek-v4-flash:0731'), +// ('deepseek-v4-pro:0813'),('deepseek-v4-flash'),('deepseek-v4-pro')) +// SELECT a.id, a.name, kv.key AS source_model, 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 (<已定价模型名集合>); +// AND btrim(kv.value) <> '' +// AND lower(btrim(kv.value)) NOT IN (SELECT model FROM priced) +// AND lower(regexp_replace(btrim(kv.value), ':.*$', '')) NOT IN (SELECT model FROM priced); // -// -- 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; +// -- 1b) extra.allowed_models 清单值必须全部有价(清单存 accounts.extra,不在 +// -- credentials;与 model_mapping 是同地位的两条可出站来源);期望 0 行 +// WITH priced(model) AS (VALUES +// ('nemotron-3-super'),('glm-5.3'),('gpt-oss:120b'),('glm-5.3-flash'), +// ('kimi-k2.6'),('kimi-k3'),('deepseek-v4.1-flash'),('minimax-m2.7'), +// ('mistral-large-3:675b'),('glm-5.1'),('glm-5.2'),('gpt-oss:20b'), +// ('qwen3.5:397b'),('kimi-k2.7-code'),('nemotron-3-nano:30b'),('minimax-m3'), +// ('gemma4:31b'),('nemotron-3-ultra'),('deepseek-v4-flash:0731'), +// ('deepseek-v4-pro:0813'),('deepseek-v4-flash'),('deepseek-v4-pro')) +// SELECT a.id, a.name, btrim(m.value) AS allowed_model +// FROM accounts a, jsonb_array_elements_text(a.extra->'allowed_models') AS m +// WHERE a.deleted_at IS NULL AND a.platform = 'ollama_cloud' +// AND jsonb_typeof(a.extra->'allowed_models') = 'array' +// AND btrim(m.value) <> '' +// AND lower(btrim(m.value)) NOT IN (SELECT model FROM priced) +// AND lower(regexp_replace(btrim(m.value), ':.*$', '')) NOT IN (SELECT model FROM priced); +// +// -- 2) 空 mapping 账号必须有「有效清单」(非空字符串数组);期望 0 行 +// -- (空 mapping + 合法清单是合规形态,不算命中;此处命中的是既无 mapping +// -- 又无有效清单的账号——运行时 deny-all,需补 allowed_models/mapping 或下线) +// SELECT a.id, a.name, a.status, a.schedulable, +// CASE WHEN NOT (a.extra ? 'allowed_models') THEN 'no_allowed_models_key' +// WHEN jsonb_typeof(a.extra->'allowed_models') <> 'array' THEN 'allowed_models_not_array' +// WHEN NOT EXISTS (SELECT 1 FROM jsonb_array_elements_text(a.extra->'allowed_models') +// WHERE btrim(value) <> '') THEN 'allowed_models_empty' +// END AS reason +// FROM accounts a +// WHERE a.deleted_at IS NULL AND a.platform = 'ollama_cloud' +// AND COALESCE(a.credentials->'model_mapping','{}'::jsonb) = '{}'::jsonb +// AND (NOT (a.extra ? 'allowed_models') +// OR jsonb_typeof(a.extra->'allowed_models') <> 'array' +// OR NOT EXISTS (SELECT 1 FROM jsonb_array_elements_text(a.extra->'allowed_models') +// WHERE btrim(value) <> '')); // // 上线后观察断言:日志中 `openai_usage.pricing_missing_record_zero_cost` 出现 // 次数必须为 0(出现即回滚放量)。定价门禁已前移到上游 I/O 之前的请求期预检 From 23995d1dbe31b16b5d1d9ab6a77537a1e09ac959 Mon Sep 17 00:00:00 2001 From: alfadb Date: Tue, 15 Sep 2026 10:49:08 +0800 Subject: [PATCH 33/81] fix(composite): restore merge-authored ollama_cloud admission lost in linearization The unified branch originally recorded these adjustments inside merge commit resolutions (b016694c3). Rebasing onto the new main linearizes history and drops merge-commit content, so restate them as a regular commit: - admit ollama_cloud to the composite ownership query platforms - add family-routing and composite-ownership regression tests - drop deepseek from the empty-mapping allow-all guard (its empty-mapping semantics are pinned by the deepseek whitelist fixtures instead) - document ollama_cloud in the OpenAI-compatible family dispatch comment --- backend/internal/server/routes/gateway.go | 2 +- ...ateway_ollama_cloud_family_routing_test.go | 103 +++++++++ .../account_ollama_cloud_whitelist_test.go | 5 +- .../composite_ollama_ownership_test.go | 204 ++++++++++++++++++ backend/internal/service/gateway_service.go | 1 + 5 files changed, 313 insertions(+), 2 deletions(-) create mode 100644 backend/internal/server/routes/gateway_ollama_cloud_family_routing_test.go create mode 100644 backend/internal/service/composite_ollama_ownership_test.go diff --git a/backend/internal/server/routes/gateway.go b/backend/internal/server/routes/gateway.go index b3bfd9cba4..7bd495c732 100644 --- a/backend/internal/server/routes/gateway.go +++ b/backend/internal/server/routes/gateway.go @@ -508,7 +508,7 @@ func getGroupPlatform(c *gin.Context) string { } // isOpenAICompatibleGatewayFamilyPlatform 报告单个平台是否经 OpenAI 网关转发 -// (openai/grok/国产 OpenAI 兼容供应商/OpenCode Go)。 +// (openai/grok/国产 OpenAI 兼容供应商/OpenCode Go/Ollama Cloud)。 func isOpenAICompatibleGatewayFamilyPlatform(platform string) bool { switch platform { case service.PlatformOpenAI, service.PlatformGrok, diff --git a/backend/internal/server/routes/gateway_ollama_cloud_family_routing_test.go b/backend/internal/server/routes/gateway_ollama_cloud_family_routing_test.go new file mode 100644 index 0000000000..b9c7640760 --- /dev/null +++ b/backend/internal/server/routes/gateway_ollama_cloud_family_routing_test.go @@ -0,0 +1,103 @@ +package routes + +import ( + "net/http" + "net/http/httptest" + "strings" + "testing" + + servermiddleware "github.com/Wei-Shaw/sub2api/internal/server/middleware" + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +// familyRouteHits 记录 stub terminal handler 各自被命中的次数。 +type familyRouteHits struct { + openAICompatible int + grok int + generic int +} + +// newOllamaCloudFamilyRouter 按 RegisterGatewayRoutes 的文本端点装配方式搭最小 +// 路由:APIKey 注入普通分组(非 composite、无池候选),composite 中间件原样接 +// 入(对非 composite 分组直接放行),messages/responses/chat completions 走真实 +// dispatchOpenAICompatibleGateway,count_tokens 走真实 +// dispatchOpenAICompatibleCountTokens,terminal handler 用 stub 标记实际进入的 +// 网关家族。 +func newOllamaCloudFamilyRouter(t *testing.T, groupPlatform string) (*gin.Engine, *familyRouteHits) { + t.Helper() + gin.SetMode(gin.TestMode) + router := gin.New() + router.Use(gin.HandlerFunc(servermiddleware.APIKeyAuthMiddleware(func(c *gin.Context) { + groupID := int64(1) + c.Set(string(servermiddleware.ContextKeyAPIKey), &service.APIKey{ + GroupID: &groupID, + Group: &service.Group{ID: groupID, Platform: groupPlatform}, + }) + c.Next() + }))) + router.Use(compositeTargetPlatformMiddleware(service.NewCompositeRouteResolver(compositeRouteRepoStub{}))) + + hits := &familyRouteHits{} + openAICompatible := func(c *gin.Context) { hits.openAICompatible++; c.Status(http.StatusNoContent) } + grokCompatible := func(c *gin.Context) { hits.grok++; c.Status(http.StatusNoContent) } + generic := func(c *gin.Context) { hits.generic++; c.Status(http.StatusNoContent) } + + // 与 RegisterGatewayRoutes 相同的注册闭包:族分发交给生产 dispatcher。 + router.POST("/v1/messages", func(c *gin.Context) { + dispatchOpenAICompatibleGateway(c, openAICompatible, generic) + }) + router.POST("/v1/responses", func(c *gin.Context) { + dispatchOpenAICompatibleGateway(c, openAICompatible, generic) + }) + router.POST("/v1/chat/completions", func(c *gin.Context) { + dispatchOpenAICompatibleGateway(c, openAICompatible, generic) + }) + router.POST("/v1/messages/count_tokens", func(c *gin.Context) { + dispatchOpenAICompatibleCountTokens(c, openAICompatible, grokCompatible, generic) + }) + return router, hits +} + +// ollama_cloud 普通分组(非 composite、无池候选)的三种文本入站端点必须全部 +// 进入 OpenAI 兼容网关,而不是通用 Anthropic 网关。族判定的唯一源头是 +// isOpenAICompatibleGatewayFamilyPlatform:清单缺 ollama_cloud 时,下列断言会以 +// generic 命中的形式失败,而不是静默通过。 +func TestOllamaCloudGroupRoutesTextEndpointsIntoOpenAICompatibleGateway(t *testing.T) { + require.True(t, isOpenAICompatibleGatewayFamilyPlatform(service.PlatformOllamaCloud), + "ollama_cloud must belong to the OpenAI-compatible gateway family") + + router, hits := newOllamaCloudFamilyRouter(t, service.PlatformOllamaCloud) + + for _, path := range []string{"/v1/messages", "/v1/responses", "/v1/chat/completions"} { + before := *hits + req := httptest.NewRequest(http.MethodPost, path, strings.NewReader(`{"model":"llama3.1"}`)) + req.Header.Set("Content-Type", "application/json") + w := httptest.NewRecorder() + router.ServeHTTP(w, req) + + require.Equal(t, http.StatusNoContent, w.Code, "%s must reach a terminal handler", path) + require.Equal(t, before.openAICompatible+1, hits.openAICompatible, + "%s must route the ollama_cloud group into the OpenAI-compatible gateway", path) + require.Equal(t, before.generic, hits.generic, + "%s must not fall through to the generic Anthropic gateway", path) + } +} + +// count_tokens 对 ollama_cloud 普通分组沿用兼容分支语义:走 OpenAI +// CountTokens(compatible stub),不落 Grok 本地估算,也不落通用处理。 +func TestOllamaCloudGroupCountTokensUsesCompatibleBranch(t *testing.T) { + router, hits := newOllamaCloudFamilyRouter(t, service.PlatformOllamaCloud) + + req := httptest.NewRequest(http.MethodPost, "/v1/messages/count_tokens", + strings.NewReader(`{"model":"llama3.1","messages":[]}`)) + req.Header.Set("Content-Type", "application/json") + w := httptest.NewRecorder() + router.ServeHTTP(w, req) + + require.Equal(t, http.StatusNoContent, w.Code) + require.Equal(t, 1, hits.openAICompatible, "count_tokens must take the compatible branch for ollama_cloud") + require.Zero(t, hits.grok) + require.Zero(t, hits.generic, "count_tokens must not fall through to the generic handler for ollama_cloud") +} diff --git a/backend/internal/service/account_ollama_cloud_whitelist_test.go b/backend/internal/service/account_ollama_cloud_whitelist_test.go index 1ca7d6e873..aa18eb01d2 100644 --- a/backend/internal/service/account_ollama_cloud_whitelist_test.go +++ b/backend/internal/service/account_ollama_cloud_whitelist_test.go @@ -98,12 +98,15 @@ func TestOllamaCloudWhitelist_NonEmptyMappingKeepsMappingSemantics(t *testing.T) // 回归护栏:非 ollama 平台的空 mapping 仍放行所有(钉住 4 处风险面语义)。 // 不含 antigravity / grok:这两个平台空 mapping 的既有语义是注入平台默认映射 // (resolveModelMapping),从来不是「放行所有」,与本次改动无关。 +// 不含 deepseek:其空 mapping 的模型能力由 DeepSeek 自身的名单测试守护, +// 本护栏只钉住 ollama_cloud 白名单改动不误伤其它平台,不替其它平台的能力 +// 定义背书。 func TestOllamaCloudWhitelist_NonOllamaEmptyMappingStillAllowsAll(t *testing.T) { t.Parallel() for _, platform := range []string{ "", PlatformAnthropic, PlatformOpenAI, PlatformGemini, - PlatformDeepseek, PlatformKimi, PlatformMiniMax, PlatformZhipu, PlatformOpenCodeGo, + PlatformKimi, PlatformMiniMax, PlatformZhipu, PlatformOpenCodeGo, } { account := &Account{ID: 1, Platform: platform, Type: AccountTypeAPIKey, Credentials: map[string]any{}} require.Truef(t, account.IsModelSupported("totally-unpriced-model"), diff --git a/backend/internal/service/composite_ollama_ownership_test.go b/backend/internal/service/composite_ollama_ownership_test.go new file mode 100644 index 0000000000..b960623be0 --- /dev/null +++ b/backend/internal/service/composite_ollama_ownership_test.go @@ -0,0 +1,204 @@ +package service + +import ( + "context" + "testing" + + "github.com/Wei-Shaw/sub2api/internal/model" + "github.com/stretchr/testify/require" +) + +// compositeOwnershipScopedRepo 是尊重查询契约的 fake account repo:只返回同时 +// 满足 groupID、platforms 白名单与 schedulable 的记录,语义与 +// accountRepository.ListModelAvailabilityCandidates 的 group 分支一致 +// (platforms 为空时返回空结果,组隔离由 groupID 保证,配置态由 schedulable +// 保证)。lastPlatforms 记录调用方实际传入的平台集合,供回归断言直接检查。 +type compositeOwnershipScopedRepo struct { + AccountRepository + records []compositeOwnershipScopedRecord + lastPlatforms []string +} + +type compositeOwnershipScopedRecord struct { + groupID int64 + platform string + schedulable bool + account Account +} + +func (r *compositeOwnershipScopedRepo) ListModelAvailabilityCandidates(_ context.Context, groupID *int64, platforms []string, _ bool) ([]Account, error) { + r.lastPlatforms = append([]string(nil), platforms...) + if groupID == nil || len(platforms) == 0 { + return nil, nil + } + allowed := make(map[string]struct{}, len(platforms)) + for _, platform := range platforms { + allowed[platform] = struct{}{} + } + accounts := make([]Account, 0, len(r.records)) + for _, rec := range r.records { + if rec.groupID != *groupID || !rec.schedulable { + continue + } + if _, ok := allowed[rec.platform]; !ok { + continue + } + accounts = append(accounts, rec.account) + } + return accounts, nil +} + +func newOllamaOwnershipResolver(records ...compositeOwnershipScopedRecord) (*CompositeRouteResolver, *compositeOwnershipScopedRepo) { + repo := &compositeOwnershipScopedRepo{records: records} + svc := &GatewayService{accountRepo: repo} + resolver := NewCompositeRouteResolver(nil) + resolver.SetModelOwnershipResolver(svc.resolveCompositeModelOwnership) + return resolver, repo +} + +func mappingAccount(id int64, platform, alias, upstreamModel string) Account { + return Account{ + ID: id, + Platform: platform, + Credentials: map[string]any{ + "model_mapping": map[string]any{alias: upstreamModel}, + }, + } +} + +// 回归护栏:组内只有 ollama_cloud 账号时,ownership 候选查询必须把 +// ollama_cloud 纳入扫描平台集合(compositeOwnershipQueryPlatforms);否则仓库 +// 层按 platforms 白名单过滤会把 ollama 账号整个丢掉,显式别名再也无法被 +// Resolve 识别(detector 刻意无 ollama 分支,只能落 unmatched)。 +// 同组 schedulable=false 与其他组的账号不得混入目标平台。 +func TestResolveCompositeModelOwnershipFindsOllamaCloudAlias(t *testing.T) { + const ( + group = int64(7) + otherGroup = int64(8) + alias = "private-ollama-alias" + upstreamModel = "qwen3-coder" + ) + resolver, repo := newOllamaOwnershipResolver( + compositeOwnershipScopedRecord{ + groupID: group, platform: PlatformOllamaCloud, schedulable: true, + account: mappingAccount(166, PlatformOllamaCloud, alias, upstreamModel), + }, + // 同组但 schedulable=false:配置态查询不得纳入。 + compositeOwnershipScopedRecord{ + groupID: group, platform: PlatformDeepseek, schedulable: false, + account: mappingAccount(163, PlatformDeepseek, alias, "deepseek-v4-pro"), + }, + // 其他组的 schedulable 账号:组隔离不得纳入。 + compositeOwnershipScopedRecord{ + groupID: otherGroup, platform: PlatformDeepseek, schedulable: true, + account: mappingAccount(151, PlatformDeepseek, alias, "deepseek-v4-pro"), + }, + ) + + decision, err := resolver.Resolve(context.Background(), group, alias, CompositeRouteEndpointResponses) + require.NoError(t, err) + require.Contains(t, repo.lastPlatforms, PlatformOllamaCloud, + "ownership 候选查询必须显式扫描 ollama_cloud,否则组内 ollama 账号不可见") + require.True(t, decision.Matched) + require.Equal(t, CompositeRouteSourceAccount, decision.Source) + require.Equal(t, PlatformOllamaCloud, decision.TargetPlatform) + require.Empty(t, decision.CandidatePlatforms, "同组不可调度与其他组账号不得构成候选池") +} + +// 最高价值反向对照用例:别名本身是 detector 能识别的真实模型名 +// (MiniMax-M3 → minimax、deepseek-flash → deepseek、k3 → kimi),组内唯一 +// 可调度账号是 ollama_cloud 的显式 mapping。ownership 查询漏掉 ollama_cloud +// 时 Resolve 会回退 detector 并投到上述错误平台;补线后必须走账号目录声明 +// (Source=account,TargetPlatform=ollama_cloud),不得被 detector 冒领。 +func TestResolveCompositeModelOwnershipPrefersOllamaCloudOverDetector(t *testing.T) { + const group = int64(7) + for _, alias := range []string{"MiniMax-M3", "deepseek-flash", "k3"} { + t.Run(alias, func(t *testing.T) { + detected, ok := DetectModelPlatform(alias) + require.True(t, ok, "反向对照别名必须能被 detector 命中") + require.NotEqual(t, PlatformOllamaCloud, detected, "detector 不得直接命中 ollama_cloud") + + resolver, repo := newOllamaOwnershipResolver( + compositeOwnershipScopedRecord{ + groupID: group, platform: PlatformOllamaCloud, schedulable: true, + account: mappingAccount(166, PlatformOllamaCloud, alias, "gpt-oss:120b"), + }, + // 同组不可调度、以及本可被 detector 投中的平台账号:都不得混入。 + compositeOwnershipScopedRecord{ + groupID: group, platform: detected, schedulable: false, + account: mappingAccount(163, detected, alias, "unused"), + }, + compositeOwnershipScopedRecord{ + groupID: 8, platform: detected, schedulable: true, + account: mappingAccount(151, detected, alias, "unused"), + }, + ) + + decision, err := resolver.Resolve(context.Background(), group, alias, CompositeRouteEndpointResponses) + require.NoError(t, err) + require.Contains(t, repo.lastPlatforms, PlatformOllamaCloud) + require.True(t, decision.Matched) + require.Equal(t, CompositeRouteSourceAccount, decision.Source, + "必须由账号目录声明解析,而不是 detector 回退") + require.NotEqual(t, CompositeRouteSourceDetector, decision.Source) + require.Equal(t, PlatformOllamaCloud, decision.TargetPlatform) + require.Empty(t, decision.CandidatePlatforms) + }) + } +} + +// 强声明分层:ollama_cloud 与 anthropic 对同一公开别名都有精确 mapping 时, +// 两者同为强声明,必须构成稳定候选池(不是 detector 单平台、也不是静默丢弃 +// ollama)。缺 ollama_cloud 时池退化为 anthropic 单平台,本用例会红。 +func TestResolveCompositeModelOwnershipPoolsOllamaCloudWithStrongClaimer(t *testing.T) { + const ( + group = int64(7) + alias = "MiniMax-M3" + ) + resolver, _ := newOllamaOwnershipResolver( + compositeOwnershipScopedRecord{ + groupID: group, platform: PlatformOllamaCloud, schedulable: true, + account: mappingAccount(166, PlatformOllamaCloud, alias, "gpt-oss:120b"), + }, + compositeOwnershipScopedRecord{ + groupID: group, platform: PlatformAnthropic, schedulable: true, + account: mappingAccount(101, PlatformAnthropic, alias, "claude-sonnet-4-5"), + }, + ) + + decision, err := resolver.Resolve(context.Background(), group, alias, CompositeRouteEndpointResponses) + require.NoError(t, err) + require.True(t, decision.Matched) + require.Equal(t, CompositeRouteSourceAccountPool, decision.Source) + require.Empty(t, decision.TargetPlatform, "多平台强声明不猜单平台") + require.ElementsMatch(t, []string{PlatformAnthropic, PlatformOllamaCloud}, decision.CandidatePlatforms) +} + +// 轻量不变量:ownership 候选扫描范围必须与「全部具体平台」的既有权威清单 +// (model.AllPlatforms)一致;新增平台若只加了 AllPlatforms 而漏掉 ownership, +// 本用例直接红灯,不引入任何新的 runtime registry。 +func TestCompositeOwnershipQueryPlatformsCoverConcretePlatforms(t *testing.T) { + require.ElementsMatch(t, model.AllPlatforms(), compositeOwnershipQueryPlatforms()) +} + +// schedulable=false 的 ollama_cloud 账号不构成候选,且显式别名不得靠 detector +// 兜底;其他组同别名账号同样不得混入(组隔离双向验证)。 +func TestResolveCompositeModelOwnershipSkipsUnschedulableOllamaCloud(t *testing.T) { + const alias = "private-ollama-alias" + resolver, repo := newOllamaOwnershipResolver( + compositeOwnershipScopedRecord{ + groupID: 7, platform: PlatformOllamaCloud, schedulable: false, + account: mappingAccount(163, PlatformOllamaCloud, alias, "qwen3-coder"), + }, + compositeOwnershipScopedRecord{ + groupID: 8, platform: PlatformOllamaCloud, schedulable: true, + account: mappingAccount(151, PlatformOllamaCloud, alias, "qwen3-coder"), + }, + ) + + decision, err := resolver.Resolve(context.Background(), 7, alias, CompositeRouteEndpointResponses) + require.NoError(t, err) + require.Contains(t, repo.lastPlatforms, PlatformOllamaCloud) + require.False(t, decision.Matched, "不可调度与其他组的 ollama 账号不得被解析为可路由目标") + require.Empty(t, decision.TargetPlatform) +} diff --git a/backend/internal/service/gateway_service.go b/backend/internal/service/gateway_service.go index f08038a454..20801c846c 100644 --- a/backend/internal/service/gateway_service.go +++ b/backend/internal/service/gateway_service.go @@ -1497,6 +1497,7 @@ func compositeOwnershipQueryPlatforms() []string { return []string{ PlatformAnthropic, PlatformOpenAI, PlatformGemini, PlatformAntigravity, PlatformGrok, PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo, + PlatformOllamaCloud, } } From f323a68505625f2dace985bde1842c61e25277b2 Mon Sep 17 00:00:00 2001 From: alfadb Date: Tue, 15 Sep 2026 17:43:32 +0800 Subject: [PATCH 34/81] fix(ollama): classify ollama_cloud groups in key group provider map --- frontend/src/utils/keyGroupProviders.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/frontend/src/utils/keyGroupProviders.ts b/frontend/src/utils/keyGroupProviders.ts index 87010a0101..778d447aa8 100644 --- a/frontend/src/utils/keyGroupProviders.ts +++ b/frontend/src/utils/keyGroupProviders.ts @@ -17,7 +17,8 @@ const PROVIDER_BY_PLATFORM: Record = { antigravity: 'other', composite: 'other', opencode_go: 'other', - typesafe: 'other' + typesafe: 'other', + ollama_cloud: 'other' } export function getKeyGroupProvider(platform: GroupPlatform): KeyGroupProvider { From ee8bb42afa638e263b91b45493ae52c94d781a26 Mon Sep 17 00:00:00 2001 From: alfadb Date: Tue, 29 Sep 2026 21:33:01 +0800 Subject: [PATCH 35/81] fix(scheduler): restore account_model ownership veto in shared eligibility gate --- backend/internal/service/openai_gateway_scheduling.go | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/backend/internal/service/openai_gateway_scheduling.go b/backend/internal/service/openai_gateway_scheduling.go index 03c528a78c..d7efe32fdc 100644 --- a/backend/internal/service/openai_gateway_scheduling.go +++ b/backend/internal/service/openai_gateway_scheduling.go @@ -457,6 +457,11 @@ func openAICompatibleAccountEligibilityFailureReasonBeforeProfit(ctx context.Con if account == nil { return "account_nil" } + if source, ok := CompositeRouteSourceFromContext(ctx); ok && source == CompositeRouteSourceAccount { + if publicModel, modelOK := RequestedPublicModelFromContext(ctx); modelOK && !CompositeAccountClaimsModel(account, publicModel) { + return "account_model_not_owned" + } + } if !account.IsOpenAICompatible() || !openAISchedulingPlatformMatchesAccount(ctx, account, platform) { return "platform_mismatch" } From 1ae1d9658e3997d1ce0790ad2d2b28515ba8239c Mon Sep 17 00:00:00 2001 From: alfadb Date: Wed, 30 Sep 2026 15:28:27 +0800 Subject: [PATCH 36/81] fix(composite): adapt upstream inflight estimate to 4-value resolvePlatform MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 上游 0.2.11 新增的在途余额预留估算按旧 3 值签名调用 resolvePlatform; 本分支签名为 4 值(额外返回携带 composite 池决策的 ctx)。快照闭包接口 无法透传 ctx,池决策场景下账号级映射估算退化为兜底路径,行为安全。 --- backend/internal/service/billing_inflight_reservation.go | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/backend/internal/service/billing_inflight_reservation.go b/backend/internal/service/billing_inflight_reservation.go index 7c6c7b45fc..dcf3a05b16 100644 --- a/backend/internal/service/billing_inflight_reservation.go +++ b/backend/internal/service/billing_inflight_reservation.go @@ -663,7 +663,10 @@ func (s *GatewayService) inflightEstimateDeps() inflightEstimateDeps { return accounts, err }, func(ctx context.Context, apiKey *APIKey, model string) (string, bool, bool) { - platform, forced, err := s.resolvePlatform(ctx, apiKey.GroupID, apiKey.Group, model) + // 本分支 resolvePlatform 返回携带 composite 池决策的 ctx;该快照闭包 + // 无法透传 ctx(上游接口只收 platform/forced),池决策场景下账号级 + // 映射估算退化为走兜底路径,行为安全。 + _, platform, forced, err := s.resolvePlatform(ctx, apiKey.GroupID, apiKey.Group, model) return platform, forced, err == nil }, ) From b9efe90e8c4fb51e94e547de93f61a9078c9026e Mon Sep 17 00:00:00 2001 From: alfadb Date: Sat, 3 Oct 2026 00:29:33 +0800 Subject: [PATCH 37/81] fix(platform): sync composite ownership scan and scheduler counts with the platform union MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit rebase 到含上游 typesafe 的 main 后,平台全集是 typesafe + ollama_cloud 的并集, 两个既有消费者必须同步: - compositeOwnershipQueryPlatforms 补 PlatformTypeSafe,保持与 model.AllPlatforms 一致(TestCompositeOwnershipQueryPlatformsCoverConcretePlatforms 钉住该不变量); - ollama_cloud_scheduling_test 的 canonical 断言随平台全集更新 11→12、24→26, 并显式断言 typesafe 也在 canonical 集内。 --- backend/internal/service/gateway_service.go | 2 +- backend/internal/service/ollama_cloud_scheduling_test.go | 5 +++-- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/backend/internal/service/gateway_service.go b/backend/internal/service/gateway_service.go index 20801c846c..a5061e6758 100644 --- a/backend/internal/service/gateway_service.go +++ b/backend/internal/service/gateway_service.go @@ -1497,7 +1497,7 @@ func compositeOwnershipQueryPlatforms() []string { return []string{ PlatformAnthropic, PlatformOpenAI, PlatformGemini, PlatformAntigravity, PlatformGrok, PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo, - PlatformOllamaCloud, + PlatformTypeSafe, PlatformOllamaCloud, } } diff --git a/backend/internal/service/ollama_cloud_scheduling_test.go b/backend/internal/service/ollama_cloud_scheduling_test.go index 0eab300679..24ee535f0e 100644 --- a/backend/internal/service/ollama_cloud_scheduling_test.go +++ b/backend/internal/service/ollama_cloud_scheduling_test.go @@ -31,8 +31,9 @@ func TestOllamaCloudPlatform_SchedulerSnapshotPlatforms(t *testing.T) { t.Parallel() platforms := schedulerSnapshotPlatforms() - require.Len(t, platforms, 11) + require.Len(t, platforms, 12) require.Contains(t, platforms[:], PlatformOllamaCloud) + require.Contains(t, platforms[:], PlatformTypeSafe) seen := make(map[string]struct{}, len(platforms)) for _, platform := range platforms { @@ -45,7 +46,7 @@ func TestOllamaCloudPlatform_SchedulerSnapshotPlatforms(t *testing.T) { // 桶数必须与平台数组长度一致:每平台 single+forced,anthropic/gemini 各多一个 mixed。 const groupID int64 = 7701 require.Equal(t, len(platforms)*2+2, schedulerCanonicalBucketCount()) - require.Equal(t, 24, schedulerCanonicalBucketCount()) + require.Equal(t, 26, schedulerCanonicalBucketCount()) buckets := schedulerCanonicalBuckets(groupID) require.Len(t, buckets, schedulerCanonicalBucketCount()) From 085e7d2ac62863a348cb03f6f3ac25cb3f1d4758 Mon Sep 17 00:00:00 2001 From: alfadb Date: Sat, 3 Oct 2026 00:35:19 +0800 Subject: [PATCH 38/81] fix(platform): keep typesafe in composite channel platform options The ollama_cloud channel-monitor UI commit replaced the compositePlatforms entry list with the pre-typesafe array plus ollama_cloud, silently dropping typesafe instead of taking the union. Backend concrete composite targets (isConcreteRequestPlatform / DetectModelPlatform and the frontend CONCRETE_PLATFORM_OPTIONS catalog) include typesafe, so composite groups were no longer selectable for typesafe channel sections. Restore typesafe alongside ollama_cloud and assert both in the existing composite channel platform options spec. --- frontend/src/views/admin/ChannelsView.vue | 4 ++-- .../src/views/admin/__tests__/channelPlatformOptions.spec.ts | 1 + 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/frontend/src/views/admin/ChannelsView.vue b/frontend/src/views/admin/ChannelsView.vue index a65dc0a2d0..e9ea1c11f4 100644 --- a/frontend/src/views/admin/ChannelsView.vue +++ b/frontend/src/views/admin/ChannelsView.vue @@ -765,8 +765,8 @@ let abortController: AbortController | null = null // ── Platform config ── const platformOrder: GroupPlatform[] = ['anthropic', 'openai', 'gemini', 'antigravity', 'grok', 'kimi', 'zhipu', 'deepseek', 'minimax', 'opencode_go', 'typesafe', 'ollama_cloud'] // Composite pricing/mapping may target every concrete schedulable provider. -// (Backend isConcreteRequestPlatform includes ollama_cloud.) -const compositePlatforms: GroupPlatform[] = ['anthropic', 'openai', 'gemini', 'antigravity', 'grok', 'kimi', 'zhipu', 'deepseek', 'minimax', 'opencode_go', 'ollama_cloud'] +// (Backend isConcreteRequestPlatform includes typesafe and ollama_cloud.) +const compositePlatforms: GroupPlatform[] = ['anthropic', 'openai', 'gemini', 'antigravity', 'grok', 'kimi', 'zhipu', 'deepseek', 'minimax', 'opencode_go', 'typesafe', 'ollama_cloud'] // ── Helpers ── function formatDate(value: string): string { diff --git a/frontend/src/views/admin/__tests__/channelPlatformOptions.spec.ts b/frontend/src/views/admin/__tests__/channelPlatformOptions.spec.ts index dc1641eda2..fb494d2258 100644 --- a/frontend/src/views/admin/__tests__/channelPlatformOptions.spec.ts +++ b/frontend/src/views/admin/__tests__/channelPlatformOptions.spec.ts @@ -12,6 +12,7 @@ describe('Composite channel platform options', () => { expect(declaration).toContain("'deepseek'") expect(declaration).toContain("'minimax'") expect(declaration).toContain("'opencode_go'") + expect(declaration).toContain("'typesafe'") expect(declaration).toContain("'ollama_cloud'") }) }) From cde26d43f45419b205169047690d90e3735121e0 Mon Sep 17 00:00:00 2001 From: alfadb Date: Sat, 3 Oct 2026 00:16:53 +0800 Subject: [PATCH 39/81] =?UTF-8?q?fix(migrations):=20912=20=E6=81=A2?= =?UTF-8?q?=E5=A4=8D=20ollama=5Fcloud=20=E5=B9=B3=E5=8F=B0=20CHECK?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 241_add_typesafe_platform.sql 覆写平台约束时剔除了 ollama_cloud,会连带剔除 Ollama Cloud。新增 912 迁移在 user_platform_quotas.platform 与 composite_model_routes.target_platform 上重建约束,集合为 241 全部平台并集 ollama_cloud(保留 typesafe),无任何 DML,约束保持默认 validated。 新增 ollama_typesafe_migration_compat_test.go:校验 912 只含两个平台 CHECK、集合等于 241 并集加 ollama_cloud、无 DML、非 NOT VALID,且不触碰 channel_monitors 相关约束。 --- ...2_restore_ollama_cloud_platform_checks.sql | 33 ++++++ .../ollama_typesafe_migration_compat_test.go | 105 ++++++++++++++++++ 2 files changed, 138 insertions(+) create mode 100644 backend/migrations/912_restore_ollama_cloud_platform_checks.sql create mode 100644 backend/migrations/ollama_typesafe_migration_compat_test.go diff --git a/backend/migrations/912_restore_ollama_cloud_platform_checks.sql b/backend/migrations/912_restore_ollama_cloud_platform_checks.sql new file mode 100644 index 0000000000..e87ec292fc --- /dev/null +++ b/backend/migrations/912_restore_ollama_cloud_platform_checks.sql @@ -0,0 +1,33 @@ +-- 恢复 Ollama Cloud 平台约束。 +-- +-- 背景:241_add_typesafe_platform.sql 把 user_platform_quotas.platform 与 +-- composite_model_routes.target_platform 两个 CHECK 覆写为不含 'ollama_cloud' +-- 的集合,会连带剔除 Ollama Cloud。本迁移在 241 之后重建这两个约束,集合为 +-- 241 的全部平台并集 'ollama_cloud'。 +-- +-- 顺序:必须晚于 241(912 按文件名排序在其后)。新集合是 241 的超集,存量行 +-- 瞬时通过校验,因此是默认的 validated 约束。 +-- 适用 fresh 建库、空表升级与已应用 241 的环境;channel_monitors / +-- channel_monitor_request_templates 的约束不在本次范围内,保持原状。 +-- +-- 仅放宽约束,无任何 DML 与数据回填。若 241 尚未应用而库中已存在 +-- platform='ollama_cloud' 的行,说明其写入发生在更宽松的旧约束下,需在启动前 +-- 停写核对;本迁移不做数据修复,也不能替代该前置处置。 + +ALTER TABLE user_platform_quotas + DROP CONSTRAINT IF EXISTS user_platform_quotas_platform_check; + +ALTER TABLE user_platform_quotas + ADD CONSTRAINT user_platform_quotas_platform_check + CHECK (platform IN ('anthropic', 'openai', 'gemini', 'antigravity', 'grok', + 'kimi', 'zhipu', 'deepseek', 'minimax', 'opencode_go', 'typesafe', + 'ollama_cloud')); + +ALTER TABLE composite_model_routes + DROP CONSTRAINT IF EXISTS composite_model_routes_target_platform_check; + +ALTER TABLE composite_model_routes + ADD CONSTRAINT composite_model_routes_target_platform_check + CHECK (target_platform IN ('anthropic', 'openai', 'gemini', 'antigravity', 'grok', + 'kimi', 'zhipu', 'deepseek', 'minimax', 'opencode_go', 'typesafe', + 'ollama_cloud')); diff --git a/backend/migrations/ollama_typesafe_migration_compat_test.go b/backend/migrations/ollama_typesafe_migration_compat_test.go new file mode 100644 index 0000000000..32a76fe0d1 --- /dev/null +++ b/backend/migrations/ollama_typesafe_migration_compat_test.go @@ -0,0 +1,105 @@ +package migrations + +import ( + "regexp" + "sort" + "strings" + "testing" + + "github.com/stretchr/testify/require" +) + +// 912 兼容迁移与上游 typesafe 迁移(241)的文件名。 +const ( + restoreOllamaCloudPlatformChecksFile = "912_restore_ollama_cloud_platform_checks.sql" + typesafePlatformMigrationFile = "241_add_typesafe_platform.sql" +) + +// dmlStatementPattern 匹配 DML 关键字;912 只允许 DDL 约束变更。 +var dmlStatementPattern = regexp.MustCompile(`(?i)\b(insert|update|delete|merge|truncate|copy|upsert)\b`) + +// stripSQLLineComments 去掉 "--" 行注释,只对可执行语句做结构校验。 +func stripSQLLineComments(content string) string { + var b strings.Builder + for _, line := range strings.Split(content, "\n") { + if idx := strings.Index(line, "--"); idx >= 0 { + line = line[:idx] + } + b.WriteString(line) + b.WriteString("\n") + } + return b.String() +} + +// executableSQL 返回去掉注释并归一化空白后的 SQL。 +func executableSQL(content []byte) string { + return strings.Join(strings.Fields(stripSQLLineComments(string(content))), " ") +} + +// platformCheckValues 提取 "CHECK ( IN (...))" 中的平台字面量。 +func platformCheckValues(t *testing.T, sql, column string) []string { + t.Helper() + + re := regexp.MustCompile(`CHECK \(` + regexp.QuoteMeta(column) + ` IN \(([^)]*)\)\)`) + match := re.FindStringSubmatch(sql) + require.NotNil(t, match, "缺少 %s 的 CHECK 约束", column) + + quoted := regexp.MustCompile(`'([^']+)'`).FindAllStringSubmatch(match[1], -1) + require.NotEmpty(t, quoted, "%s 的平台列表为空", column) + + values := make([]string, 0, len(quoted)) + for _, q := range quoted { + values = append(values, q[1]) + } + return values +} + +func sortedValues(values []string) []string { + out := append([]string(nil), values...) + sort.Strings(out) + return out +} + +// TestRestoreOllamaCloudPlatformChecksMigration 校验 912: +// 只重建两个平台 CHECK、集合等于 241 的平台并集加 ollama_cloud、无 DML、 +// 且约束为默认 validated(非 NOT VALID)。 +func TestRestoreOllamaCloudPlatformChecksMigration(t *testing.T) { + content, err := FS.ReadFile(restoreOllamaCloudPlatformChecksFile) + require.NoError(t, err) + + sql := executableSQL(content) + + // 只处理两个平台 CHECK 约束,不触碰其它约束或表。 + require.Contains(t, sql, "DROP CONSTRAINT IF EXISTS user_platform_quotas_platform_check") + require.Contains(t, sql, "DROP CONSTRAINT IF EXISTS composite_model_routes_target_platform_check") + require.Contains(t, sql, "ADD CONSTRAINT user_platform_quotas_platform_check") + require.Contains(t, sql, "ADD CONSTRAINT composite_model_routes_target_platform_check") + require.Equal(t, 2, strings.Count(sql, "DROP CONSTRAINT IF EXISTS"), "912 只应移除两个约束") + require.Equal(t, 2, strings.Count(sql, "ADD CONSTRAINT"), "912 只应新增两个约束") + require.Equal(t, 2, strings.Count(sql, "CHECK ("), "912 只应包含两个 CHECK") + require.NotContains(t, sql, "channel_monitors") + require.NotContains(t, sql, "channel_monitor_request_templates") + require.NotContains(t, sql, "NOT VALID", "平台 CHECK 必须是 validated 约束") + + // 无任何 DML 语句。 + require.NotRegexp(t, dmlStatementPattern, sql, "912 不得包含 DML 语句") + + typesafeContent, err := FS.ReadFile(typesafePlatformMigrationFile) + require.NoError(t, err) + typesafeSQL := executableSQL(typesafeContent) + + // 集合 = 241 的平台集合 ∪ {ollama_cloud},不得漏类型或多类型。 + for _, column := range []string{"platform", "target_platform"} { + base := platformCheckValues(t, typesafeSQL, column) + + expected := append(sortedValues(base), "ollama_cloud") + sort.Strings(expected) + require.Equal(t, len(base)+1, len(expected), "%s 的基准平台集合不应含 ollama_cloud", column) + + actual := sortedValues(platformCheckValues(t, sql, column)) + require.Equal(t, expected, actual, + "912 的 %s 集合必须等于 241 的平台并集加 ollama_cloud", column) + require.Contains(t, actual, "ollama_cloud") + require.Contains(t, actual, "typesafe") + } +} From 8fd9b771c5f87e6d258f42543c435800debcd934 Mon Sep 17 00:00:00 2001 From: alfadb Date: Sat, 3 Oct 2026 00:55:31 +0800 Subject: [PATCH 40/81] =?UTF-8?q?fix(migrations):=20=E6=98=BE=E5=BC=8F?= =?UTF-8?q?=E5=BF=BD=E7=95=A5=20WriteString=20=E8=BF=94=E5=9B=9E=E5=80=BC?= =?UTF-8?q?=E4=BB=A5=E9=80=9A=E8=BF=87=20errcheck?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/migrations/ollama_typesafe_migration_compat_test.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/backend/migrations/ollama_typesafe_migration_compat_test.go b/backend/migrations/ollama_typesafe_migration_compat_test.go index 32a76fe0d1..c5cff39b9a 100644 --- a/backend/migrations/ollama_typesafe_migration_compat_test.go +++ b/backend/migrations/ollama_typesafe_migration_compat_test.go @@ -25,8 +25,8 @@ func stripSQLLineComments(content string) string { if idx := strings.Index(line, "--"); idx >= 0 { line = line[:idx] } - b.WriteString(line) - b.WriteString("\n") + _, _ = b.WriteString(line) + _, _ = b.WriteString("\n") } return b.String() } From 471de8c39ffcec17c15c253e0ba83da0ab62992c Mon Sep 17 00:00:00 2001 From: alfadb Date: Thu, 8 Oct 2026 19:50:54 +0800 Subject: [PATCH 41/81] =?UTF-8?q?fix(migrations):=20=E5=90=88=E5=B9=B6=20o?= =?UTF-8?q?llama=5Fcloud=20=E5=B9=B3=E5=8F=B0=E7=BA=A6=E6=9D=9F=E8=BF=81?= =?UTF-8?q?=E7=A7=BB=E4=B8=BA=20242?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 原 239_ollama_cloud_platform.sql 先于上游 241_add_typesafe_platform.sql 执行,而 241 会把 user_platform_quotas.platform 与 composite_model_routes.target_platform 两个 CHECK 覆写为不含 ollama_cloud 的 11 项,于是又要 912_restore_ollama_cloud_platform_checks.sql 再恢复一次;对上游来说这是两个多余的迁移文件。 改为单个 242_ollama_cloud_platform.sql(文件名字节序晚于 241),一次性重建四个约束: 两张平台表 = 241 的集合 ∪ {ollama_cloud}(12 项),两张监控表 = 238 的集合 ∪ {ollama_cloud}(11 项,保留 position 幂等守卫,typesafe 不是对话模型不进 provider), 零 DML。生产库已应用 239/241/912,242 会作为新迁移再跑一次且结果与现状等价;已应用 但文件消失的 239/912 由 runner 按文件名遍历时静默忽略,不触发 checksum 校验。 --- ...form.sql => 242_ollama_cloud_platform.sql} | 22 +++++-- ...2_restore_ollama_cloud_platform_checks.sql | 33 ---------- .../ollama_cloud_platform_migration_test.go | 66 +++++++++++++++---- .../ollama_typesafe_migration_compat_test.go | 66 ++++--------------- 4 files changed, 84 insertions(+), 103 deletions(-) rename backend/migrations/{239_ollama_cloud_platform.sql => 242_ollama_cloud_platform.sql} (70%) delete mode 100644 backend/migrations/912_restore_ollama_cloud_platform_checks.sql diff --git a/backend/migrations/239_ollama_cloud_platform.sql b/backend/migrations/242_ollama_cloud_platform.sql similarity index 70% rename from backend/migrations/239_ollama_cloud_platform.sql rename to backend/migrations/242_ollama_cloud_platform.sql index 2aada9bd09..5bf5be53af 100644 --- a/backend/migrations/239_ollama_cloud_platform.sql +++ b/backend/migrations/242_ollama_cloud_platform.sql @@ -1,12 +1,22 @@ --- Add Ollama Cloud as a first-class platform. +-- 把 Ollama Cloud 加入平台白名单。 -- -- 1. user_platform_quotas.platform CHECK -- 2. composite_model_routes.target_platform CHECK -- 3. channel_monitors / channel_monitor_request_templates provider CHECK -- --- Runs after 238_opencode_go_platform.sql. DROP ... IF EXISTS + 幂等守卫保证可重入; --- 新约束是 238 的超集,必须同时保留 MiniMax 与 OpenCode Go。 --- 零 DML 回填:与 157/224/237/238 一致,只放宽约束,不写任何 DML。 +-- 顺序:必须晚于 241_add_typesafe_platform.sql。上游 241 把前两个平台 CHECK 覆写为 +-- 11 项(含 typesafe、不含 ollama_cloud),本迁移在其后重建为 12 项,即 241 的平台 +-- 集合 ∪ {ollama_cloud}。两张监控表的 provider CHECK 以 238_opencode_go_platform.sql +-- 的 10 项为基准(typesafe 不是对话模型,不进 provider 白名单),并集 'ollama_cloud'。 +-- +-- DROP ... IF EXISTS + 幂等守卫保证可重入;新约束是旧约束的超集,存量行瞬时通过校验, +-- 因此是默认的 validated 约束。零 DML 回填:与 237/238/241 一致,只放宽约束,不写任何 +-- DML。监控表的守卫以 pg_get_constraintdef 探测:约束已含 ollama_cloud 时整段跳过,避免 +-- 无谓重建。 +-- +-- 适用 fresh 建库、空表升级与已应用 241 的环境。若库中已存在 platform='ollama_cloud' +-- 的行,说明其写入发生在更宽松的旧约束下,需在启动前停写核对;本迁移不做数据修复, +-- 也不能替代该前置处置。 ALTER TABLE user_platform_quotas DROP CONSTRAINT IF EXISTS user_platform_quotas_platform_check; @@ -14,7 +24,7 @@ ALTER TABLE user_platform_quotas ALTER TABLE user_platform_quotas ADD CONSTRAINT user_platform_quotas_platform_check CHECK (platform IN ('anthropic', 'openai', 'gemini', 'antigravity', 'grok', - 'kimi', 'zhipu', 'deepseek', 'minimax', 'opencode_go', + 'kimi', 'zhipu', 'deepseek', 'minimax', 'opencode_go', 'typesafe', 'ollama_cloud')); ALTER TABLE composite_model_routes @@ -23,7 +33,7 @@ ALTER TABLE composite_model_routes ALTER TABLE composite_model_routes ADD CONSTRAINT composite_model_routes_target_platform_check CHECK (target_platform IN ('anthropic', 'openai', 'gemini', 'antigravity', 'grok', - 'kimi', 'zhipu', 'deepseek', 'minimax', 'opencode_go', + 'kimi', 'zhipu', 'deepseek', 'minimax', 'opencode_go', 'typesafe', 'ollama_cloud')); DO $$ diff --git a/backend/migrations/912_restore_ollama_cloud_platform_checks.sql b/backend/migrations/912_restore_ollama_cloud_platform_checks.sql deleted file mode 100644 index e87ec292fc..0000000000 --- a/backend/migrations/912_restore_ollama_cloud_platform_checks.sql +++ /dev/null @@ -1,33 +0,0 @@ --- 恢复 Ollama Cloud 平台约束。 --- --- 背景:241_add_typesafe_platform.sql 把 user_platform_quotas.platform 与 --- composite_model_routes.target_platform 两个 CHECK 覆写为不含 'ollama_cloud' --- 的集合,会连带剔除 Ollama Cloud。本迁移在 241 之后重建这两个约束,集合为 --- 241 的全部平台并集 'ollama_cloud'。 --- --- 顺序:必须晚于 241(912 按文件名排序在其后)。新集合是 241 的超集,存量行 --- 瞬时通过校验,因此是默认的 validated 约束。 --- 适用 fresh 建库、空表升级与已应用 241 的环境;channel_monitors / --- channel_monitor_request_templates 的约束不在本次范围内,保持原状。 --- --- 仅放宽约束,无任何 DML 与数据回填。若 241 尚未应用而库中已存在 --- platform='ollama_cloud' 的行,说明其写入发生在更宽松的旧约束下,需在启动前 --- 停写核对;本迁移不做数据修复,也不能替代该前置处置。 - -ALTER TABLE user_platform_quotas - DROP CONSTRAINT IF EXISTS user_platform_quotas_platform_check; - -ALTER TABLE user_platform_quotas - ADD CONSTRAINT user_platform_quotas_platform_check - CHECK (platform IN ('anthropic', 'openai', 'gemini', 'antigravity', 'grok', - 'kimi', 'zhipu', 'deepseek', 'minimax', 'opencode_go', 'typesafe', - 'ollama_cloud')); - -ALTER TABLE composite_model_routes - DROP CONSTRAINT IF EXISTS composite_model_routes_target_platform_check; - -ALTER TABLE composite_model_routes - ADD CONSTRAINT composite_model_routes_target_platform_check - CHECK (target_platform IN ('anthropic', 'openai', 'gemini', 'antigravity', 'grok', - 'kimi', 'zhipu', 'deepseek', 'minimax', 'opencode_go', 'typesafe', - 'ollama_cloud')); diff --git a/backend/migrations/ollama_cloud_platform_migration_test.go b/backend/migrations/ollama_cloud_platform_migration_test.go index ab5362f775..27edd053fa 100644 --- a/backend/migrations/ollama_cloud_platform_migration_test.go +++ b/backend/migrations/ollama_cloud_platform_migration_test.go @@ -1,30 +1,72 @@ package migrations import ( + "regexp" "strings" "testing" "github.com/stretchr/testify/require" ) +// ollamaCloudPlatformMigrationFile 是 Ollama Cloud 平台迁移:一次性重建 +// user_platform_quotas / composite_model_routes / channel_monitors / +// channel_monitor_request_templates 四个 CHECK 约束。 +const ollamaCloudPlatformMigrationFile = "242_ollama_cloud_platform.sql" + +// dmlStatementPattern 匹配 DML 关键字;242 只允许 DDL 约束变更。 +var dmlStatementPattern = regexp.MustCompile(`(?i)\b(insert|update|delete|merge|truncate|copy|upsert)\b`) + +// stripSQLLineComments 去掉 "--" 行注释,只对可执行语句做结构校验。 +func stripSQLLineComments(content string) string { + var b strings.Builder + for _, line := range strings.Split(content, "\n") { + if idx := strings.Index(line, "--"); idx >= 0 { + line = line[:idx] + } + _, _ = b.WriteString(line) + _, _ = b.WriteString("\n") + } + return b.String() +} + +// executableSQL 返回去掉注释并归一化空白后的 SQL。 +func executableSQL(content []byte) string { + return strings.Join(strings.Fields(stripSQLLineComments(string(content))), " ") +} + +// TestOllamaCloudPlatformMigration 校验 242 一次性重建四个约束: +// 两张平台表为 241 的 11 项 ∪ {ollama_cloud}(12 项),两张监控表为 238 的 10 项 +// ∪ {ollama_cloud}(11 项,typesafe 不是对话模型不进 provider),且只有 DDL、零 DML。 func TestOllamaCloudPlatformMigration(t *testing.T) { - content, err := FS.ReadFile("239_ollama_cloud_platform.sql") + content, err := FS.ReadFile(ollamaCloudPlatformMigrationFile) require.NoError(t, err) sql := strings.Join(strings.Fields(string(content)), " ") - require.Contains(t, sql, "user_platform_quotas_platform_check") - require.Contains(t, sql, "composite_model_routes_target_platform_check") + require.Contains(t, sql, "DROP CONSTRAINT IF EXISTS user_platform_quotas_platform_check") + require.Contains(t, sql, "DROP CONSTRAINT IF EXISTS composite_model_routes_target_platform_check") require.Contains(t, sql, "channel_monitors_provider_check") require.Contains(t, sql, "channel_monitor_request_templates_provider_check") - require.Contains(t, sql, "'ollama_cloud'") - require.Contains(t, sql, "'minimax'") - require.Contains(t, sql, "'opencode_go'") + + // 四个约束各自恰好重建一次,不牵连其它约束。 + require.Equal(t, 4, strings.Count(sql, "ADD CONSTRAINT"), "242 只应新增四个约束") + require.Equal(t, 4, strings.Count(sql, "CHECK ("), "242 只应包含四个 CHECK") + + // 两张平台表:241 的平台集合 ∪ {ollama_cloud},必须同时保留 typesafe 与 ollama_cloud。 + require.Contains(t, sql, + "CHECK (platform IN ('anthropic', 'openai', 'gemini', 'antigravity', 'grok', 'kimi', 'zhipu', 'deepseek', 'minimax', 'opencode_go', 'typesafe', 'ollama_cloud'))") + require.Contains(t, sql, + "CHECK (target_platform IN ('anthropic', 'openai', 'gemini', 'antigravity', 'grok', 'kimi', 'zhipu', 'deepseek', 'minimax', 'opencode_go', 'typesafe', 'ollama_cloud'))") + + // 两张监控表:238 的 provider 集合 ∪ {ollama_cloud},不含 typesafe。 + require.Equal(t, 2, strings.Count(sql, + "CHECK (provider IN ('openai', 'anthropic', 'gemini', 'grok', 'antigravity', 'kimi', 'zhipu', 'deepseek', 'minimax', 'opencode_go', 'ollama_cloud'))"), + "两张监控表应重建为同一个 provider 集合(不含 typesafe)") + + // 监控表的两段保留幂等守卫:约束已含 ollama_cloud 时跳过重建。 require.Contains(t, sql, "position('ollama_cloud' IN monitor_constraint_def) = 0") require.Contains(t, sql, "position('ollama_cloud' IN template_constraint_def) = 0") - require.Contains(t, sql, - "CHECK (platform IN ('anthropic', 'openai', 'gemini', 'antigravity', 'grok', 'kimi', 'zhipu', 'deepseek', 'minimax', 'opencode_go', 'ollama_cloud'))") - require.Contains(t, sql, - "CHECK (target_platform IN ('anthropic', 'openai', 'gemini', 'antigravity', 'grok', 'kimi', 'zhipu', 'deepseek', 'minimax', 'opencode_go', 'ollama_cloud'))") - require.Contains(t, sql, - "CHECK (provider IN ('openai', 'anthropic', 'gemini', 'grok', 'antigravity', 'kimi', 'zhipu', 'deepseek', 'minimax', 'opencode_go', 'ollama_cloud'))") + + // 约束必须是默认 validated(非 NOT VALID),且整个文件只有 DDL。 + require.NotContains(t, sql, "NOT VALID", "平台 CHECK 必须是 validated 约束") + require.NotRegexp(t, dmlStatementPattern, executableSQL(content), "242 不得包含 DML 语句") } diff --git a/backend/migrations/ollama_typesafe_migration_compat_test.go b/backend/migrations/ollama_typesafe_migration_compat_test.go index c5cff39b9a..26d2e68dda 100644 --- a/backend/migrations/ollama_typesafe_migration_compat_test.go +++ b/backend/migrations/ollama_typesafe_migration_compat_test.go @@ -3,38 +3,13 @@ package migrations import ( "regexp" "sort" - "strings" "testing" "github.com/stretchr/testify/require" ) -// 912 兼容迁移与上游 typesafe 迁移(241)的文件名。 -const ( - restoreOllamaCloudPlatformChecksFile = "912_restore_ollama_cloud_platform_checks.sql" - typesafePlatformMigrationFile = "241_add_typesafe_platform.sql" -) - -// dmlStatementPattern 匹配 DML 关键字;912 只允许 DDL 约束变更。 -var dmlStatementPattern = regexp.MustCompile(`(?i)\b(insert|update|delete|merge|truncate|copy|upsert)\b`) - -// stripSQLLineComments 去掉 "--" 行注释,只对可执行语句做结构校验。 -func stripSQLLineComments(content string) string { - var b strings.Builder - for _, line := range strings.Split(content, "\n") { - if idx := strings.Index(line, "--"); idx >= 0 { - line = line[:idx] - } - _, _ = b.WriteString(line) - _, _ = b.WriteString("\n") - } - return b.String() -} - -// executableSQL 返回去掉注释并归一化空白后的 SQL。 -func executableSQL(content []byte) string { - return strings.Join(strings.Fields(stripSQLLineComments(string(content))), " ") -} +// 上游 typesafe 迁移(241)的文件名。 +const typesafePlatformMigrationFile = "241_add_typesafe_platform.sql" // platformCheckValues 提取 "CHECK ( IN (...))" 中的平台字面量。 func platformCheckValues(t *testing.T, sql, column string) []string { @@ -60,46 +35,33 @@ func sortedValues(values []string) []string { return out } -// TestRestoreOllamaCloudPlatformChecksMigration 校验 912: -// 只重建两个平台 CHECK、集合等于 241 的平台并集加 ollama_cloud、无 DML、 -// 且约束为默认 validated(非 NOT VALID)。 -func TestRestoreOllamaCloudPlatformChecksMigration(t *testing.T) { - content, err := FS.ReadFile(restoreOllamaCloudPlatformChecksFile) +// TestOllamaCloudPlatformChecksSupersetOfTypesafe 校验 242 的两张平台表 CHECK 集合 +// 恰为 241 的平台集合 ∪ {ollama_cloud}:既防止退回 241 覆写 ollama_cloud 的旧状态, +// 也防止 242 抄写平台列表时漏项或凭空多出平台。 +// +// 这里断言的是两个迁移之间的集合关系而非重复一份字面量,因此 241 若被上游改动 +// (理论上不可变,但仍可能被重编号或重写),失败信息能直接指出是基准变了还是 +// 242 漂移了。 +func TestOllamaCloudPlatformChecksSupersetOfTypesafe(t *testing.T) { + content, err := FS.ReadFile(ollamaCloudPlatformMigrationFile) require.NoError(t, err) - sql := executableSQL(content) - // 只处理两个平台 CHECK 约束,不触碰其它约束或表。 - require.Contains(t, sql, "DROP CONSTRAINT IF EXISTS user_platform_quotas_platform_check") - require.Contains(t, sql, "DROP CONSTRAINT IF EXISTS composite_model_routes_target_platform_check") - require.Contains(t, sql, "ADD CONSTRAINT user_platform_quotas_platform_check") - require.Contains(t, sql, "ADD CONSTRAINT composite_model_routes_target_platform_check") - require.Equal(t, 2, strings.Count(sql, "DROP CONSTRAINT IF EXISTS"), "912 只应移除两个约束") - require.Equal(t, 2, strings.Count(sql, "ADD CONSTRAINT"), "912 只应新增两个约束") - require.Equal(t, 2, strings.Count(sql, "CHECK ("), "912 只应包含两个 CHECK") - require.NotContains(t, sql, "channel_monitors") - require.NotContains(t, sql, "channel_monitor_request_templates") - require.NotContains(t, sql, "NOT VALID", "平台 CHECK 必须是 validated 约束") - - // 无任何 DML 语句。 - require.NotRegexp(t, dmlStatementPattern, sql, "912 不得包含 DML 语句") - typesafeContent, err := FS.ReadFile(typesafePlatformMigrationFile) require.NoError(t, err) typesafeSQL := executableSQL(typesafeContent) - // 集合 = 241 的平台集合 ∪ {ollama_cloud},不得漏类型或多类型。 for _, column := range []string{"platform", "target_platform"} { base := platformCheckValues(t, typesafeSQL, column) + require.NotContains(t, base, "ollama_cloud", "241 的基准平台集合不应含 ollama_cloud") expected := append(sortedValues(base), "ollama_cloud") sort.Strings(expected) - require.Equal(t, len(base)+1, len(expected), "%s 的基准平台集合不应含 ollama_cloud", column) actual := sortedValues(platformCheckValues(t, sql, column)) require.Equal(t, expected, actual, - "912 的 %s 集合必须等于 241 的平台并集加 ollama_cloud", column) - require.Contains(t, actual, "ollama_cloud") + "242 的 %s 集合必须等于 241 的平台并集加 ollama_cloud", column) require.Contains(t, actual, "typesafe") + require.Contains(t, actual, "ollama_cloud") } } From d2025b091f961e8fbcf9fcb11b6c3d9458129f99 Mon Sep 17 00:00:00 2001 From: alfadb Date: Thu, 8 Oct 2026 23:36:26 +0800 Subject: [PATCH 42/81] refactor(composite): keep upstream explicitModelMappingClaims as exact-match fast path MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 恢复上游 main 的 explicitModelMappingClaims(逐字一致),不再随本分支删除, 以减少后续 rebase 上游时的冲突面。 为避免该函数成为死代码,compositeMappingClaimStrength 增加一步快路径:原始 mapping 精确键命中即返回 Explicit。等价性前提是 stringMappingFromRaw 的原始 mapping 是 GetModelMapping 结果的子集(非空原始 mapping 逐键保留 string 值, 平台默认映射只向并集追加条目且不产生空目标),故命中必然等价于原首个精确分支的 Explicit,其余键仍走原有匹配顺序。行为不变。 --- backend/internal/service/composite_account_claims.go | 7 +++++++ backend/internal/service/gateway_service.go | 8 ++++++++ 2 files changed, 15 insertions(+) diff --git a/backend/internal/service/composite_account_claims.go b/backend/internal/service/composite_account_claims.go index ce260a87b2..dc0a1f9b9d 100644 --- a/backend/internal/service/composite_account_claims.go +++ b/backend/internal/service/composite_account_claims.go @@ -51,6 +51,13 @@ func CompositeAccountClaimStrength(account *Account, model string) CompositeClai // 归一化通配;命中即终止。映射目标为空的条目沿用既有 strict claim 语义:不构 // 成声明,也不回落通配(显式条目对通配具有遮蔽性,转发阶段同样走不到通配)。 func compositeMappingClaimStrength(account *Account, mapping map[string]string, model string) CompositeClaimStrength { + // 快路径:原始 mapping 精确键命中即返回显式声明。等价性前提是 stringMappingFromRaw + // 的原始 mapping 是 GetModelMapping 结果的子集(非空原始 mapping 逐键保留 string 值, + // 平台默认映射只向并集追加条目且不产生空目标),故此处命中必然等价于下方首个精确 + // 分支返回的 Explicit,其余键走原有匹配顺序。 + if explicitModelMappingClaims(*account, model) { + return CompositeClaimExplicit + } if mapped, exists := mapping[model]; exists { return compositeClaimStrengthForTarget(mapped, true) } diff --git a/backend/internal/service/gateway_service.go b/backend/internal/service/gateway_service.go index a5061e6758..d6606a14f6 100644 --- a/backend/internal/service/gateway_service.go +++ b/backend/internal/service/gateway_service.go @@ -1566,6 +1566,14 @@ func (s *GatewayService) resolveCompositeModelOwnership(ctx context.Context, gro return ownership, nil } +func explicitModelMappingClaims(account Account, model string) bool { + if account.Credentials == nil || model == "" { + return false + } + mapped, ok := stringMappingFromRaw(account.Credentials["model_mapping"])[model] + return ok && strings.TrimSpace(mapped) != "" +} + // GetCompositeRouteModels returns public IDs from enabled exact composite routes. func (s *GatewayService) GetCompositeRouteModels(ctx context.Context, groupID *int64, endpoint string, includeSystemOne bool) ([]string, error) { if s == nil || s.compositeResolver == nil || groupID == nil { From 9b40c4f0cd34cf0c65c33a60cf2e8a782128dc84 Mon Sep 17 00:00:00 2001 From: shaw Date: Fri, 9 Oct 2026 14:15:21 +0800 Subject: [PATCH 43/81] =?UTF-8?q?fix(composite):=20=E8=B7=A8=E6=97=8F?= =?UTF-8?q?=E8=B4=A6=E5=8F=B7=E6=B1=A0=E4=B8=AD=E6=8C=89=E6=A8=A1=E5=9E=8B?= =?UTF-8?q?=E5=88=86=E6=B5=81=E4=B8=8E=E6=97=A0=20Anthropic=20=E7=AB=AF?= =?UTF-8?q?=E7=82=B9=E7=9A=84=E5=A4=9A=E5=8D=8F=E8=AE=AE=E8=B4=A6=E5=8F=B7?= =?UTF-8?q?=E5=A7=94=E6=B4=BE=20OpenAI=20=E7=BD=91=E5=85=B3=E9=93=BE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit #7618 新增的 Command Code(按模型分流)与 Cline(仅 Chat Completions)不满足池逻辑 「adaptive 多协议账号具备 Anthropic 原生端点」的前提:Cline 被 servable 门静默排除, Command Code 走 generic Anthropic 原生链绕过 protocol_rules(GPT 模型被发到 /messages)。 新增 Account.RequiresOpenAIProtocolChain:adaptive 且按模型分流或没有 Anthropic 原生 端点的多协议账号由 OpenAI 网关链(resolveUpstreamProtocol)转发;此类账号可入池但 不由 generic count_tokens 计数。国产厂商与 Ollama Cloud 行为不变。 --- .../handler/composite_pool_attempt_policy.go | 5 ++ .../service/composite_generic_pool.go | 21 +++++++ .../composite_pool_openai_chain_test.go | 56 +++++++++++++++++++ 3 files changed, 82 insertions(+) create mode 100644 backend/internal/service/composite_pool_openai_chain_test.go diff --git a/backend/internal/handler/composite_pool_attempt_policy.go b/backend/internal/handler/composite_pool_attempt_policy.go index 4fc612f43a..9c96fc4548 100644 --- a/backend/internal/handler/composite_pool_attempt_policy.go +++ b/backend/internal/handler/composite_pool_attempt_policy.go @@ -232,6 +232,11 @@ func compositePoolAccountDelegatesToOpenAI(account *service.Account) bool { case service.PlatformAnthropic, service.PlatformGemini, service.PlatformAntigravity: return false } + if account.RequiresOpenAIProtocolChain() { + // 按模型分流的聚合平台与无 Anthropic 原生端点的供应商:只有 OpenAI 网关链 + // 能按模型选协议或完成协议转换。 + return true + } if account.IsAnthropicProtocol() || account.IsAdaptiveAPIProtocol() { // 多协议账号走既有 generic Forward(servable 门已保证 Anthropic 协议 // base 非空);不应停留在 Chat Completions 协议上被误委派。 diff --git a/backend/internal/service/composite_generic_pool.go b/backend/internal/service/composite_generic_pool.go index 48adffb25b..9458d0ad40 100644 --- a/backend/internal/service/composite_generic_pool.go +++ b/backend/internal/service/composite_generic_pool.go @@ -60,6 +60,11 @@ func genericCompositePoolAccountServable(account *Account) bool { case PlatformAnthropic, PlatformGemini, PlatformAntigravity: return true } + if account.RequiresOpenAIProtocolChain() { + // 由 handler 层委派 OpenAI 网关链转发(按模型分流 / 协议转换),不要求 + // Anthropic 协议上游 base。 + return true + } if account.IsAnthropicProtocol() || account.IsAdaptiveAPIProtocol() { return strings.TrimSpace(account.GetAnthropicProtocolBaseURL()) != "" } @@ -78,5 +83,21 @@ func GenericCompositePoolCountableAccount(account *Account) bool { case PlatformAnthropic, PlatformGemini, PlatformAntigravity: return true } + if account.RequiresOpenAIProtocolChain() { + return false + } return account.IsAnthropicProtocol() || account.IsAdaptiveAPIProtocol() } + +// RequiresOpenAIProtocolChain 报告 adaptive 多协议账号在跨族账号池中是否只能由 +// OpenAI 网关链转发:按模型分流的聚合平台(OpenCode、Command Code)须按 +// protocol_rules / 模型目录逐模型选协议,只有该链(resolveUpstreamProtocol)实现了 +// 这一分流;没有 Anthropic 原生端点的供应商(如 Cline 只有 Chat Completions)须由 +// 该链做协议转换。其余 adaptive 账号(国产厂商、Ollama Cloud)具备 Anthropic 原生 +// 端点,仍走 generic 转发。 +func (a *Account) RequiresOpenAIProtocolChain() bool { + if a == nil || !a.IsMultiProtocolAPIKey() || !a.IsAdaptiveAPIProtocol() { + return false + } + return a.routesByModel() || strings.TrimSpace(a.GetAnthropicProtocolBaseURL()) == "" +} diff --git a/backend/internal/service/composite_pool_openai_chain_test.go b/backend/internal/service/composite_pool_openai_chain_test.go new file mode 100644 index 0000000000..c9a456d3bf --- /dev/null +++ b/backend/internal/service/composite_pool_openai_chain_test.go @@ -0,0 +1,56 @@ +//go:build unit + +package service + +import ( + "testing" + + "github.com/stretchr/testify/require" +) + +// 跨族账号池中 adaptive 多协议账号的转发链选择:按模型分流的聚合平台与没有 +// Anthropic 原生端点的供应商只能由 OpenAI 网关链转发,其余具备 Anthropic 原生 +// 端点的供应商仍走 generic 转发。 +func TestRequiresOpenAIProtocolChain(t *testing.T) { + apiKey := func(platform string, credentials map[string]any) *Account { + creds := map[string]any{"api_key": "sk-test"} + for k, v := range credentials { + creds[k] = v + } + return &Account{ID: 1, Platform: platform, Type: AccountTypeAPIKey, Credentials: creds} + } + cases := []struct { + name string + account *Account + want bool + }{ + {"kimi adaptive has native anthropic", apiKey(PlatformKimi, map[string]any{"api_protocol": APIProtocolAdaptive}), false}, + {"ollama_cloud default adaptive has native anthropic", apiKey(PlatformOllamaCloud, nil), false}, + {"opencode_go routes by model", apiKey(PlatformOpenCodeGo, nil), true}, + {"command_code routes by model", apiKey(PlatformCommandCode, nil), true}, + {"cline adaptive has no anthropic endpoint", apiKey(PlatformCline, map[string]any{"api_protocol": APIProtocolAdaptive}), true}, + {"cline default chat completions is not adaptive", apiKey(PlatformCline, nil), false}, + {"kimi pinned anthropic", apiKey(PlatformKimi, map[string]any{"api_protocol": APIProtocolAnthropic}), false}, + {"openai is not multi-protocol", apiKey(PlatformOpenAI, nil), false}, + {"nil account", nil, false}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + require.Equal(t, tc.want, tc.account.RequiresOpenAIProtocolChain()) + }) + } +} + +func TestGenericCompositePoolOpenAIChainAccounts(t *testing.T) { + cline := &Account{ID: 2, Platform: PlatformCline, Type: AccountTypeAPIKey, Credentials: map[string]any{"api_key": "sk", "api_protocol": APIProtocolAdaptive}} + commandCode := &Account{ID: 3, Platform: PlatformCommandCode, Type: AccountTypeAPIKey, Credentials: map[string]any{"api_key": "sk"}} + kimi := &Account{ID: 4, Platform: PlatformKimi, Type: AccountTypeAPIKey, Credentials: map[string]any{"api_key": "sk", "api_protocol": APIProtocolAdaptive}} + + // 委派链账号可入池(不要求 Anthropic 协议 base),但不能由 generic count_tokens 计数。 + for _, account := range []*Account{cline, commandCode} { + require.True(t, genericCompositePoolAccountServable(account), account.Platform) + require.False(t, GenericCompositePoolCountableAccount(account), account.Platform) + } + require.True(t, genericCompositePoolAccountServable(kimi)) + require.True(t, GenericCompositePoolCountableAccount(kimi)) +} From 672ea007c8250acb095f6c5f24175593996172be Mon Sep 17 00:00:00 2001 From: shaw Date: Fri, 9 Oct 2026 14:56:14 +0800 Subject: [PATCH 44/81] =?UTF-8?q?fix(composite):=20=E4=BF=AE=E5=A4=8D?= =?UTF-8?q?=E8=B4=A6=E5=8F=B7=E6=B1=A0=E5=A7=94=E6=B4=BE=E8=AE=A1=E8=B4=B9?= =?UTF-8?q?=E3=80=81Gemini=20=E5=87=AD=E6=8D=AE=E5=A4=96=E5=8F=91=E4=B8=8E?= =?UTF-8?q?=E5=BD=92=E5=B1=9E=E8=A7=A3=E6=9E=90=E7=83=AD=E8=B7=AF=E5=BE=84?= =?UTF-8?q?=E6=9F=A5=E5=BA=93?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 委派计费(缓存 token 双计费):池委派 OpenAI 网关链的结果改走 OpenAI 计费链 (submitDelegatedOpenAIUsage)。原先适配成 ForwardResult 走 generic 计费,OpenAI 口径 input_tokens 含缓存读取,被同时记为输入与缓存读取,且丢失 BillingModel。 生图/搜索/语音等结果与 OpenAI handler 一样强制入账。 - Gemini 凭据外发:/v1/messages 池选中 Gemini 账号改交 Gemini 兼容链;/v1/responses 池整平台屏蔽 Gemini 后重选(无 Gemini Responses 转换链);generic Forward / ForwardAsResponses / ForwardAsChatCompletions 拒绝 Gemini 账号,count_tokens 对 Gemini 返回 404。原先无 base_url 的 Gemini API Key 会回落 api.anthropic.com 并以 x-api-key 发出。 - 归属解析:resolveCompositeModelOwnership 结果只取决于持久化配置,按 modelsListCache 短 TTL 缓存,不再每个 composite 请求查库;配置变更最多一个 TTL 后生效。 - 计费定价作用域:后扣在 worker ctx 上取不到目标平台,组合分组按 QuotaPlatform(实际 服务平台)限定渠道定价,不再按回退顺序取到其他平台的价格。 - 平台列表等价基准补入 ollama_cloud。 --- .../composite_generic_pool_messages_test.go | 29 +++++- .../handler/composite_pool_attempt_policy.go | 69 +++++++++++++- .../composite_pool_gemini_credentials_test.go | 89 +++++++++++++++++++ backend/internal/handler/gateway_handler.go | 29 ++++++ .../gateway_handler_chat_completions.go | 21 +++++ .../handler/gateway_handler_responses.go | 36 ++++++++ .../service/composite_ownership_cache_test.go | 46 ++++++++++ .../internal/service/gateway_count_tokens.go | 3 +- backend/internal/service/gateway_forward.go | 14 +++ .../gateway_forward_as_chat_completions.go | 3 + .../service/gateway_forward_as_responses.go | 3 + ...teway_gemini_anthropic_chain_guard_test.go | 55 ++++++++++++ .../gateway_hotpath_optimization_test.go | 19 ++-- backend/internal/service/gateway_service.go | 33 +++++-- .../internal/service/gateway_usage_billing.go | 18 ++++ .../internal/service/openai_gateway_usage.go | 1 + .../internal/service/platform_list_test.go | 15 ++-- .../service/usage_pricing_context_test.go | 34 +++++++ 18 files changed, 496 insertions(+), 21 deletions(-) create mode 100644 backend/internal/handler/composite_pool_gemini_credentials_test.go create mode 100644 backend/internal/service/composite_ownership_cache_test.go create mode 100644 backend/internal/service/gateway_gemini_anthropic_chain_guard_test.go create mode 100644 backend/internal/service/usage_pricing_context_test.go diff --git a/backend/internal/handler/composite_generic_pool_messages_test.go b/backend/internal/handler/composite_generic_pool_messages_test.go index a41e80f49c..76d067778d 100644 --- a/backend/internal/handler/composite_generic_pool_messages_test.go +++ b/backend/internal/handler/composite_generic_pool_messages_test.go @@ -171,7 +171,9 @@ func newCompositePoolMessagesHarness(t *testing.T, accounts []*service.Account) ) openAIGatewayService := service.NewOpenAIGatewayService( - nil, nil, nil, nil, nil, nil, nil, + nil, + usageRepo, // usageLogRepo:委派链结果按 OpenAI 计费链入账 + nil, nil, nil, nil, nil, cfg, nil, nil, billingService, @@ -461,3 +463,28 @@ func TestCompositePoolAccountDelegationPredicateAndAdapter(t *testing.T) { require.True(t, adapted.Stream) require.Equal(t, 2, adapted.SearchCount) } + +// 委派链结果必须按 OpenAI 口径入账:OpenAI usage 的 prompt_tokens 含缓存读取, +// 入账输入 = prompt_tokens - cached_tokens。转成 ForwardResult 走 generic 计费会把 +// 缓存 token 同时记为输入与缓存读取(双计费)。 +func TestCompositePoolMessagesDelegatedUsageExcludesCachedInputTokens(t *testing.T) { + h := newCompositePoolMessagesHarness(t, []*service.Account{poolKimiAccount(41151, 41011, 0)}) + h.openAIUpstream.respond = func(compositePoolUpstreamCall, int) *http.Response { + body := `{"id":"chatcmpl-pool-cache","object":"chat.completion","created":1,"model":"kimi-k3","choices":[{"index":0,"message":{"role":"assistant","content":"hi"},"finish_reason":"stop"}],"usage":{"prompt_tokens":100,"completion_tokens":7,"prompt_tokens_details":{"cached_tokens":80}}}` + return &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{"application/json"}, "X-Request-Id": []string{"req-cc-pool-cache"}}, + Body: io.NopCloser(strings.NewReader(body)), + } + } + + c, rec := h.newRequest(t, "/v1/messages", poolMessagesBody(), service.PlatformAnthropic, service.PlatformKimi) + h.handler.Messages(c) + require.Equal(t, http.StatusOK, rec.Code) + + logs := h.usageRepo.snapshot() + require.Len(t, logs, 1) + require.Equal(t, 20, logs[0].InputTokens, "缓存读取不得再计入输入 token") + require.Equal(t, 80, logs[0].CacheReadTokens) + require.Equal(t, 7, logs[0].OutputTokens) +} diff --git a/backend/internal/handler/composite_pool_attempt_policy.go b/backend/internal/handler/composite_pool_attempt_policy.go index 9c96fc4548..73fd70b6c3 100644 --- a/backend/internal/handler/composite_pool_attempt_policy.go +++ b/backend/internal/handler/composite_pool_attempt_policy.go @@ -4,9 +4,13 @@ import ( "context" "net/http" "strconv" + "time" + "github.com/Wei-Shaw/sub2api/internal/pkg/ip" + "github.com/Wei-Shaw/sub2api/internal/pkg/logger" "github.com/Wei-Shaw/sub2api/internal/service" "github.com/gin-gonic/gin" + "go.uber.org/zap" ) // composite 账号池 per-attempt 平台策略(审查修复增量4)。 @@ -273,9 +277,10 @@ func compositePoolAccountDelegatesChatCompletionsToOpenAI(account *service.Accou } // adaptOpenAIForwardResultToForwardResult 把委派链(OpenAIGatewayService 转发方法) -// 的转发结果适配进 generic 计费链的 ForwardResult:usage token 计数、模型、请求 -// 元数据与图片/搜索计费字段逐字段映射,经既有 usage 提交流入账,计费不丢。 -// nil 安全;错误路径携带的部分结果(流中断排水 usage)同样适配。 +// 的结果转成 generic handler 的 ForwardResult,仅供 failover / ops 指标等非计费用途。 +// 两者的 usage 口径不同(OpenAI input_tokens 含缓存读取,Anthropic 口径不含),且 +// ForwardResult 不携带 BillingModel 等 OpenAI 计费字段:委派结果必须经 +// submitDelegatedOpenAIUsage 走 OpenAI 计费链,不得用本函数的结果入账。 func adaptOpenAIForwardResultToForwardResult(src *service.OpenAIForwardResult) *service.ForwardResult { if src == nil { return nil @@ -315,3 +320,61 @@ func adaptOpenAIForwardResultToForwardResult(src *service.OpenAIForwardResult) * ImageSizeBreakdown: src.ImageSizeBreakdown, } } + +// delegatedOpenAIUsage 是池委派结果入账所需的请求级信息(handler 在请求 ctx 内算定)。 +type delegatedOpenAIUsage struct { + Result *service.OpenAIForwardResult + APIKey *service.APIKey + Account *service.Account + Subscription *service.UserSubscription + QuotaPlatform string + PricingAt time.Time + RequestPayloadHash string + ChannelUsageFields service.ChannelUsageFields + LogComponent string +} + +// submitDelegatedOpenAIUsage 用 OpenAI 网关计费链记录池委派结果:委派链产出的是 +// OpenAI 口径 usage(input_tokens 含缓存读取、BillingModel、生图/搜索附加计费等), +// 必须与该账号在 OpenAI 网关上被直接服务时同一口径入账。转成 ForwardResult 走 +// generic 计费会把缓存 token 重复计费并按公开别名计价。 +func (h *GatewayHandler) submitDelegatedOpenAIUsage(c *gin.Context, in delegatedOpenAIUsage) { + res := in.Result + if res == nil || in.APIKey == nil || in.Account == nil || h.openAIGatewayService == nil { + return + } + stampOpenAIRequestedReasoningEffort(res, c) + input := &service.OpenAIRecordUsageInput{ + Result: res, + APIKey: in.APIKey, + User: in.APIKey.User, + Account: in.Account, + Subscription: in.Subscription, + InboundEndpoint: GetInboundEndpoint(c), + UpstreamEndpoint: resolveOpenAIUpstreamEndpoint(c, in.Account, res), + UserAgent: c.GetHeader("User-Agent"), + IPAddress: ip.GetClientIP(c), + SessionID: service.ExtractClientSessionID(c), + RequestPayloadHash: in.RequestPayloadHash, + APIKeyService: h.apiKeyService, + QuotaPlatform: in.QuotaPlatform, + PricingAt: in.PricingAt, + ChannelUsageFields: in.ChannelUsageFields, + } + task := func(ctx context.Context) { + if err := h.openAIGatewayService.RecordUsage(ctx, input); err != nil { + logger.L().With( + zap.String("component", in.LogComponent), + zap.Int64("api_key_id", in.APIKey.ID), + zap.Any("group_id", in.APIKey.GroupID), + zap.Int64("account_id", in.Account.ID), + ).Error("gateway.composite_pool.delegated_record_usage_failed", zap.Error(err)) + } + } + // 与 OpenAI handler 同口径:生图、搜索附加费、语音等不可在溢出时丢弃。 + if res.ImageCount > 0 || res.VideoCount > 0 || res.SearchCount > 0 || res.WebSearchCalls > 0 || res.AudioUsage != nil { + h.submitMandatoryUsageRecordTask(c.Request.Context(), task) + return + } + h.submitUsageRecordTask(c.Request.Context(), task) +} diff --git a/backend/internal/handler/composite_pool_gemini_credentials_test.go b/backend/internal/handler/composite_pool_gemini_credentials_test.go new file mode 100644 index 0000000000..bb1d028cb8 --- /dev/null +++ b/backend/internal/handler/composite_pool_gemini_credentials_test.go @@ -0,0 +1,89 @@ +package handler + +import ( + "fmt" + "net/http" + "testing" + + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/stretchr/testify/require" +) + +// poolGeminiAccount 是没有 base_url 的 Gemini API Key 账号:若误入 Anthropic 协议 +// 转发链,GetBaseURL 会回落 api.anthropic.com,Google 凭据被发往错误主机。 +func poolGeminiAccount(id int64, groupID int64, priority int) *service.Account { + return &service.Account{ + ID: id, Name: fmt.Sprintf("gemini-%d", id), Platform: service.PlatformGemini, + Type: service.AccountTypeAPIKey, Status: service.StatusActive, Schedulable: true, + Concurrency: 1, Priority: priority, + AccountGroups: []service.AccountGroup{{AccountID: id, GroupID: groupID}}, + Credentials: map[string]any{ + "api_key": "google-secret-key", + "model_mapping": map[string]any{"my-model": "gemini-3.1-pro"}, + }, + } +} + +func requireNoAnthropicUpstreamCall(t *testing.T, h *compositePoolMessagesHarness) { + t.Helper() + require.Empty(t, h.gwUpstream.snapshot(), "Gemini 凭据不得经 Anthropic 协议链发出") + require.Empty(t, h.openAIUpstream.snapshot()) +} + +// /v1/messages 池选中 Gemini 账号:交 Gemini 兼容链,不得走 generic Anthropic Forward。 +// 夹具未装配 Gemini 兼容服务,请求以错误结束,关键是没有任何 Anthropic 上游请求。 +func TestCompositePoolMessagesGeminiAccountNeverUsesAnthropicChain(t *testing.T) { + h := newCompositePoolMessagesHarness(t, []*service.Account{poolGeminiAccount(43101, 41011, 0)}) + + c, rec := h.newRequest(t, "/v1/messages", poolMessagesBody(), service.PlatformAnthropic, service.PlatformGemini) + h.handler.Messages(c) + + require.NotEqual(t, http.StatusOK, rec.Code) + requireNoAnthropicUpstreamCall(t, h) +} + +// /v1/responses 没有 Gemini 转换链:池里只有 Gemini 账号时整平台屏蔽后无号可选, +// 请求失败且没有任何上游请求。 +func TestCompositePoolResponsesNeverSendsGeminiCredentials(t *testing.T) { + h := newCompositePoolMessagesHarness(t, []*service.Account{poolGeminiAccount(43201, 41011, 0)}) + + c, rec := h.newRequest(t, "/v1/responses", poolResponsesBody(), service.PlatformAnthropic, service.PlatformGemini) + h.handler.Responses(c) + + require.NotEqual(t, http.StatusOK, rec.Code) + requireNoAnthropicUpstreamCall(t, h) +} + +// 候选平台全部是 Gemini(其余平台已被屏蔽)时明确拒绝,而不是报账号耗尽。 +func TestCompositePoolResponsesRejectsWhenOnlyGeminiCandidatesRemain(t *testing.T) { + h := newCompositePoolMessagesHarness(t, []*service.Account{poolGeminiAccount(43251, 41011, 0)}) + + c, rec := h.newRequest(t, "/v1/responses", poolResponsesBody(), service.PlatformGemini) + h.handler.Responses(c) + + require.Equal(t, http.StatusBadRequest, rec.Code, rec.Body.String()) + require.Contains(t, rec.Body.String(), "/v1/responses") + requireNoAnthropicUpstreamCall(t, h) +} + +// /v1/responses 池同时有 Gemini 与 Anthropic 账号:屏蔽 Gemini 后改选 Anthropic 账号。 +func TestCompositePoolResponsesSkipsGeminiAndUsesOtherPlatform(t *testing.T) { + h := newCompositePoolMessagesHarness(t, []*service.Account{ + poolGeminiAccount(43301, 41011, 0), + poolAnthropicAccount(43302, 41011, 1), + }) + h.gwUpstream.respond = func(compositePoolUpstreamCall, int) *http.Response { + return anthropicMessagesSSEStreamResponse() + } + + c, rec := h.newRequest(t, "/v1/responses", poolResponsesBody(), service.PlatformAnthropic, service.PlatformGemini) + h.handler.Responses(c) + + require.Equal(t, http.StatusOK, rec.Code, rec.Body.String()) + calls := h.gwUpstream.snapshot() + require.Len(t, calls, 1) + require.NotContains(t, calls[0].Authorization, "google-secret-key") + selected, ok := c.Get(opsAccountIDKey) + require.True(t, ok) + require.EqualValues(t, 43302, selected) +} diff --git a/backend/internal/handler/gateway_handler.go b/backend/internal/handler/gateway_handler.go index 6cebb786be..5d5669eb5f 100644 --- a/backend/internal/handler/gateway_handler.go +++ b/backend/internal/handler/gateway_handler.go @@ -958,6 +958,8 @@ func (h *GatewayHandler) Messages(c *gin.Context) { // 转发请求 - 根据账号平台分流 c.Set("parsed_request", attemptParsedReq) var result *service.ForwardResult + // 池委派 OpenAI 网关链时的原始结果:按 OpenAI 口径入账(见 submitDelegatedOpenAIUsage)。 + var delegatedResult *service.OpenAIForwardResult requestCtx := c.Request.Context() if fs.SwitchCount > 0 { requestCtx = service.WithAccountSwitchCount(requestCtx, fs.SwitchCount, h.metadataBridgeEnabled()) @@ -974,6 +976,14 @@ func (h *GatewayHandler) Messages(c *gin.Context) { writerSizeBeforeForward := c.Writer.Size() if account.Platform == service.PlatformAntigravity && account.Type != service.AccountTypeAPIKey { result, err = h.antigravityGatewayService.Forward(requestCtx, c, account, attemptBody, hasBoundSession) + } else if isPoolRequest && account.Platform == service.PlatformGemini { + // Gemini 账号经 Gemini 兼容链转换(与非池 gemini 分支同一实现);generic + // Forward 只能发往 Anthropic 协议上游,会把 Google 凭据发错主机。 + if h.geminiCompatService == nil { + err = errors.New("gemini compatibility service is not configured") + } else { + result, err = h.geminiCompatService.Forward(requestCtx, c, account, attemptBody) + } } else if isPoolRequest && compositePoolAccountDelegatesToOpenAI(account) { // 纯 OpenAI 族账号(无 Anthropic 协议能力)在池激活时委派 OpenAI 网关的 // /v1/messages 兼容链:Anthropic → Responses/CC 协议转换、响应写回与 @@ -983,6 +993,7 @@ func (h *GatewayHandler) Messages(c *gin.Context) { openAIResult, delegateErr := h.openAIGatewayService.ForwardAsAnthropic( requestCtx, c, account, attemptBody, "", strings.TrimSpace(resolveOpenAIMessagesDispatchMappedModel(c, apiKey, reqModel))) + delegatedResult = openAIResult result = adaptOpenAIForwardResultToForwardResult(openAIResult) err = delegateErr } else { @@ -1003,6 +1014,24 @@ func (h *GatewayHandler) Messages(c *gin.Context) { // 提交 usage 记录。成功路径与"流中断但 Forward 已观测到 usage 的部分结果" // 错误路径共用:后者若不入账,上游已计量的请求会完全漏记漏计费(#5148)。 submitForwardUsage := func(result *service.ForwardResult) { + if delegatedResult != nil { + quotaPlatform := service.QuotaPlatform(c.Request.Context(), currentAPIKey) + if isPoolAttempt { + quotaPlatform = service.QuotaPlatform(attemptPolicy.AttemptCtx, currentAPIKey) + } + h.submitDelegatedOpenAIUsage(c, delegatedOpenAIUsage{ + Result: delegatedResult, + APIKey: currentAPIKey, + Account: account, + Subscription: currentSubscription, + QuotaPlatform: quotaPlatform, + PricingAt: pricingAt, + RequestPayloadHash: service.HashUsageRequestPayload(attemptBody), + ChannelUsageFields: clientRequestedUsageFields(c, attemptChannelMapping, reqModel, delegatedResult.UpstreamModel), + LogComponent: "handler.gateway.messages", + }) + return + } // 捕获请求信息(用于异步记录,避免在 goroutine 中访问 gin.Context) userAgent := c.GetHeader("User-Agent") clientIP := ip.GetClientIP(c) diff --git a/backend/internal/handler/gateway_handler_chat_completions.go b/backend/internal/handler/gateway_handler_chat_completions.go index 60ce23f38e..af1a08482d 100644 --- a/backend/internal/handler/gateway_handler_chat_completions.go +++ b/backend/internal/handler/gateway_handler_chat_completions.go @@ -350,6 +350,8 @@ func (h *GatewayHandler) ChatCompletions(c *gin.Context) { forwardBody = h.gatewayService.ReplaceModelInBody(body, attemptChannelMapping.MappedModel) } var result *service.ForwardResult + // 池委派 OpenAI 网关链时的原始结果:按 OpenAI 口径入账(见 submitDelegatedOpenAIUsage)。 + var delegatedResult *service.OpenAIForwardResult setActualUpstreamEndpoint(c, "") // 池请求的 attempt 局部 ctx 携带选中平台(不写回 c.Request):forward 内的 // 渠道定价作用域与计费 QuotaPlatform 跟随实际平台,对齐 Messages 池 attempt 语义。 @@ -383,6 +385,7 @@ func (h *GatewayHandler) ChatCompletions(c *gin.Context) { // 包装。defaultMappedModel 传 "",与 OpenAI handler CC 路径一致。 openAIResult, delegateErr := h.openAIGatewayService.ForwardAsChatCompletions( attemptCtx, c, account, forwardBody, poolPromptCacheKey, "") + delegatedResult = openAIResult result = adaptOpenAIForwardResultToForwardResult(openAIResult) err = delegateErr } else { @@ -427,6 +430,24 @@ func (h *GatewayHandler) ChatCompletions(c *gin.Context) { } // 6. Record usage + if delegatedResult != nil { + quotaPlatform := service.QuotaPlatform(c.Request.Context(), apiKey) + if isPoolAttempt { + quotaPlatform = service.QuotaPlatform(attemptPolicy.AttemptCtx, apiKey) + } + h.submitDelegatedOpenAIUsage(c, delegatedOpenAIUsage{ + Result: delegatedResult, + APIKey: apiKey, + Account: account, + Subscription: subscription, + QuotaPlatform: quotaPlatform, + PricingAt: pricingAt, + RequestPayloadHash: service.HashUsageRequestPayload(body), + ChannelUsageFields: clientRequestedUsageFields(c, attemptChannelMapping, reqModel, delegatedResult.UpstreamModel), + LogComponent: "handler.gateway.chat_completions", + }) + return + } userAgent := c.GetHeader("User-Agent") clientIP := ip.GetClientIP(c) requestPayloadHash := service.HashUsageRequestPayload(body) diff --git a/backend/internal/handler/gateway_handler_responses.go b/backend/internal/handler/gateway_handler_responses.go index be11cf2d3e..e4113fb334 100644 --- a/backend/internal/handler/gateway_handler_responses.go +++ b/backend/internal/handler/gateway_handler_responses.go @@ -240,6 +240,21 @@ func (h *GatewayHandler) Responses(c *gin.Context) { account := selection.Account setOpsSelectedAccount(c, account.ID, account.Platform) + // Gemini 账号没有 Responses 转换链(generic 链只能发往 Anthropic 协议上游,会把 + // Google 凭据发错主机):池请求整平台屏蔽 gemini 后重选,候选只剩 gemini 时终止。 + if isPoolRequest && account.Platform == service.PlatformGemini { + releaseCompositePoolSelection(selection) + h.gatewayService.ReleaseAccountSession(context.Background(), account, sessionHash) + poolDenials.deny(account.Platform) + fs.FailedAccountIDs[account.ID] = struct{}{} + if _, ok := compositePoolSelectionRetryContext(requestCtx, poolDenials); !ok { + h.responsesErrorResponse(c, http.StatusBadRequest, "invalid_request_error", + "Model is only available on Gemini accounts in this group, which do not support /v1/responses") + return + } + continue + } + // composite 账号池 per-attempt 平台策略:对实际选中平台补做 user×platform // 配额预检与渠道映射/限制(准入 CheckBillingEligibility 时池没有 resolved // 平台、这两个维度被跳过;不得只后扣不预检)。检查为纯读,不写 RPM/计数, @@ -336,6 +351,8 @@ func (h *GatewayHandler) Responses(c *gin.Context) { forwardBody = h.gatewayService.ReplaceModelInBody(body, attemptChannelMapping.MappedModel) } var result *service.ForwardResult + // 池委派 OpenAI 网关链时的原始结果:按 OpenAI 口径入账(见 submitDelegatedOpenAIUsage)。 + var delegatedResult *service.OpenAIForwardResult setActualUpstreamEndpoint(c, "") // 池请求的 attempt 局部 ctx 携带选中平台(不写回 requestCtx,否则下一轮 // 选号会被 resolved 平台截断池语义):forward 内的渠道定价作用域与计费 @@ -361,6 +378,7 @@ func (h *GatewayHandler) Responses(c *gin.Context) { // promptCacheKey 由链内从 body 派生(与 OpenAI handler Responses 路径一致)。 setOpenAIClientTransportHTTP(c) openAIResult, delegateErr := h.openAIGatewayService.Forward(attemptCtx, c, account, forwardBody) + delegatedResult = openAIResult result = adaptOpenAIForwardResultToForwardResult(openAIResult) err = delegateErr } else { @@ -406,6 +424,24 @@ func (h *GatewayHandler) Responses(c *gin.Context) { } // 6. Record usage + if delegatedResult != nil { + quotaPlatform := service.QuotaPlatform(c.Request.Context(), apiKey) + if isPoolAttempt { + quotaPlatform = service.QuotaPlatform(attemptPolicy.AttemptCtx, apiKey) + } + h.submitDelegatedOpenAIUsage(c, delegatedOpenAIUsage{ + Result: delegatedResult, + APIKey: apiKey, + Account: account, + Subscription: subscription, + QuotaPlatform: quotaPlatform, + PricingAt: pricingAt, + RequestPayloadHash: service.HashUsageRequestPayload(body), + ChannelUsageFields: clientRequestedUsageFields(c, attemptChannelMapping, reqModel, delegatedResult.UpstreamModel), + LogComponent: "handler.gateway.responses", + }) + return + } userAgent := c.GetHeader("User-Agent") clientIP := ip.GetClientIP(c) requestPayloadHash := service.HashUsageRequestPayload(body) diff --git a/backend/internal/service/composite_ownership_cache_test.go b/backend/internal/service/composite_ownership_cache_test.go new file mode 100644 index 0000000000..4e5d599634 --- /dev/null +++ b/backend/internal/service/composite_ownership_cache_test.go @@ -0,0 +1,46 @@ +package service + +import ( + "context" + "testing" + "time" + + gocache "github.com/patrickmn/go-cache" + "github.com/stretchr/testify/require" +) + +type countingOwnershipRepo struct { + compositeOwnershipScopedRepo + calls int +} + +func (r *countingOwnershipRepo) ListModelAvailabilityCandidates(ctx context.Context, groupID *int64, platforms []string, includeUnschedulable bool) ([]Account, error) { + r.calls++ + return r.compositeOwnershipScopedRepo.ListModelAvailabilityCandidates(ctx, groupID, platforms, includeUnschedulable) +} + +// 归属解析在每个 composite 请求上执行,结果只取决于持久化配置:同一分组+模型在 +// TTL 内只查一次库,且缓存值与调用方不共享候选平台切片。 +func TestResolveCompositeModelOwnershipCachesConfigResult(t *testing.T) { + const group = int64(9) + repo := &countingOwnershipRepo{compositeOwnershipScopedRepo: compositeOwnershipScopedRepo{records: []compositeOwnershipScopedRecord{ + {groupID: group, platform: PlatformKimi, schedulable: true, account: mappingAccount(1, PlatformKimi, "shared", "kimi-k3")}, + {groupID: group, platform: PlatformDeepseek, schedulable: true, account: mappingAccount(2, PlatformDeepseek, "shared", "deepseek-v4-pro")}, + }}} + svc := &GatewayService{accountRepo: repo, modelsListCache: gocache.New(time.Minute, time.Minute), modelsListCacheTTL: time.Minute} + + first, err := svc.resolveCompositeModelOwnership(context.Background(), group, "shared") + require.NoError(t, err) + require.True(t, first.Matched) + require.Equal(t, []string{PlatformDeepseek, PlatformKimi}, first.CandidatePlatforms) + first.CandidatePlatforms[0] = "mutated" + + second, err := svc.resolveCompositeModelOwnership(context.Background(), group, "shared") + require.NoError(t, err) + require.Equal(t, 1, repo.calls, "TTL 内同一分组+模型不得重复查库") + require.Equal(t, []string{PlatformDeepseek, PlatformKimi}, second.CandidatePlatforms, "缓存值不得被调用方修改") + + _, err = svc.resolveCompositeModelOwnership(context.Background(), group, "other-model") + require.NoError(t, err) + require.Equal(t, 2, repo.calls, "不同模型各自解析") +} diff --git a/backend/internal/service/gateway_count_tokens.go b/backend/internal/service/gateway_count_tokens.go index 93c544d16c..9b0de97774 100644 --- a/backend/internal/service/gateway_count_tokens.go +++ b/backend/internal/service/gateway_count_tokens.go @@ -104,8 +104,9 @@ func (s *GatewayService) ForwardCountTokens(ctx context.Context, c *gin.Context, } // Antigravity 账户不支持 count_tokens,返回 404 让客户端 fallback 到本地估算。 + // Gemini 账户同理,且本链按 Anthropic 上游拼地址,绝不能携带其凭据发出请求。 // 返回 nil 避免 handler 层记录为错误,也不设置 ops 上游错误上下文。 - if account.Platform == PlatformAntigravity { + if account.Platform == PlatformAntigravity || account.Platform == PlatformGemini { s.countTokensError(c, http.StatusNotFound, "not_found_error", "count_tokens endpoint is not supported for this platform") return nil } diff --git a/backend/internal/service/gateway_forward.go b/backend/internal/service/gateway_forward.go index c47e90967e..ec12832c3f 100644 --- a/backend/internal/service/gateway_forward.go +++ b/backend/internal/service/gateway_forward.go @@ -88,11 +88,25 @@ func sleepWithContext(ctx context.Context, d time.Duration) error { } // Forward 转发请求到Claude API +// rejectGeminiAccountOnAnthropicChain 拦截 Gemini 账号进入 Anthropic 协议转发链: +// 该链按 Anthropic 上游拼地址(Gemini API Key 账号无 base_url 时回落 +// api.anthropic.com)并按 Anthropic 方式携带凭据,Gemini 凭据会被发往错误的主机。 +// Gemini 账号必须经 GeminiMessagesCompatService 转换。 +func rejectGeminiAccountOnAnthropicChain(account *Account) error { + if account != nil && account.Platform == PlatformGemini { + return fmt.Errorf("account %d is a gemini account and cannot be forwarded through the anthropic protocol chain", account.ID) + } + return nil +} + func (s *GatewayService) Forward(ctx context.Context, c *gin.Context, account *Account, parsed *ParsedRequest) (result *ForwardResult, err error) { startTime := time.Now() if parsed == nil { return nil, fmt.Errorf("parse request: empty request") } + if err := rejectGeminiAccountOnAnthropicChain(account); err != nil { + return nil, err + } // API-key mappings and OAuth native IDs are resolved before mimicry. validationModel := parsed.Model if account != nil { diff --git a/backend/internal/service/gateway_forward_as_chat_completions.go b/backend/internal/service/gateway_forward_as_chat_completions.go index e655089361..1dd31dae2b 100644 --- a/backend/internal/service/gateway_forward_as_chat_completions.go +++ b/backend/internal/service/gateway_forward_as_chat_completions.go @@ -34,6 +34,9 @@ func (s *GatewayService) ForwardAsChatCompletions( parsed *ParsedRequest, ) (*ForwardResult, error) { startTime := time.Now() + if err := rejectGeminiAccountOnAnthropicChain(account); err != nil { + return nil, err + } // 1. Parse Chat Completions request var ccReq apicompat.ChatCompletionsRequest diff --git a/backend/internal/service/gateway_forward_as_responses.go b/backend/internal/service/gateway_forward_as_responses.go index db8033ebe4..4923da9842 100644 --- a/backend/internal/service/gateway_forward_as_responses.go +++ b/backend/internal/service/gateway_forward_as_responses.go @@ -36,6 +36,9 @@ func (s *GatewayService) ForwardAsResponses( parsed *ParsedRequest, ) (*ForwardResult, error) { startTime := time.Now() + if err := rejectGeminiAccountOnAnthropicChain(account); err != nil { + return nil, err + } normalizedBody, normalized, err := normalizeOpenAIResponsesLegacyIngress(body) if err != nil { diff --git a/backend/internal/service/gateway_gemini_anthropic_chain_guard_test.go b/backend/internal/service/gateway_gemini_anthropic_chain_guard_test.go new file mode 100644 index 0000000000..4a5ee3de8e --- /dev/null +++ b/backend/internal/service/gateway_gemini_anthropic_chain_guard_test.go @@ -0,0 +1,55 @@ +package service + +import ( + "context" + "net/http" + "net/http/httptest" + "testing" + + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +// Gemini 账号绝不能进入 Anthropic 协议转发链:该链按 Anthropic 上游拼地址并按 +// Anthropic 方式携带凭据(无 base_url 的 Gemini API Key 账号会回落 api.anthropic.com)。 +// 服务未装配 httpUpstream,若守卫失效会在发请求时 panic。 +func TestAnthropicChainRejectsGeminiAccounts(t *testing.T) { + gin.SetMode(gin.TestMode) + account := &Account{ID: 7, Platform: PlatformGemini, Type: AccountTypeAPIKey, Credentials: map[string]any{"api_key": "google-secret-key"}} + svc := &GatewayService{} + newCtx := func() *gin.Context { + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", nil) + return c + } + + body := []byte(`{"model":"my-model","max_tokens":16,"messages":[{"role":"user","content":"hi"}]}`) + parsed, err := ParseGatewayRequest(NewRequestBodyRef(body), PlatformAnthropic) + require.NoError(t, err) + _, err = svc.Forward(context.Background(), newCtx(), account, parsed) + require.ErrorContains(t, err, "gemini account") + + _, err = svc.ForwardAsResponses(context.Background(), newCtx(), account, []byte(`{"model":"my-model","input":"hi"}`), parsed) + require.ErrorContains(t, err, "gemini account") + + _, err = svc.ForwardAsChatCompletions(context.Background(), newCtx(), account, []byte(`{"model":"my-model","messages":[{"role":"user","content":"hi"}]}`), parsed) + require.ErrorContains(t, err, "gemini account") + + require.NoError(t, rejectGeminiAccountOnAnthropicChain(&Account{Platform: PlatformAnthropic})) + require.NoError(t, rejectGeminiAccountOnAnthropicChain(&Account{Platform: PlatformAntigravity})) + require.NoError(t, rejectGeminiAccountOnAnthropicChain(nil)) +} + +// count_tokens:Gemini 账号与 Antigravity 一样返回 404 让客户端回落本地估算,不发上游。 +func TestForwardCountTokensGeminiAccountReturnsNotFoundWithoutUpstream(t *testing.T) { + gin.SetMode(gin.TestMode) + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages/count_tokens", nil) + account := &Account{ID: 8, Platform: PlatformGemini, Type: AccountTypeAPIKey, Credentials: map[string]any{"api_key": "google-secret-key"}} + parsed, err := ParseGatewayRequest(NewRequestBodyRef([]byte(`{"model":"my-model","messages":[{"role":"user","content":"hi"}]}`)), PlatformAnthropic) + require.NoError(t, err) + + require.NoError(t, (&GatewayService{}).ForwardCountTokens(context.Background(), c, account, parsed)) + require.Equal(t, http.StatusNotFound, rec.Code) +} diff --git a/backend/internal/service/gateway_hotpath_optimization_test.go b/backend/internal/service/gateway_hotpath_optimization_test.go index db7e31d9ec..3e2455c11a 100644 --- a/backend/internal/service/gateway_hotpath_optimization_test.go +++ b/backend/internal/service/gateway_hotpath_optimization_test.go @@ -574,9 +574,9 @@ func TestGetAvailableModels_UsesShortCacheAndSupportsInvalidation(t *testing.T) require.Equal(t, int64(2), store) } -// Scenario: ownership 基于配置态查询即时解析——不经过 modelsListCache TTL, -// 配置移除声明后能力立即变化;瞬态限流字段不影响能力池。 -func TestResolveCompositeModelOwnershipReflectsConfigImmediately(t *testing.T) { +// Scenario: ownership 基于配置态查询解析并按 modelsListCache 短 TTL 缓存——热路径 +// TTL 内不重复查库;瞬态限流字段不影响能力池;配置变更在缓存过期后反映。 +func TestResolveCompositeModelOwnershipCachesConfigState(t *testing.T) { groupID := int64(9) rateLimitedReset := time.Now().Add(30 * time.Minute) repo := &modelsListAccountRepoStub{ @@ -599,7 +599,14 @@ func TestResolveCompositeModelOwnershipReflectsConfigImmediately(t *testing.T) { require.Equal(t, CompositeModelOwnership{TargetPlatform: PlatformDeepseek, Matched: true}, first) require.Equal(t, int64(1), repo.listByGroupCalls.Load()) + // TTL 内命中缓存,不再查库。 + cached, err := svc.resolveCompositeModelOwnership(context.Background(), groupID, "company-model") + require.NoError(t, err) + require.Equal(t, first, cached) + require.Equal(t, int64(1), repo.listByGroupCalls.Load()) + // 瞬态限流字段(配置态查询会忽略)不改变能力。 + svc.modelsListCache.Flush() repo.byGroup[groupID] = []Account{{ ID: 1, Platform: PlatformDeepseek, @@ -612,7 +619,8 @@ func TestResolveCompositeModelOwnershipReflectsConfigImmediately(t *testing.T) { require.Equal(t, first, transient) require.Equal(t, int64(2), repo.listByGroupCalls.Load()) - // 配置移除声明后能力立即消失(无 TTL 旧列表)。 + // 缓存过期后,配置移除声明即反映为能力消失。 + svc.modelsListCache.Flush() repo.byGroup[groupID] = []Account{{ ID: 2, Platform: PlatformOpenAI, @@ -622,7 +630,8 @@ func TestResolveCompositeModelOwnershipReflectsConfigImmediately(t *testing.T) { require.Equal(t, CompositeModelOwnership{}, removed) require.Equal(t, int64(3), repo.listByGroupCalls.Load()) - // 换平台声明后立即生效。 + // 缓存过期后,换平台声明生效。 + svc.modelsListCache.Flush() repo.byGroup[groupID] = []Account{{ ID: 2, Platform: PlatformOpenAI, diff --git a/backend/internal/service/gateway_service.go b/backend/internal/service/gateway_service.go index 1232f9885b..6a111f671c 100644 --- a/backend/internal/service/gateway_service.go +++ b/backend/internal/service/gateway_service.go @@ -72,8 +72,9 @@ const ( ) const ( - cacheTTLTarget5m = "5m" - cacheTTLTarget1h = "1h" + cacheTTLTarget5m = "5m" + cacheTTLTarget1h = "1h" + compositeModelOwnershipCachePrefix = "composite-owner|" ) // ForceCacheBillingContextKey 强制缓存计费上下文键 @@ -529,6 +530,10 @@ func modelsListCacheKey(groupID *int64, platform string) string { return fmt.Sprintf("%d|%s", derefGroupID(groupID), strings.TrimSpace(platform)) } +func compositeModelOwnershipCacheKey(groupID int64, model string) string { + return fmt.Sprintf("%s%d|%s", compositeModelOwnershipCachePrefix, groupID, strings.TrimSpace(model)) +} + func prefetchedStickyGroupIDFromContext(ctx context.Context) (int64, bool) { return PrefetchedStickyGroupIDFromContext(ctx) } @@ -1501,9 +1506,9 @@ func compositeOwnershipQueryPlatforms() []string { // resolveCompositeModelOwnership 基于持久化配置判断一个公开模型由组内哪些平台 // 提供。数据源是 ListModelAvailabilityCandidates(active + schedulable,显式 // 忽略限流/过载/临时不可调度等瞬态状态),能力谓词是统一共享的 -// CompositeAccountClaimStrength。刻意不经过 modelsListCache:旧 TTL 缓存会把 -// 「带瞬态过滤的旧健康列表」喂给池,全部候选 rate-limited 时能力会凭空消失; -// 移除后每次解析即反映最新配置(含 mapping 移除),代价是每次一次配置态查询。 +// CompositeAccountClaimStrength。结果只取决于持久化配置(不含限流等瞬态状态), +// 按 modelsListCache 的短 TTL 缓存:每个 composite 请求都会解析归属,不能每次查库; +// 配置变更(含 mapping 移除)最多一个 TTL 后生效,与 /v1/models 列表缓存同口径。 // // 声明强度分层:精确 mapping 命中与受控 native 空映射同为强声明;通配命中仅 // 为弱声明(fallback)。存在强声明平台时仅强声明平台构成池/单平台,完全无强 @@ -1517,6 +1522,15 @@ func (s *GatewayService) resolveCompositeModelOwnership(ctx context.Context, gro return CompositeModelOwnership{}, nil } + cacheKey := compositeModelOwnershipCacheKey(groupID, model) + if s.modelsListCache != nil { + if cached, found := s.modelsListCache.Get(cacheKey); found { + if ownership, ok := cached.(CompositeModelOwnership); ok { + return cloneCompositeModelOwnership(ownership), nil + } + } + } + accounts, err := s.accountRepo.ListModelAvailabilityCandidates(ctx, &groupID, compositeOwnershipQueryPlatforms(), true) if err != nil { return CompositeModelOwnership{}, err @@ -1560,9 +1574,18 @@ func (s *GatewayService) resolveCompositeModelOwnership(ctx context.Context, gro ownership.CandidatePlatforms = normalizeCompositeCandidatePlatforms(candidates) } } + if s.modelsListCache != nil { + s.modelsListCache.Set(cacheKey, cloneCompositeModelOwnership(ownership), s.modelsListCacheTTL) + } return ownership, nil } +// cloneCompositeModelOwnership 复制候选平台切片:缓存值与调用方互不共享底层数组。 +func cloneCompositeModelOwnership(ownership CompositeModelOwnership) CompositeModelOwnership { + ownership.CandidatePlatforms = cloneStringSlice(ownership.CandidatePlatforms) + return ownership +} + func explicitModelMappingClaims(account Account, model string) bool { if account.Credentials == nil || model == "" { return false diff --git a/backend/internal/service/gateway_usage_billing.go b/backend/internal/service/gateway_usage_billing.go index 3a612d17d0..07f7121ec3 100644 --- a/backend/internal/service/gateway_usage_billing.go +++ b/backend/internal/service/gateway_usage_billing.go @@ -761,7 +761,25 @@ func logResponseModelBillingApplied(component string, account *Account, requestI } // recordUsageCore 是 RecordUsage 的核心实现。 +// usagePricingContext 把组合分组的定价作用域限定到本次请求实际服务的平台。后扣运行在 +// worker 池的 background ctx 上,取不到请求期的目标平台;handler 已在请求 ctx 内把它算定 +// 为 QuotaPlatform(账号池请求为选中账号的平台)。各平台渠道定价严格独立,不能按组合 +// 分组的回退顺序取到其他平台的价格。 +func usagePricingContext(ctx context.Context, apiKey *APIKey, quotaPlatform string) context.Context { + if ctx == nil || apiKey == nil || apiKey.Group == nil || apiKey.Group.Platform != PlatformComposite { + return ctx + } + if _, ok := ResolvedTargetPlatformFromContext(ctx); ok { + return ctx + } + if platform := strings.TrimSpace(quotaPlatform); isConcreteRequestPlatform(platform) { + return WithResolvedTargetPlatform(ctx, platform) + } + return ctx +} + 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 diff --git a/backend/internal/service/openai_gateway_usage.go b/backend/internal/service/openai_gateway_usage.go index e97226cfad..0392bd7acb 100644 --- a/backend/internal/service/openai_gateway_usage.go +++ b/backend/internal/service/openai_gateway_usage.go @@ -225,6 +225,7 @@ 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) } diff --git a/backend/internal/service/platform_list_test.go b/backend/internal/service/platform_list_test.go index e6a0d83af8..f299c9c7b5 100644 --- a/backend/internal/service/platform_list_test.go +++ b/backend/internal/service/platform_list_test.go @@ -10,22 +10,25 @@ import ( ) // 以下为重构前各处手写的平台列表 / switch,作为平台清单派生结果的等价基准; -// 重构后新登记的平台(Command Code、Cline)按同类平台(OpenCode)的位置补入。 +// 重构后新登记的平台(Command Code、Cline)按同类平台(OpenCode)的位置补入; +// Ollama Cloud 按其合并前的手写实现补入。 var ( legacyAllPlatforms = []string{ PlatformAnthropic, PlatformOpenAI, PlatformGemini, PlatformAntigravity, PlatformGrok, PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo, PlatformTypeSafe, PlatformCommandCode, PlatformCline, + PlatformOllamaCloud, } legacySchedulerSnapshotPlatforms = []string{ PlatformAnthropic, PlatformGemini, PlatformOpenAI, PlatformAntigravity, PlatformGrok, PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo, PlatformTypeSafe, PlatformCommandCode, PlatformCline, + PlatformOllamaCloud, } legacyCompositeMatchingPlatforms = legacySchedulerSnapshotPlatforms - legacyMultiProtocolProviders = []string{PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo, PlatformCommandCode, PlatformCline} + legacyMultiProtocolProviders = []string{PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo, PlatformCommandCode, PlatformCline, PlatformOllamaCloud} platformProbeValues = append(append([]string{}, legacyAllPlatforms...), PlatformComposite, "", "moonshot", "Kimi", "openai ", "glm", "bogus") platformProbeAccountTypes = []string{AccountTypeAPIKey, AccountTypeOAuth, AccountTypeSetupToken, AccountTypeUpstream, ""} ) @@ -39,12 +42,12 @@ func legacyIsCNProvider(platform string) bool { } func legacyIsOpenAICompatible(platform string) bool { - return platform == PlatformOpenAI || platform == PlatformGrok || legacyIsCNProvider(platform) || platform == PlatformOpenCodeGo || platform == PlatformCommandCode || platform == PlatformCline + return platform == PlatformOpenAI || platform == PlatformGrok || legacyIsCNProvider(platform) || platform == PlatformOpenCodeGo || platform == PlatformCommandCode || platform == PlatformCline || platform == PlatformOllamaCloud } func legacyNormalizeOpenAICompatiblePlatform(platform string) string { switch platform { - case PlatformGrok, PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo, PlatformCommandCode, PlatformCline: + case PlatformGrok, PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo, PlatformCommandCode, PlatformCline, PlatformOllamaCloud: return platform } return PlatformOpenAI @@ -57,7 +60,7 @@ func legacyIsUpstreamBillingProbeIdentity(platform, accountType string) bool { switch platform { case PlatformOpenAI, PlatformAnthropic, PlatformGemini, PlatformAntigravity, PlatformGrok, PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo, - PlatformTypeSafe, PlatformCommandCode, PlatformCline: + PlatformTypeSafe, PlatformCommandCode, PlatformCline, PlatformOllamaCloud: return true } return false @@ -65,7 +68,7 @@ func legacyIsUpstreamBillingProbeIdentity(platform, accountType string) bool { func legacyIsHeaderOverrideEligible(platform, accountType string) bool { switch platform { - case PlatformAnthropic, PlatformOpenAI, PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo, PlatformCommandCode, PlatformCline: + case PlatformAnthropic, PlatformOpenAI, PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo, PlatformCommandCode, PlatformCline, PlatformOllamaCloud: return accountType == AccountTypeAPIKey case PlatformGrok: return accountType == AccountTypeAPIKey || accountType == AccountTypeOAuth diff --git a/backend/internal/service/usage_pricing_context_test.go b/backend/internal/service/usage_pricing_context_test.go new file mode 100644 index 0000000000..42fc4c20c6 --- /dev/null +++ b/backend/internal/service/usage_pricing_context_test.go @@ -0,0 +1,34 @@ +package service + +import ( + "context" + "testing" + + "github.com/stretchr/testify/require" +) + +// 后扣在 worker background ctx 上运行:组合分组必须按 handler 算定的实际平台 +// (QuotaPlatform)查渠道定价,而不是按组合分组的回退顺序取到其他平台的价格。 +func TestUsagePricingContextScopesCompositeGroupToActualPlatform(t *testing.T) { + composite := &APIKey{Group: &Group{ID: 1, Platform: PlatformComposite}} + + ctx := usagePricingContext(context.Background(), composite, PlatformKimi) + require.Equal(t, PlatformKimi, channelLookupPlatform(ctx, PlatformComposite)) + + // 未算定具体平台:保持组合分组回退语义。 + ctx = usagePricingContext(context.Background(), composite, PlatformComposite) + require.Equal(t, PlatformComposite, channelLookupPlatform(ctx, PlatformComposite)) + ctx = usagePricingContext(context.Background(), composite, "") + require.Equal(t, PlatformComposite, channelLookupPlatform(ctx, PlatformComposite)) + + // 请求期已解析的目标平台不被覆盖。 + resolved := WithResolvedTargetPlatform(context.Background(), PlatformOpenAI) + ctx = usagePricingContext(resolved, composite, PlatformKimi) + require.Equal(t, PlatformOpenAI, channelLookupPlatform(ctx, PlatformComposite)) + + // 非组合分组不受影响。 + concrete := &APIKey{Group: &Group{ID: 2, Platform: PlatformKimi}} + base := context.Background() + require.Equal(t, base, usagePricingContext(base, concrete, PlatformOpenAI)) + require.Equal(t, base, usagePricingContext(base, &APIKey{}, PlatformOpenAI)) +} From fce2d45a367e0dcc2b93f5374c12ef7dc9606970 Mon Sep 17 00:00:00 2001 From: shaw Date: Fri, 9 Oct 2026 15:10:30 +0800 Subject: [PATCH 45/81] =?UTF-8?q?fix(composite):=20=E6=81=A2=E5=A4=8D=20an?= =?UTF-8?q?tigravity=20=E6=B7=B7=E5=90=88=E8=B0=83=E5=BA=A6=E5=BC=80?= =?UTF-8?q?=E5=85=B3=E5=B9=B6=E6=8C=89=E5=BD=92=E5=B1=9E=E5=B1=82=E7=BA=A7?= =?UTF-8?q?=E6=89=A7=E8=A1=8C=20account=5Fmodel=20=E5=90=A6=E5=86=B3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - antigravity 混合调度开关:平台默认映射让 antigravity 账号对 Claude / Gemini 模型 构成强声明,组合分组因此绕过混合调度开关。改为未开启混合调度的 antigravity 账号只按 管理员显式配置的映射构成声明(与 main 的 composite 声明及非 composite 混合调度同语义), 归属解析、池准入、account_model 否决三处一致生效。 - account_model 否决层级:否决与池模型门由「任意强度声明」放宽导致同平台通配 catch-all 账号冒领显式绑定的公开模型。归属记录构成时采用的声明层级(有强声明为显式, 否则通配),经路由决策写入 ctx;三个否决点与两个池模型门改用 CompositeAccountMeetsClaimTier,无层级信息时保持任意强度语义。 --- backend/internal/pkg/ctxkey/ctxkey.go | 4 + .../service/composite_account_claims.go | 29 ++++++- .../composite_antigravity_mixed_claim_test.go | 24 ++++++ .../service/composite_claim_tier_test.go | 86 +++++++++++++++++++ .../internal/service/composite_model_route.go | 6 ++ .../internal/service/composite_platform.go | 11 ++- .../service/composite_platform_test.go | 10 +-- .../service/composite_pool_contract_test.go | 9 +- .../service/composite_route_resolver.go | 28 +++--- .../gateway_hotpath_optimization_test.go | 4 +- .../internal/service/gateway_scheduling.go | 4 +- backend/internal/service/gateway_service.go | 5 ++ .../service/openai_account_scheduler.go | 2 +- .../service/openai_account_scheduler_test.go | 4 +- .../service/openai_gateway_scheduling.go | 4 +- 15 files changed, 196 insertions(+), 34 deletions(-) create mode 100644 backend/internal/service/composite_antigravity_mixed_claim_test.go create mode 100644 backend/internal/service/composite_claim_tier_test.go diff --git a/backend/internal/pkg/ctxkey/ctxkey.go b/backend/internal/pkg/ctxkey/ctxkey.go index 02aa89bfa1..b35aaa92d2 100644 --- a/backend/internal/pkg/ctxkey/ctxkey.go +++ b/backend/internal/pkg/ctxkey/ctxkey.go @@ -20,6 +20,10 @@ const ( // CompositeRouteSource 标识 composite 解析结果来自显式路由还是内置模型探测。 CompositeRouteSource Key = "ctx_composite_route_source" + // CompositeRequiredClaimStrength 是 composite 账号归属(account_model / account_pool) + // 构成时采用的声明层级:账号须达到该层级才能承接请求。 + CompositeRequiredClaimStrength Key = "ctx_composite_required_claim_strength" + // CompositeCandidatePlatforms 是 composite 多平台候选池(account_pool 决策) // 的参与平台集合(去重升序)。与 ResolvedTargetPlatform 互斥写入:池决策不 // 固定单一目标平台,选号期间不得被最终账号平台覆盖。 diff --git a/backend/internal/service/composite_account_claims.go b/backend/internal/service/composite_account_claims.go index dc0a1f9b9d..533faac4c3 100644 --- a/backend/internal/service/composite_account_claims.go +++ b/backend/internal/service/composite_account_claims.go @@ -1,6 +1,11 @@ package service -import "strings" +import ( + "context" + "strings" + + "github.com/Wei-Shaw/sub2api/internal/pkg/ctxkey" +) // CompositeClaimStrength 表达账号对某模型的声明强度。ownership 据此分层: // 存在强声明平台时池/单平台仅由强声明平台构成,完全无强声明才回退通配命中 @@ -32,6 +37,12 @@ func CompositeAccountClaimStrength(account *Account, model string) CompositeClai } mapping := account.GetModelMapping() + if account.Platform == PlatformAntigravity && !account.IsMixedSchedulingEnabled() { + // 平台默认映射(Claude / Gemini 模型)只在开启混合调度时才让 antigravity 账号 + // 服务这些模型,与非 composite 的混合调度开关同一语义;未开启时只有管理员在 + // 账号上显式配置的映射构成声明。 + mapping = stringMappingFromRaw(account.Credentials["model_mapping"]) + } if len(mapping) == 0 { // 规则B:空 mapping 仅受控 native 声明。OpenAI OAuth 空 mapping 仍受 // isOpenAIOAuthServableModel 约束(IsModelSupported 内部处理)。 @@ -105,3 +116,19 @@ func compositeClaimStrengthForTarget(mapped string, exact bool) CompositeClaimSt func CompositeAccountClaimsModel(account *Account, model string) bool { return CompositeAccountClaimStrength(account, model) != CompositeClaimNone } + +// CompositeAccountMeetsClaimTier 是选号期的 composite 归属判定(account_model 否决与 +// 账号池模型门共用):账号对公开模型的声明强度须达到构成本次归属时采用的层级。存在 +// 强声明平台时只有强声明账号可承接,通配 catch-all 账号不得冒领显式绑定的公开模型; +// ctx 无层级信息时任意强度均可(等价 CompositeAccountClaimsModel)。 +func CompositeAccountMeetsClaimTier(ctx context.Context, account *Account, model string) bool { + strength := CompositeAccountClaimStrength(account, model) + if strength == CompositeClaimNone { + return false + } + if ctx == nil { + return true + } + required, ok := ctx.Value(ctxkey.CompositeRequiredClaimStrength).(CompositeClaimStrength) + return !ok || strength >= required +} diff --git a/backend/internal/service/composite_antigravity_mixed_claim_test.go b/backend/internal/service/composite_antigravity_mixed_claim_test.go new file mode 100644 index 0000000000..7043f7ccb0 --- /dev/null +++ b/backend/internal/service/composite_antigravity_mixed_claim_test.go @@ -0,0 +1,24 @@ +package service + +import ( + "testing" + + "github.com/stretchr/testify/require" +) + +// antigravity 账号的平台默认映射(Claude / Gemini 模型)只在开启混合调度时构成 +// composite 声明;未开启时只认管理员显式配置的映射,与非 composite 混合调度开关同语义。 +func TestCompositeClaimAntigravityDefaultMappingRequiresMixedScheduling(t *testing.T) { + const model = "claude-sonnet-4-5" + mixedOff := &Account{ID: 1, Platform: PlatformAntigravity, Type: AccountTypeOAuth} + require.Equal(t, CompositeClaimNone, CompositeAccountClaimStrength(mixedOff, model)) + require.False(t, CompositeAccountClaimsModel(mixedOff, model)) + + mixedOn := &Account{ID: 2, Platform: PlatformAntigravity, Type: AccountTypeOAuth, Extra: map[string]any{"mixed_scheduling": true}} + require.Equal(t, CompositeClaimExplicit, CompositeAccountClaimStrength(mixedOn, model)) + + explicitMixedOff := &Account{ID: 3, Platform: PlatformAntigravity, Type: AccountTypeOAuth, + Credentials: map[string]any{"model_mapping": map[string]any{"team-alias": "claude-opus-4-8"}}} + require.Equal(t, CompositeClaimExplicit, CompositeAccountClaimStrength(explicitMixedOff, "team-alias")) + require.Equal(t, CompositeClaimNone, CompositeAccountClaimStrength(explicitMixedOff, model), "默认映射条目不因存在自定义映射而生效") +} diff --git a/backend/internal/service/composite_claim_tier_test.go b/backend/internal/service/composite_claim_tier_test.go new file mode 100644 index 0000000000..9f70f37837 --- /dev/null +++ b/backend/internal/service/composite_claim_tier_test.go @@ -0,0 +1,86 @@ +package service + +import ( + "context" + "testing" + + "github.com/stretchr/testify/require" +) + +// 存在强声明平台时,account_model 否决与池模型门只放行强声明账号:同平台的通配 +// catch-all 账号不得冒领管理员显式绑定的公开模型(main 上该否决为精确匹配)。 +func TestCompositeAccountMeetsClaimTierFollowsOwnershipTier(t *testing.T) { + const publicModel = "grok-public" + explicit := &Account{ID: 1, Platform: PlatformGrok, Type: AccountTypeAPIKey, + Credentials: map[string]any{"model_mapping": map[string]any{publicModel: "grok-4.3"}}} + wildcard := &Account{ID: 2, Platform: PlatformGrok, Type: AccountTypeAPIKey, + Credentials: map[string]any{"model_mapping": map[string]any{"*": "grok-3-mini"}}} + none := &Account{ID: 3, Platform: PlatformGrok, Type: AccountTypeAPIKey, + Credentials: map[string]any{"model_mapping": map[string]any{"other": "grok-3"}}} + + strongCtx := WithCompositeRouteDecision(context.Background(), CompositeRouteDecision{ + Matched: true, Source: CompositeRouteSourceAccount, PublicModel: publicModel, + TargetPlatform: PlatformGrok, UpstreamModel: publicModel, RequiredClaimStrength: CompositeClaimExplicit, + }) + require.True(t, CompositeAccountMeetsClaimTier(strongCtx, explicit, publicModel)) + require.False(t, CompositeAccountMeetsClaimTier(strongCtx, wildcard, publicModel)) + require.False(t, CompositeAccountMeetsClaimTier(strongCtx, none, publicModel)) + + // 无强声明、按通配回退构成归属时,通配账号可承接。 + wildcardCtx := WithCompositeRouteDecision(context.Background(), CompositeRouteDecision{ + Matched: true, Source: CompositeRouteSourceAccount, PublicModel: publicModel, + TargetPlatform: PlatformGrok, UpstreamModel: publicModel, RequiredClaimStrength: CompositeClaimWildcard, + }) + require.True(t, CompositeAccountMeetsClaimTier(wildcardCtx, wildcard, publicModel)) + require.False(t, CompositeAccountMeetsClaimTier(wildcardCtx, none, publicModel)) + + // 无层级信息:任意强度均可(等价 CompositeAccountClaimsModel)。 + require.True(t, CompositeAccountMeetsClaimTier(context.Background(), wildcard, publicModel)) + + // 池决策同样携带层级。 + poolCtx := WithCompositeRouteDecision(context.Background(), CompositeRouteDecision{ + Matched: true, Source: CompositeRouteSourceAccountPool, PublicModel: publicModel, + CandidatePlatforms: []string{PlatformGrok, PlatformOpenAI}, RequiredClaimStrength: CompositeClaimExplicit, + }) + require.False(t, CompositeAccountMeetsClaimTier(poolCtx, wildcard, publicModel)) +} + +func TestResolveCompositeModelOwnershipRecordsClaimTier(t *testing.T) { + const group = int64(11) + strongRepo := &compositeOwnershipScopedRepo{records: []compositeOwnershipScopedRecord{ + {groupID: group, platform: PlatformGrok, schedulable: true, account: mappingAccount(1, PlatformGrok, "alias", "grok-4.3")}, + {groupID: group, platform: PlatformOpenAI, schedulable: true, account: Account{ID: 2, Platform: PlatformOpenAI, Credentials: map[string]any{"model_mapping": map[string]any{"*": "gpt-5"}}}}, + }} + ownership, err := (&GatewayService{accountRepo: strongRepo}).resolveCompositeModelOwnership(context.Background(), group, "alias") + require.NoError(t, err) + require.Equal(t, PlatformGrok, ownership.TargetPlatform) + require.Equal(t, CompositeClaimExplicit, ownership.RequiredClaimStrength) + + wildcardRepo := &compositeOwnershipScopedRepo{records: []compositeOwnershipScopedRecord{ + {groupID: group, platform: PlatformOpenAI, schedulable: true, account: Account{ID: 2, Platform: PlatformOpenAI, Credentials: map[string]any{"model_mapping": map[string]any{"*": "gpt-5"}}}}, + }} + ownership, err = (&GatewayService{accountRepo: wildcardRepo}).resolveCompositeModelOwnership(context.Background(), group, "alias") + require.NoError(t, err) + require.Equal(t, PlatformOpenAI, ownership.TargetPlatform) + require.Equal(t, CompositeClaimWildcard, ownership.RequiredClaimStrength) +} + +func TestCompositeRouteResolverPropagatesClaimTier(t *testing.T) { + const group = int64(12) + resolver, _ := newOllamaOwnershipResolver( + compositeOwnershipScopedRecord{groupID: group, platform: PlatformGrok, schedulable: true, + account: mappingAccount(1, PlatformGrok, "alias", "grok-4.3")}, + compositeOwnershipScopedRecord{groupID: group, platform: PlatformGrok, schedulable: true, + account: Account{ID: 2, Platform: PlatformGrok, Credentials: map[string]any{"model_mapping": map[string]any{"*": "grok-3-mini"}}}}, + ) + decision, err := resolver.Resolve(context.Background(), group, "alias", CompositeRouteEndpointResponses) + require.NoError(t, err) + require.Equal(t, CompositeRouteSourceAccount, decision.Source) + require.Equal(t, CompositeClaimExplicit, decision.RequiredClaimStrength) + + ctx := WithCompositeRouteDecision(context.Background(), decision) + require.True(t, CompositeAccountMeetsClaimTier(ctx, &Account{ID: 1, Platform: PlatformGrok, + Credentials: map[string]any{"model_mapping": map[string]any{"alias": "grok-4.3"}}}, "alias")) + require.False(t, CompositeAccountMeetsClaimTier(ctx, &Account{ID: 2, Platform: PlatformGrok, + Credentials: map[string]any{"model_mapping": map[string]any{"*": "grok-3-mini"}}}, "alias")) +} diff --git a/backend/internal/service/composite_model_route.go b/backend/internal/service/composite_model_route.go index aa2d9b52a0..da5c8ea9e8 100644 --- a/backend/internal/service/composite_model_route.go +++ b/backend/internal/service/composite_model_route.go @@ -42,6 +42,9 @@ type CompositeModelOwnership struct { Matched bool Ambiguous bool CandidatePlatforms []string + // RequiredClaimStrength 是构成归属时采用的声明层级:存在强声明平台时为 + // CompositeClaimExplicit,否则为 CompositeClaimWildcard。 + RequiredClaimStrength CompositeClaimStrength } type CompositeModelOwnershipResolver func(context.Context, int64, string) (CompositeModelOwnership, error) @@ -91,6 +94,9 @@ type CompositeRouteDecision struct { CandidatePlatforms []string `json:"candidate_platforms,omitempty"` Route *CompositeModelRoute `json:"route,omitempty"` Reason string `json:"reason,omitempty"` + // RequiredClaimStrength 仅账号归属决策携带:选号时账号对公开模型的声明须达到 + // 该层级(见 CompositeAccountMeetsClaimTier)。 + RequiredClaimStrength CompositeClaimStrength `json:"-"` } // isCompositePoolDecision reports whether the decision carries a multi-platform diff --git a/backend/internal/service/composite_platform.go b/backend/internal/service/composite_platform.go index 4d2cba03e6..2e519253e6 100644 --- a/backend/internal/service/composite_platform.go +++ b/backend/internal/service/composite_platform.go @@ -96,7 +96,7 @@ func WithCompositeRouteDecision(ctx context.Context, decision CompositeRouteDeci if source := strings.TrimSpace(decision.Source); source != "" { ctx = context.WithValue(ctx, ctxkey.CompositeRouteSource, source) } - return ctx + return withCompositeRequiredClaimStrength(ctx, decision.RequiredClaimStrength) } ctx = WithResolvedTargetPlatform(ctx, decision.TargetPlatform) if model := strings.TrimSpace(decision.UpstreamModel); model != "" { @@ -108,7 +108,14 @@ func WithCompositeRouteDecision(ctx context.Context, decision CompositeRouteDeci if source := strings.TrimSpace(decision.Source); source != "" { ctx = context.WithValue(ctx, ctxkey.CompositeRouteSource, source) } - return ctx + return withCompositeRequiredClaimStrength(ctx, decision.RequiredClaimStrength) +} + +func withCompositeRequiredClaimStrength(ctx context.Context, strength CompositeClaimStrength) context.Context { + if strength <= CompositeClaimNone { + return ctx + } + return context.WithValue(ctx, ctxkey.CompositeRequiredClaimStrength, strength) } func ResolvedUpstreamModelFromContext(ctx context.Context) (string, bool) { diff --git a/backend/internal/service/composite_platform_test.go b/backend/internal/service/composite_platform_test.go index 22f769113f..2bafb19d7a 100644 --- a/backend/internal/service/composite_platform_test.go +++ b/backend/internal/service/composite_platform_test.go @@ -48,11 +48,11 @@ func TestResolveCompositeModelOwnershipKeepsProviderAccountsIsolated(t *testing. deepSeekOwnership, err := svc.resolveCompositeModelOwnership(context.Background(), groupID, "reasoning-alias") require.NoError(t, err) - require.Equal(t, CompositeModelOwnership{TargetPlatform: PlatformDeepseek, Matched: true}, deepSeekOwnership) + require.Equal(t, CompositeModelOwnership{TargetPlatform: PlatformDeepseek, Matched: true, RequiredClaimStrength: CompositeClaimExplicit}, deepSeekOwnership) openAIOwnership, err := svc.resolveCompositeModelOwnership(context.Background(), groupID, "gpt-public") require.NoError(t, err) - require.Equal(t, CompositeModelOwnership{TargetPlatform: PlatformOpenAI, Matched: true}, openAIOwnership) + require.Equal(t, CompositeModelOwnership{TargetPlatform: PlatformOpenAI, Matched: true, RequiredClaimStrength: CompositeClaimExplicit}, openAIOwnership) } // Scenario: 通配映射按既有通配语义声明;映射目标为空的别名不构成声明; @@ -80,7 +80,7 @@ func TestResolveCompositeModelOwnershipHonorsWildcardMappings(t *testing.T) { for _, model := range []string{"gpt-5", "unknown-alias"} { ownership, err := svc.resolveCompositeModelOwnership(context.Background(), groupID, model) require.NoError(t, err) - require.Equal(t, CompositeModelOwnership{TargetPlatform: PlatformOpenAI, Matched: true}, ownership, "model=%s", model) + require.Equal(t, CompositeModelOwnership{TargetPlatform: PlatformOpenAI, Matched: true, RequiredClaimStrength: CompositeClaimWildcard}, ownership, "model=%s", model) } // 映射目标为空的条目不构成声明,也无其他平台可声明。 @@ -92,7 +92,7 @@ func TestResolveCompositeModelOwnershipHonorsWildcardMappings(t *testing.T) { // 否则 grok 请求会被改写成 gpt-5(回归)。 ownership, err = svc.resolveCompositeModelOwnership(context.Background(), groupID, "grok-public") require.NoError(t, err) - require.Equal(t, CompositeModelOwnership{TargetPlatform: PlatformGrok, Matched: true}, ownership) + require.Equal(t, CompositeModelOwnership{TargetPlatform: PlatformGrok, Matched: true, RequiredClaimStrength: CompositeClaimExplicit}, ownership) } func TestResolveCompositeModelOwnershipAllowsSamePlatformAndRejectsCrossPlatformAliases(t *testing.T) { @@ -108,7 +108,7 @@ func TestResolveCompositeModelOwnershipAllowsSamePlatformAndRejectsCrossPlatform samePlatform, err := svc.resolveCompositeModelOwnership(context.Background(), groupID, "shared-openai") require.NoError(t, err) - require.Equal(t, CompositeModelOwnership{TargetPlatform: PlatformOpenAI, Matched: true}, samePlatform) + require.Equal(t, CompositeModelOwnership{TargetPlatform: PlatformOpenAI, Matched: true, RequiredClaimStrength: CompositeClaimExplicit}, samePlatform) // 跨平台同名别名:返回稳定候选池(去重升序),不再是裸 Ambiguous。 ambiguous, err := svc.resolveCompositeModelOwnership(context.Background(), groupID, "ambiguous") diff --git a/backend/internal/service/composite_pool_contract_test.go b/backend/internal/service/composite_pool_contract_test.go index 79cc63a283..089f1d3349 100644 --- a/backend/internal/service/composite_pool_contract_test.go +++ b/backend/internal/service/composite_pool_contract_test.go @@ -91,7 +91,7 @@ func TestCompositePoolOwnershipDeepseekNativePlusOpenCodeMapping(t *testing.T) { // 仅 deepseek 空 mapping 声明时保持 single(既有语义)。 single, err := svc.resolveCompositeModelOwnership(context.Background(), groupID, "deepseek-v4-pro") require.NoError(t, err) - require.Equal(t, CompositeModelOwnership{TargetPlatform: PlatformDeepseek, Matched: true}, single) + require.Equal(t, CompositeModelOwnership{TargetPlatform: PlatformDeepseek, Matched: true, RequiredClaimStrength: CompositeClaimExplicit}, single) } // 声明强度分层:有强声明平台时通配 catch-all 平台不混池;完全无强声明才 @@ -125,7 +125,7 @@ func TestCompositePoolOwnershipClaimStrengthTiering(t *testing.T) { }) ownership, err := grokFirst.resolveCompositeModelOwnership(context.Background(), groupID, "grok-public") require.NoError(t, err) - require.Equal(t, CompositeModelOwnership{TargetPlatform: PlatformGrok, Matched: true}, ownership) + require.Equal(t, CompositeModelOwnership{TargetPlatform: PlatformGrok, Matched: true, RequiredClaimStrength: CompositeClaimExplicit}, ownership) // 无任何强声明:deepseek/zhipu 均只有通配命中 → 使用通配 fallback 平台集合。 wildcardOnly := svc([]Account{ @@ -145,11 +145,12 @@ func TestCompositePoolOwnershipClaimStrengthTiering(t *testing.T) { require.True(t, fallback.Matched) require.Empty(t, fallback.TargetPlatform) require.Equal(t, []string{PlatformDeepseek, PlatformZhipu}, fallback.CandidatePlatforms) + require.Equal(t, CompositeClaimWildcard, fallback.RequiredClaimStrength) // 仅单个平台通配命中 → fallback single。 singleWildcard, err := wildcardOnly.resolveCompositeModelOwnership(context.Background(), groupID, "zhipu-x") require.NoError(t, err) - require.Equal(t, CompositeModelOwnership{TargetPlatform: PlatformZhipu, Matched: true}, singleWildcard) + require.Equal(t, CompositeModelOwnership{TargetPlatform: PlatformZhipu, Matched: true, RequiredClaimStrength: CompositeClaimWildcard}, singleWildcard) } // e. 显式 route 优先于 pool,route 的 UpstreamModel 改写语义不变。 @@ -254,7 +255,7 @@ func TestCompositePoolOwnershipUnaffectedByTransientAccountState(t *testing.T) { repo.accounts = []Account{repo.accounts[0]} single, err := svc.resolveCompositeModelOwnership(context.Background(), groupID, "deepseek-chat") require.NoError(t, err) - require.Equal(t, CompositeModelOwnership{TargetPlatform: PlatformDeepseek, Matched: true}, single) + require.Equal(t, CompositeModelOwnership{TargetPlatform: PlatformDeepseek, Matched: true, RequiredClaimStrength: CompositeClaimExplicit}, single) // 配置移除全部声明 → 能力消失(0 候选,回退 detector/unknown 原逻辑)。 repo.accounts = nil diff --git a/backend/internal/service/composite_route_resolver.go b/backend/internal/service/composite_route_resolver.go index be86c74548..e5a605211d 100644 --- a/backend/internal/service/composite_route_resolver.go +++ b/backend/internal/service/composite_route_resolver.go @@ -117,12 +117,13 @@ func (r *CompositeRouteResolver) Resolve(ctx context.Context, groupID int64, mod // TargetPlatform 为空,不回退 generic/detector,也不在此猜单平台; // 选择期由统一 OpenAI 兼容 selector 按既有 priority/load/sticky 决定。 return CompositeRouteDecision{ - Matched: true, - Source: CompositeRouteSourceAccountPool, - GroupID: groupID, - PublicModel: model, - CandidatePlatforms: normalizeCompositeCandidatePlatforms(ownership.CandidatePlatforms), - Endpoint: endpoint, + Matched: true, + Source: CompositeRouteSourceAccountPool, + GroupID: groupID, + PublicModel: model, + CandidatePlatforms: normalizeCompositeCandidatePlatforms(ownership.CandidatePlatforms), + Endpoint: endpoint, + RequiredClaimStrength: ownership.RequiredClaimStrength, }, nil } else if ownership.Ambiguous { // 旧形态保护:Ambiguous=true 但未携带候选集合(老 mock / 异常输入) @@ -136,13 +137,14 @@ func (r *CompositeRouteResolver) Resolve(ctx context.Context, groupID int64, mod return decision, nil } return CompositeRouteDecision{ - Matched: true, - Source: CompositeRouteSourceAccount, - GroupID: groupID, - PublicModel: model, - TargetPlatform: platform, - UpstreamModel: model, - Endpoint: endpoint, + Matched: true, + Source: CompositeRouteSourceAccount, + GroupID: groupID, + PublicModel: model, + TargetPlatform: platform, + UpstreamModel: model, + Endpoint: endpoint, + RequiredClaimStrength: ownership.RequiredClaimStrength, }, nil } } diff --git a/backend/internal/service/gateway_hotpath_optimization_test.go b/backend/internal/service/gateway_hotpath_optimization_test.go index 3e2455c11a..f334b25951 100644 --- a/backend/internal/service/gateway_hotpath_optimization_test.go +++ b/backend/internal/service/gateway_hotpath_optimization_test.go @@ -596,7 +596,7 @@ func TestResolveCompositeModelOwnershipCachesConfigState(t *testing.T) { first, err := svc.resolveCompositeModelOwnership(context.Background(), groupID, "company-model") require.NoError(t, err) - require.Equal(t, CompositeModelOwnership{TargetPlatform: PlatformDeepseek, Matched: true}, first) + require.Equal(t, CompositeModelOwnership{TargetPlatform: PlatformDeepseek, Matched: true, RequiredClaimStrength: CompositeClaimExplicit}, first) require.Equal(t, int64(1), repo.listByGroupCalls.Load()) // TTL 内命中缓存,不再查库。 @@ -639,7 +639,7 @@ func TestResolveCompositeModelOwnershipCachesConfigState(t *testing.T) { }} refreshed, err := svc.resolveCompositeModelOwnership(context.Background(), groupID, "company-model") require.NoError(t, err) - require.Equal(t, CompositeModelOwnership{TargetPlatform: PlatformOpenAI, Matched: true}, refreshed) + require.Equal(t, CompositeModelOwnership{TargetPlatform: PlatformOpenAI, Matched: true, RequiredClaimStrength: CompositeClaimExplicit}, refreshed) require.Equal(t, int64(4), repo.listByGroupCalls.Load()) } diff --git a/backend/internal/service/gateway_scheduling.go b/backend/internal/service/gateway_scheduling.go index a21bee25ae..ffac8d530a 100644 --- a/backend/internal/service/gateway_scheduling.go +++ b/backend/internal/service/gateway_scheduling.go @@ -1249,7 +1249,7 @@ func (s *GatewayService) gatewaySchedulingModelSupported(ctx context.Context, ac return true } if GenericCompositePoolActive(ctx) { - return CompositeAccountClaimsModel(account, requestedModel) + return CompositeAccountMeetsClaimTier(ctx, account, requestedModel) } return s.isModelSupportedByAccountWithContext(ctx, account, requestedModel) } @@ -2717,7 +2717,7 @@ func summarizeSelectionFailureStats(stats selectionFailureStats) string { // 对于 Antigravity 平台,会先获取映射后的最终模型名(包括 thinking 后缀)再检查支持 func (s *GatewayService) isModelSupportedByAccountWithContext(ctx context.Context, account *Account, requestedModel string) bool { if source, ok := CompositeRouteSourceFromContext(ctx); ok && source == CompositeRouteSourceAccount { - if publicModel, modelOK := RequestedPublicModelFromContext(ctx); modelOK && !CompositeAccountClaimsModel(account, publicModel) { + if publicModel, modelOK := RequestedPublicModelFromContext(ctx); modelOK && !CompositeAccountMeetsClaimTier(ctx, account, publicModel) { return false } } diff --git a/backend/internal/service/gateway_service.go b/backend/internal/service/gateway_service.go index 6a111f671c..12e0124133 100644 --- a/backend/internal/service/gateway_service.go +++ b/backend/internal/service/gateway_service.go @@ -1553,11 +1553,16 @@ func (s *GatewayService) resolveCompositeModelOwnership(ctx context.Context, gro } claimedPlatforms := strongPlatforms + requiredStrength := CompositeClaimExplicit if len(claimedPlatforms) == 0 { claimedPlatforms = wildcardPlatforms + requiredStrength = CompositeClaimWildcard } ownership := CompositeModelOwnership{} + if len(claimedPlatforms) > 0 { + ownership.RequiredClaimStrength = requiredStrength + } switch len(claimedPlatforms) { case 1: for platform := range claimedPlatforms { diff --git a/backend/internal/service/openai_account_scheduler.go b/backend/internal/service/openai_account_scheduler.go index 97e5f57197..2f7fadd5a7 100644 --- a/backend/internal/service/openai_account_scheduler.go +++ b/backend/internal/service/openai_account_scheduler.go @@ -1809,7 +1809,7 @@ func (s *defaultOpenAIAccountScheduler) isAccountRequestCompatibleReason(ctx con return false, "account_nil" } if source, ok := CompositeRouteSourceFromContext(ctx); ok && source == CompositeRouteSourceAccount { - if publicModel, modelOK := RequestedPublicModelFromContext(ctx); modelOK && !CompositeAccountClaimsModel(account, publicModel) { + if publicModel, modelOK := RequestedPublicModelFromContext(ctx); modelOK && !CompositeAccountMeetsClaimTier(ctx, account, publicModel) { return false, "account_model_not_owned" } } diff --git a/backend/internal/service/openai_account_scheduler_test.go b/backend/internal/service/openai_account_scheduler_test.go index b58bf9140f..43f2e9f581 100644 --- a/backend/internal/service/openai_account_scheduler_test.go +++ b/backend/internal/service/openai_account_scheduler_test.go @@ -1305,7 +1305,7 @@ func TestOpenAIGatewayService_SelectAccountWithScheduler_AccountModelRouteOnlyUs repo := schedulerTestOpenAIAccountRepo{accounts: []Account{owner, nonOwner}} ownership, err := (&GatewayService{accountRepo: repo}).resolveCompositeModelOwnership(ctx, groupID, "team-alias") require.NoError(t, err) - require.Equal(t, CompositeModelOwnership{TargetPlatform: PlatformOpenAI, Matched: true}, ownership) + require.Equal(t, CompositeModelOwnership{TargetPlatform: PlatformOpenAI, Matched: true, RequiredClaimStrength: CompositeClaimExplicit}, ownership) ctx = WithCompositeRouteDecision(ctx, CompositeRouteDecision{ Matched: true, Source: CompositeRouteSourceAccount, GroupID: groupID, PublicModel: "team-alias", TargetPlatform: ownership.TargetPlatform, UpstreamModel: "team-alias", @@ -3975,7 +3975,7 @@ func TestOpenAIGatewayService_SelectAccountWithScheduler_LegacyAccountModelRoute repo := schedulerTestOpenAIAccountRepo{accounts: []Account{owner, nonOwner}} ownership, err := (&GatewayService{accountRepo: repo}).resolveCompositeModelOwnership(ctx, groupID, "team-alias") require.NoError(t, err) - require.Equal(t, CompositeModelOwnership{TargetPlatform: PlatformOpenAI, Matched: true}, ownership) + require.Equal(t, CompositeModelOwnership{TargetPlatform: PlatformOpenAI, Matched: true, RequiredClaimStrength: CompositeClaimExplicit}, ownership) ctx = WithCompositeRouteDecision(ctx, CompositeRouteDecision{ Matched: true, Source: CompositeRouteSourceAccount, GroupID: groupID, PublicModel: "team-alias", TargetPlatform: ownership.TargetPlatform, UpstreamModel: "team-alias", diff --git a/backend/internal/service/openai_gateway_scheduling.go b/backend/internal/service/openai_gateway_scheduling.go index 4293580c41..66936e9d25 100644 --- a/backend/internal/service/openai_gateway_scheduling.go +++ b/backend/internal/service/openai_gateway_scheduling.go @@ -358,7 +358,7 @@ func openAISchedulingModelSupported(ctx context.Context, account *Account, reque return true } if openAICompositePoolActive(ctx) { - return CompositeAccountClaimsModel(account, requestedModel) || account.IsOpenAIPassthroughEnabled() + return CompositeAccountMeetsClaimTier(ctx, account, requestedModel) || account.IsOpenAIPassthroughEnabled() } return account.IsModelSupported(requestedModel) } @@ -457,7 +457,7 @@ func openAICompatibleAccountEligibilityFailureReasonBeforeProfit(ctx context.Con return "account_nil" } if source, ok := CompositeRouteSourceFromContext(ctx); ok && source == CompositeRouteSourceAccount { - if publicModel, modelOK := RequestedPublicModelFromContext(ctx); modelOK && !CompositeAccountClaimsModel(account, publicModel) { + if publicModel, modelOK := RequestedPublicModelFromContext(ctx); modelOK && !CompositeAccountMeetsClaimTier(ctx, account, publicModel) { return "account_model_not_owned" } } From db7579218a59056ffd1f514d43a3d2fff0e0fb83 Mon Sep 17 00:00:00 2001 From: shaw Date: Fri, 9 Oct 2026 15:24:59 +0800 Subject: [PATCH 46/81] =?UTF-8?q?fix(composite):=20=E4=BF=AE=E5=A4=8D?= =?UTF-8?q?=E8=B4=A6=E5=8F=B7=E6=B1=A0=E7=BB=AD=E9=93=BE=E6=B0=B8=E4=B9=85?= =?UTF-8?q?=E6=96=AD=E9=93=BE=E3=80=81=E8=B7=A8=E6=97=8F=E6=B1=A0=E7=BB=AD?= =?UTF-8?q?=E9=93=BE=E9=94=99=E5=8F=91=E4=B8=8E=E6=8E=A8=E7=90=86=E5=BC=BA?= =?UTF-8?q?=E5=BA=A6=E7=AD=96=E7=95=A5=E5=A4=B1=E6=95=88?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 续链永久断链:归属账号限流/过载/临时不可调度时 resolveAccountByPreviousResponseID 删除续链绑定,账号池守卫随后对整条会话链永久返回 400。池上下文中改为只在归属账号 永久不可用(停用、关闭调度、过期、平台不符)时删除,瞬态只跳过本次复用(非池保持原 语义);池守卫在归属账号本次失败时返回其可重试错误,绑定仍在时返回 503,仅无绑定时 400。 - 跨族池续链:generic /v1/responses 池从不处理 previous_response_id,续链会落到 Anthropic 等无该响应状态的账号(静默丢上下文、无租户校验)。续链绑定只由 OpenAI 网关链创建,入口 对池续链把候选收窄到 OpenAI 兼容族交 OpenAI handler 钉住归属,无兼容族候选时 400; generic 池委派前记录下游响应归属,并对到达 generic 的池续链明确拒绝。 - 推理强度:跨族池(generic handler)选中 openai 账号时绕过分组推理强度上限与映射。 Responses / Chat Completions 按选中账号应用策略,Messages 池绑定分组策略供委派链应用。 --- ...site_pool_reasoning_policy_generic_test.go | 103 ++++++++++++++++++ backend/internal/handler/gateway_handler.go | 5 + .../gateway_handler_chat_completions.go | 14 +++ .../handler/gateway_handler_responses.go | 25 +++++ .../handler/openai_gateway_handler.go | 12 ++ backend/internal/server/routes/gateway.go | 33 ++++++ ...ateway_composite_pool_continuation_test.go | 96 ++++++++++++++++ .../gateway_composite_pool_policy_test.go | 24 +++- ...openai_composite_pool_prev_binding_test.go | 52 +++++++++ .../service/openai_ws_forwarder_support.go | 61 +++++++++-- 10 files changed, 413 insertions(+), 12 deletions(-) create mode 100644 backend/internal/handler/composite_pool_reasoning_policy_generic_test.go create mode 100644 backend/internal/server/routes/gateway_composite_pool_continuation_test.go create mode 100644 backend/internal/service/openai_composite_pool_prev_binding_test.go diff --git a/backend/internal/handler/composite_pool_reasoning_policy_generic_test.go b/backend/internal/handler/composite_pool_reasoning_policy_generic_test.go new file mode 100644 index 0000000000..c9772366de --- /dev/null +++ b/backend/internal/handler/composite_pool_reasoning_policy_generic_test.go @@ -0,0 +1,103 @@ +package handler + +import ( + "fmt" + "io" + "net/http" + "strings" + "testing" + + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" +) + +func poolOpenAIAccount(id int64, groupID int64, priority int) *service.Account { + return &service.Account{ + ID: id, Name: fmt.Sprintf("openai-%d", id), Platform: service.PlatformOpenAI, + Type: service.AccountTypeAPIKey, Status: service.StatusActive, Schedulable: true, + Concurrency: 1, Priority: priority, + AccountGroups: []service.AccountGroup{{AccountID: id, GroupID: groupID}}, + Credentials: map[string]any{ + "api_key": "openai-key", + "base_url": "https://openai.example", + "model_mapping": map[string]any{"my-model": "gpt-5.4"}, + }, + } +} + +// openAIResponsesSSEOKResponse 是最小的 Responses 流式成功响应(openai 平台委派链以流式访问上游)。 +func openAIResponsesSSEOKResponse(model string) *http.Response { + body := "data: " + fmt.Sprintf(`{"type":"response.completed","response":{"id":"resp_pool_sse","object":"response","status":"completed","model":%q,"output":[{"type":"message","role":"assistant","content":[{"type":"output_text","text":"hi"}]}],"usage":{"input_tokens":5,"output_tokens":3}}}`, model) + "\n\n" + return &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{"text/event-stream"}}, + Body: io.NopCloser(strings.NewReader(body)), + } +} + +// 跨族账号池(generic handler)选中 openai 账号时同样受分组推理强度上限约束, +// 与纯 OpenAI 族池 / 单目标 openai 同语义。 +func TestCompositeCrossFamilyPoolAppliesReasoningEffortCap(t *testing.T) { + cases := []struct { + name, path, body, effortPath string + respond func() *http.Response + }{ + { + name: "responses", + path: "/v1/responses", + body: `{"model":"my-model","stream":false,"input":"hello","reasoning":{"effort":"xhigh"}}`, + effortPath: "reasoning.effort", + respond: func() *http.Response { return openAIResponsesOKResponse("gpt-5.4", 5, 3) }, + }, + { + name: "chat_completions", + path: "/v1/chat/completions", + body: `{"model":"my-model","stream":false,"messages":[{"role":"user","content":"hello"}],"reasoning_effort":"xhigh"}`, + effortPath: "reasoning_effort", + respond: func() *http.Response { return openAIResponsesSSEOKResponse("gpt-5.4") }, + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + h := newCompositePoolMessagesHarness(t, []*service.Account{poolOpenAIAccount(44101, 41011, 0)}) + h.group.MaxReasoningEffort = "medium" + h.openAIUpstream.respond = func(compositePoolUpstreamCall, int) *http.Response { return tc.respond() } + + c, rec := h.newRequest(t, tc.path, tc.body, service.PlatformAnthropic, service.PlatformOpenAI) + if tc.path == "/v1/responses" { + h.handler.Responses(c) + } else { + h.handler.ChatCompletions(c) + } + + require.Equal(t, http.StatusOK, rec.Code, rec.Body.String()) + calls := h.openAIUpstream.snapshot() + require.Len(t, calls, 1) + effort := gjson.GetBytes(calls[0].Body, "reasoning.effort").String() + if effort == "" { + effort = gjson.GetBytes(calls[0].Body, "reasoning_effort").String() + } + require.Equal(t, "medium", effort, "upstream body=%s", calls[0].Body) + }) + } +} + +// Messages 入口:委派 OpenAI 网关链时按分组上限压低 output_config.effort。 +func TestCompositeCrossFamilyPoolMessagesAppliesReasoningEffortCap(t *testing.T) { + h := newCompositePoolMessagesHarness(t, []*service.Account{poolOpenAIAccount(44201, 41011, 0)}) + h.group.MaxReasoningEffort = "medium" + h.openAIUpstream.respond = func(compositePoolUpstreamCall, int) *http.Response { + return openAIResponsesSSEOKResponse("gpt-5.4") + } + + c, rec := h.newRequest(t, "/v1/messages", + `{"model":"my-model","max_tokens":64,"stream":false,"messages":[{"role":"user","content":"hello"}],"output_config":{"effort":"max"}}`, + service.PlatformAnthropic, service.PlatformOpenAI) + h.handler.Messages(c) + + require.Equal(t, http.StatusOK, rec.Code, rec.Body.String()) + calls := h.openAIUpstream.snapshot() + require.Len(t, calls, 1) + require.Equal(t, "medium", gjson.GetBytes(calls[0].Body, "reasoning.effort").String(), "upstream body=%s", calls[0].Body) +} diff --git a/backend/internal/handler/gateway_handler.go b/backend/internal/handler/gateway_handler.go index 5d5669eb5f..a5d39586c3 100644 --- a/backend/internal/handler/gateway_handler.go +++ b/backend/internal/handler/gateway_handler.go @@ -172,6 +172,11 @@ func (h *GatewayHandler) Messages(c *gin.Context) { reqStream := parsedReq.Stream bindRequestedReasoningEffort(c, body, reqModel) ensureCompositeTargetPlatform(c, apiKey, reqModel) + // 账号池没有单一目标平台,准入期判不出策略族:绑定分组策略,委派 OpenAI 网关链选中 + // openai 账号时由 ForwardAsAnthropic 应用(与 OpenAI handler Messages 同语义)。 + if service.GenericCompositePoolActive(c.Request.Context()) { + bindOpenAIReasoningEffortPolicyForMessagesRequest(c, apiKey, body) + } if policyBody, changed, err := applyAnthropicReasoningEffortPolicyForRequest(c, apiKey, body); err != nil { respondOpenAIReasoningEffortPolicyError(c, err, h.errorResponse) return diff --git a/backend/internal/handler/gateway_handler_chat_completions.go b/backend/internal/handler/gateway_handler_chat_completions.go index af1a08482d..20f9d873fc 100644 --- a/backend/internal/handler/gateway_handler_chat_completions.go +++ b/backend/internal/handler/gateway_handler_chat_completions.go @@ -349,6 +349,20 @@ func (h *GatewayHandler) ChatCompletions(c *gin.Context) { if attemptChannelMapping.Mapped { forwardBody = h.gatewayService.ReplaceModelInBody(body, attemptChannelMapping.MappedModel) } + // 账号池按选中账号应用分组推理强度策略(与 OpenAI handler 同语义,仅 openai 账号)。 + if isPoolRequest { + cappedBody, changed, policyErr := applyCompositePoolReasoningEffortPolicyForSelectedAccount(c, apiKey, account, forwardBody) + if policyErr != nil { + if accountReleaseFunc != nil { + accountReleaseFunc() + } + respondOpenAIReasoningEffortPolicyError(c, policyErr, h.chatCompletionsErrorResponse) + return + } + if changed { + forwardBody = cappedBody + } + } var result *service.ForwardResult // 池委派 OpenAI 网关链时的原始结果:按 OpenAI 口径入账(见 submitDelegatedOpenAIUsage)。 var delegatedResult *service.OpenAIForwardResult diff --git a/backend/internal/handler/gateway_handler_responses.go b/backend/internal/handler/gateway_handler_responses.go index e4113fb334..18db039a9f 100644 --- a/backend/internal/handler/gateway_handler_responses.go +++ b/backend/internal/handler/gateway_handler_responses.go @@ -184,6 +184,17 @@ func (h *GatewayHandler) Responses(c *gin.Context) { // generic 调度器共用同一谓词(ctx 携带候选池且无 resolved 平台);非池请求 // poolDenials 恒为空、attempt 策略与委派分支不生效,整条路径零变化。 isPoolRequest := service.GenericCompositePoolActive(requestCtx) + if isPoolRequest { + // 续链只能由 OpenAI 兼容族归属账号服务(路由层已把这类请求收窄后交 OpenAI + // handler);到达这里说明候选池无法承接,明确拒绝而不是静默丢弃上下文。 + if strings.TrimSpace(gjson.GetBytes(body, "previous_response_id").String()) != "" { + h.responsesErrorResponse(c, http.StatusBadRequest, "invalid_request_error", + "previous_response_id is not supported for this composite model; resend the full conversation without previous_response_id") + return + } + // 委派 OpenAI 网关链创建的响应须记录下游归属,后续续链经 OpenAI handler 校验租户。 + service.SetOpenAIHTTPResponseOwner(c, subject.UserID, apiKey.ID) + } poolDenials := newCompositePoolPlatformDenials() // 3. Account selection + failover loop @@ -350,6 +361,20 @@ func (h *GatewayHandler) Responses(c *gin.Context) { if attemptChannelMapping.Mapped { forwardBody = h.gatewayService.ReplaceModelInBody(body, attemptChannelMapping.MappedModel) } + // 账号池按选中账号应用分组推理强度策略(与 OpenAI handler 同语义,仅 openai 账号)。 + if isPoolRequest { + cappedBody, changed, policyErr := applyCompositePoolReasoningEffortPolicyForSelectedAccount(c, apiKey, account, forwardBody) + if policyErr != nil { + if accountReleaseFunc != nil { + accountReleaseFunc() + } + respondOpenAIReasoningEffortPolicyError(c, policyErr, h.responsesErrorResponse) + return + } + if changed { + forwardBody = cappedBody + } + } var result *service.ForwardResult // 池委派 OpenAI 网关链时的原始结果:按 OpenAI 口径入账(见 submitDelegatedOpenAIUsage)。 var delegatedResult *service.OpenAIForwardResult diff --git a/backend/internal/handler/openai_gateway_handler.go b/backend/internal/handler/openai_gateway_handler.go index 41d67ccad0..70c752e768 100644 --- a/backend/internal/handler/openai_gateway_handler.go +++ b/backend/internal/handler/openai_gateway_handler.go @@ -783,6 +783,18 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) { // 持有的槽位(Acquired=true 时 ReleaseFunc 非空,恰一次)。 if previousResponseID != "" && compositePoolResponseStateGuardApplies(c, apiKey) && !scheduleDecision.StickyPreviousHit { releaseCompositePoolSelection(selection) + // 归属账号本次已失败被排除(如 429):返回其可重试错误,不能变成永久性的 400。 + if lastFailoverErr != nil { + h.handleFailoverExhausted(c, lastFailoverErr, streamStarted) + return + } + // 绑定仍在但归属账号暂时不可用(限流、过载、临时不可调度等):可重试。 + if h.gatewayService.HasPreviousResponseBinding(c.Request.Context(), apiKey.GroupID, previousResponseID) { + markOpsRoutingCapacityLimited(c) + h.handleStreamingAwareError(c, http.StatusServiceUnavailable, "api_error", + "the account that owns previous_response_id is temporarily unavailable; retry later", streamStarted) + return + } h.errorResponse(c, http.StatusBadRequest, "invalid_request_error", "previous_response_id belongs to a response owned by a different account; continue on the account that owns this response state or start a new response") return diff --git a/backend/internal/server/routes/gateway.go b/backend/internal/server/routes/gateway.go index c9c46ef3bb..b793538722 100644 --- a/backend/internal/server/routes/gateway.go +++ b/backend/internal/server/routes/gateway.go @@ -662,6 +662,16 @@ func compositeTargetPlatformMiddleware(resolver *service.CompositeRouteResolver) writeCompositeRouteAdmissionError(c, http.StatusBadRequest, fmt.Sprintf("Model %q cannot be resolved to any platform in this composite group (%s)", model, decision.Reason)) return } + if isCompositePoolResponsesContinuation(c, decision, body) { + // 续链绑定只由 OpenAI 网关链创建,归属账号必然属于 OpenAI 兼容族:候选池收窄到 + // 兼容族后由 OpenAI handler 按归属账号钉住与守卫,避免跨族池选到无该响应状态的 + // 账号(静默丢失上下文或跨租户续链)。 + decision.CandidatePlatforms = openAICompatibleCandidatePlatforms(decision.CandidatePlatforms) + if len(decision.CandidatePlatforms) == 0 { + writeCompositeRouteAdmissionError(c, http.StatusBadRequest, fmt.Sprintf("Model %q has no OpenAI-compatible account in this composite group to continue previous_response_id; resend the full conversation without previous_response_id", model)) + return + } + } c.Request = c.Request.WithContext(service.WithCompositeRouteDecision(c.Request.Context(), decision)) if upstreamModel := strings.TrimSpace(decision.UpstreamModel); upstreamModel != "" && upstreamModel != model && gjson.ValidBytes(body) { if _, modelPath := requestmodel.JSONModelPathForRoute(routePath, body); modelPath != "" { @@ -736,6 +746,29 @@ func compositeGeminiModelFromParams(c *gin.Context) string { return modelAction } +// isCompositePoolResponsesContinuation 报告请求是否为 composite 账号池上的 Responses +// 续链(带 previous_response_id)。 +func isCompositePoolResponsesContinuation(c *gin.Context, decision service.CompositeRouteDecision, body []byte) bool { + if c == nil || c.Request == nil || c.Request.URL == nil || !strings.Contains(c.Request.URL.Path, "/responses") { + return false + } + if strings.TrimSpace(decision.TargetPlatform) != "" || len(decision.CandidatePlatforms) == 0 { + return false + } + return strings.TrimSpace(gjson.GetBytes(body, "previous_response_id").String()) != "" +} + +// openAICompatibleCandidatePlatforms 返回候选平台中经 OpenAI 网关转发的平台(保持顺序)。 +func openAICompatibleCandidatePlatforms(candidates []string) []string { + out := make([]string, 0, len(candidates)) + for _, platform := range candidates { + if isOpenAICompatibleGatewayFamilyPlatform(platform) { + out = append(out, platform) + } + } + return out +} + func compositeRouteEndpointForPath(path string) string { switch { case strings.Contains(path, "/messages/count_tokens"): diff --git a/backend/internal/server/routes/gateway_composite_pool_continuation_test.go b/backend/internal/server/routes/gateway_composite_pool_continuation_test.go new file mode 100644 index 0000000000..7765fa8b4e --- /dev/null +++ b/backend/internal/server/routes/gateway_composite_pool_continuation_test.go @@ -0,0 +1,96 @@ +//go:build unit + +package routes + +import ( + "net/http" + "strings" + "testing" + + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" +) + +// 跨族账号池上的 Responses 续链:归属账号必然是 OpenAI 兼容族(只有 OpenAI 网关链 +// 创建续链绑定),候选池收窄到兼容族后交 OpenAI handler 按归属钉住并校验租户; +// 首轮经 generic 池委派创建的响应同样记录了下游归属,续链可继续。 +func TestCompositeCrossFamilyPoolContinuationPinsOwner(t *testing.T) { + upstream := &captureUpstream{} + deepseek := newPoolPolicyAccountWithMapping(4301, service.PlatformDeepseek, 0, map[string]any{"xpool-model": "deepseek-chat"}) + deepseek.Credentials["api_protocol"] = service.APIProtocolResponses + anthropic := newPoolPolicyAccountWithMapping(4302, service.PlatformAnthropic, 5, map[string]any{"xpool-model": "claude-sonnet-4-5"}) + router, _ := newCompositePoolPolicyTestRouter(t, poolPolicyRouterInput{ + group: newPoolPolicyGroup(nil), + accounts: []service.Account{deepseek, anthropic}, + upstream: upstream, + }) + + first := postPoolPolicyRequest(t, router, "/v1/responses", + `{"model":"xpool-model","input":"hi","prompt_cache_key":"sess-x-a","stream":false}`) + require.Equal(t, http.StatusOK, first.Code, first.Body.String()) + responseID := gjson.GetBytes(first.Body.Bytes(), "id").String() + require.True(t, strings.HasPrefix(responseID, "resp_"), "got %q", responseID) + captured := upstream.capturedSnapshot() + require.Len(t, captured, 1) + require.Equal(t, "deepseek-pool-fake.test", captured[0].host) + + before := len(upstream.capturedSnapshot()) + second := postPoolPolicyRequest(t, router, "/v1/responses", + `{"model":"xpool-model","input":"continue","prompt_cache_key":"sess-x-b","previous_response_id":"`+responseID+`","stream":false}`) + require.Equal(t, http.StatusOK, second.Code, second.Body.String()) + after := upstream.capturedSnapshot()[before:] + require.NotEmpty(t, after) + for _, record := range after { + require.Equal(t, "deepseek-pool-fake.test", record.host, "continuation must stay on the owning account") + } +} + +// 续链请求里优先级更高的 Anthropic 账号绝不能收到带 previous_response_id 的请求。 +func TestCompositeCrossFamilyPoolContinuationNeverReachesNonOpenAIAccount(t *testing.T) { + upstream := &captureUpstream{} + deepseek := newPoolPolicyAccountWithMapping(4311, service.PlatformDeepseek, 5, map[string]any{ + "ds-only": "deepseek-chat", + "xpool-model": "deepseek-chat", + }) + deepseek.Credentials["api_protocol"] = service.APIProtocolResponses + anthropic := newPoolPolicyAccountWithMapping(4312, service.PlatformAnthropic, 0, map[string]any{"xpool-model": "claude-sonnet-4-5"}) + router, _ := newCompositePoolPolicyTestRouter(t, poolPolicyRouterInput{ + group: newPoolPolicyGroup(nil), + accounts: []service.Account{deepseek, anthropic}, + upstream: upstream, + }) + + first := postPoolPolicyRequest(t, router, "/v1/responses", + `{"model":"ds-only","input":"hi","prompt_cache_key":"sess-y-a","stream":false}`) + require.Equal(t, http.StatusOK, first.Code, first.Body.String()) + responseID := gjson.GetBytes(first.Body.Bytes(), "id").String() + require.True(t, strings.HasPrefix(responseID, "resp_"), "got %q", responseID) + + before := len(upstream.capturedSnapshot()) + second := postPoolPolicyRequest(t, router, "/v1/responses", + `{"model":"xpool-model","input":"continue","prompt_cache_key":"sess-y-b","previous_response_id":"`+responseID+`","stream":false}`) + require.Equal(t, http.StatusOK, second.Code, second.Body.String()) + for _, record := range upstream.capturedSnapshot()[before:] { + require.Equal(t, "deepseek-pool-fake.test", record.host) + } +} + +// 候选池没有 OpenAI 兼容族时续链无法继续:入口明确拒绝,不转发任何请求。 +func TestCompositePoolContinuationWithoutOpenAICompatibleCandidateRejected(t *testing.T) { + upstream := &captureUpstream{} + router, _ := newCompositePoolPolicyTestRouter(t, poolPolicyRouterInput{ + group: newPoolPolicyGroup(nil), + accounts: []service.Account{ + newPoolPolicyAccountWithMapping(4321, service.PlatformAnthropic, 0, map[string]any{"np-model": "claude-sonnet-4-5"}), + newPoolPolicyAccountWithMapping(4322, service.PlatformGemini, 1, map[string]any{"np-model": "gemini-3.1-pro"}), + }, + upstream: upstream, + }) + + w := postPoolPolicyRequest(t, router, "/v1/responses", + `{"model":"np-model","input":"continue","previous_response_id":"resp_abc","stream":false}`) + require.Equal(t, http.StatusBadRequest, w.Code, w.Body.String()) + require.Contains(t, w.Body.String(), "previous_response_id") + require.Empty(t, upstream.capturedSnapshot()) +} diff --git a/backend/internal/server/routes/gateway_composite_pool_policy_test.go b/backend/internal/server/routes/gateway_composite_pool_policy_test.go index 6367af9e6c..af7df5f463 100644 --- a/backend/internal/server/routes/gateway_composite_pool_policy_test.go +++ b/backend/internal/server/routes/gateway_composite_pool_policy_test.go @@ -287,7 +287,7 @@ func newCompositePoolPolicyTestRouter(t *testing.T, in poolPolicyRouterInput) (* handlers := &handler.Handlers{ Gateway: handler.NewGatewayHandler( - genericGateway, nil, nil, nil, nil, + genericGateway, openAIGateway, nil, nil, nil, concurrencyService, billingCache, nil, nil, nil, nil, nil, nil, cfg, nil, ), @@ -542,8 +542,9 @@ func TestCompositePoolCNPreviousResponseIDPinBeatsPriorityAndSeed(t *testing.T) } // CN→CN 未 hit 跨账号转移必须拒绝:resp id 归属 deepseek,deepseek 首跳 429 -// failover 后选中另一 CN 候选(kimi)时,状态守卫在任何转发前 400 终止, -// kimi 不收到带旧 prevID 的请求(该用例在 2A 修复前后都必须保持绿)。 +// failover 后不得转给另一 CN 候选(kimi),kimi 不收到带旧 prevID 的请求。归属账号 +// 的 429 是可重试错误,必须原样返回而不是永久性的 400,且续链绑定保留:上游恢复后 +// 同一 previous_response_id 仍回到 deepseek 继续。 func TestCompositePoolPreviousResponseIDRejectsCrossCNSelection(t *testing.T) { upstream := &captureUpstream{} group := newPoolPolicyGroup(nil) @@ -577,12 +578,25 @@ func TestCompositePoolPreviousResponseIDRejectsCrossCNSelection(t *testing.T) { wB := postPoolPolicyRequest(t, router, "/v1/responses", `{"model":"pool-model","input":"continue","prompt_cache_key":"sess-cross-b","previous_response_id":"`+responseID+`","stream":false}`) - require.Equal(t, http.StatusBadRequest, wB.Code, wB.Body.String()) - require.Contains(t, wB.Body.String(), "previous_response_id") + require.Equal(t, http.StatusTooManyRequests, wB.Code, wB.Body.String()) for _, record := range upstream.capturedSnapshot()[capturedBefore:] { require.NotEqual(t, "kimi-pool-fake.test", record.host, "the non-owning CN account must never receive the old prevID") } + + // 第三条:上游恢复,同一续链仍由归属账号服务(绑定未因 429 被删除)。 + upstream.mu.Lock() + upstream.failHost = nil + upstream.mu.Unlock() + capturedBefore = len(upstream.capturedSnapshot()) + wC := postPoolPolicyRequest(t, router, "/v1/responses", + `{"model":"pool-model","input":"continue again","prompt_cache_key":"sess-cross-c","previous_response_id":"`+responseID+`","stream":false}`) + require.Equal(t, http.StatusOK, wC.Code, wC.Body.String()) + after := upstream.capturedSnapshot()[capturedBefore:] + require.NotEmpty(t, after) + for _, record := range after { + require.Equal(t, "deepseek-pool-fake.test", record.host, "continuation must return to the owning account") + } } // claude-* 别名被两个兼容族账号同时 claim 时,/v1/messages 不套 gpt-5.x diff --git a/backend/internal/service/openai_composite_pool_prev_binding_test.go b/backend/internal/service/openai_composite_pool_prev_binding_test.go new file mode 100644 index 0000000000..a835c0f7b8 --- /dev/null +++ b/backend/internal/service/openai_composite_pool_prev_binding_test.go @@ -0,0 +1,52 @@ +package service + +import ( + "context" + "testing" + "time" + + "github.com/stretchr/testify/require" +) + +// composite 账号池要求续链命中归属账号:归属账号限流等瞬态不可用时只跳过本次复用, +// 不删除续链绑定,否则冷却结束后整条会话链被永久拒绝。永久不可用(关闭调度)仍删除。 +func TestSelectAccountByPreviousResponseIDKeepsBindingOnTransientOwnerStateInPool(t *testing.T) { + groupID := int64(31) + poolCtx := WithCompositeCandidatePlatforms(context.Background(), []string{PlatformDeepseek, PlatformKimi}) + rateLimitedUntil := time.Now().Add(30 * time.Minute) + newSvc := func(account Account) (*OpenAIGatewayService, OpenAIWSStateStore) { + cache := &stubGatewayCache{} + store := NewOpenAIWSStateStore(cache) + return &OpenAIGatewayService{ + accountRepo: stubOpenAIAccountRepo{accounts: []Account{account}}, + cache: cache, + cfg: newOpenAIWSV2TestConfig(), + concurrencyService: NewConcurrencyService(stubConcurrencyCache{}), + openaiWSStateStore: store, + }, store + } + + rateLimited := Account{ID: 41, Platform: PlatformOpenAI, Type: AccountTypeAPIKey, Status: StatusActive, + Schedulable: true, Concurrency: 1, RateLimitResetAt: &rateLimitedUntil} + svc, store := newSvc(rateLimited) + require.NoError(t, store.BindResponseAccount(poolCtx, groupID, "resp_pool_rl", rateLimited.ID, time.Hour)) + selection, err := svc.SelectAccountByPreviousResponseID(poolCtx, &groupID, "resp_pool_rl", "gpt-5.1", nil, false) + require.NoError(t, err) + require.Nil(t, selection) + bound, err := store.GetResponseAccount(poolCtx, groupID, "resp_pool_rl") + require.NoError(t, err) + require.Equal(t, rateLimited.ID, bound, "瞬态不可用不得删除池内续链绑定") + require.True(t, svc.HasPreviousResponseBinding(poolCtx, &groupID, "resp_pool_rl")) + + disabled := Account{ID: 42, Platform: PlatformOpenAI, Type: AccountTypeAPIKey, Status: StatusActive, + Schedulable: false, Concurrency: 1} + svc, store = newSvc(disabled) + require.NoError(t, store.BindResponseAccount(poolCtx, groupID, "resp_pool_off", disabled.ID, time.Hour)) + selection, err = svc.SelectAccountByPreviousResponseID(poolCtx, &groupID, "resp_pool_off", "gpt-5.1", nil, false) + require.NoError(t, err) + require.Nil(t, selection) + bound, err = store.GetResponseAccount(poolCtx, groupID, "resp_pool_off") + require.NoError(t, err) + require.Zero(t, bound, "关闭调度属永久不可用,删除绑定") + require.False(t, svc.HasPreviousResponseBinding(poolCtx, &groupID, "resp_pool_off")) +} diff --git a/backend/internal/service/openai_ws_forwarder_support.go b/backend/internal/service/openai_ws_forwarder_support.go index e84ede5e3a..5b72158b7d 100644 --- a/backend/internal/service/openai_ws_forwarder_support.go +++ b/backend/internal/service/openai_ws_forwarder_support.go @@ -566,9 +566,19 @@ func (s *OpenAIGatewayService) resolveAccountByPreviousResponseIDForCapability( } } + // composite 账号池要求续链必须命中归属账号(handler 池守卫),删除绑定即永久断链: + // 池上下文中只在归属账号永久不可用时删除(previousResponseOwnerPermanentlyUnusable), + // 限流、过载、临时不可调度、运行时熔断、调度阈值门等瞬态与配额暂停、利润否决同语义, + // 只跳过本次复用、保留绑定。非池请求保持原语义:瞬态即删除,会话改锚到新账号。 + keepOnTransient := openAICompositePoolActive(ctx) + dropTransient := func() { + if !keepOnTransient { + _ = store.DeleteResponseAccount(ctx, derefGroupID(groupID), responseID) + } + } account, err := s.getSchedulableAccount(ctx, accountID) if err != nil || account == nil { - _ = store.DeleteResponseAccount(ctx, derefGroupID(groupID), responseID) + dropTransient() return 0, nil, "", nil } // OAuth/SetupToken continuation state lives on the WSv2 session and cannot @@ -581,11 +591,14 @@ func (s *OpenAIGatewayService) resolveAccountByPreviousResponseIDForCapability( s.getOpenAIWSProtocolResolver().Resolve(account).Transport != OpenAIUpstreamTransportResponsesWebsocketV2 { return 0, nil, "", nil } - if shouldClearStickySession(account, requestedModel) || - (!account.IsOpenAI() && !openAICompositePoolHTTPResponsesOwner(ctx, account)) || !account.IsSchedulable() { + if previousResponseOwnerPermanentlyUnusable(ctx, account) { _ = store.DeleteResponseAccount(ctx, derefGroupID(groupID), responseID) return 0, nil, "", nil } + if shouldClearStickySession(account, requestedModel) { + dropTransient() + return 0, nil, "", nil + } if !parentHealthyForShadow(account, s.parentAccountLookup(ctx)) { _ = store.DeleteResponseAccount(ctx, derefGroupID(groupID), responseID) return 0, nil, "", nil @@ -611,15 +624,22 @@ func (s *OpenAIGatewayService) resolveAccountByPreviousResponseIDForCapability( } if s.schedulerSnapshot != nil && s.accountRepo != nil { latest, latestErr := s.accountRepo.GetByID(ctx, account.ID) - if latestErr != nil || latest == nil { + if latestErr != nil { + dropTransient() + return 0, nil, "", nil + } + if latest == nil { _ = store.DeleteResponseAccount(ctx, derefGroupID(groupID), responseID) return 0, nil, "", nil } - if shouldClearStickySession(latest, requestedModel) || - (!latest.IsOpenAI() && !openAICompositePoolHTTPResponsesOwner(ctx, latest)) || !latest.IsSchedulable() { + if previousResponseOwnerPermanentlyUnusable(ctx, latest) { _ = store.DeleteResponseAccount(ctx, derefGroupID(groupID), responseID) return 0, nil, "", nil } + if shouldClearStickySession(latest, requestedModel) { + dropTransient() + return 0, nil, "", nil + } if !s.openAIAccountMatchesSchedulingGroup(latest, groupID) { return 0, nil, "", nil } @@ -644,7 +664,7 @@ func (s *OpenAIGatewayService) resolveAccountByPreviousResponseIDForCapability( return 0, nil, "", nil } if s.isOpenAIAccountRequestRuntimeBlocked(latest, requestedModel) { - _ = store.DeleteResponseAccount(ctx, derefGroupID(groupID), responseID) + dropTransient() return 0, nil, "", nil } account = latest @@ -656,6 +676,33 @@ func (s *OpenAIGatewayService) resolveAccountByPreviousResponseIDForCapability( return accountID, account, responseID, store } +// previousResponseOwnerPermanentlyUnusable 报告续链归属账号是否已永久不能继续该响应链 +// (停用、关闭调度、已过期、平台不符),此时删除绑定;其余不可用状态均为瞬态。 +func previousResponseOwnerPermanentlyUnusable(ctx context.Context, account *Account) bool { + if account == nil || !account.IsActive() || !account.Schedulable { + return true + } + if account.AutoPauseOnExpired && account.ExpiresAt != nil && !time.Now().Before(*account.ExpiresAt) { + return true + } + return !account.IsOpenAI() && !openAICompositePoolHTTPResponsesOwner(ctx, account) +} + +// HasPreviousResponseBinding 报告 previous_response_id 是否仍绑定到某个账号(不校验 +// 账号当前是否可用)。供 composite 池守卫区分「归属账号暂时不可用」与「无归属」。 +func (s *OpenAIGatewayService) HasPreviousResponseBinding(ctx context.Context, groupID *int64, previousResponseID string) bool { + responseID := strings.TrimSpace(previousResponseID) + if s == nil || responseID == "" { + return false + } + store := s.getOpenAIWSStateStore() + if store == nil { + return false + } + accountID, err := store.GetResponseAccount(ctx, derefGroupID(groupID), responseID) + return err == nil && accountID > 0 +} + func classifyOpenAIWSAcquireError(err error) string { if err == nil { return "acquire_conn" From 657e45e6148d186d202194dc87da930145c5e4d2 Mon Sep 17 00:00:00 2001 From: shaw Date: Fri, 9 Oct 2026 15:30:55 +0800 Subject: [PATCH 47/81] =?UTF-8?q?fix(billing):=20=E5=89=A5=20tag=20?= =?UTF-8?q?=E4=BA=8C=E7=BA=A7=E6=9F=A5=E4=BB=B7=E5=8F=AA=E6=8E=A5=E5=8F=97?= =?UTF-8?q?=E7=A1=AE=E5=AE=9A=E6=80=A7=E5=91=BD=E4=B8=AD=EF=BC=8Cgeneric?= =?UTF-8?q?=20=E8=B7=AF=E5=BE=84=E8=A1=A5=20ollama=20=E8=AE=A1=E8=B4=B9?= =?UTF-8?q?=E9=A2=84=E6=A3=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 剥 tag 查价:名字未命中时剥掉 ":tag" 重跑整条查找链,会经家族/OpenAI 末端 catch-all 把 gpt-oss:latest 等猜成 gpt-5.4 价,并让 ollama 保存期门禁与请求期预检 误判为已定价(约 36~50 倍误计)。第二级改为只接受目录确定性识别与回退价表精确键; OpenAI 回退链排除扩展到所有带 tag 的 gpt-oss 名(含 gpt-oss-safeguard:20b)。 - generic 预检:composite 跨族账号池经 Anthropic 协议链服务 ollama_cloud 账号时没有 请求期定价预检,无价模型先被服务再按 0 元计费。GatewayService.buildUpstreamRequest (覆盖 Forward / ForwardAsResponses / ForwardAsChatCompletions)复用同一无价判定, 上游 I/O 前按入站协议信封返回 400,不触发换号。 --- backend/internal/service/billing_service.go | 31 +++++++++--- ...way_ollama_cloud_pricing_preflight_test.go | 50 +++++++++++++++++++ .../service/gateway_upstream_request.go | 3 ++ ...lama_cloud_dynamic_catalog_pricing_test.go | 26 ++++++++++ ..._gateway_ollama_cloud_pricing_preflight.go | 41 +++++++++++++-- backend/internal/service/pricing_service.go | 12 +++-- 6 files changed, 149 insertions(+), 14 deletions(-) create mode 100644 backend/internal/service/gateway_ollama_cloud_pricing_preflight_test.go diff --git a/backend/internal/service/billing_service.go b/backend/internal/service/billing_service.go index 8ca87ed0d4..9e7ced49fe 100644 --- a/backend/internal/service/billing_service.go +++ b/backend/internal/service/billing_service.go @@ -1424,30 +1424,40 @@ func (s *BillingService) GetModelPricing(model string) (*ModelPricing, error) { // 展示/估算路径可与历史补账同刻复算,测试也能用固定时点钉住断言。 // // 两级查价:字面名完整跑一遍查找链(LiteLLM → fallback),未命中且名含 -// ":tag" 时用剥 tag 名重跑一次同一查找链(pricingAt 原样传递)。字面优先: -// bedrock canonical key(如 us.anthropic.claude-sonnet-4-5-20250929-v1:0) -// 本身含 ":0",字面命中时绝不剥;剥 tag 仅是 miss 后的第二级,见 +// ":tag" 时用剥 tag 名重查一次(pricingAt 原样传递)。字面优先:bedrock +// canonical key(如 us.anthropic.claude-sonnet-4-5-20250929-v1:0)本身含 ":0", +// 字面命中时绝不剥;剥 tag 仅是 miss 后的第二级,见 // normalizePricingModelNameForLookup。 +// +// 第二级只接受确定性命中(目录精确识别 + 回退价表精确键),不走按子串猜系列的 +// 兜底:剥掉 tag 的名字(如 gpt-oss:latest → gpt-oss)会被家族/OpenAI 末端 +// catch-all 猜成无关模型的价格,并让计费门禁误判为已定价。 func (s *BillingService) getModelPricingAt(model string, pricingAt time.Time) (*ModelPricing, error) { - pricing, err := s.getModelPricingAtOnce(model, pricingAt) + pricing, err := s.getModelPricingAtOnce(model, pricingAt, false) if err == nil { return pricing, nil } if stripped, ok := normalizePricingModelNameForLookup(model); ok { - if retry, retryErr := s.getModelPricingAtOnce(stripped, pricingAt); retryErr == nil { + if retry, retryErr := s.getModelPricingAtOnce(stripped, pricingAt, true); retryErr == nil { return retry, nil } } return nil, err } -func (s *BillingService) getModelPricingAtOnce(model string, pricingAt time.Time) (*ModelPricing, error) { +// getModelPricingAtOnce 跑一遍查找链;identifiedOnly 时只接受确定性命中。 +func (s *BillingService) getModelPricingAtOnce(model string, pricingAt time.Time, identifiedOnly bool) (*ModelPricing, error) { // 标准化模型名称(转小写) model = strings.ToLower(model) // 1. 优先从动态价格服务获取 if s.pricingService != nil { - litellmPricing := s.pricingService.GetModelPricing(model) + var litellmPricing *LiteLLMModelPricing + if identifiedOnly { + litellmPricing = s.pricingService.GetIdentifiedModelPricing(model) + } else { + litellmPricing = s.pricingService.GetModelPricing(model) + } // 仅有图片价、无 token 价的条目(如 LiteLLM 的 imagen 类模型)不能用于 // token 计费:直接返回会把 token 流量按 $0 计费。跳过后走 fallback, // 无 fallback 则 fail-closed(ErrModelPricingUnavailable)。 @@ -1489,7 +1499,12 @@ func (s *BillingService) getModelPricingAtOnce(model string, pricingAt time.Time } // 2. 使用硬编码回退价格 - fallback := s.getFallbackPricing(model) + var fallback *ModelPricing + if identifiedOnly { + fallback = s.fallbackPrices[model] + } else { + fallback = s.getFallbackPricing(model) + } if fallback != nil { // 按模型名去重:每个模型每进程最多打一条 warn,避免热路径每请求刷屏(issue #3394)。 // model 在函数入口已 ToLower,故 GLM-5.2 / glm-5.2 视为同一条目。 diff --git a/backend/internal/service/gateway_ollama_cloud_pricing_preflight_test.go b/backend/internal/service/gateway_ollama_cloud_pricing_preflight_test.go new file mode 100644 index 0000000000..7cfdb5d86a --- /dev/null +++ b/backend/internal/service/gateway_ollama_cloud_pricing_preflight_test.go @@ -0,0 +1,50 @@ +package service + +import ( + "context" + "net/http" + "net/http/httptest" + "testing" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" +) + +// generic 网关(composite 跨族账号池经 Anthropic 协议链服务 ollama_cloud)同样在上游 +// I/O 之前拒绝无价出站模型,不得先服务再按 0 元计费。 +func TestGenericGatewayOllamaCloudPricingPreflight(t *testing.T) { + gin.SetMode(gin.TestMode) + billing := NewBillingService(&config.Config{}, nil) + svc := &GatewayService{resolver: NewModelPricingResolver(nil, billing)} + ollama := &Account{ID: 9, Platform: PlatformOllamaCloud, Type: AccountTypeAPIKey, + Credentials: map[string]any{"api_key": "sk-ollama"}} + + newCtx := func(path string) (*gin.Context, *httptest.ResponseRecorder) { + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, path, nil) + return c, rec + } + + c, rec := newCtx("/v1/messages") + _, _, err := svc.buildUpstreamRequest(context.Background(), c, ollama, + []byte(`{"model":"unpriced-ollama-model","max_tokens":8,"messages":[]}`), "sk-ollama", "apikey", "unpriced-ollama-model", false, false) + require.Error(t, err) + require.Equal(t, http.StatusBadRequest, rec.Code) + require.Equal(t, "error", gjson.GetBytes(rec.Body.Bytes(), "type").String(), "Anthropic 入站使用 Anthropic 错误信封") + require.Equal(t, "invalid_request_error", gjson.GetBytes(rec.Body.Bytes(), "error.type").String()) + + c, rec = newCtx("/v1/responses") + _, _, err = svc.buildUpstreamRequest(context.Background(), c, ollama, + []byte(`{"model":"unpriced-ollama-model","max_tokens":8,"messages":[]}`), "sk-ollama", "apikey", "unpriced-ollama-model", false, false) + require.Error(t, err) + require.Equal(t, http.StatusBadRequest, rec.Code) + require.False(t, gjson.GetBytes(rec.Body.Bytes(), "type").Exists(), "OpenAI 入站使用 OpenAI 错误信封") + + // 有价模型、非 ollama 账号不受预检影响。 + require.NoError(t, svc.enforceOllamaCloudRequestPricingPreflight(context.Background(), nil, ollama, []byte(`{"model":"gpt-oss:120b"}`), "")) + require.NoError(t, svc.enforceOllamaCloudRequestPricingPreflight(context.Background(), nil, + &Account{ID: 10, Platform: PlatformKimi, Type: AccountTypeAPIKey}, []byte(`{"model":"unpriced-ollama-model"}`), "")) +} diff --git a/backend/internal/service/gateway_upstream_request.go b/backend/internal/service/gateway_upstream_request.go index 5e11d5af93..49b6838531 100644 --- a/backend/internal/service/gateway_upstream_request.go +++ b/backend/internal/service/gateway_upstream_request.go @@ -19,6 +19,9 @@ import ( ) func (s *GatewayService) buildUpstreamRequest(ctx context.Context, c *gin.Context, account *Account, body []byte, token, tokenType, modelID string, reqStream bool, mimicClaudeCode bool) (*http.Request, []byte, error) { + if err := s.enforceOllamaCloudRequestPricingPreflight(ctx, c, account, body, modelID); err != nil { + return nil, nil, err + } body = stripDeferredToolCacheControl(body) if account.Platform == PlatformAnthropic && account.Type == AccountTypeServiceAccount { req, err := s.buildUpstreamRequestAnthropicVertex(ctx, c, account, body, token, modelID, reqStream) diff --git a/backend/internal/service/ollama_cloud_dynamic_catalog_pricing_test.go b/backend/internal/service/ollama_cloud_dynamic_catalog_pricing_test.go index 0566ea4f06..8fd32044eb 100644 --- a/backend/internal/service/ollama_cloud_dynamic_catalog_pricing_test.go +++ b/backend/internal/service/ollama_cloud_dynamic_catalog_pricing_test.go @@ -150,3 +150,29 @@ func TestGetModelPricing_GptOssExclusionNarrowedToColonNamespace(t *testing.T) { "antigravity hyphen-form name must resolve via the OpenAI catch-all (gpt-5.4), not fail open") }) } + +// 剥 tag 二级查价只接受确定性命中:gpt-oss:latest 剥成 gpt-oss 后不得被 OpenAI 末端 +// catch-all 猜成 gpt-5.4 价;gpt-oss-safeguard:20b 等带 tag 变体同样不进 OpenAI 链。 +// 无确定价时 fail-closed,计费门禁据此拒绝保存与转发,而不是按无关模型价静默计费。 +func TestGetModelPricing_TaggedNamesNeverGuessedFromStrippedName(t *testing.T) { + bs := newTestBillingServiceWithOpenAILadderCatalog(t) + + for _, model := range []string{"gpt-oss:latest", "gpt-oss:999b", "gpt-oss-safeguard:20b"} { + t.Run(model, func(t *testing.T) { + _, err := bs.getModelPricingAt(model, ollamaPricingAt) + require.ErrorIs(t, err, ErrModelPricingUnavailable) + }) + } + + // 剥 tag 后精确命中目录的名字仍按基础模型定价。 + pricing, err := bs.getModelPricingAt("gpt-5.4:latest", ollamaPricingAt) + require.NoError(t, err) + require.InDelta(t, 2.5e-6, pricing.InputPricePerToken, 1e-12) + + // 带 tag 的 ollama 价卡精确键与无 tag 的 Antigravity 连字符形态不受影响。 + pricing, err = bs.getModelPricingAt("gpt-oss:20b", ollamaPricingAt) + require.NoError(t, err) + require.InDelta(t, 0.07e-6, pricing.InputPricePerToken, 1e-12) + _, err = bs.getModelPricingAt("gpt-oss-120b-medium", ollamaPricingAt) + require.NoError(t, err) +} 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 9c23e5cab9..ab06456a4e 100644 --- a/backend/internal/service/openai_gateway_ollama_cloud_pricing_preflight.go +++ b/backend/internal/service/openai_gateway_ollama_cloud_pricing_preflight.go @@ -80,7 +80,15 @@ func ollamaCloudBillingGroupFromContext(ctx context.Context) *Group { // struct 的单测与内部调用不应被门禁拦截(与 resolveOpenAIChannelPricing 的 nil 守卫 // 同一取舍)。 func (s *OpenAIGatewayService) ollamaCloudModelUnpricedForBilling(ctx context.Context, model string) bool { - if s == nil || s.resolver == nil { + if s == nil { + return false + } + return ollamaCloudModelUnpricedForBilling(ctx, s.resolver, model) +} + +// ollamaCloudModelUnpricedForBilling 是 OpenAI 网关与 generic 网关共用的无价判定。 +func ollamaCloudModelUnpricedForBilling(ctx context.Context, resolver *ModelPricingResolver, model string) bool { + if resolver == nil { return false } group := ollamaCloudBillingGroupFromContext(ctx) @@ -89,7 +97,7 @@ func (s *OpenAIGatewayService) ollamaCloudModelUnpricedForBilling(ctx context.Co gid := group.ID groupID = &gid } - resolved := s.resolver.Resolve(ctx, PricingInput{Model: model, GroupID: groupID, Group: group}) + resolved := resolver.Resolve(ctx, PricingInput{Model: model, GroupID: groupID, Group: group}) if resolved == nil { return true } @@ -102,7 +110,7 @@ func (s *OpenAIGatewayService) ollamaCloudModelUnpricedForBilling(ctx context.Co // 定价上下文取 1 token(最低档):GetIntervalPricing 返回 nil 与否只取决于 // BasePricing 是否存在,与上下文档位无关,与 calculateTokenCost 的失败条件 // 完全同一条链。 - return s.resolver.GetIntervalPricing(resolved, 1) == nil + return resolver.GetIntervalPricing(resolved, 1) == nil } // enforceOllamaCloudRequestPricingPreflight 在上游 I/O 之前对 ollama_cloud 出站做 @@ -124,3 +132,30 @@ func (s *OpenAIGatewayService) enforceOllamaCloudRequestPricingPreflight(ctx con respondOpenAIOllamaCloudUnpricedModelError(c, err) return err } + +// enforceOllamaCloudRequestPricingPreflight 是 generic 网关(composite 跨族账号池经 +// Anthropic 协议链服务 ollama_cloud 账号)的同一预检:在上游 I/O 之前拒绝无价出站模型, +// 错误信封按入站协议选择(/messages 为 Anthropic 风格,其余为 OpenAI 风格)。 +func (s *GatewayService) enforceOllamaCloudRequestPricingPreflight(ctx context.Context, c *gin.Context, account *Account, body []byte, fallbackModel string) error { + if s == nil || account == nil || !account.IsOllamaCloud() { + return nil + } + model := strings.TrimSpace(gjson.GetBytes(body, "model").String()) + if model == "" { + model = strings.TrimSpace(fallbackModel) + } + if model == "" || !ollamaCloudModelUnpricedForBilling(ctx, s.resolver, model) { + return nil + } + err := &openAIOllamaCloudUnpricedModelError{model: model} + if c != nil { + setOpsUpstreamError(c, http.StatusBadRequest, err.Error(), "") + MarkResponseCommitted(c) + payload := gin.H{"error": gin.H{"type": "invalid_request_error", "message": err.Error()}} + if c.Request != nil && c.Request.URL != nil && strings.Contains(c.Request.URL.Path, "/messages") { + payload = gin.H{"type": "error", "error": gin.H{"type": "invalid_request_error", "message": err.Error()}} + } + c.JSON(http.StatusBadRequest, payload) + } + return err +} diff --git a/backend/internal/service/pricing_service.go b/backend/internal/service/pricing_service.go index e3938763dd..84bbe8d98f 100644 --- a/backend/internal/service/pricing_service.go +++ b/backend/internal/service/pricing_service.go @@ -1220,9 +1220,10 @@ func (s *PricingService) GetModelPricing(modelName string) *LiteLLMModelPricing // 不进本回退链 —— 否则 matchOpenAIModel 的末端 catch-all 会把它落到 // DefaultTestModel("gpt-5.4") 的价卡($2.5/$15 per MTok)上静默误计。 // 返回 nil 交还 BillingService 走 fallbackPrices 的 ollama 专属价卡。 - // 排除只收窄到 "gpt-oss:"(冒号命名空间,ollama 命名形态);连字符形态如 - // Antigravity 的 "gpt-oss-120b-medium" 不在排除内,保持进 OpenAI 链的既有行为。 - if strings.HasPrefix(lookupCandidates[0], "gpt-") && !strings.HasPrefix(lookupCandidates[0], "gpt-oss:") { + // 排除收窄到带 ":tag" 的 gpt-oss 系列(ollama 命名形态,含 gpt-oss-safeguard:20b + // 等变体);无 tag 的连字符形态如 Antigravity 的 "gpt-oss-120b-medium" 不在排除内, + // 保持进 OpenAI 链的既有行为。 + if strings.HasPrefix(lookupCandidates[0], "gpt-") && !isTaggedGPTOSSModel(lookupCandidates[0]) { return s.matchOpenAIModel(lookupCandidates[0]) } @@ -1742,3 +1743,8 @@ func isNumeric(s string) bool { } return true } + +// isTaggedGPTOSSModel 报告模型名是否为带 ":tag" 的 gpt-oss 开放权重模型(ollama 命名)。 +func isTaggedGPTOSSModel(model string) bool { + return strings.HasPrefix(model, "gpt-oss") && strings.Contains(model, ":") +} From 7e20400a8289a218716a7bab831cd715b0cf9b87 Mon Sep 17 00:00:00 2001 From: shaw Date: Fri, 9 Oct 2026 15:32:51 +0800 Subject: [PATCH 48/81] =?UTF-8?q?test(composite):=20=E6=96=B0=E5=A2=9E=20h?= =?UTF-8?q?andler=20=E6=B5=8B=E8=AF=95=E8=A1=A5=20unit=20=E6=9E=84?= =?UTF-8?q?=E5=BB=BA=E6=A0=87=E7=AD=BE=EF=BC=88=E4=BE=9D=E8=B5=96=20unit?= =?UTF-8?q?=20=E5=A4=B9=E5=85=B7=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../internal/handler/composite_pool_gemini_credentials_test.go | 2 ++ .../handler/composite_pool_reasoning_policy_generic_test.go | 2 ++ 2 files changed, 4 insertions(+) diff --git a/backend/internal/handler/composite_pool_gemini_credentials_test.go b/backend/internal/handler/composite_pool_gemini_credentials_test.go index bb1d028cb8..eb0189f970 100644 --- a/backend/internal/handler/composite_pool_gemini_credentials_test.go +++ b/backend/internal/handler/composite_pool_gemini_credentials_test.go @@ -1,3 +1,5 @@ +//go:build unit + package handler import ( diff --git a/backend/internal/handler/composite_pool_reasoning_policy_generic_test.go b/backend/internal/handler/composite_pool_reasoning_policy_generic_test.go index c9772366de..44db7df146 100644 --- a/backend/internal/handler/composite_pool_reasoning_policy_generic_test.go +++ b/backend/internal/handler/composite_pool_reasoning_policy_generic_test.go @@ -1,3 +1,5 @@ +//go:build unit + package handler import ( From db19b5616baf1a85de69f5691530d28e23ea3947 Mon Sep 17 00:00:00 2001 From: shaw Date: Fri, 9 Oct 2026 15:45:52 +0800 Subject: [PATCH 49/81] =?UTF-8?q?test(platform):=20provider=20profile=20?= =?UTF-8?q?=E8=B0=93=E8=AF=8D=E7=AD=89=E4=BB=B7=E5=9F=BA=E5=87=86=E8=A1=A5?= =?UTF-8?q?=E5=85=A5=20ollama=5Fcloud?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/internal/service/platform_list_test.go | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/backend/internal/service/platform_list_test.go b/backend/internal/service/platform_list_test.go index f299c9c7b5..d20929bfe8 100644 --- a/backend/internal/service/platform_list_test.go +++ b/backend/internal/service/platform_list_test.go @@ -130,9 +130,10 @@ func TestProviderProfilesUseOpenAIGateway(t *testing.T) { func TestProviderProfileAccountPredicatesMatchLegacy(t *testing.T) { for _, platform := range platformProbeValues { account := &Account{Platform: platform, Type: AccountTypeAPIKey} - // Cline 只有 Chat Completions 一个端点,按入站协议分流(其余入站转换)。 - require.Equal(t, legacyIsCNProvider(platform) || platform == PlatformCline, account.RoutesProtocolByInbound(), platform) - require.Equal(t, legacyIsCNProvider(platform) || platform == PlatformOpenCodeGo || platform == PlatformCommandCode || platform == PlatformCline, account.IsMultiProtocolAPIKey(), platform) + // Cline 只有 Chat Completions 一个端点,按入站协议分流(其余入站转换);Ollama Cloud + // 合并前的手写判断与国产厂商并列(三协议原生端点,按入站协议分流)。 + require.Equal(t, legacyIsCNProvider(platform) || platform == PlatformCline || platform == PlatformOllamaCloud, account.RoutesProtocolByInbound(), platform) + require.Equal(t, legacyIsCNProvider(platform) || platform == PlatformOpenCodeGo || platform == PlatformCommandCode || platform == PlatformCline || platform == PlatformOllamaCloud, account.IsMultiProtocolAPIKey(), platform) } var nilAccount *Account require.False(t, nilAccount.RoutesProtocolByInbound()) From 1975e65493fadd61ef21bea59c2c9bd1cdeff31d Mon Sep 17 00:00:00 2001 From: shaw Date: Fri, 9 Oct 2026 17:20:45 +0800 Subject: [PATCH 50/81] =?UTF-8?q?fix(composite):=20count=5Ftokens=20?= =?UTF-8?q?=E9=80=89=E4=B8=AD=20grok=20=E8=B4=A6=E5=8F=B7=E6=97=B6?= =?UTF-8?q?=E6=9C=AC=E5=9C=B0=E4=BC=B0=E7=AE=97=EF=BC=8C=E6=9D=9C=E7=BB=9D?= =?UTF-8?q?=20xAI=20=E5=87=AD=E6=8D=AE=E5=8F=91=E5=BE=80=20api.openai.com?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 兼容族账号池(如 [deepseek, grok])的 count_tokens 走 OpenAI CountTokens, 可选中 grok 账号;ForwardCountTokensAsAnthropic 只对多协议账号本地估算, grok 的 GetOpenAIBaseURL 为空会回落 api.openai.com 并携带 xAI 凭据,401 还会 误伤账号调度。grok 与多协议账号同走本地估算。 --- .../handler/openai_gateway_count_tokens.go | 4 +- .../ollama_cloud_platform_routing_test.go | 49 ++++++++++--------- .../service/openai_gateway_count_tokens.go | 8 +-- 3 files changed, 32 insertions(+), 29 deletions(-) diff --git a/backend/internal/handler/openai_gateway_count_tokens.go b/backend/internal/handler/openai_gateway_count_tokens.go index 2df4f4f2d0..6f51edd207 100644 --- a/backend/internal/handler/openai_gateway_count_tokens.go +++ b/backend/internal/handler/openai_gateway_count_tokens.go @@ -232,8 +232,8 @@ func (h *OpenAIGatewayHandler) CountTokens(c *gin.Context) { reqModel := parsedReq.Model ensureCompositeTargetPlatform(c, apiKey, reqModel) - // composite+grok 在路由层已分流到 GrokCountTokens,这里可达的目标平台是 - // openai 与 CN 供应商;CN 账号由 ForwardCountTokensAsAnthropic 本地估算。 + // 单目标 composite+grok 在路由层已分流到 GrokCountTokens;兼容族账号池仍可能 + // 选中 grok 账号,与 CN 账号一样由 ForwardCountTokensAsAnthropic 本地估算。 if !openAICompatibleTextTargetAllowed(c, apiKey, reqModel) { h.anthropicErrorResponse(c, http.StatusBadRequest, "invalid_request_error", "Model is not supported by this OpenAI-compatible endpoint for composite groups") return diff --git a/backend/internal/service/ollama_cloud_platform_routing_test.go b/backend/internal/service/ollama_cloud_platform_routing_test.go index 3f6e2e302a..3e33ff60c5 100644 --- a/backend/internal/service/ollama_cloud_platform_routing_test.go +++ b/backend/internal/service/ollama_cloud_platform_routing_test.go @@ -185,34 +185,35 @@ func TestShouldForwardOpenAIResponsesViaRawChatCompletions_OllamaCloud(t *testin require.False(t, shouldForwardOpenAIResponsesViaRawChatCompletions(account(APIProtocolResponses))) } -// TestForwardCountTokensAsAnthropic_OllamaCloudEstimatesLocally 覆盖 ⑨ findings B1: -// ollama_cloud 账号命中本地估算分支,返回 200 且不产生任何出站请求。 -func TestForwardCountTokensAsAnthropic_OllamaCloudEstimatesLocally(t *testing.T) { +// TestForwardCountTokensAsAnthropic_EstimatesLocallyWithoutUpstream 覆盖无 +// Anthropic count_tokens 端点的账号:ollama_cloud(⑨ findings B1)与 grok +// (composite 兼容族账号池可选中,放行会把 xAI 凭据发往 api.openai.com) +// 均命中本地估算分支,返回 200 且不产生任何出站请求。 +func TestForwardCountTokensAsAnthropic_EstimatesLocallyWithoutUpstream(t *testing.T) { gin.SetMode(gin.TestMode) body := []byte(`{"model":"claude-sonnet-4-5","system":"You are helpful.","messages":[{"role":"user","content":"hello"}]}`) - rec := httptest.NewRecorder() - c, _ := gin.CreateTestContext(rec) - c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages/count_tokens", bytes.NewReader(body)) - c.Request.Header.Set("Content-Type", "application/json") + for _, account := range []*Account{ + {ID: 904, Platform: PlatformOllamaCloud, Type: AccountTypeAPIKey, Credentials: map[string]any{"api_key": "sk-test"}, Extra: map[string]any{}}, + {ID: 905, Platform: PlatformGrok, Type: AccountTypeAPIKey, Credentials: map[string]any{"api_key": "xai-test"}, Extra: map[string]any{}}, + {ID: 906, Platform: PlatformGrok, Type: AccountTypeOAuth, Credentials: map[string]any{"access_token": "xai-oauth"}, Extra: map[string]any{}}, + } { + t.Run(account.Platform+"_"+account.Type, func(t *testing.T) { + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages/count_tokens", bytes.NewReader(body)) + c.Request.Header.Set("Content-Type", "application/json") - upstream := &httpUpstreamRecorder{err: errors.New("local estimate must not hit upstream")} - svc := ollamaCloudRoutingTestService() - svc.httpUpstream = upstream + upstream := &httpUpstreamRecorder{err: errors.New("local estimate must not hit upstream")} + svc := ollamaCloudRoutingTestService() + svc.httpUpstream = upstream - account := &Account{ - ID: 904, - Name: "ollama-cloud-count-tokens", - Platform: PlatformOllamaCloud, - Type: AccountTypeAPIKey, - Credentials: map[string]any{"api_key": "sk-test"}, - Extra: map[string]any{}, + err := svc.ForwardCountTokensAsAnthropic(context.Background(), c, account, body, "claude-sonnet-4-5") + require.NoError(t, err) + require.Equal(t, http.StatusOK, rec.Code) + require.Greater(t, gjson.Get(rec.Body.String(), "input_tokens").Int(), int64(0)) + require.Nil(t, upstream.lastReq) + require.Empty(t, upstream.requests) + }) } - - err := svc.ForwardCountTokensAsAnthropic(context.Background(), c, account, body, "claude-sonnet-4-5") - require.NoError(t, err) - require.Equal(t, http.StatusOK, rec.Code) - require.Greater(t, gjson.Get(rec.Body.String(), "input_tokens").Int(), int64(0)) - require.Nil(t, upstream.lastReq) - require.Empty(t, upstream.requests) } diff --git a/backend/internal/service/openai_gateway_count_tokens.go b/backend/internal/service/openai_gateway_count_tokens.go index e1af16566f..c42feabc98 100644 --- a/backend/internal/service/openai_gateway_count_tokens.go +++ b/backend/internal/service/openai_gateway_count_tokens.go @@ -273,13 +273,15 @@ func (s *OpenAIGatewayService) ForwardCountTokensAsAnthropic( // 高频调用此端点,本地 tiktoken 估算是与 Grok 一致的既有方案。 // Ollama Cloud 同因:其 Anthropic 兼容层同样未提供该端点(上游只有 // /v1/responses/input_tokens),转发同样只会得到 404。 - if account.IsMultiProtocolAPIKey() { + // Grok 无 input_tokens 端点且 GetOpenAIBaseURL 为空:composite 兼容族账号池 + // 可选中 grok 账号,若放行会把 xAI 凭据发往 api.openai.com。 + if account.IsMultiProtocolAPIKey() || account.IsGrok() { estimated, err := estimateAnthropicCountTokensLocally(body) if err != nil { writeAnthropicCountTokensError(c, http.StatusBadRequest, "invalid_request_error", "Failed to parse request body") - return fmt.Errorf("count_tokens: estimate cn provider input tokens: %w", err) + return fmt.Errorf("count_tokens: estimate input tokens locally: %w", err) } - logger.L().Debug("openai count_tokens: cn provider local estimate", + logger.L().Debug("openai count_tokens: local estimate", zap.Int64("account_id", account.ID), zap.Int("estimated_input_tokens", estimated), ) From ab6b1f79b242401154fa277201155083c3420c11 Mon Sep 17 00:00:00 2001 From: shaw Date: Fri, 9 Oct 2026 17:20:46 +0800 Subject: [PATCH 51/81] =?UTF-8?q?fix(billing):=20generic=20=E9=93=BE?= =?UTF-8?q?=E8=BD=AC=E5=8F=91=E7=9A=84=E6=89=98=E7=AE=A1=E6=A8=A1=E5=9E=8B?= =?UTF-8?q?=E8=B4=A6=E5=8F=B7=E6=8C=89=E5=AE=9E=E9=99=85=E8=BD=AC=E5=8F=91?= =?UTF-8?q?=E6=A8=A1=E5=9E=8B=E8=AE=A1=E8=B4=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit composite 跨族池中 adaptive/anthropic 协议的 CN 与 Ollama Cloud 账号经 generic Forward 转发,计费取客户端请求名:claude-* 别名映射到 glm 等托管模型时按 Claude 价收费。与 OpenAI 链同口径:按实际转发模型计费,未显式定价的 claude-* 候选剔除;抽出 accountServesHostedModels / dropUnpricedClaudeBillingCandidates 供两条链共用。 --- .../service/gateway_record_usage_test.go | 48 +++++++++++++++++++ .../internal/service/gateway_usage_billing.go | 14 ++++++ .../internal/service/openai_gateway_usage.go | 19 ++++++-- 3 files changed, 78 insertions(+), 3 deletions(-) diff --git a/backend/internal/service/gateway_record_usage_test.go b/backend/internal/service/gateway_record_usage_test.go index 9dfa556298..e11960a0c7 100644 --- a/backend/internal/service/gateway_record_usage_test.go +++ b/backend/internal/service/gateway_record_usage_test.go @@ -230,6 +230,54 @@ func TestGatewayServiceRecordUsage_GeminiFlashThinkingTierUsesCatalogPrice(t *te } } +// composite 跨族池里 CN / Ollama Cloud 账号经 generic 链转发:请求名(claude-*)只是 +// 入站别名,计费须按实际转发的托管模型,且未显式定价的 claude-* 不得按 Claude 价计; +// anthropic 账号仍按请求模型计费。 +func TestGatewayServiceRecordUsage_HostedModelAccountsBillByUpstreamModel(t *testing.T) { + pricing := map[string]*LiteLLMModelPricing{ + "claude-sonnet-4-5": {InputCostPerToken: 3e-6, OutputCostPerToken: 15e-6}, + "glm-5.3": {InputCostPerToken: 1e-6, OutputCostPerToken: 2e-6}, + } + cases := []struct { + name string + account *Account + upstreamModel string + wantCost float64 + }{ + {"ollama_cloud mapped", &Account{ID: 701, Platform: PlatformOllamaCloud, Type: AccountTypeAPIKey}, "glm-5.3", 1000*1e-6 + 100*2e-6}, + {"cn provider mapped", &Account{ID: 702, Platform: PlatformZhipu, Type: AccountTypeAPIKey}, "glm-5.3", 1000*1e-6 + 100*2e-6}, + {"cn provider unmapped claude", &Account{ID: 703, Platform: PlatformKimi, Type: AccountTypeAPIKey}, "claude-sonnet-4-5", 0}, + {"anthropic keeps requested model", &Account{ID: 704, Platform: PlatformAnthropic, Type: AccountTypeAPIKey}, "glm-5.3", 1000*3e-6 + 100*15e-6}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + usageRepo := &openAIRecordUsageLogRepoStub{inserted: true} + svc := newGatewayRecordUsageServiceForTest(usageRepo, &openAIRecordUsageUserRepoStub{}, &openAIRecordUsageSubRepoStub{}) + svc.billingService = NewBillingService(svc.cfg, &PricingService{pricingData: pricing}) + svc.resolver = NewModelPricingResolver(nil, svc.billingService) + group := &Group{ID: 28, Platform: PlatformComposite, RateMultiplier: 1} + + err := svc.RecordUsage(context.Background(), &RecordUsageInput{ + Result: &ForwardResult{ + RequestID: "hosted_model_billing", + Model: "claude-sonnet-4-5", + UpstreamModel: tc.upstreamModel, + Usage: ClaudeUsage{InputTokens: 1000, OutputTokens: 100}, + Duration: time.Second, + }, + APIKey: &APIKey{ID: 501, GroupID: &group.ID, Group: group}, + User: &User{ID: 601}, + Account: tc.account, + }) + + require.NoError(t, err) + require.NotNil(t, usageRepo.lastLog) + require.Equal(t, "claude-sonnet-4-5", usageRepo.lastLog.RequestedModel) + require.InDelta(t, tc.wantCost, usageRepo.lastLog.TotalCost, 1e-12) + }) + } +} + func TestGatewayServiceRecordUsage_PreservesChannelMappedUpstreamModel(t *testing.T) { usageRepo := &openAIRecordUsageLogRepoStub{inserted: true} svc := newGatewayRecordUsageServiceForTest(usageRepo, &openAIRecordUsageUserRepoStub{}, &openAIRecordUsageSubRepoStub{}) diff --git a/backend/internal/service/gateway_usage_billing.go b/backend/internal/service/gateway_usage_billing.go index 07f7121ec3..4161a30d5f 100644 --- a/backend/internal/service/gateway_usage_billing.go +++ b/backend/internal/service/gateway_usage_billing.go @@ -824,6 +824,12 @@ func (s *GatewayService) recordUsageCore(ctx context.Context, input *recordUsage // 确定计费模型 concreteBillingModel := forwardResultBillingModel(result.Model, result.UpstreamModel) + hostedModels := accountServesHostedModels(account) + if hostedModels { + // 托管模型上游(composite 跨族池经 generic 链转发的 CN / Ollama Cloud 账号) + // 按实际转发的模型计费,与 OpenAI 链 result.BillingModel 同口径。 + concreteBillingModel = forwardResultBillingModel(result.UpstreamModel, result.Model) + } billingModel := concreteBillingModel if input.BillingModelSource == BillingModelSourceChannelMapped && input.ChannelMappedModel != "" { billingModel = input.ChannelMappedModel @@ -841,6 +847,14 @@ func (s *GatewayService) recordUsageCore(ctx context.Context, input *recordUsage // 通用兜底(与 OpenAI 路径的 usageBillingModelCandidates 语义对齐): // 选定模型查不到任何价格时回退到实际转发的具体模型。已定价流量不受影响。 billingModel = s.billableModelWithFallback(ctx, apiKey, billingModel, result.UpstreamModel, result.Model) + if hostedModels { + // 与 OpenAI 链 filterCNProviderBillingModelCandidates 一致:claude-* 名不会被 + // 托管上游真正服务,未显式定价时不得按 Claude 价计费;候选全部落空则走零成本告警。 + billingModel = firstUsageBillingModel(dropUnpricedClaudeBillingCandidates( + usageBillingModelCandidates(billingModel, concreteBillingModel), + func(model string) bool { return s.resolveChannelPricing(ctx, model, apiKey) != nil }, + )) + } // 确定 RequestedModel(渠道映射前的原始模型) requestedModel := result.Model diff --git a/backend/internal/service/openai_gateway_usage.go b/backend/internal/service/openai_gateway_usage.go index 0392bd7acb..63e75034d1 100644 --- a/backend/internal/service/openai_gateway_usage.go +++ b/backend/internal/service/openai_gateway_usage.go @@ -1011,17 +1011,30 @@ func groupMediaPricingLooksIncomplete(group *Group) bool { // 以避免误计价」的既有设计意图一致;运营者的修复手段是配置账号级 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() && !account.IsOllamaCloud()) { + if !accountServesHostedModels(account) { return candidates } + return dropUnpricedClaudeBillingCandidates(candidates, func(model string) bool { + return s.resolveOpenAIChannelPricing(ctx, model, apiKey) != nil + }) +} + +// accountServesHostedModels 报告账号上游是否只服务自家托管模型(CN 供应商 / +// OpenCode Go / Ollama Cloud):请求里的 claude-* 等名字只是入站别名,计费须按 +// 实际转发的模型,不能按请求名。 +func accountServesHostedModels(account *Account) bool { + return account != nil && (account.IsCNProvider() || account.IsOpenCodeGo() || account.IsOllamaCloud()) +} + +// dropUnpricedClaudeBillingCandidates 剔除未显式配置分组/渠道定价的 claude-* 候选。 +func dropUnpricedClaudeBillingCandidates(candidates []string, channelPriced func(model string) bool) []string { out := make([]string, 0, len(candidates)) for _, candidate := range candidates { trimmed := strings.TrimSpace(candidate) if trimmed == "" { continue } - if strings.Contains(strings.ToLower(trimmed), "claude") && - s.resolveOpenAIChannelPricing(ctx, trimmed, apiKey) == nil { + if strings.Contains(strings.ToLower(trimmed), "claude") && !channelPriced(trimmed) { continue } out = append(out, candidate) From b77335165c5975fcf7536b4c7e2f79509bb6a74d Mon Sep 17 00:00:00 2001 From: shaw Date: Fri, 9 Oct 2026 17:20:46 +0800 Subject: [PATCH 52/81] =?UTF-8?q?fix(ollama):=20Responses=20=E8=BD=AC?= =?UTF-8?q?=E5=8F=91=E4=BF=9D=E7=95=99=E5=AE=A2=E6=88=B7=E7=AB=AF=E6=9C=AA?= =?UTF-8?q?=E8=B6=85=E9=99=90=E7=9A=84=20max=5Foutput=5Ftokens?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ollama_cloud 落入平台 switch 的 default 分支被删除 max_output_tokens,后续 clamp 只在超限时回写,常规上限(如 4096)被静默丢弃。纳入保留分支,超限值 仍由 clamp 收敛到 65535。 --- backend/internal/service/openai_gateway_forward.go | 3 ++- .../openai_gateway_ollama_cloud_max_tokens_test.go | 9 +++++++++ 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/backend/internal/service/openai_gateway_forward.go b/backend/internal/service/openai_gateway_forward.go index 8888bf214c..58ce394319 100644 --- a/backend/internal/service/openai_gateway_forward.go +++ b/backend/internal/service/openai_gateway_forward.go @@ -584,9 +584,10 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco maxOutputTokens := gjson.GetBytes(body, "max_output_tokens") if maxOutputTokens.Exists() { switch account.Platform { - case PlatformOpenAI, PlatformDeepseek: + case PlatformOpenAI, PlatformDeepseek, PlatformOllamaCloud: // Preserve Responses-native output limits unless the selected upstream // explicitly rejects the field in the bounded HTTP retry loop below. + // Ollama Cloud over-cap values are clamped after this switch. case PlatformAnthropic: decoded, decodeErr := ensureReqBody() if decodeErr != nil { diff --git a/backend/internal/service/openai_gateway_ollama_cloud_max_tokens_test.go b/backend/internal/service/openai_gateway_ollama_cloud_max_tokens_test.go index 2940634737..8a5cac55fe 100644 --- a/backend/internal/service/openai_gateway_ollama_cloud_max_tokens_test.go +++ b/backend/internal/service/openai_gateway_ollama_cloud_max_tokens_test.go @@ -420,6 +420,15 @@ func TestForwardResponsesClampsOllamaCloudMaxOutputTokens(t *testing.T) { require.Equal(t, int64(65535), gjson.GetBytes(upstream.lastBody, "max_output_tokens").Int()) }) + t.Run("ollama_cloud platform keeps in-cap client limit", func(t *testing.T) { + account := ollamaUpstreamTestAccount(PlatformOllamaCloud, 339) + account.Credentials["api_protocol"] = APIProtocolResponses + inCap := []byte(`{"model":"gpt-oss:120b-cloud","input":"hi","max_output_tokens":4096,"stream":false}`) + upstream, err := run(account, inCap) + require.Error(t, err) + require.Equal(t, int64(4096), gjson.GetBytes(upstream.lastBody, "max_output_tokens").Int()) + }) + t.Run("official deepseek with leftover usage extra is untouched", func(t *testing.T) { account := officialDeepSeekTestAccount(333) account.Credentials["api_protocol"] = APIProtocolResponses From 10a5028d7f6add4d3a87e84bfafdd39698c235f0 Mon Sep 17 00:00:00 2001 From: shaw Date: Fri, 9 Oct 2026 17:20:47 +0800 Subject: [PATCH 53/81] =?UTF-8?q?fix(composite):=20generic=20Responses/CC?= =?UTF-8?q?=20=E5=A7=94=E6=B4=BE=E9=93=BE=E6=B5=81=E4=B8=AD=E6=96=AD?= =?UTF-8?q?=E6=97=B6=E9=83=A8=E5=88=86=E7=94=A8=E9=87=8F=E7=85=A7=E5=B8=B8?= =?UTF-8?q?=E5=85=A5=E8=B4=A6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 委派 OpenAI 网关链的池 attempt 在非 failover 错误时直接返回,丢弃上游已计量 的部分 usage;与 OpenAI handler 及 generic Messages 同语义(#5148)补记。 --- ...posite_generic_pool_text_endpoints_test.go | 24 +++++++++++ .../gateway_handler_chat_completions.go | 40 ++++++++++++------- .../handler/gateway_handler_responses.go | 40 ++++++++++++------- 3 files changed, 74 insertions(+), 30 deletions(-) diff --git a/backend/internal/handler/composite_generic_pool_text_endpoints_test.go b/backend/internal/handler/composite_generic_pool_text_endpoints_test.go index 62c33f6fbf..ddba7de277 100644 --- a/backend/internal/handler/composite_generic_pool_text_endpoints_test.go +++ b/backend/internal/handler/composite_generic_pool_text_endpoints_test.go @@ -8,6 +8,7 @@ import ( "net/http" "strings" "testing" + "testing/iotest" "github.com/Wei-Shaw/sub2api/internal/service" "github.com/stretchr/testify/require" @@ -245,6 +246,29 @@ func TestCompositePoolChatCompletionsDelegatesPureOpenAIFamilyAccount(t *testing require.Equal(t, "kimi-k3", *logs[0].UpstreamModel) } +// 委派链流中断(已向客户端写出内容、无法 failover):与 OpenAI handler 同语义, +// 上游已计量的部分 usage 照常入账(#5148),不得静默漏记。 +func TestCompositePoolChatCompletionsDelegatedStreamTruncationRecordsPartialUsage(t *testing.T) { + h := newCompositePoolMessagesHarness(t, []*service.Account{poolKimiAccount(42405, 41011, 0)}) + h.openAIUpstream.respond = func(compositePoolUpstreamCall, int) *http.Response { + stream := "data: {\"id\":\"chatcmpl-cut\",\"object\":\"chat.completion.chunk\",\"model\":\"kimi-k3\",\"choices\":[{\"index\":0,\"delta\":{\"content\":\"partial\"}}]}\n\n" + return &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{"text/event-stream"}}, + Body: io.NopCloser(io.MultiReader(strings.NewReader(stream), iotest.ErrReader(io.ErrUnexpectedEOF))), + } + } + + body := `{"model":"my-model","stream":true,"messages":[{"role":"user","content":"hello"}]}` + c, _ := h.newRequest(t, "/v1/chat/completions", body, service.PlatformAnthropic, service.PlatformKimi) + h.handler.ChatCompletions(c) + + require.Len(t, h.openAIUpstream.snapshot(), 1) + logs := h.usageRepo.snapshot() + require.Len(t, logs, 1, "流中断的委派结果必须入账") + require.EqualValues(t, 42405, logs[0].AccountID) +} + // 池选中 adaptive 多协议账号:CC 入站由 OpenAI CC 链直转供应商原生 CC 端点 // (入站同族优先,零转换;与其在纯 OpenAI 族池中的行为一致),不走 CC→Anthropic // 既有转换链。 diff --git a/backend/internal/handler/gateway_handler_chat_completions.go b/backend/internal/handler/gateway_handler_chat_completions.go index 20f9d873fc..7dc9a637ef 100644 --- a/backend/internal/handler/gateway_handler_chat_completions.go +++ b/backend/internal/handler/gateway_handler_chat_completions.go @@ -410,6 +410,25 @@ func (h *GatewayHandler) ChatCompletions(c *gin.Context) { accountReleaseFunc() } + // 池委派 OpenAI 网关链的结果按 OpenAI 口径入账(见 submitDelegatedOpenAIUsage)。 + submitDelegatedUsage := func() { + quotaPlatform := service.QuotaPlatform(c.Request.Context(), apiKey) + if isPoolAttempt { + quotaPlatform = service.QuotaPlatform(attemptPolicy.AttemptCtx, apiKey) + } + h.submitDelegatedOpenAIUsage(c, delegatedOpenAIUsage{ + Result: delegatedResult, + APIKey: apiKey, + Account: account, + Subscription: subscription, + QuotaPlatform: quotaPlatform, + PricingAt: pricingAt, + RequestPayloadHash: service.HashUsageRequestPayload(body), + ChannelUsageFields: clientRequestedUsageFields(c, attemptChannelMapping, reqModel, delegatedResult.UpstreamModel), + LogComponent: "handler.gateway.chat_completions", + }) + } + if err != nil { var failoverErr *service.UpstreamFailoverError if errors.As(err, &failoverErr) { @@ -440,26 +459,17 @@ func (h *GatewayHandler) ChatCompletions(c *gin.Context) { zap.Bool("upstream_error_response_already_written", upstreamErrorAlreadyCommunicated), zap.Error(err), ) + // 委派链流中断与 OpenAI handler 同语义:上游已计量的部分 usage 照常入账(#5148); + // failover 错误恒定 result=nil,不会重复计费。 + if delegatedResult != nil { + submitDelegatedUsage() + } return } // 6. Record usage if delegatedResult != nil { - quotaPlatform := service.QuotaPlatform(c.Request.Context(), apiKey) - if isPoolAttempt { - quotaPlatform = service.QuotaPlatform(attemptPolicy.AttemptCtx, apiKey) - } - h.submitDelegatedOpenAIUsage(c, delegatedOpenAIUsage{ - Result: delegatedResult, - APIKey: apiKey, - Account: account, - Subscription: subscription, - QuotaPlatform: quotaPlatform, - PricingAt: pricingAt, - RequestPayloadHash: service.HashUsageRequestPayload(body), - ChannelUsageFields: clientRequestedUsageFields(c, attemptChannelMapping, reqModel, delegatedResult.UpstreamModel), - LogComponent: "handler.gateway.chat_completions", - }) + submitDelegatedUsage() return } userAgent := c.GetHeader("User-Agent") diff --git a/backend/internal/handler/gateway_handler_responses.go b/backend/internal/handler/gateway_handler_responses.go index 18db039a9f..36ed9e8f29 100644 --- a/backend/internal/handler/gateway_handler_responses.go +++ b/backend/internal/handler/gateway_handler_responses.go @@ -414,6 +414,25 @@ func (h *GatewayHandler) Responses(c *gin.Context) { accountReleaseFunc() } + // 池委派 OpenAI 网关链的结果按 OpenAI 口径入账(见 submitDelegatedOpenAIUsage)。 + submitDelegatedUsage := func() { + quotaPlatform := service.QuotaPlatform(c.Request.Context(), apiKey) + if isPoolAttempt { + quotaPlatform = service.QuotaPlatform(attemptPolicy.AttemptCtx, apiKey) + } + h.submitDelegatedOpenAIUsage(c, delegatedOpenAIUsage{ + Result: delegatedResult, + APIKey: apiKey, + Account: account, + Subscription: subscription, + QuotaPlatform: quotaPlatform, + PricingAt: pricingAt, + RequestPayloadHash: service.HashUsageRequestPayload(body), + ChannelUsageFields: clientRequestedUsageFields(c, attemptChannelMapping, reqModel, delegatedResult.UpstreamModel), + LogComponent: "handler.gateway.responses", + }) + } + if err != nil { var failoverErr *service.UpstreamFailoverError if errors.As(err, &failoverErr) { @@ -445,26 +464,17 @@ func (h *GatewayHandler) Responses(c *gin.Context) { zap.Bool("upstream_error_response_already_written", upstreamErrorAlreadyCommunicated), zap.Error(err), ) + // 委派链流中断与 OpenAI handler 同语义:上游已计量的部分 usage 照常入账(#5148); + // failover 错误恒定 result=nil,不会重复计费。 + if delegatedResult != nil { + submitDelegatedUsage() + } return } // 6. Record usage if delegatedResult != nil { - quotaPlatform := service.QuotaPlatform(c.Request.Context(), apiKey) - if isPoolAttempt { - quotaPlatform = service.QuotaPlatform(attemptPolicy.AttemptCtx, apiKey) - } - h.submitDelegatedOpenAIUsage(c, delegatedOpenAIUsage{ - Result: delegatedResult, - APIKey: apiKey, - Account: account, - Subscription: subscription, - QuotaPlatform: quotaPlatform, - PricingAt: pricingAt, - RequestPayloadHash: service.HashUsageRequestPayload(body), - ChannelUsageFields: clientRequestedUsageFields(c, attemptChannelMapping, reqModel, delegatedResult.UpstreamModel), - LogComponent: "handler.gateway.responses", - }) + submitDelegatedUsage() return } userAgent := c.GetHeader("User-Agent") From fbd50da3f1daa0e665f0ebf6cee346579f4b6c38 Mon Sep 17 00:00:00 2001 From: shaw Date: Fri, 9 Oct 2026 17:20:47 +0800 Subject: [PATCH 54/81] =?UTF-8?q?fix(composite):=20=E6=9C=AA=E8=A7=A3?= =?UTF-8?q?=E6=9E=90=E6=A8=A1=E5=9E=8B=E4=BB=85=E5=9C=A8=E6=96=87=E6=9C=AC?= =?UTF-8?q?=E7=AB=AF=E7=82=B9=E6=8B=92=E7=BB=9D=EF=BC=8C=E6=81=A2=E5=A4=8D?= =?UTF-8?q?=20Seedance=20=E7=AD=89=E7=AB=AF=E7=82=B9=E6=94=BE=E8=A1=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 中间件对 composite 未解析模型一律 400,导致 Seedance 任务等由 handler 自定 平台的端点回归。入口拒绝只作用于 messages / responses / chat/completions。 --- backend/internal/server/routes/gateway.go | 21 +++++++-- .../routes/gateway_composite_pool_test.go | 43 ++++++++++++++++--- 2 files changed, 54 insertions(+), 10 deletions(-) diff --git a/backend/internal/server/routes/gateway.go b/backend/internal/server/routes/gateway.go index b793538722..a996837633 100644 --- a/backend/internal/server/routes/gateway.go +++ b/backend/internal/server/routes/gateway.go @@ -655,10 +655,15 @@ func compositeTargetPlatformMiddleware(resolver *service.CompositeRouteResolver) return } if !decision.Matched { - // composite 请求的模型既无显式路由、也无账号映射/候选池可归入 - // 具体平台:继续放行只会落到通用网关并按通用协议报错。对 - // composite 在入口明确以请求错误拒绝(带模型名与原因),信封 - // 按入站 endpoint 协议选择。 + if !compositeRouteResolutionRequired(c.Request.URL.Path) { + // 非文本端点(Seedance 任务、媒体等)由 handler 按自身平台语义处理。 + requestmodel.ResetRequestBody(c.Request, body) + c.Next() + return + } + // 文本端点的模型既无显式路由、也无账号映射/候选池可归入具体平台: + // 继续放行只会落到通用网关并按通用协议报错。对 composite 在入口明确 + // 以请求错误拒绝(带模型名与原因),信封按入站 endpoint 协议选择。 writeCompositeRouteAdmissionError(c, http.StatusBadRequest, fmt.Sprintf("Model %q cannot be resolved to any platform in this composite group (%s)", model, decision.Reason)) return } @@ -769,6 +774,14 @@ func openAICompatibleCandidatePlatforms(candidates []string) []string { return out } +// compositeRouteResolutionRequired 报告 composite 未解析的模型是否必须在入口拒绝: +// 文本端点放行后会被 handler 的 detector 折叠成单平台或落到通用网关错发协议。 +func compositeRouteResolutionRequired(path string) bool { + return strings.Contains(path, "/messages") || + strings.Contains(path, "/responses") || + strings.Contains(path, "/chat/completions") +} + func compositeRouteEndpointForPath(path string) string { switch { case strings.Contains(path, "/messages/count_tokens"): diff --git a/backend/internal/server/routes/gateway_composite_pool_test.go b/backend/internal/server/routes/gateway_composite_pool_test.go index 495c38c44c..80b0ab85f8 100644 --- a/backend/internal/server/routes/gateway_composite_pool_test.go +++ b/backend/internal/server/routes/gateway_composite_pool_test.go @@ -39,7 +39,9 @@ func newCompositePoolTestRouter(t *testing.T, terminal gin.HandlerFunc, ownershi resolver := service.NewCompositeRouteResolver(compositeRouteRepoStub{}) resolver.SetModelOwnershipResolver(ownership.ResolveModelOwnership) router.Use(compositeTargetPlatformMiddleware(resolver)) - router.POST("/v1/chat/completions", terminal) + for _, path := range []string{"/v1/chat/completions", "/v1/messages", "/v1/responses", "/v1/contents/generations/tasks"} { + router.POST(path, terminal) + } return router } @@ -82,20 +84,49 @@ func TestCompositeTargetPlatformMiddlewareWritesPoolDecision(t *testing.T) { require.Equal(t, http.StatusNoContent, w.Code) } -// composite 请求的模型无法解析到任何平台时必须显式 400,不能再静默放行到 +// composite 文本端点的模型无法解析到任何平台时必须显式 400,不能再静默放行到 // 通用网关按通用协议报错。 func TestCompositeTargetPlatformMiddlewareRejectsUnresolvedModel(t *testing.T) { + for _, path := range []string{"/v1/chat/completions", "/v1/messages", "/v1/responses"} { + t.Run(path, func(t *testing.T) { + router := newCompositePoolTestRouter(t, func(c *gin.Context) { + t.Fatal("unresolvable composite model must not reach any handler") + }, compositePoolOwnershipStub{}, service.PlatformComposite) + + req := httptest.NewRequest(http.MethodPost, path, strings.NewReader(`{"model":"totally-unknown-alias"}`)) + req.Header.Set("Content-Type", "application/json") + w := httptest.NewRecorder() + router.ServeHTTP(w, req) + + require.Equal(t, http.StatusBadRequest, w.Code) + require.Contains(t, w.Body.String(), "totally-unknown-alias") + }) + } +} + +// 非文本端点(Seedance 任务等)由 handler 按自身平台语义处理:未解析的模型照常放行, +// 不写目标平台/候选池、body 原样保留。 +func TestCompositeTargetPlatformMiddlewarePassesUnresolvedModelOnNonTextEndpoints(t *testing.T) { + const body = `{"model":"doubao-seedance-2-0","content":[{"type":"text","text":"cat"}]}` + seen := false router := newCompositePoolTestRouter(t, func(c *gin.Context) { - t.Fatal("unresolvable composite model must not reach any handler") + seen = true + _, resolved := service.ResolvedTargetPlatformFromContext(c.Request.Context()) + require.False(t, resolved) + require.Empty(t, service.CompositeCandidatePlatformsFromContext(c.Request.Context())) + got, err := io.ReadAll(c.Request.Body) + require.NoError(t, err) + require.JSONEq(t, body, string(got)) + c.Status(http.StatusNoContent) }, compositePoolOwnershipStub{}, service.PlatformComposite) - req := httptest.NewRequest(http.MethodPost, "/v1/chat/completions", strings.NewReader(`{"model":"totally-unknown-alias"}`)) + req := httptest.NewRequest(http.MethodPost, "/v1/contents/generations/tasks", strings.NewReader(body)) req.Header.Set("Content-Type", "application/json") w := httptest.NewRecorder() router.ServeHTTP(w, req) - require.Equal(t, http.StatusBadRequest, w.Code) - require.Contains(t, w.Body.String(), "totally-unknown-alias") + require.True(t, seen) + require.Equal(t, http.StatusNoContent, w.Code) } // 非 composite 分组保持原行为:无模型解析拦截。 From 68de8722877758be4e86568a05f63e6cb36ed75d Mon Sep 17 00:00:00 2001 From: shaw Date: Fri, 9 Oct 2026 17:20:48 +0800 Subject: [PATCH 55/81] =?UTF-8?q?fix(composite):=20generic=20Messages=20?= =?UTF-8?q?=E6=B1=A0=E8=A1=A5=E9=BD=90=20messages=20=E8=B0=83=E5=BA=A6?= =?UTF-8?q?=E5=BC=80=E5=85=B3=E3=80=81=E6=8E=A8=E7=90=86=E5=BC=BA=E5=BA=A6?= =?UTF-8?q?=E4=B8=8E=E9=85=8D=E9=A2=9D=E8=87=AA=E5=8A=A8=E6=9A=82=E5=81=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - allow_messages_dispatch 关闭时整平台屏蔽 openai,与 OpenAI handler 同语义; - 选中 anthropic 账号时按单目标 anthropic 语义应用分组推理强度策略; - 池成员门纳入策略 deny 与 openai/grok 配额自动暂停(注入全局默认阈值), sticky、负载感知与 legacy 取号统一经此门; - 测试调度快照按桶平台返回,与生产单平台桶一致。 --- .../composite_generic_pool_messages_test.go | 52 ++++++++++++++++++- .../internal/handler/composite_platform.go | 12 +++++ ...site_pool_reasoning_policy_generic_test.go | 21 ++++++++ backend/internal/handler/gateway_handler.go | 27 ++++++++++ .../service/composite_generic_pool.go | 21 ++++++++ .../composite_generic_pool_scheduling_test.go | 30 +++++++++++ .../internal/service/gateway_scheduling.go | 6 +++ 7 files changed, 168 insertions(+), 1 deletion(-) diff --git a/backend/internal/handler/composite_generic_pool_messages_test.go b/backend/internal/handler/composite_generic_pool_messages_test.go index 76d067778d..31181971ae 100644 --- a/backend/internal/handler/composite_generic_pool_messages_test.go +++ b/backend/internal/handler/composite_generic_pool_messages_test.go @@ -137,6 +137,22 @@ type compositePoolMessagesHarness struct { usageRepo *compositePoolUsageLogRepo } +// platformScopedSchedulerCache 按桶平台返回快照,与生产调度快照的单平台桶语义一致 +// (池按候选平台逐桶取号,被 deny 的平台整桶跳过)。 +type platformScopedSchedulerCache struct { + fakeSchedulerCache +} + +func (f *platformScopedSchedulerCache) GetSnapshot(_ context.Context, bucket service.SchedulerBucket) ([]*service.Account, bool, error) { + out := make([]*service.Account, 0, len(f.accounts)) + for _, account := range f.accounts { + if account != nil && account.Platform == bucket.Platform { + out = append(out, account) + } + } + return out, true, nil +} + func newCompositePoolMessagesHarness(t *testing.T, accounts []*service.Account) *compositePoolMessagesHarness { t.Helper() gin.SetMode(gin.TestMode) @@ -151,7 +167,7 @@ func newCompositePoolMessagesHarness(t *testing.T, accounts []*service.Account) openAIUpstream := &compositePoolFakeUpstream{} gwUpstream := &compositePoolFakeUpstream{} - schedulerCache := &fakeSchedulerCache{accounts: accounts} + schedulerCache := &platformScopedSchedulerCache{fakeSchedulerCache{accounts: accounts}} schedulerSnapshot := service.NewSchedulerSnapshotService(schedulerCache, nil, nil, nil, nil) billingService := service.NewBillingService(cfg, nil) @@ -488,3 +504,37 @@ func TestCompositePoolMessagesDelegatedUsageExcludesCachedInputTokens(t *testing require.Equal(t, 80, logs[0].CacheReadTokens) require.Equal(t, 7, logs[0].OutputTokens) } + +// 跨族 Messages 池与 OpenAI handler 同语义:分组关闭 allow_messages_dispatch 时 openai +// 账号整平台屏蔽、由其余平台承接;开启时 openai 账号可被委派。 +func TestCompositePoolMessagesRespectsAllowMessagesDispatch(t *testing.T) { + t.Run("disabled masks openai", func(t *testing.T) { + h := newCompositePoolMessagesHarness(t, []*service.Account{ + poolOpenAIAccount(41301, 41011, 0), + poolAnthropicAccount(41302, 41011, 10), + }) + h.gwUpstream.respond = func(compositePoolUpstreamCall, int) *http.Response { + return anthropicMessagesOKResponse() + } + + c, rec := h.newRequest(t, "/v1/messages", poolMessagesBody(), service.PlatformAnthropic, service.PlatformOpenAI) + h.handler.Messages(c) + + require.Equal(t, http.StatusOK, rec.Code) + require.Empty(t, h.openAIUpstream.snapshot(), "开关关闭时 openai 账号不得承接 /v1/messages") + require.Len(t, h.gwUpstream.snapshot(), 1) + }) + + t.Run("enabled delegates openai", func(t *testing.T) { + h := newCompositePoolMessagesHarness(t, []*service.Account{poolOpenAIAccount(41304, 41011, 0)}) + h.group.AllowMessagesDispatch = true + + c, _ := h.newRequest(t, "/v1/messages", poolMessagesBody(), service.PlatformAnthropic, service.PlatformOpenAI) + h.handler.Messages(c) + + calls := h.openAIUpstream.snapshot() + require.NotEmpty(t, calls) + require.Contains(t, calls[0].Authorization, "openai-key") + require.Empty(t, h.gwUpstream.snapshot()) + }) +} diff --git a/backend/internal/handler/composite_platform.go b/backend/internal/handler/composite_platform.go index dd2e4ce03c..6f7c3604fa 100644 --- a/backend/internal/handler/composite_platform.go +++ b/backend/internal/handler/composite_platform.go @@ -256,6 +256,18 @@ func releaseCompositePoolSelection(selection *service.AccountSelectionResult) { } } +// applyCompositePoolAnthropicReasoningEffortPolicy 为 composite 账号池 /v1/messages +// 选中 anthropic 账号的 attempt 补齐分组推理强度策略:池请求准入期有效平台为 +// composite,applyAnthropicReasoningEffortPolicyForRequest 不生效;选中 anthropic +// 账号时与单目标 anthropic 同语义,其余平台由各自转发链处理。 +func applyCompositePoolAnthropicReasoningEffortPolicy(apiKey *service.APIKey, account *service.Account, body []byte) ([]byte, bool, error) { + if apiKey == nil || apiKey.Group == nil || account == nil || account.Platform != service.PlatformAnthropic { + return body, false, nil + } + maxEffort, mappings := anthropicCompatibleReasoningEffortPolicy(apiKey.Group.MaxReasoningEffort, apiKey.Group.ReasoningEffortMappings) + return service.ApplyReasoningEffortPolicy(body, maxEffort, mappings, apiKey.Group.MaxReasoningEffortOverLimit) +} + // applyCompositePoolReasoningEffortPolicyForSelectedAccount 在账号选定后为 // composite 账号池请求补齐组 reasoning-effort 策略(CC/Responses 直转路径: // 服务侧 forward 不再应用组策略)。池请求准入期没有单一目标平台,无法预判 diff --git a/backend/internal/handler/composite_pool_reasoning_policy_generic_test.go b/backend/internal/handler/composite_pool_reasoning_policy_generic_test.go index 44db7df146..e0000dd1aa 100644 --- a/backend/internal/handler/composite_pool_reasoning_policy_generic_test.go +++ b/backend/internal/handler/composite_pool_reasoning_policy_generic_test.go @@ -89,6 +89,7 @@ func TestCompositeCrossFamilyPoolAppliesReasoningEffortCap(t *testing.T) { func TestCompositeCrossFamilyPoolMessagesAppliesReasoningEffortCap(t *testing.T) { h := newCompositePoolMessagesHarness(t, []*service.Account{poolOpenAIAccount(44201, 41011, 0)}) h.group.MaxReasoningEffort = "medium" + h.group.AllowMessagesDispatch = true h.openAIUpstream.respond = func(compositePoolUpstreamCall, int) *http.Response { return openAIResponsesSSEOKResponse("gpt-5.4") } @@ -103,3 +104,23 @@ func TestCompositeCrossFamilyPoolMessagesAppliesReasoningEffortCap(t *testing.T) require.Len(t, calls, 1) require.Equal(t, "medium", gjson.GetBytes(calls[0].Body, "reasoning.effort").String(), "upstream body=%s", calls[0].Body) } + +// 跨族 Messages 池选中 anthropic 账号:准入期有效平台为 composite,组推理强度上限须在 +// attempt 级补齐,与单目标 anthropic 同语义。 +func TestCompositeCrossFamilyPoolMessagesAppliesReasoningEffortCapToAnthropic(t *testing.T) { + h := newCompositePoolMessagesHarness(t, []*service.Account{poolAnthropicAccount(44202, 41011, 0)}) + h.group.MaxReasoningEffort = "medium" + h.gwUpstream.respond = func(compositePoolUpstreamCall, int) *http.Response { + return anthropicMessagesOKResponse() + } + + c, rec := h.newRequest(t, "/v1/messages", + `{"model":"my-model","max_tokens":64,"stream":false,"messages":[{"role":"user","content":"hello"}],"output_config":{"effort":"max"}}`, + service.PlatformAnthropic, service.PlatformKimi) + h.handler.Messages(c) + + require.Equal(t, http.StatusOK, rec.Code, rec.Body.String()) + calls := h.gwUpstream.snapshot() + require.Len(t, calls, 1) + require.Equal(t, "medium", gjson.GetBytes(calls[0].Body, "output_config.effort").String(), "upstream body=%s", calls[0].Body) +} diff --git a/backend/internal/handler/gateway_handler.go b/backend/internal/handler/gateway_handler.go index a5d39586c3..bc827896db 100644 --- a/backend/internal/handler/gateway_handler.go +++ b/backend/internal/handler/gateway_handler.go @@ -647,6 +647,15 @@ func (h *GatewayHandler) Messages(c *gin.Context) { // poolDenials 恒为空、attempt 策略不生效,整条路径零变化。 isPoolRequest := service.GenericCompositePoolActive(c.Request.Context()) poolDenials := newCompositePoolPlatformDenials() + if isPoolRequest && !apiKey.Group.AllowMessagesDispatch { + // 与 OpenAI handler 的 allowOpenAICompatibleMessagesDispatch 同语义:openai 账号承接 + // /v1/messages 受分组开关控制(grok / 多协议供应商豁免),关闭时整平台屏蔽 openai。 + poolDenials.deny(service.PlatformOpenAI) + if _, ok := compositePoolSelectionRetryContext(c.Request.Context(), poolDenials); !ok { + h.errorResponse(c, http.StatusForbidden, "permission_error", "This group does not allow /v1/messages dispatch") + return + } + } // 单账号分组提前设置 SingleAccountRetry 标记,让 Service 层首次 503 就不设模型限流标记。 // 避免单账号分组收到 503 (MODEL_CAPACITY_EXHAUSTED) 时设 29s 限流,导致后续请求连续快速失败。 @@ -785,6 +794,24 @@ func (h *GatewayHandler) Messages(c *gin.Context) { continue } } + // 账号池选中 anthropic 账号:按单目标 anthropic 语义补齐分组推理强度策略(放在槽位获取前)。 + if isPoolRequest { + cappedBody, changed, policyErr := applyCompositePoolAnthropicReasoningEffortPolicy(apiKey, account, attemptParsedReq.Body.Bytes()) + if policyErr != nil { + releaseCompositePoolSelection(selection) + h.gatewayService.ReleaseAccountSession(context.Background(), account, sessionKey) + respondOpenAIReasoningEffortPolicyError(c, policyErr, h.errorResponse) + return + } + if changed { + if err := attemptParsedReq.ReplaceBody(cappedBody); err != nil { + releaseCompositePoolSelection(selection) + h.gatewayService.ReleaseAccountSession(context.Background(), account, sessionKey) + h.errorResponse(c, http.StatusBadRequest, "invalid_request_error", "Failed to apply reasoning effort policy") + return + } + } + } // 检查请求拦截(预热请求、SUGGESTION MODE等) if account.IsInterceptWarmupEnabled() { diff --git a/backend/internal/service/composite_generic_pool.go b/backend/internal/service/composite_generic_pool.go index 9458d0ad40..186c3b6d5a 100644 --- a/backend/internal/service/composite_generic_pool.go +++ b/backend/internal/service/composite_generic_pool.go @@ -35,6 +35,18 @@ func genericCompositePoolAllowsAccount(ctx context.Context, account *Account) bo if account == nil || !genericCompositePoolAccountServable(account) { return false } + // 本次请求被策略 deny 的平台整平台排除(与 OpenAI 族调度门同语义),覆盖 + // 不经 listSchedulableAccountsForCompositePool 取号的 sticky / 路由 / legacy 路径。 + if compositePoolPlatformDenied(ctx, account.Platform) { + return false + } + // 委派 OpenAI 网关链的 openai / grok 账号不经 OpenAI 调度资格门,沿用其配额自动暂停。 + if paused, _ := shouldAutoPauseOpenAIAccountByQuota(ctx, account); paused { + return false + } + if paused, _ := shouldAutoPauseGrokAccountByQuota(account); paused { + return false + } for _, platform := range CompositeCandidatePlatformsFromContext(ctx) { if platform == account.Platform { return true @@ -43,6 +55,15 @@ func genericCompositePoolAllowsAccount(ctx context.Context, account *Account) bo return false } +// withCompositePoolQuotaAutoPauseContext 为 generic 账号池选号注入 OpenAI 配额自动暂停 +// 的全局默认阈值(与 OpenAI 调度器同源,SettingService 内存缓存,不读库)。 +func (s *GatewayService) withCompositePoolQuotaAutoPauseContext(ctx context.Context) context.Context { + if s == nil || s.settingService == nil || !GenericCompositePoolActive(ctx) { + return ctx + } + return withOpenAIQuotaAutoPauseSettings(ctx, s.settingService.GetOpenAIQuotaAutoPauseSettings(ctx)) +} + // genericCompositePoolAccountServable 报告账号能否被 generic messages 路径服务。 // 纯能力判定,不依赖候选池: // - PlatformAnthropic:generic 网关原生账号(OAuth/APIKey/ServiceAccount); diff --git a/backend/internal/service/composite_generic_pool_scheduling_test.go b/backend/internal/service/composite_generic_pool_scheduling_test.go index 451089556f..f4699ed664 100644 --- a/backend/internal/service/composite_generic_pool_scheduling_test.go +++ b/backend/internal/service/composite_generic_pool_scheduling_test.go @@ -379,6 +379,33 @@ func TestGenericCompositePool_LoadAwareSelectsAcrossPlatforms(t *testing.T) { require.EqualValues(t, 44402, selection.Account.ID) } +// ---- e1. 委派 OpenAI 链的账号沿用配额自动暂停 ---- + +func TestGenericCompositePool_SkipsQuotaAutoPausedOpenAIAccount(t *testing.T) { + groupID := int64(41007) + group := newGenericPoolTestGroup(groupID) + model := "my-model" + ctx := genericPoolTestContext([]string{PlatformAnthropic, PlatformOpenAI}) + + build := func(usedPercent float64) *GatewayService { + openai := genericPoolTestAccount(44601, PlatformOpenAI, groupID, 0, + map[string]any{"model_mapping": map[string]any{"my-model": "gpt-5.4"}}, + map[string]any{"codex_5h_used_percent": usedPercent, "auto_pause_5h_threshold": 0.95}) + anthropic := genericPoolTestAccount(44602, PlatformAnthropic, groupID, 5, + map[string]any{"model_mapping": map[string]any{"my-model": "claude-sonnet-4-5"}}, nil) + svc, _ := newGenericPoolTestService([]Account{openai, anthropic}, group, &compositePoolTestCache{}, nil) + return svc + } + + selected, err := build(50).SelectAccountForModelWithExclusions(ctx, &groupID, "", model, nil) + require.NoError(t, err) + require.EqualValues(t, 44601, selected.ID, "未达阈值时 openai 按 priority 获胜") + + selected, err = build(95).SelectAccountForModelWithExclusions(ctx, &groupID, "", model, nil) + require.NoError(t, err) + require.EqualValues(t, 44602, selected.ID, "达到自动暂停阈值的 openai 账号不得被池选中") +} + // ---- e2. 显式 resolved 平台 pin 优先于池(单平台旧行为保持) ---- func TestGenericCompositePool_ResolvedPlatformPinBeatsPool(t *testing.T) { @@ -438,6 +465,9 @@ func TestCompositeGenericPoolPredicates(t *testing.T) { require.True(t, genericCompositePoolAllowsAccount(poolCtx, &openai)) require.False(t, genericCompositePoolAllowsAccount(poolCtx, &gemini), "gemini 不在候选池") require.False(t, genericCompositePoolAllowsAccount(context.Background(), &kimiAdaptive), "无池恒 false") + deniedCtx := WithCompositePoolDeniedPlatforms(poolCtx, []string{PlatformOpenAI}) + require.False(t, genericCompositePoolAllowsAccount(deniedCtx, &openai), "被 deny 的平台整平台排除(含 sticky 复检)") + require.True(t, genericCompositePoolAllowsAccount(deniedCtx, &anthropicNative)) // countable:anthropic 原生 / anthropic-协议 / adaptive / gemini / antigravity // 可计数;纯 OpenAI 族(chat_completions 国产 / openai)不算。 diff --git a/backend/internal/service/gateway_scheduling.go b/backend/internal/service/gateway_scheduling.go index ffac8d530a..784014c029 100644 --- a/backend/internal/service/gateway_scheduling.go +++ b/backend/internal/service/gateway_scheduling.go @@ -74,6 +74,7 @@ func (s *GatewayService) SelectAccountForModelWithExclusions(ctx context.Context platform = PlatformAnthropic } ctx = s.withGatewayProfitControlGate(ctx, groupID) + ctx = s.withCompositePoolQuotaAutoPauseContext(ctx) // Claude Code 限制可能已将 groupID 解析为 fallback group, // 渠道限制预检查必须使用解析后的分组。 @@ -127,6 +128,7 @@ func (s *GatewayService) SelectAccountWithLoadAwareness(ctx context.Context, gro } ctx = s.withGroupContext(ctx, group) ctx = s.withGatewayProfitControlGate(ctx, groupID) + ctx = s.withCompositePoolQuotaAutoPauseContext(ctx) // Claude Code 限制可能已将 groupID 解析为 fallback group, // 渠道限制预检查必须使用解析后的分组。 @@ -1162,6 +1164,10 @@ func (s *GatewayService) listSchedulableAccountsForCompositePool(ctx context.Con if _, duplicate := seen[bucket[i].ID]; duplicate { continue } + // 与 sticky / 负载感知路径同一池成员门;legacy 选号循环不逐账号复检池成员资格,在取号时统一过滤。 + if !genericCompositePoolAllowsAccount(ctx, &bucket[i]) { + continue + } seen[bucket[i].ID] = struct{}{} merged = append(merged, bucket[i]) } From 7a79afd06b8df7e26d616b62bc30434e10ad352b Mon Sep 17 00:00:00 2001 From: shaw Date: Fri, 9 Oct 2026 17:20:49 +0800 Subject: [PATCH 56/81] =?UTF-8?q?fix(frontend):=20Ollama=20Cloud=20?= =?UTF-8?q?=E7=BC=96=E8=BE=91=E5=BC=B9=E7=AA=97=E6=94=AF=E6=8C=81=E6=9C=88?= =?UTF-8?q?=E5=BA=A6=E4=BF=A1=E7=94=A8=E9=A2=9D=E5=BA=A6=EF=BC=8C=E9=9D=9E?= =?UTF-8?q?=E6=B3=95=E9=A2=9D=E5=BA=A6=E6=8B=92=E7=BB=9D=E6=8F=90=E4=BA=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 编辑弹窗缺少 monthly_credit_usd 输入,credits 账号建后无法修改额度;新建时 非法额度被静默丢弃。credits 模式编辑可改额度、legacy 模式移除该字段,两处 均校验正数。 --- .../components/account/CreateAccountModal.vue | 9 ++-- .../components/account/EditAccountModal.vue | 35 +++++++++++++ .../__tests__/CreateAccountModal.spec.ts | 13 +++++ .../__tests__/EditAccountModal.spec.ts | 49 +++++++++++++++++++ .../components/account/credentialsBuilder.ts | 6 +++ .../src/i18n/locales/en/admin/accounts.ts | 3 +- .../src/i18n/locales/zh/admin/accounts.ts | 3 +- 7 files changed, 113 insertions(+), 5 deletions(-) diff --git a/frontend/src/components/account/CreateAccountModal.vue b/frontend/src/components/account/CreateAccountModal.vue index 55c9035363..b900bc1975 100644 --- a/frontend/src/components/account/CreateAccountModal.vue +++ b/frontend/src/components/account/CreateAccountModal.vue @@ -4123,6 +4123,7 @@ import { isCNProviderPlatform, isHeaderOverrideCapable, isMultiProtocolApiKeyPlatform, + parseOllamaMonthlyCreditUsd, providerAccountModes, providerModeLabel, providerNativeProtocols, @@ -6037,10 +6038,12 @@ const handleSubmit = async () => { credentials.account_mode = currentOpenCodeOrCNMode() if (form.platform === 'ollama_cloud' && ollamaAccountMode.value === 'ollama_credits') { // Ollama Cloud credits 模式需同时录入月度信用额度(USD)作为分母。 - const monthlyCreditUsd = Number.parseFloat(ollamaMonthlyCreditUsdInput.value) - if (Number.isFinite(monthlyCreditUsd) && monthlyCreditUsd > 0) { - credentials.monthly_credit_usd = monthlyCreditUsd + const monthlyCreditUsd = parseOllamaMonthlyCreditUsd(ollamaMonthlyCreditUsdInput.value) + if (monthlyCreditUsd === null) { + appStore.showError(t('admin.accounts.ollamaCloud.accountMode.monthlyCreditUsdInvalid')) + return } + credentials.monthly_credit_usd = monthlyCreditUsd } credentials.api_protocol = apiProtocol.value if (apiProtocol.value === 'adaptive') { diff --git a/frontend/src/components/account/EditAccountModal.vue b/frontend/src/components/account/EditAccountModal.vue index 949ac2386b..0d757f98e0 100644 --- a/frontend/src/components/account/EditAccountModal.vue +++ b/frontend/src/components/account/EditAccountModal.vue @@ -148,6 +148,19 @@ + +
+ + +
@@ -3174,6 +3187,7 @@ import { defaultOpenCodeProtocolRules, defaultProviderProtocolRules, isMultiProtocolApiKeyPlatform, + parseOllamaMonthlyCreditUsd, parseOpenCodeGoProtocolRules, providerAccountModes, providerModeLabel, @@ -3396,6 +3410,11 @@ const isGenericMultiProtocolAccount = computed( props.account?.platform !== 'opencode_go' ) const genericAccountModes = computed(() => providerAccountModes(props.account?.platform ?? '')) +// Ollama Cloud credits 模式的月度信用额度(USD)输入;仅 credits 模式写入凭据。 +const editOllamaMonthlyCreditUsd = ref('60') +const isOllamaCreditsAccount = computed( + () => isGenericMultiProtocolAccount.value && props.account?.platform === 'ollama_cloud' && editAccountMode.value === 'ollama_credits' +) // CnBaseUrlPresets 的 platform prop 是平台字面量联合类型,模板里不能写 // `as` 断言(其中的 `|` 会被 eslint 误判为 Vue2 filter 语法),经此 computed 传递。 const cnPresetPlatform = computed(() => { @@ -4421,6 +4440,10 @@ const syncFormFromAccount = (newAccount: Account | null) => { } else { editAccountMode.value = resolveProviderAccountMode(newAccount.platform, credentials.account_mode) } + if (newAccount.platform === 'ollama_cloud') { + const storedCredit = Number(credentials.monthly_credit_usd) + editOllamaMonthlyCreditUsd.value = Number.isFinite(storedCredit) && storedCredit > 0 ? String(storedCredit) : '60' + } const storedProtocol = credentials.api_protocol editApiProtocol.value = storedProtocol === 'adaptive' || @@ -5180,6 +5203,14 @@ const handleSubmit = async () => { } } + const ollamaMonthlyCreditUsd = isOllamaCreditsAccount.value + ? parseOllamaMonthlyCreditUsd(editOllamaMonthlyCreditUsd.value) + : null + if (isOllamaCreditsAccount.value && ollamaMonthlyCreditUsd === null) { + appStore.showError(t('admin.accounts.ollamaCloud.accountMode.monthlyCreditUsdInvalid')) + return + } + const updatePayload: Record = { ...form } try { // 后端期望 proxy_id: 0 表示清除代理,而不是 null @@ -5218,6 +5249,10 @@ const handleSubmit = async () => { // 国产供应商:模式与协议写入凭据(决定额度/余额探测与转发端点/格式)。 if (isCNApiKeyAccount.value) { newCredentials.account_mode = currentOpenCodeOrCNMode() + if (props.account.platform === 'ollama_cloud') { + if (ollamaMonthlyCreditUsd !== null) newCredentials.monthly_credit_usd = ollamaMonthlyCreditUsd + else delete newCredentials.monthly_credit_usd + } newCredentials.api_protocol = editApiProtocol.value if (editApiProtocol.value === 'adaptive') { const defaults = defaultCNAdaptiveBaseUrls(adaptivePresetPlatform.value, currentOpenCodeOrCNMode()) diff --git a/frontend/src/components/account/__tests__/CreateAccountModal.spec.ts b/frontend/src/components/account/__tests__/CreateAccountModal.spec.ts index 01e5e0d861..4460809d91 100644 --- a/frontend/src/components/account/__tests__/CreateAccountModal.spec.ts +++ b/frontend/src/components/account/__tests__/CreateAccountModal.spec.ts @@ -981,6 +981,19 @@ describe('CreateAccountModal Ollama Cloud protocol and quota mode', () => { }) }) + it('rejects ollama_credits mode without a positive monthly credit', async () => { + const wrapper = mountModal() + await selectOllamaCloudPlatform(wrapper) + await selectButtonByText(wrapper, 'admin.accounts.ollamaCloud.accountMode.credits') + await wrapper.get('[data-testid="ollama-monthly-credit-usd"]').setValue('0') + await wrapper.get('form#create-account-form input[type="text"]').setValue('ollama credits') + await wrapper.get('form#create-account-form input[type="password"]').setValue('sk-ollama') + await wrapper.get('form#create-account-form').trigger('submit.prevent') + await flushPromises() + + expect(createAccountMock).not.toHaveBeenCalled() + }) + it('applies the 300 USD quick preset to the monthly credit input', async () => { const wrapper = mountModal() await selectOllamaCloudPlatform(wrapper) diff --git a/frontend/src/components/account/__tests__/EditAccountModal.spec.ts b/frontend/src/components/account/__tests__/EditAccountModal.spec.ts index 2281bacd4d..b1a3836efa 100644 --- a/frontend/src/components/account/__tests__/EditAccountModal.spec.ts +++ b/frontend/src/components/account/__tests__/EditAccountModal.spec.ts @@ -516,6 +516,55 @@ describe('EditAccountModal', () => { }) }) + it('edits the Ollama Cloud monthly credit in credits mode', async () => { + const account = buildAccount() + account.platform = 'ollama_cloud' + account.credentials = { + api_key: 'sk-ollama', + account_mode: 'ollama_credits', + api_protocol: 'chat_completions', + base_url: 'https://ollama.com/v1', + monthly_credit_usd: 60 + } + updateAccountMock.mockReset().mockResolvedValue(account) + checkMixedChannelRiskMock.mockReset().mockResolvedValue({ has_risk: false }) + + const wrapper = mountModal(account) + const input = wrapper.get('[data-testid="edit-ollama-monthly-credit-usd"]') + expect((input.element as HTMLInputElement).value).toBe('60') + await input.setValue('300') + await wrapper.get('form#edit-account-form').trigger('submit.prevent') + + expect(updateAccountMock).toHaveBeenCalledTimes(1) + expect(updateAccountMock.mock.calls[0]?.[1]?.credentials).toMatchObject({ + account_mode: 'ollama_credits', + monthly_credit_usd: 300 + }) + }) + + it('drops the Ollama Cloud monthly credit in legacy mode', async () => { + const account = buildAccount() + account.platform = 'ollama_cloud' + account.credentials = { + api_key: 'sk-ollama', + account_mode: 'ollama_legacy', + api_protocol: 'chat_completions', + base_url: 'https://ollama.com/v1', + monthly_credit_usd: 60 + } + updateAccountMock.mockReset().mockResolvedValue(account) + checkMixedChannelRiskMock.mockReset().mockResolvedValue({ has_risk: false }) + + const wrapper = mountModal(account) + expect(wrapper.find('[data-testid="edit-ollama-monthly-credit-usd"]').exists()).toBe(false) + await wrapper.get('form#edit-account-form').trigger('submit.prevent') + + expect(updateAccountMock).toHaveBeenCalledTimes(1) + const credentials = updateAccountMock.mock.calls[0]?.[1]?.credentials + expect(credentials).toMatchObject({ account_mode: 'ollama_legacy' }) + expect('monthly_credit_usd' in credentials).toBe(false) + }) + it('treats a legacy OpenCode account without account_mode as GO', async () => { const account = buildAccount() account.platform = 'opencode_go' diff --git a/frontend/src/components/account/credentialsBuilder.ts b/frontend/src/components/account/credentialsBuilder.ts index 7f5bb515c8..a0dfbf8dc6 100644 --- a/frontend/src/components/account/credentialsBuilder.ts +++ b/frontend/src/components/account/credentialsBuilder.ts @@ -6,6 +6,12 @@ import { type ProviderProtocolRule } from '@/constants/platformCatalog' +/** Ollama Cloud credits 模式的月度信用额度(USD):仅接受正有限数,否则返回 null。 */ +export function parseOllamaMonthlyCreditUsd(input: string): number | null { + const value = Number.parseFloat(input) + return Number.isFinite(value) && value > 0 ? value : null +} + export function applyInterceptWarmup( credentials: Record, enabled: boolean, diff --git a/frontend/src/i18n/locales/en/admin/accounts.ts b/frontend/src/i18n/locales/en/admin/accounts.ts index df99b01bbd..78bc09cd2d 100644 --- a/frontend/src/i18n/locales/en/admin/accounts.ts +++ b/frontend/src/i18n/locales/en/admin/accounts.ts @@ -298,7 +298,8 @@ export default { credits: 'Credits (monthly pool)', creditsDesc: 'Metered and monitored via a monthly USD credit pool', monthlyCreditUsd: 'Monthly credit (USD)', - monthlyCreditUsdPlaceholder: 'e.g. 60' + monthlyCreditUsdPlaceholder: 'e.g. 60', + monthlyCreditUsdInvalid: 'Monthly credit must be a positive number' }, sessionSecurityHint: 'The browser session is encrypted at rest and sent only to the fixed official settings URL.', configured: 'Configured', diff --git a/frontend/src/i18n/locales/zh/admin/accounts.ts b/frontend/src/i18n/locales/zh/admin/accounts.ts index e2a04fedfb..4b60dc124a 100644 --- a/frontend/src/i18n/locales/zh/admin/accounts.ts +++ b/frontend/src/i18n/locales/zh/admin/accounts.ts @@ -143,7 +143,8 @@ export default { credits: 'Credits(月度信用池)', creditsDesc: '按月度美元信用额度计费与监控', monthlyCreditUsd: '月度信用额度(USD)', - monthlyCreditUsdPlaceholder: '例如 60' + monthlyCreditUsdPlaceholder: '例如 60', + monthlyCreditUsdInvalid: '月度信用额度须为正数' }, sessionSecurityHint: '浏览器会话会加密落库,且只发送到固定的 Ollama 官方设置页。', configured: '已配置', From cc6be11f1705cdddd9b7133957736f90d2f5f6f9 Mon Sep 17 00:00:00 2001 From: shaw Date: Sat, 10 Oct 2026 10:50:24 +0800 Subject: [PATCH 57/81] =?UTF-8?q?fix(billing):=20=E6=A8=A1=E7=B3=8A?= =?UTF-8?q?=E6=9F=A5=E4=BB=B7=E8=B7=B3=E8=BF=87=E7=A9=BA=E5=9F=BA=E5=90=8D?= =?UTF-8?q?=EF=BC=8C=E4=BF=AE=E5=A4=8D=20qwen3.5:397b/gemma4:31b=20?= =?UTF-8?q?=E8=90=BD=20$0=20=E4=BB=B7=E5=8D=A1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit extractBaseName 会丢弃含 ":" 的片段,整段带 tag 的模型名(qwen3.5:397b、 gemma4:31b)基名为空串,与 LiteLLM 目录里 ollama/llama2:13b 等同样剥光的 $0 条目相等,按 map 遍历顺序随机命中;动态目录命中即短路 fallbackPrices, ollama 专属价卡成为死代码,保存期门禁与请求期预检均放行。 --- ...lama_cloud_dynamic_catalog_pricing_test.go | 36 +++++++++++++++++++ backend/internal/service/pricing_service.go | 6 ++++ 2 files changed, 42 insertions(+) diff --git a/backend/internal/service/ollama_cloud_dynamic_catalog_pricing_test.go b/backend/internal/service/ollama_cloud_dynamic_catalog_pricing_test.go index 8fd32044eb..a28b543ffd 100644 --- a/backend/internal/service/ollama_cloud_dynamic_catalog_pricing_test.go +++ b/backend/internal/service/ollama_cloud_dynamic_catalog_pricing_test.go @@ -25,6 +25,7 @@ package service import ( "testing" + "github.com/Wei-Shaw/sub2api/internal/config" "github.com/stretchr/testify/require" ) @@ -176,3 +177,38 @@ func TestGetModelPricing_TaggedNamesNeverGuessedFromStrippedName(t *testing.T) { _, err = bs.getModelPricingAt("gpt-oss-120b-medium", ollamaPricingAt) require.NoError(t, err) } + +// TestGetModelPricing_OllamaCloudTaggedModelsIgnoreEmptyBaseNameCatalogEntries 回归: +// "qwen3.5:397b" / "gemma4:31b" 整段带 ":",extractBaseName 剥光后基名为空串;真实 +// LiteLLM 目录里 "ollama/llama2:13b"($0)、"openrouter/openai/o3:batch" 等条目的基名 +// 同样为空。模糊匹配不得让空基名互相命中,否则这两个模型按 map 遍历顺序随机落到 +// $0 等错误价卡,fallbackPrices 的 ollama 价卡成为死代码。 +func TestGetModelPricing_OllamaCloudTaggedModelsIgnoreEmptyBaseNameCatalogEntries(t *testing.T) { + catalog := `{ + "ollama/llama2:13b": {"input_cost_per_token": 0.0, "output_cost_per_token": 0.0, "litellm_provider": "ollama", "mode": "chat"}, + "ollama/llama3:8b": {"input_cost_per_token": 0.0, "output_cost_per_token": 0.0, "litellm_provider": "ollama", "mode": "chat"}, + "openrouter/thinkingmachines/inkling:free": {"input_cost_per_token": 0.0, "output_cost_per_token": 0.0, "litellm_provider": "openrouter", "mode": "chat"}, + "openrouter/openai/o3:batch": {"input_cost_per_token": 1e-06, "output_cost_per_token": 4e-06, "litellm_provider": "openrouter", "mode": "chat"} + }` + bs := NewBillingService(&config.Config{}, newStubPricingServiceFromJSON(t, catalog)) + + tests := []struct { + model string + wantInput float64 + wantOut float64 + }{ + {"qwen3.5:397b", 0.60e-6, 3.60e-6}, + {"gemma4:31b", 0.14e-6, 0.40e-6}, + } + for _, tt := range tests { + t.Run(tt.model, func(t *testing.T) { + require.Nil(t, bs.pricingService.GetModelPricing(tt.model), + "model %s must not fuzzy-match catalog entries whose base name is also empty", tt.model) + pricing, err := bs.getModelPricingAt(tt.model, ollamaPricingAt) + require.NoError(t, err) + require.NotNil(t, pricing) + require.InDelta(t, tt.wantInput, pricing.InputPricePerToken, 1e-12) + require.InDelta(t, tt.wantOut, pricing.OutputPricePerToken, 1e-12) + }) + } +} diff --git a/backend/internal/service/pricing_service.go b/backend/internal/service/pricing_service.go index 84bbe8d98f..bdae9483f7 100644 --- a/backend/internal/service/pricing_service.go +++ b/backend/internal/service/pricing_service.go @@ -1260,7 +1260,13 @@ func (s *PricingService) lookupIdentifiedModelPricingLocked(lookupCandidates []s // 3. 尝试模糊匹配(去掉版本号后缀) // claude-opus-4-5-20251101 -> claude-opus-4.5 + // 基名为空(如 "qwen3.5:397b" 整段带 ":" 被剥光)时不做模糊匹配:空基名会与 + // 价格表里所有同样剥光的条目("ollama/llama2:13b" 等 $0 价)相等,按 map 遍历 + // 顺序随机命中。 baseName := s.extractBaseName(lookupCandidates[0]) + if baseName == "" { + return nil + } for key, pricing := range s.pricingData { keyBase := s.extractBaseName(strings.ToLower(key)) if keyBase == baseName { From ed8d6fb297e783f8c3ce2ab16fff5459f07228d8 Mon Sep 17 00:00:00 2001 From: shaw Date: Sat, 10 Oct 2026 10:58:08 +0800 Subject: [PATCH 58/81] =?UTF-8?q?fix(composite):=20=E8=B4=A6=E5=8F=B7?= =?UTF-8?q?=E6=B1=A0=E5=A7=94=E6=B4=BE=20OpenAI=20=E7=BD=91=E5=85=B3?= =?UTF-8?q?=E9=93=BE=E8=A1=A5=E9=BD=90=20cyber=20=E4=BC=9A=E8=AF=9D?= =?UTF-8?q?=E5=B0=81=E7=A6=81=E4=B8=8E=E4=BA=8B=E5=90=8E=E8=AE=B0=E5=BD=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit generic Messages/Responses/CC 三个入口在跨族账号池中直接调用 OpenAI 网关服务 转发 openai 族账号,却没有 OpenAI handler 的 cyber 处理:已封禁会话照常外发, 新命中 cyber_policy 时不封会话、不记风控事件、出错轮次不计费。 - 池请求选号前按 OpenAI handler 同语义拒绝已封禁会话(按入站端点错误格式); - 委派 attempt 返回后 recordCyberPolicyIfMarked,委派入账带 CyberBlocked; - 委派 attempt 的错误告知判定改用 OpenAI 链口径,流式 response.failed / cyber 原始错误体已透传时不再追加终止错误帧。 --- backend/cmd/server/wire_gen.go | 2 +- .../composite_generic_pool_messages_test.go | 6 +- .../handler/composite_pool_attempt_policy.go | 31 ++++++++++ .../composite_pool_delegated_cyber_test.go | 58 +++++++++++++++++++ backend/internal/handler/gateway_handler.go | 13 ++++- .../gateway_handler_chat_completions.go | 10 +++- .../handler/gateway_handler_responses.go | 10 +++- backend/internal/handler/wire.go | 2 + 8 files changed, 126 insertions(+), 6 deletions(-) create mode 100644 backend/internal/handler/composite_pool_delegated_cyber_test.go diff --git a/backend/cmd/server/wire_gen.go b/backend/cmd/server/wire_gen.go index 04d029aeee..6771a37ef5 100644 --- a/backend/cmd/server/wire_gen.go +++ b/backend/cmd/server/wire_gen.go @@ -296,8 +296,8 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) { userMessageQueueService := service.ProvideUserMessageQueueService(userMsgQueueCache, rpmCache, configConfig) legacyEngine := securityaudit.NewLegacyModerationAdapter(contentModerationService) coordinator := securityaudit.NewCoordinator(legacyEngine, promptService) - gatewayHandler := handler.ProvideGatewayHandler(gatewayService, openAIGatewayService, geminiMessagesCompatService, antigravityGatewayService, userService, concurrencyService, billingCacheService, usageService, apiKeyService, usageRecordWorkerPool, errorPassthroughService, contentModerationService, userMessageQueueService, configConfig, settingService, coordinator) openAIGatewayHandler := handler.ProvideOpenAIGatewayHandler(openAIGatewayService, pluginManager, concurrencyService, billingCacheService, apiKeyService, usageRecordWorkerPool, errorPassthroughService, contentModerationService, opsService, grokQuotaService, configConfig, coordinator, compositeRouteResolver) + gatewayHandler := handler.ProvideGatewayHandler(gatewayService, openAIGatewayService, geminiMessagesCompatService, antigravityGatewayService, userService, concurrencyService, billingCacheService, usageService, apiKeyService, usageRecordWorkerPool, errorPassthroughService, contentModerationService, userMessageQueueService, configConfig, settingService, coordinator, openAIGatewayHandler) handlerSettingHandler := handler.ProvideSettingHandler(settingService, buildInfo, notificationEmailService) totpHandler := handler.NewTotpHandler(totpService) passkeyRepository := repository.NewPasskeyRepository(db) diff --git a/backend/internal/handler/composite_generic_pool_messages_test.go b/backend/internal/handler/composite_generic_pool_messages_test.go index 31181971ae..411148a371 100644 --- a/backend/internal/handler/composite_generic_pool_messages_test.go +++ b/backend/internal/handler/composite_generic_pool_messages_test.go @@ -194,8 +194,9 @@ func newCompositePoolMessagesHarness(t *testing.T, accounts []*service.Account) nil, nil, billingService, nil, nil, - openAIUpstream, // httpUpstream:委派链假上游 - nil, nil, nil, nil, nil, nil, nil, nil, + openAIUpstream, // httpUpstream:委派链假上游 + service.NewDeferredService(nil, nil, 0), // deferredService:SIMPLE 模式入账后登记 last_used + nil, nil, nil, nil, nil, nil, nil, ) billingCacheService := service.NewBillingCacheService(nil, nil, nil, nil, nil, nil, cfg, nil) @@ -208,6 +209,7 @@ func newCompositePoolMessagesHarness(t *testing.T, accounts []*service.Account) concurrencyHelper: NewConcurrencyHelper(service.NewConcurrencyService(&fakeConcurrencyCache{}), SSEPingFormatClaude, 0), maxAccountSwitches: 3, cfg: cfg, + openAIHandler: &OpenAIGatewayHandler{gatewayService: openAIGatewayService}, } return &compositePoolMessagesHarness{ handler: handler, diff --git a/backend/internal/handler/composite_pool_attempt_policy.go b/backend/internal/handler/composite_pool_attempt_policy.go index 73fd70b6c3..290489e1d5 100644 --- a/backend/internal/handler/composite_pool_attempt_policy.go +++ b/backend/internal/handler/composite_pool_attempt_policy.go @@ -334,6 +334,36 @@ type delegatedOpenAIUsage struct { LogComponent string } +// rejectCompositePoolCyberSessionBlocked 在账号池选号前按 OpenAI handler 同语义拒绝 +// 已被 cyber 封禁的会话:池可能委派 OpenAI 网关链,封禁正是为了阻止该会话继续 +// 发往 OpenAI 上游。返回 true 表示已写出 403。非池请求不调用,路径零变化。 +func (h *GatewayHandler) rejectCompositePoolCyberSessionBlocked(c *gin.Context, apiKey *service.APIKey, body []byte, model string, format cyberSessionBlockFormat) bool { + if h == nil || h.openAIHandler == nil { + return false + } + return h.openAIHandler.rejectIfCyberSessionBlocked(c, apiKey, body, model, format) +} + +// recordDelegatedCyberPolicyIfMarked 在池委派 OpenAI 网关链的 attempt 返回后做 cyber +// 事后记录(会话封禁、风控事件、forward 出错时的用量行),与 OpenAI handler 各入口 +// forward 之后的 recordCyberPolicyIfMarked 同口径。无 cyber 标记时为空操作。 +func (h *GatewayHandler) recordDelegatedCyberPolicyIfMarked(c *gin.Context, apiKey *service.APIKey, account *service.Account, subscription *service.UserSubscription, model string, forwardErrored bool, body []byte, channelFields service.ChannelUsageFields) { + if h == nil || h.openAIHandler == nil || service.GetOpsCyberPolicy(c) == nil { + return + } + h.openAIHandler.recordCyberPolicyIfMarked(c, apiKey, account, subscription, model, forwardErrored, body, channelFields, service.HashUsageRequestPayload(body)) +} + +// compositePoolDelegatedForwardErrorAlreadyCommunicated 按 attempt 实际走的转发链判定 +// 错误是否已告知客户端:委派 OpenAI 网关链时用该链的判定(上游 response.failed / +// cyber 原始错误体已透传),避免 generic 判定把流式响应当作未告知再追加错误帧。 +func compositePoolDelegatedForwardErrorAlreadyCommunicated(c *gin.Context, delegated bool, writerSizeBeforeForward int, err error) bool { + if delegated { + return openAIForwardErrorAlreadyCommunicated(c, writerSizeBeforeForward, err) + } + return gatewayForwardErrorAlreadyCommunicated(c, writerSizeBeforeForward, err) +} + // submitDelegatedOpenAIUsage 用 OpenAI 网关计费链记录池委派结果:委派链产出的是 // OpenAI 口径 usage(input_tokens 含缓存读取、BillingModel、生图/搜索附加计费等), // 必须与该账号在 OpenAI 网关上被直接服务时同一口径入账。转成 ForwardResult 走 @@ -360,6 +390,7 @@ func (h *GatewayHandler) submitDelegatedOpenAIUsage(c *gin.Context, in delegated QuotaPlatform: in.QuotaPlatform, PricingAt: in.PricingAt, ChannelUsageFields: in.ChannelUsageFields, + CyberBlocked: service.GetOpsCyberPolicy(c) != nil, } task := func(ctx context.Context) { if err := h.openAIGatewayService.RecordUsage(ctx, input); err != nil { diff --git a/backend/internal/handler/composite_pool_delegated_cyber_test.go b/backend/internal/handler/composite_pool_delegated_cyber_test.go new file mode 100644 index 0000000000..72b7fafbed --- /dev/null +++ b/backend/internal/handler/composite_pool_delegated_cyber_test.go @@ -0,0 +1,58 @@ +//go:build unit + +package handler + +import ( + "io" + "net/http" + "strings" + "testing" + + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/stretchr/testify/require" +) + +// 跨族池委派 OpenAI 网关链时,上游 cyber_policy 拒绝须与 OpenAI handler 同口径做事后 +// 记录(会话封禁 / 风控事件 / 出错用量行),且透传的上游错误体不再被 generic 兜底 +// 追加错误帧。 +func TestCompositePoolResponsesDelegatedCyberPolicyIsRecorded(t *testing.T) { + h := newCompositePoolMessagesHarness(t, []*service.Account{poolKimiResponsesAccount(41401, 41011, 0)}) + h.openAIUpstream.respond = func(compositePoolUpstreamCall, int) *http.Response { + return &http.Response{ + StatusCode: http.StatusBadRequest, + Header: http.Header{"Content-Type": []string{"application/json"}}, + Body: io.NopCloser(strings.NewReader(`{"error":{"code":"cyber_policy","message":"flagged","type":"invalid_request_error"}}`)), + } + } + + c, rec := h.newRequest(t, "/v1/responses", poolResponsesBody(), service.PlatformAnthropic, service.PlatformKimi) + h.handler.Responses(c) + + require.NotNil(t, service.GetOpsCyberPolicy(c), "委派链必须标记 cyber 命中") + require.True(t, c.GetBool(cyberPolicyRecordedKey), "generic 池委派路径必须执行 cyber 事后记录") + require.Equal(t, http.StatusBadRequest, rec.Code) + require.Equal(t, 1, strings.Count(rec.Body.String(), "cyber_policy"), "上游错误体原样透传一次,不追加兜底错误") +} + +// 委派 OpenAI 网关链的流式 response.failed 已由该链透传给客户端:generic handler 不得 +// 再追加一个终止错误帧(客户端会收到两个终止事件)。 +func TestCompositePoolResponsesDelegatedStreamFailureNotDoubleTerminated(t *testing.T) { + h := newCompositePoolMessagesHarness(t, []*service.Account{poolOpenAIAccount(41402, 41011, 0)}) + h.openAIUpstream.respond = func(compositePoolUpstreamCall, int) *http.Response { + // 先有语义输出再失败:已写出内容后不可 failover,委派链透传 response.failed。 + sse := `data: {"type":"response.output_text.delta","item_id":"msg_1","output_index":0,"content_index":0,"delta":"partial"}` + "\n\n" + + `data: {"type":"response.failed","response":{"id":"resp_pool_failed","object":"response","status":"failed","error":{"code":"server_error","message":"boom"}}}` + "\n\n" + return &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{"text/event-stream"}}, + Body: io.NopCloser(strings.NewReader(sse)), + } + } + + body := `{"model":"my-model","stream":true,"input":"hello"}` + c, rec := h.newRequest(t, "/v1/responses", body, service.PlatformAnthropic, service.PlatformOpenAI) + h.handler.Responses(c) + + require.Equal(t, 1, strings.Count(rec.Body.String(), "response.failed"), + "response.failed 只能出现一次,body=%s", rec.Body.String()) +} diff --git a/backend/internal/handler/gateway_handler.go b/backend/internal/handler/gateway_handler.go index bc827896db..326fed571f 100644 --- a/backend/internal/handler/gateway_handler.go +++ b/backend/internal/handler/gateway_handler.go @@ -58,6 +58,9 @@ type GatewayHandler struct { maxAccountSwitchesGemini int cfg *config.Config settingService *service.SettingService + // openAIHandler 供账号池委派 OpenAI 网关链时复用其 cyber 会话封禁与事后记录 + // (cyber_policy 只在该链标记,见 composite_pool_attempt_policy.go)。 + openAIHandler *OpenAIGatewayHandler } // NewGatewayHandler creates a new GatewayHandler @@ -646,6 +649,9 @@ func (h *GatewayHandler) Messages(c *gin.Context) { // generic 调度器共用同一谓词(ctx 携带候选池且无 resolved 平台);非池请求 // poolDenials 恒为空、attempt 策略不生效,整条路径零变化。 isPoolRequest := service.GenericCompositePoolActive(c.Request.Context()) + if isPoolRequest && h.rejectCompositePoolCyberSessionBlocked(c, apiKey, body, reqModel, cyberBlockFormatAnthropic) { + return + } poolDenials := newCompositePoolPlatformDenials() if isPoolRequest && !apiKey.Group.AllowMessagesDispatch { // 与 OpenAI handler 的 allowOpenAICompatibleMessagesDispatch 同语义:openai 账号承接 @@ -992,6 +998,7 @@ func (h *GatewayHandler) Messages(c *gin.Context) { var result *service.ForwardResult // 池委派 OpenAI 网关链时的原始结果:按 OpenAI 口径入账(见 submitDelegatedOpenAIUsage)。 var delegatedResult *service.OpenAIForwardResult + delegated := false requestCtx := c.Request.Context() if fs.SwitchCount > 0 { requestCtx = service.WithAccountSwitchCount(requestCtx, fs.SwitchCount, h.metadataBridgeEnabled()) @@ -1025,6 +1032,7 @@ func (h *GatewayHandler) Messages(c *gin.Context) { openAIResult, delegateErr := h.openAIGatewayService.ForwardAsAnthropic( requestCtx, c, account, attemptBody, "", strings.TrimSpace(resolveOpenAIMessagesDispatchMappedModel(c, apiKey, reqModel))) + delegated = true delegatedResult = openAIResult result = adaptOpenAIForwardResultToForwardResult(openAIResult) err = delegateErr @@ -1042,6 +1050,9 @@ func (h *GatewayHandler) Messages(c *gin.Context) { if accountReleaseFunc != nil { accountReleaseFunc() } + if delegated { + h.recordDelegatedCyberPolicyIfMarked(c, currentAPIKey, account, currentSubscription, reqModel, err != nil, attemptBody, clientRequestedUsageFields(c, attemptChannelMapping, reqModel, "")) + } // 提交 usage 记录。成功路径与"流中断但 Forward 已观测到 usage 的部分结果" // 错误路径共用:后者若不入账,上游已计量的请求会完全漏记漏计费(#5148)。 @@ -1208,7 +1219,7 @@ func (h *GatewayHandler) Messages(c *gin.Context) { return } } - upstreamErrorAlreadyCommunicated := gatewayForwardErrorAlreadyCommunicated(c, writerSizeBeforeForward, err) + upstreamErrorAlreadyCommunicated := compositePoolDelegatedForwardErrorAlreadyCommunicated(c, delegated, writerSizeBeforeForward, err) wroteFallback := false if !upstreamErrorAlreadyCommunicated { wroteFallback = h.ensureForwardErrorResponse(c, streamStarted) diff --git a/backend/internal/handler/gateway_handler_chat_completions.go b/backend/internal/handler/gateway_handler_chat_completions.go index 7dc9a637ef..8bd65b7765 100644 --- a/backend/internal/handler/gateway_handler_chat_completions.go +++ b/backend/internal/handler/gateway_handler_chat_completions.go @@ -184,6 +184,9 @@ func (h *GatewayHandler) ChatCompletions(c *gin.Context) { // 调度器共用同一谓词(ctx 携带候选池且无 resolved 平台);非池请求 poolDenials // 恒为空、attempt 策略与委派分支不生效,整条路径零变化。 isPoolRequest := service.GenericCompositePoolActive(c.Request.Context()) + if isPoolRequest && h.rejectCompositePoolCyberSessionBlocked(c, apiKey, body, reqModel, cyberBlockFormatChat) { + return + } poolDenials := newCompositePoolPlatformDenials() // 委派 CC 链的 promptCacheKey 语义对齐 OpenAI handler CC 路径(headers → // prompt_cache_key 提取,仅池激活时计算,非池请求不新增解析)。 @@ -366,6 +369,7 @@ func (h *GatewayHandler) ChatCompletions(c *gin.Context) { var result *service.ForwardResult // 池委派 OpenAI 网关链时的原始结果:按 OpenAI 口径入账(见 submitDelegatedOpenAIUsage)。 var delegatedResult *service.OpenAIForwardResult + delegated := false setActualUpstreamEndpoint(c, "") // 池请求的 attempt 局部 ctx 携带选中平台(不写回 c.Request):forward 内的 // 渠道定价作用域与计费 QuotaPlatform 跟随实际平台,对齐 Messages 池 attempt 语义。 @@ -399,6 +403,7 @@ func (h *GatewayHandler) ChatCompletions(c *gin.Context) { // 包装。defaultMappedModel 传 "",与 OpenAI handler CC 路径一致。 openAIResult, delegateErr := h.openAIGatewayService.ForwardAsChatCompletions( attemptCtx, c, account, forwardBody, poolPromptCacheKey, "") + delegated = true delegatedResult = openAIResult result = adaptOpenAIForwardResultToForwardResult(openAIResult) err = delegateErr @@ -409,6 +414,9 @@ func (h *GatewayHandler) ChatCompletions(c *gin.Context) { if accountReleaseFunc != nil { accountReleaseFunc() } + if delegated { + h.recordDelegatedCyberPolicyIfMarked(c, apiKey, account, subscription, reqModel, err != nil, body, clientRequestedUsageFields(c, attemptChannelMapping, reqModel, "")) + } // 池委派 OpenAI 网关链的结果按 OpenAI 口径入账(见 submitDelegatedOpenAIUsage)。 submitDelegatedUsage := func() { @@ -448,7 +456,7 @@ func (h *GatewayHandler) ChatCompletions(c *gin.Context) { return } } - upstreamErrorAlreadyCommunicated := gatewayForwardErrorAlreadyCommunicated(c, writerSizeBeforeForward, err) + upstreamErrorAlreadyCommunicated := compositePoolDelegatedForwardErrorAlreadyCommunicated(c, delegated, writerSizeBeforeForward, err) wroteFallback := false if !upstreamErrorAlreadyCommunicated { wroteFallback = h.ensureForwardErrorResponse(c, streamStarted) diff --git a/backend/internal/handler/gateway_handler_responses.go b/backend/internal/handler/gateway_handler_responses.go index 36ed9e8f29..21cfc1fc29 100644 --- a/backend/internal/handler/gateway_handler_responses.go +++ b/backend/internal/handler/gateway_handler_responses.go @@ -192,6 +192,9 @@ func (h *GatewayHandler) Responses(c *gin.Context) { "previous_response_id is not supported for this composite model; resend the full conversation without previous_response_id") return } + if h.rejectCompositePoolCyberSessionBlocked(c, apiKey, body, reqModel, cyberBlockFormatResponses) { + return + } // 委派 OpenAI 网关链创建的响应须记录下游归属,后续续链经 OpenAI handler 校验租户。 service.SetOpenAIHTTPResponseOwner(c, subject.UserID, apiKey.ID) } @@ -378,6 +381,7 @@ func (h *GatewayHandler) Responses(c *gin.Context) { var result *service.ForwardResult // 池委派 OpenAI 网关链时的原始结果:按 OpenAI 口径入账(见 submitDelegatedOpenAIUsage)。 var delegatedResult *service.OpenAIForwardResult + delegated := false setActualUpstreamEndpoint(c, "") // 池请求的 attempt 局部 ctx 携带选中平台(不写回 requestCtx,否则下一轮 // 选号会被 resolved 平台截断池语义):forward 内的渠道定价作用域与计费 @@ -403,6 +407,7 @@ func (h *GatewayHandler) Responses(c *gin.Context) { // promptCacheKey 由链内从 body 派生(与 OpenAI handler Responses 路径一致)。 setOpenAIClientTransportHTTP(c) openAIResult, delegateErr := h.openAIGatewayService.Forward(attemptCtx, c, account, forwardBody) + delegated = true delegatedResult = openAIResult result = adaptOpenAIForwardResultToForwardResult(openAIResult) err = delegateErr @@ -413,6 +418,9 @@ func (h *GatewayHandler) Responses(c *gin.Context) { if accountReleaseFunc != nil { accountReleaseFunc() } + if delegated { + h.recordDelegatedCyberPolicyIfMarked(c, apiKey, account, subscription, reqModel, err != nil, body, clientRequestedUsageFields(c, attemptChannelMapping, reqModel, "")) + } // 池委派 OpenAI 网关链的结果按 OpenAI 口径入账(见 submitDelegatedOpenAIUsage)。 submitDelegatedUsage := func() { @@ -453,7 +461,7 @@ func (h *GatewayHandler) Responses(c *gin.Context) { return } } - upstreamErrorAlreadyCommunicated := gatewayForwardErrorAlreadyCommunicated(c, writerSizeBeforeForward, err) + upstreamErrorAlreadyCommunicated := compositePoolDelegatedForwardErrorAlreadyCommunicated(c, delegated, writerSizeBeforeForward, err) wroteFallback := false if !upstreamErrorAlreadyCommunicated { wroteFallback = h.ensureForwardErrorResponse(c, streamStarted) diff --git a/backend/internal/handler/wire.go b/backend/internal/handler/wire.go index e87d440c33..1f41d4feba 100644 --- a/backend/internal/handler/wire.go +++ b/backend/internal/handler/wire.go @@ -113,11 +113,13 @@ func ProvideGatewayHandler( cfg *config.Config, settingService *service.SettingService, coordinator *securityaudit.Coordinator, + openAIHandler *OpenAIGatewayHandler, ) *GatewayHandler { h := NewGatewayHandler(gatewayService, openAIGatewayService, geminiCompatService, antigravityGatewayService, userService, concurrencyService, billingCacheService, usageService, apiKeyService, usageRecordWorkerPool, errorPassthroughService, contentModerationService, userMsgQueueService, cfg, settingService) h.securityAuditCoordinator = coordinator + h.openAIHandler = openAIHandler return h } From a0155fee2615f5af1ecdf95e27bb88bba2b8b7e2 Mon Sep 17 00:00:00 2001 From: shaw Date: Sat, 10 Oct 2026 11:01:20 +0800 Subject: [PATCH 59/81] =?UTF-8?q?fix(composite):=20generic=20=E9=93=BE=20A?= =?UTF-8?q?nthropic=20=E5=8D=8F=E8=AE=AE=E7=AB=AF=E7=82=B9=E6=8C=89?= =?UTF-8?q?=E7=89=88=E6=9C=AC=E6=84=9F=E7=9F=A5=E6=8B=BC=E6=8E=A5=EF=BC=8C?= =?UTF-8?q?=E4=BF=AE=E5=A4=8D=20/v1/v1/messages?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 跨族账号池中 ollama_cloud / 按模型分流平台账号经 GatewayService 转发时, anthropicUpstreamTargetURL 朴素拼接,base 带 /v1 即拼出 /v1/v1/messages (count_tokens 同),而同一账号在 OpenAI 族原生 Anthropic 链上版本感知拼接、 工作正常。抽出 anthropicProtocolEndpointURL 供两条链共用同一规则。 --- ...eway_anthropic_upstream_target_url_test.go | 49 +++++++++++++++++++ .../service/gateway_upstream_request.go | 7 +-- ...penai_gateway_messages_anthropic_native.go | 14 ++++-- 3 files changed, 63 insertions(+), 7 deletions(-) create mode 100644 backend/internal/service/gateway_anthropic_upstream_target_url_test.go diff --git a/backend/internal/service/gateway_anthropic_upstream_target_url_test.go b/backend/internal/service/gateway_anthropic_upstream_target_url_test.go new file mode 100644 index 0000000000..743648997f --- /dev/null +++ b/backend/internal/service/gateway_anthropic_upstream_target_url_test.go @@ -0,0 +1,49 @@ +//go:build unit + +package service + +import ( + "testing" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/stretchr/testify/require" +) + +// generic 链(跨族账号池走 GatewayService.Forward / CountTokens)与 OpenAI 族原生 +// Anthropic 链同一拼接规则:ollama / 按模型分流平台的 Anthropic 协议 base 带 /v1 时 +// 版本感知拼接,不得拼出 /v1/v1/messages;其余供应商保持朴素拼接。 +func TestAnthropicUpstreamTargetURL_VersionAwareForOllamaCloud(t *testing.T) { + svc := &GatewayService{cfg: &config.Config{Security: config.SecurityConfig{URLAllowlist: config.URLAllowlistConfig{Enabled: false}}}} + + ollama := &Account{ + ID: 1, Platform: PlatformOllamaCloud, Type: AccountTypeAPIKey, + Credentials: map[string]any{ + "api_key": "ollama-key", + "api_protocol": APIProtocolAnthropic, + "base_url": "https://ollama.com/v1", + }, + } + got, err := svc.anthropicUpstreamTargetURL(ollama, "/v1/messages") + require.NoError(t, err) + require.Equal(t, "https://ollama.com/v1/messages", got) + got, err = svc.anthropicUpstreamTargetURL(ollama, "/v1/messages/count_tokens") + require.NoError(t, err) + require.Equal(t, "https://ollama.com/v1/messages/count_tokens", got) + + ollama.Credentials["base_url"] = "https://ollama.com" + got, err = svc.anthropicUpstreamTargetURL(ollama, "/v1/messages") + require.NoError(t, err) + require.Equal(t, "https://ollama.com/v1/messages", got) + + kimi := &Account{ + ID: 2, Platform: PlatformKimi, Type: AccountTypeAPIKey, + Credentials: map[string]any{ + "api_key": "kimi-key", + "api_protocol": APIProtocolAnthropic, + "base_url": "https://api.moonshot.cn/anthropic", + }, + } + got, err = svc.anthropicUpstreamTargetURL(kimi, "/v1/messages") + require.NoError(t, err) + require.Equal(t, "https://api.moonshot.cn/anthropic/v1/messages", got) +} diff --git a/backend/internal/service/gateway_upstream_request.go b/backend/internal/service/gateway_upstream_request.go index 49b6838531..49abe1ba95 100644 --- a/backend/internal/service/gateway_upstream_request.go +++ b/backend/internal/service/gateway_upstream_request.go @@ -1017,8 +1017,9 @@ func anthropicUpstreamBaseForAuth(account *Account) string { // anthropicUpstreamTargetURL 组装 Anthropic 上游端点(path 以 "/" 开头,如 // "/v1/messages"、"/v1/messages/count_tokens")。CN/多协议账号( -// GetAnthropicProtocolBaseURL 非空)按 {base}{path} 朴素拼接、不附加 ?beta=true -// (第三方端点不接受该参数,与 OpenAI 族 nativeAnthropicTargetURL 对齐); +// GetAnthropicProtocolBaseURL 非空)经 anthropicProtocolEndpointURL 拼接(与 OpenAI 族 +// nativeAnthropicTargetURL 同一规则,ollama / 按模型分流平台版本感知)、不附加 +// ?beta=true(第三方端点不接受该参数); // classic anthropic 账号保持 {base}{path}?beta=true 现状。返回空串表示无自定义 // base(走官方默认 claudeAPIURL / claudeAPICountTokensURL),由调用方保持默认。 func (s *GatewayService) anthropicUpstreamTargetURL(account *Account, path string) (string, error) { @@ -1028,7 +1029,7 @@ func (s *GatewayService) anthropicUpstreamTargetURL(account *Account, path strin if err != nil { return "", err } - return strings.TrimRight(validatedURL, "/") + path, nil + return anthropicProtocolEndpointURL(account, validatedURL, path), nil } baseURL := account.GetBaseURL() if baseURL == "" { diff --git a/backend/internal/service/openai_gateway_messages_anthropic_native.go b/backend/internal/service/openai_gateway_messages_anthropic_native.go index 5ee7d6743a..90816c92ea 100644 --- a/backend/internal/service/openai_gateway_messages_anthropic_native.go +++ b/backend/internal/service/openai_gateway_messages_anthropic_native.go @@ -146,12 +146,18 @@ func (s *OpenAIGatewayService) nativeAnthropicTargetURL(account *Account) (strin // 连接测试共用。按模型分流的聚合平台(OpenCode、Command Code 等)的基址可能沿用带 /v1 // 的 Chat Completions 基址,用版本感知拼接避免 /v1/v1/messages;其余供应商朴素拼接。 func nativeAnthropicMessagesURL(account *Account, validatedBaseURL string) string { - // 版本感知拼接:base 已带 /v1 时不再追加,避免拼出 /v1/v1/messages(按模型分流平台的 - // Chat Completions base 带 /v1;Ollama Cloud 的 anthropic 默认 base 不带,自定义可能带)。 + return anthropicProtocolEndpointURL(account, validatedBaseURL, "/v1/messages") +} + +// anthropicProtocolEndpointURL 由已校验的 Anthropic 协议基址拼出端点(endpoint 以 "/v1" +// 开头),OpenAI 族原生 Anthropic 链与 generic 链共用。版本感知拼接:base 已带 /v1 时 +// 不再追加,避免拼出 /v1/v1/messages(按模型分流平台的 Chat Completions base 带 /v1; +// Ollama Cloud 的 anthropic 默认 base 不带,自定义可能带);其余供应商朴素拼接。 +func anthropicProtocolEndpointURL(account *Account, validatedBaseURL, endpoint string) string { if account.routesByModel() || account.IsOllamaCloud() { - return buildOpenAIEndpointURL(validatedBaseURL, "/v1/messages") + return buildOpenAIEndpointURL(validatedBaseURL, endpoint) } - return strings.TrimRight(validatedBaseURL, "/") + "/v1/messages" + return strings.TrimRight(validatedBaseURL, "/") + endpoint } func resolveMappedUpstreamModel(account *Account, body []byte, defaultMappedModel string) string { From 7ea472861b332cb98135c11b6a8a9edc590298f8 Mon Sep 17 00:00:00 2001 From: shaw Date: Sat, 10 Oct 2026 11:03:29 +0800 Subject: [PATCH 60/81] =?UTF-8?q?fix(composite):=20ollama=5Fcloud=20?= =?UTF-8?q?=E7=A9=BA=20mapping=20=E8=B4=A6=E5=8F=B7=E6=8C=89=20allowed=5Fm?= =?UTF-8?q?odels=20=E7=99=BD=E5=90=8D=E5=8D=95=E6=9E=84=E6=88=90=E5=BC=BA?= =?UTF-8?q?=E5=A3=B0=E6=98=8E?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit DetectModelPlatform 刻意不识别 ollama,空 mapping 的受控 native 声明对 ollama_cloud 永不成立:只配 extra.allowed_models 的账号在 composite 里声明强度恒为 None, /v1/models 列出的模型却无法路由(未识别名 400,gpt-oss/glm/kimi 等被 detector 投到其他平台)。清单精确命中(IsModelSupported 的 ollama 运行时白名单)即强声明。 --- .../service/composite_account_claims.go | 10 +++++++ .../composite_ollama_ownership_test.go | 27 +++++++++++++++++++ 2 files changed, 37 insertions(+) diff --git a/backend/internal/service/composite_account_claims.go b/backend/internal/service/composite_account_claims.go index 533faac4c3..d4139319b0 100644 --- a/backend/internal/service/composite_account_claims.go +++ b/backend/internal/service/composite_account_claims.go @@ -44,6 +44,16 @@ func CompositeAccountClaimStrength(account *Account, model string) CompositeClai mapping = stringMappingFromRaw(account.Credentials["model_mapping"]) } if len(mapping) == 0 { + if account.IsOllamaCloud() { + // ollama_cloud 空 mapping:extra.allowed_models 是管理员逐名声明的出站白名单 + // (DetectModelPlatform 刻意不识别 ollama,受控 native 永不成立)。清单精确 + // 命中(IsModelSupported 的 ollama 运行时白名单)即强声明,与 /v1/models + // 列表同一语义;无清单为 deny-all。 + if account.IsModelSupported(model) { + return CompositeClaimExplicit + } + return CompositeClaimNone + } // 规则B:空 mapping 仅受控 native 声明。OpenAI OAuth 空 mapping 仍受 // isOpenAIOAuthServableModel 约束(IsModelSupported 内部处理)。 if platform, ok := DetectModelPlatform(model); !ok || platform != account.Platform { diff --git a/backend/internal/service/composite_ollama_ownership_test.go b/backend/internal/service/composite_ollama_ownership_test.go index b960623be0..3454e2c3f7 100644 --- a/backend/internal/service/composite_ollama_ownership_test.go +++ b/backend/internal/service/composite_ollama_ownership_test.go @@ -202,3 +202,30 @@ func TestResolveCompositeModelOwnershipSkipsUnschedulableOllamaCloud(t *testing. require.False(t, decision.Matched, "不可调度与其他组的 ollama 账号不得被解析为可路由目标") require.Empty(t, decision.TargetPlatform) } + +// ollama_cloud 只配 extra.allowed_models、不配 model_mapping 的账号:清单项是管理员 +// 显式声明的出站白名单,必须构成强声明,否则 detector 无 ollama 分支,账号在 composite +// 里永远不可路由(/v1/models 却列出这些模型);清单外模型不得冒领。 +func TestResolveCompositeModelOwnershipOllamaCloudAllowedModelsWithoutMapping(t *testing.T) { + const group = int64(9) + ollama := Account{ + ID: 171, + Platform: PlatformOllamaCloud, + Type: AccountTypeAPIKey, + Extra: map[string]any{OllamaCloudAllowedModelsExtraKey: []any{"qwen3.5:397b", "glm-5.1"}}, + } + resolver, _ := newOllamaOwnershipResolver( + compositeOwnershipScopedRecord{groupID: group, platform: PlatformOllamaCloud, schedulable: true, account: ollama}, + ) + + for _, model := range []string{"qwen3.5:397b", "glm-5.1"} { + decision, err := resolver.Resolve(context.Background(), group, model, CompositeRouteEndpointResponses) + require.NoError(t, err) + require.True(t, decision.Matched, "model=%s", model) + require.Equal(t, CompositeRouteSourceAccount, decision.Source, "model=%s", model) + require.Equal(t, PlatformOllamaCloud, decision.TargetPlatform, "model=%s", model) + } + + require.Equal(t, CompositeClaimExplicit, CompositeAccountClaimStrength(&ollama, "glm-5.1")) + require.Equal(t, CompositeClaimNone, CompositeAccountClaimStrength(&ollama, "kimi-k3"), "清单外模型不得声明") +} From 502f8b827d4b84161e856c52a76b0204bf3a7e66 Mon Sep 17 00:00:00 2001 From: shaw Date: Sat, 10 Oct 2026 11:04:50 +0800 Subject: [PATCH 61/81] =?UTF-8?q?fix(composite):=20=E8=B4=A6=E5=8F=B7?= =?UTF-8?q?=E9=85=8D=E7=BD=AE=E5=8F=98=E6=9B=B4=E6=97=B6=E7=AB=8B=E5=8D=B3?= =?UTF-8?q?=E5=A4=B1=E6=95=88=20composite=20=E5=BD=92=E5=B1=9E=E7=BC=93?= =?UTF-8?q?=E5=AD=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit d1f65572c 删除了 invalidateCompositeModelOwnershipCache,InvalidateAvailableModelsCache 解析 "composite-owner|" 前缀键失败即跳过:账号 mapping / 白名单变更后最长一个 models_list_cache_ttl 内仍按旧归属路由或拒绝,main 上是立即生效。恢复该失效 (热路径仍走缓存,不读库)。 --- .../gateway_hotpath_optimization_test.go | 11 ++++---- backend/internal/service/gateway_service.go | 25 +++++++++++++++++++ 2 files changed, 31 insertions(+), 5 deletions(-) diff --git a/backend/internal/service/gateway_hotpath_optimization_test.go b/backend/internal/service/gateway_hotpath_optimization_test.go index f334b25951..e49a6b7373 100644 --- a/backend/internal/service/gateway_hotpath_optimization_test.go +++ b/backend/internal/service/gateway_hotpath_optimization_test.go @@ -575,7 +575,7 @@ func TestGetAvailableModels_UsesShortCacheAndSupportsInvalidation(t *testing.T) } // Scenario: ownership 基于配置态查询解析并按 modelsListCache 短 TTL 缓存——热路径 -// TTL 内不重复查库;瞬态限流字段不影响能力池;配置变更在缓存过期后反映。 +// TTL 内不重复查库;瞬态限流字段不影响能力池;配置变更经缓存失效立即反映。 func TestResolveCompositeModelOwnershipCachesConfigState(t *testing.T) { groupID := int64(9) rateLimitedReset := time.Now().Add(30 * time.Minute) @@ -619,8 +619,9 @@ func TestResolveCompositeModelOwnershipCachesConfigState(t *testing.T) { require.Equal(t, first, transient) require.Equal(t, int64(2), repo.listByGroupCalls.Load()) - // 缓存过期后,配置移除声明即反映为能力消失。 - svc.modelsListCache.Flush() + // 账号配置变更触发的失效(InvalidateAvailableModelsCache)立即清除归属缓存: + // 移除声明即反映为能力消失,不必等 TTL。 + svc.InvalidateAvailableModelsCache(&groupID, PlatformDeepseek) repo.byGroup[groupID] = []Account{{ ID: 2, Platform: PlatformOpenAI, @@ -630,8 +631,8 @@ func TestResolveCompositeModelOwnershipCachesConfigState(t *testing.T) { require.Equal(t, CompositeModelOwnership{}, removed) require.Equal(t, int64(3), repo.listByGroupCalls.Load()) - // 缓存过期后,换平台声明生效。 - svc.modelsListCache.Flush() + // 换平台声明同样在失效后立即生效。 + svc.InvalidateAvailableModelsCache(&groupID, "") repo.byGroup[groupID] = []Account{{ ID: 2, Platform: PlatformOpenAI, diff --git a/backend/internal/service/gateway_service.go b/backend/internal/service/gateway_service.go index 12e0124133..50d640fa1f 100644 --- a/backend/internal/service/gateway_service.go +++ b/backend/internal/service/gateway_service.go @@ -1646,6 +1646,9 @@ func (s *GatewayService) InvalidateAvailableModelsCache(groupID *int64, platform if s == nil || s.modelsListCache == nil { return } + // composite 归属缓存与模型列表共用 modelsListCache:账号 mapping / 白名单变更时 + // 一并失效,配置变更立即生效而不必等 TTL。 + s.invalidateCompositeModelOwnershipCache(groupID) normalizedPlatform := strings.TrimSpace(platform) // 完整匹配时精准失效;否则按维度批量失效。 @@ -1674,6 +1677,28 @@ func (s *GatewayService) InvalidateAvailableModelsCache(groupID *int64, platform } } +// invalidateCompositeModelOwnershipCache 删除 composite 归属缓存条目(键形如 +// "composite-owner||");groupID 为 nil 时清空全部分组。 +func (s *GatewayService) invalidateCompositeModelOwnershipCache(groupID *int64) { + for key := range s.modelsListCache.Items() { + if !strings.HasPrefix(key, compositeModelOwnershipCachePrefix) { + continue + } + if groupID == nil { + s.modelsListCache.Delete(key) + continue + } + parts := strings.SplitN(strings.TrimPrefix(key, compositeModelOwnershipCachePrefix), "|", 2) + if len(parts) != 2 { + continue + } + cachedGroupID, err := strconv.ParseInt(parts[0], 10, 64) + if err == nil && cachedGroupID == *groupID { + s.modelsListCache.Delete(key) + } + } +} + const debugGatewayBodyDefaultFilename = "gateway_debug.log" // initDebugGatewayBodyFile 初始化网关调试日志文件。 From 6e5faccef631757e7828219c0cc983cdce7bff82 Mon Sep 17 00:00:00 2001 From: shaw Date: Sat, 10 Oct 2026 11:07:07 +0800 Subject: [PATCH 62/81] =?UTF-8?q?fix(ollama):=20=E5=87=BA=E7=AB=99?= =?UTF-8?q?=E6=95=B4=E5=BD=A2=E7=9A=84=E5=AE=98=E6=96=B9=20host=20?= =?UTF-8?q?=E5=88=A4=E5=AE=9A=E5=AE=B9=E5=BF=8D=20base=5Furl=20=E6=9C=AB?= =?UTF-8?q?=E5=B0=BE=E6=96=9C=E6=9D=A0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit CC/Responses 路径的 max_tokens clamp 与推理字段归一化直接把 base_url 交给 isOllamaCloudBaseURL(只认 path 为空或 /v1),"https://ollama.com/v1/" 这类 配置出站端点不变却漏掉 65535 钳制而被上游 400;Anthropic 侧早已先去尾斜杠。 出站整形统一经 isOllamaCloudOutboundBaseURL;用量窗口资格门禁仍严格比对。 --- backend/internal/service/anthropic_apikey_auth.go | 2 +- .../service/ollama_cloud_messages_max_tokens.go | 6 +----- backend/internal/service/ollama_cloud_usage.go | 8 ++++++++ .../openai_gateway_ollama_cloud_cc_reasoning.go | 2 +- .../service/openai_gateway_ollama_cloud_max_tokens.go | 4 ++-- .../openai_gateway_ollama_cloud_max_tokens_test.go | 11 +++++++++++ 6 files changed, 24 insertions(+), 9 deletions(-) diff --git a/backend/internal/service/anthropic_apikey_auth.go b/backend/internal/service/anthropic_apikey_auth.go index d72083672d..d348fba769 100644 --- a/backend/internal/service/anthropic_apikey_auth.go +++ b/backend/internal/service/anthropic_apikey_auth.go @@ -42,7 +42,7 @@ func (a *Account) GetAnthropicAPIKeyAuthScheme() string { // 与 '.../v1' 均合理),再复用既有严格 host helper isOllamaCloudBaseURL(精确 // host、https、无 query/fragment、路径仅空或 /v1),不按 substring 匹配。 func isOllamaCloudAnthropicAuthBaseURL(baseURL string) bool { - return isOllamaCloudBaseURL(strings.TrimRight(strings.TrimSpace(baseURL), "/")) + return isOllamaCloudOutboundBaseURL(baseURL) } // setAnthropicAPIKeyAuthHeader 写入上游认证头。除 extra 覆写外,Ollama Cloud diff --git a/backend/internal/service/ollama_cloud_messages_max_tokens.go b/backend/internal/service/ollama_cloud_messages_max_tokens.go index 4bd1498930..d689627fcf 100644 --- a/backend/internal/service/ollama_cloud_messages_max_tokens.go +++ b/backend/internal/service/ollama_cloud_messages_max_tokens.go @@ -1,9 +1,5 @@ package service -import ( - "strings" -) - // clampOllamaCloudAnthropicMessagesMaxTokens 是 Anthropic Messages 出站 // (/v1/messages,含 CC / Responses 桥接与 passthrough)的 max_tokens clamp 钩子, // 与 raw CC / Responses 路径共用 cap 配置与实现。判定与出站 URL 组装同源:调用方 @@ -16,7 +12,7 @@ func clampOllamaCloudAnthropicMessagesMaxTokens(account *Account, baseURL string if account == nil || len(body) == 0 { return body } - if !isOllamaCloudBaseURL(strings.TrimRight(strings.TrimSpace(baseURL), "/")) { + if !isOllamaCloudOutboundBaseURL(baseURL) { return body } return clampOllamaCloudMaxTokens(account, body) diff --git a/backend/internal/service/ollama_cloud_usage.go b/backend/internal/service/ollama_cloud_usage.go index f9abc53c83..cb8237c63d 100644 --- a/backend/internal/service/ollama_cloud_usage.go +++ b/backend/internal/service/ollama_cloud_usage.go @@ -1119,6 +1119,14 @@ func IsOllamaCloudUsageAccount(account *Account) bool { return ollamaCloudUsageEligibilityReason(account) == "" } +// isOllamaCloudOutboundBaseURL 是出站请求整形(max_tokens clamp、推理字段归一化、 +// Bearer 认证)用的官方 host 判定:URL 拼装会规范化末尾 "/","https://ollama.com/v1/" +// 与 "https://ollama.com/v1" 发往同一端点,判定必须一致。用量窗口资格门禁仍按 +// isOllamaCloudBaseURL 严格比对,不受影响。 +func isOllamaCloudOutboundBaseURL(raw string) bool { + return isOllamaCloudBaseURL(strings.TrimRight(strings.TrimSpace(raw), "/")) +} + func isOllamaCloudBaseURL(raw string) bool { raw = strings.TrimSpace(raw) if raw == "" || strings.ContainsAny(raw, "?#") { diff --git a/backend/internal/service/openai_gateway_ollama_cloud_cc_reasoning.go b/backend/internal/service/openai_gateway_ollama_cloud_cc_reasoning.go index 8ac5d7b838..5ef463ed09 100644 --- a/backend/internal/service/openai_gateway_ollama_cloud_cc_reasoning.go +++ b/backend/internal/service/openai_gateway_ollama_cloud_cc_reasoning.go @@ -22,7 +22,7 @@ func isOllamaCloudDeepSeekUpstream(account *Account, upstreamModel string) bool if account == nil { return false } - if !isOllamaCloudBaseURL(account.GetOpenAIBaseURL()) { + if !isOllamaCloudOutboundBaseURL(account.GetOpenAIBaseURL()) { return false } return isDeepSeekModel(upstreamModel) diff --git a/backend/internal/service/openai_gateway_ollama_cloud_max_tokens.go b/backend/internal/service/openai_gateway_ollama_cloud_max_tokens.go index a30e39b77e..5ee239ab7c 100644 --- a/backend/internal/service/openai_gateway_ollama_cloud_max_tokens.go +++ b/backend/internal/service/openai_gateway_ollama_cloud_max_tokens.go @@ -28,7 +28,7 @@ func clampOllamaCloudUpstreamMaxTokens(account *Account, body []byte) []byte { if account == nil || len(body) == 0 { return body } - if !isOllamaCloudBaseURL(account.GetOpenAIBaseURL()) { + if !isOllamaCloudOutboundBaseURL(account.GetOpenAIBaseURL()) { return body } return clampOllamaCloudMaxTokens(account, body) @@ -59,7 +59,7 @@ func ollamaCloudResponsesMaxOutputTokensClamp(account *Account, upstreamModel st if account == nil || account.Type != AccountTypeAPIKey { return 0, false, "" } - if !isOllamaCloudBaseURL(ollamaCloudResponsesUpstreamBaseURL(account)) { + if !isOllamaCloudOutboundBaseURL(ollamaCloudResponsesUpstreamBaseURL(account)) { return 0, false, "" } value := gjson.GetBytes(body, "max_output_tokens") diff --git a/backend/internal/service/openai_gateway_ollama_cloud_max_tokens_test.go b/backend/internal/service/openai_gateway_ollama_cloud_max_tokens_test.go index 8a5cac55fe..ed6c172d68 100644 --- a/backend/internal/service/openai_gateway_ollama_cloud_max_tokens_test.go +++ b/backend/internal/service/openai_gateway_ollama_cloud_max_tokens_test.go @@ -188,6 +188,17 @@ func ollamaUpstreamTestAccount(platform string, id int64) *Account { } } +// base_url 末尾 "/" 不改变出站端点(URL 拼装会规范化),clamp 判定必须与之一致: +// "https://ollama.com/v1/" 与 "https://ollama.com/" 同样按 Ollama 上游钳制。 +func TestClampOllamaCloudUpstreamMaxTokensToleratesTrailingSlash(t *testing.T) { + for _, baseURL := range []string{"https://ollama.com/v1/", "https://ollama.com/"} { + account := ollamaUpstreamTestAccount(PlatformOllamaCloud, 303) + account.Credentials["base_url"] = baseURL + got := clampOllamaCloudUpstreamMaxTokens(account, []byte(`{"model":"gpt-oss:120b","max_tokens":100000}`)) + require.JSONEq(t, `{"model":"gpt-oss:120b","max_tokens":65535}`, string(got), "base_url=%s", baseURL) + } +} + // officialDeepSeekTestAccount 构造官方 DeepSeek 账号,extra 里带残留的 Ollama // usage 快照键:usage extra 不得把非 Ollama host 识别为 Ollama 上游。 func officialDeepSeekTestAccount(id int64) *Account { From 4504b5b7fa158e69ba45b1d89f70822a805053ab Mon Sep 17 00:00:00 2001 From: shaw Date: Sat, 10 Oct 2026 11:08:42 +0800 Subject: [PATCH 63/81] =?UTF-8?q?fix(ollama):=20=E9=87=91=E9=A2=9D?= =?UTF-8?q?=E5=87=AD=E6=8D=AE=E9=9D=9E=E6=9C=89=E9=99=90=E5=80=BC=E6=8C=89?= =?UTF-8?q?=E6=97=A0=E6=B3=95=E8=A7=A3=E6=9E=90=E5=A4=84=E7=90=86=EF=BC=8C?= =?UTF-8?q?=E9=81=BF=E5=85=8D=E8=B4=A6=E5=8F=B7=E5=88=97=E8=A1=A8=E5=BA=8F?= =?UTF-8?q?=E5=88=97=E5=8C=96=E5=A4=B1=E8=B4=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit strconv.ParseFloat 接受 "Inf",monthly_credit_usd="Inf" 能通过 >0 判断写进 OllamaCloudUsageState,json.Marshal(+Inf) 报错,含该账号的账号列表/详情接口 返回空响应体。GetCredentialAsFloat64 对 NaN/±Inf 返回 0。 --- backend/internal/service/account.go | 15 ++++++++++++--- .../internal/service/ollama_cloud_usage_test.go | 12 ++++++++++++ 2 files changed, 24 insertions(+), 3 deletions(-) diff --git a/backend/internal/service/account.go b/backend/internal/service/account.go index e21cedbf6c..bbe6d42bad 100644 --- a/backend/internal/service/account.go +++ b/backend/internal/service/account.go @@ -6,6 +6,7 @@ import ( "errors" "hash/fnv" "log/slog" + "math" "net/url" "reflect" "sort" @@ -443,10 +444,18 @@ func (a *Account) GetCredentialAsInt64(key string) int64 { return 0 } -// GetCredentialAsFloat64 返回浮点型凭据值,缺失或无法解析时返回 0。与 -// GetCredentialAsInt64 同样的类型容忍(JSONB 数字为 float64/json.Number, -// 运营也可能手写成字符串),供 Ollama Cloud monthly_credit_usd 等金额键读取。 +// GetCredentialAsFloat64 返回浮点型凭据值,缺失、无法解析或非有限值(NaN/±Inf, +// strconv.ParseFloat 接受 "Inf"/"NaN")时返回 0。与 GetCredentialAsInt64 同样的类型 +// 容忍(JSONB 数字为 float64/json.Number,运营也可能手写成字符串),供 Ollama Cloud +// monthly_credit_usd 等金额键读取;非有限值进入 DTO 会让 JSON 序列化失败。 func (a *Account) GetCredentialAsFloat64(key string) float64 { + if f := a.getCredentialAsFloat64(key); !math.IsNaN(f) && !math.IsInf(f, 0) { + return f + } + return 0 +} + +func (a *Account) getCredentialAsFloat64(key string) float64 { if a == nil || a.Credentials == nil { return 0 } diff --git a/backend/internal/service/ollama_cloud_usage_test.go b/backend/internal/service/ollama_cloud_usage_test.go index d8857e6b48..7f16dca752 100644 --- a/backend/internal/service/ollama_cloud_usage_test.go +++ b/backend/internal/service/ollama_cloud_usage_test.go @@ -608,6 +608,18 @@ func TestOllamaCloudUsageStateModeAndMonthlyCredit(t *testing.T) { credentials: map[string]any{"account_mode": AccountModeOllamaCredits, "monthly_credit_usd": float64(0)}, wantMode: AccountModeOllamaCredits, }, + { + // strconv.ParseFloat 接受 "Inf"/"NaN":非有限值进 DTO 会让 JSON 序列化失败, + // 账号列表接口整页返回空响应体。 + name: "信用池为 Inf 字符串 → 视为无该字段", + credentials: map[string]any{"account_mode": AccountModeOllamaCredits, "monthly_credit_usd": "Inf"}, + wantMode: AccountModeOllamaCredits, + }, + { + name: "信用池为 NaN 字符串 → 视为无该字段", + credentials: map[string]any{"account_mode": AccountModeOllamaCredits, "monthly_credit_usd": "NaN"}, + wantMode: AccountModeOllamaCredits, + }, { name: "不认识的 mode 值保守回落 legacy", credentials: map[string]any{"account_mode": "ollama_turbo"}, From a14044e66823de79885152055a1dafb5387737d3 Mon Sep 17 00:00:00 2001 From: shaw Date: Sat, 10 Oct 2026 11:13:01 +0800 Subject: [PATCH 64/81] =?UTF-8?q?fix(composite):=20antigravity=20=E5=B9=B3?= =?UTF-8?q?=E5=8F=B0=E9=BB=98=E8=AE=A4=E6=98=A0=E5=B0=84=E4=B8=8D=E6=9E=84?= =?UTF-8?q?=E6=88=90=20composite=20=E5=A3=B0=E6=98=8E=EF=BC=8C=E6=81=A2?= =?UTF-8?q?=E5=A4=8D=E6=B7=B7=E5=90=88=E8=B0=83=E5=BA=A6=E5=8D=95=E7=9B=AE?= =?UTF-8?q?=E6=A0=87=E8=AF=AD=E4=B9=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 开启混合调度的 antigravity 默认映射(claude-* / gemini-* 精确键)被算作强声明, 「anthropic + 混合调度 antigravity」这类存量分组被静默改成账号池:分组模型路由 失效(池平台哨兵为 composite),user×platform 配额改按 antigravity 计——anthropic 配额耗尽后 antigravity 照常服务 Claude 请求,绕过 anthropic 配额;渠道定价作用域 也随之改变。 - antigravity 只有账号显式 model_mapping 构成声明(与 main 归属语义一致); - 由 detector / 他平台声明解析出的 anthropic / gemini 单目标照常经混合调度展开 antigravity 账号,展开账号不受 account_model 归属层级否决,按映射判定可服务。 --- .../service/composite_account_claims.go | 11 +++-- .../composite_antigravity_mixed_claim_test.go | 43 +++++++++++++++++-- .../internal/service/gateway_scheduling.go | 13 +++++- 3 files changed, 58 insertions(+), 9 deletions(-) diff --git a/backend/internal/service/composite_account_claims.go b/backend/internal/service/composite_account_claims.go index d4139319b0..44743d3f07 100644 --- a/backend/internal/service/composite_account_claims.go +++ b/backend/internal/service/composite_account_claims.go @@ -37,10 +37,13 @@ func CompositeAccountClaimStrength(account *Account, model string) CompositeClai } mapping := account.GetModelMapping() - if account.Platform == PlatformAntigravity && !account.IsMixedSchedulingEnabled() { - // 平台默认映射(Claude / Gemini 模型)只在开启混合调度时才让 antigravity 账号 - // 服务这些模型,与非 composite 的混合调度开关同一语义;未开启时只有管理员在 - // 账号上显式配置的映射构成声明。 + if account.Platform == PlatformAntigravity { + // antigravity 只有管理员在账号上显式配置的映射构成 composite 声明。平台默认映射 + // (Claude / Gemini 模型)属于混合调度语义:开启混合调度时由 detector 判出的 + // anthropic / gemini 单目标经混合调度展开服务这些模型(配额、渠道定价与分组模型 + // 路由仍按该平台),与 main 及非 composite 分组一致;若默认映射也算声明, + // 「anthropic + 混合调度 antigravity」会被静默改成账号池,antigravity 按自身 + // 平台计配额,绕过 anthropic 配额。 mapping = stringMappingFromRaw(account.Credentials["model_mapping"]) } if len(mapping) == 0 { diff --git a/backend/internal/service/composite_antigravity_mixed_claim_test.go b/backend/internal/service/composite_antigravity_mixed_claim_test.go index 7043f7ccb0..6c07ad6d46 100644 --- a/backend/internal/service/composite_antigravity_mixed_claim_test.go +++ b/backend/internal/service/composite_antigravity_mixed_claim_test.go @@ -1,24 +1,59 @@ package service import ( + "context" "testing" + "github.com/Wei-Shaw/sub2api/internal/pkg/ctxkey" "github.com/stretchr/testify/require" ) -// antigravity 账号的平台默认映射(Claude / Gemini 模型)只在开启混合调度时构成 -// composite 声明;未开启时只认管理员显式配置的映射,与非 composite 混合调度开关同语义。 -func TestCompositeClaimAntigravityDefaultMappingRequiresMixedScheduling(t *testing.T) { +// antigravity 账号只有管理员显式配置的映射构成 composite 声明;平台默认映射(Claude / +// Gemini 模型)属于混合调度语义,无论是否开启混合调度都不构成声明。 +func TestCompositeClaimAntigravityOnlyExplicitMappingClaims(t *testing.T) { const model = "claude-sonnet-4-5" mixedOff := &Account{ID: 1, Platform: PlatformAntigravity, Type: AccountTypeOAuth} require.Equal(t, CompositeClaimNone, CompositeAccountClaimStrength(mixedOff, model)) require.False(t, CompositeAccountClaimsModel(mixedOff, model)) mixedOn := &Account{ID: 2, Platform: PlatformAntigravity, Type: AccountTypeOAuth, Extra: map[string]any{"mixed_scheduling": true}} - require.Equal(t, CompositeClaimExplicit, CompositeAccountClaimStrength(mixedOn, model)) + require.Equal(t, CompositeClaimNone, CompositeAccountClaimStrength(mixedOn, model), + "混合调度开启时默认映射也不构成声明,否则与 anthropic 静默成池") explicitMixedOff := &Account{ID: 3, Platform: PlatformAntigravity, Type: AccountTypeOAuth, Credentials: map[string]any{"model_mapping": map[string]any{"team-alias": "claude-opus-4-8"}}} require.Equal(t, CompositeClaimExplicit, CompositeAccountClaimStrength(explicitMixedOff, "team-alias")) require.Equal(t, CompositeClaimNone, CompositeAccountClaimStrength(explicitMixedOff, model), "默认映射条目不因存在自定义映射而生效") } + +// 「anthropic 原生账号 + 开启混合调度的 antigravity」分组:归属解析为 anthropic 单目标 +// (不成池),antigravity 经混合调度展开服务——配额、渠道定价与分组模型路由仍按 +// anthropic,与 main 一致;混合调度展开的账号不受 account_model 归属层级否决。 +func TestCompositeAnthropicWithMixedAntigravityStaysSingleTarget(t *testing.T) { + const ( + group = int64(21) + model = "claude-sonnet-4-5" + ) + antigravity := Account{ID: 212, Platform: PlatformAntigravity, Type: AccountTypeOAuth, Extra: map[string]any{"mixed_scheduling": true}} + resolver, _ := newOllamaOwnershipResolver( + compositeOwnershipScopedRecord{groupID: group, platform: PlatformAnthropic, schedulable: true, + account: Account{ID: 211, Platform: PlatformAnthropic, Type: AccountTypeAPIKey}}, + compositeOwnershipScopedRecord{groupID: group, platform: PlatformAntigravity, schedulable: true, account: antigravity}, + ) + + decision, err := resolver.Resolve(context.Background(), group, model, CompositeRouteEndpointMessages) + require.NoError(t, err) + require.True(t, decision.Matched) + require.Equal(t, PlatformAnthropic, decision.TargetPlatform) + require.Empty(t, decision.CandidatePlatforms, "不得与混合调度 antigravity 构成账号池") + + ctx := WithCompositeRouteDecision(context.Background(), decision) + require.Equal(t, CompositeRouteSourceAccount, ctx.Value(ctxkey.CompositeRouteSource)) + svc := &GatewayService{} + require.True(t, svc.isModelSupportedByAccountWithContext(ctx, &antigravity, model), + "混合调度展开的 antigravity 账号按映射判定可服务,不被归属层级否决") + + mixedOff := antigravity + mixedOff.Extra = nil + require.False(t, compositeMixedSchedulingExpandedAccount(ctx, &mixedOff), "未开启混合调度不属于展开账号") +} diff --git a/backend/internal/service/gateway_scheduling.go b/backend/internal/service/gateway_scheduling.go index 784014c029..eb9c2839e2 100644 --- a/backend/internal/service/gateway_scheduling.go +++ b/backend/internal/service/gateway_scheduling.go @@ -2719,10 +2719,21 @@ func summarizeSelectionFailureStats(stats selectionFailureStats) string { ) } +// compositeMixedSchedulingExpandedAccount 报告账号是否经混合调度展开进入 composite +// 单目标(anthropic / gemini)的候选集:antigravity 账号的平台默认映射不构成 composite +// 声明,其可服务性按混合调度原语义由下方映射判定,不受 account_model 归属层级否决。 +func compositeMixedSchedulingExpandedAccount(ctx context.Context, account *Account) bool { + if account == nil || account.Platform != PlatformAntigravity || !account.IsMixedSchedulingEnabled() { + return false + } + resolved, ok := ResolvedTargetPlatformFromContext(ctx) + return ok && (resolved == PlatformAnthropic || resolved == PlatformGemini) +} + // isModelSupportedByAccountWithContext 根据账户平台检查模型支持(带 context) // 对于 Antigravity 平台,会先获取映射后的最终模型名(包括 thinking 后缀)再检查支持 func (s *GatewayService) isModelSupportedByAccountWithContext(ctx context.Context, account *Account, requestedModel string) bool { - if source, ok := CompositeRouteSourceFromContext(ctx); ok && source == CompositeRouteSourceAccount { + if source, ok := CompositeRouteSourceFromContext(ctx); ok && source == CompositeRouteSourceAccount && !compositeMixedSchedulingExpandedAccount(ctx, account) { if publicModel, modelOK := RequestedPublicModelFromContext(ctx); modelOK && !CompositeAccountMeetsClaimTier(ctx, account, publicModel) { return false } From 6d17e26eceaa6079df502fdface6f9911905ac4d Mon Sep 17 00:00:00 2001 From: shaw Date: Sat, 10 Oct 2026 11:14:37 +0800 Subject: [PATCH 65/81] =?UTF-8?q?fix(composite):=20generic=20count=5Ftoken?= =?UTF-8?q?s=20=E5=AF=B9=E5=A4=9A=E5=8D=8F=E8=AE=AE=20API=20Key=20?= =?UTF-8?q?=E8=B4=A6=E5=8F=B7=E6=9C=AC=E5=9C=B0=E4=BC=B0=E7=AE=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 跨族账号池会把 adaptive / anthropic 协议的国产厂商与 Ollama Cloud 账号交给 GatewayService.ForwardCountTokens,转发 {base}/v1/messages/count_tokens 只会 常态 404(上游无该端点),错误还会流入账号处置;同类账号在 OpenAI 族链一律 本地估算。两条链对齐为本地估算。 --- .../composite_generic_pool_messages_test.go | 14 ++++++++++++++ backend/internal/service/gateway_count_tokens.go | 13 +++++++++++++ 2 files changed, 27 insertions(+) diff --git a/backend/internal/handler/composite_generic_pool_messages_test.go b/backend/internal/handler/composite_generic_pool_messages_test.go index 411148a371..b2f8f2e7d0 100644 --- a/backend/internal/handler/composite_generic_pool_messages_test.go +++ b/backend/internal/handler/composite_generic_pool_messages_test.go @@ -419,6 +419,20 @@ func TestCompositePoolCountTokensSkipsUncountableOpenAIAccount(t *testing.T) { require.Empty(t, h.openAIUpstream.snapshot()) } +// count_tokens 池请求选中 adaptive 多协议账号(国产厂商 / Ollama Cloud):其 Anthropic +// 兼容层无 count_tokens 端点,与 OpenAI 族链同口径本地估算,不转发上游。 +func TestCompositePoolCountTokensMultiProtocolAccountEstimatesLocally(t *testing.T) { + h := newCompositePoolMessagesHarness(t, []*service.Account{poolAdaptiveKimiAccount(41451, 41011, 0)}) + + c, rec := h.newRequest(t, "/v1/messages/count_tokens", poolCountTokensBody(), service.PlatformAnthropic, service.PlatformKimi) + h.handler.CountTokens(c) + + require.Equal(t, http.StatusOK, rec.Code) + require.Positive(t, gjson.GetBytes(rec.Body.Bytes(), "input_tokens").Int()) + require.Empty(t, h.gwUpstream.snapshot(), "多协议账号不得转发 count_tokens 到上游") + require.Empty(t, h.openAIUpstream.snapshot()) +} + // count_tokens 池请求跳过纯 OpenAI 族账号后改选可计数的 anthropic 账号并成功转发。 func TestCompositePoolCountTokensSkipsThenForwardsCountableAccount(t *testing.T) { h := newCompositePoolMessagesHarness(t, []*service.Account{ diff --git a/backend/internal/service/gateway_count_tokens.go b/backend/internal/service/gateway_count_tokens.go index 9b0de97774..a51b22c957 100644 --- a/backend/internal/service/gateway_count_tokens.go +++ b/backend/internal/service/gateway_count_tokens.go @@ -111,6 +111,19 @@ func (s *GatewayService) ForwardCountTokens(ctx context.Context, c *gin.Context, return nil } + // 多协议 API Key 供应商(国产厂商、聚合平台、Ollama Cloud)的 Anthropic 兼容层均未 + // 提供 /v1/messages/count_tokens:与 OpenAI 族链 ForwardCountTokensAsAnthropic 同口径 + // 本地估算,不发上游(跨族账号池会把这类账号交给本链,转发只会常态 404)。 + if account.IsMultiProtocolAPIKey() { + estimated, err := estimateAnthropicCountTokensLocally(body) + if err != nil { + s.countTokensError(c, http.StatusBadRequest, "invalid_request_error", "Failed to parse request body") + return fmt.Errorf("count_tokens: estimate input tokens locally: %w", err) + } + c.JSON(http.StatusOK, gin.H{"input_tokens": estimated}) + return nil + } + // 应用模型映射: // - APIKey 账号:使用账号级别的显式映射(如果配置),否则透传原始模型名 // - OAuth/SetupToken 账号:使用 Anthropic 标准映射(短ID → 长ID) From 8d36844f39352122ea733686ad427c69f25f75ca Mon Sep 17 00:00:00 2001 From: shaw Date: Sat, 10 Oct 2026 11:15:50 +0800 Subject: [PATCH 66/81] =?UTF-8?q?fix(composite):=20=E9=9D=9E=20APIKey=20?= =?UTF-8?q?=E5=A4=9A=E5=8D=8F=E8=AE=AE=E8=B4=A6=E5=8F=B7=E4=B8=8D=E5=BE=97?= =?UTF-8?q?=E8=BF=9B=E5=85=A5=20generic=20=E8=B4=A6=E5=8F=B7=E6=B1=A0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit generic Forward 只对 APIKey 账号使用协议化 Anthropic base,其余类型回落官方 api.anthropic.com;池成员资格只校验协议 base 非空,异常配置的 OAuth 类型 国产 / Ollama 账号(api_protocol=anthropic/adaptive)被选中时会带自身凭据 发往 Anthropic。多协议分支要求 APIKey 类型。 --- backend/internal/service/composite_generic_pool.go | 11 +++++++---- .../service/composite_generic_pool_scheduling_test.go | 9 +++++++++ 2 files changed, 16 insertions(+), 4 deletions(-) diff --git a/backend/internal/service/composite_generic_pool.go b/backend/internal/service/composite_generic_pool.go index 186c3b6d5a..39142bf4ab 100644 --- a/backend/internal/service/composite_generic_pool.go +++ b/backend/internal/service/composite_generic_pool.go @@ -68,9 +68,9 @@ func (s *GatewayService) withCompositePoolQuotaAutoPauseContext(ctx context.Cont // 纯能力判定,不依赖候选池: // - PlatformAnthropic:generic 网关原生账号(OAuth/APIKey/ServiceAccount); // - gemini / antigravity:既有 generic 调度支持的平台; -// - anthropic-协议 / adaptive 多协议账号:要求能解析出 Anthropic 协议上游 base -// (GetAnthropicProtocolBaseURL 非空,含 api_base_urls.anthropic 与供应商×模式 -// 默认端点),避免入池后转发期才发现无端点可用; +// - anthropic-协议 / adaptive 多协议账号:要求 APIKey 类型且能解析出 Anthropic 协议 +// 上游 base(GetAnthropicProtocolBaseURL 非空,含 api_base_urls.anthropic 与供应商× +// 模式默认端点),避免入池后转发期才发现无端点可用或回落官方 Anthropic; // - OpenAI 兼容账号(openai/grok/国产供应商/opencode_go):转发由 handler 层 // 委派协议转换链服务,不因账号停留在 Chat Completions 协议而被池排除。 func genericCompositePoolAccountServable(account *Account) bool { @@ -87,7 +87,10 @@ func genericCompositePoolAccountServable(account *Account) bool { return true } if account.IsAnthropicProtocol() || account.IsAdaptiveAPIProtocol() { - return strings.TrimSpace(account.GetAnthropicProtocolBaseURL()) != "" + // generic Forward 只对 APIKey 账号使用协议化 base(buildUpstreamRequest),其余 + // 类型回落官方 api.anthropic.com:非 APIKey 的多协议账号(异常配置)入池会把 + // 自身凭据发往 Anthropic,一律不可服务。 + return account.Type == AccountTypeAPIKey && strings.TrimSpace(account.GetAnthropicProtocolBaseURL()) != "" } return account.IsOpenAICompatible() } diff --git a/backend/internal/service/composite_generic_pool_scheduling_test.go b/backend/internal/service/composite_generic_pool_scheduling_test.go index f4699ed664..929ea56c14 100644 --- a/backend/internal/service/composite_generic_pool_scheduling_test.go +++ b/backend/internal/service/composite_generic_pool_scheduling_test.go @@ -459,6 +459,15 @@ func TestCompositeGenericPoolPredicates(t *testing.T) { require.True(t, genericCompositePoolAccountServable(&gemini)) require.True(t, genericCompositePoolAccountServable(&antigravity)) + // 非 APIKey 的多协议账号(异常配置):generic Forward 不用协议化 base、回落官方 + // api.anthropic.com,入池会把自身凭据发往 Anthropic,不可服务。 + zhipuAnthropicOAuth := zhipuAnthropic + zhipuAnthropicOAuth.Type = AccountTypeOAuth + require.False(t, genericCompositePoolAccountServable(&zhipuAnthropicOAuth)) + kimiAdaptiveOAuth := kimiAdaptive + kimiAdaptiveOAuth.Type = AccountTypeOAuth + require.False(t, genericCompositePoolAccountServable(&kimiAdaptiveOAuth)) + // 池成员资格:平台 ∈ 候选池为准;池外平台一律拒绝。 require.True(t, genericCompositePoolAllowsAccount(poolCtx, &kimiAdaptive)) require.True(t, genericCompositePoolAllowsAccount(poolCtx, &anthropicNative)) From bc362b7dabdd215bdb0dfb87e046c1a7c3530519 Mon Sep 17 00:00:00 2001 From: shaw Date: Sat, 10 Oct 2026 11:18:01 +0800 Subject: [PATCH 67/81] =?UTF-8?q?fix(ollama):=20OpenAI=20=E9=93=BE?= =?UTF-8?q?=E5=AE=9A=E4=BB=B7=E9=A2=84=E6=A3=80=E5=AF=B9=20/v1/messages=20?= =?UTF-8?q?=E5=85=A5=E7=AB=99=E8=BF=94=E5=9B=9E=20Anthropic=20=E9=94=99?= =?UTF-8?q?=E8=AF=AF=E4=BF=A1=E5=B0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit OpenAI 网关的 ollama_cloud 未定价预检一律写 OpenAI 风格 {"error":{...}}, /v1/messages 入站(原生 Anthropic、Messages→CC/Responses 桥接)缺顶层 "type":"error";generic 链同名预检已按入站协议选信封。两条链共用同一写出函数。 --- ..._gateway_ollama_cloud_pricing_preflight.go | 28 +++++++++---------- ...way_ollama_cloud_pricing_preflight_test.go | 1 + 2 files changed, 14 insertions(+), 15 deletions(-) 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 ab06456a4e..7fd4d295aa 100644 --- a/backend/internal/service/openai_gateway_ollama_cloud_pricing_preflight.go +++ b/backend/internal/service/openai_gateway_ollama_cloud_pricing_preflight.go @@ -50,14 +50,20 @@ func (e *openAIOllamaCloudUnpricedModelError) Error() string { // 先例由服务层直接写出 400 invalid_request_error。写前 MarkResponseCommitted 与 // cyber_policy / grok content 拒绝同款:handler 侧 ensureForwardErrorResponse / // ensureAnthropicErrorResponse 检测到响应已提交便不再追加 fallback 错误;返回的 -// 错误非 UpstreamFailoverError——不换号、不写账号处置。 +// 错误非 UpstreamFailoverError——不换号、不写账号处置。错误信封按入站协议选择: +// /messages 入站(OpenAI 族原生 Anthropic / Messages 桥接链与 generic 链)为 Anthropic +// 风格,其余为 OpenAI 风格。 func respondOpenAIOllamaCloudUnpricedModelError(c *gin.Context, err *openAIOllamaCloudUnpricedModelError) { + if c == nil { + return + } setOpsUpstreamError(c, http.StatusBadRequest, err.Error(), "") MarkResponseCommitted(c) - c.JSON(http.StatusBadRequest, gin.H{"error": gin.H{ - "type": "invalid_request_error", - "message": err.Error(), - }}) + payload := gin.H{"error": gin.H{"type": "invalid_request_error", "message": err.Error()}} + if c.Request != nil && c.Request.URL != nil && strings.Contains(c.Request.URL.Path, "/messages") { + payload = gin.H{"type": "error", "error": gin.H{"type": "invalid_request_error", "message": err.Error()}} + } + c.JSON(http.StatusBadRequest, payload) } // ollamaCloudBillingGroupFromContext 取认证中间件放入 ctx 的计费分组(与利润门 D @@ -135,7 +141,7 @@ func (s *OpenAIGatewayService) enforceOllamaCloudRequestPricingPreflight(ctx con // enforceOllamaCloudRequestPricingPreflight 是 generic 网关(composite 跨族账号池经 // Anthropic 协议链服务 ollama_cloud 账号)的同一预检:在上游 I/O 之前拒绝无价出站模型, -// 错误信封按入站协议选择(/messages 为 Anthropic 风格,其余为 OpenAI 风格)。 +// 与 OpenAI 网关共用 respondOpenAIOllamaCloudUnpricedModelError(信封按入站协议选择)。 func (s *GatewayService) enforceOllamaCloudRequestPricingPreflight(ctx context.Context, c *gin.Context, account *Account, body []byte, fallbackModel string) error { if s == nil || account == nil || !account.IsOllamaCloud() { return nil @@ -148,14 +154,6 @@ func (s *GatewayService) enforceOllamaCloudRequestPricingPreflight(ctx context.C return nil } err := &openAIOllamaCloudUnpricedModelError{model: model} - if c != nil { - setOpsUpstreamError(c, http.StatusBadRequest, err.Error(), "") - MarkResponseCommitted(c) - payload := gin.H{"error": gin.H{"type": "invalid_request_error", "message": err.Error()}} - if c.Request != nil && c.Request.URL != nil && strings.Contains(c.Request.URL.Path, "/messages") { - payload = gin.H{"type": "error", "error": gin.H{"type": "invalid_request_error", "message": err.Error()}} - } - c.JSON(http.StatusBadRequest, payload) - } + 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 index 6086fadede..1ea9fc6fd1 100644 --- a/backend/internal/service/openai_gateway_ollama_cloud_pricing_preflight_test.go +++ b/backend/internal/service/openai_gateway_ollama_cloud_pricing_preflight_test.go @@ -227,4 +227,5 @@ func TestOllamaCloudPricingPreflight_AnthropicNativePathRejectsUnpriced(t *testi c, rec, ctx := pricingPreflightContext("/v1/messages", body, nil) _, err := svc.ForwardAsAnthropic(ctx, c, account, body, "", "") assertPricingPreflightRejected(t, c, upstream, rec, err, "totally-unpriced-model") + require.Equal(t, "error", gjson.Get(rec.Body.String(), "type").String(), "/v1/messages 入站必须使用 Anthropic 错误信封") } From bcb44606150881a8ce781ea2138d695b6e0d5c3e Mon Sep 17 00:00:00 2001 From: shaw Date: Sat, 10 Oct 2026 11:19:09 +0800 Subject: [PATCH 68/81] =?UTF-8?q?fix(channel-monitor):=20ollama=5Fcloud=20?= =?UTF-8?q?replace=20=E6=A8=A1=E5=BC=8F=E8=AF=B7=E6=B1=82=E4=BD=93?= =?UTF-8?q?=E6=A0=A1=E9=AA=8C=E6=8C=89=20OpenAI=20Chat=20=E5=90=8C?= =?UTF-8?q?=E6=9E=84=E5=A4=84=E7=90=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ollama_cloud 探活适配器与 OpenAI Chat Completions 同构,却不在 isOpenAICompatibleChatProvider 中,replace 模式缺 messages 的请求体可保存, 之后每次探活必然失败。 --- backend/internal/service/channel_monitor_checker.go | 3 ++- .../internal/service/channel_monitor_checker_body_test.go | 8 ++++++++ 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/backend/internal/service/channel_monitor_checker.go b/backend/internal/service/channel_monitor_checker.go index fceef2434a..6725fa20ca 100644 --- a/backend/internal/service/channel_monitor_checker.go +++ b/backend/internal/service/channel_monitor_checker.go @@ -493,7 +493,8 @@ func bodyMergeDenyKey(provider, apiMode string) string { func isOpenAICompatibleChatProvider(provider string) bool { switch provider { case MonitorProviderOpenAI, MonitorProviderGrok, - MonitorProviderKimi, MonitorProviderZhipu, MonitorProviderDeepseek, MonitorProviderMiniMax: + MonitorProviderKimi, MonitorProviderZhipu, MonitorProviderDeepseek, MonitorProviderMiniMax, + MonitorProviderOllamaCloud: return true default: return false diff --git a/backend/internal/service/channel_monitor_checker_body_test.go b/backend/internal/service/channel_monitor_checker_body_test.go index 922eb86732..8ba8032418 100644 --- a/backend/internal/service/channel_monitor_checker_body_test.go +++ b/backend/internal/service/channel_monitor_checker_body_test.go @@ -213,6 +213,14 @@ func TestGrokMonitorConfiguration(t *testing.T) { } } +// ollama_cloud 探活适配器与 OpenAI Chat 同构:replace 模式的请求体同样必须带 messages, +// 否则保存成功后每次探活都失败。 +func TestValidateReplaceRequestBody_OllamaCloudRequiresMessages(t *testing.T) { + if err := validateReplaceRequestBody(MonitorProviderOllamaCloud, MonitorAPIModeChatCompletions, map[string]any{}); err == nil { + t.Fatal("ollama_cloud replace-mode body should require messages") + } +} + func TestRunCheckForModel_Grok_DefaultChatRequest(t *testing.T) { h := &openAICaptureHandler{} endpoint := setupFakeOpenAI(t, h) From 04b0ac54d0b4d78a3a7667b6f597948275ba5813 Mon Sep 17 00:00:00 2001 From: shaw Date: Sat, 5 Dec 2026 10:41:13 +0800 Subject: [PATCH 69/81] =?UTF-8?q?fix(scheduler):=20=E8=A1=A5=E9=BD=90=20ol?= =?UTF-8?q?lama=5Fcloud=20=E5=BF=AB=E7=85=A7=E6=8A=95=E5=BD=B1=E5=AD=97?= =?UTF-8?q?=E6=AE=B5=E4=B8=8E=E7=94=A8=E9=87=8F=E6=9B=B4=E6=96=B0=E5=90=8E?= =?UTF-8?q?=E7=9A=84=E8=B0=83=E5=BA=A6=E7=BC=93=E5=AD=98=E5=90=8C=E6=AD=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../account_repo_ollama_cloud_usage.go | 14 +++- ...epo_ollama_cloud_usage_integration_test.go | 58 ++++++++++++++++ .../internal/repository/scheduler_cache.go | 10 ++- .../scheduler_cache_ollama_cloud_test.go | 69 +++++++++++++++++++ 4 files changed, 148 insertions(+), 3 deletions(-) diff --git a/backend/internal/repository/account_repo_ollama_cloud_usage.go b/backend/internal/repository/account_repo_ollama_cloud_usage.go index 2be8bae189..b3448fbc96 100644 --- a/backend/internal/repository/account_repo_ollama_cloud_usage.go +++ b/backend/internal/repository/account_repo_ollama_cloud_usage.go @@ -199,6 +199,7 @@ func (r *accountRepository) updateOllamaCloudUsageGroup( if !ok || apiKey == "" { return service.ErrOllamaCloudUsageAccountInvalid } + var syncedMemberIDs []int64 apply := func(txCtx context.Context, client *dbent.Client) error { matchesProxy, err := lockAndMatchProbeProxyIdentity(txCtx, client, account) if err != nil { @@ -274,6 +275,7 @@ func (r *accountRepository) updateOllamaCloudUsageGroup( if affected != int64(len(members)) { return service.ErrOllamaCloudUsageIdentityChanged } + syncedMemberIDs = memberIDs return nil } if dbent.TxFromContext(ctx) != nil { @@ -281,7 +283,11 @@ func (r *accountRepository) updateOllamaCloudUsageGroup( } tx, err := r.client.Tx(ctx) if errors.Is(err, dbent.ErrTxStarted) { - return apply(ctx, r.client) + if err := apply(ctx, r.client); err != nil { + return err + } + r.syncSchedulerAccountSnapshots(ctx, syncedMemberIDs) + return nil } if err != nil { return err @@ -291,7 +297,11 @@ func (r *accountRepository) updateOllamaCloudUsageGroup( if err := apply(txCtx, tx.Client()); err != nil { return err } - return tx.Commit() + if err := tx.Commit(); err != nil { + return err + } + r.syncSchedulerAccountSnapshots(ctx, syncedMemberIDs) + return nil } func lockOllamaCloudUsageGroup( diff --git a/backend/internal/repository/account_repo_ollama_cloud_usage_integration_test.go b/backend/internal/repository/account_repo_ollama_cloud_usage_integration_test.go index 753d1bef26..4573ca5675 100644 --- a/backend/internal/repository/account_repo_ollama_cloud_usage_integration_test.go +++ b/backend/internal/repository/account_repo_ollama_cloud_usage_integration_test.go @@ -303,6 +303,64 @@ func TestOllamaCloudUsageGroupWritesAreAtomicAcrossPlatformsAndURLVariants(t *te require.NotContains(t, firstLoaded.Extra, service.OllamaCloudUsageSessionExtraKey) } +type ollamaUsageSnapshotSyncCache struct { + service.SchedulerCache + mu sync.Mutex + accounts map[int64]*service.Account +} + +func (c *ollamaUsageSnapshotSyncCache) SetAccount(_ context.Context, account *service.Account) error { + if account == nil { + return nil + } + c.mu.Lock() + defer c.mu.Unlock() + if c.accounts == nil { + c.accounts = make(map[int64]*service.Account) + } + cloned := *account + c.accounts[account.ID] = &cloned + return nil +} + +func TestUpdateOllamaCloudUsageSnapshotSyncsGroupMembersToSchedulerCache(t *testing.T) { + ctx := context.Background() + tx := testEntTx(t) + cache := &ollamaUsageSnapshotSyncCache{} + repo := newAccountRepositoryWithSQL(tx.Client(), tx, cache) + first := mustCreateAccount(t, tx.Client(), &service.Account{ + Name: "ollama-cache-sync-1", Platform: service.PlatformOllamaCloud, Type: service.AccountTypeAPIKey, + Credentials: map[string]any{"api_key": "shared-sync-key", "base_url": "https://ollama.com/v1"}, + Extra: map[string]any{ + service.OllamaCloudUsageSessionExtraKey: "cipher:shared", + service.OllamaCloudUsageAutoRefreshExtraKey: true, + }, + }) + second := mustCreateAccount(t, tx.Client(), &service.Account{ + Name: "ollama-cache-sync-2", Platform: service.PlatformOllamaCloud, Type: service.AccountTypeAPIKey, + Credentials: map[string]any{"api_key": "shared-sync-key", "base_url": "https://ollama.com/v1"}, + Extra: map[string]any{ + service.OllamaCloudUsageSessionExtraKey: "cipher:shared", + service.OllamaCloudUsageAutoRefreshExtraKey: true, + }, + }) + firstLoaded, err := repo.GetByID(ctx, first.ID) + require.NoError(t, err) + now := time.Now().UTC() + snapshot := &service.OllamaCloudUsageSnapshot{ + Status: service.OllamaCloudUsageStatusOK, LastAttemptAt: now, NextRefreshAt: now.Add(time.Hour), + } + require.NoError(t, repo.UpdateOllamaCloudUsageSnapshot(ctx, firstLoaded, snapshot)) + + cache.mu.Lock() + defer cache.mu.Unlock() + for _, id := range []int64{first.ID, second.ID} { + synced := cache.accounts[id] + require.NotNil(t, synced, "member %d must be synced to scheduler cache", id) + require.Contains(t, synced.Extra, service.OllamaCloudUsageSnapshotExtraKey) + } +} + func TestConcurrentOllamaCloudUsageSaveAndDeleteSerializeGroupState(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() diff --git a/backend/internal/repository/scheduler_cache.go b/backend/internal/repository/scheduler_cache.go index 009acf8bec..de95040ff7 100644 --- a/backend/internal/repository/scheduler_cache.go +++ b/backend/internal/repository/scheduler_cache.go @@ -1648,7 +1648,12 @@ func filterSchedulerCredentials(credentials map[string]any) map[string]any { // Gemini 显式缓存的候选过滤(GeminiExplicitCacheExclusions)读本投影判定账号是否支持显式缓存: // 官方地址、Vertex 认证方式与上游网关的显式缓存声明。缺这几个键时只能按类型粗筛, // 不支持的账号要逐个选中后才被剔除。 - "base_url", "auth_mode", service.GeminiExplicitCacheUpstreamCredentialKey, service.GeminiExplicitCacheUpstreamMaxTTLCredentialKey} + "base_url", "auth_mode", service.GeminiExplicitCacheUpstreamCredentialKey, service.GeminiExplicitCacheUpstreamMaxTTLCredentialKey, + // Ollama Cloud 调度阈值过滤(GetOllamaCloudAccountMode)与 generic 跨平台池候选资格 + // (GetAPIProtocol / GetAnthropicProtocolBaseURL)均跑在本投影上:缺 account_mode + // 会使 credits 账号误入 legacy 窗口评估,缺 api_protocol / api_base_urls 会使多协议账号 + // 在快照态丢失协议配置(如绕过非 APIKey 多协议账号防入池守卫)。 + "account_mode", "api_protocol", "api_base_urls"} filtered := make(map[string]any) for _, key := range keys { if value, ok := credentials[key]; ok && value != nil { @@ -1722,6 +1727,9 @@ func filterSchedulerExtra(extra map[string]any) map[string]any { // 裁掉它,白名单账号会在选号阶段被整体误判为 model_not_supported, // 表现为 ollama_cloud 分组恒 no available accounts。 service.OllamaCloudAllowedModelsExtraKey, + // ollama_cloud legacy 账号的 5h/7d 调度阈值停调跑在本投影上: + // 缺该快照键会导致快照态 decodeOllamaCloudUsageSnapshot 恒为 nil 而失去停调保护。 + service.OllamaCloudUsageSnapshotExtraKey, "codex_fingerprint_mode", "codex_fingerprint_seed", "codex_5h_used_percent", diff --git a/backend/internal/repository/scheduler_cache_ollama_cloud_test.go b/backend/internal/repository/scheduler_cache_ollama_cloud_test.go index 63473073b3..2c49fb65b2 100644 --- a/backend/internal/repository/scheduler_cache_ollama_cloud_test.go +++ b/backend/internal/repository/scheduler_cache_ollama_cloud_test.go @@ -5,6 +5,7 @@ package repository import ( "encoding/json" "testing" + "time" "github.com/Wei-Shaw/sub2api/internal/service" "github.com/stretchr/testify/require" @@ -37,3 +38,71 @@ func TestFilterSchedulerExtra_KeepsOllamaCloudAllowedModels(t *testing.T) { require.True(t, account.IsModelSupported("gpt-oss:120b")) require.False(t, account.IsModelSupported("totally-unpriced-model")) } + +// ollama_cloud 调度阈值停调(EvaluateAccountSchedulingThreshold)与多协议池资格 +// 均在快照投影账号上执行:必须保留 ollama_cloud_usage_snapshot、account_mode、 +// api_protocol 与 api_base_urls。 +func TestSchedulerMetadataAccount_KeepsOllamaCloudThresholdAndProtocolProjection(t *testing.T) { + now := time.Date(2026, time.October, 10, 12, 0, 0, 0, time.UTC) + fiveHourReset := now.Add(2 * time.Hour) + snapshot := map[string]any{ + "status": service.OllamaCloudUsageStatusOK, + "data": map[string]any{ + "five_hour": map[string]any{ + "used_percent": 95.0, + "reset_at": fiveHourReset.Format(time.RFC3339), + }, + }, + } + + legacyAccount := service.Account{ + ID: 11, + Platform: service.PlatformOllamaCloud, + Type: service.AccountTypeAPIKey, + Status: service.StatusActive, + Schedulable: true, + Credentials: map[string]any{ + "api_key": "sk-ollama", + "base_url": "https://ollama.com/v1", + "account_mode": service.AccountModeOllamaLegacy, + "api_protocol": service.APIProtocolAdaptive, + "api_base_urls": map[string]any{ + "chat_completions": "https://ollama.com/v1", + "anthropic": "https://ollama.com", + "responses": "https://ollama.com/v1", + }, + "account_scheduling_threshold": 80, + }, + Extra: map[string]any{ + service.OllamaCloudAllowedModelsExtraKey: []string{"qwen3.5:397b"}, + service.OllamaCloudUsageSnapshotExtraKey: snapshot, + }, + } + + _, metaPayload, err := marshalSchedulerCacheAccount(legacyAccount) + require.NoError(t, err) + var projected service.Account + require.NoError(t, json.Unmarshal(metaPayload, &projected)) + + require.Equal(t, service.AccountModeOllamaLegacy, projected.GetOllamaCloudAccountMode()) + require.Equal(t, service.APIProtocolAdaptive, projected.GetAPIProtocol()) + require.Equal(t, "https://ollama.com", projected.GetAnthropicProtocolBaseURL()) + decision := service.EvaluateAccountSchedulingThreshold(&projected, nil, now) + require.True(t, decision.ShouldPause, "快照投影账号达到 5h 阈值时必须停调") + + // credits 账号在投影后必须保持 ollama_credits 模式,不得退回 legacy 被窗口停调。 + creditsAccount := legacyAccount + creditsAccount.ID = 12 + creditsAccount.Credentials = map[string]any{ + "api_key": "sk-ollama", + "base_url": "https://ollama.com/v1", + "account_mode": service.AccountModeOllamaCredits, + "account_scheduling_threshold": 80, + } + _, creditsMeta, err := marshalSchedulerCacheAccount(creditsAccount) + require.NoError(t, err) + var projectedCredits service.Account + require.NoError(t, json.Unmarshal(creditsMeta, &projectedCredits)) + require.Equal(t, service.AccountModeOllamaCredits, projectedCredits.GetOllamaCloudAccountMode()) + require.False(t, service.EvaluateAccountSchedulingThreshold(&projectedCredits, nil, now).ShouldPause) +} From 18f11c391a0092a975f7ea0b39a9b593d74e9bb7 Mon Sep 17 00:00:00 2001 From: shaw Date: Sat, 5 Dec 2026 10:41:13 +0800 Subject: [PATCH 70/81] =?UTF-8?q?fix(composite):=20=E6=94=B6=E6=95=9B?= =?UTF-8?q?=E8=B4=A6=E5=8F=B7=E6=B1=A0=E6=A8=A1=E5=9E=8B=E9=97=A8=E7=A6=81?= =?UTF-8?q?=E3=80=81=E9=80=8F=E4=BC=A0=E6=AE=8B=E7=95=99=E6=98=A0=E5=B0=84?= =?UTF-8?q?=E5=85=BC=E5=AE=B9=E4=B8=8E=E8=B4=9F=E8=BD=BD=E6=84=9F=E7=9F=A5?= =?UTF-8?q?=E8=87=AA=E5=8A=A8=E6=9A=82=E5=81=9C=E6=B3=A8=E5=85=A5=E9=A1=BA?= =?UTF-8?q?=E5=BA=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../service/composite_account_claims.go | 8 +++- .../composite_generic_pool_scheduling_test.go | 41 +++++++++++++++++++ .../internal/service/gateway_scheduling.go | 39 ++++++++++++++---- .../openai_composite_pool_scheduling_test.go | 27 ++++++++++++ .../service/openai_gateway_scheduling.go | 7 +++- 5 files changed, 113 insertions(+), 9 deletions(-) diff --git a/backend/internal/service/composite_account_claims.go b/backend/internal/service/composite_account_claims.go index 44743d3f07..d2fe1108f3 100644 --- a/backend/internal/service/composite_account_claims.go +++ b/backend/internal/service/composite_account_claims.go @@ -37,7 +37,13 @@ func CompositeAccountClaimStrength(account *Account, model string) CompositeClai } mapping := account.GetModelMapping() - if account.Platform == PlatformAntigravity { + if account.IsOpenAIPassthroughEnabled() && !account.IsOpenAIPassthroughModelFilterEnabled() { + // 未开启按模型筛选的 OpenAI 透传账号忽略残留旧 model_mapping(#4936): + // 按空 mapping 进入下方受控 native 规则——对 OpenAI 原生模型(IsModelSupported 通过) + // 给强声明,避免同组存在空映射号时被 account_model_not_owned 误踢;对非原生模型或 + // 自定义别名不声明(CompositeClaimNone),不冒领其它平台或未知别名。 + mapping = nil + } else if account.Platform == PlatformAntigravity { // antigravity 只有管理员在账号上显式配置的映射构成 composite 声明。平台默认映射 // (Claude / Gemini 模型)属于混合调度语义:开启混合调度时由 detector 判出的 // anthropic / gemini 单目标经混合调度展开服务这些模型(配额、渠道定价与分组模型 diff --git a/backend/internal/service/composite_generic_pool_scheduling_test.go b/backend/internal/service/composite_generic_pool_scheduling_test.go index 929ea56c14..ab14f81ef9 100644 --- a/backend/internal/service/composite_generic_pool_scheduling_test.go +++ b/backend/internal/service/composite_generic_pool_scheduling_test.go @@ -404,6 +404,47 @@ func TestGenericCompositePool_SkipsQuotaAutoPausedOpenAIAccount(t *testing.T) { selected, err = build(95).SelectAccountForModelWithExclusions(ctx, &groupID, "", model, nil) require.NoError(t, err) require.EqualValues(t, 44602, selected.ID, "达到自动暂停阈值的 openai 账号不得被池选中") + + // SelectAccountWithLoadAwareness 在内部经 resolvePlatform 解析出候选池时(入参 ctx + // 尚未携带 CompositeCandidatePlatforms),同样须注入全局默认配额暂停阈值。 + loadCfg := &config.Config{} + loadCfg.Gateway.Scheduling.LoadBatchEnabled = true + openaiGlobalPaused := genericPoolTestAccount(44603, PlatformOpenAI, groupID, 0, + map[string]any{"model_mapping": map[string]any{"my-model": "gpt-5.4"}}, + map[string]any{"codex_5h_used_percent": 95.0}) + anthropicBackup := genericPoolTestAccount(44604, PlatformAnthropic, groupID, 5, + map[string]any{"model_mapping": map[string]any{"my-model": "claude-sonnet-4-5"}}, nil) + svcLoadAware, _ := newGenericPoolTestService([]Account{openaiGlobalPaused, anthropicBackup}, group, &compositePoolTestCache{}, loadCfg) + svcLoadAware.concurrencyService = NewConcurrencyService(schedulerTestConcurrencyCache{}) + svcLoadAware.compositeResolver = NewCompositeRouteResolver(nil) + svcLoadAware.compositeResolver.SetModelOwnershipResolver(func(_ context.Context, _ int64, _ string) (CompositeModelOwnership, error) { + return CompositeModelOwnership{ + Matched: true, + CandidatePlatforms: []string{PlatformAnthropic, PlatformOpenAI}, + RequiredClaimStrength: CompositeClaimExplicit, + }, nil + }) + settingSvc := &SettingService{} + settingSvc.openAIQuotaAutoPauseSettingsCache.Store(&cachedOpenAIQuotaAutoPauseSettings{ + settings: OpsOpenAIAccountQuotaAutoPauseSettings{DefaultThreshold5h: 0.90}, + expiresAt: time.Now().Add(time.Hour).UnixNano(), + }) + svcLoadAware.settingService = settingSvc + res, err := svcLoadAware.SelectAccountWithLoadAwareness(context.Background(), &groupID, "", model, nil, "", 0) + require.NoError(t, err) + require.NotNil(t, res) + require.EqualValues(t, 44604, res.Account.ID, "内部解析候选池时全局 5h 配额暂停阈值同样生效") + + // generic 池模型能力门保留平台特定约束(如 Antigravity thinking 后缀与 OpenAI 退役模型)。 + poolCtx := genericPoolTestContext([]string{PlatformAntigravity, PlatformOpenAI}) + agNoThinking := genericPoolTestAccount(44605, PlatformAntigravity, groupID, 0, + map[string]any{"model_mapping": map[string]any{"claude-sonnet-4-5": "claude-sonnet-4-5"}}, nil) + thinkingCtx := WithThinkingEnabled(poolCtx, true, false) + require.False(t, svcLoadAware.gatewaySchedulingModelSupported(thinkingCtx, &agNoThinking, "claude-sonnet-4-5")) + oauthRetired := genericPoolTestAccount(44606, PlatformOpenAI, groupID, 0, + map[string]any{"model_mapping": map[string]any{"my-model": "gpt-5.5"}}, nil) + oauthRetired.Type = AccountTypeOAuth + require.False(t, svcLoadAware.gatewaySchedulingModelSupported(poolCtx, &oauthRetired, "my-model")) } // ---- e2. 显式 resolved 平台 pin 优先于池(单平台旧行为保持) ---- diff --git a/backend/internal/service/gateway_scheduling.go b/backend/internal/service/gateway_scheduling.go index f0696fc7e9..3921dd8b06 100644 --- a/backend/internal/service/gateway_scheduling.go +++ b/backend/internal/service/gateway_scheduling.go @@ -129,7 +129,6 @@ func (s *GatewayService) SelectAccountWithLoadAwareness(ctx context.Context, gro } ctx = s.withGroupContext(ctx, group) ctx = s.withGatewayProfitControlGate(ctx, groupID) - ctx = s.withCompositePoolQuotaAutoPauseContext(ctx) // Claude Code 限制可能已将 groupID 解析为 fallback group, // 渠道限制预检查必须使用解析后的分组。 @@ -227,6 +226,7 @@ func (s *GatewayService) SelectAccountWithLoadAwareness(ctx context.Context, gro if err != nil { return nil, err } + ctx = s.withCompositePoolQuotaAutoPauseContext(ctx) preferOAuth := platform == PlatformGemini if s.debugModelRoutingEnabled() && requestedModel != "" && modelRoutingAppliesToTargetPlatform(platform) { logger.LegacyPrintf("service.gateway", "[ModelRoutingDebug] load-aware enabled: group_id=%v model=%s session=%s platform=%s", derefGroupID(groupID), requestedModel, shortSessionHash(sessionHash), platform) @@ -1166,7 +1166,7 @@ func (s *GatewayService) listSchedulableAccountsForCompositePool(ctx context.Con continue } // 与 sticky / 负载感知路径同一池成员门;legacy 选号循环不逐账号复检池成员资格,在取号时统一过滤。 - if !genericCompositePoolAllowsAccount(ctx, &bucket[i]) { + if !s.gatewayCompositePoolAllowsAccount(ctx, &bucket[i]) { continue } seen[bucket[i].ID] = struct{}{} @@ -1252,23 +1252,48 @@ func (s *GatewayService) isAccountAllowedForPlatform(account *Account, platform // 账号平台门:composite account_pool 激活时改用候选池成员校验(池 immutable, // 防止 sticky 命中池外账号导致池塌缩),单平台请求保持 // isAccountAllowedForPlatform 原语义(含混合调度展开)。 +func (s *GatewayService) gatewayParentAccountLookup(ctx context.Context) func(int64) *Account { + return func(id int64) *Account { + if s == nil { + return nil + } + if s.schedulerSnapshot != nil { + if a, err := s.schedulerSnapshot.GetAccount(ctx, id); err == nil && a != nil { + return a + } + } + if s.accountRepo == nil { + return nil + } + a, _ := s.accountRepo.GetByID(ctx, id) + return a + } +} + +func (s *GatewayService) gatewayCompositePoolAllowsAccount(ctx context.Context, account *Account) bool { + return genericCompositePoolAllowsAccount(ctx, account) && + parentHealthyForShadow(account, s.gatewayParentAccountLookup(ctx)) +} + func (s *GatewayService) gatewaySchedulingPlatformMatchesAccount(ctx context.Context, account *Account, platform string, useMixed bool) bool { if GenericCompositePoolActive(ctx) { - return genericCompositePoolAllowsAccount(ctx, account) + return s.gatewayCompositePoolAllowsAccount(ctx, account) } return s.isAccountAllowedForPlatform(account, platform, useMixed) } // gatewaySchedulingModelSupported 是 generic 调度选号/sticky 的模型能力门: -// 池请求使用契约共享谓词 CompositeAccountClaimsModel(与构池一致,任意强度命中 -// 均算,防 IsModelSupported 的 allow-all 语义冒领其他平台模型),单平台请求保持 -// isModelSupportedByAccountWithContext 原语义不变。 +// 池请求先按契约共享谓词(含 OpenAI passthrough 例外)拦截跨平台冒领,再复用 +// isModelSupportedByAccountWithContext 保留 Antigravity thinking 后缀、Bedrock +// 模型解析与 OpenAI 退役订阅模型等平台能力校验;单平台请求保持原语义不变。 func (s *GatewayService) gatewaySchedulingModelSupported(ctx context.Context, account *Account, requestedModel string) bool { if account == nil || requestedModel == "" { return true } if GenericCompositePoolActive(ctx) { - return CompositeAccountMeetsClaimTier(ctx, account, requestedModel) + if !CompositeAccountMeetsClaimTier(ctx, account, requestedModel) && !account.IsOpenAIPassthroughEnabled() { + return false + } } return s.isModelSupportedByAccountWithContext(ctx, account, requestedModel) } diff --git a/backend/internal/service/openai_composite_pool_scheduling_test.go b/backend/internal/service/openai_composite_pool_scheduling_test.go index 41e491c89d..49534ad889 100644 --- a/backend/internal/service/openai_composite_pool_scheduling_test.go +++ b/backend/internal/service/openai_composite_pool_scheduling_test.go @@ -783,6 +783,33 @@ func TestOpenAICompositePool_PassthroughStaleMappingSelectionException(t *testin _, err = svc3.SelectAccountForModelWithExclusions(onlyPassthroughCtx, &groupID, "", "my-model", nil) require.Error(t, err) require.True(t, errors.Is(err, ErrNoAvailableAccounts)) + + // passthrough 选号期例外仍须受 supportsOpenAIRequestModel 约束: + // 1) 开启 openai_passthrough_model_filter 时,未命中白名单不得放行; + // 2) OAuth passthrough 不得接异族模型(送 codex 必 400); + // 3) OAuth 账号不得接退役订阅模型 gpt-5.5。 + filteredPassthrough := newPassthroughAccount() + filteredPassthrough.Extra["openai_passthrough_model_filter"] = true + require.False(t, openAISchedulingModelSupported(poolCtx, &filteredPassthrough, "my-model", false)) + require.True(t, openAISchedulingModelSupported(poolCtx, &filteredPassthrough, "old-model", false)) + + oauthPassthrough := compositePoolTestAccount(37004, PlatformOpenAI, 22013, 0, nil) + oauthPassthrough.Type = AccountTypeOAuth + oauthPassthrough.Extra = map[string]any{"openai_oauth_passthrough": true} + require.False(t, openAISchedulingModelSupported(poolCtx, &oauthPassthrough, "deepseek-chat", false)) + require.False(t, openAISchedulingModelSupported(poolCtx, &oauthPassthrough, "gpt-5.5", false)) + require.True(t, openAISchedulingModelSupported(poolCtx, &oauthPassthrough, "gpt-5.4", false)) + + // 未开启 model_filter 的 passthrough 账号(带残留旧 mapping)对 OpenAI 原生模型具有 + // 受控 native 强声明,同组存在空映射号时不会被 account_model_not_owned 误踢;对非原生 + // 模型仍保持无声明。 + stalePassthrough := newPassthroughAccount() + require.Equal(t, CompositeClaimExplicit, CompositeAccountClaimStrength(&stalePassthrough, "gpt-5.4")) + require.Equal(t, CompositeClaimNone, CompositeAccountClaimStrength(&stalePassthrough, "deepseek-flash")) + + // openAICompositePoolAllowsAccount 同步排除 deniedPlatforms。 + deniedOpenAICtx := WithCompositePoolDeniedPlatforms(poolCtx, []string{PlatformOpenAI}) + require.False(t, openAICompositePoolAllowsAccount(deniedOpenAICtx, &strictPeer)) } // ---- composite account_pool 下 CN/OpenCode 的 previous_response_id 归属 ---- diff --git a/backend/internal/service/openai_gateway_scheduling.go b/backend/internal/service/openai_gateway_scheduling.go index eee4129c54..ee56d08ec8 100644 --- a/backend/internal/service/openai_gateway_scheduling.go +++ b/backend/internal/service/openai_gateway_scheduling.go @@ -334,6 +334,9 @@ func openAICompositePoolAllowsAccount(ctx context.Context, account *Account) boo if account == nil || !account.IsOpenAICompatible() { return false } + if compositePoolPlatformDenied(ctx, account.Platform) { + return false + } for _, platform := range CompositeCandidatePlatformsFromContext(ctx) { if platform == account.Platform { return true @@ -369,7 +372,9 @@ func openAISchedulingModelSupported(ctx context.Context, account *Account, reque return true } if openAICompositePoolActive(ctx) { - return CompositeAccountMeetsClaimTier(ctx, account, requestedModel) || account.IsOpenAIPassthroughEnabled() + if !CompositeAccountMeetsClaimTier(ctx, account, requestedModel) && !account.IsOpenAIPassthroughEnabled() { + return false + } } return supportsOpenAIRequestModel(account, requestedModel, requireCompact) } From e7fcf51343bcd6e2b51a0ea98c3d04c1276ece32 Mon Sep 17 00:00:00 2001 From: shaw Date: Sat, 5 Dec 2026 10:41:13 +0800 Subject: [PATCH 71/81] =?UTF-8?q?fix(ollama,=20billing):=20=E6=8B=A6?= =?UTF-8?q?=E6=88=AA=E6=9C=AA=E9=85=8D=E4=BB=B7=20claude=20=E5=87=BA?= =?UTF-8?q?=E7=AB=99=E6=A8=A1=E5=9E=8B=E5=B9=B6=E5=AF=B9=E9=BD=90=E8=AE=A1?= =?UTF-8?q?=E8=B4=B9=E9=85=8D=E9=A2=9D=E5=B9=B3=E5=8F=B0=E3=80=81=E8=BF=9E?= =?UTF-8?q?=E6=8E=A5=E6=B5=8B=E8=AF=95=E4=B8=8E=E7=9B=91=E6=8E=A7=E4=BD=99?= =?UTF-8?q?=E9=A2=9D=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, From b89c2c98c78e059d3cc1ee255036c0957096c75e Mon Sep 17 00:00:00 2001 From: shaw Date: Sat, 5 Dec 2026 10:41:13 +0800 Subject: [PATCH 72/81] =?UTF-8?q?fix(gateway):=20=E8=A1=A5=E9=BD=90?= =?UTF-8?q?=E8=B7=A8=E6=97=8F=E8=B4=A6=E5=8F=B7=E6=B1=A0=20compact=20?= =?UTF-8?q?=E8=B7=AF=E7=94=B1=E3=80=81=E7=94=9F=E5=9B=BE=E9=97=A8=E7=A6=81?= =?UTF-8?q?=E3=80=81=E6=8E=A8=E7=90=86=E5=BC=BA=E5=BA=A6=E7=AD=96=E7=95=A5?= =?UTF-8?q?=E4=B8=8E=E6=B5=81=E5=BC=8F=E9=94=99=E8=AF=AF=E8=BE=93=E5=87=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../internal/handler/composite_platform.go | 8 ++- ...site_pool_reasoning_policy_generic_test.go | 49 +++++++++++++++++++ backend/internal/handler/gateway_handler.go | 10 ++-- .../gateway_handler_chat_completions.go | 11 ++++- .../handler/gateway_handler_responses.go | 27 ++++++++-- .../handler/openai_chat_completions.go | 4 +- .../handler/openai_gateway_handler.go | 8 +-- backend/internal/server/routes/gateway.go | 19 +++++++ ...ateway_composite_pool_continuation_test.go | 36 ++++++++++++++ .../gateway_composite_pool_policy_test.go | 5 ++ 10 files changed, 162 insertions(+), 15 deletions(-) diff --git a/backend/internal/handler/composite_platform.go b/backend/internal/handler/composite_platform.go index 7d084186a8..a4266ea89b 100644 --- a/backend/internal/handler/composite_platform.go +++ b/backend/internal/handler/composite_platform.go @@ -314,8 +314,12 @@ func applyCompositePoolReasoningEffortPolicyForSelectedAccount(c *gin.Context, a if _, isPool := compositeAccountPoolCandidates(c); !isPool { return body, false, nil } - if account.Platform != service.PlatformOpenAI { + if account.Platform != service.PlatformOpenAI && account.Platform != service.PlatformAnthropic { return body, false, nil } - return service.ApplyOpenAIReasoningEffortPolicy(body, apiKey.Group.MaxReasoningEffort, apiKey.Group.ReasoningEffortMappings, apiKey.Group.MaxReasoningEffortOverLimit) + maxEffort, mappings := apiKey.Group.MaxReasoningEffort, apiKey.Group.ReasoningEffortMappings + if account.Platform == service.PlatformAnthropic { + maxEffort, mappings = anthropicCompatibleReasoningEffortPolicy(maxEffort, mappings) + } + return service.ApplyOpenAIReasoningEffortPolicy(body, maxEffort, mappings, apiKey.Group.MaxReasoningEffortOverLimit) } diff --git a/backend/internal/handler/composite_pool_reasoning_policy_generic_test.go b/backend/internal/handler/composite_pool_reasoning_policy_generic_test.go index e0000dd1aa..1e68d64b83 100644 --- a/backend/internal/handler/composite_pool_reasoning_policy_generic_test.go +++ b/backend/internal/handler/composite_pool_reasoning_policy_generic_test.go @@ -124,3 +124,52 @@ func TestCompositeCrossFamilyPoolMessagesAppliesReasoningEffortCapToAnthropic(t require.Len(t, calls, 1) require.Equal(t, "medium", gjson.GetBytes(calls[0].Body, "output_config.effort").String(), "upstream body=%s", calls[0].Body) } + +// 跨族池在 /v1/responses 与 /v1/chat/completions 选中 anthropic 账号时,同样须补齐 +// 分组推理强度策略(含 deny 拦截)。 +func TestCompositeCrossFamilyPoolTextEndpointsApplyReasoningEffortPolicyToAnthropic(t *testing.T) { + for _, tc := range []struct { + name, path, body string + }{ + { + name: "responses", + path: "/v1/responses", + body: `{"model":"my-model","stream":false,"input":"hello","reasoning":{"effort":"high"}}`, + }, + { + name: "chat_completions", + path: "/v1/chat/completions", + body: `{"model":"my-model","stream":false,"messages":[{"role":"user","content":"hello"}],"reasoning_effort":"high"}`, + }, + } { + t.Run(tc.name, func(t *testing.T) { + h := newCompositePoolMessagesHarness(t, []*service.Account{poolAnthropicAccount(44203, 41011, 0)}) + h.group.MaxReasoningEffort = "low" + h.group.MaxReasoningEffortOverLimit = "deny" + + c, rec := h.newRequest(t, tc.path, tc.body, service.PlatformAnthropic, service.PlatformOpenAI) + if tc.path == "/v1/responses" { + h.handler.Responses(c) + } else { + h.handler.ChatCompletions(c) + } + require.Equal(t, http.StatusForbidden, rec.Code, rec.Body.String()) + require.Empty(t, h.gwUpstream.snapshot()) + }) + } +} + +// 跨族池 /v1/responses 在分组禁用生图时,须拦截显式生图工具请求,不得经委派绕过。 +func TestCompositeCrossFamilyPoolResponsesEnforcesGroupImageGenerationGate(t *testing.T) { + h := newCompositePoolMessagesHarness(t, []*service.Account{poolOpenAIAccount(44204, 41011, 0)}) + h.group.AllowImageGeneration = false + + c, rec := h.newRequest(t, "/v1/responses", + `{"model":"my-model","stream":false,"input":"draw a cat","tools":[{"type":"image_generation"}]}`, + service.PlatformAnthropic, service.PlatformOpenAI) + h.handler.Responses(c) + + require.Equal(t, http.StatusForbidden, rec.Code, rec.Body.String()) + require.Contains(t, rec.Body.String(), service.ImageGenerationPermissionMessage()) + require.Empty(t, h.openAIUpstream.snapshot()) +} diff --git a/backend/internal/handler/gateway_handler.go b/backend/internal/handler/gateway_handler.go index 2133465516..535d346caf 100644 --- a/backend/internal/handler/gateway_handler.go +++ b/backend/internal/handler/gateway_handler.go @@ -812,18 +812,21 @@ func (h *GatewayHandler) Messages(c *gin.Context) { } // 账号池选中 anthropic 账号:按单目标 anthropic 语义补齐分组推理强度策略(放在槽位获取前)。 if isPoolRequest { + streamAwareWrite := func(cc *gin.Context, status int, code, message string) { + h.handleStreamingAwareError(cc, status, code, message, streamStarted) + } cappedBody, changed, policyErr := applyCompositePoolAnthropicReasoningEffortPolicy(apiKey, account, attemptParsedReq.Body.Bytes()) if policyErr != nil { releaseCompositePoolSelection(selection) h.gatewayService.ReleaseAccountSession(context.Background(), account, sessionKey) - respondOpenAIReasoningEffortPolicyError(c, policyErr, h.errorResponse) + respondOpenAIReasoningEffortPolicyError(c, policyErr, streamAwareWrite) return } if changed { if err := attemptParsedReq.ReplaceBody(cappedBody); err != nil { releaseCompositePoolSelection(selection) h.gatewayService.ReleaseAccountSession(context.Background(), account, sessionKey) - h.errorResponse(c, http.StatusBadRequest, "invalid_request_error", "Failed to apply reasoning effort policy") + streamAwareWrite(c, http.StatusBadRequest, "invalid_request_error", "Failed to apply reasoning effort policy") return } } @@ -1020,7 +1023,8 @@ func (h *GatewayHandler) Messages(c *gin.Context) { // 渠道定价作用域与计费 QuotaPlatform 跟随实际平台,对齐 OpenAI 池 attempt 语义。 if isPoolRequest { requestCtx = compositePoolAttemptContext(requestCtx, account) - } else if channelMapping.Mapped { + } + if attemptChannelMapping.Mapped { // 选号按客户端模型,转发按渠道映射后的模型:模型级账号状态按选号模型记录。 requestCtx = service.WithGatewaySchedulingModel(requestCtx, reqModel) } diff --git a/backend/internal/handler/gateway_handler_chat_completions.go b/backend/internal/handler/gateway_handler_chat_completions.go index f4f25b3b18..803616d583 100644 --- a/backend/internal/handler/gateway_handler_chat_completions.go +++ b/backend/internal/handler/gateway_handler_chat_completions.go @@ -367,14 +367,21 @@ func (h *GatewayHandler) ChatCompletions(c *gin.Context) { if attemptChannelMapping.Mapped { forwardBody = h.gatewayService.ReplaceModelInBody(body, attemptChannelMapping.MappedModel) } - // 账号池按选中账号应用分组推理强度策略(与 OpenAI handler 同语义,仅 openai 账号)。 + // 账号池按选中账号应用分组推理强度策略(与单目标同语义,覆盖 openai / anthropic 账号)。 if isPoolRequest { cappedBody, changed, policyErr := applyCompositePoolReasoningEffortPolicyForSelectedAccount(c, apiKey, account, forwardBody) if policyErr != nil { if accountReleaseFunc != nil { accountReleaseFunc() } - respondOpenAIReasoningEffortPolicyError(c, policyErr, h.chatCompletionsErrorResponse) + streamAwareWrite := func(cc *gin.Context, status int, code, message string) { + if streamStarted { + h.handleStreamingAwareError(cc, status, code, message, true) + return + } + h.chatCompletionsErrorResponse(cc, status, code, message) + } + respondOpenAIReasoningEffortPolicyError(c, policyErr, streamAwareWrite) return } if changed { diff --git a/backend/internal/handler/gateway_handler_responses.go b/backend/internal/handler/gateway_handler_responses.go index 0b7ed3fad2..47f2841d23 100644 --- a/backend/internal/handler/gateway_handler_responses.go +++ b/backend/internal/handler/gateway_handler_responses.go @@ -130,6 +130,13 @@ func (h *GatewayHandler) Responses(c *gin.Context) { h.responsesErrorResponse(c, http.StatusBadRequest, "invalid_request_error", service.ImageGenerationPermissionMessage()) return } + if apiKey.Group != nil && apiKey.Group.Platform == service.PlatformComposite && + service.IsExplicitImageGenerationIntentValidated("/v1/responses", reqModel, body) && + !service.GroupAllowsImageGeneration(apiKey.Group) { + service.MarkOpsClientBusinessLimited(c, service.OpsClientBusinessLimitedReasonLocalFeatureGate) + h.responsesErrorResponse(c, http.StatusForbidden, "permission_error", service.ImageGenerationPermissionMessage()) + return + } if decision := h.checkSecurityAudit(c, reqLog, apiKey, subject, service.ContentModerationProtocolOpenAIResponses, reqModel, body); decision != nil && !decision.AllowNextStage { h.responsesSecurityAuditError(c, decision) @@ -280,8 +287,13 @@ func (h *GatewayHandler) Responses(c *gin.Context) { poolDenials.deny(account.Platform) fs.FailedAccountIDs[account.ID] = struct{}{} if _, ok := compositePoolSelectionRetryContext(requestCtx, poolDenials); !ok { - h.responsesErrorResponse(c, http.StatusBadRequest, "invalid_request_error", - "Model is only available on Gemini accounts in this group, which do not support /v1/responses") + if streamStarted { + h.handleStreamingAwareError(c, http.StatusBadRequest, "invalid_request_error", + "Model is only available on Gemini accounts in this group, which do not support /v1/responses", true) + } else { + h.responsesErrorResponse(c, http.StatusBadRequest, "invalid_request_error", + "Model is only available on Gemini accounts in this group, which do not support /v1/responses") + } return } continue @@ -382,14 +394,21 @@ func (h *GatewayHandler) Responses(c *gin.Context) { if attemptChannelMapping.Mapped { forwardBody = h.gatewayService.ReplaceModelInBody(body, attemptChannelMapping.MappedModel) } - // 账号池按选中账号应用分组推理强度策略(与 OpenAI handler 同语义,仅 openai 账号)。 + // 账号池按选中账号应用分组推理强度策略(与单目标同语义,覆盖 openai / anthropic 账号)。 if isPoolRequest { cappedBody, changed, policyErr := applyCompositePoolReasoningEffortPolicyForSelectedAccount(c, apiKey, account, forwardBody) if policyErr != nil { if accountReleaseFunc != nil { accountReleaseFunc() } - respondOpenAIReasoningEffortPolicyError(c, policyErr, h.responsesErrorResponse) + streamAwareWrite := func(cc *gin.Context, status int, code, message string) { + if streamStarted { + h.handleStreamingAwareError(cc, status, code, message, true) + return + } + h.responsesErrorResponse(cc, status, code, message) + } + respondOpenAIReasoningEffortPolicyError(c, policyErr, streamAwareWrite) return } if changed { diff --git a/backend/internal/handler/openai_chat_completions.go b/backend/internal/handler/openai_chat_completions.go index fbbc204dc3..a06f9fd996 100644 --- a/backend/internal/handler/openai_chat_completions.go +++ b/backend/internal/handler/openai_chat_completions.go @@ -252,7 +252,9 @@ func (h *OpenAIGatewayHandler) ChatCompletions(c *gin.Context) { poolPolicyBody := body if cappedBody, changed, err := applyCompositePoolReasoningEffortPolicyForSelectedAccount(c, apiKey, account, body); err != nil { releaseCompositePoolSelection(selection) - respondOpenAIReasoningEffortPolicyError(c, err, h.errorResponse) + respondOpenAIReasoningEffortPolicyError(c, err, func(cc *gin.Context, status int, code, message string) { + h.handleStreamingAwareError(cc, status, code, message, streamStarted) + }) return } else if changed { poolPolicyBody = cappedBody diff --git a/backend/internal/handler/openai_gateway_handler.go b/backend/internal/handler/openai_gateway_handler.go index 71fc939e77..32c196366f 100644 --- a/backend/internal/handler/openai_gateway_handler.go +++ b/backend/internal/handler/openai_gateway_handler.go @@ -852,8 +852,8 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) { "the account that owns previous_response_id is temporarily unavailable; retry later", streamStarted) return } - h.errorResponse(c, http.StatusBadRequest, "invalid_request_error", - "previous_response_id belongs to a response owned by a different account; continue on the account that owns this response state or start a new response") + h.handleStreamingAwareError(c, http.StatusBadRequest, "invalid_request_error", + "previous_response_id belongs to a response owned by a different account; continue on the account that owns this response state or start a new response", streamStarted) return } // 仅实际 openai 平台账号要求 API-key 才支持 HTTP continuation; @@ -895,7 +895,9 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) { poolPolicyBody := forwardBody if cappedBody, changed, err := applyCompositePoolReasoningEffortPolicyForSelectedAccount(c, apiKey, account, forwardBody); err != nil { releaseCompositePoolSelection(selection) - respondOpenAIReasoningEffortPolicyError(c, err, h.errorResponse) + respondOpenAIReasoningEffortPolicyError(c, err, func(cc *gin.Context, status int, code, message string) { + h.handleStreamingAwareError(cc, status, code, message, streamStarted) + }) return } else if changed { poolPolicyBody = cappedBody diff --git a/backend/internal/server/routes/gateway.go b/backend/internal/server/routes/gateway.go index c530efaf12..322efbda0e 100644 --- a/backend/internal/server/routes/gateway.go +++ b/backend/internal/server/routes/gateway.go @@ -711,6 +711,14 @@ func compositeTargetPlatformMiddleware(resolver *service.CompositeRouteResolver) writeCompositeRouteAdmissionError(c, http.StatusBadRequest, fmt.Sprintf("Model %q has no OpenAI-compatible account in this composite group to continue previous_response_id; resend the full conversation without previous_response_id", model)) return } + } else if isCompositePoolResponsesCompact(c, decision) { + // /responses/compact 仅由 OpenAI 网关链支持(含 compact 归一化、渠道限制与心跳): + // 跨族候选池收窄到 OpenAI 兼容族,避免落入通用网关按普通 Responses 误转协议。 + decision.CandidatePlatforms = openAICompatibleCandidatePlatforms(decision.CandidatePlatforms) + if len(decision.CandidatePlatforms) == 0 { + writeCompositeRouteAdmissionError(c, http.StatusBadRequest, fmt.Sprintf("Model %q has no OpenAI-compatible account in this composite group to support /responses/compact", model)) + return + } } c.Request = c.Request.WithContext(service.WithCompositeRouteDecision(c.Request.Context(), decision)) if upstreamModel := strings.TrimSpace(decision.UpstreamModel); upstreamModel != "" && upstreamModel != model && gjson.ValidBytes(body) { @@ -796,6 +804,17 @@ func isCompositePoolResponsesContinuation(c *gin.Context, decision service.Compo return strings.TrimSpace(gjson.GetBytes(body, "previous_response_id").String()) != "" } +func isCompositePoolResponsesCompact(c *gin.Context, decision service.CompositeRouteDecision) bool { + if c == nil || c.Request == nil || c.Request.URL == nil { + return false + } + if strings.TrimSpace(decision.TargetPlatform) != "" || len(decision.CandidatePlatforms) == 0 { + return false + } + path := strings.TrimRight(c.Request.URL.Path, "/") + return strings.HasSuffix(path, "/responses/compact") +} + // openAICompatibleCandidatePlatforms 返回候选平台中经 OpenAI 网关转发的平台(保持顺序)。 func openAICompatibleCandidatePlatforms(candidates []string) []string { out := make([]string, 0, len(candidates)) diff --git a/backend/internal/server/routes/gateway_composite_pool_continuation_test.go b/backend/internal/server/routes/gateway_composite_pool_continuation_test.go index 7765fa8b4e..8f9915eb78 100644 --- a/backend/internal/server/routes/gateway_composite_pool_continuation_test.go +++ b/backend/internal/server/routes/gateway_composite_pool_continuation_test.go @@ -94,3 +94,39 @@ func TestCompositePoolContinuationWithoutOpenAICompatibleCandidateRejected(t *te require.Contains(t, w.Body.String(), "previous_response_id") require.Empty(t, upstream.capturedSnapshot()) } + +// 跨族账号池访问 /v1/responses/compact:候选池收窄到 OpenAI 兼容族交由 OpenAI handler +// 处理,优先级更高的 Anthropic 账号不会收到 compact 请求;无兼容族候选时入口明确拒绝。 +func TestCompositeCrossFamilyPoolCompactNarrowsToOpenAICompatible(t *testing.T) { + upstream := &captureUpstream{} + openai := newPoolPolicyAccountWithMapping(4331, service.PlatformOpenAI, 5, map[string]any{"compact-model": "gpt-5.4"}) + anthropic := newPoolPolicyAccountWithMapping(4332, service.PlatformAnthropic, 0, map[string]any{"compact-model": "claude-sonnet-4-5"}) + router, _ := newCompositePoolPolicyTestRouter(t, poolPolicyRouterInput{ + group: newPoolPolicyGroup(nil), + accounts: []service.Account{openai, anthropic}, + upstream: upstream, + }) + + w := postPoolPolicyRequest(t, router, "/v1/responses/compact", + `{"model":"compact-model","input":"compact this"}`) + require.Equal(t, http.StatusOK, w.Code, w.Body.String()) + captured := upstream.capturedSnapshot() + require.Len(t, captured, 1) + require.Equal(t, "openai-pool-fake.test", captured[0].host) + require.True(t, strings.HasSuffix(captured[0].path, "/responses/compact"), "path=%q", captured[0].path) + + upstreamNone := &captureUpstream{} + routerNone, _ := newCompositePoolPolicyTestRouter(t, poolPolicyRouterInput{ + group: newPoolPolicyGroup(nil), + accounts: []service.Account{ + newPoolPolicyAccountWithMapping(4333, service.PlatformAnthropic, 0, map[string]any{"np-compact": "claude-sonnet-4-5"}), + newPoolPolicyAccountWithMapping(4334, service.PlatformGemini, 1, map[string]any{"np-compact": "gemini-3.1-pro"}), + }, + upstream: upstreamNone, + }) + wNone := postPoolPolicyRequest(t, routerNone, "/v1/responses/compact", + `{"model":"np-compact","input":"compact this"}`) + require.Equal(t, http.StatusBadRequest, wNone.Code, wNone.Body.String()) + require.Contains(t, wNone.Body.String(), "/responses/compact") + require.Empty(t, upstreamNone.capturedSnapshot()) +} diff --git a/backend/internal/server/routes/gateway_composite_pool_policy_test.go b/backend/internal/server/routes/gateway_composite_pool_policy_test.go index af7df5f463..3e20023b75 100644 --- a/backend/internal/server/routes/gateway_composite_pool_policy_test.go +++ b/backend/internal/server/routes/gateway_composite_pool_policy_test.go @@ -165,6 +165,7 @@ func (c *stickyMemoryGatewayCache) GetReasoningContent(context.Context, string) type poolPolicyCapturedRequest struct { accountID int64 host string + path string body []byte } @@ -187,6 +188,7 @@ func (u *captureUpstream) capture(req *http.Request, accountID int64) []byte { u.captured = append(u.captured, poolPolicyCapturedRequest{ accountID: accountID, host: req.URL.Hostname(), + path: req.URL.Path, body: body, }) u.mu.Unlock() @@ -210,6 +212,9 @@ func (u *captureUpstream) respondFor(req *http.Request) *http.Response { Body: io.NopCloser(strings.NewReader(`{"error":{"message":"rate limited"}}`)), } } + if strings.HasSuffix(req.URL.Path, "/responses/compact") { + return compositeDispatchResponse("application/json", `{"id":"resp_compact","object":"response.compaction","output":[],"usage":{"input_tokens":1,"output_tokens":1,"total_tokens":2}}`) + } if strings.Contains(req.URL.Path, "/responses") { sse := "event: response.completed\n" + `data: {"type":"response.completed","response":{"id":"resp_pool","object":"response","status":"completed","model":"deepseek-chat","output":[{"type":"message","role":"assistant","content":[{"type":"output_text","text":"ok"}]}],"usage":{"input_tokens":1,"output_tokens":1,"total_tokens":2}}}` + "\n\n" From b54f4f155ae4d34de2d0cbfe48b22be19679846b Mon Sep 17 00:00:00 2001 From: shaw Date: Sat, 5 Dec 2026 10:41:13 +0800 Subject: [PATCH 73/81] =?UTF-8?q?fix(frontend):=20=E6=96=B0=E5=BB=BA=20oll?= =?UTF-8?q?ama=5Fcloud=20=E8=B4=A6=E5=8F=B7=E9=BB=98=E8=AE=A4=E9=A2=84?= =?UTF-8?q?=E5=A1=AB=E7=99=BD=E5=90=8D=E5=8D=95=E5=B9=B6=E6=94=B6=E6=95=9B?= =?UTF-8?q?=20credits=20=E6=A8=A1=E5=BC=8F=E8=A1=A8=E5=8D=95=E7=BB=86?= =?UTF-8?q?=E8=8A=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/components/account/CreateAccountModal.vue | 13 +++++++++++-- .../src/components/account/EditAccountModal.vue | 8 ++++---- .../src/components/account/OllamaCloudUsageCell.vue | 5 ++++- .../account/__tests__/CreateAccountModal.spec.ts | 3 +++ 4 files changed, 22 insertions(+), 7 deletions(-) diff --git a/frontend/src/components/account/CreateAccountModal.vue b/frontend/src/components/account/CreateAccountModal.vue index 6c6bd710f1..40997346fa 100644 --- a/frontend/src/components/account/CreateAccountModal.vue +++ b/frontend/src/components/account/CreateAccountModal.vue @@ -656,7 +656,7 @@ v-model="ollamaMonthlyCreditUsdInput" type="number" min="0" - step="1" + step="any" class="input" :placeholder="t('admin.accounts.ollamaCloud.accountMode.monthlyCreditUsdPlaceholder')" data-testid="ollama-monthly-credit-usd" @@ -4631,7 +4631,8 @@ const submitsViaGenericApiKeyPath = computed( const supportsCreateSchedulingThresholdOverride = computed( () => (SCHEDULING_THRESHOLD_PLATFORMS as readonly string[]).includes(form.platform) && - submitsViaGenericApiKeyPath.value + submitsViaGenericApiKeyPath.value && + !(form.platform === 'ollama_cloud' && ollamaAccountMode.value === 'ollama_credits') ) const genericAccountModes = computed(() => providerAccountModes(form.platform)) // 按模型分流的供应商(OpenCode 等):adaptive 账号携带 protocol_rules。 @@ -4751,6 +4752,8 @@ function selectOllamaCloudPlatform() { ollamaAccountMode.value = 'ollama_legacy' apiKeyBaseUrl.value = defaultCNBaseUrl('ollama_cloud', ollamaAccountMode.value, 'adaptive') resetAdaptiveBaseUrls('ollama_cloud', ollamaAccountMode.value) + modelRestrictionMode.value = 'whitelist' + allowedModels.value = [...getModelsByPlatform('ollama_cloud')] } function selectGenericMultiProtocolPlatform(platform: string) { form.platform = platform @@ -5399,6 +5402,12 @@ watch( modelRestrictionMode.value = 'whitelist' allowedModels.value = ['jev-latest'] } + if (newPlatform === 'ollama_cloud') { + // Ollama Cloud 后端保存期门禁拒绝空映射且无白名单的账号(防静默零计费), + // 默认预填平台已定价模型白名单,使默认建号路径直接满足保存期门禁。 + modelRestrictionMode.value = 'whitelist' + allowedModels.value = [...getModelsByPlatform('ollama_cloud')] + } // Antigravity: 默认使用映射模式并填充默认映射 if (newPlatform === 'antigravity') { antigravityModelRestrictionMode.value = 'mapping' diff --git a/frontend/src/components/account/EditAccountModal.vue b/frontend/src/components/account/EditAccountModal.vue index 447dd8eda0..1eab54094d 100644 --- a/frontend/src/components/account/EditAccountModal.vue +++ b/frontend/src/components/account/EditAccountModal.vue @@ -169,7 +169,7 @@ v-model="editOllamaMonthlyCreditUsd" type="number" min="0" - step="1" + step="any" class="input" :placeholder="t('admin.accounts.ollamaCloud.accountMode.monthlyCreditUsdPlaceholder')" data-testid="edit-ollama-monthly-credit-usd" @@ -4159,8 +4159,8 @@ const tempUnschedEnabled = ref(false) const accountSchedulingThresholdOverrideEnabled = ref(false) const accountSchedulingThresholdOverrideValue = ref(100) const ACCOUNT_SCHEDULING_THRESHOLD_CREDENTIAL_KEY = 'account_scheduling_threshold' -const supportsAccountSchedulingThresholdOverride = computed(() => - supportsAccountSchedulingThresholdOverridePlatform(props.account?.platform) +const supportsAccountSchedulingThresholdOverride = computed( + () => supportsAccountSchedulingThresholdOverridePlatform(props.account?.platform) && !isOllamaCreditsAccount.value ) const tempUnschedRules = ref([]) const getModelMappingKey = createStableObjectKeyResolver('edit-model-mapping') @@ -5410,7 +5410,7 @@ const applyAccountSchedulingThresholdOverridePatch = ( currentCredentials: Record, platform: Account['platform'] | undefined = props.account?.platform ) => { - if (!supportsAccountSchedulingThresholdOverridePlatform(platform)) { + if (!supportsAccountSchedulingThresholdOverridePlatform(platform) || isOllamaCreditsAccount.value) { return } const current = normalizeAccountSchedulingThresholdOverride( diff --git a/frontend/src/components/account/OllamaCloudUsageCell.vue b/frontend/src/components/account/OllamaCloudUsageCell.vue index 9935f0a94b..bbf33115cd 100644 --- a/frontend/src/components/account/OllamaCloudUsageCell.vue +++ b/frontend/src/components/account/OllamaCloudUsageCell.vue @@ -104,7 +104,10 @@ const isCredits = computed(() => state.value?.mode === 'ollama_credits') const balanceNumber = computed(() => { const raw = snapshot.value?.data?.balance if (!raw) return null - const parsed = Number.parseFloat(raw.replace(/[^0-9.]/g, '')) + const cleaned = raw.replace(/[^0-9.-]/g, '') + const match = cleaned.match(/^-?\d+(?:\.\d+)?/) + if (!match) return null + const parsed = Number.parseFloat(match[0]) return Number.isFinite(parsed) ? parsed : null }) diff --git a/frontend/src/components/account/__tests__/CreateAccountModal.spec.ts b/frontend/src/components/account/__tests__/CreateAccountModal.spec.ts index 15542f3984..7f858cb2a6 100644 --- a/frontend/src/components/account/__tests__/CreateAccountModal.spec.ts +++ b/frontend/src/components/account/__tests__/CreateAccountModal.spec.ts @@ -1249,6 +1249,9 @@ describe('CreateAccountModal Ollama Cloud protocol and quota mode', () => { } }) expect('monthly_credit_usd' in credentials).toBe(false) + // 默认预填平台已定价模型白名单,对齐后端 validateOllamaCloudAccountModelPricingGate 门禁 + expect(credentials?.model_mapping).toBeDefined() + expect(Object.keys(credentials?.model_mapping as Record).length).toBeGreaterThan(0) }) it('prefills the locked anthropic protocol endpoint without the /v1 suffix', async () => { From 06ea8a21dcb6fb9fdd0a924208a57dcda0f2e071 Mon Sep 17 00:00:00 2001 From: shaw Date: Sat, 5 Dec 2026 12:10:27 +0800 Subject: [PATCH 74/81] =?UTF-8?q?fix(composite,=20billing):=20=E4=BF=AE?= =?UTF-8?q?=E5=A4=8D=E8=B4=A6=E5=8F=B7=E6=B1=A0=E5=9C=A8=E9=80=94=E9=A2=84?= =?UTF-8?q?=E7=95=99=E6=9F=A5=E6=A1=B6=E3=80=81=E9=99=8D=E7=BA=A7=E5=88=86?= =?UTF-8?q?=E7=BB=84=E4=B8=8A=E4=B8=8B=E6=96=87=E6=AE=8B=E7=95=99=E4=B8=8E?= =?UTF-8?q?=E6=B8=A0=E9=81=93=E6=A8=A1=E5=9E=8B=E9=99=90=E5=88=B6=E4=BD=9C?= =?UTF-8?q?=E7=94=A8=E5=9F=9F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../handler/composite_pool_attempt_policy.go | 11 +++- backend/internal/handler/gateway_handler.go | 16 +++-- .../gateway_handler_chat_completions.go | 4 +- .../handler/gateway_handler_responses.go | 4 +- .../handler/openai_chat_completions.go | 4 +- .../handler/openai_gateway_handler.go | 8 ++- ...eway_composite_pool_attempt_policy_test.go | 53 ++++++++++++++++ .../service/billing_inflight_reservation.go | 37 +++++++----- .../internal/service/composite_platform.go | 16 +++++ .../internal/service/composite_pool_policy.go | 60 +++++++++++++++---- backend/internal/service/gateway_forward.go | 13 +++- .../internal/service/gateway_scheduling.go | 11 +++- .../service/openai_gateway_scheduling.go | 3 +- .../service/openai_gateway_service.go | 25 +++++++- 14 files changed, 222 insertions(+), 43 deletions(-) diff --git a/backend/internal/handler/composite_pool_attempt_policy.go b/backend/internal/handler/composite_pool_attempt_policy.go index 290489e1d5..dc996f6dba 100644 --- a/backend/internal/handler/composite_pool_attempt_policy.go +++ b/backend/internal/handler/composite_pool_attempt_policy.go @@ -138,12 +138,19 @@ type compositePoolAttemptPolicyFailure struct { // ChannelRestricted 表示该模型在选中平台作用域下被渠道定价限制拒绝,按调度 // 阶段渠道限制同语义终止(账号存在且模型受支持,仅当前平台被限制)。 ChannelRestricted bool + // AccountChannelRestricted 表示限制仅来自当前账号映射后的 upstream 模型, + // 重选时只排除该账号,不整平台屏蔽同平台其它账号。 + AccountChannelRestricted bool } func (f compositePoolAttemptPolicyFailure) denied() bool { return f.QuotaErr != nil || f.ChannelRestricted } +func (f compositePoolAttemptPolicyFailure) deniesPlatform() bool { + return f.QuotaErr != nil || (f.ChannelRestricted && !f.AccountChannelRestricted) +} + // compositePoolAttemptPolicy 汇总一次 attempt 的策略检查结果。 type compositePoolAttemptPolicy struct { // AttemptCtx 仅供该 attempt 的渠道/计费/forward 使用;不写回 c.Request。 @@ -187,7 +194,9 @@ func evaluateCompositePoolAttemptPolicy( } if gateway != nil && apiKey != nil && apiKey.GroupID != nil { result.Mapping = gateway.CompositePoolAttemptChannelMapping(result.AttemptCtx, apiKey.GroupID, requestedModel) - result.Failure.ChannelRestricted = gateway.CompositePoolAttemptChannelRestricted(result.AttemptCtx, apiKey.GroupID, account, requestedModel, requireCompact) + platformRestricted, accountRestricted := gateway.CompositePoolAttemptChannelRestriction(result.AttemptCtx, apiKey.GroupID, account, requestedModel, requireCompact) + result.Failure.ChannelRestricted = platformRestricted || accountRestricted + result.Failure.AccountChannelRestricted = accountRestricted && !platformRestricted } return result } diff --git a/backend/internal/handler/gateway_handler.go b/backend/internal/handler/gateway_handler.go index 535d346caf..63fbcfa396 100644 --- a/backend/internal/handler/gateway_handler.go +++ b/backend/internal/handler/gateway_handler.go @@ -789,15 +789,17 @@ func (h *GatewayHandler) Messages(c *gin.Context) { // 候选全部被业务限制时按原语义终止,不误报 model unsupported。 attemptPolicy := compositePoolAttemptPolicy{AttemptCtx: c.Request.Context(), Mapping: channelMapping} isPoolAttempt := false - if isPoolRequest && compositePoolAttemptPolicyApplies(c, apiKey) { + if isPoolRequest && compositePoolAttemptPolicyApplies(c, currentAPIKey) { attemptPolicy = evaluateCompositePoolAttemptPolicy( - c.Request.Context(), h.billingCacheService, h.openAIGatewayService, apiKey, subscription, account, reqModel, false) + c.Request.Context(), h.billingCacheService, h.openAIGatewayService, currentAPIKey, currentSubscription, account, reqModel, false) isPoolAttempt = true if attemptPolicy.Failure.denied() { releaseCompositePoolSelection(selection) // 选号链可能已为该账号注册会话槽:排除前释放,镜像 profit-veto 分支。 h.gatewayService.ReleaseAccountSession(context.Background(), account, sessionKey) - poolDenials.deny(account.Platform) + if attemptPolicy.Failure.deniesPlatform() { + poolDenials.deny(account.Platform) + } fs.FailedAccountIDs[account.ID] = struct{}{} // 候选全部被业务限制:按 deny 原因明确终止(后续重选不再尝试)。 if _, ok := compositePoolSelectionRetryContext(c.Request.Context(), poolDenials); !ok { @@ -815,7 +817,7 @@ func (h *GatewayHandler) Messages(c *gin.Context) { streamAwareWrite := func(cc *gin.Context, status int, code, message string) { h.handleStreamingAwareError(cc, status, code, message, streamStarted) } - cappedBody, changed, policyErr := applyCompositePoolAnthropicReasoningEffortPolicy(apiKey, account, attemptParsedReq.Body.Bytes()) + cappedBody, changed, policyErr := applyCompositePoolAnthropicReasoningEffortPolicy(currentAPIKey, account, attemptParsedReq.Body.Bytes()) if policyErr != nil { releaseCompositePoolSelection(selection) h.gatewayService.ReleaseAccountSession(context.Background(), account, sessionKey) @@ -1203,11 +1205,13 @@ func (h *GatewayHandler) Messages(c *gin.Context) { h.handleStreamingAwareError(c, status, code, message, streamStarted) return } - // 兜底重试按"直接请求兜底分组"处理:清除强制平台,允许按分组平台调度 - ctx := context.WithValue(c.Request.Context(), ctxkey.ForcePlatform, "") + // 兜底重试按"直接请求兜底分组"处理:清除强制平台与原分组的 composite 路由/池上下文,允许按兜底分组调度 + ctx := service.WithoutCompositeRouteContext(context.WithValue(c.Request.Context(), ctxkey.ForcePlatform, "")) c.Request = c.Request.WithContext(ctx) currentAPIKey = fallbackAPIKey currentSubscription = nil + isPoolRequest = false + poolDenials = newCompositePoolPlatformDenials() fallbackUsed = true retryWithFallback = true // 原分组账号已确定性失败(prompt too long),先释放其会话注册再走兜底分组 diff --git a/backend/internal/handler/gateway_handler_chat_completions.go b/backend/internal/handler/gateway_handler_chat_completions.go index 803616d583..f11d0e9943 100644 --- a/backend/internal/handler/gateway_handler_chat_completions.go +++ b/backend/internal/handler/gateway_handler_chat_completions.go @@ -283,7 +283,9 @@ func (h *GatewayHandler) ChatCompletions(c *gin.Context) { // 选号链可能已为该账号注册会话槽(键与选号一致):排除前释放 //(镜像 Messages 池分支)。 h.gatewayService.ReleaseAccountSession(context.Background(), account, selectionSessionHash) - poolDenials.deny(account.Platform) + if attemptPolicy.Failure.deniesPlatform() { + poolDenials.deny(account.Platform) + } fs.FailedAccountIDs[account.ID] = struct{}{} // 候选全部被业务限制:按 deny 原因明确终止(后续重选不再尝试)。 if _, ok := compositePoolSelectionRetryContext(c.Request.Context(), poolDenials); !ok { diff --git a/backend/internal/handler/gateway_handler_responses.go b/backend/internal/handler/gateway_handler_responses.go index 47f2841d23..4995af3cff 100644 --- a/backend/internal/handler/gateway_handler_responses.go +++ b/backend/internal/handler/gateway_handler_responses.go @@ -316,7 +316,9 @@ func (h *GatewayHandler) Responses(c *gin.Context) { releaseCompositePoolSelection(selection) // 选号链可能已为该账号注册会话槽:排除前释放(镜像 Messages 池分支)。 h.gatewayService.ReleaseAccountSession(context.Background(), account, sessionHash) - poolDenials.deny(account.Platform) + if attemptPolicy.Failure.deniesPlatform() { + poolDenials.deny(account.Platform) + } fs.FailedAccountIDs[account.ID] = struct{}{} // 候选全部被业务限制:按 deny 原因明确终止(后续重选不再尝试)。 if _, ok := compositePoolSelectionRetryContext(requestCtx, poolDenials); !ok { diff --git a/backend/internal/handler/openai_chat_completions.go b/backend/internal/handler/openai_chat_completions.go index a06f9fd996..794ea77feb 100644 --- a/backend/internal/handler/openai_chat_completions.go +++ b/backend/internal/handler/openai_chat_completions.go @@ -279,7 +279,9 @@ func (h *OpenAIGatewayHandler) ChatCompletions(c *gin.Context) { streamAwareWrite := func(cc *gin.Context, status int, code, message string) { h.handleStreamingAwareError(cc, status, code, message, streamStarted) } - poolDenials.deny(account.Platform) + if attemptPolicy.Failure.deniesPlatform() { + poolDenials.deny(account.Platform) + } // 同时排除该账号:下一轮 masked ctx 下 sticky 层对 excluded 账号 // 提前返回(不 clear),不会把原 sticky 账号当 platform mismatch // 清掉粘性绑定;其它平台成功后按用户目标正常改绑。 diff --git a/backend/internal/handler/openai_gateway_handler.go b/backend/internal/handler/openai_gateway_handler.go index 32c196366f..900bbea1b9 100644 --- a/backend/internal/handler/openai_gateway_handler.go +++ b/backend/internal/handler/openai_gateway_handler.go @@ -927,7 +927,9 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) { respondCompositePoolAttemptPolicyFailure(c, attemptPolicy.Failure, streamAwareWrite) return } - poolDenials.deny(account.Platform) + if attemptPolicy.Failure.deniesPlatform() { + poolDenials.deny(account.Platform) + } // 同时排除该账号:下一轮 masked ctx 下 sticky 层对 excluded 账号 // 提前返回(不 clear),不会把原 sticky 账号当 platform mismatch // 清掉粘性绑定;其它平台成功后按用户目标正常改绑。 @@ -1591,7 +1593,9 @@ func (h *OpenAIGatewayHandler) Messages(c *gin.Context) { isPoolAttemptMsg = true if attemptPolicyMsg.Failure.denied() { releaseCompositePoolSelection(selection) - poolDenials.deny(account.Platform) + if attemptPolicyMsg.Failure.deniesPlatform() { + poolDenials.deny(account.Platform) + } // 同时排除该账号:下一轮 masked ctx 下 sticky 层对 excluded 账号 // 提前返回(不 clear),不清掉原 sticky 粘性绑定。 failedAccountIDs[account.ID] = struct{}{} diff --git a/backend/internal/server/routes/gateway_composite_pool_attempt_policy_test.go b/backend/internal/server/routes/gateway_composite_pool_attempt_policy_test.go index 71c7cdc031..fe1c05943e 100644 --- a/backend/internal/server/routes/gateway_composite_pool_attempt_policy_test.go +++ b/backend/internal/server/routes/gateway_composite_pool_attempt_policy_test.go @@ -822,3 +822,56 @@ func TestCompositePoolAttemptPolicyDenyWithSiblingAccountsKeepsBinding(t *testin "after a successful take-over the sticky binding is updated normally via Set") } } + +// ── 8) BillingModelSource=upstream 逐账号限制只排除受限账号,不屏蔽同平台合法兄弟号 ─ +func TestCompositePoolAttemptPolicyUpstreamRestrictionDoesNotMaskSiblingAccount(t *testing.T) { + now := time.Now().UTC() + quotaCache := &attemptPolicyQuotaCache{entries: map[string]*service.UserPlatformQuotaCacheEntry{ + service.PlatformDeepseek: allowedAttemptPolicyEntry(now), + service.PlatformOpenAI: allowedAttemptPolicyEntry(now), + }} + upstream := &attemptPolicyUpstream{} + channel := &service.Channel{ + ID: 1, + Status: service.StatusActive, + GroupIDs: []int64{attemptPolicyGroupID}, + RestrictModels: true, + BillingModelSource: service.BillingModelSourceUpstream, + ModelMapping: map[string]map[string]string{ + service.PlatformAnthropic: {"deepseek-flash": "unlisted-claude"}, + service.PlatformDeepseek: {"deepseek-flash": "deepseek-mid"}, + }, + ModelPricing: []service.ChannelModelPricing{ + {Platform: service.PlatformDeepseek, Models: []string{"deepseek-allowed"}}, + }, + } + // 4341(deepseek priority 1):映射为受限的 deepseek-blocked; + // 4342(deepseek priority 2):经渠道映射 deepseek-mid → deepseek-allowed(合法); + // 4343(openai priority 3):映射为受限的 gpt-blocked(用于凑成双平台池)。 + router := newCompositePoolAttemptPolicyRouter(t, attemptPolicyRouterInput{ + accounts: []service.Account{ + newAttemptPolicyAccount(4341, service.PlatformDeepseek, 1, map[string]any{ + "deepseek-flash": "deepseek-blocked", + "deepseek-mid": "deepseek-blocked", + }), + newAttemptPolicyAccount(4342, service.PlatformDeepseek, 2, map[string]any{ + "deepseek-flash": "deepseek-allowed", + "deepseek-mid": "deepseek-allowed", + }), + newAttemptPolicyAccount(4343, service.PlatformOpenAI, 3, map[string]any{ + "deepseek-flash": "gpt-blocked", + }), + }, + quotaCache: quotaCache, + upstream: upstream, + channel: channel, + }) + + w := postAttemptPolicyRequest(t, router, "/v1/chat/completions", + `{"model":"deepseek-flash","messages":[{"role":"user","content":"hi"}],"stream":false}`) + require.Equal(t, http.StatusOK, w.Code, w.Body.String()) + captured := upstream.snapshot() + require.Len(t, captured, 1) + require.Contains(t, captured[0].host, "deepseek-pool-fake.test") + require.Equal(t, "deepseek-allowed", gjson.GetBytes(captured[0].body, "model").String()) +} diff --git a/backend/internal/service/billing_inflight_reservation.go b/backend/internal/service/billing_inflight_reservation.go index fcda8e3c6a..d2b43ca566 100644 --- a/backend/internal/service/billing_inflight_reservation.go +++ b/backend/internal/service/billing_inflight_reservation.go @@ -404,8 +404,8 @@ type inflightEstimateDeps struct { type inflightSnapshotLister func(ctx context.Context, groupID *int64, platform string, hasForcePlatform bool) ([]Account, error) // inflightAccountMappedModelsFromSnapshot 基于调度器快照在内存中匹配账号级映射(支持通配规则)。 -// resolvePlatform 返回与调度器一致的平台;无分组 API Key 使用调度器的未分组账号池(groupID=nil)。 -func inflightAccountMappedModelsFromSnapshot(list inflightSnapshotLister, resolvePlatform func(ctx context.Context, apiKey *APIKey, model string) (string, bool, bool)) func(ctx context.Context, apiKey *APIKey, model string) []string { +// resolvePlatform 返回可能携带 composite 池决策的 ctx 及目标平台;无分组 API Key 使用调度器的未分组账号池(groupID=nil)。 +func inflightAccountMappedModelsFromSnapshot(list inflightSnapshotLister, resolvePlatform func(ctx context.Context, apiKey *APIKey, model string) (context.Context, string, bool, bool)) func(ctx context.Context, apiKey *APIKey, model string) []string { if list == nil || resolvePlatform == nil { return nil } @@ -414,11 +414,11 @@ func inflightAccountMappedModelsFromSnapshot(list inflightSnapshotLister, resolv if apiKey == nil || model == "" { return nil } - platform, forced, ok := resolvePlatform(ctx, apiKey, model) + resolvedCtx, platform, forced, ok := resolvePlatform(ctx, apiKey, model) if !ok || platform == "" { return nil } - accounts, err := list(ctx, apiKey.GroupID, platform, forced) + accounts, err := list(resolvedCtx, apiKey.GroupID, platform, forced) if err != nil { return nil } @@ -721,15 +721,15 @@ func (s *GatewayService) inflightEstimateDeps() inflightEstimateDeps { snap := s.schedulerSnapshot d.accountMappedModels = inflightAccountMappedModelsFromSnapshot( func(ctx context.Context, groupID *int64, platform string, forced bool) ([]Account, error) { + if GenericCompositePoolActive(ctx) { + return s.listSchedulableAccountsForCompositePool(ctx, groupID, CompositeCandidatePlatformsFromContext(ctx)) + } accounts, _, err := snap.ListSchedulableAccounts(ctx, groupID, platform, forced) return accounts, err }, - func(ctx context.Context, apiKey *APIKey, model string) (string, bool, bool) { - // 本分支 resolvePlatform 返回携带 composite 池决策的 ctx;该快照闭包 - // 无法透传 ctx(上游接口只收 platform/forced),池决策场景下账号级 - // 映射估算退化为走兜底路径,行为安全。 - _, platform, forced, err := s.resolvePlatform(ctx, apiKey.GroupID, apiKey.Group, model) - return platform, forced, err == nil + func(ctx context.Context, apiKey *APIKey, model string) (context.Context, string, bool, bool) { + resolvedCtx, platform, forced, err := s.resolvePlatform(ctx, apiKey.GroupID, apiKey.Group, model) + return resolvedCtx, platform, forced, err == nil }, ) } @@ -755,15 +755,24 @@ func (s *OpenAIGatewayService) inflightEstimateDeps() inflightEstimateDeps { snap := s.schedulerSnapshot d.accountMappedModels = inflightAccountMappedModelsFromSnapshot( func(ctx context.Context, groupID *int64, platform string, forced bool) ([]Account, error) { + if openAICompositePoolActive(ctx) { + return s.listSchedulableAccountsForCompositePool(ctx, groupID, CompositeCandidatePlatformsFromContext(ctx)) + } accounts, _, err := snap.ListSchedulableAccounts(ctx, groupID, platform, forced) return accounts, err }, - func(ctx context.Context, apiKey *APIKey, model string) (string, bool, bool) { + func(ctx context.Context, apiKey *APIKey, model string) (context.Context, string, bool, bool) { platform := PlatformOpenAI - if apiKey.Group != nil && apiKey.Group.Platform != "" && apiKey.Group.Platform != PlatformComposite { - platform = apiKey.Group.Platform + if apiKey.Group != nil && apiKey.Group.Platform != "" { + if apiKey.Group.Platform == PlatformComposite { + if resolved, ok := ResolvedTargetPlatformFromContext(ctx); ok { + platform = resolved + } + } else { + platform = apiKey.Group.Platform + } } - return NormalizeOpenAICompatiblePlatform(platform), false, true + return ctx, NormalizeOpenAICompatiblePlatform(platform), false, true }, ) } diff --git a/backend/internal/service/composite_platform.go b/backend/internal/service/composite_platform.go index b1370357d8..7329aa69b3 100644 --- a/backend/internal/service/composite_platform.go +++ b/backend/internal/service/composite_platform.go @@ -120,6 +120,22 @@ func withCompositeRequiredClaimStrength(ctx context.Context, strength CompositeC return context.WithValue(ctx, ctxkey.CompositeRequiredClaimStrength, strength) } +// WithoutCompositeRouteContext 清除请求切换到兜底/降级分组前残留的原分组 composite +// 路由与候选池上下文,避免非 composite 兜底分组误继承原分组的候选池或目标平台。 +func WithoutCompositeRouteContext(ctx context.Context) context.Context { + if ctx == nil { + return nil + } + ctx = context.WithValue(ctx, ctxkey.ResolvedTargetPlatform, "") + ctx = context.WithValue(ctx, ctxkey.ResolvedUpstreamModel, "") + ctx = context.WithValue(ctx, ctxkey.RequestedPublicModel, "") + ctx = context.WithValue(ctx, ctxkey.CompositeRouteSource, "") + ctx = context.WithValue(ctx, ctxkey.CompositeRequiredClaimStrength, CompositeClaimNone) + ctx = context.WithValue(ctx, ctxkey.CompositeCandidatePlatforms, ([]string)(nil)) + ctx = context.WithValue(ctx, compositePoolDeniedPlatformsKey{}, ([]string)(nil)) + return ctx +} + // RewriteCompositeRequestModel puts a composite route's upstream model into the // request body at modelPath. The client chose its thinking mode for the model // it asked for, so a mode the upstream model rejects becomes the nearest mode diff --git a/backend/internal/service/composite_pool_policy.go b/backend/internal/service/composite_pool_policy.go index 076dcbe8ce..e5117c2bd5 100644 --- a/backend/internal/service/composite_pool_policy.go +++ b/backend/internal/service/composite_pool_policy.go @@ -65,22 +65,60 @@ func compositePoolPlatformDenied(ctx context.Context, platform string) bool { return false } +// checkCompositePoolChannelPricingRestriction 在账号池选号前按实际候选平台判断请求是否 +// 被整池渠道限制:仅当全部未被策略 deny 的候选平台都限制该模型时才在调度入口拦截, +// 避免非池内平台的渠道映射行跨平台误杀池请求。 +func checkCompositePoolChannelPricingRestriction(ctx context.Context, restrictedOn func(context.Context) bool) bool { + checked := 0 + for _, platform := range CompositeCandidatePlatformsFromContext(ctx) { + if compositePoolPlatformDenied(ctx, platform) { + continue + } + checked++ + if !restrictedOn(WithResolvedTargetPlatform(ctx, platform)) { + return false + } + } + return checked > 0 +} + +// CompositePoolAttemptChannelRestriction 报告选中账号平台作用域下该模型是否被渠道定价限制拒绝, +// 并区分平台级限制(requested / channel_mapped / response)与逐账号限制(upstream): +// 后者仅代表当前账号映射后的上游模型受限,不得将同平台其它合法账号整平台屏蔽。 +func (s *OpenAIGatewayService) CompositePoolAttemptChannelRestriction(ctx context.Context, groupID *int64, account *Account, requestedModel string, requireCompact bool) (platformRestricted bool, accountRestricted bool) { + if s == nil || groupID == nil || account == nil || requestedModel == "" { + return false, false + } + if s.checkChannelPricingRestriction(ctx, groupID, requestedModel) { + return true, false + } + if s.needsUpstreamChannelRestrictionCheck(ctx, groupID) { + effectiveModel := requestedModel + if s.channelService != nil { + if mapping := s.channelService.ResolveChannelMapping(ctx, *groupID, requestedModel); mapping.Mapped { + effectiveModel = mapping.MappedModel + } + } + var upstreamModel string + if account.Platform == PlatformAntigravity { + upstreamModel = mapAntigravityModel(account, effectiveModel) + } else { + upstreamModel = resolveOpenAIAccountUpstreamModelForRequest(account, effectiveModel, requireCompact) + } + if upstreamModel != "" && s.channelService != nil && s.channelService.IsModelRestricted(ctx, *groupID, upstreamModel) { + return false, true + } + } + return false, false +} + // CompositePoolAttemptChannelRestricted 报告选中账号平台作用域下该模型是否被 // 渠道定价限制拒绝。ctx 必须是带 ResolvedTargetPlatform=account.Platform 的 // attempt 局部 ctx。语义与调度阶段逐候选检查一致(checkChannelPricingRestriction // + upstream 计费基准的逐账号检查),不重复检查用户配额或 RPM。 func (s *OpenAIGatewayService) CompositePoolAttemptChannelRestricted(ctx context.Context, groupID *int64, account *Account, requestedModel string, requireCompact bool) bool { - if s == nil || groupID == nil || account == nil || requestedModel == "" { - return false - } - if s.checkChannelPricingRestriction(ctx, groupID, requestedModel) { - return true - } - if s.needsUpstreamChannelRestrictionCheck(ctx, groupID) && - s.isUpstreamModelRestrictedByChannel(ctx, *groupID, account, requestedModel, requireCompact) { - return true - } - return false + platformRestricted, accountRestricted := s.CompositePoolAttemptChannelRestriction(ctx, groupID, account, requestedModel, requireCompact) + return platformRestricted || accountRestricted } // CompositePoolAttemptChannelMapping 返回选中账号平台作用域的渠道级模型映射。 diff --git a/backend/internal/service/gateway_forward.go b/backend/internal/service/gateway_forward.go index 71d30e7508..c1b5e2bdb2 100644 --- a/backend/internal/service/gateway_forward.go +++ b/backend/internal/service/gateway_forward.go @@ -999,6 +999,11 @@ func (s *GatewayService) checkChannelPricingRestriction(ctx context.Context, gro if groupID == nil || s.channelService == nil || requestedModel == "" { return false } + if GenericCompositePoolActive(ctx) { + return checkCompositePoolChannelPricingRestriction(ctx, func(candCtx context.Context) bool { + return s.checkChannelPricingRestriction(candCtx, groupID, requestedModel) + }) + } mapping := s.channelService.ResolveChannelMapping(ctx, *groupID, requestedModel) billingModel := billingModelForRestriction(mapping.BillingModelSource, requestedModel, mapping.MappedModel) if billingModel == "" { @@ -1029,9 +1034,15 @@ func billingModelForRestriction(source, requestedModel, channelMappedModel strin // isUpstreamModelRestrictedByChannel 检查账号映射后的上游模型是否受渠道定价限制。 // 仅在 BillingModelSource="upstream" 且 RestrictModels=true 时由调度循环调用。 func (s *GatewayService) isUpstreamModelRestrictedByChannel(ctx context.Context, groupID int64, account *Account, requestedModel string) bool { - if s.channelService == nil { + if s.channelService == nil || account == nil { return false } + if GenericCompositePoolActive(ctx) && account.Platform != "" { + ctx = WithResolvedTargetPlatform(ctx, account.Platform) + if mapping := s.channelService.ResolveChannelMapping(ctx, groupID, requestedModel); mapping.Mapped { + requestedModel = mapping.MappedModel + } + } upstreamModel := resolveAccountUpstreamModel(account, requestedModel) if upstreamModel == "" { return false diff --git a/backend/internal/service/gateway_scheduling.go b/backend/internal/service/gateway_scheduling.go index 3921dd8b06..be4858a126 100644 --- a/backend/internal/service/gateway_scheduling.go +++ b/backend/internal/service/gateway_scheduling.go @@ -39,6 +39,7 @@ func (s *GatewayService) SelectAccountForModelWithExclusions(ctx context.Context if hasForcePlatform && forcePlatform != "" { platform = forcePlatform } else if groupID != nil { + origGroupID := derefGroupID(groupID) group, resolvedGroupID, err := s.resolveGatewayGroup(ctx, groupID) if err != nil { return nil, err @@ -46,6 +47,9 @@ func (s *GatewayService) SelectAccountForModelWithExclusions(ctx context.Context if group == nil { return nil, ErrGroupNotFound } + if derefGroupID(resolvedGroupID) != origGroupID { + ctx = WithoutCompositeRouteContext(ctx) + } groupID = resolvedGroupID ctx = s.withGroupContext(ctx, group) platform = group.Platform @@ -123,10 +127,14 @@ func (s *GatewayService) SelectAccountWithLoadAwareness(ctx context.Context, gro cfg := s.schedulingConfig() // 检查 Claude Code 客户端限制(可能会替换 groupID 为降级分组) + origGroupID := derefGroupID(groupID) group, groupID, err := s.checkClaudeCodeRestriction(ctx, groupID) if err != nil { return nil, err } + if derefGroupID(groupID) != origGroupID { + ctx = WithoutCompositeRouteContext(ctx) + } ctx = s.withGroupContext(ctx, group) ctx = s.withGatewayProfitControlGate(ctx, groupID) @@ -1291,7 +1299,8 @@ func (s *GatewayService) gatewaySchedulingModelSupported(ctx context.Context, ac return true } if GenericCompositePoolActive(ctx) { - if !CompositeAccountMeetsClaimTier(ctx, account, requestedModel) && !account.IsOpenAIPassthroughEnabled() { + passthroughUnfiltered := account.IsOpenAIPassthroughEnabled() && !account.IsOpenAIPassthroughModelFilterEnabled() + if !CompositeAccountMeetsClaimTier(ctx, account, requestedModel) && !passthroughUnfiltered { return false } } diff --git a/backend/internal/service/openai_gateway_scheduling.go b/backend/internal/service/openai_gateway_scheduling.go index ee56d08ec8..10b5de25a9 100644 --- a/backend/internal/service/openai_gateway_scheduling.go +++ b/backend/internal/service/openai_gateway_scheduling.go @@ -372,7 +372,8 @@ func openAISchedulingModelSupported(ctx context.Context, account *Account, reque return true } if openAICompositePoolActive(ctx) { - if !CompositeAccountMeetsClaimTier(ctx, account, requestedModel) && !account.IsOpenAIPassthroughEnabled() { + passthroughUnfiltered := account.IsOpenAIPassthroughEnabled() && !account.IsOpenAIPassthroughModelFilterEnabled() + if !CompositeAccountMeetsClaimTier(ctx, account, requestedModel) && !passthroughUnfiltered { return false } } diff --git a/backend/internal/service/openai_gateway_service.go b/backend/internal/service/openai_gateway_service.go index f3422ad7d7..59efc3cdf9 100644 --- a/backend/internal/service/openai_gateway_service.go +++ b/backend/internal/service/openai_gateway_service.go @@ -650,6 +650,11 @@ func (s *OpenAIGatewayService) checkChannelPricingRestriction(ctx context.Contex if groupID == nil || s.channelService == nil || requestedModel == "" { return false } + if openAICompositePoolActive(ctx) { + return checkCompositePoolChannelPricingRestriction(ctx, func(candCtx context.Context) bool { + return s.checkChannelPricingRestriction(candCtx, groupID, requestedModel) + }) + } mapping := s.channelService.ResolveChannelMapping(ctx, *groupID, requestedModel) billingModel := billingModelForRestriction(mapping.BillingModelSource, requestedModel, mapping.MappedModel) if billingModel == "" { @@ -659,14 +664,28 @@ func (s *OpenAIGatewayService) checkChannelPricingRestriction(ctx context.Contex } func (s *OpenAIGatewayService) isUpstreamModelRestrictedByChannel(ctx context.Context, groupID int64, account *Account, requestedModel string, requireCompact bool) bool { - if s.channelService == nil { + if s.channelService == nil || account == nil { return false } + poolActive := openAICompositePoolActive(ctx) if compactForwardModel, ok := openAIForwardModelFromContext(ctx); ok { - requestedModel = compactForwardModel.model + if !poolActive { + requestedModel = compactForwardModel.model + } requireCompact = compactForwardModel.useCompactModelMapping } - upstreamModel := resolveOpenAIAccountUpstreamModelForRequest(account, requestedModel, requireCompact) + if poolActive && account.Platform != "" { + ctx = WithResolvedTargetPlatform(ctx, account.Platform) + if mapping := s.channelService.ResolveChannelMapping(ctx, groupID, requestedModel); mapping.Mapped { + requestedModel = mapping.MappedModel + } + } + var upstreamModel string + if account.Platform == PlatformAntigravity { + upstreamModel = mapAntigravityModel(account, requestedModel) + } else { + upstreamModel = resolveOpenAIAccountUpstreamModelForRequest(account, requestedModel, requireCompact) + } if upstreamModel == "" { return false } From e3c23b25e0a595e364de7ab91d2de5c74f1fb095 Mon Sep 17 00:00:00 2001 From: shaw Date: Sat, 5 Dec 2026 12:10:27 +0800 Subject: [PATCH 75/81] =?UTF-8?q?fix(ollama,=20monitor):=20=E8=A1=A5?= =?UTF-8?q?=E9=BD=90=E9=BB=98=E8=AE=A4=E4=B8=8A=E6=B8=B8=E7=99=BD=E5=90=8D?= =?UTF-8?q?=E5=8D=95=E3=80=81=E5=A4=9A=E5=8D=8F=E8=AE=AE=E7=A9=BA=E5=9F=BA?= =?UTF-8?q?=E5=9D=80=E5=AE=88=E5=8D=AB=E3=80=81credits=20=E7=9B=91?= =?UTF-8?q?=E6=8E=A7=E5=8E=BB=E7=AA=97=E4=B8=8E=E6=B5=81=E5=BC=8F=E9=A2=84?= =?UTF-8?q?=E6=A3=80=E9=94=99=E8=AF=AF=E5=B8=A7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/internal/config/config.go | 2 + backend/internal/config/config_test.go | 4 +- .../account_repo_ollama_cloud_usage.go | 18 +- .../channel_monitor_ollama_cloud_test.go | 44 ++- .../service/channel_monitor_quota_fetcher.go | 22 +- .../service/channel_monitor_validate.go | 5 + .../service/composite_pool_audit_r5_test.go | 339 ++++++++++++++++++ backend/internal/service/openai_embeddings.go | 3 + ...penai_gateway_messages_anthropic_native.go | 2 +- .../openai_gateway_ollama_cloud_max_tokens.go | 31 +- ..._gateway_ollama_cloud_pricing_preflight.go | 83 ++++- .../service/openai_gateway_request_body.go | 10 +- backend/internal/service/upstream_models.go | 5 +- 13 files changed, 537 insertions(+), 31 deletions(-) create mode 100644 backend/internal/service/composite_pool_audit_r5_test.go diff --git a/backend/internal/config/config.go b/backend/internal/config/config.go index 9a94d93ebe..d97b475379 100644 --- a/backend/internal/config/config.go +++ b/backend/internal/config/config.go @@ -2216,6 +2216,8 @@ func setDefaults() { "api.minimaxi.com", // MiniMax CN quota + inference "api.minimax.io", // MiniMax intl; frozen allowlists must add this host to use the intl site "opencode.ai", + "ollama.com", + "www.ollama.com", "generativelanguage.googleapis.com", "cloudcode-pa.googleapis.com", "*.openai.azure.com", diff --git a/backend/internal/config/config_test.go b/backend/internal/config/config_test.go index a6b393ef04..2c13ec7446 100644 --- a/backend/internal/config/config_test.go +++ b/backend/internal/config/config_test.go @@ -997,6 +997,8 @@ func TestLoadDefaultSecurityToggles(t *testing.T) { "api.kimi.ai", "api.moonshot.ai", "api.moonshot.cn", + "ollama.com", + "www.ollama.com", } hostSet := make(map[string]struct{}, len(cfg.Security.URLAllowlist.UpstreamHosts)) for _, h := range cfg.Security.URLAllowlist.UpstreamHosts { @@ -1012,7 +1014,7 @@ func TestLoadDefaultSecurityToggles(t *testing.T) { RequireAllowlist: true, AllowPrivate: cfg.Security.URLAllowlist.AllowPrivateHosts, } - for _, host := range []string{"api.kimi.com", "api.kimi.ai"} { + for _, host := range []string{"api.kimi.com", "api.kimi.ai", "ollama.com", "www.ollama.com"} { target := "https://" + host + "/coding/v1/usages" normalized, err := urlvalidator.ValidateHTTPSURL(target, opts) require.NoError(t, err) diff --git a/backend/internal/repository/account_repo_ollama_cloud_usage.go b/backend/internal/repository/account_repo_ollama_cloud_usage.go index b3448fbc96..18379b865c 100644 --- a/backend/internal/repository/account_repo_ollama_cloud_usage.go +++ b/backend/internal/repository/account_repo_ollama_cloud_usage.go @@ -8,6 +8,7 @@ import ( "time" dbent "github.com/Wei-Shaw/sub2api/ent" + "github.com/Wei-Shaw/sub2api/internal/pkg/logger" "github.com/Wei-Shaw/sub2api/internal/service" "github.com/lib/pq" ) @@ -286,7 +287,7 @@ func (r *accountRepository) updateOllamaCloudUsageGroup( if err := apply(ctx, r.client); err != nil { return err } - r.syncSchedulerAccountSnapshots(ctx, syncedMemberIDs) + r.syncOllamaCloudUsageSchedulerState(ctx, syncedMemberIDs) return nil } if err != nil { @@ -300,10 +301,23 @@ func (r *accountRepository) updateOllamaCloudUsageGroup( if err := tx.Commit(); err != nil { return err } - r.syncSchedulerAccountSnapshots(ctx, syncedMemberIDs) + r.syncOllamaCloudUsageSchedulerState(ctx, syncedMemberIDs) return nil } +func (r *accountRepository) syncOllamaCloudUsageSchedulerState(ctx context.Context, memberIDs []int64) { + if r == nil || len(memberIDs) == 0 { + return + } + for _, memberID := range memberIDs { + id := memberID + if err := enqueueSchedulerOutbox(ctx, r.sql, service.SchedulerOutboxEventAccountChanged, &id, nil, nil); err != nil { + logger.LegacyPrintf("repository.account", "[SchedulerOutbox] enqueue ollama cloud usage sync failed: account=%d err=%v", id, err) + } + } + r.syncSchedulerAccountSnapshots(ctx, memberIDs) +} + func lockOllamaCloudUsageGroup( ctx context.Context, client *dbent.Client, diff --git a/backend/internal/service/channel_monitor_ollama_cloud_test.go b/backend/internal/service/channel_monitor_ollama_cloud_test.go index 87d65deb0d..2c61c42652 100644 --- a/backend/internal/service/channel_monitor_ollama_cloud_test.go +++ b/backend/internal/service/channel_monitor_ollama_cloud_test.go @@ -243,7 +243,7 @@ func TestQuotaFetcher_OpenCodeGoStillRoutesToCNQuota(t *testing.T) { } func TestParseOllamaCloudBalanceUSD_RejectsNonFiniteValues(t *testing.T) { - for _, raw := range []string{"NaN", "Inf", "+Inf", "-Inf", "Infinity", "$NaN", "USD$Inf"} { + for _, raw := range []string{"NaN", "Inf", "+Inf", "-Inf", "Infinity", "$NaN", "USD$Inf", "--$1.50"} { val, ok := parseOllamaCloudBalanceUSD(raw) require.False(t, ok, "raw=%q", raw) require.Zero(t, val) @@ -251,4 +251,46 @@ func TestParseOllamaCloudBalanceUSD_RejectsNonFiniteValues(t *testing.T) { val, ok := parseOllamaCloudBalanceUSD("$12.50") require.True(t, ok) require.InDelta(t, 12.50, val, 1e-9) + + for _, raw := range []string{"-$1.50", "-USD$1.50", "$-1.50", "-$1,234.50"} { + neg, negOK := parseOllamaCloudBalanceUSD(raw) + require.True(t, negOK, "raw=%q", raw) + if raw == "-$1,234.50" { + require.InDelta(t, -1234.50, neg, 1e-9) + } else { + require.InDelta(t, -1.50, neg, 1e-9) + } + } +} + +func TestQuotaFetcher_OllamaCloudCreditsModeSuppressesWindowTiers(t *testing.T) { + fetcher, _, _, _, accounts := newQuotaFetcherTestSetup(t) + account := ollamaCloudQuotaTestAccount(37, ollamaCloudUsageSnapshotExtra( + OllamaCloudUsageStatusOK, time.Now().UTC(), + &OllamaCloudUsageData{ + Plan: "credits", + FiveHour: &OllamaCloudUsageWindow{UsedPercent: 98.0}, + SevenDay: &OllamaCloudUsageWindow{UsedPercent: 95.0}, + Balance: "$42.00", + }, + "", + )) + account.Credentials["account_mode"] = AccountModeOllamaCredits + accounts.accounts[37] = account + + snapshot := fetcher.Fetch(context.Background(), 37) + require.True(t, snapshot.Success) + require.Empty(t, snapshot.Tiers, "credits 账号不应透出残留 5h/7d 窗口触发误告警") + require.NotNil(t, snapshot.Balance) + require.InDelta(t, 42.0, *snapshot.Balance, 1e-9) + require.Equal(t, MonitorStatusOperational, deriveQuotaCheckResult(snapshot, "quota", time.Now()).Status) +} + +func TestMonitorAccountQuotaCapability_OllamaCloudEligibility(t *testing.T) { + official := ollamaCloudQuotaTestAccount(38, nil) + require.NoError(t, monitorAccountQuotaCapability(official)) + + relay := ollamaCloudQuotaTestAccount(39, nil) + relay.Credentials["base_url"] = "https://relay.example.com/v1" + require.ErrorIs(t, monitorAccountQuotaCapability(relay), ErrChannelMonitorAccountNotSupportable) } diff --git a/backend/internal/service/channel_monitor_quota_fetcher.go b/backend/internal/service/channel_monitor_quota_fetcher.go index 78e2b4564d..f0354bbd04 100644 --- a/backend/internal/service/channel_monitor_quota_fetcher.go +++ b/backend/internal/service/channel_monitor_quota_fetcher.go @@ -501,7 +501,9 @@ func (f *ChannelMonitorQuotaFetcher) fetchOllamaCloudQuota(account *Account, now PlanLevel: snapshot.Data.Plan, FetchedAt: fetchedAt, } - out.Tiers = ollamaCloudQuotaTiers(snapshot.Data) + if account.GetOllamaCloudAccountMode() == AccountModeOllamaLegacy { + out.Tiers = ollamaCloudQuotaTiers(snapshot.Data) + } if balance, ok := parseOllamaCloudBalanceUSD(snapshot.Data.Balance); ok { out.Balance = &balance out.Currency = "USD" @@ -539,17 +541,25 @@ func appendOllamaCloudQuotaTier(tiers *[]domain.MonitorQuotaTier, window string, // 派生百分比,故 credits 账号只透出余额,不参与 used_percent 告警)。 func parseOllamaCloudBalanceUSD(raw string) (float64, bool) { raw = strings.TrimSpace(raw) - raw = strings.TrimPrefix(raw, "USD") - raw = strings.TrimPrefix(raw, "$") - raw = strings.ReplaceAll(strings.TrimSpace(raw), ",", "") - if raw == "" { + sign := 1.0 + switch { + case strings.HasPrefix(raw, "-"): + sign = -1.0 + raw = strings.TrimSpace(raw[1:]) + case strings.HasPrefix(raw, "+"): + raw = strings.TrimSpace(raw[1:]) + } + raw = strings.TrimSpace(strings.TrimPrefix(raw, "USD")) + raw = strings.TrimSpace(strings.TrimPrefix(raw, "$")) + raw = strings.ReplaceAll(raw, ",", "") + if raw == "" || (sign < 0 && (strings.HasPrefix(raw, "-") || strings.HasPrefix(raw, "+"))) { return 0, false } value, err := strconv.ParseFloat(raw, 64) if err != nil || math.IsNaN(value) || math.IsInf(value, 0) { return 0, false } - return value, true + return sign * value, true } // ollamaCloudUsageReasonHint 把 EligibleReason 原因码翻译成运维可读的提示 diff --git a/backend/internal/service/channel_monitor_validate.go b/backend/internal/service/channel_monitor_validate.go index 309d3d2269..1c78877c42 100644 --- a/backend/internal/service/channel_monitor_validate.go +++ b/backend/internal/service/channel_monitor_validate.go @@ -222,6 +222,11 @@ func monitorAccountQuotaCapability(account *Account) error { switch account.Platform { case PlatformOpenCodeGo: return nil + case PlatformOllamaCloud: + if ollamaCloudUsageEligibilityReason(account) != "" { + return ErrChannelMonitorAccountNotSupportable + } + return nil case PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax: if account.IsCodingPlan() { if p := account.GetCodingPlanProvider(); p != PlatformKimi && p != PlatformZhipu && p != PlatformMiniMax { diff --git a/backend/internal/service/composite_pool_audit_r5_test.go b/backend/internal/service/composite_pool_audit_r5_test.go new file mode 100644 index 0000000000..7ec0f88d96 --- /dev/null +++ b/backend/internal/service/composite_pool_audit_r5_test.go @@ -0,0 +1,339 @@ +//go:build unit + +package service + +import ( + "bytes" + "context" + "net/http" + "net/http/httptest" + "testing" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" +) + +func TestEstimateInflightReservation_CompositePoolAndResolvedTarget(t *testing.T) { + cfg := &config.Config{RunMode: config.RunModeStandard} + cfg.Default.RateMultiplier = 1 + cfg.Billing.InflightReservation.Enabled = true + cfg.Billing.InflightReservation.DefaultMaxTokens = 1000 + cfg.Billing.InflightReservation.MaxInputTokens = 10000 + cfg.Billing.InflightReservation.MaxOutputTokens = 10000 + billing := NewBillingService(cfg, nil) + resolver := NewModelPricingResolver(nil, billing) + + groupID := int64(501) + compositeGroup := &Group{ID: groupID, Name: "comp-pool", Platform: PlatformComposite, RateMultiplier: 1} + apiKey := &APIKey{ + ID: 1, + UserID: 10, + GroupID: &groupID, + Group: compositeGroup, + User: &User{ID: 10, Balance: 10}, + } + + snap := &inflightSnapshotCacheStub{byBucket: make(map[string][]Account)} + snap.set(groupID, PlatformAnthropic, []Account{{ + ID: 1, Platform: PlatformAnthropic, Type: AccountTypeAPIKey, Status: StatusActive, Schedulable: true, + Credentials: map[string]any{"api_key": "sk-ant", "model_mapping": map[string]any{"coding-flagship": "claude-opus-4-6"}}, + }}) + snap.set(groupID, PlatformOllamaCloud, []Account{{ + ID: 2, Platform: PlatformOllamaCloud, Type: AccountTypeAPIKey, Status: StatusActive, Schedulable: true, + Credentials: map[string]any{"api_key": "sk-ol", "model_mapping": map[string]any{"coding-flagship": "qwen3.5:397b"}}, + }}) + snap.set(groupID, PlatformDeepseek, []Account{{ + ID: 3, Platform: PlatformDeepseek, Type: AccountTypeAPIKey, Status: StatusActive, Schedulable: true, + Credentials: map[string]any{"api_key": "sk-ds", "model_mapping": map[string]any{"coding-flagship": "deepseek-v4-pro"}}, + }}) + + // 1. 跨族候选池(GatewayService):从候选平台桶读取映射模型估算预留,不查不存在的 composite 桶。 + gwSvc := &GatewayService{cfg: cfg, billingService: billing, resolver: resolver} + repo := attachInflightSnapshot(gwSvc, snap) + poolCtx := WithCompositeCandidatePlatforms(context.Background(), []string{PlatformAnthropic, PlatformOllamaCloud}) + cost, ok := gwSvc.EstimateInflightReservation(poolCtx, apiKey, InflightEstimateRequest{ + Model: "coding-flagship", + BodyBytes: 400, + MaxTokens: 500, + }) + require.True(t, ok, "composite pool custom alias must resolve mapped model pricing for inflight reservation") + require.Greater(t, cost, 0.0) + require.Equal(t, int64(0), repo.dbCalls.Load()) + + // 2. OpenAI 兼容族池(OpenAIGatewayService):不硬编码只查 openai 桶。 + openAISvc := &OpenAIGatewayService{ + cfg: cfg, + billingService: billing, + resolver: resolver, + accountRepo: repo, + schedulerSnapshot: NewSchedulerSnapshotService(snap, nil, repo, nil, cfg), + } + oaPoolCtx := WithCompositeCandidatePlatforms(context.Background(), []string{PlatformDeepseek, PlatformOllamaCloud}) + oaCost, oaOK := openAISvc.EstimateInflightReservation(oaPoolCtx, apiKey, InflightEstimateRequest{ + Model: "coding-flagship", + BodyBytes: 400, + MaxTokens: 500, + }) + require.True(t, oaOK, "OpenAI-family composite pool must read candidate buckets instead of empty openai bucket") + require.Greater(t, oaCost, 0.0) + + // 3. 单目标 composite(ResolvedTargetPlatform=deepseek):查 deepseek 桶而非 openai 桶。 + singleCtx := WithResolvedTargetPlatform(context.Background(), PlatformDeepseek) + singleCost, singleOK := openAISvc.EstimateInflightReservation(singleCtx, apiKey, InflightEstimateRequest{ + Model: "coding-flagship", + BodyBytes: 400, + MaxTokens: 500, + }) + require.True(t, singleOK) + require.Greater(t, singleCost, 0.0) +} + +type r5MultiGroupRepo struct { + GroupRepository + byID map[int64]*Group +} + +func (r *r5MultiGroupRepo) GetByID(_ context.Context, id int64) (*Group, error) { + if g, ok := r.byID[id]; ok { + return g, nil + } + return nil, ErrGroupNotFound +} + +func (r *r5MultiGroupRepo) GetByIDLite(ctx context.Context, id int64) (*Group, error) { + return r.GetByID(ctx, id) +} + +type r5FallbackAccountRepo struct { + genericPoolTestAccountRepo +} + +func (r *r5FallbackAccountRepo) ListSchedulableByGroupIDAndPlatforms(ctx context.Context, groupID int64, platforms []string) ([]Account, error) { + var out []Account + for _, p := range platforms { + items, err := r.ListSchedulableByGroupIDAndPlatform(ctx, groupID, p) + if err != nil { + return nil, err + } + out = append(out, items...) + } + return out, nil +} + +func TestWithoutCompositeRouteContext_ClearsPoolStateOnFallbackGroup(t *testing.T) { + primaryID := int64(601) + fallbackID := int64(602) + primaryGroup := &Group{ + ID: primaryID, + Name: "comp-cc-only", + Platform: PlatformComposite, + ClaudeCodeOnly: true, + FallbackGroupID: &fallbackID, + } + fallbackGroup := &Group{ + ID: fallbackID, + Name: "ant-fallback", + Platform: PlatformAnthropic, + } + groupRepo := &r5MultiGroupRepo{byID: map[int64]*Group{ + primaryID: primaryGroup, + fallbackID: fallbackGroup, + }} + fallbackAcc := genericPoolTestAccount(7001, PlatformAnthropic, fallbackID, 1, map[string]any{ + "api_key": "sk-ant-fallback", + }, nil) + accountRepo := &r5FallbackAccountRepo{genericPoolTestAccountRepo{accounts: []Account{fallbackAcc}}} + svc := &GatewayService{ + cfg: &config.Config{}, + groupRepo: groupRepo, + accountRepo: accountRepo, + } + + // 原请求带主分组(composite)解析出的跨平台候选池(不含 anthropic)。 + ctx := WithCompositeRouteDecision(context.Background(), CompositeRouteDecision{ + Matched: true, + Source: CompositeRouteSourceAccountPool, + GroupID: primaryID, + PublicModel: "claude-sonnet-4-5", + CandidatePlatforms: []string{PlatformDeepseek, PlatformOllamaCloud}, + RequiredClaimStrength: CompositeClaimExplicit, + }) + ctx = WithCompositePoolDeniedPlatforms(ctx, []string{PlatformDeepseek}) + + // 非 Claude Code 客户端触发降级分组切换后,不应残留原分组候选池导致 anthropic 兜底组选不出账号。 + selected, err := svc.SelectAccountForModelWithExclusions(ctx, &primaryID, "", "claude-sonnet-4-5", nil) + require.NoError(t, err) + require.NotNil(t, selected) + require.EqualValues(t, 7001, selected.ID) + + res, err := svc.SelectAccountWithLoadAwareness(ctx, &primaryID, "", "claude-sonnet-4-5", nil, "", 0) + require.NoError(t, err) + require.NotNil(t, res) + require.EqualValues(t, 7001, res.Account.ID) +} + +func TestCompositePoolChannelRestriction_NonPoolPlatformAndAccountUpstreamScope(t *testing.T) { + groupID := poolAttemptGroupID + ch := Channel{ + ID: 1, + Status: StatusActive, + GroupIDs: []int64{groupID}, + RestrictModels: true, + BillingModelSource: BillingModelSourceChannelMapped, + ModelMapping: map[string]map[string]string{ + // 非池内的 anthropic 平台把别名映射到未配价模型;池内 deepseek / ollama_cloud 正常配价。 + PlatformAnthropic: {"shared-alias": "unlisted-claude"}, + PlatformDeepseek: {"shared-alias": "deepseek-chat"}, + PlatformOllamaCloud: {"shared-alias": "qwen3.5:397b"}, + }, + ModelPricing: []ChannelModelPricing{ + {Platform: PlatformDeepseek, Models: []string{"deepseek-chat"}}, + {Platform: PlatformOllamaCloud, Models: []string{"qwen3.5:397b"}}, + }, + } + channelSvc := newPoolAttemptChannelService(t, ch) + oaSvc := newPoolAttemptOpenAIGateway(channelSvc) + gwSvc := &GatewayService{channelService: channelSvc} + + poolCtx := WithCompositeCandidatePlatforms(context.Background(), []string{PlatformDeepseek, PlatformOllamaCloud}) + require.False(t, oaSvc.checkChannelPricingRestriction(poolCtx, &groupID, "shared-alias"), + "non-pool anthropic channel mapping must not block [deepseek, ollama_cloud] pool") + require.False(t, gwSvc.checkChannelPricingRestriction(poolCtx, &groupID, "shared-alias")) + + allRestrictedCtx := WithCompositeCandidatePlatforms(context.Background(), []string{PlatformAnthropic}) + require.True(t, oaSvc.checkChannelPricingRestriction(allRestrictedCtx, &groupID, "shared-alias")) +} + +func TestPassthroughModelFilter_EnforcesCompositeClaimTier(t *testing.T) { + poolCtx := WithCompositeRouteDecision(context.Background(), CompositeRouteDecision{ + Matched: true, + Source: CompositeRouteSourceAccountPool, + GroupID: 801, + PublicModel: "gpt-5.4", + CandidatePlatforms: []string{PlatformOpenAI, PlatformOllamaCloud}, + RequiredClaimStrength: CompositeClaimExplicit, + }) + + // 开启 openai_passthrough_model_filter 且仅通配命中(Wildcard < Explicit)时,不得绕过声明层级。 + wildcardFiltered := &Account{ + ID: 8001, + Platform: PlatformOpenAI, + Type: AccountTypeAPIKey, + Credentials: map[string]any{ + "api_key": "sk-pt", + "model_mapping": map[string]any{"gpt-*": "gpt-*"}, + }, + Extra: map[string]any{ + "openai_passthrough": true, + "openai_passthrough_model_filter": true, + }, + } + require.False(t, openAISchedulingModelSupported(poolCtx, wildcardFiltered, "gpt-5.4", false)) + svc := &GatewayService{cfg: &config.Config{}} + require.False(t, svc.gatewaySchedulingModelSupported(poolCtx, wildcardFiltered, "gpt-5.4")) + + // 精确键命中(Explicit >= Explicit)放行。 + exactFiltered := &Account{ + ID: 8002, + Platform: PlatformOpenAI, + Type: AccountTypeAPIKey, + Credentials: map[string]any{ + "api_key": "sk-pt", + "model_mapping": map[string]any{"gpt-5.4": "gpt-5.4"}, + }, + Extra: map[string]any{ + "openai_passthrough": true, + "openai_passthrough_model_filter": true, + }, + } + require.True(t, openAISchedulingModelSupported(poolCtx, exactFiltered, "gpt-5.4", false)) + require.True(t, svc.gatewaySchedulingModelSupported(poolCtx, exactFiltered, "gpt-5.4")) +} + +func TestBuildOpenAIAPIKeyModelsRequest_MultiProtocolEmptyBaseURLAndWWWHost(t *testing.T) { + // 1. 多协议平台缺省 baseURL 为空时显式报错,绝不回落 api.openai.com 泄露第三方凭据。 + origProfile := providerProfiles[PlatformOllamaCloud] + providerProfiles[PlatformOllamaCloud] = &ProviderProfile{ + Platform: PlatformOllamaCloud, + DefaultMode: AccountModeOllamaLegacy, + Modes: map[string]ProviderEndpoints{AccountModeOllamaLegacy: {}}, + } + t.Cleanup(func() { providerProfiles[PlatformOllamaCloud] = origProfile }) + + acc := &Account{ + ID: 9001, + Platform: PlatformOllamaCloud, + Type: AccountTypeAPIKey, + Credentials: map[string]any{"api_key": "sk-secret"}, + } + req, err := buildOpenAIAPIKeyModelsRequest(context.Background(), acc, func(s string) (string, error) { return s, nil }) + require.Error(t, err) + require.Nil(t, req) + + // 2. models.dev 已知 host 匹配同时识别 www.ollama.com。 + registry := map[string]modelsDevProvider{ + "ollama-cloud": {Models: map[string]modelsDevModel{"qwen3.5:397b": {}}}, + } + provider, ok := matchModelsDevProvider(registry, "https://www.ollama.com/v1") + require.True(t, ok) + require.Equal(t, "ollama-cloud", provider.ID) +} + +func TestAnthropicProtocolEndpointURL_LegacyHostOllamaCloudV1(t *testing.T) { + legacyAcc := &Account{ + ID: 9101, + Platform: PlatformDeepseek, + Type: AccountTypeAPIKey, + Credentials: map[string]any{ + "api_key": "sk-ollama", + "api_protocol": APIProtocolAnthropic, + "base_url": "https://ollama.com/v1", + }, + } + require.Equal(t, "https://ollama.com/v1/messages", anthropicProtocolEndpointURL(legacyAcc, "https://ollama.com/v1", "/v1/messages")) + require.Equal(t, "https://www.ollama.com/v1/messages", anthropicProtocolEndpointURL(legacyAcc, "https://www.ollama.com/v1", "/v1/messages")) +} + +func TestOllamaCloudResponsesMaxOutputTokensClamp_StripsOverCapMaxTokensAlongsideMaxOutputTokens(t *testing.T) { + acc := &Account{ + ID: 9201, + Platform: PlatformOllamaCloud, + Type: AccountTypeAPIKey, + Credentials: map[string]any{"api_key": "sk-ol", "base_url": "https://ollama.com/v1"}, + } + body := []byte(`{"model":"qwen3.5:397b","max_output_tokens":4096,"max_tokens":256000}`) + out := ollamaCloudClampResponsesMaxOutputTokensBody(acc, "qwen3.5:397b", body) + require.Equal(t, int64(4096), gjson.GetBytes(out, "max_output_tokens").Int()) + require.False(t, gjson.GetBytes(out, "max_tokens").Exists(), "over-cap residual max_tokens must be stripped") +} + +func TestWriteServiceLocalInvalidRequestResponse_StreamAlreadyStartedEmitsSSE(t *testing.T) { + gin.SetMode(gin.TestMode) + + for _, tc := range []struct { + path string + wantSubstr string + }{ + {path: "/v1/responses", wantSubstr: "event: response.failed"}, + {path: "/v1/messages", wantSubstr: "event: error"}, + {path: "/v1/chat/completions", wantSubstr: "data: [DONE]"}, + } { + t.Run(tc.path, func(t *testing.T) { + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, tc.path, bytes.NewReader([]byte(`{}`))) + c.Header("Content-Type", "text/event-stream") + c.Status(http.StatusOK) + _, _ = c.Writer.Write([]byte(": ping\n\n")) + c.Writer.Flush() + + writeServiceLocalInvalidRequestResponse(c, "unpriced model blocked") + + require.True(t, IsResponseCommitted(c)) + require.Contains(t, rec.Body.String(), tc.wantSubstr) + require.Contains(t, rec.Body.String(), "unpriced model blocked") + }) + } +} diff --git a/backend/internal/service/openai_embeddings.go b/backend/internal/service/openai_embeddings.go index 9771d770db..647d3818c6 100644 --- a/backend/internal/service/openai_embeddings.go +++ b/backend/internal/service/openai_embeddings.go @@ -55,6 +55,9 @@ func (s *OpenAIGatewayService) ForwardEmbeddings( // embeddings 需使用 OpenAI 格式 base。 baseURL := account.GetOpenAIFormatBaseURL() if baseURL == "" { + if account.IsMultiProtocolAPIKey() { + return nil, fmt.Errorf("account %d has no openai embeddings base url", account.ID) + } baseURL = "https://api.openai.com" } validatedURL, err := s.validateUpstreamBaseURL(baseURL) diff --git a/backend/internal/service/openai_gateway_messages_anthropic_native.go b/backend/internal/service/openai_gateway_messages_anthropic_native.go index 3a508cf06b..2d48a9864c 100644 --- a/backend/internal/service/openai_gateway_messages_anthropic_native.go +++ b/backend/internal/service/openai_gateway_messages_anthropic_native.go @@ -164,7 +164,7 @@ func nativeAnthropicMessagesURL(account *Account, validatedBaseURL string) strin // 端点从不附加 ?beta=true:第三方端点不接受该参数,Cloudflare 账号 REST 端点还会直接 // 拒绝(其 messages 端点的判定见 buildAnthropicMessagesURL,两处语义保持一致)。 func anthropicProtocolEndpointURL(account *Account, validatedBaseURL, endpoint string) string { - if account.routesByModel() || account.IsOllamaCloud() { + if account.routesByModel() || account.IsOllamaCloud() || isOllamaCloudOutboundBaseURL(validatedBaseURL) { return buildOpenAIEndpointURL(validatedBaseURL, endpoint) } return strings.TrimRight(validatedBaseURL, "/") + endpoint diff --git a/backend/internal/service/openai_gateway_ollama_cloud_max_tokens.go b/backend/internal/service/openai_gateway_ollama_cloud_max_tokens.go index 5ee239ab7c..f6856e5b70 100644 --- a/backend/internal/service/openai_gateway_ollama_cloud_max_tokens.go +++ b/backend/internal/service/openai_gateway_ollama_cloud_max_tokens.go @@ -62,19 +62,30 @@ func ollamaCloudResponsesMaxOutputTokensClamp(account *Account, upstreamModel st if !isOllamaCloudOutboundBaseURL(ollamaCloudResponsesUpstreamBaseURL(account)) { return 0, false, "" } - value := gjson.GetBytes(body, "max_output_tokens") - sourceField := "" - if !value.Exists() { - if fallback := gjson.GetBytes(body, "max_tokens"); fallback.Exists() { - value = fallback - sourceField = "max_tokens" - } - } cap := ollamaCloudMaxTokensCap(account) - if cap <= 0 || !value.Exists() || value.Type != gjson.Number || value.Int() <= cap { + if cap <= 0 { return 0, false, "" } - return cap, true, sourceField + maxOutput := gjson.GetBytes(body, "max_output_tokens") + maxTokens := gjson.GetBytes(body, "max_tokens") + hasOverCapMaxTokens := maxTokens.Exists() && maxTokens.Type == gjson.Number && maxTokens.Int() > cap + if maxOutput.Exists() { + if maxOutput.Type == gjson.Number && maxOutput.Int() > cap { + sourceField := "" + if maxTokens.Exists() { + sourceField = "max_tokens" + } + return cap, true, sourceField + } + if hasOverCapMaxTokens && maxOutput.Type == gjson.Number { + return maxOutput.Int(), true, "max_tokens" + } + return 0, false, "" + } + if !hasOverCapMaxTokens { + return 0, false, "" + } + return cap, true, "max_tokens" } // ollamaCloudClampResponsesMaxOutputTokensBody 是原生 /v1/responses 出站 body 的 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 1080d2830e..1979c44c19 100644 --- a/backend/internal/service/openai_gateway_ollama_cloud_pricing_preflight.go +++ b/backend/internal/service/openai_gateway_ollama_cloud_pricing_preflight.go @@ -23,9 +23,11 @@ package service import ( "context" + "encoding/json" "fmt" "net/http" "strings" + "time" "github.com/Wei-Shaw/sub2api/internal/pkg/ctxkey" "github.com/gin-gonic/gin" @@ -57,11 +59,86 @@ func respondOpenAIOllamaCloudUnpricedModelError(c *gin.Context, err *openAIOllam if c == nil { return } - setOpsUpstreamError(c, http.StatusBadRequest, err.Error(), "") + writeServiceLocalInvalidRequestResponse(c, err.Error()) +} + +// writeServiceLocalInvalidRequestResponse 写出服务层本地拦截的 400 invalid_request_error: +// 若并发排队心跳或 compact 保活已将响应头提交为 SSE(200 text/event-stream),改按入站协议 +// 发送合规的 SSE 终止错误帧,避免向已开始的 SSE 流直接拼入裸 JSON;未开始流时保持原 400 JSON。 +func writeServiceLocalInvalidRequestResponse(c *gin.Context, message string) { + if c == nil { + return + } + setOpsUpstreamError(c, http.StatusBadRequest, message, "") + streamCommitted := StopOpenAICompactSSEKeepaliveCommitted(c) + if c.Writer != nil && (streamCommitted || c.Writer.Written()) { + MarkOpsStreamError(c, "invalid_request_error", message, http.StatusBadRequest) + MarkResponseCommitted(c) + path := "" + if c.Request != nil && c.Request.URL != nil { + path = c.Request.URL.Path + } + switch { + case strings.Contains(path, "/responses"): + reqID, _ := c.Get("request_id") + respID, _ := reqID.(string) + if strings.TrimSpace(respID) == "" { + respID = fmt.Sprintf("resp_%d", time.Now().UnixNano()) + } else if !strings.HasPrefix(respID, "resp_") { + respID = "resp_" + respID + } + model, _ := c.Get("ops_request_model") + modelStr, _ := model.(string) + eventBody, marshalErr := json.Marshal(map[string]any{ + "type": "response.failed", + "sequence_number": 0, + "response": map[string]any{ + "id": respID, + "object": "response", + "created_at": time.Now().Unix(), + "model": modelStr, + "status": "failed", + "output": []any{}, + "error": map[string]any{ + "code": "invalid_request_error", + "message": message, + }, + }, + }) + if marshalErr == nil { + _, _ = fmt.Fprintf(c.Writer, "event: response.failed\ndata: %s\n\n", eventBody) + } + case strings.Contains(path, "/messages"): + eventBody, marshalErr := json.Marshal(map[string]any{ + "type": "error", + "error": map[string]any{ + "type": "invalid_request_error", + "message": message, + }, + }) + if marshalErr == nil { + _, _ = fmt.Fprintf(c.Writer, "event: error\ndata: %s\n\n", eventBody) + } + default: + eventBody, marshalErr := json.Marshal(map[string]any{ + "error": map[string]any{ + "type": "invalid_request_error", + "message": message, + }, + }) + if marshalErr == nil { + _, _ = fmt.Fprintf(c.Writer, "data: %s\n\ndata: [DONE]\n\n", eventBody) + } + } + if flusher, ok := c.Writer.(http.Flusher); ok { + flusher.Flush() + } + return + } MarkResponseCommitted(c) - payload := gin.H{"error": gin.H{"type": "invalid_request_error", "message": err.Error()}} + payload := gin.H{"error": gin.H{"type": "invalid_request_error", "message": message}} if c.Request != nil && c.Request.URL != nil && strings.Contains(c.Request.URL.Path, "/messages") { - payload = gin.H{"type": "error", "error": gin.H{"type": "invalid_request_error", "message": err.Error()}} + payload = gin.H{"type": "error", "error": gin.H{"type": "invalid_request_error", "message": message}} } c.JSON(http.StatusBadRequest, payload) } diff --git a/backend/internal/service/openai_gateway_request_body.go b/backend/internal/service/openai_gateway_request_body.go index 33a3ff0805..272b2dbf2c 100644 --- a/backend/internal/service/openai_gateway_request_body.go +++ b/backend/internal/service/openai_gateway_request_body.go @@ -309,12 +309,10 @@ func (e *openAIResponsesStatelessFieldError) Error() string { // openAIForwardErrorAlreadyCommunicated 识别的消息前缀里,不置位的话 handler 会因 // Writer 已写出而向 JSON body 尾部追加 SSE 终止帧,污染响应体。 func respondOpenAIStatelessFieldError(c *gin.Context, statelessErr *openAIResponsesStatelessFieldError) { - setOpsUpstreamError(c, http.StatusBadRequest, statelessErr.Error(), "") - MarkResponseCommitted(c) - c.JSON(http.StatusBadRequest, gin.H{"error": gin.H{ - "type": "invalid_request_error", - "message": statelessErr.Error(), - }}) + if c == nil { + return + } + writeServiceLocalInvalidRequestResponse(c, statelessErr.Error()) } func shouldAliasDeepSeekResponsesInputImages(account *Account) bool { diff --git a/backend/internal/service/upstream_models.go b/backend/internal/service/upstream_models.go index 9ffb23988a..b5fc1954c9 100644 --- a/backend/internal/service/upstream_models.go +++ b/backend/internal/service/upstream_models.go @@ -743,7 +743,7 @@ func matchModelsDevProviderByKnownHost(registry map[string]modelsDevProvider, ac providerID = "openai" case "opencode.ai": providerID = "opencode-go" - case "ollama.com": + case "ollama.com", "www.ollama.com": // 实测 models.dev registry(api.json):provider ID 是 `ollama-cloud` // (不是 "ollama"),且其 api 字段为 https://ollama.com/v1 —— 常规 // base 走上方 API-URL 匹配即可命中;本 case 兜底 registry 形态漂移 @@ -1236,6 +1236,9 @@ func buildOpenAIAPIKeyModelsRequest(ctx context.Context, account *Account, valid // 列表同步需使用 OpenAI 格式 base(供应商 × 模式默认)。 baseURL := account.GetOpenAIFormatBaseURL() if strings.TrimSpace(baseURL) == "" { + if account.IsMultiProtocolAPIKey() { + return nil, newUpstreamModelSyncConfigError("No OpenAI base URL is configured for this account", nil) + } baseURL = "https://api.openai.com" } normalizedBaseURL, err := validateBaseURL(baseURL) From ad1ead4541a85f3d21e5cc484e3d467dd5e4a855 Mon Sep 17 00:00:00 2001 From: shaw Date: Sat, 5 Dec 2026 12:10:27 +0800 Subject: [PATCH 76/81] =?UTF-8?q?fix(frontend,=20catalog):=20=E5=AF=BC?= =?UTF-8?q?=E5=87=BA=E5=A4=9A=E5=8D=8F=E8=AE=AE=E9=BB=98=E8=AE=A4=E5=8D=8F?= =?UTF-8?q?=E8=AE=AE=E5=B9=B6=E4=BF=AE=E5=A4=8D=20ollama=5Fcloud=20?= =?UTF-8?q?=E7=BC=96=E8=BE=91=E5=BC=B9=E7=AA=97=E5=8D=8F=E8=AE=AE/?= =?UTF-8?q?=E5=9F=BA=E5=9D=80/=E7=99=BD=E5=90=8D=E5=8D=95=E5=9B=9E?= =?UTF-8?q?=E5=A1=AB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/internal/service/platform_catalog.go | 18 ++-- .../internal/service/platform_catalog_test.go | 1 + .../components/account/EditAccountModal.vue | 33 +++++++- .../__tests__/EditAccountModal.spec.ts | 82 +++++++++++++++++++ .../components/account/credentialsBuilder.ts | 14 ++++ .../constants/platformCatalog.builtin.json | 1 + frontend/src/constants/platformCatalog.ts | 1 + 7 files changed, 139 insertions(+), 11 deletions(-) diff --git a/backend/internal/service/platform_catalog.go b/backend/internal/service/platform_catalog.go index 7ef15368c5..eda3fefc49 100644 --- a/backend/internal/service/platform_catalog.go +++ b/backend/internal/service/platform_catalog.go @@ -25,9 +25,10 @@ type PlatformCatalogEntry struct { // ProviderProfileInfo 是 ProviderProfile 的对外形状。 type ProviderProfileInfo struct { - DefaultMode string `json:"default_mode"` - Routing ProviderRouting `json:"routing"` - ResponsesPath string `json:"responses_path,omitempty"` + DefaultMode string `json:"default_mode"` + DefaultAPIProtocol string `json:"default_api_protocol,omitempty"` + Routing ProviderRouting `json:"routing"` + ResponsesPath string `json:"responses_path,omitempty"` // ModelCatalog 表示模型支持的协议由上游 /models 自动获取(账号规则仍优先)。 ModelCatalog bool `json:"model_catalog,omitempty"` // Modes 以默认模式开头,其余按模式名排序。 @@ -76,11 +77,12 @@ func providerProfileInfo(profile *ProviderProfile) *ProviderProfileInfo { modes = append([]string{profile.DefaultMode}, modes...) } info := &ProviderProfileInfo{ - DefaultMode: profile.DefaultMode, - Routing: routing, - ResponsesPath: profile.ResponsesPath, - ModelCatalog: profile.ModelCatalog, - Modes: make([]ProviderModeInfo, 0, len(modes)), + DefaultMode: profile.DefaultMode, + DefaultAPIProtocol: profile.DefaultAPIProtocol, + Routing: routing, + ResponsesPath: profile.ResponsesPath, + ModelCatalog: profile.ModelCatalog, + Modes: make([]ProviderModeInfo, 0, len(modes)), } for _, mode := range modes { endpoints := profile.Modes[mode] diff --git a/backend/internal/service/platform_catalog_test.go b/backend/internal/service/platform_catalog_test.go index b6da5ae5d6..8476db463a 100644 --- a/backend/internal/service/platform_catalog_test.go +++ b/backend/internal/service/platform_catalog_test.go @@ -26,6 +26,7 @@ func TestBuildPlatformCatalogMirrorsPlatformListAndProfiles(t *testing.T) { } require.NotNil(t, entry.MultiProtocol, entry.ID) require.Equal(t, profile.DefaultMode, entry.MultiProtocol.DefaultMode, entry.ID) + require.Equal(t, profile.DefaultAPIProtocol, entry.MultiProtocol.DefaultAPIProtocol, entry.ID) require.Equal(t, profile.DefaultMode, entry.MultiProtocol.Modes[0].Mode, entry.ID) require.Equal(t, profile.ResponsesPath, entry.MultiProtocol.ResponsesPath, entry.ID) require.Len(t, entry.MultiProtocol.Modes, len(profile.Modes), entry.ID) diff --git a/frontend/src/components/account/EditAccountModal.vue b/frontend/src/components/account/EditAccountModal.vue index 1eab54094d..99da3379b1 100644 --- a/frontend/src/components/account/EditAccountModal.vue +++ b/frontend/src/components/account/EditAccountModal.vue @@ -3481,6 +3481,7 @@ import { buildPlanTypeOptions, cloneOpenCodeGoProtocolRules, defaultOpenCodeProtocolRules, + defaultProviderApiProtocol, defaultProviderProtocolRules, isMultiProtocolApiKeyPlatform, parseOllamaMonthlyCreditUsd, @@ -3826,7 +3827,11 @@ watch(editAccountMode, (mode, previousMode) => { editBaseUrl.value = editAdaptiveBaseUrls.value.chat_completions return } - editBaseUrl.value = defaultCNBaseUrl(props.account!.platform, mode, editApiProtocol.value) + const previousDefault = defaultCNBaseUrl(props.account!.platform, previousMode, editApiProtocol.value) + const nextDefault = defaultCNBaseUrl(props.account!.platform, mode, editApiProtocol.value) + if (!editBaseUrl.value.trim() || editBaseUrl.value.trim() === previousDefault) { + editBaseUrl.value = nextDefault + } }) watch(editOpenCodeAccountMode, (mode, previousMode) => { if (!isCNApiKeyAccount.value || props.account?.platform !== 'opencode_go' || syncingForm.value) return @@ -4957,7 +4962,7 @@ const syncFormFromAccount = (newAccount: Account | null) => { storedProtocol === 'anthropic' || storedProtocol === 'responses' ? storedProtocol - : 'chat_completions' + : defaultProviderApiProtocol(newAccount.platform) if (!cnSupportsNativeResponses(newAccount.platform, currentOpenCodeOrCNMode()) && editApiProtocol.value === 'responses') { editApiProtocol.value = 'chat_completions' } @@ -5021,6 +5026,20 @@ const syncFormFromAccount = (newAccount: Account | null) => { // Load model mappings and detect mode loadModelRestrictionFromMapping(credentials.model_mapping as Record | undefined) + if ( + newAccount.platform === 'ollama_cloud' && + allowedModels.value.length === 0 && + modelMappings.value.length === 0 && + Array.isArray((newAccount.extra as Record | undefined)?.allowed_models) + ) { + const extraAllowed = ((newAccount.extra as Record).allowed_models as unknown[]) + .filter((item): item is string => typeof item === 'string' && item.trim() !== '') + .map((item) => item.trim()) + if (extraAllowed.length > 0) { + allowedModels.value = Array.from(new Set(extraAllowed)) + modelRestrictionMode.value = 'whitelist' + } + } // Load pool mode poolModeEnabled.value = credentials.pool_mode === true @@ -5410,12 +5429,20 @@ const applyAccountSchedulingThresholdOverridePatch = ( currentCredentials: Record, platform: Account['platform'] | undefined = props.account?.platform ) => { - if (!supportsAccountSchedulingThresholdOverridePlatform(platform) || isOllamaCreditsAccount.value) { + if (!supportsAccountSchedulingThresholdOverridePlatform(platform)) { return } const current = normalizeAccountSchedulingThresholdOverride( currentCredentials[ACCOUNT_SCHEDULING_THRESHOLD_CREDENTIAL_KEY] ) + if (isOllamaCreditsAccount.value) { + if (current !== null) { + credentials[ACCOUNT_SCHEDULING_THRESHOLD_CREDENTIAL_KEY] = null + } else { + delete credentials[ACCOUNT_SCHEDULING_THRESHOLD_CREDENTIAL_KEY] + } + return + } if (!accountSchedulingThresholdOverrideEnabled.value) { if (current !== null) { credentials[ACCOUNT_SCHEDULING_THRESHOLD_CREDENTIAL_KEY] = null diff --git a/frontend/src/components/account/__tests__/EditAccountModal.spec.ts b/frontend/src/components/account/__tests__/EditAccountModal.spec.ts index 7d37d7b9b7..28a347e1e9 100644 --- a/frontend/src/components/account/__tests__/EditAccountModal.spec.ts +++ b/frontend/src/components/account/__tests__/EditAccountModal.spec.ts @@ -2224,3 +2224,85 @@ describe('EditAccountModal temp-unschedulable rule scope', () => { wrapper.unmount() }) }) + +describe('EditAccountModal ollama_cloud regressions', () => { + beforeEach(() => { + resetPlatformCatalog() + authIsSimpleMode.value = true + updateAccountMock.mockReset() + checkMixedChannelRiskMock.mockReset().mockResolvedValue({ has_risk: false }) + }) + + it('defaults missing api_protocol to adaptive and loads extra.allowed_models whitelist', async () => { + const account = { + ...buildAccount(), + platform: 'ollama_cloud', + type: 'apikey', + credentials: { + api_key: 'sk-ollama', + account_mode: 'ollama_legacy' + }, + extra: { + allowed_models: ['qwen3.5:397b', 'gpt-oss:120b'] + } + } as any + updateAccountMock.mockResolvedValue(account) + const wrapper = mountModal(account) + + expect(wrapper.get('[data-testid="model-whitelist-value"]').text()).toBe('qwen3.5:397b,gpt-oss:120b') + + await wrapper.get('form#edit-account-form').trigger('submit.prevent') + expect(updateAccountMock).toHaveBeenCalledTimes(1) + const submitted = updateAccountMock.mock.calls[0]?.[1]?.credentials + expect(submitted).toMatchObject({ + account_mode: 'ollama_legacy', + api_protocol: 'adaptive', + base_url: 'https://ollama.com/v1', + api_base_urls: { + chat_completions: 'https://ollama.com/v1', + responses: 'https://ollama.com/v1', + anthropic: 'https://ollama.com' + } + }) + wrapper.unmount() + }) + + it('preserves custom base_url in chat_completions protocol and clears threshold override when switching to credits', async () => { + const account = { + ...buildAccount(), + platform: 'ollama_cloud', + type: 'apikey', + credentials: { + api_key: 'sk-ollama', + account_mode: 'ollama_legacy', + api_protocol: 'chat_completions', + base_url: 'https://ollama-relay.internal/v1', + account_scheduling_threshold: 85, + model_mapping: { 'qwen3.5:397b': 'qwen3.5:397b' } + }, + extra: {} + } as any + updateAccountMock.mockResolvedValue(account) + const wrapper = mountModal(account) + + const creditsBtn = wrapper + .get('[data-testid="edit-generic-account-mode"]') + .findAll('button') + .find((btn) => btn.text().includes('admin.accounts.ollamaCloud.accountMode.credits')) + expect(creditsBtn).toBeDefined() + await creditsBtn!.trigger('click') + await flushPromises() + + await wrapper.get('form#edit-account-form').trigger('submit.prevent') + expect(updateAccountMock).toHaveBeenCalledTimes(1) + const submitted = updateAccountMock.mock.calls[0]?.[1]?.credentials + expect(submitted).toMatchObject({ + account_mode: 'ollama_credits', + api_protocol: 'chat_completions', + base_url: 'https://ollama-relay.internal/v1', + monthly_credit_usd: 60, + account_scheduling_threshold: null + }) + wrapper.unmount() + }) +}) diff --git a/frontend/src/components/account/credentialsBuilder.ts b/frontend/src/components/account/credentialsBuilder.ts index 0218070e19..d55a4ab595 100644 --- a/frontend/src/components/account/credentialsBuilder.ts +++ b/frontend/src/components/account/credentialsBuilder.ts @@ -385,6 +385,20 @@ export function providerRoutesByModel(platform: string): boolean { return getProviderProfile(platform)?.routing === 'by_model' } +/** 供应商未显式配置 api_protocol 时的默认协议(与后端 Account.GetAPIProtocol 对齐)。 */ +export function defaultProviderApiProtocol(platform: string): CnApiProtocol { + const configured = getProviderProfile(platform)?.default_api_protocol + if ( + configured === 'adaptive' || + configured === 'chat_completions' || + configured === 'anthropic' || + configured === 'responses' + ) { + return configured + } + return providerRoutesByModel(platform) ? 'adaptive' : 'chat_completions' +} + /** 上游模型目录给出每个模型支持的协议;未命中分流规则的模型据此选协议。 */ export function providerHasModelCatalog(platform: string): boolean { return getProviderProfile(platform)?.model_catalog === true diff --git a/frontend/src/constants/platformCatalog.builtin.json b/frontend/src/constants/platformCatalog.builtin.json index c4fec9271f..f5d2000f12 100644 --- a/frontend/src/constants/platformCatalog.builtin.json +++ b/frontend/src/constants/platformCatalog.builtin.json @@ -286,6 +286,7 @@ "cn_provider": false, "multi_protocol": { "default_mode": "ollama_legacy", + "default_api_protocol": "adaptive", "routing": "by_inbound", "modes": [ { diff --git a/frontend/src/constants/platformCatalog.ts b/frontend/src/constants/platformCatalog.ts index 16bc44e22a..24020af317 100644 --- a/frontend/src/constants/platformCatalog.ts +++ b/frontend/src/constants/platformCatalog.ts @@ -30,6 +30,7 @@ export interface ProviderModeInfo { export interface ProviderProfileInfo { default_mode: string + default_api_protocol?: string routing: ProviderRouting responses_path?: string /** 上游 /models 为每个模型给出 supported_endpoints,按模型分流时未命中规则的模型据此选协议。 */ From e9481fb0cb9a6997b520f2812192ddfcbe8b934a Mon Sep 17 00:00:00 2001 From: shaw Date: Sat, 5 Dec 2026 17:26:44 +0800 Subject: [PATCH 77/81] =?UTF-8?q?fix(billing,=20ollama):=20=E4=BF=AE?= =?UTF-8?q?=E5=A4=8D=E7=BB=84=E5=90=88=E6=B1=A0=E5=85=AC=E5=BC=80=E5=88=AB?= =?UTF-8?q?=E5=90=8D=E8=AE=A1=E8=B4=B9=E5=9B=9E=E9=80=80=E3=80=81=E9=80=9A?= =?UTF-8?q?=E9=85=8D=E5=80=8D=E7=8E=87=E5=8D=A1=E9=A2=84=E6=A3=80=E7=BB=95?= =?UTF-8?q?=E8=BF=87=E4=B8=8E=E5=B8=A6=20tag=20=E6=A8=A1=E5=9E=8B=E5=9F=BA?= =?UTF-8?q?=E5=90=8D=E7=A2=B0=E6=92=9E?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../handler/openai_gateway_handler.go | 4 ++ .../service/billing_inflight_reservation.go | 41 ++++++++++-- backend/internal/service/billing_service.go | 20 ++++++ backend/internal/service/channel_service.go | 16 ++++- .../service/gateway_request_pricing.go | 11 ++++ .../internal/service/gateway_usage_billing.go | 61 ++++++++++++++++-- .../service/model_pricing_resolver.go | 64 +++++++++++++++---- ..._gateway_ollama_cloud_pricing_preflight.go | 23 +++++-- .../internal/service/openai_gateway_usage.go | 54 ++++++++++++---- backend/internal/service/pricing_service.go | 20 +++++- 10 files changed, 270 insertions(+), 44 deletions(-) diff --git a/backend/internal/handler/openai_gateway_handler.go b/backend/internal/handler/openai_gateway_handler.go index 900bbea1b9..1803307630 100644 --- a/backend/internal/handler/openai_gateway_handler.go +++ b/backend/internal/handler/openai_gateway_handler.go @@ -5045,6 +5045,8 @@ func (h *OpenAIGatewayHandler) recordCyberPolicyIfMarked(c *gin.Context, apiKey // 提前拍成标量,避免在下方 goroutine 内访问 gin.Context。 sessionID := service.ExtractClientSessionID(c) nativeCompactionV2 := service.IsOpenAINativeCompactionV2(c) + upstreamModel := strings.TrimSpace(c.GetString(service.OpsUpstreamModelKey)) + pricingAt := service.RequestPricingAtFromContext(requestCtx) apiKeyPrefix := "" if apiKey != nil { apiKeyPrefix = keyPrefix(apiKey.Key, 8) @@ -5104,6 +5106,8 @@ func (h *OpenAIGatewayHandler) recordCyberPolicyIfMarked(c *gin.Context, apiKey Subscription: subscription, RequestID: requestID, Model: model, + UpstreamModel: upstreamModel, + PricingAt: pricingAt, Stream: stream, InputTokens: mark.UpstreamInTok, OutputTokens: mark.UpstreamOutTok, diff --git a/backend/internal/service/billing_inflight_reservation.go b/backend/internal/service/billing_inflight_reservation.go index d2b43ca566..b239521578 100644 --- a/backend/internal/service/billing_inflight_reservation.go +++ b/backend/internal/service/billing_inflight_reservation.go @@ -648,6 +648,37 @@ func (d inflightEstimateDeps) estimate(ctx context.Context, apiKey *APIKey, req // 免费分组:不计费,也无需预留。 return 0, true } + composite := apiKey.Group != nil && apiKey.Group.Platform == PlatformComposite + if composite { + if _, resolved := ResolvedTargetPlatformFromContext(ctx); !resolved { + if candidates := CompositeCandidatePlatformsFromContext(ctx); len(candidates) > 0 { + best := 0.0 + for _, candPlatform := range candidates { + if compositePoolPlatformDenied(ctx, candPlatform) { + continue + } + candCtx := WithResolvedTargetPlatform(ctx, candPlatform) + if c := d.estimateForContext(candCtx, apiKey, req, textRate, imageRate, true); c > best { + best = c + } + } + if best <= 0 { + logInflightUnpriced(req.Model, apiKey.GroupID) + return 0, false + } + return best, true + } + } + } + best := d.estimateForContext(ctx, apiKey, req, textRate, imageRate, composite) + if best <= 0 { + logInflightUnpriced(req.Model, apiKey.GroupID) + return 0, false + } + return best, true +} + +func (d inflightEstimateDeps) estimateForContext(ctx context.Context, apiKey *APIKey, req InflightEstimateRequest, textRate, imageRate float64, composite bool) float64 { primary, fallbacks, upstreamInput := inflightBillingModelCandidates(ctx, d, apiKey, req.Model) bestOf := func(models []string) float64 { best := 0.0 @@ -661,7 +692,6 @@ func (d inflightEstimateDeps) estimate(ctx context.Context, apiKey *APIKey, req best := bestOf(primary) // composite 分组:计费侧除非别名有显式渠道价,否则按实际转发的具体模型计费; // 别名本身可能命中家族模糊价(低估),因此与候选具体模型一起取最高。 - composite := apiKey.Group != nil && apiKey.Group.Platform == PlatformComposite if best <= 0 || composite { // 与 billableModelWithFallback 同口径:首选模型无价时回退到实际转发模型。 if c := bestOf(fallbacks); c > best { @@ -674,11 +704,7 @@ func (d inflightEstimateDeps) estimate(ctx context.Context, apiKey *APIKey, req } } } - if best <= 0 { - logInflightUnpriced(req.Model, apiKey.GroupID) - return 0, false - } - return best, true + return best } // EstimateInflightReservationCost 仅用基础定价的简化估算(保留给无 resolver 的调用方/测试)。 @@ -724,6 +750,9 @@ func (s *GatewayService) inflightEstimateDeps() inflightEstimateDeps { if GenericCompositePoolActive(ctx) { return s.listSchedulableAccountsForCompositePool(ctx, groupID, CompositeCandidatePlatformsFromContext(ctx)) } + if len(CompositeCandidatePlatformsFromContext(ctx)) > 0 { + forced = true + } accounts, _, err := snap.ListSchedulableAccounts(ctx, groupID, platform, forced) return accounts, err }, diff --git a/backend/internal/service/billing_service.go b/backend/internal/service/billing_service.go index 04951bf7a4..b754d045c5 100644 --- a/backend/internal/service/billing_service.go +++ b/backend/internal/service/billing_service.go @@ -1627,6 +1627,26 @@ func (s *BillingService) HasIdentifiedTokenPricing(model string) bool { return ok && pricing != nil } +// HasIdentifiedPositiveTokenPricing 判断模型是否在价格表中能被确定性识别且具备正 token 单价。 +// 用于区分「真实标准模型名(如 claude-sonnet-4-5)」与「未识别公开别名(如 haiku-pro)或 +// LiteLLM 中的 $0 实验占位条目(如 gemini-flash-experimental)」。 +func (s *BillingService) HasIdentifiedPositiveTokenPricing(model string) bool { + if s == nil { + return false + } + model = strings.ToLower(strings.TrimSpace(model)) + if model == "" { + return false + } + if s.pricingService != nil { + if pricing := s.pricingService.GetIdentifiedModelPricing(model); pricing != nil && !pricing.TokenPricingAbsent { + return pricing.InputCostPerToken > 0 || pricing.OutputCostPerToken > 0 + } + } + pricing, ok := s.fallbackPrices[model] + return ok && pricing != nil && (pricing.InputPricePerToken > 0 || pricing.OutputPricePerToken > 0) +} + // GetModelPricing 获取模型价格配置 func (s *BillingService) GetModelPricing(model string) (*ModelPricing, error) { return s.getModelPricingAt(model, timezone.Now()) diff --git a/backend/internal/service/channel_service.go b/backend/internal/service/channel_service.go index 1346258d42..fc48b3191b 100644 --- a/backend/internal/service/channel_service.go +++ b/backend/internal/service/channel_service.go @@ -647,16 +647,26 @@ func resolveMapping(lk *channelLookup, groupID int64, model string) ChannelMappi } // checkRestricted 基于已查找的渠道信息检查模型是否被限制。 -// 只在本平台的定价列表中查找。 +// 只在本平台的定价列表中查找;匹配顺序与 lookupChannelPricingNormalized 对齐 +// (字面 → Codex 归一 → 剥 ":tag"),避免基础名渠道价能计费却被模型限制误拦截。 func checkRestricted(lk *channelLookup, groupID int64, model string) bool { if !lk.channel.RestrictModels { return false } - modelLower := strings.ToLower(model) - // 使用与查找定价相同的跨平台逻辑 + modelLower := strings.ToLower(strings.TrimSpace(model)) if lookupPricingAcrossPlatforms(lk.cache, groupID, lk.platform, modelLower) != nil { return false } + if normalized := normalizeKnownOpenAICodexModel(model); normalized != "" && !strings.EqualFold(normalized, strings.TrimSpace(model)) { + if lookupPricingAcrossPlatforms(lk.cache, groupID, lk.platform, strings.ToLower(normalized)) != nil { + return false + } + } + if stripped, ok := normalizePricingModelNameForLookup(model); ok { + if lookupPricingAcrossPlatforms(lk.cache, groupID, lk.platform, strings.ToLower(stripped)) != nil { + return false + } + } return true } diff --git a/backend/internal/service/gateway_request_pricing.go b/backend/internal/service/gateway_request_pricing.go index d86d9b8bdd..039d0da1b1 100644 --- a/backend/internal/service/gateway_request_pricing.go +++ b/backend/internal/service/gateway_request_pricing.go @@ -43,6 +43,17 @@ func GatewayTokenRequestPricingAtFromContext(ctx context.Context) time.Time { return pricingAt } +// RequestPricingAtFromContext returns the frozen request pricing timestamp from +// either the OpenAI gateway or shared gateway request context. +func RequestPricingAtFromContext(ctx context.Context) time.Time { + if ctx != nil { + if pricingAt, ok := ctx.Value(openAIPricingAtCtxKey{}).(time.Time); ok && !pricingAt.IsZero() { + return pricingAt + } + } + return GatewayTokenRequestPricingAtFromContext(ctx) +} + func gatewayTokenRequestBillingGroupFromContext(ctx context.Context) *Group { if ctx == nil { return nil diff --git a/backend/internal/service/gateway_usage_billing.go b/backend/internal/service/gateway_usage_billing.go index 7d468ee871..146346bcd5 100644 --- a/backend/internal/service/gateway_usage_billing.go +++ b/backend/internal/service/gateway_usage_billing.go @@ -952,15 +952,24 @@ func (s *GatewayService) recordUsageMultipliers(ctx context.Context, apiKey *API // account 用于识别托管模型上游(CN 供应商 / OpenCode Go / Ollama Cloud,见 // accountServesHostedModels):其请求名只是入站别名,计费须按实际转发的模型。 func (s *GatewayService) recordUsageBillingModel(ctx context.Context, apiKey *APIKey, account *Account, result *ForwardResult, fields ChannelUsageFields) string { + isCompositeGroup := apiKey != nil && apiKey.Group != nil && apiKey.Group.Platform == PlatformComposite concreteBillingModel := forwardResultBillingModel(result.Model, result.UpstreamModel) hostedModels := accountServesHostedModels(account) if hostedModels { // 托管模型上游(composite 跨族池经 generic 链转发的 CN / Ollama Cloud 账号) // 按实际转发的模型计费,与 OpenAI 链 result.BillingModel 同口径。 concreteBillingModel = forwardResultBillingModel(result.UpstreamModel, result.Model) + } else if isCompositeGroup && strings.TrimSpace(result.UpstreamModel) != "" && + !strings.EqualFold(strings.TrimSpace(result.Model), strings.TrimSpace(result.UpstreamModel)) && + (s.billingService == nil || !s.billingService.HasIdentifiedPositiveTokenPricing(result.Model)) { + // composite 账号池/账号映射不改写请求体 model:result.Model 仍是未识别公开别名 + //(如 haiku-pro)或 $0 占位条目(如 gemini-flash-experimental)时,实际转发模型 + // 在 UpstreamModel;真实已识别标准模型(如 claude-sonnet-4-5)保持按请求模型计费。 + concreteBillingModel = strings.TrimSpace(result.UpstreamModel) } billingModel := concreteBillingModel - if fields.BillingModelSource == BillingModelSourceChannelMapped && fields.ChannelMappedModel != "" { + if fields.BillingModelSource == BillingModelSourceChannelMapped && fields.ChannelMappedModel != "" && + (!hostedModels || fields.ChannelMappedModel != fields.OriginalModel) { billingModel = fields.ChannelMappedModel } if fields.BillingModelSource == BillingModelSourceRequested && fields.OriginalModel != "" { @@ -970,7 +979,7 @@ func (s *GatewayService) recordUsageBillingModel(ctx context.Context, apiKey *AP // 进入上面的来源覆盖:任意别名查无价会静默落 $0,含家族词的别名则被价格表的 // 家族模糊匹配错计(如 Opus 流量按 Sonnet 兜底价)。除非管理员为别名显式配置了 // 渠道定价(OpenRouter 式自定价),composite 请求一律按实际转发的具体模型计费。 - if apiKey.Group != nil && apiKey.Group.Platform == PlatformComposite { + if isCompositeGroup { billingModel = s.compositeBillableModel(ctx, apiKey, billingModel, concreteBillingModel) } // 通用兜底(与 OpenAI 路径的 usageBillingModelCandidates 语义对齐): @@ -981,7 +990,9 @@ func (s *GatewayService) recordUsageBillingModel(ctx context.Context, apiKey *AP // 托管上游真正服务,未显式定价时不得按 Claude 价计费;候选全部落空则走零成本告警。 billingModel = firstUsageBillingModel(dropUnpricedClaudeBillingCandidates( usageBillingModelCandidates(billingModel, concreteBillingModel), - func(model string) bool { return s.resolveChannelPricing(ctx, model, apiKey) != nil }, + func(model string) bool { + return compositeAliasHasExplicitChannelPrice(s.resolveChannelPricing(ctx, model, apiKey), model) + }, )) } return billingModel @@ -1143,6 +1154,48 @@ func (s *GatewayService) calculateRecordUsageCost( return tokenCost } +// channelModelPricingHasExplicitRate 判断渠道/分组定价卡片是否显式配置了单价(而非仅配置倍率)。 +func channelModelPricingHasExplicitRate(chPricing *ChannelModelPricing) bool { + if chPricing == nil { + return false + } + if channelModelPricingHasTopLevelTokenRate(chPricing) || chPricing.PerRequestPrice != nil { + return true + } + for i := range chPricing.Intervals { + if intervalHasConcreteTokenRate(&chPricing.Intervals[i]) || chPricing.Intervals[i].PerRequestPrice != nil { + return true + } + } + return false +} + +// compositeAliasHasExplicitChannelPrice 判断公开别名是否具备针对该模型显式配置的渠道/分组定价 +// (排除裸 "*" 全局通配卡片与无单价的纯倍率卡片,避免 "*" 卡片把别名误留作计费模型)。 +func compositeAliasHasExplicitChannelPrice(resolved *ResolvedPricing, model string) bool { + if resolved == nil || (resolved.Source != PricingSourceGroup && resolved.Source != PricingSourceChannel) { + return false + } + chPricing := resolved.channelPricing + if !channelModelPricingHasExplicitRate(chPricing) { + return false + } + target := normalizeChannelPricingModelName(model) + for _, pattern := range chPricing.Models { + p := normalizeChannelPricingModelName(pattern) + if p == "" || p == "*" { + continue + } + if p == target { + return true + } + if strings.HasSuffix(p, "*") && strings.HasPrefix(target, strings.TrimSuffix(p, "*")) { + return true + } + } + return false +} + // compositeBillableModel 决定 composite 分组请求的计费模型:来源覆盖把计费模型 // 换成公开别名等非具体模型时,只有管理员为该名字显式配置了渠道定价才按其计费 // (OpenRouter 式自定价),否则回退到实际转发的具体模型,避免别名落入价格表的 @@ -1151,7 +1204,7 @@ func (s *GatewayService) compositeBillableModel(ctx context.Context, apiKey *API if concreteBillingModel == "" || billingModel == concreteBillingModel { return billingModel } - if s.resolveChannelPricing(ctx, billingModel, apiKey) != nil { + if compositeAliasHasExplicitChannelPrice(s.resolveChannelPricing(ctx, billingModel, apiKey), billingModel) { return billingModel } logger.LegacyPrintf("service.gateway", "[Billing] composite billing model %q has no explicit channel pricing, billing by concrete model %q", billingModel, concreteBillingModel) diff --git a/backend/internal/service/model_pricing_resolver.go b/backend/internal/service/model_pricing_resolver.go index b13d2d1a8e..ca49c6f306 100644 --- a/backend/internal/service/model_pricing_resolver.go +++ b/backend/internal/service/model_pricing_resolver.go @@ -266,9 +266,51 @@ func (r *ModelPricingResolver) applyChannelOverrides(ctx context.Context, groupI } } +func channelModelPricingHasTopLevelTokenRate(chPricing *ChannelModelPricing) bool { + if chPricing == nil { + return false + } + return chPricing.InputPrice != nil || + chPricing.OutputPrice != nil || + chPricing.CacheWritePrice != nil || + chPricing.CacheWrite1hPrice != nil || + chPricing.CacheWrite12hPrice != nil || + chPricing.CacheReadPrice != nil || + chPricing.ImageInputPrice != nil || + chPricing.ImageOutputPrice != nil +} + +func intervalHasConcreteTokenRate(iv *PricingInterval) bool { + if iv == nil { + return false + } + return iv.InputPrice != nil || + iv.OutputPrice != nil || + iv.CacheWritePrice != nil || + iv.CacheWrite1hPrice != nil || + iv.CacheWrite12hPrice != nil || + iv.CacheReadPrice != nil +} + // applyTokenOverrides 应用 token 模式的渠道覆盖 func (r *ModelPricingResolver) applyTokenOverrides(chPricing *ChannelModelPricing, resolved *ResolvedPricing) { + if chPricing.CacheWrite1hPrice != nil { + resolved.SupportsCacheBreakdown = true + } + for i := range chPricing.Intervals { + if chPricing.Intervals[i].CacheWrite1hPrice != nil { + resolved.SupportsCacheBreakdown = true + break + } + } + resolved.Intervals = filterValidIntervals(chPricing.Intervals) + if resolved.BasePricing == nil { + // 基础目录无价且渠道/分组卡片未显式填写任何顶层单价(例如仅配置 "*" 峰谷或推理倍率)时, + // 保持 BasePricing 为 nil,避免把未定价模型伪装成 $0 已定价条目绕过预检与缺价告警。 + if !channelModelPricingHasTopLevelTokenRate(chPricing) { + return + } resolved.BasePricing = &ModelPricing{} } else { // 防止修改 fallbackPrices 中的共享指针 @@ -277,25 +319,14 @@ func (r *ModelPricingResolver) applyTokenOverrides(chPricing *ChannelModelPricin } applyChannelTokenPriceOverrides(resolved.BasePricing, chPricing) - if chPricing.CacheWrite1hPrice != nil { - resolved.SupportsCacheBreakdown = true + if resolved.SupportsCacheBreakdown { resolved.BasePricing.SupportsCacheBreakdown = true } - for i := range chPricing.Intervals { - if chPricing.Intervals[i].CacheWrite1hPrice != nil { - resolved.SupportsCacheBreakdown = true - resolved.BasePricing.SupportsCacheBreakdown = true - break - } - } resolved.BasePricing.FastMultiplier = chPricing.FastMultiplier resolved.BasePricing.FlexMultiplier = chPricing.FlexMultiplier resolved.BasePricing.UltrafastMultiplierOverride = chPricing.UltrafastMultiplier resolved.BasePricing.ReasoningEffortMultipliers = maps.Clone(chPricing.ReasoningEffortMultipliers) applyChannelImagePriceOverrides(chPricing, resolved.BasePricing) - - // 区间未命中时回退到上面已经应用渠道覆盖的基础价。 - resolved.Intervals = filterValidIntervals(chPricing.Intervals) } // applyChannelImagePriceOverrides 应用渠道图片输入/输出价,规则与其他 token 字段一致: @@ -354,8 +385,17 @@ func (r *ModelPricingResolver) GetIntervalPricing(resolved *ResolvedPricing, tot if iv == nil { return resolved.BasePricing } + if resolved.BasePricing == nil && !intervalHasConcreteTokenRate(iv) { + return nil + } pricing := intervalToModelPricing(iv, resolved.BasePricing, resolved.channelPricing) + if resolved.BasePricing == nil && resolved.channelPricing != nil { + pricing.FastMultiplier = resolved.channelPricing.FastMultiplier + pricing.FlexMultiplier = resolved.channelPricing.FlexMultiplier + pricing.UltrafastMultiplierOverride = resolved.channelPricing.UltrafastMultiplier + pricing.ReasoningEffortMultipliers = maps.Clone(resolved.channelPricing.ReasoningEffortMultipliers) + } // BasePricing 为 nil(仅配置区间)时拷贝不到该标志,从 resolved 回填, // 保证 computeCacheCreationCost 的 5m/1h 分档判断不被区间路径吞掉。 pricing.SupportsCacheBreakdown = resolved.SupportsCacheBreakdown 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 1979c44c19..7bbafb97dd 100644 --- a/backend/internal/service/openai_gateway_ollama_cloud_pricing_preflight.go +++ b/backend/internal/service/openai_gateway_ollama_cloud_pricing_preflight.go @@ -210,10 +210,16 @@ func (s *OpenAIGatewayService) enforceOllamaCloudRequestPricingPreflight(ctx con if account == nil || !account.IsOllamaCloud() { return nil } - model := strings.TrimSpace(gjson.GetBytes(body, "model").String()) - if model == "" { + modelField := gjson.GetBytes(body, "model") + if !modelField.Exists() { return nil } + model := strings.TrimSpace(modelField.String()) + if model == "" { + err := &openAIOllamaCloudUnpricedModelError{model: ""} + respondOpenAIOllamaCloudUnpricedModelError(c, err) + return err + } if !s.ollamaCloudModelUnpricedForBilling(ctx, model) { return nil } @@ -229,11 +235,20 @@ func (s *GatewayService) enforceOllamaCloudRequestPricingPreflight(ctx context.C if s == nil || account == nil || !account.IsOllamaCloud() { return nil } - model := strings.TrimSpace(gjson.GetBytes(body, "model").String()) + modelField := gjson.GetBytes(body, "model") + model := strings.TrimSpace(modelField.String()) if model == "" { model = strings.TrimSpace(fallbackModel) } - if model == "" || !ollamaCloudModelUnpricedForBilling(ctx, s.resolver, model) { + if model == "" { + if !modelField.Exists() { + return nil + } + err := &openAIOllamaCloudUnpricedModelError{model: ""} + respondOpenAIOllamaCloudUnpricedModelError(c, err) + return err + } + if !ollamaCloudModelUnpricedForBilling(ctx, s.resolver, model) { return nil } err := &openAIOllamaCloudUnpricedModelError{model: model} diff --git a/backend/internal/service/openai_gateway_usage.go b/backend/internal/service/openai_gateway_usage.go index e541dd8f69..fb5c386445 100644 --- a/backend/internal/service/openai_gateway_usage.go +++ b/backend/internal/service/openai_gateway_usage.go @@ -51,14 +51,16 @@ type OpenAIRecordUsageInput struct { // 用量按上游真实 token 计费,与 WS cyber 及正常请求口径一致(InputTokens/OutputTokens // 取自上游 response.failed 报告的 usage,即 mark.UpstreamInTok/OutTok)。 type CyberPolicyUsageInput struct { - APIKey *APIKey - Account *Account - Subscription *UserSubscription - RequestID string - Model string - Stream bool - InputTokens int - OutputTokens int + APIKey *APIKey + Account *Account + Subscription *UserSubscription + RequestID string + Model string + UpstreamModel string + PricingAt time.Time + Stream bool + InputTokens int + OutputTokens int // 渠道归因与请求级 meta,使 cyber 计费行与正常 RecordUsage 行口径一致 // (否则 cyber 行 channel_id 等为空,渠道维度统计会遗漏 cyber 命中)。 InboundEndpoint string @@ -82,10 +84,21 @@ func (s *OpenAIGatewayService) RecordCyberPolicyUsageLog(ctx context.Context, in if s == nil || in.APIKey == nil || in.APIKey.User == nil || in.Account == nil || strings.TrimSpace(in.Model) == "" { return } + forwardInputModel := strings.TrimSpace(in.Model) + if mapped := strings.TrimSpace(in.ChannelMappedModel); mapped != "" { + forwardInputModel = mapped + } + billingModel := resolveOpenAIForwardModel(in.Account, forwardInputModel, "") + upstreamModel := strings.TrimSpace(in.UpstreamModel) + if upstreamModel == "" { + upstreamModel = normalizeOpenAIModelForUpstream(in.Account, billingModel) + } result := &OpenAIForwardResult{ - RequestID: in.RequestID, - Model: in.Model, - Stream: in.Stream, + RequestID: in.RequestID, + Model: in.Model, + BillingModel: billingModel, + UpstreamModel: upstreamModel, + Stream: in.Stream, Usage: OpenAIUsage{ InputTokens: in.InputTokens, OutputTokens: in.OutputTokens, @@ -97,6 +110,7 @@ func (s *OpenAIGatewayService) RecordCyberPolicyUsageLog(ctx context.Context, in User: in.APIKey.User, Account: in.Account, Subscription: in.Subscription, + PricingAt: in.PricingAt, InboundEndpoint: in.InboundEndpoint, UpstreamEndpoint: in.UpstreamEndpoint, UserAgent: in.UserAgent, @@ -297,18 +311,32 @@ func (s *OpenAIGatewayService) RecordUsage(ctx context.Context, input *OpenAIRec videoMultiplier := resolveVideoRateMultiplier(apiKey, baseMultiplier) var cost *CostBreakdown - billingModel := forwardResultBillingModel(result.Model, result.UpstreamModel) + concreteBillingModel := forwardResultBillingModel(result.Model, result.UpstreamModel) if result.BillingModel != "" { - billingModel = strings.TrimSpace(result.BillingModel) + concreteBillingModel = strings.TrimSpace(result.BillingModel) } + if apiKey != nil && apiKey.Group != nil && apiKey.Group.Platform == PlatformComposite && + strings.TrimSpace(result.UpstreamModel) != "" && + strings.EqualFold(concreteBillingModel, strings.TrimSpace(result.Model)) && + !strings.EqualFold(strings.TrimSpace(result.Model), strings.TrimSpace(result.UpstreamModel)) && + (s.billingService == nil || !s.billingService.HasIdentifiedPositiveTokenPricing(result.Model)) { + concreteBillingModel = strings.TrimSpace(result.UpstreamModel) + } + billingModel := concreteBillingModel if input.BillingModelSource == BillingModelSourceChannelMapped && input.ChannelMappedModel != "" && input.ChannelMappedModel != input.OriginalModel { billingModel = input.ChannelMappedModel } if input.BillingModelSource == BillingModelSourceRequested && input.OriginalModel != "" { billingModel = input.OriginalModel } + if apiKey != nil && apiKey.Group != nil && apiKey.Group.Platform == PlatformComposite && + concreteBillingModel != "" && billingModel != concreteBillingModel && + !compositeAliasHasExplicitChannelPrice(s.resolveOpenAIChannelPricing(ctx, billingModel, apiKey), billingModel) { + billingModel = concreteBillingModel + } billingModels := usageBillingModelCandidates( billingModel, + concreteBillingModel, result.BillingModel, input.ChannelMappedModel, input.OriginalModel, diff --git a/backend/internal/service/pricing_service.go b/backend/internal/service/pricing_service.go index f7dc44bb6c..e610e8ef71 100644 --- a/backend/internal/service/pricing_service.go +++ b/backend/internal/service/pricing_service.go @@ -1513,15 +1513,31 @@ func (s *PricingService) extractBaseName(model string) string { if len(part) == 8 && isNumeric(part) { continue } - // 跳过版本号(如 v1:0) + // 跳过 Bedrock 版本号(如 v1:0);非 Bedrock 的 ":tag"(如 3:675b、oss:120b、 + // mini:free)属于具体型号标签,整段剥掉会把多段名压成无关基础模型(mistral-large、 + // gpt、gpt-4o),此处返回空串交由二级确定性剥 tag 查价处理。 if strings.Contains(part, ":") { - continue + if isBedrockVersionSegment(part) { + continue + } + return "" } result = append(result, part) } return strings.Join(result, "-") } +func isBedrockVersionSegment(part string) bool { + if len(part) < 4 || part[0] != 'v' { + return false + } + colon := strings.IndexByte(part, ':') + if colon <= 1 || colon == len(part)-1 { + return false + } + return isNumeric(part[1:colon]) && isNumeric(part[colon+1:]) +} + // matchByModelFamily 基于模型系列匹配 func (s *PricingService) matchByModelFamily(model string) *LiteLLMModelPricing { model = normalizeAntigravityClaudeTierAlias(model) From 319ee85330be954b7137fb08f5ffcaee7efe8c94 Mon Sep 17 00:00:00 2001 From: shaw Date: Sat, 5 Dec 2026 17:26:44 +0800 Subject: [PATCH 78/81] =?UTF-8?q?fix(gateway,=20composite):=20=E4=BF=AE?= =?UTF-8?q?=E5=A4=8D=E8=B7=A8=E7=BB=84=E9=99=8D=E7=BA=A7=E5=87=AD=E6=8D=AE?= =?UTF-8?q?=E9=9A=94=E7=A6=BB=E3=80=81input=5Ftokens/compact=20=E6=B1=A0?= =?UTF-8?q?=E6=94=B6=E7=AA=84=E4=B8=8E=E8=BF=9E=E6=8E=A5=E6=B5=8B=E8=AF=95?= =?UTF-8?q?=E4=B8=AD=E8=BD=AC=E5=9F=BA=E5=9D=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../internal/handler/admin/account_handler.go | 13 + .../handler/composite_pool_attempt_policy.go | 46 +++ .../handler/composite_pool_audit_r6_test.go | 322 +++++++++++++++ backend/internal/handler/gateway_handler.go | 31 +- .../gateway_handler_chat_completions.go | 17 +- .../handler/gateway_handler_responses.go | 43 +- backend/internal/handler/grok_media.go | 9 +- .../handler/openai_gateway_count_tokens.go | 20 +- .../account_repo_ollama_cloud_usage.go | 8 +- .../internal/repository/scheduler_cache.go | 1 + .../scheduler_cache_ollama_cloud_test.go | 6 + backend/internal/server/routes/gateway.go | 49 ++- .../gateway_composite_pool_policy_test.go | 47 +++ backend/internal/service/account.go | 4 + .../account_ollama_cloud_pricing_gate.go | 9 + backend/internal/service/account_service.go | 3 + .../internal/service/account_test_service.go | 5 +- .../account_test_service_cn_adaptive.go | 6 +- backend/internal/service/admin_account.go | 31 ++ .../service/channel_monitor_quota_fetcher.go | 3 + .../service/composite_pool_audit_r6_test.go | 377 ++++++++++++++++++ .../service/gateway_anthropic_passthrough.go | 2 + .../internal/service/gateway_scheduling.go | 25 +- backend/internal/service/gateway_service.go | 3 + .../service/gateway_upstream_request.go | 5 + .../service/openai_gateway_cc_pipeline.go | 1 + .../service/openai_gateway_count_tokens.go | 2 +- .../service/openai_gateway_messages.go | 1 + .../internal/service/openai_model_mapping.go | 2 + .../service/openai_ws_forwarder_support.go | 4 + backend/internal/service/opencode_go.go | 1 + 31 files changed, 1046 insertions(+), 50 deletions(-) create mode 100644 backend/internal/handler/composite_pool_audit_r6_test.go create mode 100644 backend/internal/service/composite_pool_audit_r6_test.go diff --git a/backend/internal/handler/admin/account_handler.go b/backend/internal/handler/admin/account_handler.go index b73c76a58f..6d0ce5d618 100644 --- a/backend/internal/handler/admin/account_handler.go +++ b/backend/internal/handler/admin/account_handler.go @@ -2976,6 +2976,19 @@ func (h *AccountHandler) respondAvailableModels(c *gin.Context, account *service return } + if account.IsOllamaCloud() && len(account.GetModelMapping()) == 0 { + allowed := account.GetOllamaCloudOutboundModels() + if len(allowed) == 0 { + allowed = service.DefaultOllamaCloudModelIDs() + } + models := make([]claude.Model, 0, len(allowed)) + for _, id := range allowed { + models = append(models, claude.Model{ID: id, Type: "model", DisplayName: id}) + } + response.Success(c, models) + return + } + // Handle Claude/Anthropic accounts // For OAuth and Setup-Token accounts: return default models if account.IsOAuth() { diff --git a/backend/internal/handler/composite_pool_attempt_policy.go b/backend/internal/handler/composite_pool_attempt_policy.go index dc996f6dba..e37e38caf3 100644 --- a/backend/internal/handler/composite_pool_attempt_policy.go +++ b/backend/internal/handler/composite_pool_attempt_policy.go @@ -56,6 +56,52 @@ func compositePoolAttemptContext(base context.Context, account *service.Account) return service.WithResolvedTargetPlatform(base, account.Platform) } +// syncSelectionEffectiveGroup 在选号发生 ClaudeCodeOnly 跨分组降级切换时,同步当前 +// 调度分组、请求上下文、渠道映射与池状态(不改写最终计费归属 apiKey)。 +func (h *GatewayHandler) syncSelectionEffectiveGroup( + c *gin.Context, + baseAPIKey *service.APIKey, + schedAPIKey *service.APIKey, + baseCtx context.Context, + channelMapping service.ChannelMappingResult, + reqModel string, + isPoolRequest bool, + poolDenials *compositePoolPlatformDenials, + selection *service.AccountSelectionResult, +) (*service.APIKey, context.Context, service.ChannelMappingResult, bool, *compositePoolPlatformDenials, bool) { + if selection == nil || selection.EffectiveGroup == nil || schedAPIKey == nil || + selection.EffectiveGroup.ID == derefGroupID(schedAPIKey.GroupID) { + return schedAPIKey, baseCtx, channelMapping, isPoolRequest, poolDenials, false + } + nextKey := cloneAPIKeyWithGroup(baseAPIKey, selection.EffectiveGroup) + nextCtx := baseCtx + if selection.SelectionCtx != nil { + nextCtx = selection.SelectionCtx + } + if c != nil && c.Request != nil { + c.Request = c.Request.WithContext(nextCtx) + } + nextPool := service.GenericCompositePoolActive(nextCtx) + nextModel := reqModel + if !nextPool { + if upstreamModel, ok := service.ResolvedUpstreamModelFromContext(nextCtx); ok && upstreamModel != "" { + nextModel = upstreamModel + } + } + nextMapping := service.ChannelMappingResult{MappedModel: nextModel, Mapped: nextModel != reqModel} + if !nextPool && h != nil && h.gatewayService != nil { + resolvedMapping, _ := h.gatewayService.ResolveChannelMappingAndRestrict(nextCtx, nextKey.GroupID, nextModel) + if resolvedMapping.Mapped { + nextMapping = resolvedMapping + } + } + return nextKey, nextCtx, nextMapping, nextPool, newCompositePoolPlatformDenials(), true +} + +func compositeOrPoolDispatchActive(isPoolRequest bool, schedAPIKey *service.APIKey) bool { + return isPoolRequest || (schedAPIKey != nil && schedAPIKey.Group != nil && schedAPIKey.Group.Platform == service.PlatformComposite) +} + // compositePoolPlatformDenials 记录一次请求内被业务限制(配额/渠道限制)的平台, // 供 failover 再选时做整平台 mask。每个请求一个实例,仅在 handler 的顺序 failover // 循环里读写,无并发访问。 diff --git a/backend/internal/handler/composite_pool_audit_r6_test.go b/backend/internal/handler/composite_pool_audit_r6_test.go new file mode 100644 index 0000000000..f61952981a --- /dev/null +++ b/backend/internal/handler/composite_pool_audit_r6_test.go @@ -0,0 +1,322 @@ +//go:build unit + +package handler + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/Wei-Shaw/sub2api/internal/pkg/ctxkey" + middleware2 "github.com/Wei-Shaw/sub2api/internal/server/middleware" + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +type multiGroupStubRepo struct { + fakeGroupRepo + byID map[int64]*service.Group +} + +func (r *multiGroupStubRepo) GetByID(_ context.Context, id int64) (*service.Group, error) { + if g, ok := r.byID[id]; ok { + return g, nil + } + return nil, service.ErrGroupNotFound +} + +func (r *multiGroupStubRepo) GetByIDLite(ctx context.Context, id int64) (*service.Group, error) { + return r.GetByID(ctx, id) +} + +// C3 正向:anthropic 分组开启 ClaudeCodeOnly 并降级到 composite 池分组时,选中 OpenAI +// 账号必须经 OpenAI 兼容链转发,绝不能误入 GatewayService.Forward 把 API Key 发往 api.anthropic.com。 +func TestClaudeCodeOnlyFallback_AnthropicToCompositePoolDelegatesOpenAIWithoutLeak(t *testing.T) { + gin.SetMode(gin.TestMode) + + primaryID := int64(5101) + fallbackID := int64(5102) + primaryGroup := &service.Group{ + ID: primaryID, + Name: "ant-cc-only", + Platform: service.PlatformAnthropic, + Status: service.StatusActive, + Hydrated: true, + ClaudeCodeOnly: true, + FallbackGroupID: &fallbackID, + AllowMessagesDispatch: true, + } + fallbackGroup := &service.Group{ + ID: fallbackID, + Name: "comp-fallback-pool", + Platform: service.PlatformComposite, + Status: service.StatusActive, + Hydrated: true, + AllowMessagesDispatch: true, + } + + openAIAcc := &service.Account{ + ID: 8101, + Name: "oa-pool-member", + Platform: service.PlatformOpenAI, + Type: service.AccountTypeAPIKey, + Status: service.StatusActive, + Schedulable: true, + Concurrency: 2, + Priority: 1, + GroupIDs: []int64{fallbackID}, + Credentials: map[string]any{ + "api_key": "sk-openai-secret-never-send-to-anthropic", + "base_url": "https://openai-mock.example/v1", + "model_mapping": map[string]any{"shared-model": "gpt-5.4"}, + }, + Extra: map[string]any{ + "openai_responses_mode": "force_chat_completions", + "openai_responses_supported": false, + }, + } + antAcc := &service.Account{ + ID: 8102, + Name: "ant-pool-member", + Platform: service.PlatformAnthropic, + Type: service.AccountTypeAPIKey, + Status: service.StatusActive, + Schedulable: true, + Concurrency: 2, + Priority: 10, + GroupIDs: []int64{fallbackID}, + Credentials: map[string]any{ + "api_key": "sk-ant", + "base_url": "https://anthropic-mock.example", + "model_mapping": map[string]any{"shared-model": "claude-sonnet-4-5"}, + }, + } + accounts := []*service.Account{openAIAcc, antAcc} + + cfg := &config.Config{RunMode: config.RunModeSimple} + cfg.Security = config.SecurityConfig{URLAllowlist: config.URLAllowlistConfig{Enabled: false}} + + openAIUpstream := &compositePoolFakeUpstream{ + respond: func(_ compositePoolUpstreamCall, _ int) *http.Response { + return chatCompletionsOKResponse("gpt-5.4", 10, 5) + }, + } + gwUpstream := &compositePoolFakeUpstream{} + groupRepo := &multiGroupStubRepo{byID: map[int64]*service.Group{ + primaryID: primaryGroup, + fallbackID: fallbackGroup, + }} + schedCache := &platformScopedSchedulerCache{fakeSchedulerCache{accounts: accounts}} + snap := service.NewSchedulerSnapshotService(schedCache, nil, nil, nil, nil) + bs := service.NewBillingService(cfg, nil) + usageRepo := &compositePoolUsageLogRepo{} + + compositeResolver := service.NewCompositeRouteResolver(nil) + gwSvc := service.NewGatewayService( + nil, groupRepo, usageRepo, nil, nil, nil, nil, nil, cfg, snap, nil, bs, nil, nil, nil, + gwUpstream, nil, nil, nil, nil, nil, nil, nil, nil, nil, compositeResolver, nil, nil, + ) + compositeResolver.SetModelOwnershipResolver(func(context.Context, int64, string) (service.CompositeModelOwnership, error) { + return service.CompositeModelOwnership{ + Matched: true, + CandidatePlatforms: []string{service.PlatformAnthropic, service.PlatformOpenAI}, + RequiredClaimStrength: service.CompositeClaimExplicit, + }, nil + }) + oaSvc := service.NewOpenAIGatewayService( + nil, usageRepo, nil, nil, nil, nil, nil, cfg, nil, nil, bs, nil, nil, + openAIUpstream, service.NewDeferredService(nil, nil, 0), nil, nil, nil, nil, nil, nil, nil, + ) + billingCache := service.NewBillingCacheService(nil, nil, nil, nil, nil, nil, cfg, nil) + t.Cleanup(billingCache.Stop) + + h := &GatewayHandler{ + gatewayService: gwSvc, + openAIGatewayService: oaSvc, + billingCacheService: billingCache, + concurrencyHelper: NewConcurrencyHelper(service.NewConcurrencyService(&fakeConcurrencyCache{}), SSEPingFormatClaude, 0), + maxAccountSwitches: 3, + cfg: cfg, + openAIHandler: &OpenAIGatewayHandler{gatewayService: oaSvc}, + } + + body := `{"model":"shared-model","max_tokens":32,"messages":[{"role":"user","content":"hi"}]}` + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", strings.NewReader(body)) + c.Request.Header.Set("Content-Type", "application/json") + c.Request.Header.Set("User-Agent", "curl/8.0") // 非 Claude Code 客户端,触发 FallbackGroupID + apiKey := &service.APIKey{ + ID: 1, UserID: 1, GroupID: &primaryID, Group: primaryGroup, + User: &service.User{ID: 1, Concurrency: 5}, + } + ctx := context.WithValue(c.Request.Context(), ctxkey.Group, primaryGroup) + c.Request = c.Request.WithContext(ctx) + c.Set(string(middleware2.ContextKeyAPIKey), apiKey) + c.Set(string(middleware2.ContextKeyUser), middleware2.AuthSubject{UserID: 1, Concurrency: 5}) + + h.Messages(c) + + require.Equal(t, http.StatusOK, rec.Code, rec.Body.String()) + require.Empty(t, gwUpstream.snapshot(), "OpenAI APIKey must NEVER enter generic Anthropic HTTP upstream") + require.Len(t, openAIUpstream.snapshot(), 1, "OpenAI pool account must be delegated to OpenAIGatewayService") +} + +// H8:通用池委派 OpenAI 链因组推理强度策略 deny 返回 403 JSON 时,不得在尾部追加 SSE 错误帧。 +func TestCompositePoolDelegatedReasoningDeny_PureJSONWithoutTrailingSSE(t *testing.T) { + openAIAcc := &service.Account{ + ID: 8201, + Name: "oa-deny", + Platform: service.PlatformOpenAI, + Type: service.AccountTypeAPIKey, + Status: service.StatusActive, + Schedulable: true, + Concurrency: 2, + Priority: 1, + GroupIDs: []int64{41011}, + Credentials: map[string]any{ + "api_key": "sk-oa", + "base_url": "https://openai-mock.example/v1", + "model_mapping": map[string]any{"shared-effort": "gpt-5.4"}, + }, + } + antAcc := &service.Account{ + ID: 8202, + Name: "ant-peer", + Platform: service.PlatformAnthropic, + Type: service.AccountTypeAPIKey, + Status: service.StatusActive, + Schedulable: true, + Concurrency: 2, + Priority: 10, + GroupIDs: []int64{41011}, + Credentials: map[string]any{ + "api_key": "sk-ant", + "model_mapping": map[string]any{"shared-effort": "claude-sonnet-4-5"}, + }, + } + harness := newCompositePoolMessagesHarness(t, []*service.Account{openAIAcc, antAcc}) + harness.group.AllowMessagesDispatch = true + harness.group.MaxReasoningEffort = "medium" + harness.group.MaxReasoningEffortOverLimit = service.ReasoningEffortOverLimitDeny + + c, rec := harness.newRequest(t, "/v1/messages", + `{"model":"shared-effort","max_tokens":64,"output_config":{"effort":"max"},"messages":[{"role":"user","content":"hi"}]}`, + service.PlatformAnthropic, service.PlatformOpenAI) + harness.handler.Messages(c) + + require.Equal(t, http.StatusForbidden, rec.Code, rec.Body.String()) + require.NotContains(t, rec.Body.String(), "event: error", "403 JSON body must not be corrupted with trailing SSE frames") + var parsed map[string]any + require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &parsed), + "response body must remain valid single JSON document: %s", rec.Body.String()) +} + +// C3 反向:composite 池分组开启 ClaudeCodeOnly(且未开启 AllowMessagesDispatch 或受原组策略限制) +// 降级到普通 anthropic 分组时,不得套用原分组的池策略把降级分组账号逐个踢进 502。 +func TestClaudeCodeOnlyFallback_CompositePoolToAnthropicServesFallbackGroup(t *testing.T) { + gin.SetMode(gin.TestMode) + + primaryID := int64(5201) + fallbackID := int64(5202) + primaryGroup := &service.Group{ + ID: primaryID, + Name: "comp-cc-only", + Platform: service.PlatformComposite, + Status: service.StatusActive, + Hydrated: true, + ClaudeCodeOnly: true, + FallbackGroupID: &fallbackID, + } + fallbackGroup := &service.Group{ + ID: fallbackID, + Name: "ant-fallback", + Platform: service.PlatformAnthropic, + Status: service.StatusActive, + Hydrated: true, + } + antAcc := &service.Account{ + ID: 8301, + Name: "ant-fallback-acc", + Platform: service.PlatformAnthropic, + Type: service.AccountTypeAPIKey, + Status: service.StatusActive, + Schedulable: true, + Concurrency: 2, + Priority: 1, + GroupIDs: []int64{fallbackID}, + Credentials: map[string]any{ + "api_key": "sk-ant-fallback", + "base_url": "https://anthropic-fallback.example", + }, + } + + cfg := &config.Config{RunMode: config.RunModeSimple} + cfg.Security = config.SecurityConfig{URLAllowlist: config.URLAllowlistConfig{Enabled: false}} + gwUpstream := &compositePoolFakeUpstream{ + respond: func(_ compositePoolUpstreamCall, _ int) *http.Response { + return anthropicMessagesOKResponse() + }, + } + groupRepo := &multiGroupStubRepo{byID: map[int64]*service.Group{ + primaryID: primaryGroup, + fallbackID: fallbackGroup, + }} + schedCache := &platformScopedSchedulerCache{fakeSchedulerCache{accounts: []*service.Account{antAcc}}} + snap := service.NewSchedulerSnapshotService(schedCache, nil, nil, nil, nil) + bs := service.NewBillingService(cfg, nil) + usageRepo := &compositePoolUsageLogRepo{} + gwSvc := service.NewGatewayService( + nil, groupRepo, usageRepo, nil, nil, nil, nil, nil, cfg, snap, nil, bs, nil, nil, nil, + gwUpstream, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, + ) + oaSvc := service.NewOpenAIGatewayService( + nil, usageRepo, nil, nil, nil, nil, nil, cfg, nil, nil, bs, nil, nil, + &compositePoolFakeUpstream{}, service.NewDeferredService(nil, nil, 0), nil, nil, nil, nil, nil, nil, nil, + ) + billingCache := service.NewBillingCacheService(nil, nil, nil, nil, nil, nil, cfg, nil) + t.Cleanup(billingCache.Stop) + + h := &GatewayHandler{ + gatewayService: gwSvc, + openAIGatewayService: oaSvc, + billingCacheService: billingCache, + concurrencyHelper: NewConcurrencyHelper(service.NewConcurrencyService(&fakeConcurrencyCache{}), SSEPingFormatClaude, 0), + maxAccountSwitches: 3, + cfg: cfg, + openAIHandler: &OpenAIGatewayHandler{gatewayService: oaSvc}, + } + + body := `{"model":"claude-sonnet-4-5","max_tokens":32,"messages":[{"role":"user","content":"hi"}]}` + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", strings.NewReader(body)) + c.Request.Header.Set("Content-Type", "application/json") + c.Request.Header.Set("User-Agent", "curl/8.0") + ctx := service.WithCompositeRouteDecision(c.Request.Context(), service.CompositeRouteDecision{ + Matched: true, + Source: service.CompositeRouteSourceAccountPool, + GroupID: primaryID, + PublicModel: "claude-sonnet-4-5", + CandidatePlatforms: []string{service.PlatformDeepseek, service.PlatformOpenAI}, + RequiredClaimStrength: service.CompositeClaimExplicit, + }) + ctx = context.WithValue(ctx, ctxkey.Group, primaryGroup) + c.Request = c.Request.WithContext(ctx) + apiKey := &service.APIKey{ + ID: 1, UserID: 1, GroupID: &primaryID, Group: primaryGroup, + User: &service.User{ID: 1, Concurrency: 5}, + } + c.Set(string(middleware2.ContextKeyAPIKey), apiKey) + c.Set(string(middleware2.ContextKeyUser), middleware2.AuthSubject{UserID: 1, Concurrency: 5}) + + h.Messages(c) + + require.Equal(t, http.StatusOK, rec.Code, rec.Body.String()) + require.Len(t, gwUpstream.snapshot(), 1) +} diff --git a/backend/internal/handler/gateway_handler.go b/backend/internal/handler/gateway_handler.go index 63fbcfa396..978e0f34f2 100644 --- a/backend/internal/handler/gateway_handler.go +++ b/backend/internal/handler/gateway_handler.go @@ -697,6 +697,7 @@ func (h *GatewayHandler) Messages(c *gin.Context) { for { fs := NewFailoverState(h.maxAccountSwitches, hasBoundSession) retryWithFallback := false + schedAPIKey := currentAPIKey for { attemptParsedReq, err := parsedReq.CloneForBody(body) @@ -721,7 +722,7 @@ func (h *GatewayHandler) Messages(c *gin.Context) { selectCtx = maskedCtx } } - selection, err := h.gatewayService.SelectAccountWithLoadAwareness(selectCtx, currentAPIKey.GroupID, sessionKey, reqModel, fs.FailedAccountIDs, parsedReq.MetadataUserID, subject.UserID) + selection, err := h.gatewayService.SelectAccountWithLoadAwareness(selectCtx, schedAPIKey.GroupID, sessionKey, reqModel, fs.FailedAccountIDs, parsedReq.MetadataUserID, subject.UserID) if err != nil { if failoverClientGone(c) { reqLog.Info("gateway.account_select_aborted_client_disconnected", zap.Error(err)) @@ -769,6 +770,15 @@ func (h *GatewayHandler) Messages(c *gin.Context) { if rejectSelectedAccountIfModerated(c, account.ID, selectionReleaseFunc(selection), h.anthropicSecurityAuditError) { return } + var switchedGroup bool + schedAPIKey, _, channelMapping, isPoolRequest, poolDenials, switchedGroup = h.syncSelectionEffectiveGroup( + c, currentAPIKey, schedAPIKey, c.Request.Context(), channelMapping, reqModel, isPoolRequest, poolDenials, selection) + if switchedGroup && isPoolRequest { + bindOpenAIReasoningEffortPolicyForMessagesRequest(c, schedAPIKey, body) + if !schedAPIKey.Group.AllowMessagesDispatch { + poolDenials.deny(service.PlatformOpenAI) + } + } setOpsSelectedAccount(c, account.ID, account.Platform) // [DEBUG-STICKY] 打印账号选择结果 @@ -789,10 +799,13 @@ func (h *GatewayHandler) Messages(c *gin.Context) { // 候选全部被业务限制时按原语义终止,不误报 model unsupported。 attemptPolicy := compositePoolAttemptPolicy{AttemptCtx: c.Request.Context(), Mapping: channelMapping} isPoolAttempt := false - if isPoolRequest && compositePoolAttemptPolicyApplies(c, currentAPIKey) { + if isPoolRequest && compositePoolAttemptPolicyApplies(c, schedAPIKey) { attemptPolicy = evaluateCompositePoolAttemptPolicy( - c.Request.Context(), h.billingCacheService, h.openAIGatewayService, currentAPIKey, currentSubscription, account, reqModel, false) + c.Request.Context(), h.billingCacheService, h.openAIGatewayService, schedAPIKey, currentSubscription, account, reqModel, false) isPoolAttempt = true + if isPoolRequest && !schedAPIKey.Group.AllowMessagesDispatch && account.Platform == service.PlatformOpenAI { + attemptPolicy.Failure.ChannelRestricted = true + } if attemptPolicy.Failure.denied() { releaseCompositePoolSelection(selection) // 选号链可能已为该账号注册会话槽:排除前释放,镜像 profit-veto 分支。 @@ -817,7 +830,7 @@ func (h *GatewayHandler) Messages(c *gin.Context) { streamAwareWrite := func(cc *gin.Context, status int, code, message string) { h.handleStreamingAwareError(cc, status, code, message, streamStarted) } - cappedBody, changed, policyErr := applyCompositePoolAnthropicReasoningEffortPolicy(currentAPIKey, account, attemptParsedReq.Body.Bytes()) + cappedBody, changed, policyErr := applyCompositePoolAnthropicReasoningEffortPolicy(schedAPIKey, account, attemptParsedReq.Body.Bytes()) if policyErr != nil { releaseCompositePoolSelection(selection) h.gatewayService.ReleaseAccountSession(context.Background(), account, sessionKey) @@ -1035,11 +1048,12 @@ func (h *GatewayHandler) Messages(c *gin.Context) { if selection.ProfitGateActive() { attemptedAccountIDs = append(attemptedAccountIDs, account.ID) } + canCrossFamilyDispatch := compositeOrPoolDispatchActive(isPoolRequest, schedAPIKey) // 记录 Forward 前已写入字节数,Forward 后若增加则说明 SSE 内容已发,禁止 failover writerSizeBeforeForward := c.Writer.Size() if account.Platform == service.PlatformAntigravity && account.Type != service.AccountTypeAPIKey { result, err = h.antigravityGatewayService.Forward(requestCtx, c, account, attemptBody, hasBoundSession) - } else if isPoolRequest && account.Platform == service.PlatformGemini { + } else if canCrossFamilyDispatch && account.Platform == service.PlatformGemini { // Gemini 账号经 Gemini 兼容链转换(与非池 gemini 分支同一实现);generic // Forward 只能发往 Anthropic 协议上游,会把 Google 凭据发错主机。 if h.geminiCompatService == nil { @@ -1047,15 +1061,15 @@ func (h *GatewayHandler) Messages(c *gin.Context) { } else { result, err = h.geminiCompatService.Forward(requestCtx, c, account, attemptBody) } - } else if isPoolRequest && compositePoolAccountDelegatesToOpenAI(account) { - // 纯 OpenAI 族账号(无 Anthropic 协议能力)在池激活时委派 OpenAI 网关的 + } else if canCrossFamilyDispatch && compositePoolAccountDelegatesToOpenAI(account) { + // 纯 OpenAI 族账号(无 Anthropic 协议能力)在池激活或跨组切入 composite 时委派 OpenAI 网关的 // /v1/messages 兼容链:Anthropic → Responses/CC 协议转换、响应写回与 // failover 错误信封都由该链完成,错误信封已是 Anthropic 风格,不再二次包装。 // promptCacheKey 传 ""(内部按 cache_control / metadata 会话种子兜底); // defaultMappedModel 与 OpenAI handler Messages 路径同源。 openAIResult, delegateErr := h.openAIGatewayService.ForwardAsAnthropic( requestCtx, c, account, attemptBody, "", - strings.TrimSpace(resolveOpenAIMessagesDispatchMappedModel(c, apiKey, reqModel))) + strings.TrimSpace(resolveOpenAIMessagesDispatchMappedModel(c, schedAPIKey, reqModel))) delegated = true delegatedResult = openAIResult result = adaptOpenAIForwardResultToForwardResult(openAIResult) @@ -1212,6 +1226,7 @@ func (h *GatewayHandler) Messages(c *gin.Context) { currentSubscription = nil isPoolRequest = false poolDenials = newCompositePoolPlatformDenials() + channelMapping, _ = h.gatewayService.ResolveChannelMappingAndRestrict(c.Request.Context(), currentAPIKey.GroupID, reqModel) fallbackUsed = true retryWithFallback = true // 原分组账号已确定性失败(prompt too long),先释放其会话注册再走兜底分组 diff --git a/backend/internal/handler/gateway_handler_chat_completions.go b/backend/internal/handler/gateway_handler_chat_completions.go index f11d0e9943..cbe7598d08 100644 --- a/backend/internal/handler/gateway_handler_chat_completions.go +++ b/backend/internal/handler/gateway_handler_chat_completions.go @@ -211,6 +211,7 @@ func (h *GatewayHandler) ChatCompletions(c *gin.Context) { if groupPlatform == service.PlatformGemini { fs = NewFailoverState(h.maxAccountSwitchesGemini, false) } + schedAPIKey := apiKey for { if failoverClientGone(c) { @@ -225,7 +226,7 @@ func (h *GatewayHandler) ChatCompletions(c *gin.Context) { selectCtx = maskedCtx } } - selection, err := h.gatewayService.SelectAccountWithLoadAwareness(selectCtx, apiKey.GroupID, selectionSessionHash, reqModel, fs.FailedAccountIDs, "", int64(0)) + selection, err := h.gatewayService.SelectAccountWithLoadAwareness(selectCtx, schedAPIKey.GroupID, selectionSessionHash, reqModel, fs.FailedAccountIDs, "", int64(0)) if err != nil { if failoverClientGone(c) { reqLog.Info("gateway.cc.account_select_aborted_client_disconnected", zap.Error(err)) @@ -264,6 +265,12 @@ func (h *GatewayHandler) ChatCompletions(c *gin.Context) { if rejectSelectedAccountIfModerated(c, account.ID, selectionReleaseFunc(selection), h.openAISecurityAuditError) { return } + var switchedGroup bool + schedAPIKey, _, channelMapping, isPoolRequest, poolDenials, switchedGroup = h.syncSelectionEffectiveGroup( + c, apiKey, schedAPIKey, c.Request.Context(), channelMapping, reqModel, isPoolRequest, poolDenials, selection) + if switchedGroup && compositeOrPoolDispatchActive(isPoolRequest, schedAPIKey) && poolPromptCacheKey == "" && h.openAIGatewayService != nil { + poolPromptCacheKey = h.openAIGatewayService.ExtractSessionID(c, body) + } setOpsSelectedAccount(c, account.ID, account.Platform) // composite 账号池 per-attempt 平台策略:对实际选中平台补做 user×platform @@ -274,9 +281,9 @@ func (h *GatewayHandler) ChatCompletions(c *gin.Context) { // 候选全部被业务限制时按原语义终止,不误报 model unsupported。 attemptPolicy := compositePoolAttemptPolicy{AttemptCtx: c.Request.Context(), Mapping: channelMapping} isPoolAttempt := false - if isPoolRequest && compositePoolAttemptPolicyApplies(c, apiKey) { + if isPoolRequest && compositePoolAttemptPolicyApplies(c, schedAPIKey) { attemptPolicy = evaluateCompositePoolAttemptPolicy( - c.Request.Context(), h.billingCacheService, h.openAIGatewayService, apiKey, subscription, account, reqModel, false) + c.Request.Context(), h.billingCacheService, h.openAIGatewayService, schedAPIKey, subscription, account, reqModel, false) isPoolAttempt = true if attemptPolicy.Failure.denied() { releaseCompositePoolSelection(selection) @@ -371,7 +378,7 @@ func (h *GatewayHandler) ChatCompletions(c *gin.Context) { } // 账号池按选中账号应用分组推理强度策略(与单目标同语义,覆盖 openai / anthropic 账号)。 if isPoolRequest { - cappedBody, changed, policyErr := applyCompositePoolReasoningEffortPolicyForSelectedAccount(c, apiKey, account, forwardBody) + cappedBody, changed, policyErr := applyCompositePoolReasoningEffortPolicyForSelectedAccount(c, schedAPIKey, account, forwardBody) if policyErr != nil { if accountReleaseFunc != nil { accountReleaseFunc() @@ -420,7 +427,7 @@ func (h *GatewayHandler) ChatCompletions(c *gin.Context) { } setActualUpstreamEndpoint(c, EndpointAntigravityGenerateContent) result, err = h.antigravityGatewayService.ForwardAsChatCompletions(attemptCtx, c, account, forwardBody, parsedReq) - } else if isPoolRequest && compositePoolAccountDelegatesChatCompletionsToOpenAI(account) { + } else if compositeOrPoolDispatchActive(isPoolRequest, schedAPIKey) && compositePoolAccountDelegatesChatCompletionsToOpenAI(account) { // OpenAI 兼容族账号在池激活时委派 OpenAI 网关 CC 链:入站同族优先 //(零转换,adaptive 账号由该链直转供应商原生 CC 端点),响应写回与 // failover 错误信封都由该链完成,错误信封已是 OpenAI CC 风格,不再二次 diff --git a/backend/internal/handler/gateway_handler_responses.go b/backend/internal/handler/gateway_handler_responses.go index 4995af3cff..083df3ba83 100644 --- a/backend/internal/handler/gateway_handler_responses.go +++ b/backend/internal/handler/gateway_handler_responses.go @@ -224,6 +224,7 @@ func (h *GatewayHandler) Responses(c *gin.Context) { // 3. Account selection + failover loop fs := NewFailoverState(h.maxAccountSwitches, false) + schedAPIKey := apiKey for { if failoverClientGone(c) { @@ -238,7 +239,7 @@ func (h *GatewayHandler) Responses(c *gin.Context) { selectCtx = maskedCtx } } - selection, err := h.gatewayService.SelectAccountWithLoadAwareness(selectCtx, apiKey.GroupID, sessionHash, reqModel, fs.FailedAccountIDs, "", int64(0)) + selection, err := h.gatewayService.SelectAccountWithLoadAwareness(selectCtx, schedAPIKey.GroupID, sessionHash, reqModel, fs.FailedAccountIDs, "", int64(0)) if err != nil { if failoverClientGone(c) { reqLog.Info("gateway.responses.account_select_aborted_client_disconnected", zap.Error(err)) @@ -277,26 +278,34 @@ func (h *GatewayHandler) Responses(c *gin.Context) { if rejectSelectedAccountIfModerated(c, account.ID, selectionReleaseFunc(selection), h.responsesSecurityAuditError) { return } + var switchedGroup bool + schedAPIKey, requestCtx, channelMapping, isPoolRequest, poolDenials, switchedGroup = h.syncSelectionEffectiveGroup( + c, apiKey, schedAPIKey, requestCtx, channelMapping, reqModel, isPoolRequest, poolDenials, selection) + if switchedGroup && isPoolRequest { + service.SetOpenAIHTTPResponseOwner(c, subject.UserID, apiKey.ID) + } setOpsSelectedAccount(c, account.ID, account.Platform) // Gemini 账号没有 Responses 转换链(generic 链只能发往 Anthropic 协议上游,会把 // Google 凭据发错主机):池请求整平台屏蔽 gemini 后重选,候选只剩 gemini 时终止。 - if isPoolRequest && account.Platform == service.PlatformGemini { + if compositeOrPoolDispatchActive(isPoolRequest, schedAPIKey) && account.Platform == service.PlatformGemini { releaseCompositePoolSelection(selection) h.gatewayService.ReleaseAccountSession(context.Background(), account, sessionHash) - poolDenials.deny(account.Platform) - fs.FailedAccountIDs[account.ID] = struct{}{} - if _, ok := compositePoolSelectionRetryContext(requestCtx, poolDenials); !ok { - if streamStarted { - h.handleStreamingAwareError(c, http.StatusBadRequest, "invalid_request_error", - "Model is only available on Gemini accounts in this group, which do not support /v1/responses", true) - } else { - h.responsesErrorResponse(c, http.StatusBadRequest, "invalid_request_error", - "Model is only available on Gemini accounts in this group, which do not support /v1/responses") + if isPoolRequest { + poolDenials.deny(account.Platform) + fs.FailedAccountIDs[account.ID] = struct{}{} + if _, ok := compositePoolSelectionRetryContext(requestCtx, poolDenials); ok { + continue } - return } - continue + if streamStarted { + h.handleStreamingAwareError(c, http.StatusBadRequest, "invalid_request_error", + "Model is only available on Gemini accounts in this group, which do not support /v1/responses", true) + } else { + h.responsesErrorResponse(c, http.StatusBadRequest, "invalid_request_error", + "Model is only available on Gemini accounts in this group, which do not support /v1/responses") + } + return } // composite 账号池 per-attempt 平台策略:对实际选中平台补做 user×platform @@ -308,9 +317,9 @@ func (h *GatewayHandler) Responses(c *gin.Context) { // unsupported。 attemptPolicy := compositePoolAttemptPolicy{AttemptCtx: requestCtx, Mapping: channelMapping} isPoolAttempt := false - if isPoolRequest && compositePoolAttemptPolicyApplies(c, apiKey) { + if isPoolRequest && compositePoolAttemptPolicyApplies(c, schedAPIKey) { attemptPolicy = evaluateCompositePoolAttemptPolicy( - requestCtx, h.billingCacheService, h.openAIGatewayService, apiKey, subscription, account, reqModel, false) + requestCtx, h.billingCacheService, h.openAIGatewayService, schedAPIKey, subscription, account, reqModel, false) isPoolAttempt = true if attemptPolicy.Failure.denied() { releaseCompositePoolSelection(selection) @@ -398,7 +407,7 @@ func (h *GatewayHandler) Responses(c *gin.Context) { } // 账号池按选中账号应用分组推理强度策略(与单目标同语义,覆盖 openai / anthropic 账号)。 if isPoolRequest { - cappedBody, changed, policyErr := applyCompositePoolReasoningEffortPolicyForSelectedAccount(c, apiKey, account, forwardBody) + cappedBody, changed, policyErr := applyCompositePoolReasoningEffortPolicyForSelectedAccount(c, schedAPIKey, account, forwardBody) if policyErr != nil { if accountReleaseFunc != nil { accountReleaseFunc() @@ -439,7 +448,7 @@ func (h *GatewayHandler) Responses(c *gin.Context) { } setActualUpstreamEndpoint(c, EndpointAntigravityGenerateContent) result, err = h.antigravityGatewayService.ForwardAsResponses(attemptCtx, c, account, forwardBody, parsedReq) - } else if isPoolRequest && compositePoolAccountDelegatesResponsesToOpenAI(account) { + } else if compositeOrPoolDispatchActive(isPoolRequest, schedAPIKey) && compositePoolAccountDelegatesResponsesToOpenAI(account) { // 纯 OpenAI 族 / 原生 Responses 账号在池激活时委派 OpenAI 网关 Responses // 链:入站同族优先(零或近零转换),响应写回与 failover 错误信封都由该 // 链完成,错误信封已是 OpenAI Responses 风格,不再二次包装。 diff --git a/backend/internal/handler/grok_media.go b/backend/internal/handler/grok_media.go index 91be906c71..e88b321627 100644 --- a/backend/internal/handler/grok_media.go +++ b/backend/internal/handler/grok_media.go @@ -163,7 +163,11 @@ func (h *OpenAIGatewayHandler) handleGrokMedia(c *gin.Context, endpoint service. defer userReleaseFunc() } - if err := h.billingCacheService.CheckBillingEligibility(c.Request.Context(), apiKey.User, apiKey, apiKey.Group, subscription, service.QuotaPlatform(c.Request.Context(), apiKey)); err != nil { + quotaPlatform := service.QuotaPlatform(c.Request.Context(), apiKey) + if quotaPlatform == "" { + quotaPlatform = platform + } + if err := h.billingCacheService.CheckBillingEligibility(c.Request.Context(), apiKey.User, apiKey, apiKey.Group, subscription, quotaPlatform); err != nil { reqLog.Info("grok_media.billing_eligibility_check_failed", zap.Error(err)) status, code, message, retryAfter := billingErrorDetails(err) if retryAfter > 0 { @@ -206,6 +210,9 @@ func (h *OpenAIGatewayHandler) handleGrokMedia(c *gin.Context, endpoint service. // 范围内:显式豁免,防止 service 层防御性装门按文本 D 误过滤媒体请求, // 也防止已计费的在途视频任务因绑定账号被门排除而查询返回伪 404。 requestCtx := service.WithOpenAIProfitControlSuppressed(c.Request.Context()) + if apiKey.Group != nil && apiKey.Group.Platform == service.PlatformComposite { + requestCtx = service.WithResolvedTargetPlatform(service.WithoutCompositeRouteContext(requestCtx), platform) + } profitVetoCount := 0 failedAccountIDs := make(map[int64]struct{}) sameAccountRetryCount := make(map[int64]int) diff --git a/backend/internal/handler/openai_gateway_count_tokens.go b/backend/internal/handler/openai_gateway_count_tokens.go index 15588a0c28..f7a09bca9e 100644 --- a/backend/internal/handler/openai_gateway_count_tokens.go +++ b/backend/internal/handler/openai_gateway_count_tokens.go @@ -84,6 +84,9 @@ func (h *OpenAIGatewayHandler) ResponsesInputTokens(c *gin.Context) { } channelMapping, _ := h.gatewayService.ResolveChannelMappingAndRestrict(c.Request.Context(), apiKey.GroupID, reqModel) + if compositePoolAttemptPolicyApplies(c, apiKey) { + channelMapping = service.ChannelMappingResult{MappedModel: reqModel} + } routingModel := reqModel forwardBody := body if channelMapping.Mapped { @@ -127,6 +130,13 @@ func (h *OpenAIGatewayHandler) ResponsesInputTokens(c *gin.Context) { return } setOpsSelectedAccount(c, account.ID, account.Platform) + if compositePoolAttemptPolicyApplies(c, apiKey) { + attemptMapping := h.gatewayService.CompositePoolAttemptChannelMapping( + compositePoolAttemptContext(c.Request.Context(), account), apiKey.GroupID, reqModel) + if attemptMapping.Mapped { + forwardBody = h.gatewayService.ReplaceModelInBody(body, attemptMapping.MappedModel) + } + } if err := h.gatewayService.ForwardResponsesInputTokens(c.Request.Context(), c, account, forwardBody); err != nil { reqLog.Error("openai_input_tokens.forward_failed", zap.Int64("account_id", account.ID), zap.Error(err)) } @@ -250,6 +260,9 @@ func (h *OpenAIGatewayHandler) CountTokens(c *gin.Context) { setOpsEndpointContext(c, "", int16(service.RequestTypeFromLegacy(false, false))) channelMapping, _ := h.gatewayService.ResolveChannelMappingAndRestrict(c.Request.Context(), apiKey.GroupID, reqModel) + if compositePoolAttemptPolicyApplies(c, apiKey) { + channelMapping = service.ChannelMappingResult{MappedModel: reqModel} + } mappedBodyForMessages := newOpenAIModelMappedBodyCache(body, h.gatewayService.ReplaceModelInBody) subscription, _ := middleware2.GetSubscriptionFromContext(c) @@ -304,7 +317,12 @@ func (h *OpenAIGatewayHandler) CountTokens(c *gin.Context) { return } setOpsSelectedAccount(c, account.ID, account.Platform) - forwardBody := mappedBodyForMessages(channelMapping.Mapped, channelMapping.MappedModel) + attemptMapping := channelMapping + if compositePoolAttemptPolicyApplies(c, apiKey) { + attemptMapping = h.gatewayService.CompositePoolAttemptChannelMapping( + compositePoolAttemptContext(c.Request.Context(), account), apiKey.GroupID, reqModel) + } + forwardBody := mappedBodyForMessages(attemptMapping.Mapped, attemptMapping.MappedModel) defaultMappedModel := preferredMappedModel if err := h.gatewayService.ForwardCountTokensAsAnthropic(c.Request.Context(), c, account, forwardBody, defaultMappedModel); err != nil { diff --git a/backend/internal/repository/account_repo_ollama_cloud_usage.go b/backend/internal/repository/account_repo_ollama_cloud_usage.go index 18379b865c..964ac6f578 100644 --- a/backend/internal/repository/account_repo_ollama_cloud_usage.go +++ b/backend/internal/repository/account_repo_ollama_cloud_usage.go @@ -280,7 +280,13 @@ func (r *accountRepository) updateOllamaCloudUsageGroup( return nil } if dbent.TxFromContext(ctx) != nil { - return apply(ctx, clientFromContext(ctx, r.client)) + if err := apply(ctx, clientFromContext(ctx, r.client)); err != nil { + return err + } + service.AfterAccountCommit(ctx, func(commitCtx context.Context) { + r.syncOllamaCloudUsageSchedulerState(commitCtx, syncedMemberIDs) + }) + return nil } tx, err := r.client.Tx(ctx) if errors.Is(err, dbent.ErrTxStarted) { diff --git a/backend/internal/repository/scheduler_cache.go b/backend/internal/repository/scheduler_cache.go index de95040ff7..dbefc2b697 100644 --- a/backend/internal/repository/scheduler_cache.go +++ b/backend/internal/repository/scheduler_cache.go @@ -1754,6 +1754,7 @@ func filterSchedulerExtra(extra map[string]any) map[string]any { service.UpstreamBillingProbeExtraKey, service.GrokMediaEligibleExtraKey, "grok_billing_snapshot", + "grok_usage_snapshot", } filtered := make(map[string]any) for _, key := range keys { diff --git a/backend/internal/repository/scheduler_cache_ollama_cloud_test.go b/backend/internal/repository/scheduler_cache_ollama_cloud_test.go index 2c49fb65b2..3aa1512e8c 100644 --- a/backend/internal/repository/scheduler_cache_ollama_cloud_test.go +++ b/backend/internal/repository/scheduler_cache_ollama_cloud_test.go @@ -105,4 +105,10 @@ func TestSchedulerMetadataAccount_KeepsOllamaCloudThresholdAndProtocolProjection require.NoError(t, json.Unmarshal(creditsMeta, &projectedCredits)) require.Equal(t, service.AccountModeOllamaCredits, projectedCredits.GetOllamaCloudAccountMode()) require.False(t, service.EvaluateAccountSchedulingThreshold(&projectedCredits, nil, now).ShouldPause) + + // H7: Grok OAuth 配额快照(grok_usage_snapshot)必须进入投影,保证跨族池自动暂停生效。 + grokExtra := filterSchedulerExtra(map[string]any{ + "grok_usage_snapshot": map[string]any{"remaining_queries": 0}, + }) + require.Contains(t, grokExtra, "grok_usage_snapshot") } diff --git a/backend/internal/server/routes/gateway.go b/backend/internal/server/routes/gateway.go index 322efbda0e..647a634d16 100644 --- a/backend/internal/server/routes/gateway.go +++ b/backend/internal/server/routes/gateway.go @@ -181,8 +181,18 @@ func RegisterGatewayRoutes( }) return } - if service.IsOpenAIResponsesInputTokensRequestPath(c) && isOpenAIResponsesCompatibleGatewayPlatform(c) { - h.OpenAIGateway.ResponsesInputTokens(c) + if service.IsOpenAIResponsesInputTokensRequestPath(c) { + if isOpenAIResponsesCompatibleGatewayPlatform(c) { + h.OpenAIGateway.ResponsesInputTokens(c) + return + } + service.MarkOpsClientBusinessLimited(c, service.OpsClientBusinessLimitedReasonLocalFeatureGate) + c.AbortWithStatusJSON(http.StatusNotFound, gin.H{ + "error": gin.H{ + "type": "not_found_error", + "message": "Responses input_tokens is not supported for this platform", + }, + }) return } next(c) @@ -711,14 +721,23 @@ func compositeTargetPlatformMiddleware(resolver *service.CompositeRouteResolver) writeCompositeRouteAdmissionError(c, http.StatusBadRequest, fmt.Sprintf("Model %q has no OpenAI-compatible account in this composite group to continue previous_response_id; resend the full conversation without previous_response_id", model)) return } - } else if isCompositePoolResponsesCompact(c, decision) { - // /responses/compact 仅由 OpenAI 网关链支持(含 compact 归一化、渠道限制与心跳): - // 跨族候选池收窄到 OpenAI 兼容族,避免落入通用网关按普通 Responses 误转协议。 + } else if isCompositePoolResponsesCompact(c, decision, body) { + // /responses/compact(含裸 /responses 的 compaction_trigger v1/v2)仅由 OpenAI 网关链 + // 支持(含 compact 归一化、渠道限制与心跳):跨族候选池收窄到 OpenAI 兼容族, + // 避免落入通用网关按普通 Responses 误转协议。 decision.CandidatePlatforms = openAICompatibleCandidatePlatforms(decision.CandidatePlatforms) if len(decision.CandidatePlatforms) == 0 { writeCompositeRouteAdmissionError(c, http.StatusBadRequest, fmt.Sprintf("Model %q has no OpenAI-compatible account in this composite group to support /responses/compact", model)) return } + } else if isCompositePoolResponsesInputTokens(c, decision) { + // /responses/input_tokens 为免计费 token 预检端点,仅由 OpenAI 网关链支持: + // 跨族候选池收窄到 OpenAI 兼容族,防止落入通用网关触发真实推理并扣费。 + decision.CandidatePlatforms = openAICompatibleCandidatePlatforms(decision.CandidatePlatforms) + if len(decision.CandidatePlatforms) == 0 { + writeCompositeRouteAdmissionError(c, http.StatusBadRequest, fmt.Sprintf("Model %q has no OpenAI-compatible account in this composite group to support /responses/input_tokens", model)) + return + } } c.Request = c.Request.WithContext(service.WithCompositeRouteDecision(c.Request.Context(), decision)) if upstreamModel := strings.TrimSpace(decision.UpstreamModel); upstreamModel != "" && upstreamModel != model && gjson.ValidBytes(body) { @@ -804,7 +823,7 @@ func isCompositePoolResponsesContinuation(c *gin.Context, decision service.Compo return strings.TrimSpace(gjson.GetBytes(body, "previous_response_id").String()) != "" } -func isCompositePoolResponsesCompact(c *gin.Context, decision service.CompositeRouteDecision) bool { +func isCompositePoolResponsesCompact(c *gin.Context, decision service.CompositeRouteDecision, body []byte) bool { if c == nil || c.Request == nil || c.Request.URL == nil { return false } @@ -812,7 +831,23 @@ func isCompositePoolResponsesCompact(c *gin.Context, decision service.CompositeR return false } path := strings.TrimRight(c.Request.URL.Path, "/") - return strings.HasSuffix(path, "/responses/compact") + if strings.HasSuffix(path, "/responses/compact") { + return true + } + if path == "/v1/responses" || path == "/responses" || path == "/backend-api/codex/responses" { + return service.HasCompactionTriggerInInput(body) + } + return false +} + +func isCompositePoolResponsesInputTokens(c *gin.Context, decision service.CompositeRouteDecision) bool { + if c == nil || c.Request == nil || c.Request.URL == nil { + return false + } + if strings.TrimSpace(decision.TargetPlatform) != "" || len(decision.CandidatePlatforms) == 0 { + return false + } + return service.IsOpenAIResponsesInputTokensRequestPath(c) } // openAICompatibleCandidatePlatforms 返回候选平台中经 OpenAI 网关转发的平台(保持顺序)。 diff --git a/backend/internal/server/routes/gateway_composite_pool_policy_test.go b/backend/internal/server/routes/gateway_composite_pool_policy_test.go index 3e20023b75..d96dac0b74 100644 --- a/backend/internal/server/routes/gateway_composite_pool_policy_test.go +++ b/backend/internal/server/routes/gateway_composite_pool_policy_test.go @@ -628,3 +628,50 @@ func TestCompositePoolMessagesClaudeAliasUsesAccountMapping(t *testing.T) { require.Equal(t, "deepseek-chat", gjson.GetBytes(captured[0].body, "model").String(), "outbound model must come from the selected account's model_mapping, not the gpt-5.x dispatch default") } + +// C4:跨族候选池([anthropic, deepseek])调用免计费 /v1/responses/input_tokens 时, +// 必须收窄到 OpenAI 兼容族走 ResponsesInputTokens,绝不能跌落进 GatewayHandler.Responses +// 执行真实付费生成。 +func TestCompositeCrossFamilyPool_ResponsesInputTokensNeverTriggersGeneration(t *testing.T) { + upstream := &captureUpstream{} + group := newPoolPolicyGroup(nil) + router, _ := newCompositePoolPolicyTestRouter(t, poolPolicyRouterInput{ + group: group, + accounts: []service.Account{ + newPoolPolicyAccountWithMapping(4301, service.PlatformAnthropic, 0, map[string]any{"shared-count": "claude-sonnet-4-6"}), + newPoolPolicyAccountWithMapping(4302, service.PlatformDeepseek, 5, map[string]any{"shared-count": "deepseek-chat"}), + }, + upstream: upstream, + }) + + w := postPoolPolicyRequest(t, router, "/v1/responses/input_tokens", + `{"model":"shared-count","input":"hello world"}`) + require.Equal(t, http.StatusOK, w.Code, w.Body.String()) + require.Equal(t, "response.input_tokens", gjson.GetBytes(w.Body.Bytes(), "object").String()) + require.Greater(t, gjson.GetBytes(w.Body.Bytes(), "input_tokens").Int(), int64(0)) + require.Empty(t, upstream.capturedSnapshot(), "token count must estimate locally on CN relay and never run Anthropic generation") +} + +// H6:裸 /v1/responses 携带 compaction_trigger 时,跨族池必须收窄到 OpenAI 兼容族。 +func TestCompositeCrossFamilyPool_BareResponsesCompactionTriggerNarrowsToOpenAIFamily(t *testing.T) { + upstream := &captureUpstream{} + group := newPoolPolicyGroup(nil) + ds := newPoolPolicyAccountWithMapping(4312, service.PlatformDeepseek, 5, map[string]any{"shared-compact": "deepseek-chat"}) + ds.Credentials["api_protocol"] = service.APIProtocolResponses + router, _ := newCompositePoolPolicyTestRouter(t, poolPolicyRouterInput{ + group: group, + accounts: []service.Account{ + newPoolPolicyAccountWithMapping(4311, service.PlatformAnthropic, 0, map[string]any{"shared-compact": "claude-sonnet-4-6"}), + ds, + }, + upstream: upstream, + }) + + w := postPoolPolicyRequest(t, router, "/v1/responses", + `{"model":"shared-compact","stream":false,"input":[{"type":"compaction_trigger"}]}`) + // 收窄到兼容族后绝不会发往 anthropic-pool-fake.test。 + for _, rec := range upstream.capturedSnapshot() { + require.NotEqual(t, "anthropic-pool-fake.test", rec.host, + "compaction_trigger on bare /v1/responses must never route to generic Anthropic handler; resp=%s", w.Body.String()) + } +} diff --git a/backend/internal/service/account.go b/backend/internal/service/account.go index 72903b6f72..fcee9e4b05 100644 --- a/backend/internal/service/account.go +++ b/backend/internal/service/account.go @@ -1099,6 +1099,10 @@ func (a *Account) isModelMappingSupported(requestedModel string) bool { } return true // 无映射 = 允许所有 } + if a.IsOllamaCloud() { + mapped, matched := a.ResolveMappedModel(requestedModel) + return matched && strings.TrimSpace(mapped) != "" + } if mappingSupportsRequestedModel(mapping, requestedModel) { return true } diff --git a/backend/internal/service/account_ollama_cloud_pricing_gate.go b/backend/internal/service/account_ollama_cloud_pricing_gate.go index 7de3d2d483..77faea84ec 100644 --- a/backend/internal/service/account_ollama_cloud_pricing_gate.go +++ b/backend/internal/service/account_ollama_cloud_pricing_gate.go @@ -113,6 +113,15 @@ func ollamaCloudSchedulableBySave(a *Account) bool { return a != nil && a.IsActive() && a.Schedulable } +// GetOllamaCloudOutboundModels 返回 ollama_cloud 账号配置的可出站模型列表(model_mapping +// 目标或 extra.allowed_models 白名单),供管理端账号可用模型与连接测试默认选项复用。 +func (a *Account) GetOllamaCloudOutboundModels() []string { + if a == nil || !a.IsOllamaCloud() { + return nil + } + return ollamaCloudOutboundModelNames(a) +} + // ollamaCloudOutboundModelNames 收集 ollama_cloud 账号的可出站模型名集合 // (去重、去空)。空 mapping 且无有效清单时返回 nil。 // diff --git a/backend/internal/service/account_service.go b/backend/internal/service/account_service.go index 52db6cd9d7..08ed7f2896 100644 --- a/backend/internal/service/account_service.go +++ b/backend/internal/service/account_service.go @@ -258,6 +258,9 @@ func (s *AccountService) Create(ctx context.Context, req CreateAccountRequest) ( } else { account.AutoPauseOnExpired = true } + if req.Platform == PlatformOllamaCloud && req.Type != AccountTypeAPIKey { + return nil, errors.New("ollama_cloud accounts only support apikey credentials") + } // B2-③ 保存期无价门禁:ollama_cloud 账号的可出站模型名必须全部可定价。 if err := validateOllamaCloudAccountModelPricingGate(s.billingService, account); err != nil { diff --git a/backend/internal/service/account_test_service.go b/backend/internal/service/account_test_service.go index 26d67f7243..319131cb04 100644 --- a/backend/internal/service/account_test_service.go +++ b/backend/internal/service/account_test_service.go @@ -479,13 +479,14 @@ func (s *AccountTestService) testNativeResponsesConnection(c *gin.Context, accou if authToken == "" { return s.sendErrorAndEnd(c, "No API key available") } + mappedModelID := account.GetMappedModel(testModelID) c.Writer.Header().Set("Content-Type", "text/event-stream") c.Writer.Header().Set("Cache-Control", "no-cache") c.Writer.Header().Set("Connection", "keep-alive") c.Writer.Header().Set("X-Accel-Buffering", "no") c.Writer.Flush() - s.sendEvent(c, TestEvent{Type: "test_start", Model: testModelID}) - return s.testCNProviderAdaptiveResponsesConnection(c, account, testModelID, authToken) + s.sendEvent(c, TestEvent{Type: "test_start", Model: mappedModelID}) + return s.testCNProviderAdaptiveResponsesConnection(c, account, mappedModelID, authToken) } // testOllamaCloudAccountConnection probes an Ollama Cloud account's native diff --git a/backend/internal/service/account_test_service_cn_adaptive.go b/backend/internal/service/account_test_service_cn_adaptive.go index ab6574c385..75f3df0211 100644 --- a/backend/internal/service/account_test_service_cn_adaptive.go +++ b/backend/internal/service/account_test_service_cn_adaptive.go @@ -163,7 +163,11 @@ func (s *AccountTestService) processCNProviderAdaptiveAnthropicStream(c *gin.Con func (s *AccountTestService) testCNProviderAdaptiveResponsesConnection(c *gin.Context, account *Account, testModelID string, authToken string) error { ctx := c.Request.Context() - baseURL, err := s.validateUpstreamBaseURL(account.GetCNProtocolBaseURL(APIProtocolResponses)) + rawBaseURL := account.GetOpenAIBaseURL() + if account.IsAdaptiveAPIProtocol() { + rawBaseURL = account.GetCNProtocolBaseURL(APIProtocolResponses) + } + baseURL, err := s.validateUpstreamBaseURL(rawBaseURL) if err != nil { return s.sendErrorAndEnd(c, fmt.Sprintf("Invalid adaptive Responses base URL: %s", err.Error())) } diff --git a/backend/internal/service/admin_account.go b/backend/internal/service/admin_account.go index 53b22e7f95..8d6e6582ef 100644 --- a/backend/internal/service/admin_account.go +++ b/backend/internal/service/admin_account.go @@ -425,6 +425,9 @@ func buildAccountForCreate(input *CreateAccountInput, accountExtra map[string]an if input.Platform == PlatformTypeSafe && input.Type != AccountTypeAPIKey { return nil, errors.New("typesafe accounts only support apikey credentials") } + if input.Platform == PlatformOllamaCloud && input.Type != AccountTypeAPIKey { + return nil, errors.New("ollama_cloud accounts only support apikey credentials") + } // Probe/session state is system-managed. Only explicit account settings can enable it. delete(accountExtra, UpstreamBillingProbeEnabledExtraKey) delete(accountExtra, UpstreamBillingRateSyncEnabledExtraKey) @@ -610,6 +613,9 @@ func (s *adminServiceImpl) UpdateAccount(ctx context.Context, id int64, input *U if account.Platform == PlatformTypeSafe && input.Type != "" && input.Type != AccountTypeAPIKey { return nil, errors.New("typesafe accounts only support apikey credentials") } + if account.Platform == PlatformOllamaCloud && input.Type != "" && input.Type != AccountTypeAPIKey { + return nil, errors.New("ollama_cloud accounts only support apikey credentials") + } // B2-③ 保存期无价门禁的触发判定快照:必须在应用本次请求的变更之前采集。 prevPlatform := account.Platform prevOutboundSet := append([]string(nil), ollamaCloudOutboundModelNames(account)...) @@ -1018,6 +1024,22 @@ func (s *adminServiceImpl) UpdateAccountExtra(ctx context.Context, id int64, upd return err } } + if _, exists := updates[OllamaCloudAllowedModelsExtraKey]; exists { + account, err := s.accountRepo.GetByID(ctx, id) + if err != nil { + return err + } + if account != nil && account.IsOllamaCloud() { + next := *account + next.Extra = mergeMap(nil, account.Extra) + for key, value := range updates { + next.Extra[key] = value + } + if err := validateOllamaCloudAccountModelPricingGate(s.billingService, &next); err != nil { + return err + } + } + } if len(updates) == 0 { return nil } @@ -1445,6 +1467,15 @@ func (s *adminServiceImpl) RefreshAccountCredentials(ctx context.Context, id int } func (s *adminServiceImpl) ClearAccountError(ctx context.Context, id int64) (*Account, error) { + current, err := s.accountRepo.GetByID(ctx, id) + if err != nil { + return nil, err + } + if current != nil && current.IsOllamaCloud() && current.Schedulable && !ollamaCloudSchedulableBySave(current) { + if err := validateOllamaCloudAccountModelPricingGate(s.billingService, current); err != nil { + return nil, err + } + } if err := s.accountRepo.ClearError(ctx, id); err != nil { return nil, err } diff --git a/backend/internal/service/channel_monitor_quota_fetcher.go b/backend/internal/service/channel_monitor_quota_fetcher.go index f0354bbd04..551c47a89a 100644 --- a/backend/internal/service/channel_monitor_quota_fetcher.go +++ b/backend/internal/service/channel_monitor_quota_fetcher.go @@ -507,6 +507,9 @@ func (f *ChannelMonitorQuotaFetcher) fetchOllamaCloudQuota(account *Account, now if balance, ok := parseOllamaCloudBalanceUSD(snapshot.Data.Balance); ok { out.Balance = &balance out.Currency = "USD" + if account.GetOllamaCloudAccountMode() == AccountModeOllamaCredits { + out.BalanceLow = balance <= 0 || (f.balanceThreshold > 0 && balance < f.balanceThreshold) + } } return out } diff --git a/backend/internal/service/composite_pool_audit_r6_test.go b/backend/internal/service/composite_pool_audit_r6_test.go new file mode 100644 index 0000000000..b2e1b70888 --- /dev/null +++ b/backend/internal/service/composite_pool_audit_r6_test.go @@ -0,0 +1,377 @@ +//go:build unit + +package service + +import ( + "context" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/Wei-Shaw/sub2api/internal/pkg/ctxkey" + "github.com/stretchr/testify/require" +) + +// C1:composite 账号池不改写请求体 model 时,通用链与 OpenAI 链对未识别公开别名或 +// LiteLLM $0 占位条目均必须按实际转发的具体模型计费,且通配倍率卡不得误留别名。 +func TestCompositePoolPublicAliasBilling_BothChainsBillConcreteModel(t *testing.T) { + catalog := `{ + "gemini-flash-experimental": {"input_cost_per_token": 0.0, "output_cost_per_token": 0.0, "litellm_provider": "gemini", "mode": "chat"}, + "claude-opus-5": {"input_cost_per_token": 5e-06, "output_cost_per_token": 25e-06, "litellm_provider": "anthropic", "mode": "chat"}, + "gpt-5.4": {"input_cost_per_token": 2.5e-06, "output_cost_per_token": 15e-06, "litellm_provider": "openai", "mode": "chat"} + }` + cfg := &config.Config{RunMode: config.RunModeStandard} + cfg.Default.RateMultiplier = 1 + bs := NewBillingService(cfg, newStubPricingServiceFromJSON(t, catalog)) + + groupID := int64(601) + compGroup := &Group{ID: groupID, Platform: PlatformComposite, Status: StatusActive, Hydrated: true, RateMultiplier: 1} + apiKey := &APIKey{ID: 1, GroupID: &groupID, Group: compGroup, User: &User{ID: 1}} + + t.Run("generic_chain_zero_placeholder_and_family_alias_bill_concrete_opus", func(t *testing.T) { + for _, publicAlias := range []string{"gemini-flash-experimental", "haiku-pro"} { + usageRepo := &openAIRecordUsageLogRepoStub{inserted: true} + svc := newGatewayRecordUsageServiceForTest(usageRepo, &openAIRecordUsageUserRepoStub{}, &openAIRecordUsageSubRepoStub{}) + svc.billingService = bs + svc.resolver = NewModelPricingResolver(nil, bs) + + err := svc.RecordUsage(context.Background(), &RecordUsageInput{ + Result: &ForwardResult{ + RequestID: "comp_alias_" + publicAlias, + Model: publicAlias, + UpstreamModel: "claude-opus-5", + Usage: ClaudeUsage{InputTokens: 100_000, OutputTokens: 20_000}, + Duration: time.Second, + }, + QuotaPlatform: PlatformAnthropic, + APIKey: apiKey, + User: apiKey.User, + Account: &Account{ID: 11, Platform: PlatformAnthropic, Type: AccountTypeAPIKey}, + }) + require.NoError(t, err) + require.NotNil(t, usageRepo.lastLog) + // 100k * $5e-6 + 20k * $25e-6 = $1.00 + require.InDelta(t, 1.0, usageRepo.lastLog.TotalCost, 1e-9, "alias=%s must bill concrete claude-opus-5", publicAlias) + } + }) + + t.Run("openai_chain_requested_source_falls_back_to_concrete_model_in_composite", func(t *testing.T) { + usageRepo := &openAIRecordUsageLogRepoStub{inserted: true} + oaSvc := &OpenAIGatewayService{ + cfg: cfg, + usageLogRepo: usageRepo, + userRepo: &openAIRecordUsageUserRepoStub{}, + billingService: bs, + resolver: NewModelPricingResolver(nil, bs), + } + err := oaSvc.RecordUsage(context.Background(), &OpenAIRecordUsageInput{ + Result: &OpenAIForwardResult{ + RequestID: "oa_comp_req_source", + Model: "gemini-flash-experimental", + BillingModel: "qwen3.5:397b", + UpstreamModel: "qwen3.5:397b", + Usage: OpenAIUsage{InputTokens: 100_000, OutputTokens: 10_000}, + }, + APIKey: apiKey, + User: apiKey.User, + Account: &Account{ID: 12, Platform: PlatformOllamaCloud, Type: AccountTypeAPIKey}, + QuotaPlatform: PlatformOllamaCloud, + ChannelUsageFields: ChannelUsageFields{ + OriginalModel: "gemini-flash-experimental", + ChannelMappedModel: "gemini-flash-experimental", + BillingModelSource: BillingModelSourceRequested, + }, + }) + require.NoError(t, err) + require.NotNil(t, usageRepo.lastLog) + // qwen3.5:397b: 100k * $0.60e-6 + 10k * $3.60e-6 = $0.096 (绝非 $0) + require.InDelta(t, 0.096, usageRepo.lastLog.TotalCost, 1e-9) + }) + + t.Run("hosted_model_with_wildcard_multiplier_card_keeps_upstream_price", func(t *testing.T) { + chSvc := newChannelServiceWithPricings(groupID, []ChannelModelPricing{{ + Platform: PlatformOllamaCloud, + Models: []string{"*"}, + BillingMode: BillingModeToken, + ReasoningEffortMultipliers: map[string]float64{"high": 1.0}, + }}) + usageRepo := &openAIRecordUsageLogRepoStub{inserted: true} + svc := newGatewayRecordUsageServiceForTest(usageRepo, &openAIRecordUsageUserRepoStub{}, &openAIRecordUsageSubRepoStub{}) + svc.billingService = bs + svc.channelService = chSvc + svc.resolver = NewModelPricingResolver(chSvc, bs) + + err := svc.RecordUsage(context.Background(), &RecordUsageInput{ + Result: &ForwardResult{ + RequestID: "ollama_wildcard_card", + Model: "gpt-5.4", + UpstreamModel: "qwen3.5:397b", + Usage: ClaudeUsage{InputTokens: 100_000, OutputTokens: 10_000}, + Duration: time.Second, + }, + QuotaPlatform: PlatformOllamaCloud, + APIKey: apiKey, + User: apiKey.User, + Account: &Account{ID: 13, Platform: PlatformOllamaCloud, Type: AccountTypeAPIKey}, + ChannelUsageFields: ChannelUsageFields{ + OriginalModel: "gpt-5.4", + ChannelMappedModel: "gpt-5.4", + BillingModelSource: BillingModelSourceChannelMapped, + }, + }) + require.NoError(t, err) + require.InDelta(t, 0.096, usageRepo.lastLog.TotalCost, 1e-9, "hosted ollama_cloud must bill qwen3.5:397b, not gpt-5.4") + }) +} + +// C2:仅配倍率的通配分组/渠道卡片不得把未定价模型伪装成 $0 已定价绕过 ollama_cloud 预检。 +func TestOllamaCloudPricingPreflight_WildcardMultiplierCardDoesNotBypassUnpricedModel(t *testing.T) { + const groupID = int64(602) + bs := NewBillingService(nil, nil) + chSvc := newChannelServiceWithPricings(groupID, []ChannelModelPricing{{ + Platform: PlatformOllamaCloud, + Models: []string{"*"}, + BillingMode: BillingModeToken, + ReasoningEffortMultipliers: map[string]float64{"high": 1.5}, + }}) + resolver := NewModelPricingResolver(chSvc, bs) + group := &Group{ID: groupID, Platform: PlatformOllamaCloud, Status: StatusActive, Hydrated: true} + ctx := context.WithValue(context.Background(), ctxkey.Group, group) + + require.True(t, ollamaCloudModelUnpricedForBilling(ctx, resolver, "qwen3.5:32b-unpriced"), + "multiplier-only wildcard card must not make unpriced ollama model pass preflight") + require.False(t, ollamaCloudModelUnpricedForBilling(ctx, resolver, "qwen3.5:397b"), + "base-priced ollama model must still pass preflight with wildcard multiplier card") +} + +// H1:extractBaseName 仅剥 Bedrock 版本号(v1:0),非 Bedrock 的 :tag 模型不得跨型号碰撞。 +func TestExtractBaseName_ColonTaggedModelsNeverCollideWithBaseOrFamily(t *testing.T) { + catalog := `{ + "mistral-large": {"input_cost_per_token": 2e-06, "output_cost_per_token": 6e-06, "litellm_provider": "mistral", "mode": "chat"}, + "gpt-oss:120b": {"input_cost_per_token": 0.15e-06, "output_cost_per_token": 0.60e-06, "litellm_provider": "ollama", "mode": "chat"}, + "gpt-4o": {"input_cost_per_token": 2.5e-06, "output_cost_per_token": 10e-06, "litellm_provider": "openai", "mode": "chat"}, + "gpt-4o-mini": {"input_cost_per_token": 0.15e-06, "output_cost_per_token": 0.60e-06, "litellm_provider": "openai", "mode": "chat"}, + "claude-sonnet-4-5": {"input_cost_per_token": 3e-06, "output_cost_per_token": 15e-06, "litellm_provider": "anthropic", "mode": "chat"} + }` + bs := NewBillingService(&config.Config{}, newStubPricingServiceFromJSON(t, catalog)) + + // 1. mistral-large-3:675b 不得被目录里的 "mistral-large" 模糊匹配抢走,必须走内置 $0.50/$1.50。 + pMistral, err := bs.getModelPricingAt("mistral-large-3:675b", ollamaPricingAt) + require.NoError(t, err) + require.InDelta(t, 0.50e-6, pMistral.InputPricePerToken, 1e-12) + require.InDelta(t, 1.50e-6, pMistral.OutputPricePerToken, 1e-12) + + // 2. 目录含 "gpt-oss:120b"(旧代码基名为 "gpt")时,"gpt-oss:20b" 不得撞成 120b 价, + // 未定价的 "gpt-oss:999b" 也必须报缺价而非溜过 ollama 门禁。 + p20b, err := bs.getModelPricingAt("gpt-oss:20b", ollamaPricingAt) + require.NoError(t, err) + require.InDelta(t, 0.07e-6, p20b.InputPricePerToken, 1e-12) + _, err = bs.getModelPricingAt("gpt-oss:999b", ollamaPricingAt) + require.ErrorIs(t, err, ErrModelPricingUnavailable) + + // 3. "gpt-4o-mini:free" 经二级确定性剥 tag 命中 "gpt-4o-mini"($0.15),而非模糊撞上 "gpt-4o"($2.50)。 + pMini, err := bs.getModelPricingAt("gpt-4o-mini:free", ollamaPricingAt) + require.NoError(t, err) + require.InDelta(t, 0.15e-6, pMini.InputPricePerToken, 1e-12) + + // 4. Bedrock 版本后缀(-v1:0)继续正常剥离并识别。 + require.NotNil(t, bs.pricingService.GetIdentifiedModelPricing("claude-sonnet-4-5-20250929-v1:0")) +} + +// H2:固定 api_protocol=responses 且配置自定义中转 base_url 时,连接测试必须打中转地址并应用映射。 +func TestAccountTestService_OllamaCloudPinnedResponsesHonorsCustomRelayBaseURL(t *testing.T) { + account := ollamaCloudTestAccount(603, map[string]any{ + "api_protocol": APIProtocolResponses, + "base_url": "https://relay.example.com/v1", + "model_mapping": map[string]any{"public-alias": "qwen3.5:397b"}, + }) + svc, upstream := adaptiveCNAccountTestService(account, adaptiveCNResponsesTestResponse()) + c, _ := newTestContext() + + err := svc.TestAccountConnection(c, account.ID, "public-alias", "", AccountTestModeDefault) + require.NoError(t, err) + require.Len(t, upstream.requests, 1) + require.Equal(t, "https://relay.example.com/v1/responses", upstream.requests[0].URL.String(), + "custom relay base_url must not leak credentials to official ollama.com") + require.Contains(t, string(upstream.lastBody), `"model":"qwen3.5:397b"`) +} + +// H3:ollama_cloud 映射目标为空串时,调度判不支持且请求期预检显式拦截。 +func TestOllamaCloudBlankMappingTarget_DeniedInSchedulingAndPreflight(t *testing.T) { + acc := &Account{ + ID: 604, + Platform: PlatformOllamaCloud, + Type: AccountTypeAPIKey, + Credentials: map[string]any{ + "api_key": "sk-ol", + "model_mapping": map[string]any{"*": "gpt-oss:120b", "blocked-model": " "}, + }, + } + require.False(t, acc.IsModelSupported("blocked-model")) + require.True(t, acc.IsModelSupported("allowed-any")) + + upstream := &httpUpstreamRecorder{} + svc := newPricingPreflightTestService(upstream, 0, nil) + body := []byte(`{"model":" ","input":"hi","stream":false}`) + c, rec, ctx := pricingPreflightContext("/v1/responses", body, nil) + err := svc.enforceOllamaCloudRequestPricingPreflight(ctx, c, acc, body) + require.Error(t, err) + require.Equal(t, 400, rec.Code) +} + +// H4:composite 候选池在途预留按实际候选平台解析渠道映射,不被非池平台映射误导低估。 +func TestEstimateInflightReservation_CompositePoolScopesChannelMappingPerCandidate(t *testing.T) { + cfg := &config.Config{RunMode: config.RunModeStandard} + cfg.Default.RateMultiplier = 1 + cfg.Billing.InflightReservation.Enabled = true + cfg.Billing.InflightReservation.DefaultMaxTokens = 1000 + cfg.Billing.InflightReservation.MaxInputTokens = 10000 + cfg.Billing.InflightReservation.MaxOutputTokens = 10000 + + catalog := `{ + "claude-3-haiku": {"input_cost_per_token": 0.25e-06, "output_cost_per_token": 1.25e-06, "litellm_provider": "anthropic", "mode": "chat"}, + "gpt-5.5-pro": {"input_cost_per_token": 15e-06, "output_cost_per_token": 120e-06, "litellm_provider": "openai", "mode": "chat"} + }` + billing := NewBillingService(cfg, newStubPricingServiceFromJSON(t, catalog)) + + groupID := int64(605) + ch := Channel{ + ID: 1, + Status: StatusActive, + GroupIDs: []int64{groupID}, + BillingModelSource: BillingModelSourceChannelMapped, + ModelMapping: map[string]map[string]string{ + // 非池内 anthropic 平台映射到廉价模型,不得遮蔽池内 openai 账号的昂贵映射。 + PlatformAnthropic: {"pro-alias": "claude-3-haiku"}, + }, + } + chSvc := newTestChannelService(makeStandardRepo(ch, map[int64]string{groupID: PlatformComposite})) + resolver := NewModelPricingResolver(chSvc, billing) + + snap := &inflightSnapshotCacheStub{byBucket: make(map[string][]Account)} + snap.set(groupID, PlatformOpenAI, []Account{{ + ID: 1, Platform: PlatformOpenAI, Type: AccountTypeAPIKey, Status: StatusActive, Schedulable: true, + Credentials: map[string]any{"api_key": "sk-oa", "model_mapping": map[string]any{"pro-alias": "gpt-5.5-pro"}}, + }}) + snap.set(groupID, PlatformDeepseek, []Account{{ + ID: 2, Platform: PlatformDeepseek, Type: AccountTypeAPIKey, Status: StatusActive, Schedulable: true, + Credentials: map[string]any{"api_key": "sk-ds", "model_mapping": map[string]any{"pro-alias": "deepseek-v4-pro"}}, + }}) + repo := &inflightCountingAccountRepo{} + oaSvc := &OpenAIGatewayService{ + cfg: cfg, + billingService: billing, + channelService: chSvc, + resolver: resolver, + accountRepo: repo, + schedulerSnapshot: NewSchedulerSnapshotService(snap, nil, repo, nil, cfg), + } + apiKey := &APIKey{ + ID: 1, UserID: 1, GroupID: &groupID, + Group: &Group{ID: groupID, Platform: PlatformComposite, RateMultiplier: 1}, + User: &User{ID: 1, Balance: 100}, + } + poolCtx := WithCompositeCandidatePlatforms(context.Background(), []string{PlatformDeepseek, PlatformOpenAI}) + cost, ok := oaSvc.EstimateInflightReservation(poolCtx, apiKey, InflightEstimateRequest{ + Model: "pro-alias", + BodyBytes: 4000, // 1000 input tokens + MaxTokens: 1000, + }) + require.True(t, ok) + // gpt-5.5-pro: 1000 * $15e-6 + 1000 * $120e-6 = $0.135(远高于 claude-3-haiku 的 $0.0015) + require.InDelta(t, 0.135, cost, 1e-9) +} + +// M1 + M3a + M2 + M4 + M8 + C3 防护单元测试。 +func TestAuditR6_OAuthGPTOSS_TagRestriction_AdminGates_MonitorAndCyber(t *testing.T) { + // M1: OpenAI OAuth 不冒领 gpt-oss:120b,但 DetectModelPlatform 保持原契约。 + require.False(t, isOpenAIOAuthServableModel("gpt-oss:120b")) + require.False(t, isOpenAIOAuthServableModel("gpt-oss-120b")) + openAIOAuth := &Account{ID: 1, Platform: PlatformOpenAI, Type: AccountTypeOAuth} + require.Equal(t, CompositeClaimNone, CompositeAccountClaimStrength(openAIOAuth, "gpt-oss:120b")) + plat, ok := DetectModelPlatform("gpt-oss:120b") + require.True(t, ok) + require.Equal(t, PlatformOpenAI, plat) + + // M3a: 渠道按基础名配价并开启 RestrictModels 时,带 :tag 的同款模型放行。 + groupID := int64(606) + chSvc := newTestChannelService(makeStandardRepo(Channel{ + ID: 2, + Status: StatusActive, + GroupIDs: []int64{groupID}, + RestrictModels: true, + ModelPricing: []ChannelModelPricing{{ + Platform: PlatformOllamaCloud, + Models: []string{"deepseek-v4-flash"}, + }}, + }, map[int64]string{groupID: PlatformComposite})) + ctx := WithResolvedTargetPlatform(context.Background(), PlatformOllamaCloud) + require.False(t, chSvc.IsModelRestricted(ctx, groupID, "deepseek-v4-flash:0731")) + require.True(t, chSvc.IsModelRestricted(ctx, groupID, "unlisted-model:0731")) + + // M2: ClearAccountError 拒绝恢复未定价的 ollama_cloud 账号,且仅允许 apikey 类型。 + repo := newOllamaGateAdminRepoStub() + adminSvc := &adminServiceImpl{accountRepo: repo, billingService: NewBillingService(&config.Config{}, nil)} + erroredUnpriced := seedOllamaGateAccount(t, repo, func(a *Account) { + a.Status = StatusError + a.Schedulable = true + }) + _, err := adminSvc.ClearAccountError(context.Background(), erroredUnpriced.ID) + requireModelPricingMissing(t, err) + + _, err = adminSvc.CreateAccount(context.Background(), &CreateAccountInput{ + Name: "bad-oauth", Platform: PlatformOllamaCloud, Type: AccountTypeOAuth, + SkipDefaultGroupBind: true, + }) + require.ErrorContains(t, err, "apikey") + + // C3 纵深防护:非 anthropic 且无 base_url 的 APIKey 账号绝不默认发往 api.anthropic.com。 + req, _, err := (&GatewayService{}).buildUpstreamRequest( + context.Background(), nil, + &Account{ID: 99, Platform: PlatformOpenAI, Type: AccountTypeAPIKey, Credentials: map[string]any{"api_key": "sk-live"}}, + []byte(`{"model":"gpt-5.4","messages":[]}`), "sk-live", "apikey", "gpt-5.4", false, false, + ) + require.Error(t, err) + require.Nil(t, req) + + // M8: ollama_credits 余额为 $0.00 或负数时置 BalanceLow=true。 + now := time.Now().UTC() + fetcher := &ChannelMonitorQuotaFetcher{balanceThreshold: 5.0} + creditsAcc := &Account{ + ID: 77, Platform: PlatformOllamaCloud, Type: AccountTypeAPIKey, + Credentials: map[string]any{"api_key": "sk", "base_url": "https://ollama.com/v1", "account_mode": AccountModeOllamaCredits}, + Extra: map[string]any{ + OllamaCloudUsageSnapshotExtraKey: &OllamaCloudUsageSnapshot{ + Status: OllamaCloudUsageStatusOK, + FetchedAt: &now, + Data: &OllamaCloudUsageData{Balance: "$0.00"}, + }, + }, + } + snap := fetcher.fetchOllamaCloudQuota(creditsAcc, now) + require.True(t, snap.Success) + require.True(t, snap.BalanceLow) + + // M4: RecordCyberPolicyUsageLog 解析账号级映射模型计费,而非按未定价公开别名落 $0。 + usageRepo := &openAIRecordUsageLogRepoStub{inserted: true} + cyberCatalog := `{"gpt-5.5-pro": {"input_cost_per_token": 15e-06, "output_cost_per_token": 120e-06, "litellm_provider": "openai", "mode": "chat"}}` + cyberBS := NewBillingService(&config.Config{}, newStubPricingServiceFromJSON(t, cyberCatalog)) + oaSvc := &OpenAIGatewayService{ + cfg: &config.Config{RunMode: config.RunModeStandard}, + usageLogRepo: usageRepo, + userRepo: &openAIRecordUsageUserRepoStub{}, + billingService: cyberBS, + resolver: NewModelPricingResolver(nil, cyberBS), + } + compGroup := &Group{ID: groupID, Platform: PlatformComposite, RateMultiplier: 1} + oaSvc.RecordCyberPolicyUsageLog(context.Background(), CyberPolicyUsageInput{ + APIKey: &APIKey{ID: 1, GroupID: &groupID, Group: compGroup, User: &User{ID: 1}}, + Account: &Account{ID: 88, Platform: PlatformOpenAI, Type: AccountTypeAPIKey, Credentials: map[string]any{"model_mapping": map[string]any{"team/coder": "gpt-5.5-pro"}}}, + RequestID: "req_cyber_alias", + Model: "team/coder", + InputTokens: 10_000, + OutputTokens: 1_000, + }) + require.NotNil(t, usageRepo.lastLog) + require.InDelta(t, 0.27, usageRepo.lastLog.TotalCost, 1e-9) +} diff --git a/backend/internal/service/gateway_anthropic_passthrough.go b/backend/internal/service/gateway_anthropic_passthrough.go index 0154319187..d4884a3dab 100644 --- a/backend/internal/service/gateway_anthropic_passthrough.go +++ b/backend/internal/service/gateway_anthropic_passthrough.go @@ -312,6 +312,8 @@ func (s *GatewayService) buildUpstreamRequestAnthropicAPIKeyPassthrough( } if protocolTargetURL != "" { targetURL = protocolTargetURL + } else if account.Platform != PlatformAnthropic { + return nil, nil, fmt.Errorf("account %d (%s) has no anthropic base url and cannot default to api.anthropic.com", account.ID, account.Platform) } } diff --git a/backend/internal/service/gateway_scheduling.go b/backend/internal/service/gateway_scheduling.go index be4858a126..a8bda7551e 100644 --- a/backend/internal/service/gateway_scheduling.go +++ b/backend/internal/service/gateway_scheduling.go @@ -234,6 +234,11 @@ func (s *GatewayService) SelectAccountWithLoadAwareness(ctx context.Context, gro if err != nil { return nil, err } + if derefGroupID(groupID) != origGroupID { + if upstreamModel, ok := ResolvedUpstreamModelFromContext(ctx); ok && upstreamModel != "" { + requestedModel = upstreamModel + } + } ctx = s.withCompositePoolQuotaAutoPauseContext(ctx) preferOAuth := platform == PlatformGemini if s.debugModelRoutingEnabled() && requestedModel != "" && modelRoutingAppliesToTargetPlatform(platform) { @@ -1015,7 +1020,7 @@ func (s *GatewayService) resolvePlatform(ctx context.Context, groupID *int64, gr // 池决策写回 ctx(immutable 候选池),平台保持 composite 哨兵用于日志。 return WithCompositeRouteDecision(ctx, decision), PlatformComposite, false, nil } - return ctx, decision.TargetPlatform, false, nil + return WithCompositeRouteDecision(ctx, decision), decision.TargetPlatform, false, nil } return ctx, group.Platform, false, nil } @@ -1036,7 +1041,7 @@ func (s *GatewayService) resolvePlatform(ctx context.Context, groupID *int64, gr // 池决策写回 ctx(immutable 候选池),平台保持 composite 哨兵用于日志。 return WithCompositeRouteDecision(ctx, decision), PlatformComposite, false, nil } - return ctx, decision.TargetPlatform, false, nil + return WithCompositeRouteDecision(ctx, decision), decision.TargetPlatform, false, nil } return ctx, group.Platform, false, nil } @@ -1720,11 +1725,19 @@ func (s *GatewayService) newSelectionResult(ctx context.Context, groupID *int64, } return nil, err } + var effectiveGroup *Group + if ctx != nil { + if g, ok := ctx.Value(ctxkey.Group).(*Group); ok && g != nil { + effectiveGroup = g + } + } return attachSelectionProfitGate(ctx, &AccountSelectionResult{ - Account: hydrated, - Acquired: acquired, - ReleaseFunc: release, - WaitPlan: waitPlan, + Account: hydrated, + Acquired: acquired, + ReleaseFunc: release, + WaitPlan: waitPlan, + EffectiveGroup: effectiveGroup, + SelectionCtx: ctx, }), nil } diff --git a/backend/internal/service/gateway_service.go b/backend/internal/service/gateway_service.go index b2cf71b1ad..ed524a7ef0 100644 --- a/backend/internal/service/gateway_service.go +++ b/backend/internal/service/gateway_service.go @@ -659,6 +659,9 @@ type AccountSelectionResult struct { // 局部 ctx 上,handler 必须经 ContextWithSelectionProfitGate 重放后才能在 // 调度栈之外做抢槽后终检与准入后粘性绑定。 profitGate *openAIProfitControlGate + // EffectiveGroup 与 SelectionCtx 携带 ClaudeCodeOnly 降级切换后实际生效的分组与选号上下文。 + EffectiveGroup *Group + SelectionCtx context.Context } // ProfitGateActive 报告本次选号是否处于利润门之下。 diff --git a/backend/internal/service/gateway_upstream_request.go b/backend/internal/service/gateway_upstream_request.go index ad0bb3564e..ad0dabccea 100644 --- a/backend/internal/service/gateway_upstream_request.go +++ b/backend/internal/service/gateway_upstream_request.go @@ -75,6 +75,8 @@ func (s *GatewayService) buildUpstreamRequest(ctx context.Context, c *gin.Contex } if protocolTargetURL != "" { targetURL = protocolTargetURL + } else if account.Platform != PlatformAnthropic { + return nil, nil, fmt.Errorf("account %d (%s) has no anthropic base url and cannot default to api.anthropic.com", account.ID, account.Platform) } } else if account.IsCustomBaseURLEnabled() { customURL := account.GetCustomBaseURL() @@ -1073,6 +1075,9 @@ func (s *GatewayService) anthropicUpstreamTargetURL(account *Account, path strin } return anthropicProtocolEndpointURL(account, validatedURL, path), nil } + if account != nil && account.Platform != PlatformAnthropic && strings.TrimSpace(account.GetCredential("base_url")) == "" { + return "", fmt.Errorf("account %d (%s) has no anthropic base url and cannot default to api.anthropic.com", account.ID, account.Platform) + } baseURL := account.GetBaseURL() if baseURL == "" { return "", nil diff --git a/backend/internal/service/openai_gateway_cc_pipeline.go b/backend/internal/service/openai_gateway_cc_pipeline.go index cc4b830a36..35da55ad2c 100644 --- a/backend/internal/service/openai_gateway_cc_pipeline.go +++ b/backend/internal/service/openai_gateway_cc_pipeline.go @@ -428,6 +428,7 @@ func (s *OpenAIGatewayService) readCCUpstreamJSONResponse( // writeOpenAIResponsesFallbackError 以 /v1/responses 回退路径的既有错误格式回写 // (裸 error 对象;不调用 MarkResponseCommitted,与原内联写法保持一致)。 func writeOpenAIResponsesFallbackError(c *gin.Context, statusCode int, errType, message string) { + MarkResponseCommitted(c) c.JSON(statusCode, gin.H{ "error": gin.H{ "type": errType, diff --git a/backend/internal/service/openai_gateway_count_tokens.go b/backend/internal/service/openai_gateway_count_tokens.go index 720386fa45..c9d9ea59cb 100644 --- a/backend/internal/service/openai_gateway_count_tokens.go +++ b/backend/internal/service/openai_gateway_count_tokens.go @@ -150,7 +150,7 @@ func prepareNativeOpenAIInputTokensCountRequest(body []byte, account *Account) ( } func shouldEstimateOpenAIInputTokensLocally(account *Account) bool { - if account == nil || account.IsGrok() || account.RoutesProtocolByInbound() || account.Type == AccountTypeUpstream { + if account == nil || account.IsGrok() || account.IsMultiProtocolAPIKey() || account.RoutesProtocolByInbound() || account.Type == AccountTypeUpstream { return true } if account.Type != AccountTypeAPIKey { diff --git a/backend/internal/service/openai_gateway_messages.go b/backend/internal/service/openai_gateway_messages.go index e59b7201b2..1332f81a8b 100644 --- a/backend/internal/service/openai_gateway_messages.go +++ b/backend/internal/service/openai_gateway_messages.go @@ -1504,6 +1504,7 @@ func (s *OpenAIGatewayService) handleAnthropicStreamingResponse( // body would be unreadable to the client's SSE parser, so the error is written // as an SSE error event instead. func writeAnthropicError(c *gin.Context, statusCode int, errType, message string) { + MarkResponseCommitted(c) if c.Writer.Written() && strings.HasPrefix(c.Writer.Header().Get("Content-Type"), "text/event-stream") { if _, err := fmt.Fprint(c.Writer, buildAnthropicStreamErrorSSE(errType, message)); err == nil { c.Writer.Flush() diff --git a/backend/internal/service/openai_model_mapping.go b/backend/internal/service/openai_model_mapping.go index 0c0ff9e74b..12a4daf4b9 100644 --- a/backend/internal/service/openai_model_mapping.go +++ b/backend/internal/service/openai_model_mapping.go @@ -31,6 +31,8 @@ func resolveOpenAIForwardModel(account *Account, requestedModel, messagesDispatc // ResolveThinkingProtocol(thinking_protocol.go)。 var openAIOAuthForeignModelPrefixes = []string{ "claude-", + "gpt-oss:", + "gpt-oss-", "deepseek-", "glm-", "kimi-", diff --git a/backend/internal/service/openai_ws_forwarder_support.go b/backend/internal/service/openai_ws_forwarder_support.go index 5b9d18760c..b5e9229a0a 100644 --- a/backend/internal/service/openai_ws_forwarder_support.go +++ b/backend/internal/service/openai_ws_forwarder_support.go @@ -577,6 +577,10 @@ func (s *OpenAIGatewayService) resolveAccountByPreviousResponseIDForCapability( } } account, err := s.getSchedulableAccount(ctx, accountID) + if errors.Is(err, ErrAccountNotFound) { + _ = store.DeleteResponseAccount(ctx, derefGroupID(groupID), responseID) + return 0, nil, "", nil + } if err != nil || account == nil { dropTransient() return 0, nil, "", nil diff --git a/backend/internal/service/opencode_go.go b/backend/internal/service/opencode_go.go index 7709cb55e3..1d19ad8e8f 100644 --- a/backend/internal/service/opencode_go.go +++ b/backend/internal/service/opencode_go.go @@ -84,6 +84,7 @@ func writeOpenCodeUnsupportedModelError(c *gin.Context, isAnthropic bool, model if isAnthropic { writeAnthropicError(c, http.StatusBadRequest, "invalid_request_error", msg) } else { + MarkResponseCommitted(c) c.JSON(http.StatusBadRequest, gin.H{ "error": gin.H{ "type": "invalid_request_error", From e15d1b50829f9e535e71a9801dde0a23a78b3b5b Mon Sep 17 00:00:00 2001 From: shaw Date: Sat, 5 Dec 2026 17:26:44 +0800 Subject: [PATCH 79/81] =?UTF-8?q?fix(frontend):=20=E6=B8=85=E7=90=86=20oll?= =?UTF-8?q?ama=5Fcloud=20=E7=BC=96=E8=BE=91=E6=AE=8B=E7=95=99=20allowed=5F?= =?UTF-8?q?models=20=E5=B9=B6=E8=A1=A5=E9=BD=90=E8=B4=A6=E5=8F=B7=E6=B1=A0?= =?UTF-8?q?=E8=B7=AF=E7=94=B1=E9=A2=84=E8=A7=88=E4=B8=8E=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/BulkEditAccountModal.vue | 11 ++++++++++ .../components/account/EditAccountModal.vue | 11 +++++++++- .../account/OllamaCloudUsageCell.vue | 19 ++++++++++++----- .../account/OllamaCloudUsageSettings.vue | 10 +++++---- .../__tests__/EditAccountModal.spec.ts | 8 ++++++- .../__tests__/OllamaCloudUsageCell.spec.ts | 18 ++++++++++++++++ frontend/src/components/keys/UseKeyModal.vue | 6 ++++++ .../src/i18n/locales/en/admin/overview.ts | 3 +++ .../src/i18n/locales/zh/admin/overview.ts | 3 +++ frontend/src/types/index.ts | 3 ++- frontend/src/views/admin/GroupsView.vue | 21 +++++++++++++++++-- 11 files changed, 99 insertions(+), 14 deletions(-) diff --git a/frontend/src/components/account/BulkEditAccountModal.vue b/frontend/src/components/account/BulkEditAccountModal.vue index 05118068d5..b954316cfb 100644 --- a/frontend/src/components/account/BulkEditAccountModal.vue +++ b/frontend/src/components/account/BulkEditAccountModal.vue @@ -2075,6 +2075,14 @@ const buildUpdatePayload = (): Record | null => { const baseUrlValue = baseUrl.value.trim() if (baseUrlValue) { credentials.base_url = baseUrlValue + if (props.selectedPlatforms.length > 0 && props.selectedPlatforms.every((p) => p === 'ollama_cloud')) { + const anthropicBase = baseUrlValue.replace(/\/v1\/?$/, '') || baseUrlValue + credentials.api_base_urls = { + chat_completions: baseUrlValue, + responses: baseUrlValue, + anthropic: anthropicBase + } + } credentialsChanged = true } } @@ -2144,6 +2152,9 @@ const buildUpdatePayload = (): Record | null => { credentials.model_mapping = modelMapping ?? {} credentialsChanged = true } + if (props.selectedPlatforms.includes('ollama_cloud')) { + ensureExtra().allowed_models = null + } } if (enableCustomErrorCodes.value) { diff --git a/frontend/src/components/account/EditAccountModal.vue b/frontend/src/components/account/EditAccountModal.vue index 99da3379b1..860d3c6588 100644 --- a/frontend/src/components/account/EditAccountModal.vue +++ b/frontend/src/components/account/EditAccountModal.vue @@ -3797,7 +3797,11 @@ watch(editApiProtocol, (protocol, previousProtocol) => { defaultCNBaseUrl(props.account!.platform, currentOpenCodeOrCNMode(), protocol) return } - editBaseUrl.value = defaultCNBaseUrl(props.account!.platform, currentOpenCodeOrCNMode(), protocol) + const previousDefault = defaultCNBaseUrl(props.account!.platform, currentOpenCodeOrCNMode(), previousProtocol) + const nextDefault = defaultCNBaseUrl(props.account!.platform, currentOpenCodeOrCNMode(), protocol) + if (!editBaseUrl.value.trim() || editBaseUrl.value.trim() === previousDefault) { + editBaseUrl.value = nextDefault + } }) watch(editAccountMode, (mode, previousMode) => { if (!isCNApiKeyAccount.value || syncingForm.value) return @@ -6475,6 +6479,11 @@ const handleSubmit = async () => { delete newExtra.upstream_billing_probe_enabled delete newExtra.upstream_billing_rate_sync_enabled delete newExtra.upstream_billing_group_sync_enabled + if (props.account.platform === 'ollama_cloud' && !isOpenAIModelRestrictionDisabled.value) { + // 编辑弹窗统一通过 credentials.model_mapping 维护模型限制;清理历史 extra.allowed_models, + // 防止清空模型保存后被旧 extra.allowed_models 静默复活或绕过空清单拒绝。 + delete newExtra.allowed_models + } } // Total quota if (editQuotaLimit.value != null && editQuotaLimit.value > 0) { diff --git a/frontend/src/components/account/OllamaCloudUsageCell.vue b/frontend/src/components/account/OllamaCloudUsageCell.vue index bbf33115cd..3a7354a3d5 100644 --- a/frontend/src/components/account/OllamaCloudUsageCell.vue +++ b/frontend/src/components/account/OllamaCloudUsageCell.vue @@ -104,17 +104,26 @@ const isCredits = computed(() => state.value?.mode === 'ollama_credits') const balanceNumber = computed(() => { const raw = snapshot.value?.data?.balance if (!raw) return null - const cleaned = raw.replace(/[^0-9.-]/g, '') - const match = cleaned.match(/^-?\d+(?:\.\d+)?/) - if (!match) return null - const parsed = Number.parseFloat(match[0]) + let s = raw.trim() + let sign = 1 + if (s.startsWith('-')) { + sign = -1 + s = s.slice(1).trim() + } else if (s.startsWith('+')) { + s = s.slice(1).trim() + } + s = s.replace(/^USD\s*/i, '').replace(/^\$\s*/, '').replace(/,/g, '').trim() + if (!/^\d+(?:\.\d+)?$/.test(s)) return null + const parsed = sign * Number.parseFloat(s) return Number.isFinite(parsed) ? parsed : null }) // credits 模式的月度信用池已用百分比:(pool - balance) / pool,clamp 0-100。 const creditsPoolUtilization = computed(() => { const pool = state.value?.monthly_credit_usd - if (!isCredits.value || !pool || pool <= 0 || balanceNumber.value === null) return null + if (!isCredits.value || typeof pool !== 'number' || !Number.isFinite(pool) || pool <= 0 || balanceNumber.value === null) { + return null + } const used = ((pool - balanceNumber.value) / pool) * 100 return Math.min(Math.max(used, 0), 100) }) diff --git a/frontend/src/components/account/OllamaCloudUsageSettings.vue b/frontend/src/components/account/OllamaCloudUsageSettings.vue index 7caaa173a0..872c2b064a 100644 --- a/frontend/src/components/account/OllamaCloudUsageSettings.vue +++ b/frontend/src/components/account/OllamaCloudUsageSettings.vue @@ -35,10 +35,12 @@
{{ t('admin.accounts.ollamaCloud.plan') }} {{ snapshot.data?.plan || '-' }} - {{ t('admin.accounts.ollamaCloud.fiveHour') }} - {{ windowSummary(snapshot.data?.five_hour) }} - {{ t('admin.accounts.ollamaCloud.sevenDay') }} - {{ windowSummary(snapshot.data?.seven_day) }} + {{ t('admin.accounts.ollamaCloud.balance') }} {{ snapshot.data?.balance || '-' }} {{ t('admin.accounts.ollamaCloud.models') }} diff --git a/frontend/src/components/account/__tests__/EditAccountModal.spec.ts b/frontend/src/components/account/__tests__/EditAccountModal.spec.ts index 28a347e1e9..eb8fe2f722 100644 --- a/frontend/src/components/account/__tests__/EditAccountModal.spec.ts +++ b/frontend/src/components/account/__tests__/EditAccountModal.spec.ts @@ -2253,17 +2253,23 @@ describe('EditAccountModal ollama_cloud regressions', () => { await wrapper.get('form#edit-account-form').trigger('submit.prevent') expect(updateAccountMock).toHaveBeenCalledTimes(1) - const submitted = updateAccountMock.mock.calls[0]?.[1]?.credentials + const payload = updateAccountMock.mock.calls[0]?.[1] + const submitted = payload?.credentials expect(submitted).toMatchObject({ account_mode: 'ollama_legacy', api_protocol: 'adaptive', base_url: 'https://ollama.com/v1', + model_mapping: { + 'qwen3.5:397b': 'qwen3.5:397b', + 'gpt-oss:120b': 'gpt-oss:120b' + }, api_base_urls: { chat_completions: 'https://ollama.com/v1', responses: 'https://ollama.com/v1', anthropic: 'https://ollama.com' } }) + expect(payload?.extra?.allowed_models).toBeUndefined() wrapper.unmount() }) diff --git a/frontend/src/components/account/__tests__/OllamaCloudUsageCell.spec.ts b/frontend/src/components/account/__tests__/OllamaCloudUsageCell.spec.ts index 49febab9a8..90696999ed 100644 --- a/frontend/src/components/account/__tests__/OllamaCloudUsageCell.spec.ts +++ b/frontend/src/components/account/__tests__/OllamaCloudUsageCell.spec.ts @@ -156,6 +156,24 @@ describe('OllamaCloudUsageCell', () => { .toBe('admin.accounts.ollamaCloud.balance: $12.00') }) + it('rejects ambiguous compound balance strings while accepting negative USD balances', () => { + const compound = usageState() + compound.mode = 'ollama_credits' + compound.monthly_credit_usd = 60 + compound.snapshot!.data!.balance = '$9.50 / $20.00' + const compoundWrapper = mount(OllamaCloudUsageCell, { props: { account: account(compound) } }) + expect(compoundWrapper.findAllComponents(UsageProgressBar)).toHaveLength(0) + + const negative = usageState() + negative.mode = 'ollama_credits' + negative.monthly_credit_usd = 60 + negative.snapshot!.data!.balance = '-$1.50' + const negWrapper = mount(OllamaCloudUsageCell, { props: { account: account(negative) } }) + const bars = negWrapper.findAllComponents(UsageProgressBar) + expect(bars).toHaveLength(1) + expect(bars[0].props('utilization')).toBe(100) + }) + it('reacts to an account snapshot update', async () => { const wrapper = mount(OllamaCloudUsageCell, { props: { account: account() } }) const next = usageState() diff --git a/frontend/src/components/keys/UseKeyModal.vue b/frontend/src/components/keys/UseKeyModal.vue index bae34d27f5..1d160f478a 100644 --- a/frontend/src/components/keys/UseKeyModal.vue +++ b/frontend/src/components/keys/UseKeyModal.vue @@ -824,6 +824,11 @@ const currentFiles = computed((): FileConfig[] => { return generateRoutedCodexFiles(apiBase, apiKey, 'composite') } return generateAnthropicFiles(baseRoot, apiKey) + case 'ollama_cloud': + if (activeClientTab.value === 'codex') { + return generateRoutedCodexFiles(apiBase, apiKey, 'ollama_cloud') + } + return generateAnthropicFiles(baseRoot, apiKey) default: if (activeClientTab.value === 'codex' && props.platform) { return generateRoutedCodexFiles(apiBase, apiKey, props.platform) @@ -1316,6 +1321,7 @@ function generateRoutedCodexFiles( deepseek: 'deepseek-v4-pro', minimax: 'MiniMax-M3', opencode_go: 'glm-5.3', + ollama_cloud: 'gpt-oss:120b', composite: 'gpt-6.1-sol' } const preferredModel = preferredModels[platform] || '' diff --git a/frontend/src/i18n/locales/en/admin/overview.ts b/frontend/src/i18n/locales/en/admin/overview.ts index bb19e72d26..a34d72773b 100644 --- a/frontend/src/i18n/locales/en/admin/overview.ts +++ b/frontend/src/i18n/locales/en/admin/overview.ts @@ -1198,6 +1198,7 @@ export default { matchType: 'Match', endpoint: 'Endpoint', targetPlatform: 'Target Platform', + candidatePlatforms: 'Candidate Platforms', upstreamModel: 'Upstream Model', upstreamModelHint: 'Leave empty to pass the original requested model through: under prefix match each matched model forwards verbatim (e.g. deepseek-v4-flash and deepseek-v4-pro each forwarded as-is); set a value to forward every matched request to that fixed model.', notes: 'Notes', @@ -1230,6 +1231,8 @@ export default { }, sources: { route: 'Route', + accountModel: 'Account Mapping', + accountPool: 'Account Pool', detector: 'Detector' } }, diff --git a/frontend/src/i18n/locales/zh/admin/overview.ts b/frontend/src/i18n/locales/zh/admin/overview.ts index 7362bf3508..77ebd6f676 100644 --- a/frontend/src/i18n/locales/zh/admin/overview.ts +++ b/frontend/src/i18n/locales/zh/admin/overview.ts @@ -1195,6 +1195,7 @@ export default { matchType: '匹配方式', endpoint: '端点', targetPlatform: '目标平台', + candidatePlatforms: '候选平台', upstreamModel: '上游模型', upstreamModelHint: '留空表示透传原始请求模型:前缀匹配下每个命中模型各自原样转发(如 deepseek-v4-flash、deepseek-v4-pro 分别转发);填写则所有命中请求都固定转发该模型。', notes: '备注', @@ -1227,6 +1228,8 @@ export default { }, sources: { route: '路由', + accountModel: '账号映射', + accountPool: '跨平台账号池', detector: '内置识别' } }, diff --git a/frontend/src/types/index.ts b/frontend/src/types/index.ts index 0a32c3c52c..31f874e5a5 100644 --- a/frontend/src/types/index.ts +++ b/frontend/src/types/index.ts @@ -703,7 +703,7 @@ export type CompositeRouteEndpoint = | 'images' | 'gemini' -export type CompositeRouteSource = 'route' | 'detector' | string +export type CompositeRouteSource = 'route' | 'account_model' | 'account_pool' | 'detector' | string export interface CompositeModelRoute { id: number @@ -743,6 +743,7 @@ export interface CompositeRouteDecision { public_model: string target_platform: Exclude | '' upstream_model: string + candidate_platforms?: Array> endpoint: CompositeRouteEndpoint route?: CompositeModelRoute reason?: string diff --git a/frontend/src/views/admin/GroupsView.vue b/frontend/src/views/admin/GroupsView.vue index 3962ddaf0a..9e6c3ea168 100644 --- a/frontend/src/views/admin/GroupsView.vue +++ b/frontend/src/views/admin/GroupsView.vue @@ -4124,7 +4124,15 @@ v-if="compositePreviewDecision.matched" class="space-y-1 text-gray-700 dark:text-gray-300" > -
+
+ {{ t("admin.groups.compositeRoutes.candidatePlatforms") }}: + {{ + compositePreviewDecision.candidate_platforms + .map((p) => formatCompositePlatform(p)) + .join(", ") + }} +
+
{{ t("admin.groups.compositeRoutes.targetPlatform") }}: {{ formatCompositePlatform( @@ -4134,7 +4142,10 @@
{{ t("admin.groups.compositeRoutes.upstreamModel") }}: - {{ compositePreviewDecision.upstream_model }} + {{ + compositePreviewDecision.upstream_model || + compositePreviewDecision.public_model + }}
{ const compositeRouteSourceLabel = (source: string) => { if (source === "route") return t("admin.groups.compositeRoutes.sources.route"); + if (source === "account_model") { + return t("admin.groups.compositeRoutes.sources.accountModel"); + } + if (source === "account_pool") { + return t("admin.groups.compositeRoutes.sources.accountPool"); + } if (source === "detector") { return t("admin.groups.compositeRoutes.sources.detector"); } From 517f3222e446898c6202b44a7eac2364fc608770 Mon Sep 17 00:00:00 2001 From: shaw Date: Sat, 5 Dec 2026 19:16:03 +0800 Subject: [PATCH 80/81] =?UTF-8?q?fix(composite,=20ollama):=20=E6=94=B6?= =?UTF-8?q?=E5=8F=A3=E8=B7=A8=E7=BB=84=E9=99=8D=E7=BA=A7=E6=A0=A1=E9=AA=8C?= =?UTF-8?q?=E3=80=81=E6=B1=A0=E7=AD=96=E7=95=A5=E9=94=99=E8=AF=AF=E4=BF=9D?= =?UTF-8?q?=E7=95=99=E3=80=81OAuth=20=E9=80=8F=E4=BC=A0=E9=97=A8=E7=A6=81?= =?UTF-8?q?=E4=B8=8E=E4=BA=8B=E5=8A=A1=20outbox?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../handler/composite_pool_attempt_policy.go | 11 +- .../handler/composite_pool_audit_r7_test.go | 318 +++++++++++++++++ backend/internal/handler/gateway_handler.go | 30 +- .../gateway_handler_chat_completions.go | 13 + .../handler/gateway_handler_responses.go | 29 +- .../handler/openai_chat_completions.go | 6 + .../handler/openai_gateway_handler.go | 12 + .../account_repo_ollama_cloud_usage.go | 27 +- .../account_repo_ollama_cloud_usage_test.go | 29 ++ .../service/composite_pool_audit_r7_test.go | 332 ++++++++++++++++++ .../internal/service/gateway_scheduling.go | 26 +- .../internal/service/gateway_usage_billing.go | 34 +- .../service/openai_codex_models_service.go | 4 +- ..._gateway_ollama_cloud_pricing_preflight.go | 16 +- .../internal/service/openai_gateway_usage.go | 2 +- .../service/openai_ws_forwarder_support.go | 4 + 16 files changed, 842 insertions(+), 51 deletions(-) create mode 100644 backend/internal/handler/composite_pool_audit_r7_test.go create mode 100644 backend/internal/service/composite_pool_audit_r7_test.go diff --git a/backend/internal/handler/composite_pool_attempt_policy.go b/backend/internal/handler/composite_pool_attempt_policy.go index e37e38caf3..ed07d67b3b 100644 --- a/backend/internal/handler/composite_pool_attempt_policy.go +++ b/backend/internal/handler/composite_pool_attempt_policy.go @@ -187,14 +187,17 @@ type compositePoolAttemptPolicyFailure struct { // AccountChannelRestricted 表示限制仅来自当前账号映射后的 upstream 模型, // 重选时只排除该账号,不整平台屏蔽同平台其它账号。 AccountChannelRestricted bool + // MessagesDispatchForbidden 表示分组关闭了 AllowMessagesDispatch,禁止 openai 账号 + // 承接 /v1/messages(终止时须返回 403 permission_error,不能误报 503)。 + MessagesDispatchForbidden bool } func (f compositePoolAttemptPolicyFailure) denied() bool { - return f.QuotaErr != nil || f.ChannelRestricted + return f.QuotaErr != nil || f.ChannelRestricted || f.MessagesDispatchForbidden } func (f compositePoolAttemptPolicyFailure) deniesPlatform() bool { - return f.QuotaErr != nil || (f.ChannelRestricted && !f.AccountChannelRestricted) + return f.QuotaErr != nil || f.MessagesDispatchForbidden || (f.ChannelRestricted && !f.AccountChannelRestricted) } // compositePoolAttemptPolicy 汇总一次 attempt 的策略检查结果。 @@ -274,6 +277,10 @@ func respondCompositePoolAttemptPolicyFailure(c *gin.Context, failure compositeP write(c, status, code, message) return } + if failure.MessagesDispatchForbidden { + write(c, http.StatusForbidden, "permission_error", "This group does not allow /v1/messages dispatch") + return + } write(c, http.StatusServiceUnavailable, "api_error", "Service temporarily unavailable") } diff --git a/backend/internal/handler/composite_pool_audit_r7_test.go b/backend/internal/handler/composite_pool_audit_r7_test.go new file mode 100644 index 0000000000..d424cb485e --- /dev/null +++ b/backend/internal/handler/composite_pool_audit_r7_test.go @@ -0,0 +1,318 @@ +//go:build unit + +package handler + +import ( + "context" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/Wei-Shaw/sub2api/internal/pkg/ctxkey" + middleware2 "github.com/Wei-Shaw/sub2api/internal/server/middleware" + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +func buildClaudeCodeFallbackCompositeHandler( + t *testing.T, + allowMessagesDispatch bool, + ownership service.CompositeModelOwnership, + accounts []*service.Account, +) (*GatewayHandler, *service.Group, *compositePoolFakeUpstream, *compositePoolFakeUpstream) { + t.Helper() + gin.SetMode(gin.TestMode) + + primaryID := int64(7101) + fallbackID := int64(7102) + primaryGroup := &service.Group{ + ID: primaryID, + Name: "ant-cc-only", + Platform: service.PlatformAnthropic, + Status: service.StatusActive, + Hydrated: true, + ClaudeCodeOnly: true, + FallbackGroupID: &fallbackID, + AllowMessagesDispatch: true, + } + fallbackGroup := &service.Group{ + ID: fallbackID, + Name: "comp-fallback", + Platform: service.PlatformComposite, + Status: service.StatusActive, + Hydrated: true, + AllowMessagesDispatch: allowMessagesDispatch, + } + + cfg := &config.Config{RunMode: config.RunModeSimple} + cfg.Security = config.SecurityConfig{URLAllowlist: config.URLAllowlistConfig{Enabled: false}} + + openAIUpstream := &compositePoolFakeUpstream{ + respond: func(_ compositePoolUpstreamCall, _ int) *http.Response { + return chatCompletionsOKResponse("gpt-5.4", 10, 5) + }, + } + gwUpstream := &compositePoolFakeUpstream{} + groupRepo := &multiGroupStubRepo{byID: map[int64]*service.Group{ + primaryID: primaryGroup, + fallbackID: fallbackGroup, + }} + schedCache := &platformScopedSchedulerCache{fakeSchedulerCache{accounts: accounts}} + snap := service.NewSchedulerSnapshotService(schedCache, nil, nil, nil, nil) + bs := service.NewBillingService(cfg, nil) + usageRepo := &compositePoolUsageLogRepo{} + + compositeResolver := service.NewCompositeRouteResolver(nil) + gwSvc := service.NewGatewayService( + nil, groupRepo, usageRepo, nil, nil, nil, nil, nil, cfg, snap, nil, bs, nil, nil, nil, + gwUpstream, nil, nil, nil, nil, nil, nil, nil, nil, nil, compositeResolver, nil, nil, + ) + compositeResolver.SetModelOwnershipResolver(func(context.Context, int64, string) (service.CompositeModelOwnership, error) { + return ownership, nil + }) + oaSvc := service.NewOpenAIGatewayService( + nil, usageRepo, nil, nil, nil, nil, nil, cfg, nil, nil, bs, nil, nil, + openAIUpstream, service.NewDeferredService(nil, nil, 0), nil, nil, nil, nil, nil, nil, nil, + ) + billingCache := service.NewBillingCacheService(nil, nil, nil, nil, nil, nil, cfg, nil) + t.Cleanup(billingCache.Stop) + + h := &GatewayHandler{ + gatewayService: gwSvc, + openAIGatewayService: oaSvc, + billingCacheService: billingCache, + concurrencyHelper: NewConcurrencyHelper(service.NewConcurrencyService(&fakeConcurrencyCache{}), SSEPingFormatClaude, 0), + maxAccountSwitches: 3, + cfg: cfg, + openAIHandler: &OpenAIGatewayHandler{gatewayService: oaSvc}, + } + return h, primaryGroup, openAIUpstream, gwUpstream +} + +// P0 回归:ClaudeCodeOnly 分组降级到 composite 分组时,携带 previous_response_id 的 +// /v1/responses 请求绝不能绕过租户归属校验被委派给共享 OpenAI 账号。 +func TestClaudeCodeOnlyFallback_ResponsesRejectsPreviousResponseID(t *testing.T) { + openAIAcc := &service.Account{ + ID: 7201, + Name: "oa-shared", + Platform: service.PlatformOpenAI, + Type: service.AccountTypeAPIKey, + Status: service.StatusActive, + Schedulable: true, + Concurrency: 2, + Priority: 1, + GroupIDs: []int64{7102}, + Credentials: map[string]any{ + "api_key": "sk-oa-shared", + "base_url": "https://openai-mock.example/v1", + "model_mapping": map[string]any{"gpt-5.4": "gpt-5.4"}, + }, + } + h, primaryGroup, openAIUpstream, gwUpstream := buildClaudeCodeFallbackCompositeHandler( + t, + true, + service.CompositeModelOwnership{ + Matched: true, + TargetPlatform: service.PlatformOpenAI, + RequiredClaimStrength: service.CompositeClaimExplicit, + }, + []*service.Account{openAIAcc}, + ) + + body := `{"model":"gpt-5.4","previous_response_id":"resp_victim_123","input":"steal state"}` + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", strings.NewReader(body)) + c.Request.Header.Set("Content-Type", "application/json") + c.Request.Header.Set("User-Agent", "curl/8.0") + primaryID := primaryGroup.ID + apiKey := &service.APIKey{ID: 2, UserID: 2, GroupID: &primaryID, Group: primaryGroup, User: &service.User{ID: 2, Concurrency: 5}} + c.Request = c.Request.WithContext(context.WithValue(c.Request.Context(), ctxkey.Group, primaryGroup)) + c.Set(string(middleware2.ContextKeyAPIKey), apiKey) + c.Set(string(middleware2.ContextKeyUser), middleware2.AuthSubject{UserID: 2, Concurrency: 5}) + + h.Responses(c) + + require.Equal(t, http.StatusBadRequest, rec.Code, rec.Body.String()) + require.Contains(t, rec.Body.String(), "previous_response_id") + require.Empty(t, openAIUpstream.snapshot(), "must not delegate unverified previous_response_id to shared OpenAI account") + require.Empty(t, gwUpstream.snapshot()) +} + +// 回归:ClaudeCodeOnly 分组降级到 AllowMessagesDispatch=false 的 composite 组(单目标与账号池) +// 选中 openai 账号时均返回 403 permission_error,不得绕过或误报 503。 +func TestClaudeCodeOnlyFallback_MessagesAllowMessagesDispatchForbidden(t *testing.T) { + openAIAcc := &service.Account{ + ID: 7301, + Name: "oa-single", + Platform: service.PlatformOpenAI, + Type: service.AccountTypeAPIKey, + Status: service.StatusActive, + Schedulable: true, + Concurrency: 2, + Priority: 1, + GroupIDs: []int64{7102}, + Credentials: map[string]any{ + "api_key": "sk-oa", + "base_url": "https://openai-mock.example/v1", + "model_mapping": map[string]any{"shared-model": "gpt-5.4"}, + }, + } + + for _, tc := range []struct { + name string + ownership service.CompositeModelOwnership + }{ + { + name: "single_target_openai", + ownership: service.CompositeModelOwnership{ + Matched: true, + TargetPlatform: service.PlatformOpenAI, + RequiredClaimStrength: service.CompositeClaimExplicit, + }, + }, + { + name: "pool_only_openai_schedulable", + ownership: service.CompositeModelOwnership{ + Matched: true, + CandidatePlatforms: []string{service.PlatformAnthropic, service.PlatformOpenAI}, + RequiredClaimStrength: service.CompositeClaimExplicit, + }, + }, + } { + t.Run(tc.name, func(t *testing.T) { + h, primaryGroup, openAIUpstream, gwUpstream := buildClaudeCodeFallbackCompositeHandler( + t, false, tc.ownership, []*service.Account{openAIAcc}, + ) + body := `{"model":"shared-model","max_tokens":32,"messages":[{"role":"user","content":"hi"}]}` + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", strings.NewReader(body)) + c.Request.Header.Set("Content-Type", "application/json") + c.Request.Header.Set("User-Agent", "curl/8.0") + primaryID := primaryGroup.ID + apiKey := &service.APIKey{ID: 1, UserID: 1, GroupID: &primaryID, Group: primaryGroup, User: &service.User{ID: 1, Concurrency: 5}} + c.Request = c.Request.WithContext(context.WithValue(c.Request.Context(), ctxkey.Group, primaryGroup)) + c.Set(string(middleware2.ContextKeyAPIKey), apiKey) + c.Set(string(middleware2.ContextKeyUser), middleware2.AuthSubject{UserID: 1, Concurrency: 5}) + + h.Messages(c) + + require.Equal(t, http.StatusForbidden, rec.Code, rec.Body.String()) + require.Contains(t, rec.Body.String(), "permission_error") + require.Empty(t, openAIUpstream.snapshot()) + require.Empty(t, gwUpstream.snapshot()) + }) + } +} + +// 回归:CountTokens 降级选中不可计数的 OpenAI 账号时返回 404,绝不把 OpenAI Key 发往 Anthropic count_tokens。 +func TestClaudeCodeOnlyFallback_CountTokensRejectsUncountableOpenAIAccount(t *testing.T) { + openAIAcc := &service.Account{ + ID: 7401, + Name: "oa-uncountable", + Platform: service.PlatformOpenAI, + Type: service.AccountTypeAPIKey, + Status: service.StatusActive, + Schedulable: true, + Concurrency: 2, + Priority: 1, + GroupIDs: []int64{7102}, + Credentials: map[string]any{ + "api_key": "sk-oa-never-send-to-count-tokens", + "base_url": "https://openai-mock.example/v1", + "model_mapping": map[string]any{"shared-model": "gpt-5.4"}, + }, + } + h, primaryGroup, openAIUpstream, gwUpstream := buildClaudeCodeFallbackCompositeHandler( + t, + true, + service.CompositeModelOwnership{ + Matched: true, + TargetPlatform: service.PlatformOpenAI, + RequiredClaimStrength: service.CompositeClaimExplicit, + }, + []*service.Account{openAIAcc}, + ) + + body := `{"model":"shared-model","messages":[{"role":"user","content":"hi"}]}` + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages/count_tokens", strings.NewReader(body)) + c.Request.Header.Set("Content-Type", "application/json") + c.Request.Header.Set("User-Agent", "curl/8.0") + primaryID := primaryGroup.ID + apiKey := &service.APIKey{ID: 1, UserID: 1, GroupID: &primaryID, Group: primaryGroup, User: &service.User{ID: 1, Concurrency: 5}} + c.Request = c.Request.WithContext(context.WithValue(c.Request.Context(), ctxkey.Group, primaryGroup)) + c.Set(string(middleware2.ContextKeyAPIKey), apiKey) + c.Set(string(middleware2.ContextKeyUser), middleware2.AuthSubject{UserID: 1, Concurrency: 5}) + + h.CountTokens(c) + + require.Equal(t, http.StatusNotFound, rec.Code, rec.Body.String()) + require.Empty(t, gwUpstream.snapshot(), "must not forward OpenAI APIKey to Anthropic count_tokens") + require.Empty(t, openAIUpstream.snapshot()) +} + +// 回归:池首轮触发业务策略拒绝(429 平台配额),且次轮无其余可调度平台账号时, +// 返回真实的 429 + Retry-After 而非 502。 +func TestCompositePool_PreservesPolicyFailureInsteadOf502WhenExhausted(t *testing.T) { + openAIAcc := &service.Account{ + ID: 7501, + Name: "oa-quota-hit", + Platform: service.PlatformOpenAI, + Type: service.AccountTypeAPIKey, + Status: service.StatusActive, + Schedulable: true, + Concurrency: 2, + Priority: 1, + GroupIDs: []int64{41011}, + Credentials: map[string]any{ + "api_key": "sk-oa", + "base_url": "https://openai-mock.example/v1", + "model_mapping": map[string]any{"shared-model": "gpt-5.4"}, + }, + } + // Candidate pool has [anthropic, openai], but only openai has a schedulable account. + harness := newCompositePoolMessagesHarness(t, []*service.Account{openAIAcc}) + harness.group.AllowMessagesDispatch = true + quotaLimit := 1.0 + now := time.Now() + stdCfg := &config.Config{RunMode: config.RunModeStandard} + billingCache := service.NewBillingCacheService( + &r7QuotaBillingCache{ + poolAttemptFakeQuotaCache: poolAttemptFakeQuotaCache{ + entry: &service.UserPlatformQuotaCacheEntry{ + SchemaVersion: service.UserPlatformQuotaCacheSchemaV1, + DailyLimitUSD: "aLimit, + DailyUsageUSD: 2.0, + DailyWindowStart: &now, + }, + }, + }, + nil, nil, nil, nil, nil, stdCfg, &poolAttemptFakeQuotaRepo{}, + ) + t.Cleanup(billingCache.Stop) + harness.handler.billingCacheService = billingCache + + c, rec := harness.newRequest(t, "/v1/messages", + `{"model":"shared-model","max_tokens":32,"messages":[{"role":"user","content":"hi"}]}`, + service.PlatformAnthropic, service.PlatformOpenAI) + harness.handler.Messages(c) + + require.Equal(t, http.StatusTooManyRequests, rec.Code, rec.Body.String()) + require.NotEmpty(t, rec.Header().Get("Retry-After")) + require.Empty(t, harness.openAIUpstream.snapshot()) +} + +type r7QuotaBillingCache struct { + poolAttemptFakeQuotaCache +} + +func (*r7QuotaBillingCache) GetUserBalance(context.Context, int64) (float64, error) { + return 100.0, nil +} diff --git a/backend/internal/handler/gateway_handler.go b/backend/internal/handler/gateway_handler.go index 978e0f34f2..c4fffb8c7c 100644 --- a/backend/internal/handler/gateway_handler.go +++ b/backend/internal/handler/gateway_handler.go @@ -696,6 +696,7 @@ func (h *GatewayHandler) Messages(c *gin.Context) { for { fs := NewFailoverState(h.maxAccountSwitches, hasBoundSession) + var lastPolicyFailure compositePoolAttemptPolicyFailure retryWithFallback := false schedAPIKey := currentAPIKey @@ -760,6 +761,11 @@ func (h *GatewayHandler) Messages(c *gin.Context) { default: // FailoverExhausted if fs.LastFailoverErr != nil { h.handleFailoverExhausted(c, fs.LastFailoverErr, platform, streamStarted) + } else if lastPolicyFailure.denied() { + streamAwareWrite := func(cc *gin.Context, status int, code, message string) { + h.handleStreamingAwareError(cc, status, code, message, streamStarted) + } + respondCompositePoolAttemptPolicyFailure(c, lastPolicyFailure, streamAwareWrite) } else { h.handleFailoverExhaustedSimple(c, 502, streamStarted) } @@ -773,10 +779,18 @@ func (h *GatewayHandler) Messages(c *gin.Context) { var switchedGroup bool schedAPIKey, _, channelMapping, isPoolRequest, poolDenials, switchedGroup = h.syncSelectionEffectiveGroup( c, currentAPIKey, schedAPIKey, c.Request.Context(), channelMapping, reqModel, isPoolRequest, poolDenials, selection) - if switchedGroup && isPoolRequest { + if switchedGroup && compositeOrPoolDispatchActive(isPoolRequest, schedAPIKey) { bindOpenAIReasoningEffortPolicyForMessagesRequest(c, schedAPIKey, body) if !schedAPIKey.Group.AllowMessagesDispatch { - poolDenials.deny(service.PlatformOpenAI) + if !isPoolRequest && account.Platform == service.PlatformOpenAI { + releaseCompositePoolSelection(selection) + h.gatewayService.ReleaseAccountSession(context.Background(), account, sessionKey) + h.handleStreamingAwareError(c, http.StatusForbidden, "permission_error", "This group does not allow /v1/messages dispatch", streamStarted) + return + } + if isPoolRequest { + poolDenials.deny(service.PlatformOpenAI) + } } } setOpsSelectedAccount(c, account.ID, account.Platform) @@ -804,7 +818,7 @@ func (h *GatewayHandler) Messages(c *gin.Context) { c.Request.Context(), h.billingCacheService, h.openAIGatewayService, schedAPIKey, currentSubscription, account, reqModel, false) isPoolAttempt = true if isPoolRequest && !schedAPIKey.Group.AllowMessagesDispatch && account.Platform == service.PlatformOpenAI { - attemptPolicy.Failure.ChannelRestricted = true + attemptPolicy.Failure.MessagesDispatchForbidden = true } if attemptPolicy.Failure.denied() { releaseCompositePoolSelection(selection) @@ -813,6 +827,7 @@ func (h *GatewayHandler) Messages(c *gin.Context) { if attemptPolicy.Failure.deniesPlatform() { poolDenials.deny(account.Platform) } + lastPolicyFailure = attemptPolicy.Failure fs.FailedAccountIDs[account.ID] = struct{}{} // 候选全部被业务限制:按 deny 原因明确终止(后续重选不再尝试)。 if _, ok := compositePoolSelectionRetryContext(c.Request.Context(), poolDenials); !ok { @@ -2466,9 +2481,16 @@ func (h *GatewayHandler) CountTokens(c *gin.Context) { h.errorResponse(c, cls.Status, cls.ErrType, cls.Message) return } - if !isPoolRequest || service.GenericCompositePoolCountableAccount(account) { + if service.GenericCompositePoolCountableAccount(account) { break } + if !isPoolRequest { + // ClaudeCodeOnly 等跨组降级选到不可计数的外平台账号时,不得把其凭据送进 + // Anthropic /v1/messages/count_tokens 链路。 + h.gatewayService.ReleaseAccountSession(context.Background(), account, sessionHash) + h.errorResponse(c, http.StatusNotFound, "not_found_error", "count_tokens endpoint is not supported for this platform") + return + } reqLog.Info("gateway.count_tokens_pool_skip_uncountable_account", zap.Int64("account_id", account.ID), zap.String("account_platform", account.Platform), diff --git a/backend/internal/handler/gateway_handler_chat_completions.go b/backend/internal/handler/gateway_handler_chat_completions.go index cbe7598d08..e5b1c19e02 100644 --- a/backend/internal/handler/gateway_handler_chat_completions.go +++ b/backend/internal/handler/gateway_handler_chat_completions.go @@ -211,6 +211,7 @@ func (h *GatewayHandler) ChatCompletions(c *gin.Context) { if groupPlatform == service.PlatformGemini { fs = NewFailoverState(h.maxAccountSwitchesGemini, false) } + var lastPolicyFailure compositePoolAttemptPolicyFailure schedAPIKey := apiKey for { @@ -255,6 +256,17 @@ func (h *GatewayHandler) ChatCompletions(c *gin.Context) { default: if fs.LastFailoverErr != nil { h.handleCCFailoverExhausted(c, fs.LastFailoverErr, streamStarted) + } else if lastPolicyFailure.denied() { + streamAwareWrite := func(cc *gin.Context, status int, code, message string) { + if streamStarted { + h.handleStreamingAwareError(cc, status, code, message, true) + return + } + h.chatCompletionsErrorResponse(cc, status, code, message) + } + respondCompositePoolAttemptPolicyFailure(c, lastPolicyFailure, streamAwareWrite) + } else if streamStarted { + h.handleStreamingAwareError(c, http.StatusBadGateway, "server_error", "All available accounts exhausted", true) } else { h.chatCompletionsErrorResponse(c, http.StatusBadGateway, "server_error", "All available accounts exhausted") } @@ -293,6 +305,7 @@ func (h *GatewayHandler) ChatCompletions(c *gin.Context) { if attemptPolicy.Failure.deniesPlatform() { poolDenials.deny(account.Platform) } + lastPolicyFailure = attemptPolicy.Failure fs.FailedAccountIDs[account.ID] = struct{}{} // 候选全部被业务限制:按 deny 原因明确终止(后续重选不再尝试)。 if _, ok := compositePoolSelectionRetryContext(c.Request.Context(), poolDenials); !ok { diff --git a/backend/internal/handler/gateway_handler_responses.go b/backend/internal/handler/gateway_handler_responses.go index 083df3ba83..f2255f883f 100644 --- a/backend/internal/handler/gateway_handler_responses.go +++ b/backend/internal/handler/gateway_handler_responses.go @@ -224,6 +224,7 @@ func (h *GatewayHandler) Responses(c *gin.Context) { // 3. Account selection + failover loop fs := NewFailoverState(h.maxAccountSwitches, false) + var lastPolicyFailure compositePoolAttemptPolicyFailure schedAPIKey := apiKey for { @@ -268,6 +269,17 @@ func (h *GatewayHandler) Responses(c *gin.Context) { default: if fs.LastFailoverErr != nil { h.handleResponsesFailoverExhausted(c, fs.LastFailoverErr, streamStarted) + } else if lastPolicyFailure.denied() { + streamAwareWrite := func(cc *gin.Context, status int, code, message string) { + if streamStarted { + h.handleStreamingAwareError(cc, status, code, message, true) + return + } + h.responsesErrorResponse(cc, status, code, message) + } + respondCompositePoolAttemptPolicyFailure(c, lastPolicyFailure, streamAwareWrite) + } else if streamStarted { + h.handleStreamingAwareError(c, http.StatusBadGateway, "server_error", "All available accounts exhausted", true) } else { h.responsesErrorResponse(c, http.StatusBadGateway, "server_error", "All available accounts exhausted") } @@ -281,7 +293,21 @@ func (h *GatewayHandler) Responses(c *gin.Context) { var switchedGroup bool schedAPIKey, requestCtx, channelMapping, isPoolRequest, poolDenials, switchedGroup = h.syncSelectionEffectiveGroup( c, apiKey, schedAPIKey, requestCtx, channelMapping, reqModel, isPoolRequest, poolDenials, selection) - if switchedGroup && isPoolRequest { + if switchedGroup && compositeOrPoolDispatchActive(isPoolRequest, schedAPIKey) { + // 跨组降级进入 composite 组(单目标或账号池)前从未做过 previous_response_id 租户校验, + // 绝不允许把未校验的 previous_response_id 委派到共享 OpenAI 账号。 + if strings.TrimSpace(gjson.GetBytes(body, "previous_response_id").String()) != "" { + releaseCompositePoolSelection(selection) + h.gatewayService.ReleaseAccountSession(context.Background(), account, sessionHash) + if streamStarted { + h.handleStreamingAwareError(c, http.StatusBadRequest, "invalid_request_error", + "previous_response_id is not supported for this composite model; resend the full conversation without previous_response_id", true) + } else { + h.responsesErrorResponse(c, http.StatusBadRequest, "invalid_request_error", + "previous_response_id is not supported for this composite model; resend the full conversation without previous_response_id") + } + return + } service.SetOpenAIHTTPResponseOwner(c, subject.UserID, apiKey.ID) } setOpsSelectedAccount(c, account.ID, account.Platform) @@ -328,6 +354,7 @@ func (h *GatewayHandler) Responses(c *gin.Context) { if attemptPolicy.Failure.deniesPlatform() { poolDenials.deny(account.Platform) } + lastPolicyFailure = attemptPolicy.Failure fs.FailedAccountIDs[account.ID] = struct{}{} // 候选全部被业务限制:按 deny 原因明确终止(后续重选不再尝试)。 if _, ok := compositePoolSelectionRetryContext(requestCtx, poolDenials); !ok { diff --git a/backend/internal/handler/openai_chat_completions.go b/backend/internal/handler/openai_chat_completions.go index 794ea77feb..1ba5ff58b2 100644 --- a/backend/internal/handler/openai_chat_completions.go +++ b/backend/internal/handler/openai_chat_completions.go @@ -183,6 +183,7 @@ func (h *OpenAIGatewayHandler) ChatCompletions(c *gin.Context) { // deniedPlatforms,重选时以 filtered candidate ctx 传 selector 做整平台 mask; // 原请求 ctx 的候选池 immutable,不把选中账号写回。非池请求恒不生效。 poolDenials := newCompositePoolPlatformDenials() + var lastPolicyFailure compositePoolAttemptPolicyFailure selectionCtx := c.Request.Context() for { @@ -224,6 +225,10 @@ func (h *OpenAIGatewayHandler) ChatCompletions(c *gin.Context) { } else { if lastFailoverErr != nil { h.handleFailoverExhausted(c, lastFailoverErr, streamStarted) + } else if lastPolicyFailure.denied() { + respondCompositePoolAttemptPolicyFailure(c, lastPolicyFailure, func(cc *gin.Context, status int, code, message string) { + h.handleStreamingAwareError(cc, status, code, message, streamStarted) + }) } else { h.handleStreamingAwareError(c, http.StatusBadGateway, "api_error", "Upstream request failed", streamStarted) } @@ -282,6 +287,7 @@ func (h *OpenAIGatewayHandler) ChatCompletions(c *gin.Context) { if attemptPolicy.Failure.deniesPlatform() { poolDenials.deny(account.Platform) } + lastPolicyFailure = attemptPolicy.Failure // 同时排除该账号:下一轮 masked ctx 下 sticky 层对 excluded 账号 // 提前返回(不 clear),不会把原 sticky 账号当 platform mismatch // 清掉粘性绑定;其它平台成功后按用户目标正常改绑。 diff --git a/backend/internal/handler/openai_gateway_handler.go b/backend/internal/handler/openai_gateway_handler.go index 1803307630..2581d86bd7 100644 --- a/backend/internal/handler/openai_gateway_handler.go +++ b/backend/internal/handler/openai_gateway_handler.go @@ -738,6 +738,7 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) { // deniedPlatforms,重选时以 filtered candidate ctx 传 selector 做整平台 mask; // 原请求 ctx 的候选池 immutable,不把选中账号写回。非池请求恒不生效。 poolDenials := newCompositePoolPlatformDenials() + var lastPolicyFailure compositePoolAttemptPolicyFailure selectionCtx := c.Request.Context() var ( requestPayloadHashComputed bool @@ -806,6 +807,10 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) { } if lastFailoverErr != nil { h.handleFailoverExhausted(c, lastFailoverErr, streamStarted) + } else if lastPolicyFailure.denied() { + respondCompositePoolAttemptPolicyFailure(c, lastPolicyFailure, func(cc *gin.Context, status int, code, message string) { + h.handleStreamingAwareError(cc, status, code, message, streamStarted) + }) } else { h.handleFailoverExhaustedSimple(c, 502, streamStarted) } @@ -930,6 +935,7 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) { if attemptPolicy.Failure.deniesPlatform() { poolDenials.deny(account.Platform) } + lastPolicyFailure = attemptPolicy.Failure // 同时排除该账号:下一轮 masked ctx 下 sticky 层对 excluded 账号 // 提前返回(不 clear),不会把原 sticky 账号当 platform mismatch // 清掉粘性绑定;其它平台成功后按用户目标正常改绑。 @@ -1510,6 +1516,7 @@ func (h *OpenAIGatewayHandler) Messages(c *gin.Context) { // deniedPlatforms,重选时以 filtered candidate ctx 传 selector 做整平台 mask; // 原请求 ctx 的候选池 immutable,不把选中账号写回。非池请求恒不生效。 poolDenials := newCompositePoolPlatformDenials() + var lastPolicyFailure compositePoolAttemptPolicyFailure selectionCtx := c.Request.Context() for { @@ -1556,6 +1563,10 @@ func (h *OpenAIGatewayHandler) Messages(c *gin.Context) { } else { if lastFailoverErr != nil { h.handleAnthropicFailoverExhausted(c, lastFailoverErr, streamStarted) + } else if lastPolicyFailure.denied() { + respondCompositePoolAttemptPolicyFailure(c, lastPolicyFailure, func(cc *gin.Context, status int, code, message string) { + h.anthropicStreamingAwareError(cc, status, code, message, streamStarted) + }) } else { h.anthropicStreamingAwareError(c, http.StatusBadGateway, "api_error", "Upstream request failed", streamStarted) } @@ -1596,6 +1607,7 @@ func (h *OpenAIGatewayHandler) Messages(c *gin.Context) { if attemptPolicyMsg.Failure.deniesPlatform() { poolDenials.deny(account.Platform) } + lastPolicyFailure = attemptPolicyMsg.Failure // 同时排除该账号:下一轮 masked ctx 下 sticky 层对 excluded 账号 // 提前返回(不 clear),不清掉原 sticky 粘性绑定。 failedAccountIDs[account.ID] = struct{}{} diff --git a/backend/internal/repository/account_repo_ollama_cloud_usage.go b/backend/internal/repository/account_repo_ollama_cloud_usage.go index 964ac6f578..5c741ffd25 100644 --- a/backend/internal/repository/account_repo_ollama_cloud_usage.go +++ b/backend/internal/repository/account_repo_ollama_cloud_usage.go @@ -8,7 +8,6 @@ import ( "time" dbent "github.com/Wei-Shaw/sub2api/ent" - "github.com/Wei-Shaw/sub2api/internal/pkg/logger" "github.com/Wei-Shaw/sub2api/internal/service" "github.com/lib/pq" ) @@ -276,6 +275,12 @@ func (r *accountRepository) updateOllamaCloudUsageGroup( if affected != int64(len(members)) { return service.ErrOllamaCloudUsageIdentityChanged } + for _, memberID := range memberIDs { + id := memberID + if err := enqueueSchedulerOutbox(txCtx, client, service.SchedulerOutboxEventAccountChanged, &id, nil, nil); err != nil { + return err + } + } syncedMemberIDs = memberIDs return nil } @@ -284,7 +289,7 @@ func (r *accountRepository) updateOllamaCloudUsageGroup( return err } service.AfterAccountCommit(ctx, func(commitCtx context.Context) { - r.syncOllamaCloudUsageSchedulerState(commitCtx, syncedMemberIDs) + r.syncSchedulerAccountSnapshots(commitCtx, syncedMemberIDs) }) return nil } @@ -293,7 +298,8 @@ func (r *accountRepository) updateOllamaCloudUsageGroup( if err := apply(ctx, r.client); err != nil { return err } - r.syncOllamaCloudUsageSchedulerState(ctx, syncedMemberIDs) + // 外层事务尚未提交且未把 tx 放进 ctx:outbox 已在事务内落库, + // 不能提前把未提交行刷进 Redis 快照,交由 outbox 在外层提交后异步同步。 return nil } if err != nil { @@ -307,23 +313,10 @@ func (r *accountRepository) updateOllamaCloudUsageGroup( if err := tx.Commit(); err != nil { return err } - r.syncOllamaCloudUsageSchedulerState(ctx, syncedMemberIDs) + r.syncSchedulerAccountSnapshots(ctx, syncedMemberIDs) return nil } -func (r *accountRepository) syncOllamaCloudUsageSchedulerState(ctx context.Context, memberIDs []int64) { - if r == nil || len(memberIDs) == 0 { - return - } - for _, memberID := range memberIDs { - id := memberID - if err := enqueueSchedulerOutbox(ctx, r.sql, service.SchedulerOutboxEventAccountChanged, &id, nil, nil); err != nil { - logger.LegacyPrintf("repository.account", "[SchedulerOutbox] enqueue ollama cloud usage sync failed: account=%d err=%v", id, err) - } - } - r.syncSchedulerAccountSnapshots(ctx, memberIDs) -} - func lockOllamaCloudUsageGroup( ctx context.Context, client *dbent.Client, diff --git a/backend/internal/repository/account_repo_ollama_cloud_usage_test.go b/backend/internal/repository/account_repo_ollama_cloud_usage_test.go index 42617672b3..16e13a0261 100644 --- a/backend/internal/repository/account_repo_ollama_cloud_usage_test.go +++ b/backend/internal/repository/account_repo_ollama_cloud_usage_test.go @@ -122,6 +122,9 @@ func TestSaveAndDeleteOllamaCloudUsageSessionKeepCiphertextOutOfSQL(t *testing.T mock.ExpectExec(`(?s)UPDATE accounts.*ollama_cloud_usage_session.*ollama_cloud_usage_auto_refresh.*ollama_cloud_usage_snapshot`). WithArgs(`{"ollama_cloud_usage_auto_refresh":true,"ollama_cloud_usage_session":"cipher:wos-session=browser-cookie-secret"}`, "key", sqlmock.AnyArg()). WillReturnResult(sqlmock.NewResult(0, 1)) + mock.ExpectExec(regexp.QuoteMeta("INSERT INTO scheduler_outbox")). + WithArgs(service.SchedulerOutboxEventAccountChanged, account.ID, nil, nil, sqlmock.AnyArg()). + WillReturnResult(sqlmock.NewResult(1, 1)) mock.ExpectCommit() require.NoError(t, repo.SaveOllamaCloudUsageSession(context.Background(), account, replacement, true)) @@ -131,6 +134,9 @@ func TestSaveAndDeleteOllamaCloudUsageSessionKeepCiphertextOutOfSQL(t *testing.T mock.ExpectExec(`(?s)UPDATE accounts.*ollama_cloud_usage_session.*ollama_cloud_usage_auto_refresh.*ollama_cloud_usage_snapshot`). WithArgs(`{}`, "key", sqlmock.AnyArg()). WillReturnResult(sqlmock.NewResult(0, 1)) + mock.ExpectExec(regexp.QuoteMeta("INSERT INTO scheduler_outbox")). + WithArgs(service.SchedulerOutboxEventAccountChanged, account.ID, nil, nil, sqlmock.AnyArg()). + WillReturnResult(sqlmock.NewResult(1, 1)) mock.ExpectCommit() require.NoError(t, repo.DeleteOllamaCloudUsageSession(context.Background(), account)) @@ -287,6 +293,9 @@ func TestDisableOllamaCloudUsageAutoRefreshUsesGroupIdentityCAS(t *testing.T) { mock.ExpectExec(`(?s)UPDATE accounts.*ollama_cloud_usage_auto_refresh`). WithArgs(`{"ollama_cloud_usage_auto_refresh":false,"ollama_cloud_usage_session":"cipher:wos-session=secret"}`, "key", sqlmock.AnyArg()). WillReturnResult(sqlmock.NewResult(0, 1)) + mock.ExpectExec(regexp.QuoteMeta("INSERT INTO scheduler_outbox")). + WithArgs(service.SchedulerOutboxEventAccountChanged, account.ID, nil, nil, sqlmock.AnyArg()). + WillReturnResult(sqlmock.NewResult(1, 1)) mock.ExpectCommit() repo := newAccountRepositoryWithSQL(client, nil, nil) @@ -397,3 +406,23 @@ func TestUpdateCredentialsPlainCNAPIKeyAccountCleanupStaysSemanticallyEquivalent require.NotContains(t, query, "- 'upstream_billing_rate_sync_enabled'") require.NoError(t, mock.ExpectationsWereMet()) } + +func TestUpdateOllamaCloudUsageRollsBackWhenOutboxFails(t *testing.T) { + client, mock := newOllamaCloudUsageRepositoryTestClient(t) + account := ollamaCloudUsageRepositoryAccount() + mock.ExpectBegin() + expectOllamaCloudUsageGroupLock(mock, account, true, `"cipher:wos-session=secret"`, `true`, `null`) + mock.ExpectExec(`(?s)UPDATE accounts.*ollama_cloud_usage_auto_refresh`). + WithArgs(`{"ollama_cloud_usage_auto_refresh":false,"ollama_cloud_usage_session":"cipher:wos-session=secret"}`, "key", sqlmock.AnyArg()). + WillReturnResult(sqlmock.NewResult(0, 1)) + mock.ExpectExec(regexp.QuoteMeta("INSERT INTO scheduler_outbox")). + WithArgs(service.SchedulerOutboxEventAccountChanged, account.ID, nil, nil, sqlmock.AnyArg()). + WillReturnError(context.DeadlineExceeded) + mock.ExpectRollback() + repo := newAccountRepositoryWithSQL(client, nil, nil) + + err := repo.DisableOllamaCloudUsageAutoRefresh(context.Background(), account) + + require.ErrorIs(t, err, context.DeadlineExceeded) + require.NoError(t, mock.ExpectationsWereMet()) +} diff --git a/backend/internal/service/composite_pool_audit_r7_test.go b/backend/internal/service/composite_pool_audit_r7_test.go new file mode 100644 index 0000000000..9c9f639417 --- /dev/null +++ b/backend/internal/service/composite_pool_audit_r7_test.go @@ -0,0 +1,332 @@ +//go:build unit + +package service + +import ( + "context" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/Wei-Shaw/sub2api/internal/pkg/ctxkey" + "github.com/stretchr/testify/require" +) + +func TestGenericPool_OpenAIOAuthPassthroughRejectsNonCodexModels(t *testing.T) { + svc := &GatewayService{} + poolCtx := WithCompositeCandidatePlatforms(context.Background(), []string{PlatformAnthropic, PlatformOpenAI}) + + oauthPassthrough := &Account{ + ID: 9101, + Platform: PlatformOpenAI, + Type: AccountTypeOAuth, + Extra: map[string]any{"openai_oauth_passthrough": true}, + } + require.False(t, svc.gatewaySchedulingModelSupported(poolCtx, oauthPassthrough, "claude-sonnet-4-5"), + "OpenAI OAuth passthrough must not accept claude-* models in generic composite pools") + require.False(t, svc.gatewaySchedulingModelSupported(poolCtx, oauthPassthrough, "gpt-5.5"), + "OpenAI OAuth passthrough must still honor retired subscription model gate") + require.True(t, svc.gatewaySchedulingModelSupported(poolCtx, oauthPassthrough, "gpt-5.4"), + "OpenAI OAuth passthrough remains eligible for native Codex models") + + apiKeyPassthrough := &Account{ + ID: 9102, + Platform: PlatformOpenAI, + Type: AccountTypeAPIKey, + Credentials: map[string]any{ + "model_mapping": map[string]any{"old-model": "gpt-4o"}, + }, + Extra: map[string]any{"openai_passthrough": true}, + } + require.True(t, svc.gatewaySchedulingModelSupported(poolCtx, apiKeyPassthrough, "my-custom-alias"), + "OpenAI APIKey passthrough preserves the PR's stale-mapping selection exception") +} + +func TestOllamaCloudPreflightAndBilling_WildcardMultiplierCardAndBillingGroup(t *testing.T) { + catalog := `{ + "claude-sonnet-4-5": {"input_cost_per_token": 3e-06, "output_cost_per_token": 15e-06, "litellm_provider": "anthropic", "mode": "chat"}, + "gpt-oss:120b": {"input_cost_per_token": 1.5e-07, "output_cost_per_token": 6e-07, "litellm_provider": "openai", "mode": "chat"} + }` + cfg := &config.Config{RunMode: config.RunModeStandard} + cfg.Default.RateMultiplier = 1 + bs := NewBillingService(cfg, newStubPricingServiceFromJSON(t, catalog)) + + groupID := int64(9201) + group := &Group{ID: groupID, Platform: PlatformOllamaCloud, Status: StatusActive, Hydrated: true, RateMultiplier: 1} + buildOllamaChannelSvc := func(pricings []ChannelModelPricing) *ChannelService { + ch := Channel{ + ID: 9210, + Name: "ollama-ch", + Status: StatusActive, + ModelPricing: pricings, + GroupIDs: []int64{groupID}, + } + cs := &ChannelService{} + cs.cache.Store(populateChannelCache([]Channel{ch}, map[int64]string{groupID: PlatformOllamaCloud})) + return cs + } + chSvc := buildOllamaChannelSvc([]ChannelModelPricing{{ + Platform: PlatformOllamaCloud, + Models: []string{"*"}, + BillingMode: BillingModeToken, + ReasoningEffortMultipliers: map[string]float64{"high": 1.2}, + }}) + resolver := NewModelPricingResolver(chSvc, bs) + + ctx := context.WithValue(context.Background(), ctxkey.Group, group) + require.True(t, ollamaCloudModelUnpricedForBilling(ctx, resolver, "claude-sonnet-4-5"), + "wildcard multiplier-only '*' card must NOT pass claude-* through ollama_cloud preflight") + + apiKey := &APIKey{ID: 1, GroupID: &groupID, Group: group, User: &User{ID: 1}} + oaSvc := &OpenAIGatewayService{ + cfg: cfg, + billingService: bs, + channelService: chSvc, + resolver: resolver, + } + ollamaAcc := &Account{ID: 9202, Platform: PlatformOllamaCloud, Type: AccountTypeAPIKey} + filtered := oaSvc.filterCNProviderBillingModelCandidates(ctx, ollamaAcc, apiKey, []string{"claude-sonnet-4-5", "gpt-oss:120b"}) + require.Equal(t, []string{"gpt-oss:120b"}, filtered, + "wildcard multiplier-only '*' card must NOT keep claude-* as billing model for hosted-model accounts") + + // Explicit single-model card matches tagged model names in compositeAliasHasExplicitChannelPrice. + explicitPrice := 1e-6 + chSvcExplicit := buildOllamaChannelSvc([]ChannelModelPricing{{ + Platform: PlatformOllamaCloud, + Models: []string{"claude-sonnet-4-5"}, + BillingMode: BillingModeToken, + InputPrice: &explicitPrice, + OutputPrice: &explicitPrice, + }}) + resolverExplicit := NewModelPricingResolver(chSvcExplicit, bs) + require.False(t, ollamaCloudModelUnpricedForBilling(ctx, resolverExplicit, "claude-sonnet-4-5:cloud"), + "explicit model card must match :tag-stripped model consistently across preflight and billing") + resolved := resolverExplicit.Resolve(ctx, PricingInput{Model: "claude-sonnet-4-5:cloud", GroupID: &groupID, Group: group}) + require.True(t, compositeAliasHasExplicitChannelPrice(resolved, "claude-sonnet-4-5:cloud")) + + // Billing group frozen at request entry takes precedence over fallback ctxkey.Group. + primaryGroup := &Group{ID: 9203, Platform: PlatformAnthropic, Status: StatusActive, Hydrated: true} + fallbackGroup := &Group{ID: 9204, Platform: PlatformComposite, Status: StatusActive, Hydrated: true} + reqCtx, _ := WithGatewayTokenRequestPricing(context.WithValue(context.Background(), ctxkey.Group, primaryGroup)) + reqCtx = context.WithValue(reqCtx, ctxkey.Group, fallbackGroup) + gotGroup := ollamaCloudBillingGroupFromContext(reqCtx) + require.NotNil(t, gotGroup) + require.Equal(t, primaryGroup.ID, gotGroup.ID, + "preflight must read the authenticated billing group frozen before fallback overwrote ctxkey.Group") +} + +func TestPreviousResponseDBRecheck_ErrAccountNotFoundDeletesBindingInPool(t *testing.T) { + groupID := int64(9301) + poolCtx := WithCompositeCandidatePlatforms(context.Background(), []string{PlatformDeepseek, PlatformOpenAI}) + + staleSnapAcc := Account{ + ID: 9302, + Platform: PlatformOpenAI, + Type: AccountTypeAPIKey, + Status: StatusActive, + Schedulable: true, + Concurrency: 1, + GroupIDs: []int64{groupID}, + } + snapCache := &r7SnapshotCache{ + accountByID: map[int64]*Account{staleSnapAcc.ID: &staleSnapAcc}, + } + snapSvc := NewSchedulerSnapshotService(snapCache, nil, nil, nil, nil) + + cache := &stubGatewayCache{} + store := NewOpenAIWSStateStore(cache) + svc := &OpenAIGatewayService{ + // Repo returns ErrAccountNotFound (real PG behavior) while snapshot still holds staleSnapAcc. + accountRepo: r7NotFoundAccountRepo{}, + schedulerSnapshot: snapSvc, + cache: cache, + cfg: newOpenAIWSV2TestConfig(), + concurrencyService: NewConcurrencyService(stubConcurrencyCache{}), + openaiWSStateStore: store, + } + + require.NoError(t, store.BindResponseAccount(poolCtx, groupID, "resp_deleted_owner", staleSnapAcc.ID, time.Hour)) + selection, err := svc.SelectAccountByPreviousResponseID(poolCtx, &groupID, "resp_deleted_owner", "gpt-5.4", nil, false) + require.NoError(t, err) + require.Nil(t, selection) + require.False(t, svc.HasPreviousResponseBinding(poolCtx, &groupID, "resp_deleted_owner"), + "ErrAccountNotFound from DB recheck must clear previous_response_id binding even in composite pools") +} + +func TestCodexModelSupportsImageInput_OllamaCloud(t *testing.T) { + acc := Account{ + ID: 9401, + Platform: PlatformOllamaCloud, + Type: AccountTypeAPIKey, + Status: StatusActive, + Schedulable: true, + Credentials: map[string]any{ + "model_mapping": map[string]any{"gemma4:31b": "gemma4:31b"}, + }, + Extra: map[string]any{ + "image_input_models": []any{"gemma4:31b"}, + }, + } + require.True(t, accountCodexModelSupportsImageInput(&acc, "gemma4:31b")) + require.True(t, groupCodexModelSupportsImageInput(PlatformOllamaCloud, "gemma4:31b", []Account{acc}, nil, false)) + require.False(t, groupCodexModelSupportsImageInput(PlatformOllamaCloud, "gpt-oss:120b", []Account{acc}, nil, false)) +} + +func TestSelectAccountWithLoadAwareness_FallbackCompositeResolvesBeforeChannelRestriction(t *testing.T) { + primaryID := int64(9501) + fallbackID := int64(9502) + primaryGroup := &Group{ + ID: primaryID, + Platform: PlatformAnthropic, + Status: StatusActive, + Hydrated: true, + ClaudeCodeOnly: true, + FallbackGroupID: &fallbackID, + } + fallbackGroup := &Group{ + ID: fallbackID, + Platform: PlatformComposite, + Status: StatusActive, + Hydrated: true, + } + + dsAcc := Account{ + ID: 9503, + Platform: PlatformDeepseek, + Type: AccountTypeAPIKey, + Status: StatusActive, + Schedulable: true, + Concurrency: 2, + GroupIDs: []int64{fallbackID}, + Credentials: map[string]any{ + "api_key": "sk-ds", + "model_mapping": map[string]any{"shared-model": "deepseek-chat"}, + }, + } + + // Channel on fallbackGroup restricts models and has a restricted mapping on anthropic, + // while deepseek's shared-model is explicitly priced and allowed. + price := 1e-6 + ch := Channel{ + ID: 9510, + Status: StatusActive, + RestrictModels: true, + GroupIDs: []int64{fallbackID}, + ModelPricing: []ChannelModelPricing{{ + Platform: PlatformDeepseek, + Models: []string{"shared-model"}, + BillingMode: BillingModeToken, + InputPrice: &price, + OutputPrice: &price, + }}, + ModelMapping: map[string]map[string]string{ + PlatformAnthropic: {"shared-model": "unpriced-restricted-model"}, + }, + } + chSvc := &ChannelService{} + chSvc.cache.Store(populateChannelCache([]Channel{ch}, map[int64]string{fallbackID: PlatformComposite})) + + resolver := NewCompositeRouteResolver(nil) + resolver.SetModelOwnershipResolver(func(context.Context, int64, string) (CompositeModelOwnership, error) { + return CompositeModelOwnership{ + Matched: true, + TargetPlatform: PlatformDeepseek, + RequiredClaimStrength: CompositeClaimExplicit, + }, nil + }) + + groupRepo := &stubGroupRepoByID{groups: map[int64]*Group{ + primaryID: primaryGroup, + fallbackID: fallbackGroup, + }} + accRepo := &stubGatewayAccountRepo{accounts: []Account{dsAcc}} + cfg := &config.Config{RunMode: config.RunModeStandard} + svc := &GatewayService{ + cfg: cfg, + groupRepo: groupRepo, + accountRepo: accRepo, + channelService: chSvc, + compositeResolver: resolver, + } + + // Non-Claude-Code request on primaryID falls back to fallbackID (composite -> deepseek). + // Before the fix, checkChannelPricingRestriction ran before resolvePlatform with no target + // platform in ctx, matched the anthropic channel mapping, and falsely rejected the request. + ctx := context.WithValue(context.Background(), ctxkey.Group, primaryGroup) + sel, err := svc.SelectAccountWithLoadAwareness(ctx, &primaryID, "", "shared-model", nil, "", 0) + require.NoError(t, err) + require.NotNil(t, sel) + require.NotNil(t, sel.Account) + require.Equal(t, dsAcc.ID, sel.Account.ID) + require.NotNil(t, sel.EffectiveGroup) + require.Equal(t, fallbackID, sel.EffectiveGroup.ID) + gotPlatform, ok := ResolvedTargetPlatformFromContext(sel.SelectionCtx) + require.True(t, ok) + require.Equal(t, PlatformDeepseek, gotPlatform) +} + +type r7NotFoundAccountRepo struct { + AccountRepository +} + +func (r7NotFoundAccountRepo) GetByID(context.Context, int64) (*Account, error) { + return nil, ErrAccountNotFound +} + +type r7SnapshotCache struct { + SchedulerCache + accountByID map[int64]*Account +} + +func (c *r7SnapshotCache) GetAccount(_ context.Context, accountID int64) (*Account, error) { + if acc, ok := c.accountByID[accountID]; ok { + copied := *acc + return &copied, nil + } + return nil, nil +} + +type stubGroupRepoByID struct { + GroupRepository + groups map[int64]*Group +} + +func (r *stubGroupRepoByID) GetByID(_ context.Context, id int64) (*Group, error) { + if g, ok := r.groups[id]; ok { + return g, nil + } + return nil, ErrGroupNotFound +} + +func (r *stubGroupRepoByID) GetByIDLite(ctx context.Context, id int64) (*Group, error) { + return r.GetByID(ctx, id) +} + +type stubGatewayAccountRepo struct { + AccountRepository + accounts []Account +} + +func (r *stubGatewayAccountRepo) ListSchedulableByGroupIDAndPlatform(_ context.Context, _ int64, platform string) ([]Account, error) { + out := make([]Account, 0, len(r.accounts)) + for _, acc := range r.accounts { + if acc.Platform == platform { + out = append(out, acc) + } + } + return out, nil +} + +func (r *stubGatewayAccountRepo) ListSchedulableByGroupIDAndPlatforms(_ context.Context, _ int64, platforms []string) ([]Account, error) { + allow := make(map[string]struct{}, len(platforms)) + for _, p := range platforms { + allow[p] = struct{}{} + } + out := make([]Account, 0, len(r.accounts)) + for _, acc := range r.accounts { + if _, ok := allow[acc.Platform]; ok { + out = append(out, acc) + } + } + return out, nil +} diff --git a/backend/internal/service/gateway_scheduling.go b/backend/internal/service/gateway_scheduling.go index a8bda7551e..dc6a4aaf27 100644 --- a/backend/internal/service/gateway_scheduling.go +++ b/backend/internal/service/gateway_scheduling.go @@ -138,8 +138,18 @@ func (s *GatewayService) SelectAccountWithLoadAwareness(ctx context.Context, gro ctx = s.withGroupContext(ctx, group) ctx = s.withGatewayProfitControlGate(ctx, groupID) + ctx, platform, hasForcePlatform, err := s.resolvePlatform(ctx, groupID, group, requestedModel) + if err != nil { + return nil, err + } + if derefGroupID(groupID) != origGroupID { + if upstreamModel, ok := ResolvedUpstreamModelFromContext(ctx); ok && upstreamModel != "" { + requestedModel = upstreamModel + } + } + // Claude Code 限制可能已将 groupID 解析为 fallback group, - // 渠道限制预检查必须使用解析后的分组。 + // 渠道限制预检查必须在解析出目标平台/账号池与上游模型后执行。 if s.checkChannelPricingRestriction(ctx, groupID, requestedModel) { slog.Warn("channel pricing restriction blocked request", "group_id", derefGroupID(groupID), @@ -230,15 +240,6 @@ func (s *GatewayService) SelectAccountWithLoadAwareness(ctx context.Context, gro } } - ctx, platform, hasForcePlatform, err := s.resolvePlatform(ctx, groupID, group, requestedModel) - if err != nil { - return nil, err - } - if derefGroupID(groupID) != origGroupID { - if upstreamModel, ok := ResolvedUpstreamModelFromContext(ctx); ok && upstreamModel != "" { - requestedModel = upstreamModel - } - } ctx = s.withCompositePoolQuotaAutoPauseContext(ctx) preferOAuth := platform == PlatformGemini if s.debugModelRoutingEnabled() && requestedModel != "" && modelRoutingAppliesToTargetPlatform(platform) { @@ -2882,9 +2883,10 @@ func (s *GatewayService) isModelSupportedByAccount(account *Account, requestedMo _, ok := ResolveBedrockModelID(account, requestedModel) return ok } - // Passthrough ignores leftover mappings unless model filtering is enabled. + // Passthrough ignores leftover mappings unless model filtering is enabled, + // while still honoring OAuth servable-model / retirement guards inside IsModelSupported. if account.IsOpenAIPassthroughEnabled() && !account.IsOpenAIPassthroughModelFilterEnabled() { - return true + return account.IsModelSupported(requestedModel) } // OAuth/SetupToken 账号使用 Anthropic 标准映射(短ID → 长ID) if account.Platform == PlatformAnthropic && account.Type != AccountTypeAPIKey { diff --git a/backend/internal/service/gateway_usage_billing.go b/backend/internal/service/gateway_usage_billing.go index 146346bcd5..053a1db612 100644 --- a/backend/internal/service/gateway_usage_billing.go +++ b/backend/internal/service/gateway_usage_billing.go @@ -1172,6 +1172,7 @@ func channelModelPricingHasExplicitRate(chPricing *ChannelModelPricing) bool { // compositeAliasHasExplicitChannelPrice 判断公开别名是否具备针对该模型显式配置的渠道/分组定价 // (排除裸 "*" 全局通配卡片与无单价的纯倍率卡片,避免 "*" 卡片把别名误留作计费模型)。 +// 与 lookupChannelPricingNormalized 对齐:同时支持字面名、Codex 归一化名与剥 ":tag" 名。 func compositeAliasHasExplicitChannelPrice(resolved *ResolvedPricing, model string) bool { if resolved == nil || (resolved.Source != PricingSourceGroup && resolved.Source != PricingSourceChannel) { return false @@ -1180,17 +1181,38 @@ func compositeAliasHasExplicitChannelPrice(resolved *ResolvedPricing, model stri if !channelModelPricingHasExplicitRate(chPricing) { return false } - target := normalizeChannelPricingModelName(model) + targets := make([]string, 0, 3) + appendTarget := func(name string) { + normalized := normalizeChannelPricingModelName(name) + if normalized == "" { + return + } + for _, existing := range targets { + if existing == normalized { + return + } + } + targets = append(targets, normalized) + } + appendTarget(model) + if codexNorm := normalizeKnownOpenAICodexModel(model); codexNorm != "" { + appendTarget(codexNorm) + } + if stripped, ok := normalizePricingModelNameForLookup(model); ok { + appendTarget(stripped) + } for _, pattern := range chPricing.Models { p := normalizeChannelPricingModelName(pattern) if p == "" || p == "*" { continue } - if p == target { - return true - } - if strings.HasSuffix(p, "*") && strings.HasPrefix(target, strings.TrimSuffix(p, "*")) { - return true + for _, target := range targets { + if p == target { + return true + } + if strings.HasSuffix(p, "*") && strings.HasPrefix(target, strings.TrimSuffix(p, "*")) { + return true + } } } return false diff --git a/backend/internal/service/openai_codex_models_service.go b/backend/internal/service/openai_codex_models_service.go index 4d7ff94320..32ad286f63 100644 --- a/backend/internal/service/openai_codex_models_service.go +++ b/backend/internal/service/openai_codex_models_service.go @@ -1208,7 +1208,7 @@ func groupCodexModelSupportsImageInput( } } switch platform { - case PlatformOpenAI, PlatformGrok, PlatformDeepseek, PlatformOpenCodeGo, PlatformCommandCode: + case PlatformOpenAI, PlatformGrok, PlatformDeepseek, PlatformOpenCodeGo, PlatformCommandCode, PlatformOllamaCloud: default: return false } @@ -1371,7 +1371,7 @@ func accountCodexModelSupportsImageInput(account *Account, upstreamModel string) return false } switch account.Platform { - case PlatformOpenAI, PlatformDeepseek, PlatformOpenCodeGo, PlatformCommandCode: + case PlatformOpenAI, PlatformDeepseek, PlatformOpenCodeGo, PlatformCommandCode, PlatformOllamaCloud: if accountDeclaresImageInputModel(account, upstreamModel) { return true } 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 7bbafb97dd..8e1a3e8dbf 100644 --- a/backend/internal/service/openai_gateway_ollama_cloud_pricing_preflight.go +++ b/backend/internal/service/openai_gateway_ollama_cloud_pricing_preflight.go @@ -143,14 +143,17 @@ func writeServiceLocalInvalidRequestResponse(c *gin.Context, message string) { c.JSON(http.StatusBadRequest, payload) } -// ollamaCloudBillingGroupFromContext 取认证中间件放入 ctx 的计费分组(与利润门 D -// 同一口径:计费永远按 apiKey 自身分组),用于分组/渠道定价查找。ctx 无有效分组 -// (内部调用、直接构造 service 的单测)时返回 nil——等价于计费在无分组输入下的 -// 解析行为,不会让预检更严格。 +// ollamaCloudBillingGroupFromContext 取认证时刻的计费分组(与利润门 D 同一口径: +// 即使 ClaudeCodeOnly 降级切组覆盖了 ctxkey.Group,计费永远按 apiKey 自身分组), +// 用于分组/渠道定价查找。ctx 无有效分组(内部调用、直接构造 service 的单测)时返回 +// nil——等价于计费在无分组输入下的解析行为,不会让预检更严格。 func ollamaCloudBillingGroupFromContext(ctx context.Context) *Group { if ctx == nil { return nil } + if billingGroup := gatewayTokenRequestBillingGroupFromContext(ctx); billingGroup != nil { + return billingGroup + } group, _ := ctx.Value(ctxkey.Group).(*Group) if IsGroupContextValid(group) { return group @@ -185,9 +188,10 @@ func ollamaCloudModelUnpricedForBilling(ctx context.Context, resolver *ModelPric return true } // 与 RecordUsage 的 dropUnpricedClaudeBillingCandidates 对齐:ollama_cloud 上游不按全局 - // Claude 价卡对 claude-* 出站名计费,仅显式配置分组/渠道定价时放行。 + // Claude 价卡对 claude-* 出站名计费,仅针对该模型显式配置分组/渠道单价卡时放行 + // (排除裸 "*" 通配卡与纯倍率卡,保证预检与通用链/OpenAI 链计费口径完全一致)。 if strings.Contains(strings.ToLower(strings.TrimSpace(model)), "claude") && - resolved.Source != PricingSourceGroup && resolved.Source != PricingSourceChannel { + !compositeAliasHasExplicitChannelPrice(resolved, model) { return true } // 与 CalculateCostUnified 的模式分发一致:按次/图片/视频模式由 diff --git a/backend/internal/service/openai_gateway_usage.go b/backend/internal/service/openai_gateway_usage.go index fb5c386445..fe42bfafb8 100644 --- a/backend/internal/service/openai_gateway_usage.go +++ b/backend/internal/service/openai_gateway_usage.go @@ -1071,7 +1071,7 @@ func (s *OpenAIGatewayService) filterCNProviderBillingModelCandidates(ctx contex return candidates } return dropUnpricedClaudeBillingCandidates(candidates, func(model string) bool { - return s.resolveOpenAIChannelPricing(ctx, model, apiKey) != nil + return compositeAliasHasExplicitChannelPrice(s.resolveOpenAIChannelPricing(ctx, model, apiKey), model) }) } diff --git a/backend/internal/service/openai_ws_forwarder_support.go b/backend/internal/service/openai_ws_forwarder_support.go index b5e9229a0a..b1e2798496 100644 --- a/backend/internal/service/openai_ws_forwarder_support.go +++ b/backend/internal/service/openai_ws_forwarder_support.go @@ -632,6 +632,10 @@ func (s *OpenAIGatewayService) resolveAccountByPreviousResponseIDForCapability( } if s.schedulerSnapshot != nil && s.accountRepo != nil { latest, latestErr := s.accountRepo.GetByID(ctx, account.ID) + if errors.Is(latestErr, ErrAccountNotFound) { + _ = store.DeleteResponseAccount(ctx, derefGroupID(groupID), responseID) + return 0, nil, "", nil + } if latestErr != nil { dropTransient() return 0, nil, "", nil From 76981e526b5b013f2bbd367506442428aee91309 Mon Sep 17 00:00:00 2001 From: shaw Date: Sat, 5 Dec 2026 19:31:47 +0800 Subject: [PATCH 81/81] =?UTF-8?q?fix(repository):=20=E5=AF=B9=E9=BD=90=20E?= =?UTF-8?q?rrTxStarted=20=E5=88=86=E6=94=AF=E8=B0=83=E5=BA=A6=E5=BF=AB?= =?UTF-8?q?=E7=85=A7=E5=90=8C=E6=AD=A5=EF=BC=88=E5=85=BC=E5=AE=B9=20testEn?= =?UTF-8?q?tTx=20=E5=A4=B9=E5=85=B7=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../internal/repository/account_repo_ollama_cloud_usage.go | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/backend/internal/repository/account_repo_ollama_cloud_usage.go b/backend/internal/repository/account_repo_ollama_cloud_usage.go index 5c741ffd25..1523e63ad1 100644 --- a/backend/internal/repository/account_repo_ollama_cloud_usage.go +++ b/backend/internal/repository/account_repo_ollama_cloud_usage.go @@ -298,8 +298,9 @@ func (r *accountRepository) updateOllamaCloudUsageGroup( if err := apply(ctx, r.client); err != nil { return err } - // 外层事务尚未提交且未把 tx 放进 ctx:outbox 已在事务内落库, - // 不能提前把未提交行刷进 Redis 快照,交由 outbox 在外层提交后异步同步。 + // 对齐 account_repo.go:516(contextTx == nil 时立即刷快照,兼容 testEntTx 集成测试夹具; + // 生产嵌套事务均经 dbent.TxFromContext 走上方 AfterAccountCommit 分支)。 + r.syncSchedulerAccountSnapshots(ctx, syncedMemberIDs) return nil } if err != nil {