diff --git a/backend/internal/handler/composite_pool_attempt_policy.go b/backend/internal/handler/composite_pool_attempt_policy.go index 290489e1d5..dc996f6dba 100644 --- a/backend/internal/handler/composite_pool_attempt_policy.go +++ b/backend/internal/handler/composite_pool_attempt_policy.go @@ -138,12 +138,19 @@ type compositePoolAttemptPolicyFailure struct { // ChannelRestricted 表示该模型在选中平台作用域下被渠道定价限制拒绝,按调度 // 阶段渠道限制同语义终止(账号存在且模型受支持,仅当前平台被限制)。 ChannelRestricted bool + // AccountChannelRestricted 表示限制仅来自当前账号映射后的 upstream 模型, + // 重选时只排除该账号,不整平台屏蔽同平台其它账号。 + AccountChannelRestricted bool } func (f compositePoolAttemptPolicyFailure) denied() bool { return f.QuotaErr != nil || f.ChannelRestricted } +func (f compositePoolAttemptPolicyFailure) deniesPlatform() bool { + return f.QuotaErr != nil || (f.ChannelRestricted && !f.AccountChannelRestricted) +} + // compositePoolAttemptPolicy 汇总一次 attempt 的策略检查结果。 type compositePoolAttemptPolicy struct { // AttemptCtx 仅供该 attempt 的渠道/计费/forward 使用;不写回 c.Request。 @@ -187,7 +194,9 @@ func evaluateCompositePoolAttemptPolicy( } if gateway != nil && apiKey != nil && apiKey.GroupID != nil { result.Mapping = gateway.CompositePoolAttemptChannelMapping(result.AttemptCtx, apiKey.GroupID, requestedModel) - result.Failure.ChannelRestricted = gateway.CompositePoolAttemptChannelRestricted(result.AttemptCtx, apiKey.GroupID, account, requestedModel, requireCompact) + platformRestricted, accountRestricted := gateway.CompositePoolAttemptChannelRestriction(result.AttemptCtx, apiKey.GroupID, account, requestedModel, requireCompact) + result.Failure.ChannelRestricted = platformRestricted || accountRestricted + result.Failure.AccountChannelRestricted = accountRestricted && !platformRestricted } return result } diff --git a/backend/internal/handler/gateway_handler.go b/backend/internal/handler/gateway_handler.go index 535d346caf..63fbcfa396 100644 --- a/backend/internal/handler/gateway_handler.go +++ b/backend/internal/handler/gateway_handler.go @@ -789,15 +789,17 @@ func (h *GatewayHandler) Messages(c *gin.Context) { // 候选全部被业务限制时按原语义终止,不误报 model unsupported。 attemptPolicy := compositePoolAttemptPolicy{AttemptCtx: c.Request.Context(), Mapping: channelMapping} isPoolAttempt := false - if isPoolRequest && compositePoolAttemptPolicyApplies(c, apiKey) { + if isPoolRequest && compositePoolAttemptPolicyApplies(c, currentAPIKey) { attemptPolicy = evaluateCompositePoolAttemptPolicy( - c.Request.Context(), h.billingCacheService, h.openAIGatewayService, apiKey, subscription, account, reqModel, false) + c.Request.Context(), h.billingCacheService, h.openAIGatewayService, currentAPIKey, currentSubscription, account, reqModel, false) isPoolAttempt = true if attemptPolicy.Failure.denied() { releaseCompositePoolSelection(selection) // 选号链可能已为该账号注册会话槽:排除前释放,镜像 profit-veto 分支。 h.gatewayService.ReleaseAccountSession(context.Background(), account, sessionKey) - poolDenials.deny(account.Platform) + if attemptPolicy.Failure.deniesPlatform() { + poolDenials.deny(account.Platform) + } fs.FailedAccountIDs[account.ID] = struct{}{} // 候选全部被业务限制:按 deny 原因明确终止(后续重选不再尝试)。 if _, ok := compositePoolSelectionRetryContext(c.Request.Context(), poolDenials); !ok { @@ -815,7 +817,7 @@ func (h *GatewayHandler) Messages(c *gin.Context) { streamAwareWrite := func(cc *gin.Context, status int, code, message string) { h.handleStreamingAwareError(cc, status, code, message, streamStarted) } - cappedBody, changed, policyErr := applyCompositePoolAnthropicReasoningEffortPolicy(apiKey, account, attemptParsedReq.Body.Bytes()) + cappedBody, changed, policyErr := applyCompositePoolAnthropicReasoningEffortPolicy(currentAPIKey, account, attemptParsedReq.Body.Bytes()) if policyErr != nil { releaseCompositePoolSelection(selection) h.gatewayService.ReleaseAccountSession(context.Background(), account, sessionKey) @@ -1203,11 +1205,13 @@ func (h *GatewayHandler) Messages(c *gin.Context) { h.handleStreamingAwareError(c, status, code, message, streamStarted) return } - // 兜底重试按"直接请求兜底分组"处理:清除强制平台,允许按分组平台调度 - ctx := context.WithValue(c.Request.Context(), ctxkey.ForcePlatform, "") + // 兜底重试按"直接请求兜底分组"处理:清除强制平台与原分组的 composite 路由/池上下文,允许按兜底分组调度 + ctx := service.WithoutCompositeRouteContext(context.WithValue(c.Request.Context(), ctxkey.ForcePlatform, "")) c.Request = c.Request.WithContext(ctx) currentAPIKey = fallbackAPIKey currentSubscription = nil + isPoolRequest = false + poolDenials = newCompositePoolPlatformDenials() fallbackUsed = true retryWithFallback = true // 原分组账号已确定性失败(prompt too long),先释放其会话注册再走兜底分组 diff --git a/backend/internal/handler/gateway_handler_chat_completions.go b/backend/internal/handler/gateway_handler_chat_completions.go index 803616d583..f11d0e9943 100644 --- a/backend/internal/handler/gateway_handler_chat_completions.go +++ b/backend/internal/handler/gateway_handler_chat_completions.go @@ -283,7 +283,9 @@ func (h *GatewayHandler) ChatCompletions(c *gin.Context) { // 选号链可能已为该账号注册会话槽(键与选号一致):排除前释放 //(镜像 Messages 池分支)。 h.gatewayService.ReleaseAccountSession(context.Background(), account, selectionSessionHash) - poolDenials.deny(account.Platform) + if attemptPolicy.Failure.deniesPlatform() { + poolDenials.deny(account.Platform) + } fs.FailedAccountIDs[account.ID] = struct{}{} // 候选全部被业务限制:按 deny 原因明确终止(后续重选不再尝试)。 if _, ok := compositePoolSelectionRetryContext(c.Request.Context(), poolDenials); !ok { diff --git a/backend/internal/handler/gateway_handler_responses.go b/backend/internal/handler/gateway_handler_responses.go index 47f2841d23..4995af3cff 100644 --- a/backend/internal/handler/gateway_handler_responses.go +++ b/backend/internal/handler/gateway_handler_responses.go @@ -316,7 +316,9 @@ func (h *GatewayHandler) Responses(c *gin.Context) { releaseCompositePoolSelection(selection) // 选号链可能已为该账号注册会话槽:排除前释放(镜像 Messages 池分支)。 h.gatewayService.ReleaseAccountSession(context.Background(), account, sessionHash) - poolDenials.deny(account.Platform) + if attemptPolicy.Failure.deniesPlatform() { + poolDenials.deny(account.Platform) + } fs.FailedAccountIDs[account.ID] = struct{}{} // 候选全部被业务限制:按 deny 原因明确终止(后续重选不再尝试)。 if _, ok := compositePoolSelectionRetryContext(requestCtx, poolDenials); !ok { diff --git a/backend/internal/handler/openai_chat_completions.go b/backend/internal/handler/openai_chat_completions.go index a06f9fd996..794ea77feb 100644 --- a/backend/internal/handler/openai_chat_completions.go +++ b/backend/internal/handler/openai_chat_completions.go @@ -279,7 +279,9 @@ func (h *OpenAIGatewayHandler) ChatCompletions(c *gin.Context) { streamAwareWrite := func(cc *gin.Context, status int, code, message string) { h.handleStreamingAwareError(cc, status, code, message, streamStarted) } - poolDenials.deny(account.Platform) + if attemptPolicy.Failure.deniesPlatform() { + poolDenials.deny(account.Platform) + } // 同时排除该账号:下一轮 masked ctx 下 sticky 层对 excluded 账号 // 提前返回(不 clear),不会把原 sticky 账号当 platform mismatch // 清掉粘性绑定;其它平台成功后按用户目标正常改绑。 diff --git a/backend/internal/handler/openai_gateway_handler.go b/backend/internal/handler/openai_gateway_handler.go index 32c196366f..900bbea1b9 100644 --- a/backend/internal/handler/openai_gateway_handler.go +++ b/backend/internal/handler/openai_gateway_handler.go @@ -927,7 +927,9 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) { respondCompositePoolAttemptPolicyFailure(c, attemptPolicy.Failure, streamAwareWrite) return } - poolDenials.deny(account.Platform) + if attemptPolicy.Failure.deniesPlatform() { + poolDenials.deny(account.Platform) + } // 同时排除该账号:下一轮 masked ctx 下 sticky 层对 excluded 账号 // 提前返回(不 clear),不会把原 sticky 账号当 platform mismatch // 清掉粘性绑定;其它平台成功后按用户目标正常改绑。 @@ -1591,7 +1593,9 @@ func (h *OpenAIGatewayHandler) Messages(c *gin.Context) { isPoolAttemptMsg = true if attemptPolicyMsg.Failure.denied() { releaseCompositePoolSelection(selection) - poolDenials.deny(account.Platform) + if attemptPolicyMsg.Failure.deniesPlatform() { + poolDenials.deny(account.Platform) + } // 同时排除该账号:下一轮 masked ctx 下 sticky 层对 excluded 账号 // 提前返回(不 clear),不清掉原 sticky 粘性绑定。 failedAccountIDs[account.ID] = struct{}{} diff --git a/backend/internal/server/routes/gateway_composite_pool_attempt_policy_test.go b/backend/internal/server/routes/gateway_composite_pool_attempt_policy_test.go index 71c7cdc031..fe1c05943e 100644 --- a/backend/internal/server/routes/gateway_composite_pool_attempt_policy_test.go +++ b/backend/internal/server/routes/gateway_composite_pool_attempt_policy_test.go @@ -822,3 +822,56 @@ func TestCompositePoolAttemptPolicyDenyWithSiblingAccountsKeepsBinding(t *testin "after a successful take-over the sticky binding is updated normally via Set") } } + +// ── 8) BillingModelSource=upstream 逐账号限制只排除受限账号,不屏蔽同平台合法兄弟号 ─ +func TestCompositePoolAttemptPolicyUpstreamRestrictionDoesNotMaskSiblingAccount(t *testing.T) { + now := time.Now().UTC() + quotaCache := &attemptPolicyQuotaCache{entries: map[string]*service.UserPlatformQuotaCacheEntry{ + service.PlatformDeepseek: allowedAttemptPolicyEntry(now), + service.PlatformOpenAI: allowedAttemptPolicyEntry(now), + }} + upstream := &attemptPolicyUpstream{} + channel := &service.Channel{ + ID: 1, + Status: service.StatusActive, + GroupIDs: []int64{attemptPolicyGroupID}, + RestrictModels: true, + BillingModelSource: service.BillingModelSourceUpstream, + ModelMapping: map[string]map[string]string{ + service.PlatformAnthropic: {"deepseek-flash": "unlisted-claude"}, + service.PlatformDeepseek: {"deepseek-flash": "deepseek-mid"}, + }, + ModelPricing: []service.ChannelModelPricing{ + {Platform: service.PlatformDeepseek, Models: []string{"deepseek-allowed"}}, + }, + } + // 4341(deepseek priority 1):映射为受限的 deepseek-blocked; + // 4342(deepseek priority 2):经渠道映射 deepseek-mid → deepseek-allowed(合法); + // 4343(openai priority 3):映射为受限的 gpt-blocked(用于凑成双平台池)。 + router := newCompositePoolAttemptPolicyRouter(t, attemptPolicyRouterInput{ + accounts: []service.Account{ + newAttemptPolicyAccount(4341, service.PlatformDeepseek, 1, map[string]any{ + "deepseek-flash": "deepseek-blocked", + "deepseek-mid": "deepseek-blocked", + }), + newAttemptPolicyAccount(4342, service.PlatformDeepseek, 2, map[string]any{ + "deepseek-flash": "deepseek-allowed", + "deepseek-mid": "deepseek-allowed", + }), + newAttemptPolicyAccount(4343, service.PlatformOpenAI, 3, map[string]any{ + "deepseek-flash": "gpt-blocked", + }), + }, + quotaCache: quotaCache, + upstream: upstream, + channel: channel, + }) + + w := postAttemptPolicyRequest(t, router, "/v1/chat/completions", + `{"model":"deepseek-flash","messages":[{"role":"user","content":"hi"}],"stream":false}`) + require.Equal(t, http.StatusOK, w.Code, w.Body.String()) + captured := upstream.snapshot() + require.Len(t, captured, 1) + require.Contains(t, captured[0].host, "deepseek-pool-fake.test") + require.Equal(t, "deepseek-allowed", gjson.GetBytes(captured[0].body, "model").String()) +} diff --git a/backend/internal/service/billing_inflight_reservation.go b/backend/internal/service/billing_inflight_reservation.go index fcda8e3c6a..d2b43ca566 100644 --- a/backend/internal/service/billing_inflight_reservation.go +++ b/backend/internal/service/billing_inflight_reservation.go @@ -404,8 +404,8 @@ type inflightEstimateDeps struct { type inflightSnapshotLister func(ctx context.Context, groupID *int64, platform string, hasForcePlatform bool) ([]Account, error) // inflightAccountMappedModelsFromSnapshot 基于调度器快照在内存中匹配账号级映射(支持通配规则)。 -// resolvePlatform 返回与调度器一致的平台;无分组 API Key 使用调度器的未分组账号池(groupID=nil)。 -func inflightAccountMappedModelsFromSnapshot(list inflightSnapshotLister, resolvePlatform func(ctx context.Context, apiKey *APIKey, model string) (string, bool, bool)) func(ctx context.Context, apiKey *APIKey, model string) []string { +// resolvePlatform 返回可能携带 composite 池决策的 ctx 及目标平台;无分组 API Key 使用调度器的未分组账号池(groupID=nil)。 +func inflightAccountMappedModelsFromSnapshot(list inflightSnapshotLister, resolvePlatform func(ctx context.Context, apiKey *APIKey, model string) (context.Context, string, bool, bool)) func(ctx context.Context, apiKey *APIKey, model string) []string { if list == nil || resolvePlatform == nil { return nil } @@ -414,11 +414,11 @@ func inflightAccountMappedModelsFromSnapshot(list inflightSnapshotLister, resolv if apiKey == nil || model == "" { return nil } - platform, forced, ok := resolvePlatform(ctx, apiKey, model) + resolvedCtx, platform, forced, ok := resolvePlatform(ctx, apiKey, model) if !ok || platform == "" { return nil } - accounts, err := list(ctx, apiKey.GroupID, platform, forced) + accounts, err := list(resolvedCtx, apiKey.GroupID, platform, forced) if err != nil { return nil } @@ -721,15 +721,15 @@ func (s *GatewayService) inflightEstimateDeps() inflightEstimateDeps { snap := s.schedulerSnapshot d.accountMappedModels = inflightAccountMappedModelsFromSnapshot( func(ctx context.Context, groupID *int64, platform string, forced bool) ([]Account, error) { + if GenericCompositePoolActive(ctx) { + return s.listSchedulableAccountsForCompositePool(ctx, groupID, CompositeCandidatePlatformsFromContext(ctx)) + } accounts, _, err := snap.ListSchedulableAccounts(ctx, groupID, platform, forced) return accounts, err }, - func(ctx context.Context, apiKey *APIKey, model string) (string, bool, bool) { - // 本分支 resolvePlatform 返回携带 composite 池决策的 ctx;该快照闭包 - // 无法透传 ctx(上游接口只收 platform/forced),池决策场景下账号级 - // 映射估算退化为走兜底路径,行为安全。 - _, platform, forced, err := s.resolvePlatform(ctx, apiKey.GroupID, apiKey.Group, model) - return platform, forced, err == nil + func(ctx context.Context, apiKey *APIKey, model string) (context.Context, string, bool, bool) { + resolvedCtx, platform, forced, err := s.resolvePlatform(ctx, apiKey.GroupID, apiKey.Group, model) + return resolvedCtx, platform, forced, err == nil }, ) } @@ -755,15 +755,24 @@ func (s *OpenAIGatewayService) inflightEstimateDeps() inflightEstimateDeps { snap := s.schedulerSnapshot d.accountMappedModels = inflightAccountMappedModelsFromSnapshot( func(ctx context.Context, groupID *int64, platform string, forced bool) ([]Account, error) { + if openAICompositePoolActive(ctx) { + return s.listSchedulableAccountsForCompositePool(ctx, groupID, CompositeCandidatePlatformsFromContext(ctx)) + } accounts, _, err := snap.ListSchedulableAccounts(ctx, groupID, platform, forced) return accounts, err }, - func(ctx context.Context, apiKey *APIKey, model string) (string, bool, bool) { + func(ctx context.Context, apiKey *APIKey, model string) (context.Context, string, bool, bool) { platform := PlatformOpenAI - if apiKey.Group != nil && apiKey.Group.Platform != "" && apiKey.Group.Platform != PlatformComposite { - platform = apiKey.Group.Platform + if apiKey.Group != nil && apiKey.Group.Platform != "" { + if apiKey.Group.Platform == PlatformComposite { + if resolved, ok := ResolvedTargetPlatformFromContext(ctx); ok { + platform = resolved + } + } else { + platform = apiKey.Group.Platform + } } - return NormalizeOpenAICompatiblePlatform(platform), false, true + return ctx, NormalizeOpenAICompatiblePlatform(platform), false, true }, ) } diff --git a/backend/internal/service/composite_platform.go b/backend/internal/service/composite_platform.go index b1370357d8..7329aa69b3 100644 --- a/backend/internal/service/composite_platform.go +++ b/backend/internal/service/composite_platform.go @@ -120,6 +120,22 @@ func withCompositeRequiredClaimStrength(ctx context.Context, strength CompositeC return context.WithValue(ctx, ctxkey.CompositeRequiredClaimStrength, strength) } +// WithoutCompositeRouteContext 清除请求切换到兜底/降级分组前残留的原分组 composite +// 路由与候选池上下文,避免非 composite 兜底分组误继承原分组的候选池或目标平台。 +func WithoutCompositeRouteContext(ctx context.Context) context.Context { + if ctx == nil { + return nil + } + ctx = context.WithValue(ctx, ctxkey.ResolvedTargetPlatform, "") + ctx = context.WithValue(ctx, ctxkey.ResolvedUpstreamModel, "") + ctx = context.WithValue(ctx, ctxkey.RequestedPublicModel, "") + ctx = context.WithValue(ctx, ctxkey.CompositeRouteSource, "") + ctx = context.WithValue(ctx, ctxkey.CompositeRequiredClaimStrength, CompositeClaimNone) + ctx = context.WithValue(ctx, ctxkey.CompositeCandidatePlatforms, ([]string)(nil)) + ctx = context.WithValue(ctx, compositePoolDeniedPlatformsKey{}, ([]string)(nil)) + return ctx +} + // RewriteCompositeRequestModel puts a composite route's upstream model into the // request body at modelPath. The client chose its thinking mode for the model // it asked for, so a mode the upstream model rejects becomes the nearest mode diff --git a/backend/internal/service/composite_pool_policy.go b/backend/internal/service/composite_pool_policy.go index 076dcbe8ce..e5117c2bd5 100644 --- a/backend/internal/service/composite_pool_policy.go +++ b/backend/internal/service/composite_pool_policy.go @@ -65,22 +65,60 @@ func compositePoolPlatformDenied(ctx context.Context, platform string) bool { return false } +// checkCompositePoolChannelPricingRestriction 在账号池选号前按实际候选平台判断请求是否 +// 被整池渠道限制:仅当全部未被策略 deny 的候选平台都限制该模型时才在调度入口拦截, +// 避免非池内平台的渠道映射行跨平台误杀池请求。 +func checkCompositePoolChannelPricingRestriction(ctx context.Context, restrictedOn func(context.Context) bool) bool { + checked := 0 + for _, platform := range CompositeCandidatePlatformsFromContext(ctx) { + if compositePoolPlatformDenied(ctx, platform) { + continue + } + checked++ + if !restrictedOn(WithResolvedTargetPlatform(ctx, platform)) { + return false + } + } + return checked > 0 +} + +// CompositePoolAttemptChannelRestriction 报告选中账号平台作用域下该模型是否被渠道定价限制拒绝, +// 并区分平台级限制(requested / channel_mapped / response)与逐账号限制(upstream): +// 后者仅代表当前账号映射后的上游模型受限,不得将同平台其它合法账号整平台屏蔽。 +func (s *OpenAIGatewayService) CompositePoolAttemptChannelRestriction(ctx context.Context, groupID *int64, account *Account, requestedModel string, requireCompact bool) (platformRestricted bool, accountRestricted bool) { + if s == nil || groupID == nil || account == nil || requestedModel == "" { + return false, false + } + if s.checkChannelPricingRestriction(ctx, groupID, requestedModel) { + return true, false + } + if s.needsUpstreamChannelRestrictionCheck(ctx, groupID) { + effectiveModel := requestedModel + if s.channelService != nil { + if mapping := s.channelService.ResolveChannelMapping(ctx, *groupID, requestedModel); mapping.Mapped { + effectiveModel = mapping.MappedModel + } + } + var upstreamModel string + if account.Platform == PlatformAntigravity { + upstreamModel = mapAntigravityModel(account, effectiveModel) + } else { + upstreamModel = resolveOpenAIAccountUpstreamModelForRequest(account, effectiveModel, requireCompact) + } + if upstreamModel != "" && s.channelService != nil && s.channelService.IsModelRestricted(ctx, *groupID, upstreamModel) { + return false, true + } + } + return false, false +} + // CompositePoolAttemptChannelRestricted 报告选中账号平台作用域下该模型是否被 // 渠道定价限制拒绝。ctx 必须是带 ResolvedTargetPlatform=account.Platform 的 // attempt 局部 ctx。语义与调度阶段逐候选检查一致(checkChannelPricingRestriction // + upstream 计费基准的逐账号检查),不重复检查用户配额或 RPM。 func (s *OpenAIGatewayService) CompositePoolAttemptChannelRestricted(ctx context.Context, groupID *int64, account *Account, requestedModel string, requireCompact bool) bool { - if s == nil || groupID == nil || account == nil || requestedModel == "" { - return false - } - if s.checkChannelPricingRestriction(ctx, groupID, requestedModel) { - return true - } - if s.needsUpstreamChannelRestrictionCheck(ctx, groupID) && - s.isUpstreamModelRestrictedByChannel(ctx, *groupID, account, requestedModel, requireCompact) { - return true - } - return false + platformRestricted, accountRestricted := s.CompositePoolAttemptChannelRestriction(ctx, groupID, account, requestedModel, requireCompact) + return platformRestricted || accountRestricted } // CompositePoolAttemptChannelMapping 返回选中账号平台作用域的渠道级模型映射。 diff --git a/backend/internal/service/gateway_forward.go b/backend/internal/service/gateway_forward.go index 71d30e7508..c1b5e2bdb2 100644 --- a/backend/internal/service/gateway_forward.go +++ b/backend/internal/service/gateway_forward.go @@ -999,6 +999,11 @@ func (s *GatewayService) checkChannelPricingRestriction(ctx context.Context, gro if groupID == nil || s.channelService == nil || requestedModel == "" { return false } + if GenericCompositePoolActive(ctx) { + return checkCompositePoolChannelPricingRestriction(ctx, func(candCtx context.Context) bool { + return s.checkChannelPricingRestriction(candCtx, groupID, requestedModel) + }) + } mapping := s.channelService.ResolveChannelMapping(ctx, *groupID, requestedModel) billingModel := billingModelForRestriction(mapping.BillingModelSource, requestedModel, mapping.MappedModel) if billingModel == "" { @@ -1029,9 +1034,15 @@ func billingModelForRestriction(source, requestedModel, channelMappedModel strin // isUpstreamModelRestrictedByChannel 检查账号映射后的上游模型是否受渠道定价限制。 // 仅在 BillingModelSource="upstream" 且 RestrictModels=true 时由调度循环调用。 func (s *GatewayService) isUpstreamModelRestrictedByChannel(ctx context.Context, groupID int64, account *Account, requestedModel string) bool { - if s.channelService == nil { + if s.channelService == nil || account == nil { return false } + if GenericCompositePoolActive(ctx) && account.Platform != "" { + ctx = WithResolvedTargetPlatform(ctx, account.Platform) + if mapping := s.channelService.ResolveChannelMapping(ctx, groupID, requestedModel); mapping.Mapped { + requestedModel = mapping.MappedModel + } + } upstreamModel := resolveAccountUpstreamModel(account, requestedModel) if upstreamModel == "" { return false diff --git a/backend/internal/service/gateway_scheduling.go b/backend/internal/service/gateway_scheduling.go index 3921dd8b06..be4858a126 100644 --- a/backend/internal/service/gateway_scheduling.go +++ b/backend/internal/service/gateway_scheduling.go @@ -39,6 +39,7 @@ func (s *GatewayService) SelectAccountForModelWithExclusions(ctx context.Context if hasForcePlatform && forcePlatform != "" { platform = forcePlatform } else if groupID != nil { + origGroupID := derefGroupID(groupID) group, resolvedGroupID, err := s.resolveGatewayGroup(ctx, groupID) if err != nil { return nil, err @@ -46,6 +47,9 @@ func (s *GatewayService) SelectAccountForModelWithExclusions(ctx context.Context if group == nil { return nil, ErrGroupNotFound } + if derefGroupID(resolvedGroupID) != origGroupID { + ctx = WithoutCompositeRouteContext(ctx) + } groupID = resolvedGroupID ctx = s.withGroupContext(ctx, group) platform = group.Platform @@ -123,10 +127,14 @@ func (s *GatewayService) SelectAccountWithLoadAwareness(ctx context.Context, gro cfg := s.schedulingConfig() // 检查 Claude Code 客户端限制(可能会替换 groupID 为降级分组) + origGroupID := derefGroupID(groupID) group, groupID, err := s.checkClaudeCodeRestriction(ctx, groupID) if err != nil { return nil, err } + if derefGroupID(groupID) != origGroupID { + ctx = WithoutCompositeRouteContext(ctx) + } ctx = s.withGroupContext(ctx, group) ctx = s.withGatewayProfitControlGate(ctx, groupID) @@ -1291,7 +1299,8 @@ func (s *GatewayService) gatewaySchedulingModelSupported(ctx context.Context, ac return true } if GenericCompositePoolActive(ctx) { - if !CompositeAccountMeetsClaimTier(ctx, account, requestedModel) && !account.IsOpenAIPassthroughEnabled() { + passthroughUnfiltered := account.IsOpenAIPassthroughEnabled() && !account.IsOpenAIPassthroughModelFilterEnabled() + if !CompositeAccountMeetsClaimTier(ctx, account, requestedModel) && !passthroughUnfiltered { return false } } diff --git a/backend/internal/service/openai_gateway_scheduling.go b/backend/internal/service/openai_gateway_scheduling.go index ee56d08ec8..10b5de25a9 100644 --- a/backend/internal/service/openai_gateway_scheduling.go +++ b/backend/internal/service/openai_gateway_scheduling.go @@ -372,7 +372,8 @@ func openAISchedulingModelSupported(ctx context.Context, account *Account, reque return true } if openAICompositePoolActive(ctx) { - if !CompositeAccountMeetsClaimTier(ctx, account, requestedModel) && !account.IsOpenAIPassthroughEnabled() { + passthroughUnfiltered := account.IsOpenAIPassthroughEnabled() && !account.IsOpenAIPassthroughModelFilterEnabled() + if !CompositeAccountMeetsClaimTier(ctx, account, requestedModel) && !passthroughUnfiltered { return false } } diff --git a/backend/internal/service/openai_gateway_service.go b/backend/internal/service/openai_gateway_service.go index f3422ad7d7..59efc3cdf9 100644 --- a/backend/internal/service/openai_gateway_service.go +++ b/backend/internal/service/openai_gateway_service.go @@ -650,6 +650,11 @@ func (s *OpenAIGatewayService) checkChannelPricingRestriction(ctx context.Contex if groupID == nil || s.channelService == nil || requestedModel == "" { return false } + if openAICompositePoolActive(ctx) { + return checkCompositePoolChannelPricingRestriction(ctx, func(candCtx context.Context) bool { + return s.checkChannelPricingRestriction(candCtx, groupID, requestedModel) + }) + } mapping := s.channelService.ResolveChannelMapping(ctx, *groupID, requestedModel) billingModel := billingModelForRestriction(mapping.BillingModelSource, requestedModel, mapping.MappedModel) if billingModel == "" { @@ -659,14 +664,28 @@ func (s *OpenAIGatewayService) checkChannelPricingRestriction(ctx context.Contex } func (s *OpenAIGatewayService) isUpstreamModelRestrictedByChannel(ctx context.Context, groupID int64, account *Account, requestedModel string, requireCompact bool) bool { - if s.channelService == nil { + if s.channelService == nil || account == nil { return false } + poolActive := openAICompositePoolActive(ctx) if compactForwardModel, ok := openAIForwardModelFromContext(ctx); ok { - requestedModel = compactForwardModel.model + if !poolActive { + requestedModel = compactForwardModel.model + } requireCompact = compactForwardModel.useCompactModelMapping } - upstreamModel := resolveOpenAIAccountUpstreamModelForRequest(account, requestedModel, requireCompact) + if poolActive && account.Platform != "" { + ctx = WithResolvedTargetPlatform(ctx, account.Platform) + if mapping := s.channelService.ResolveChannelMapping(ctx, groupID, requestedModel); mapping.Mapped { + requestedModel = mapping.MappedModel + } + } + var upstreamModel string + if account.Platform == PlatformAntigravity { + upstreamModel = mapAntigravityModel(account, requestedModel) + } else { + upstreamModel = resolveOpenAIAccountUpstreamModelForRequest(account, requestedModel, requireCompact) + } if upstreamModel == "" { return false }