From 10a5028d7f6add4d3a87e84bfafdd39698c235f0 Mon Sep 17 00:00:00 2001 From: shaw Date: Fri, 9 Oct 2026 17:20:47 +0800 Subject: [PATCH] =?UTF-8?q?fix(composite):=20generic=20Responses/CC=20?= =?UTF-8?q?=E5=A7=94=E6=B4=BE=E9=93=BE=E6=B5=81=E4=B8=AD=E6=96=AD=E6=97=B6?= =?UTF-8?q?=E9=83=A8=E5=88=86=E7=94=A8=E9=87=8F=E7=85=A7=E5=B8=B8=E5=85=A5?= =?UTF-8?q?=E8=B4=A6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 委派 OpenAI 网关链的池 attempt 在非 failover 错误时直接返回,丢弃上游已计量 的部分 usage;与 OpenAI handler 及 generic Messages 同语义(#5148)补记。 --- ...posite_generic_pool_text_endpoints_test.go | 24 +++++++++++ .../gateway_handler_chat_completions.go | 40 ++++++++++++------- .../handler/gateway_handler_responses.go | 40 ++++++++++++------- 3 files changed, 74 insertions(+), 30 deletions(-) diff --git a/backend/internal/handler/composite_generic_pool_text_endpoints_test.go b/backend/internal/handler/composite_generic_pool_text_endpoints_test.go index 62c33f6fbf..ddba7de277 100644 --- a/backend/internal/handler/composite_generic_pool_text_endpoints_test.go +++ b/backend/internal/handler/composite_generic_pool_text_endpoints_test.go @@ -8,6 +8,7 @@ import ( "net/http" "strings" "testing" + "testing/iotest" "github.com/Wei-Shaw/sub2api/internal/service" "github.com/stretchr/testify/require" @@ -245,6 +246,29 @@ func TestCompositePoolChatCompletionsDelegatesPureOpenAIFamilyAccount(t *testing require.Equal(t, "kimi-k3", *logs[0].UpstreamModel) } +// 委派链流中断(已向客户端写出内容、无法 failover):与 OpenAI handler 同语义, +// 上游已计量的部分 usage 照常入账(#5148),不得静默漏记。 +func TestCompositePoolChatCompletionsDelegatedStreamTruncationRecordsPartialUsage(t *testing.T) { + h := newCompositePoolMessagesHarness(t, []*service.Account{poolKimiAccount(42405, 41011, 0)}) + h.openAIUpstream.respond = func(compositePoolUpstreamCall, int) *http.Response { + stream := "data: {\"id\":\"chatcmpl-cut\",\"object\":\"chat.completion.chunk\",\"model\":\"kimi-k3\",\"choices\":[{\"index\":0,\"delta\":{\"content\":\"partial\"}}]}\n\n" + return &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{"text/event-stream"}}, + Body: io.NopCloser(io.MultiReader(strings.NewReader(stream), iotest.ErrReader(io.ErrUnexpectedEOF))), + } + } + + body := `{"model":"my-model","stream":true,"messages":[{"role":"user","content":"hello"}]}` + c, _ := h.newRequest(t, "/v1/chat/completions", body, service.PlatformAnthropic, service.PlatformKimi) + h.handler.ChatCompletions(c) + + require.Len(t, h.openAIUpstream.snapshot(), 1) + logs := h.usageRepo.snapshot() + require.Len(t, logs, 1, "流中断的委派结果必须入账") + require.EqualValues(t, 42405, logs[0].AccountID) +} + // 池选中 adaptive 多协议账号:CC 入站由 OpenAI CC 链直转供应商原生 CC 端点 // (入站同族优先,零转换;与其在纯 OpenAI 族池中的行为一致),不走 CC→Anthropic // 既有转换链。 diff --git a/backend/internal/handler/gateway_handler_chat_completions.go b/backend/internal/handler/gateway_handler_chat_completions.go index 20f9d873fc..7dc9a637ef 100644 --- a/backend/internal/handler/gateway_handler_chat_completions.go +++ b/backend/internal/handler/gateway_handler_chat_completions.go @@ -410,6 +410,25 @@ func (h *GatewayHandler) ChatCompletions(c *gin.Context) { accountReleaseFunc() } + // 池委派 OpenAI 网关链的结果按 OpenAI 口径入账(见 submitDelegatedOpenAIUsage)。 + submitDelegatedUsage := func() { + quotaPlatform := service.QuotaPlatform(c.Request.Context(), apiKey) + if isPoolAttempt { + quotaPlatform = service.QuotaPlatform(attemptPolicy.AttemptCtx, apiKey) + } + h.submitDelegatedOpenAIUsage(c, delegatedOpenAIUsage{ + Result: delegatedResult, + APIKey: apiKey, + Account: account, + Subscription: subscription, + QuotaPlatform: quotaPlatform, + PricingAt: pricingAt, + RequestPayloadHash: service.HashUsageRequestPayload(body), + ChannelUsageFields: clientRequestedUsageFields(c, attemptChannelMapping, reqModel, delegatedResult.UpstreamModel), + LogComponent: "handler.gateway.chat_completions", + }) + } + if err != nil { var failoverErr *service.UpstreamFailoverError if errors.As(err, &failoverErr) { @@ -440,26 +459,17 @@ func (h *GatewayHandler) ChatCompletions(c *gin.Context) { zap.Bool("upstream_error_response_already_written", upstreamErrorAlreadyCommunicated), zap.Error(err), ) + // 委派链流中断与 OpenAI handler 同语义:上游已计量的部分 usage 照常入账(#5148); + // failover 错误恒定 result=nil,不会重复计费。 + if delegatedResult != nil { + submitDelegatedUsage() + } return } // 6. Record usage if delegatedResult != nil { - quotaPlatform := service.QuotaPlatform(c.Request.Context(), apiKey) - if isPoolAttempt { - quotaPlatform = service.QuotaPlatform(attemptPolicy.AttemptCtx, apiKey) - } - h.submitDelegatedOpenAIUsage(c, delegatedOpenAIUsage{ - Result: delegatedResult, - APIKey: apiKey, - Account: account, - Subscription: subscription, - QuotaPlatform: quotaPlatform, - PricingAt: pricingAt, - RequestPayloadHash: service.HashUsageRequestPayload(body), - ChannelUsageFields: clientRequestedUsageFields(c, attemptChannelMapping, reqModel, delegatedResult.UpstreamModel), - LogComponent: "handler.gateway.chat_completions", - }) + submitDelegatedUsage() return } userAgent := c.GetHeader("User-Agent") diff --git a/backend/internal/handler/gateway_handler_responses.go b/backend/internal/handler/gateway_handler_responses.go index 18db039a9f..36ed9e8f29 100644 --- a/backend/internal/handler/gateway_handler_responses.go +++ b/backend/internal/handler/gateway_handler_responses.go @@ -414,6 +414,25 @@ func (h *GatewayHandler) Responses(c *gin.Context) { accountReleaseFunc() } + // 池委派 OpenAI 网关链的结果按 OpenAI 口径入账(见 submitDelegatedOpenAIUsage)。 + submitDelegatedUsage := func() { + quotaPlatform := service.QuotaPlatform(c.Request.Context(), apiKey) + if isPoolAttempt { + quotaPlatform = service.QuotaPlatform(attemptPolicy.AttemptCtx, apiKey) + } + h.submitDelegatedOpenAIUsage(c, delegatedOpenAIUsage{ + Result: delegatedResult, + APIKey: apiKey, + Account: account, + Subscription: subscription, + QuotaPlatform: quotaPlatform, + PricingAt: pricingAt, + RequestPayloadHash: service.HashUsageRequestPayload(body), + ChannelUsageFields: clientRequestedUsageFields(c, attemptChannelMapping, reqModel, delegatedResult.UpstreamModel), + LogComponent: "handler.gateway.responses", + }) + } + if err != nil { var failoverErr *service.UpstreamFailoverError if errors.As(err, &failoverErr) { @@ -445,26 +464,17 @@ func (h *GatewayHandler) Responses(c *gin.Context) { zap.Bool("upstream_error_response_already_written", upstreamErrorAlreadyCommunicated), zap.Error(err), ) + // 委派链流中断与 OpenAI handler 同语义:上游已计量的部分 usage 照常入账(#5148); + // failover 错误恒定 result=nil,不会重复计费。 + if delegatedResult != nil { + submitDelegatedUsage() + } return } // 6. Record usage if delegatedResult != nil { - quotaPlatform := service.QuotaPlatform(c.Request.Context(), apiKey) - if isPoolAttempt { - quotaPlatform = service.QuotaPlatform(attemptPolicy.AttemptCtx, apiKey) - } - h.submitDelegatedOpenAIUsage(c, delegatedOpenAIUsage{ - Result: delegatedResult, - APIKey: apiKey, - Account: account, - Subscription: subscription, - QuotaPlatform: quotaPlatform, - PricingAt: pricingAt, - RequestPayloadHash: service.HashUsageRequestPayload(body), - ChannelUsageFields: clientRequestedUsageFields(c, attemptChannelMapping, reqModel, delegatedResult.UpstreamModel), - LogComponent: "handler.gateway.responses", - }) + submitDelegatedUsage() return } userAgent := c.GetHeader("User-Agent")