From 528ec6ae455a80f5282cd82bf4e8a67d78e0b866 Mon Sep 17 00:00:00 2001 From: alfadb Date: Sat, 12 Sep 2026 14:04:04 +0800 Subject: [PATCH] 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 | 150 ++- .../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 | 116 +- .../internal/service/openai_gateway_usage.go | 6 + .../service/openai_ws_forwarder_support.go | 30 +- .../internal/service/ops_upstream_context.go | 55 + 40 files changed, 6656 insertions(+), 230 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 c1bde61d63..ca3e124fad 100644 --- a/backend/internal/handler/endpoint.go +++ b/backend/internal/handler/endpoint.go @@ -311,11 +311,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 147f4460a8..e708cc56de 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 { @@ -161,13 +167,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, @@ -220,6 +232,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 { // 利润终检否决:排除该账号重新选号;否决次数达上限则按无可用账号终止。 @@ -236,9 +293,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) { @@ -247,13 +309,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) @@ -276,7 +344,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) { @@ -293,7 +366,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 600d2c7372..2aa8acc199 100644 --- a/backend/internal/handler/openai_gateway_handler.go +++ b/backend/internal/handler/openai_gateway_handler.go @@ -205,6 +205,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)) } @@ -315,6 +325,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 } @@ -560,6 +584,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) @@ -641,6 +672,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 @@ -651,7 +688,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, @@ -715,7 +752,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. @@ -742,6 +794,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 { // 利润终检否决:排除该账号重新选号,全池耗尽由下一轮选号报错; @@ -765,20 +868,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 @@ -801,7 +916,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) { @@ -819,7 +939,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, @@ -1211,6 +1331,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 错误场景复用规则。 @@ -1262,6 +1388,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 @@ -1272,7 +1404,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, @@ -1326,6 +1458,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 { // 利润终检否决:排除该账号重新选号,全池耗尽由下一轮选号报错; @@ -1344,8 +1506,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() { @@ -1353,13 +1516,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 @@ -1383,7 +1552,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) { @@ -1401,7 +1575,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 ea58e3af25..4f72607861 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 bd6e5e7ebe..0b0d1b9505 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) }) // /v1/messages/count_tokens: OpenAI bridges upstream, Grok estimates // locally, and Anthropic-compatible platforms retain their existing path. @@ -216,18 +195,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) { @@ -235,11 +206,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) { @@ -357,11 +324,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 // 之前,避免逐条路由手工维护链导致漏挂。 @@ -392,11 +355,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) { @@ -539,6 +498,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) @@ -579,13 +668,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 6ddb9cfa9a..64384abb47 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) @@ -192,6 +254,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 20505a3985..4d7da09ff6 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 f2e1928ace..e2129c63b3 100644 --- a/backend/internal/service/composite_route_resolver.go +++ b/backend/internal/service/composite_route_resolver.go @@ -66,7 +66,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 32d38cf40d..06045a5740 100644 --- a/backend/internal/service/gateway_forward_as_chat_completions.go +++ b/backend/internal/service/gateway_forward_as_chat_completions.go @@ -155,6 +155,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 8855b13e52..13a8308529 100644 --- a/backend/internal/service/gateway_hotpath_optimization_test.go +++ b/backend/internal/service/gateway_hotpath_optimization_test.go @@ -179,6 +179,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 { @@ -564,9 +573,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: {{ @@ -587,21 +598,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 f5dd160c79..24586d7abe 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 97e35fdb1b..37832473c9 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) } @@ -1463,59 +1458,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) != "" -} - // GetSchedulablePlatforms returns the concrete platforms that currently have // schedulable accounts in the target group. func (s *GatewayService) GetSchedulablePlatforms(ctx context.Context, groupID *int64) map[string]struct{} { @@ -1548,7 +1566,6 @@ func (s *GatewayService) InvalidateAvailableModelsCache(groupID *int64, platform if s == nil || s.modelsListCache == nil { return } - s.invalidateCompositeModelOwnershipCache(groupID) normalizedPlatform := strings.TrimSpace(platform) // 完整匹配时精准失效;否则按维度批量失效。 @@ -1577,26 +1594,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 4d8e74c162..25588864c2 100644 --- a/backend/internal/service/gateway_upstream_request.go +++ b/backend/internal/service/gateway_upstream_request.go @@ -215,6 +215,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 } @@ -340,6 +346,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 5ad63d30f8..f47407dad7 100644 --- a/backend/internal/service/openai_account_scheduler.go +++ b/backend/internal/service/openai_account_scheduler.go @@ -375,6 +375,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, @@ -389,46 +444,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 { @@ -524,7 +545,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 } @@ -1282,6 +1309,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 } @@ -1449,7 +1481,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 } @@ -1775,6 +1807,11 @@ func (s *defaultOpenAIAccountScheduler) isAccountRequestCompatibleReason(ctx con 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" } @@ -1803,7 +1840,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 && @@ -2282,6 +2319,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_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 cbc5de9d28..6b9300fa59 100644 --- a/backend/internal/service/openai_gateway_messages.go +++ b/backend/internal/service/openai_gateway_messages.go @@ -389,6 +389,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 263eceba04..d863d6d484 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 928e3fa982..a7aad11948 100644 --- a/backend/internal/service/openai_gateway_messages_chat_fallback.go +++ b/backend/internal/service/openai_gateway_messages_chat_fallback.go @@ -113,6 +113,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 2ee6bea077..393a63a25d 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,7 +455,7 @@ func openAICompatibleAccountEligibilityFailureReasonBeforeProfit(ctx context.Con if account == nil { return "account_nil" } - if account.Platform != platform || !account.IsOpenAICompatible() { + if !account.IsOpenAICompatible() || !openAISchedulingPlatformMatchesAccount(ctx, account, platform) { return "platform_mismatch" } if !account.IsSchedulableForModelWithContext(ctx, requestedModel) { @@ -431,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) { @@ -951,6 +1014,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 @@ -1183,7 +1251,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) @@ -1470,7 +1540,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 6ae03bb5a2..cb0802b95f 100644 --- a/backend/internal/service/openai_gateway_usage.go +++ b/backend/internal/service/openai_gateway_usage.go @@ -494,9 +494,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 := func() error { 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