From eabf37852a2fde06afe5cebcaefd19b307add1bc Mon Sep 17 00:00:00 2001 From: shaw Date: Tue, 24 Nov 2026 09:42:41 +0800 Subject: [PATCH] =?UTF-8?q?fix(openai):=20compact=20response.failed=20?= =?UTF-8?q?=E6=94=B9=E5=86=99=E5=AE=B9=E9=87=8F=E9=99=8D=E8=BD=BD=E7=A0=81?= =?UTF-8?q?=EF=BC=8C=E7=A9=BA=E7=99=BD=20code=20=E5=9B=9E=E9=80=80?= =?UTF-8?q?=E5=86=85=E5=B5=8C=E6=8F=90=E5=8F=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 透传结构化错误在 compact 心跳已提交时写 response.failed,上游的 server_is_overloaded / slow_down 必须与其它写 response.failed 的路径一样 改写为可重试的 server_error,否则 Codex 会直接终止会话 - error.code 为空白字符串时回退到 message 内嵌 JSON 的 code,与错误分类 看到的 code 保持一致 - 移除测试文件中仅为保留 import 而存在的占位变量 --- .../service/openai_compact_stream_bridge.go | 9 +++- .../service/openai_gateway_passthrough.go | 16 +++--- ...penai_passthrough_error_forwarding_test.go | 51 +++++++++++++++++-- 3 files changed, 66 insertions(+), 10 deletions(-) diff --git a/backend/internal/service/openai_compact_stream_bridge.go b/backend/internal/service/openai_compact_stream_bridge.go index 14a419e95c..47a4f4ea56 100644 --- a/backend/internal/service/openai_compact_stream_bridge.go +++ b/backend/internal/service/openai_compact_stream_bridge.go @@ -117,9 +117,16 @@ func writeOpenAICompactSSEFailureMessage(c *gin.Context, statusCode int, errType // invalid_encrypted_content),供客户端区分确定性请求失败;code 为空时回落 // upstream_error。ops 侧的错误类型保持 upstream_error 不变。message 由调用方 // 负责脱敏。 +// +// 容量降载码(server_is_overloaded / slow_down)不得原样写进 response.failed: +// Codex 把它们判为致命错误并直接终止会话,所有写 response.failed 的路径都改写为 +// 可重试的 openAICapacityShedRetryableClientCode(见该常量注释)。 func writeOpenAICompactSSEFailureWithCode(c *gin.Context, statusCode int, code, message string) { - if strings.TrimSpace(code) == "" { + switch strings.ToLower(strings.TrimSpace(code)) { + case "": code = "upstream_error" + case "server_is_overloaded", "slow_down": + code = openAICapacityShedRetryableClientCode } writeOpenAICompactSSEFailureEvent(c, statusCode, "upstream_error", code, message) } diff --git a/backend/internal/service/openai_gateway_passthrough.go b/backend/internal/service/openai_gateway_passthrough.go index 7288cdee12..5771366930 100644 --- a/backend/internal/service/openai_gateway_passthrough.go +++ b/backend/internal/service/openai_gateway_passthrough.go @@ -934,17 +934,21 @@ func openAIPassthroughClientErrorField(account *Account, value gjson.Result) str } // openAIPassthroughClientErrorCode 返回允许写给客户端的 error.code。 -// error.code 缺失时沿用 extractUpstreamErrorCode 对"message 内嵌 JSON"形态的 -// 兼容提取;error.code 存在但不是标量时不回退,直接视为无 code。 +// error.code 缺失、为 null 或为空白字符串时,沿用 extractUpstreamErrorCode 对 +// "message 内嵌 JSON"形态的兼容提取(与错误分类看到的 code 保持一致); +// error.code 是对象、数组或布尔值时不回退,直接视为无 code。 func openAIPassthroughClientErrorCode(account *Account, body []byte) string { - if code := gjson.GetBytes(body, "error.code"); code.Exists() && code.Type != gjson.Null { + code := gjson.GetBytes(body, "error.code") + blank := !code.Exists() || code.Type == gjson.Null || + (code.Type == gjson.String && strings.TrimSpace(code.Str) == "") + if !blank { return openAIPassthroughClientErrorField(account, code) } - code := sanitizeOpenAIPassthroughClientErrorText(account, extractUpstreamErrorCode(body)) - if len(code) > openAIPassthroughClientErrorFieldMaxBytes || strings.HasPrefix(code, "{") || strings.HasPrefix(code, "[") { + inner := sanitizeOpenAIPassthroughClientErrorText(account, extractUpstreamErrorCode(body)) + if len(inner) > openAIPassthroughClientErrorFieldMaxBytes || strings.HasPrefix(inner, "{") || strings.HasPrefix(inner, "[") { return "" } - return code + return inner } // writeOpenAIPassthroughStructuredErrorEnvelope 在净化后的 OpenAI 错误信封内 diff --git a/backend/internal/service/openai_passthrough_error_forwarding_test.go b/backend/internal/service/openai_passthrough_error_forwarding_test.go index 595cf77ef8..5b2aead8d5 100644 --- a/backend/internal/service/openai_passthrough_error_forwarding_test.go +++ b/backend/internal/service/openai_passthrough_error_forwarding_test.go @@ -8,7 +8,6 @@ import ( "net/http/httptest" "strings" "testing" - "time" "github.com/Wei-Shaw/sub2api/internal/config" "github.com/Wei-Shaw/sub2api/internal/model" @@ -336,8 +335,6 @@ func TestOpenAIGatewayService_APIKeyPassthrough_ContextWindowPreservesCodeAndCom }) } -var _ = time.Second - // forwardOpenAIPassthroughErrorForTest 让透传账号收到给定的上游错误响应,返回写给客户端的结果。 func forwardOpenAIPassthroughErrorForTest(t *testing.T, c *gin.Context, upstreamStatus int, upstreamBody string, credentials map[string]any) { t.Helper() @@ -475,6 +472,12 @@ func TestOpenAIGatewayService_APIKeyPassthrough_StructuredErrorHardening(t *test require.Equal(t, "", openAIPassthroughClientErrorCode(nil, []byte(`{"error":{"code":true}}`))) require.Equal(t, "inner_code", openAIPassthroughClientErrorCode(nil, []byte(`{"error":{"message":"{\"error\":{\"code\":\"inner_code\"}}"}}`))) require.Equal(t, "", openAIPassthroughClientErrorCode(nil, []byte(`{"error":{"message":"{\"error\":{\"code\":{\"k\":\"v\"}}}"}}`))) + // error.code 为空白字符串时与分类逻辑一致,回退到 message 内嵌 JSON 的 code。 + require.Equal(t, "inner_code", openAIPassthroughClientErrorCode(nil, []byte(`{"error":{"code":"","message":"{\"error\":{\"code\":\"inner_code\"}}"}}`))) + require.Equal(t, "inner_code", openAIPassthroughClientErrorCode(nil, []byte(`{"error":{"code":" ","message":"{\"error\":{\"code\":\"inner_code\"}}"}}`))) + require.Equal(t, "inner_code", openAIPassthroughClientErrorCode(nil, []byte(`{"error":{"code":null,"message":"{\"error\":{\"code\":\"inner_code\"}}"}}`))) + // error.code 是非标量时不回退。 + require.Equal(t, "", openAIPassthroughClientErrorCode(nil, []byte(`{"error":{"code":{"k":"v"},"message":"{\"error\":{\"code\":\"inner_code\"}}"}}`))) }) t.Run("ordinary 400 that merely mentions invalid_encrypted_content stays sanitized", func(t *testing.T) { @@ -537,3 +540,45 @@ func TestOpenAIGatewayService_APIKeyPassthrough_RuleWithoutCustomMessageSanitize require.Equal(t, custom, gjson.Get(rec.Body.String(), "error.message").String()) }) } + +// Codex 把 server_is_overloaded / slow_down 判为致命错误并终止会话,写进 +// response.failed 前必须改写为可重试的错误码;其它上游 code 原样保留。 +func TestOpenAIGatewayService_APIKeyPassthrough_CompactFailedRewritesCapacityShedCode(t *testing.T) { + gin.SetMode(gin.TestMode) + + for upstreamCode, wantCode := range map[string]string{ + "server_is_overloaded": openAICapacityShedRetryableClientCode, + "slow_down": openAICapacityShedRetryableClientCode, + "SERVER_IS_OVERLOADED": openAICapacityShedRetryableClientCode, + "rate_limit_exceeded": "rate_limit_exceeded", + } { + t.Run(upstreamCode, func(t *testing.T) { + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses/compact", bytes.NewReader(nil)) + MarkOpenAICompactClientStream(c) + stop := StartOpenAICompactSSEKeepalive(c, keepaliveTestInterval) + defer stop() + waitForKeepaliveBeats() + + ruleSvc := &ErrorPassthroughService{} + ruleSvc.setLocalCache([]*model.ErrorPassthroughRule{{ + ID: 1, Name: "openai-400-body", Enabled: true, Priority: 1, + ErrorCodes: []int{http.StatusBadRequest}, MatchMode: model.MatchModeAny, + Platforms: []string{PlatformOpenAI}, PassthroughCode: true, PassthroughBody: true, + }}) + BindErrorPassthroughService(c, ruleSvc) + + forwardOpenAIPassthroughErrorForTest(t, c, http.StatusBadRequest, + `{"error":{"message":"Selected model is at capacity.","type":"server_error","code":"`+upstreamCode+`"}}`, + map[string]any{"api_key": "sk-test"}) + + require.Equal(t, http.StatusOK, rec.Code) + events := parseCompactBridgeSSE(t, stripKeepaliveComments(rec.Body.String())) + require.Len(t, events, 1) + require.Equal(t, "response.failed", events[0][0]) + require.Equal(t, wantCode, gjson.Get(events[0][1], "response.error.code").String()) + require.Contains(t, gjson.Get(events[0][1], "response.error.message").String(), "at capacity") + }) + } +}