From b89c2c98c78e059d3cc1ee255036c0957096c75e Mon Sep 17 00:00:00 2001 From: shaw Date: Sat, 5 Dec 2026 10:41:13 +0800 Subject: [PATCH] =?UTF-8?q?fix(gateway):=20=E8=A1=A5=E9=BD=90=E8=B7=A8?= =?UTF-8?q?=E6=97=8F=E8=B4=A6=E5=8F=B7=E6=B1=A0=20compact=20=E8=B7=AF?= =?UTF-8?q?=E7=94=B1=E3=80=81=E7=94=9F=E5=9B=BE=E9=97=A8=E7=A6=81=E3=80=81?= =?UTF-8?q?=E6=8E=A8=E7=90=86=E5=BC=BA=E5=BA=A6=E7=AD=96=E7=95=A5=E4=B8=8E?= =?UTF-8?q?=E6=B5=81=E5=BC=8F=E9=94=99=E8=AF=AF=E8=BE=93=E5=87=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../internal/handler/composite_platform.go | 8 ++- ...site_pool_reasoning_policy_generic_test.go | 49 +++++++++++++++++++ backend/internal/handler/gateway_handler.go | 10 ++-- .../gateway_handler_chat_completions.go | 11 ++++- .../handler/gateway_handler_responses.go | 27 ++++++++-- .../handler/openai_chat_completions.go | 4 +- .../handler/openai_gateway_handler.go | 8 +-- backend/internal/server/routes/gateway.go | 19 +++++++ ...ateway_composite_pool_continuation_test.go | 36 ++++++++++++++ .../gateway_composite_pool_policy_test.go | 5 ++ 10 files changed, 162 insertions(+), 15 deletions(-) diff --git a/backend/internal/handler/composite_platform.go b/backend/internal/handler/composite_platform.go index 7d084186a8..a4266ea89b 100644 --- a/backend/internal/handler/composite_platform.go +++ b/backend/internal/handler/composite_platform.go @@ -314,8 +314,12 @@ func applyCompositePoolReasoningEffortPolicyForSelectedAccount(c *gin.Context, a if _, isPool := compositeAccountPoolCandidates(c); !isPool { return body, false, nil } - if account.Platform != service.PlatformOpenAI { + if account.Platform != service.PlatformOpenAI && account.Platform != service.PlatformAnthropic { return body, false, nil } - return service.ApplyOpenAIReasoningEffortPolicy(body, apiKey.Group.MaxReasoningEffort, apiKey.Group.ReasoningEffortMappings, apiKey.Group.MaxReasoningEffortOverLimit) + maxEffort, mappings := apiKey.Group.MaxReasoningEffort, apiKey.Group.ReasoningEffortMappings + if account.Platform == service.PlatformAnthropic { + maxEffort, mappings = anthropicCompatibleReasoningEffortPolicy(maxEffort, mappings) + } + return service.ApplyOpenAIReasoningEffortPolicy(body, maxEffort, mappings, apiKey.Group.MaxReasoningEffortOverLimit) } diff --git a/backend/internal/handler/composite_pool_reasoning_policy_generic_test.go b/backend/internal/handler/composite_pool_reasoning_policy_generic_test.go index e0000dd1aa..1e68d64b83 100644 --- a/backend/internal/handler/composite_pool_reasoning_policy_generic_test.go +++ b/backend/internal/handler/composite_pool_reasoning_policy_generic_test.go @@ -124,3 +124,52 @@ func TestCompositeCrossFamilyPoolMessagesAppliesReasoningEffortCapToAnthropic(t require.Len(t, calls, 1) require.Equal(t, "medium", gjson.GetBytes(calls[0].Body, "output_config.effort").String(), "upstream body=%s", calls[0].Body) } + +// 跨族池在 /v1/responses 与 /v1/chat/completions 选中 anthropic 账号时,同样须补齐 +// 分组推理强度策略(含 deny 拦截)。 +func TestCompositeCrossFamilyPoolTextEndpointsApplyReasoningEffortPolicyToAnthropic(t *testing.T) { + for _, tc := range []struct { + name, path, body string + }{ + { + name: "responses", + path: "/v1/responses", + body: `{"model":"my-model","stream":false,"input":"hello","reasoning":{"effort":"high"}}`, + }, + { + name: "chat_completions", + path: "/v1/chat/completions", + body: `{"model":"my-model","stream":false,"messages":[{"role":"user","content":"hello"}],"reasoning_effort":"high"}`, + }, + } { + t.Run(tc.name, func(t *testing.T) { + h := newCompositePoolMessagesHarness(t, []*service.Account{poolAnthropicAccount(44203, 41011, 0)}) + h.group.MaxReasoningEffort = "low" + h.group.MaxReasoningEffortOverLimit = "deny" + + c, rec := h.newRequest(t, tc.path, tc.body, service.PlatformAnthropic, service.PlatformOpenAI) + if tc.path == "/v1/responses" { + h.handler.Responses(c) + } else { + h.handler.ChatCompletions(c) + } + require.Equal(t, http.StatusForbidden, rec.Code, rec.Body.String()) + require.Empty(t, h.gwUpstream.snapshot()) + }) + } +} + +// 跨族池 /v1/responses 在分组禁用生图时,须拦截显式生图工具请求,不得经委派绕过。 +func TestCompositeCrossFamilyPoolResponsesEnforcesGroupImageGenerationGate(t *testing.T) { + h := newCompositePoolMessagesHarness(t, []*service.Account{poolOpenAIAccount(44204, 41011, 0)}) + h.group.AllowImageGeneration = false + + c, rec := h.newRequest(t, "/v1/responses", + `{"model":"my-model","stream":false,"input":"draw a cat","tools":[{"type":"image_generation"}]}`, + service.PlatformAnthropic, service.PlatformOpenAI) + h.handler.Responses(c) + + require.Equal(t, http.StatusForbidden, rec.Code, rec.Body.String()) + require.Contains(t, rec.Body.String(), service.ImageGenerationPermissionMessage()) + require.Empty(t, h.openAIUpstream.snapshot()) +} diff --git a/backend/internal/handler/gateway_handler.go b/backend/internal/handler/gateway_handler.go index 2133465516..535d346caf 100644 --- a/backend/internal/handler/gateway_handler.go +++ b/backend/internal/handler/gateway_handler.go @@ -812,18 +812,21 @@ func (h *GatewayHandler) Messages(c *gin.Context) { } // 账号池选中 anthropic 账号:按单目标 anthropic 语义补齐分组推理强度策略(放在槽位获取前)。 if isPoolRequest { + streamAwareWrite := func(cc *gin.Context, status int, code, message string) { + h.handleStreamingAwareError(cc, status, code, message, streamStarted) + } cappedBody, changed, policyErr := applyCompositePoolAnthropicReasoningEffortPolicy(apiKey, account, attemptParsedReq.Body.Bytes()) if policyErr != nil { releaseCompositePoolSelection(selection) h.gatewayService.ReleaseAccountSession(context.Background(), account, sessionKey) - respondOpenAIReasoningEffortPolicyError(c, policyErr, h.errorResponse) + respondOpenAIReasoningEffortPolicyError(c, policyErr, streamAwareWrite) return } if changed { if err := attemptParsedReq.ReplaceBody(cappedBody); err != nil { releaseCompositePoolSelection(selection) h.gatewayService.ReleaseAccountSession(context.Background(), account, sessionKey) - h.errorResponse(c, http.StatusBadRequest, "invalid_request_error", "Failed to apply reasoning effort policy") + streamAwareWrite(c, http.StatusBadRequest, "invalid_request_error", "Failed to apply reasoning effort policy") return } } @@ -1020,7 +1023,8 @@ func (h *GatewayHandler) Messages(c *gin.Context) { // 渠道定价作用域与计费 QuotaPlatform 跟随实际平台,对齐 OpenAI 池 attempt 语义。 if isPoolRequest { requestCtx = compositePoolAttemptContext(requestCtx, account) - } else if channelMapping.Mapped { + } + if attemptChannelMapping.Mapped { // 选号按客户端模型,转发按渠道映射后的模型:模型级账号状态按选号模型记录。 requestCtx = service.WithGatewaySchedulingModel(requestCtx, reqModel) } diff --git a/backend/internal/handler/gateway_handler_chat_completions.go b/backend/internal/handler/gateway_handler_chat_completions.go index f4f25b3b18..803616d583 100644 --- a/backend/internal/handler/gateway_handler_chat_completions.go +++ b/backend/internal/handler/gateway_handler_chat_completions.go @@ -367,14 +367,21 @@ func (h *GatewayHandler) ChatCompletions(c *gin.Context) { if attemptChannelMapping.Mapped { forwardBody = h.gatewayService.ReplaceModelInBody(body, attemptChannelMapping.MappedModel) } - // 账号池按选中账号应用分组推理强度策略(与 OpenAI handler 同语义,仅 openai 账号)。 + // 账号池按选中账号应用分组推理强度策略(与单目标同语义,覆盖 openai / anthropic 账号)。 if isPoolRequest { cappedBody, changed, policyErr := applyCompositePoolReasoningEffortPolicyForSelectedAccount(c, apiKey, account, forwardBody) if policyErr != nil { if accountReleaseFunc != nil { accountReleaseFunc() } - respondOpenAIReasoningEffortPolicyError(c, policyErr, h.chatCompletionsErrorResponse) + streamAwareWrite := func(cc *gin.Context, status int, code, message string) { + if streamStarted { + h.handleStreamingAwareError(cc, status, code, message, true) + return + } + h.chatCompletionsErrorResponse(cc, status, code, message) + } + respondOpenAIReasoningEffortPolicyError(c, policyErr, streamAwareWrite) return } if changed { diff --git a/backend/internal/handler/gateway_handler_responses.go b/backend/internal/handler/gateway_handler_responses.go index 0b7ed3fad2..47f2841d23 100644 --- a/backend/internal/handler/gateway_handler_responses.go +++ b/backend/internal/handler/gateway_handler_responses.go @@ -130,6 +130,13 @@ func (h *GatewayHandler) Responses(c *gin.Context) { h.responsesErrorResponse(c, http.StatusBadRequest, "invalid_request_error", service.ImageGenerationPermissionMessage()) return } + if apiKey.Group != nil && apiKey.Group.Platform == service.PlatformComposite && + service.IsExplicitImageGenerationIntentValidated("/v1/responses", reqModel, body) && + !service.GroupAllowsImageGeneration(apiKey.Group) { + service.MarkOpsClientBusinessLimited(c, service.OpsClientBusinessLimitedReasonLocalFeatureGate) + h.responsesErrorResponse(c, http.StatusForbidden, "permission_error", service.ImageGenerationPermissionMessage()) + return + } if decision := h.checkSecurityAudit(c, reqLog, apiKey, subject, service.ContentModerationProtocolOpenAIResponses, reqModel, body); decision != nil && !decision.AllowNextStage { h.responsesSecurityAuditError(c, decision) @@ -280,8 +287,13 @@ func (h *GatewayHandler) Responses(c *gin.Context) { poolDenials.deny(account.Platform) fs.FailedAccountIDs[account.ID] = struct{}{} if _, ok := compositePoolSelectionRetryContext(requestCtx, poolDenials); !ok { - h.responsesErrorResponse(c, http.StatusBadRequest, "invalid_request_error", - "Model is only available on Gemini accounts in this group, which do not support /v1/responses") + if streamStarted { + h.handleStreamingAwareError(c, http.StatusBadRequest, "invalid_request_error", + "Model is only available on Gemini accounts in this group, which do not support /v1/responses", true) + } else { + h.responsesErrorResponse(c, http.StatusBadRequest, "invalid_request_error", + "Model is only available on Gemini accounts in this group, which do not support /v1/responses") + } return } continue @@ -382,14 +394,21 @@ func (h *GatewayHandler) Responses(c *gin.Context) { if attemptChannelMapping.Mapped { forwardBody = h.gatewayService.ReplaceModelInBody(body, attemptChannelMapping.MappedModel) } - // 账号池按选中账号应用分组推理强度策略(与 OpenAI handler 同语义,仅 openai 账号)。 + // 账号池按选中账号应用分组推理强度策略(与单目标同语义,覆盖 openai / anthropic 账号)。 if isPoolRequest { cappedBody, changed, policyErr := applyCompositePoolReasoningEffortPolicyForSelectedAccount(c, apiKey, account, forwardBody) if policyErr != nil { if accountReleaseFunc != nil { accountReleaseFunc() } - respondOpenAIReasoningEffortPolicyError(c, policyErr, h.responsesErrorResponse) + streamAwareWrite := func(cc *gin.Context, status int, code, message string) { + if streamStarted { + h.handleStreamingAwareError(cc, status, code, message, true) + return + } + h.responsesErrorResponse(cc, status, code, message) + } + respondOpenAIReasoningEffortPolicyError(c, policyErr, streamAwareWrite) return } if changed { diff --git a/backend/internal/handler/openai_chat_completions.go b/backend/internal/handler/openai_chat_completions.go index fbbc204dc3..a06f9fd996 100644 --- a/backend/internal/handler/openai_chat_completions.go +++ b/backend/internal/handler/openai_chat_completions.go @@ -252,7 +252,9 @@ func (h *OpenAIGatewayHandler) ChatCompletions(c *gin.Context) { poolPolicyBody := body if cappedBody, changed, err := applyCompositePoolReasoningEffortPolicyForSelectedAccount(c, apiKey, account, body); err != nil { releaseCompositePoolSelection(selection) - respondOpenAIReasoningEffortPolicyError(c, err, h.errorResponse) + respondOpenAIReasoningEffortPolicyError(c, err, func(cc *gin.Context, status int, code, message string) { + h.handleStreamingAwareError(cc, status, code, message, streamStarted) + }) return } else if changed { poolPolicyBody = cappedBody diff --git a/backend/internal/handler/openai_gateway_handler.go b/backend/internal/handler/openai_gateway_handler.go index 71fc939e77..32c196366f 100644 --- a/backend/internal/handler/openai_gateway_handler.go +++ b/backend/internal/handler/openai_gateway_handler.go @@ -852,8 +852,8 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) { "the account that owns previous_response_id is temporarily unavailable; retry later", streamStarted) return } - h.errorResponse(c, http.StatusBadRequest, "invalid_request_error", - "previous_response_id belongs to a response owned by a different account; continue on the account that owns this response state or start a new response") + h.handleStreamingAwareError(c, http.StatusBadRequest, "invalid_request_error", + "previous_response_id belongs to a response owned by a different account; continue on the account that owns this response state or start a new response", streamStarted) return } // 仅实际 openai 平台账号要求 API-key 才支持 HTTP continuation; @@ -895,7 +895,9 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) { poolPolicyBody := forwardBody if cappedBody, changed, err := applyCompositePoolReasoningEffortPolicyForSelectedAccount(c, apiKey, account, forwardBody); err != nil { releaseCompositePoolSelection(selection) - respondOpenAIReasoningEffortPolicyError(c, err, h.errorResponse) + respondOpenAIReasoningEffortPolicyError(c, err, func(cc *gin.Context, status int, code, message string) { + h.handleStreamingAwareError(cc, status, code, message, streamStarted) + }) return } else if changed { poolPolicyBody = cappedBody diff --git a/backend/internal/server/routes/gateway.go b/backend/internal/server/routes/gateway.go index c530efaf12..322efbda0e 100644 --- a/backend/internal/server/routes/gateway.go +++ b/backend/internal/server/routes/gateway.go @@ -711,6 +711,14 @@ func compositeTargetPlatformMiddleware(resolver *service.CompositeRouteResolver) writeCompositeRouteAdmissionError(c, http.StatusBadRequest, fmt.Sprintf("Model %q has no OpenAI-compatible account in this composite group to continue previous_response_id; resend the full conversation without previous_response_id", model)) return } + } else if isCompositePoolResponsesCompact(c, decision) { + // /responses/compact 仅由 OpenAI 网关链支持(含 compact 归一化、渠道限制与心跳): + // 跨族候选池收窄到 OpenAI 兼容族,避免落入通用网关按普通 Responses 误转协议。 + decision.CandidatePlatforms = openAICompatibleCandidatePlatforms(decision.CandidatePlatforms) + if len(decision.CandidatePlatforms) == 0 { + writeCompositeRouteAdmissionError(c, http.StatusBadRequest, fmt.Sprintf("Model %q has no OpenAI-compatible account in this composite group to support /responses/compact", model)) + return + } } c.Request = c.Request.WithContext(service.WithCompositeRouteDecision(c.Request.Context(), decision)) if upstreamModel := strings.TrimSpace(decision.UpstreamModel); upstreamModel != "" && upstreamModel != model && gjson.ValidBytes(body) { @@ -796,6 +804,17 @@ func isCompositePoolResponsesContinuation(c *gin.Context, decision service.Compo return strings.TrimSpace(gjson.GetBytes(body, "previous_response_id").String()) != "" } +func isCompositePoolResponsesCompact(c *gin.Context, decision service.CompositeRouteDecision) bool { + if c == nil || c.Request == nil || c.Request.URL == nil { + return false + } + if strings.TrimSpace(decision.TargetPlatform) != "" || len(decision.CandidatePlatforms) == 0 { + return false + } + path := strings.TrimRight(c.Request.URL.Path, "/") + return strings.HasSuffix(path, "/responses/compact") +} + // openAICompatibleCandidatePlatforms 返回候选平台中经 OpenAI 网关转发的平台(保持顺序)。 func openAICompatibleCandidatePlatforms(candidates []string) []string { out := make([]string, 0, len(candidates)) diff --git a/backend/internal/server/routes/gateway_composite_pool_continuation_test.go b/backend/internal/server/routes/gateway_composite_pool_continuation_test.go index 7765fa8b4e..8f9915eb78 100644 --- a/backend/internal/server/routes/gateway_composite_pool_continuation_test.go +++ b/backend/internal/server/routes/gateway_composite_pool_continuation_test.go @@ -94,3 +94,39 @@ func TestCompositePoolContinuationWithoutOpenAICompatibleCandidateRejected(t *te require.Contains(t, w.Body.String(), "previous_response_id") require.Empty(t, upstream.capturedSnapshot()) } + +// 跨族账号池访问 /v1/responses/compact:候选池收窄到 OpenAI 兼容族交由 OpenAI handler +// 处理,优先级更高的 Anthropic 账号不会收到 compact 请求;无兼容族候选时入口明确拒绝。 +func TestCompositeCrossFamilyPoolCompactNarrowsToOpenAICompatible(t *testing.T) { + upstream := &captureUpstream{} + openai := newPoolPolicyAccountWithMapping(4331, service.PlatformOpenAI, 5, map[string]any{"compact-model": "gpt-5.4"}) + anthropic := newPoolPolicyAccountWithMapping(4332, service.PlatformAnthropic, 0, map[string]any{"compact-model": "claude-sonnet-4-5"}) + router, _ := newCompositePoolPolicyTestRouter(t, poolPolicyRouterInput{ + group: newPoolPolicyGroup(nil), + accounts: []service.Account{openai, anthropic}, + upstream: upstream, + }) + + w := postPoolPolicyRequest(t, router, "/v1/responses/compact", + `{"model":"compact-model","input":"compact this"}`) + require.Equal(t, http.StatusOK, w.Code, w.Body.String()) + captured := upstream.capturedSnapshot() + require.Len(t, captured, 1) + require.Equal(t, "openai-pool-fake.test", captured[0].host) + require.True(t, strings.HasSuffix(captured[0].path, "/responses/compact"), "path=%q", captured[0].path) + + upstreamNone := &captureUpstream{} + routerNone, _ := newCompositePoolPolicyTestRouter(t, poolPolicyRouterInput{ + group: newPoolPolicyGroup(nil), + accounts: []service.Account{ + newPoolPolicyAccountWithMapping(4333, service.PlatformAnthropic, 0, map[string]any{"np-compact": "claude-sonnet-4-5"}), + newPoolPolicyAccountWithMapping(4334, service.PlatformGemini, 1, map[string]any{"np-compact": "gemini-3.1-pro"}), + }, + upstream: upstreamNone, + }) + wNone := postPoolPolicyRequest(t, routerNone, "/v1/responses/compact", + `{"model":"np-compact","input":"compact this"}`) + require.Equal(t, http.StatusBadRequest, wNone.Code, wNone.Body.String()) + require.Contains(t, wNone.Body.String(), "/responses/compact") + require.Empty(t, upstreamNone.capturedSnapshot()) +} diff --git a/backend/internal/server/routes/gateway_composite_pool_policy_test.go b/backend/internal/server/routes/gateway_composite_pool_policy_test.go index af7df5f463..3e20023b75 100644 --- a/backend/internal/server/routes/gateway_composite_pool_policy_test.go +++ b/backend/internal/server/routes/gateway_composite_pool_policy_test.go @@ -165,6 +165,7 @@ func (c *stickyMemoryGatewayCache) GetReasoningContent(context.Context, string) type poolPolicyCapturedRequest struct { accountID int64 host string + path string body []byte } @@ -187,6 +188,7 @@ func (u *captureUpstream) capture(req *http.Request, accountID int64) []byte { u.captured = append(u.captured, poolPolicyCapturedRequest{ accountID: accountID, host: req.URL.Hostname(), + path: req.URL.Path, body: body, }) u.mu.Unlock() @@ -210,6 +212,9 @@ func (u *captureUpstream) respondFor(req *http.Request) *http.Response { Body: io.NopCloser(strings.NewReader(`{"error":{"message":"rate limited"}}`)), } } + if strings.HasSuffix(req.URL.Path, "/responses/compact") { + return compositeDispatchResponse("application/json", `{"id":"resp_compact","object":"response.compaction","output":[],"usage":{"input_tokens":1,"output_tokens":1,"total_tokens":2}}`) + } if strings.Contains(req.URL.Path, "/responses") { sse := "event: response.completed\n" + `data: {"type":"response.completed","response":{"id":"resp_pool","object":"response","status":"completed","model":"deepseek-chat","output":[{"type":"message","role":"assistant","content":[{"type":"output_text","text":"ok"}]}],"usage":{"input_tokens":1,"output_tokens":1,"total_tokens":2}}}` + "\n\n"