diff --git a/backend/internal/handler/composite_platform.go b/backend/internal/handler/composite_platform.go index 83f2058356..6765fd79be 100644 --- a/backend/internal/handler/composite_platform.go +++ b/backend/internal/handler/composite_platform.go @@ -116,6 +116,17 @@ func bindRequestedReasoningEffort(c *gin.Context, body []byte, model string) { c.Request = c.Request.WithContext(service.WithRequestedReasoningEffort(c.Request.Context(), *effort)) } +func bindRequestedReasoningEffortWithFields(c *gin.Context, body []byte, model, reasoningEffort, reasoningEffortTop, outputConfigEffort string) { + if c == nil || c.Request == nil { + return + } + effort := service.CanonicalRequestedReasoningEffortWithFields(body, reasoningEffort, reasoningEffortTop, outputConfigEffort, model) + if effort == nil { + return + } + c.Request = c.Request.WithContext(service.WithRequestedReasoningEffort(c.Request.Context(), *effort)) +} + func stampOpenAIRequestedReasoningEffort(result *service.OpenAIForwardResult, c *gin.Context) { if result == nil || result.RequestedReasoningEffort != nil { return @@ -142,6 +153,20 @@ func applyOpenAIReasoningEffortPolicyForRequest(c *gin.Context, apiKey *service. return service.ApplyOpenAIReasoningEffortPolicy(body, maxEffort, mappings, overLimit) } +func applyOpenAIReasoningEffortPolicyForRequestWithFields( + c *gin.Context, + apiKey *service.APIKey, + body []byte, + model, reasoningEffort, reasoningEffortTop, outputConfigEffort string, +) ([]byte, bool, error) { + bindRequestedReasoningEffortWithFields(c, body, strings.TrimSpace(model), reasoningEffort, reasoningEffortTop, outputConfigEffort) + maxEffort, mappings, overLimit, ok := openAIReasoningEffortPolicyForRequest(c, apiKey) + if !ok { + return body, false, nil + } + return service.ApplyOpenAIReasoningEffortPolicy(body, maxEffort, mappings, overLimit) +} + func respondOpenAIReasoningEffortPolicyError(c *gin.Context, err error, write func(*gin.Context, int, string, string)) { if c == nil || err == nil || write == nil { return diff --git a/backend/internal/handler/gateway_inflight_reservation.go b/backend/internal/handler/gateway_inflight_reservation.go index 5928220dc0..10578fbc91 100644 --- a/backend/internal/handler/gateway_inflight_reservation.go +++ b/backend/internal/handler/gateway_inflight_reservation.go @@ -2,6 +2,7 @@ package handler import ( "context" + "unsafe" "github.com/Wei-Shaw/sub2api/internal/service" "github.com/gin-gonic/gin" @@ -13,11 +14,74 @@ type inflightReservationEstimator interface { EstimateInflightReservation(ctx context.Context, apiKey *service.APIKey, req service.InflightEstimateRequest) (float64, bool) } -// requestMaxOutputTokens 从请求体中提取输出 token 上限(兼容 Anthropic / OpenAI Chat / Responses / Gemini)。 +// requestMaxOutputTokens 从请求体中提取输出 token 上限(兼容 Anthropic / OpenAI Chat / Responses / Gemini), +// 单遍零拷贝遍历顶层键,保持 max_tokens → max_completion_tokens → max_output_tokens → generationConfig.maxOutputTokens → generation_config.max_output_tokens 优先级。 func requestMaxOutputTokens(body []byte) int { - for _, path := range []string{"max_tokens", "max_completion_tokens", "max_output_tokens", "generationConfig.maxOutputTokens", "generation_config.max_output_tokens"} { - if v := gjson.GetBytes(body, path); v.Exists() && v.Type == gjson.Number && v.Int() > 0 { - return int(v.Int()) + if len(body) == 0 { + return 0 + } + const ( + maxTokensBit uint8 = 1 << iota + maxCompletionTokensBit + maxOutputTokensBit + genConfigCamelBit + genConfigSnakeBit + allMaxTokenBits = maxTokensBit | maxCompletionTokensBit | maxOutputTokensBit | genConfigCamelBit | genConfigSnakeBit + ) + var seen uint8 + var vals [5]int + root := gjson.Parse(unsafe.String(unsafe.SliceData(body), len(body))) + if !root.IsObject() { + return 0 + } + root.ForEach(func(key, value gjson.Result) bool { + switch key.Str { + case "max_tokens": + if seen&maxTokensBit == 0 { + seen |= maxTokensBit + if value.Type == gjson.Number && value.Int() > 0 { + vals[0] = int(value.Int()) + return false + } + } + case "max_completion_tokens": + if seen&maxCompletionTokensBit == 0 { + seen |= maxCompletionTokensBit + if value.Type == gjson.Number && value.Int() > 0 { + vals[1] = int(value.Int()) + } + } + case "max_output_tokens": + if seen&maxOutputTokensBit == 0 { + seen |= maxOutputTokensBit + if value.Type == gjson.Number && value.Int() > 0 { + vals[2] = int(value.Int()) + } + } + case "generationConfig": + if seen&genConfigCamelBit == 0 { + if v := value.Get("maxOutputTokens"); v.Exists() { + seen |= genConfigCamelBit + if v.Type == gjson.Number && v.Int() > 0 { + vals[3] = int(v.Int()) + } + } + } + case "generation_config": + if seen&genConfigSnakeBit == 0 { + if v := value.Get("max_output_tokens"); v.Exists() { + seen |= genConfigSnakeBit + if v.Type == gjson.Number && v.Int() > 0 { + vals[4] = int(v.Int()) + } + } + } + } + return seen != allMaxTokenBits + }) + for _, v := range vals { + if v > 0 { + return v } } return 0 diff --git a/backend/internal/handler/openai_gateway_handler.go b/backend/internal/handler/openai_gateway_handler.go index 049957cbbe..c72c5f69bc 100644 --- a/backend/internal/handler/openai_gateway_handler.go +++ b/backend/internal/handler/openai_gateway_handler.go @@ -16,6 +16,7 @@ import ( "sync/atomic" "time" "unicode/utf8" + "unsafe" "github.com/Wei-Shaw/sub2api/internal/config" "github.com/Wei-Shaw/sub2api/internal/domain" @@ -471,55 +472,67 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) { h.errorResponse(c, http.StatusBadRequest, "invalid_request_error", "Failed to parse request body") return } + service.MarkOpenAIRequestBodyJSONValidated(c) - // 使用 gjson 只读提取字段做校验,避免完整 Unmarshal - modelResult := gjson.GetBytes(body, "model") - if !modelResult.Exists() || modelResult.Type != gjson.String || modelResult.String() == "" { + // 单次只读扫描顶层校验与路由字段,避免对大请求体重复调用 gjson.GetBytes。 + ingressFields := parseOpenAIResponsesIngressFields(body) + if !ingressFields.ModelValid { h.errorResponse(c, http.StatusBadRequest, "invalid_request_error", "model is required") return } - reqModel := modelResult.String() + reqModel := ingressFields.Model ensureCompositeTargetPlatform(c, apiKey, reqModel) if !openAICompatibleTextTargetAllowed(c, apiKey, reqModel) { h.errorResponse(c, http.StatusBadRequest, "invalid_request_error", "Model is not supported by this OpenAI-compatible endpoint for composite groups") return } - if cappedBody, changed, err := applyOpenAIReasoningEffortPolicyForRequest(c, apiKey, body); err != nil { + ingressBodyChanged := false + if cappedBody, changed, err := applyOpenAIReasoningEffortPolicyForRequestWithFields( + c, apiKey, body, reqModel, + ingressFields.ReasoningEffort, ingressFields.ReasoningEffortTop, ingressFields.OutputConfigEffort, + ); err != nil { respondOpenAIReasoningEffortPolicyError(c, err, h.errorResponse) return } else if changed { body = cappedBody + ingressBodyChanged = true } if normalizedBody, changed := normalizeCodexUntrustedContext(body); changed { body = normalizedBody + ingressBodyChanged = true reqLog.Info("openai.codex_untrusted_context_normalized", zap.String("normalization", "call_output_to_user_message"), ) } if normalizedBody, changed := normalizeCodexAutomationBootstrap(body); changed { body = normalizedBody + ingressBodyChanged = true reqLog.Info("openai.codex_automation_bootstrap_normalized", zap.String("normalization", "call_output_to_user_message"), ) } if normalizedBody, changed := normalizeCodexDelegationBootstrap(body); changed { body = normalizedBody + ingressBodyChanged = true reqLog.Info("openai.codex_delegation_bootstrap_normalized", zap.String("normalization", "call_output_to_user_message"), ) } + if ingressBodyChanged { + ingressFields = parseOpenAIResponsesIngressFields(body) + } - reqStream, ok := parseOpenAICompatibleStream(body) - if !ok { + if !ingressFields.StreamValid { h.errorResponse(c, http.StatusBadRequest, "invalid_request_error", invalidStreamFieldTypeMessage) return } - if _, err := service.ValidateOpenAIServiceTierField(body); err != nil { + reqStream := ingressFields.Stream + if _, err := service.ValidateOpenAIServiceTierResult(ingressFields.ServiceTier); err != nil { h.errorResponse(c, http.StatusBadRequest, "invalid_request_error", err.Error()) return } reqLog = reqLog.With(zap.String("model", reqModel), zap.Bool("stream", reqStream)) - previousResponseID := strings.TrimSpace(gjson.GetBytes(body, "previous_response_id").String()) + previousResponseID := ingressFields.PreviousResponseID if previousResponseID != "" { previousResponseIDKind := service.ClassifyOpenAIPreviousResponseIDKind(previousResponseID) reqLog = reqLog.With( @@ -564,10 +577,10 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) { return } - // 使用 IsExplicitImageGenerationIntent 排除被动 image_gen namespace 声明。 + // 使用 IsExplicitImageGenerationIntentValidated 排除被动 image_gen namespace 声明。 // Codex 在所有请求中被动声明 image_gen namespace,宽泛检测会导致禁了生图的 // 分组中所有 Codex 请求被 403(#4447),并误占生图并发槽位。 - imageIntent := service.IsExplicitImageGenerationIntent("/v1/responses", reqModel, body) + imageIntent := service.IsExplicitImageGenerationIntentValidated("/v1/responses", reqModel, body) if imageIntent && !service.GroupAllowsImageGeneration(apiKey.Group) { h.errorResponse(c, http.StatusForbidden, "permission_error", service.ImageGenerationPermissionMessage()) return @@ -633,7 +646,11 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) { } // 余额模式在途预留:防止并发请求在预检时看到同一份余额而集体透支。 - inflightRelease, err := reserveInflightBalance(c, h.billingCacheService, h.gatewayService, apiKey, subscription, tokenInflightEstimate(reqModel, body)) + var inflightEstimate service.InflightEstimateRequest + if h.billingCacheService != nil && h.billingCacheService.InflightReservationEnabled() { + inflightEstimate = tokenInflightEstimate(reqModel, body) + } + inflightRelease, err := reserveInflightBalance(c, h.billingCacheService, h.gatewayService, apiKey, subscription, inflightEstimate) if err != nil { reqLog.Info("openai.inflight_reservation_rejected", zap.Error(err)) status, code, message, retryAfter := billingErrorDetails(err) @@ -686,6 +703,18 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) { pricingCtx, pricingAt := h.gatewayService.WithOpenAIRequestPricingContext(c.Request.Context(), apiKey.GroupID) c.Request = c.Request.WithContext(pricingCtx) + var ( + requestPayloadHashComputed bool + requestPayloadHashValue string + ) + getRequestPayloadHash := func() string { + if !requestPayloadHashComputed { + requestPayloadHashValue = service.HashUsageRequestPayload(body) + requestPayloadHashComputed = true + } + return requestPayloadHashValue + } + for { // Streaming Forward intentionally detaches the upstream request so usage can // be drained after a disconnect. Re-check the client context before every @@ -832,11 +861,9 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) { if h.handleForwardRequestBodyMemoryOverload(c, err, streamStarted) { return } - var cyberBlockBodyHTTP []byte if service.GetOpsCyberPolicy(c) != nil { - cyberBlockBodyHTTP = sessionHashBody + h.recordCyberPolicyIfMarked(c, apiKey, account, subscription, reqModel, err != nil, sessionHashBody, clientRequestedUsageFields(c, channelMapping, reqModel, ""), getRequestPayloadHash()) } - h.recordCyberPolicyIfMarked(c, apiKey, account, subscription, reqModel, err != nil, cyberBlockBodyHTTP, clientRequestedUsageFields(c, channelMapping, reqModel, ""), service.HashUsageRequestPayload(body)) forwardDurationMs := time.Since(forwardStart).Milliseconds() upstreamLatencyMs, _ := getContextInt64(c, service.OpsUpstreamLatencyMsKey) responseLatencyMs := forwardDurationMs @@ -856,7 +883,7 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) { stampOpenAIRequestedReasoningEffort(res, c) userAgent := c.GetHeader("User-Agent") clientIP := ip.GetClientIP(c) - requestPayloadHash := service.HashUsageRequestPayload(body) + requestPayloadHash := getRequestPayloadHash() inboundEndpoint := GetInboundEndpoint(c) upstreamEndpoint := resolveOpenAIUpstreamEndpoint(c, account, res) quotaPlatform := service.QuotaPlatform(c.Request.Context(), apiKey) @@ -1699,7 +1726,99 @@ func (h *OpenAIGatewayHandler) ensureAnthropicErrorResponse(c *gin.Context, stre return true } +type openAIResponsesIngressFields struct { + Model string + ModelValid bool + Stream bool + StreamValid bool + ServiceTier gjson.Result + PreviousResponseID string + ReasoningEffort string + ReasoningEffortTop string + OutputConfigEffort string +} + +// parseOpenAIResponsesIngressFields 单次只读扫描 /v1/responses 顶层入口字段, +// 提取出的字符串全部 clone 断开对原始请求体的引用;ServiceTier 仅在本次同步校验期间使用。 +func parseOpenAIResponsesIngressFields(body []byte) openAIResponsesIngressFields { + fields := openAIResponsesIngressFields{StreamValid: true} + if len(body) == 0 { + return fields + } + root := gjson.Parse(unsafe.String(unsafe.SliceData(body), len(body))) + if !root.IsObject() { + return fields + } + const ( + seenModel uint8 = 1 << iota + seenStream + seenServiceTier + seenPrevRespID + seenReasoning + seenReasoningTop + seenOutputConfig + seenAll = seenModel | seenStream | seenServiceTier | seenPrevRespID | + seenReasoning | seenReasoningTop | seenOutputConfig + ) + var seen uint8 + root.ForEach(func(key, value gjson.Result) bool { + switch key.Str { + case "model": + if seen&seenModel == 0 { + seen |= seenModel + if value.Type == gjson.String && value.String() != "" { + fields.ModelValid = true + fields.Model = strings.Clone(value.String()) + } + } + case "stream": + if seen&seenStream == 0 { + seen |= seenStream + if value.Type != gjson.True && value.Type != gjson.False { + fields.StreamValid = false + } else { + fields.Stream = value.Bool() + } + } + case "service_tier": + if seen&seenServiceTier == 0 { + seen |= seenServiceTier + fields.ServiceTier = value + } + case "previous_response_id": + if seen&seenPrevRespID == 0 { + seen |= seenPrevRespID + fields.PreviousResponseID = strings.Clone(strings.TrimSpace(value.String())) + } + case "reasoning": + if seen&seenReasoning == 0 { + if effort := value.Get("effort"); effort.Exists() { + seen |= seenReasoning + fields.ReasoningEffort = strings.Clone(strings.TrimSpace(effort.String())) + } + } + case "reasoning_effort": + if seen&seenReasoningTop == 0 { + seen |= seenReasoningTop + fields.ReasoningEffortTop = strings.Clone(strings.TrimSpace(value.String())) + } + case "output_config": + if seen&seenOutputConfig == 0 { + if effort := value.Get("effort"); effort.Exists() { + seen |= seenOutputConfig + fields.OutputConfigEffort = strings.Clone(strings.TrimSpace(effort.String())) + } + } + } + return seen != seenAll + }) + return fields +} + func (h *OpenAIGatewayHandler) validateFunctionCallOutputRequest(c *gin.Context, body []byte, reqLog *zap.Logger) bool { + if !bytes.Contains(body, []byte("function_call_output")) && !service.JSONMayEscapePlainASCII(body) { + return true + } if !gjson.GetBytes(body, `input.#(type=="function_call_output")`).Exists() { return true } diff --git a/backend/internal/handler/openai_responses_ingress_fields_test.go b/backend/internal/handler/openai_responses_ingress_fields_test.go new file mode 100644 index 0000000000..42ff7cfdcb --- /dev/null +++ b/backend/internal/handler/openai_responses_ingress_fields_test.go @@ -0,0 +1,118 @@ +package handler + +import ( + "testing" + + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/stretchr/testify/require" +) + +func TestParseOpenAIResponsesIngressFields(t *testing.T) { + body := []byte(`{ + "model": "gpt-6.2-astra", + "stream": true, + "service_tier": "fast", + "previous_response_id": " resp_abc ", + "reasoning": {"effort": " medium "}, + "reasoning_effort": " high ", + "output_config": {"effort": " low "} + }`) + fields := parseOpenAIResponsesIngressFields(body) + require.True(t, fields.ModelValid) + require.Equal(t, "gpt-6.2-astra", fields.Model) + require.True(t, fields.StreamValid) + require.True(t, fields.Stream) + require.Equal(t, "resp_abc", fields.PreviousResponseID) + require.Equal(t, "medium", fields.ReasoningEffort) + require.Equal(t, "high", fields.ReasoningEffortTop) + require.Equal(t, "low", fields.OutputConfigEffort) + + tier, err := service.ValidateOpenAIServiceTierResult(fields.ServiceTier) + require.NoError(t, err) + require.Equal(t, "priority", tier) + + // Invalid stream type. + badStream := parseOpenAIResponsesIngressFields([]byte(`{"model":"gpt-6.2-astra","stream":"true"}`)) + require.True(t, badStream.ModelValid) + require.False(t, badStream.StreamValid) + + // Missing/non-string model. + missingModel := parseOpenAIResponsesIngressFields([]byte(`{"stream":false}`)) + require.False(t, missingModel.ModelValid) + require.True(t, missingModel.StreamValid) + require.False(t, missingModel.Stream) + + // Escaped keys. + escaped := parseOpenAIResponsesIngressFields([]byte(`{"\u006dodel":"gpt-6.2-astra","\u0073tream":true,"service_tier":"invalid"}`)) + require.True(t, escaped.ModelValid) + require.Equal(t, "gpt-6.2-astra", escaped.Model) + require.True(t, escaped.StreamValid) + require.True(t, escaped.Stream) + _, err = service.ValidateOpenAIServiceTierResult(escaped.ServiceTier) + require.Error(t, err) + + // Non-object root. + arr := parseOpenAIResponsesIngressFields([]byte(`[{"model":"x"}]`)) + require.False(t, arr.ModelValid) + require.True(t, arr.StreamValid) + + // Duplicate parent keys keep scanning until nested effort exists. + dupParent := parseOpenAIResponsesIngressFields([]byte(`{"model":"gpt-6.2-astra","reasoning":{},"reasoning":{"effort":"xhigh"},"output_config":null,"output_config":{"effort":"low"}}`)) + require.Equal(t, "xhigh", dupParent.ReasoningEffort) + require.Equal(t, "low", dupParent.OutputConfigEffort) +} + +func TestRequestMaxOutputTokensSinglePassPriority(t *testing.T) { + tests := []struct { + name string + body string + want int + }{ + { + name: "max_tokens wins even when last", + body: `{"generation_config":{"max_output_tokens":50},"generationConfig":{"maxOutputTokens":40},"max_output_tokens":30,"max_completion_tokens":20,"max_tokens":10}`, + want: 10, + }, + { + name: "max_completion_tokens wins when max_tokens absent or non-positive", + body: `{"max_tokens":0,"max_output_tokens":30,"max_completion_tokens":20}`, + want: 20, + }, + { + name: "max_output_tokens wins over generationConfig", + body: `{"generationConfig":{"maxOutputTokens":40},"max_output_tokens":30}`, + want: 30, + }, + { + name: "generationConfig camelCase wins over snake_case", + body: `{"generation_config":{"max_output_tokens":50},"generationConfig":{"maxOutputTokens":40}}`, + want: 40, + }, + { + name: "generation_config snake_case fallback", + body: `{"generation_config":{"max_output_tokens":50}}`, + want: 50, + }, + { + name: "absent or non-object returns zero", + body: `[{"max_tokens":10}]`, + want: 0, + }, + { + name: "duplicate parent keys keep scanning for nested maxOutputTokens", + body: `{"generationConfig":null,"generationConfig":{"maxOutputTokens":40},"generation_config":{"max_output_tokens":50}}`, + want: 40, + }, + { + name: "duplicate snake_case parent keys keep scanning for nested max_output_tokens", + body: `{"generation_config":{},"generation_config":{"max_output_tokens":55}}`, + want: 55, + }, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + require.Equal(t, tc.want, requestMaxOutputTokens([]byte(tc.body))) + }) + } +} diff --git a/backend/internal/service/image_generation_intent.go b/backend/internal/service/image_generation_intent.go index 9593213da3..1a237fbc35 100644 --- a/backend/internal/service/image_generation_intent.go +++ b/backend/internal/service/image_generation_intent.go @@ -82,6 +82,12 @@ func IsExplicitImageGenerationIntent(endpoint string, requestedModel string, bod return openAIImageGenerationIntent(endpoint, requestedModel, body, true, true) } +// IsExplicitImageGenerationIntentValidated 与 IsExplicitImageGenerationIntent 语义一致, +// 要求调用方已确认 body 是合法 JSON,跳过重复的 gjson.ValidBytes 全量校验。 +func IsExplicitImageGenerationIntentValidated(endpoint string, requestedModel string, body []byte) bool { + return openAIImageGenerationIntent(endpoint, requestedModel, body, true, false) +} + // IsImageGenerationIntentForPlatform applies platform-specific intent rules. // // Codex advertises the image_gen namespace on ordinary Responses requests so @@ -303,9 +309,10 @@ func openAIRequestBodyHasImageGenerationDeclaration(body []byte) bool { if len(body) == 0 || !openAIBodyMayDeclareImageGeneration(body) || !gjson.ValidBytes(body) { return false } - return openAIJSONToolsContainImageGeneration(gjson.GetBytes(body, "tools")) || - openAIJSONInputContainsImageGenTool(gjson.GetBytes(body, "input")) || - openAIJSONToolChoiceSelectsImageGeneration(gjson.GetBytes(body, "tool_choice")) + root := parseRawJSONView(body) + return openAIJSONToolsContainImageGeneration(root.Get("tools")) || + openAIJSONInputContainsImageGenTool(root.Get("input")) || + openAIJSONToolChoiceSelectsImageGeneration(root.Get("tool_choice")) } func openAIRequestBodyImageGenerationToolNeedsNormalization(body []byte) bool { diff --git a/backend/internal/service/openai_canonical_seed_json.go b/backend/internal/service/openai_canonical_seed_json.go new file mode 100644 index 0000000000..4cc5e0aee6 --- /dev/null +++ b/backend/internal/service/openai_canonical_seed_json.go @@ -0,0 +1,493 @@ +package service + +import ( + "bytes" + "cmp" + "encoding/json" + "io" + "slices" + "unicode" + "unsafe" +) + +const ( + canonicalSeedJSONMaxDepth = 1000 + canonicalSeedJSONMinScanBudget = 64 << 10 + canonicalSeedJSONScanBudgetMul = 8 +) + +// writeCanonicalSeedJSON 将 JSON 文本按与 encoding/json (Unmarshal 到 any 再 Marshal) +// 字节等价的规范形态流式写入 w,避免为内联 base64 图片等大字符串分配中间副本。 +// 输入不是合法 JSON、嵌套超过上限或嵌套对象重扫超出字节预算时返回 false,调用方回退到完整解码路径。 +func writeCanonicalSeedJSON(w io.Writer, raw string) bool { + if len(raw) == 0 { + return true + } + pos := skipCanonicalJSONSpace(raw, 0) + if pos >= len(raw) { + return false + } + budget := max(len(raw)*canonicalSeedJSONScanBudgetMul, canonicalSeedJSONMinScanBudget) + end, ok := streamCanonicalJSONValue(w, raw, pos, 0, &budget) + if !ok { + return false + } + end = skipCanonicalJSONSpace(raw, end) + return end == len(raw) +} + +func skipCanonicalJSONSpace(raw string, pos int) int { + for pos < len(raw) { + switch raw[pos] { + case ' ', '\t', '\n', '\r': + pos++ + default: + return pos + } + } + return pos +} + +func writeStringNoCopy(w io.Writer, s string) { + if len(s) == 0 { + return + } + _, _ = w.Write(unsafe.Slice(unsafe.StringData(s), len(s))) +} + +// scanCanonicalJSONString 扫描从 raw[start](必须是 '"')开始的 JSON 字符串。 +// plain 为 true 表示区间内不含转义、控制字节、非 ASCII 字节以及 HTML 转义字符(<, >, &), +// 因此 raw[start:end] 与 encoding/json.Marshal 编码结果字节完全一致。 +func scanCanonicalJSONString(raw string, start int) (end int, plain bool, ok bool) { + if start >= len(raw) || raw[start] != '"' { + return 0, false, false + } + plain = true + i := start + 1 + for i < len(raw) { + c := raw[i] + if c == '"' { + return i + 1, plain, true + } + if c == '\\' { + plain = false + i += 2 + if i > len(raw) { + return 0, false, false + } + continue + } + if c < 0x20 { + return 0, false, false + } + if c >= 0x80 || c == '<' || c == '>' || c == '&' { + plain = false + } + i++ + } + return 0, false, false +} + +func isCanonicalJSONDelimiter(c byte) bool { + switch c { + case ' ', '\t', '\n', '\r', ',', ']', '}': + return true + default: + return false + } +} + +func scanCanonicalJSONNumber(raw string, start int) (int, bool) { + end := start + for end < len(raw) && !isCanonicalJSONDelimiter(raw[end]) { + end++ + } + if end == start { + return 0, false + } + return end, true +} + +func scanCanonicalJSONLiteral(raw string, start int, lit string) (int, bool) { + end := start + len(lit) + if end > len(raw) || raw[start:end] != lit { + return 0, false + } + if end < len(raw) && !isCanonicalJSONDelimiter(raw[end]) { + return 0, false + } + return end, true +} + +// scanCanonicalJSONValue 在不分配值副本的前提下验证并跳过一个 JSON 值,返回其字节区间。 +// budget 限制深层嵌套对象下的累计重扫字节量,超额立即中止并交由调用方走线性回退路径。 +func scanCanonicalJSONValue(raw string, pos int, depth int, budget *int) (valStart, valEnd int, plainStr bool, ok bool) { + if depth > canonicalSeedJSONMaxDepth || *budget < 0 { + return 0, 0, false, false + } + skipSpace := func(p int) (int, bool) { + next := skipCanonicalJSONSpace(raw, p) + *budget -= next - p + return next, *budget >= 0 + } + var withinBudget bool + pos, withinBudget = skipSpace(pos) + if !withinBudget || pos >= len(raw) { + return 0, 0, false, false + } + charge := func(n int) bool { + *budget -= n + return *budget >= 0 + } + switch raw[pos] { + case '"': + end, plain, valid := scanCanonicalJSONString(raw, pos) + if !valid || !charge(end-pos) { + return 0, 0, false, false + } + return pos, end, plain, true + case '{': + if !charge(1) { + return 0, 0, false, false + } + i, within := skipSpace(pos + 1) + if !within { + return 0, 0, false, false + } + if i < len(raw) && raw[i] == '}' { + if !charge(1) { + return 0, 0, false, false + } + return pos, i + 1, false, true + } + for { + keyEnd, _, valid := scanCanonicalJSONString(raw, i) + if !valid || !charge(keyEnd-i) { + return 0, 0, false, false + } + i, within = skipSpace(keyEnd) + if !within || i >= len(raw) || raw[i] != ':' || !charge(1) { + return 0, 0, false, false + } + _, ve, _, valid := scanCanonicalJSONValue(raw, i+1, depth+1, budget) + if !valid { + return 0, 0, false, false + } + i, within = skipSpace(ve) + if !within || i >= len(raw) { + return 0, 0, false, false + } + if raw[i] == '}' { + if !charge(1) { + return 0, 0, false, false + } + return pos, i + 1, false, true + } + if raw[i] != ',' || !charge(1) { + return 0, 0, false, false + } + i, within = skipSpace(i + 1) + if !within { + return 0, 0, false, false + } + } + case '[': + if !charge(1) { + return 0, 0, false, false + } + i, within := skipSpace(pos + 1) + if !within { + return 0, 0, false, false + } + if i < len(raw) && raw[i] == ']' { + if !charge(1) { + return 0, 0, false, false + } + return pos, i + 1, false, true + } + for { + _, ve, _, valid := scanCanonicalJSONValue(raw, i, depth+1, budget) + if !valid { + return 0, 0, false, false + } + i, within = skipSpace(ve) + if !within || i >= len(raw) { + return 0, 0, false, false + } + if raw[i] == ']' { + if !charge(1) { + return 0, 0, false, false + } + return pos, i + 1, false, true + } + if raw[i] != ',' || !charge(1) { + return 0, 0, false, false + } + i, within = skipSpace(i + 1) + if !within { + return 0, 0, false, false + } + } + case 't': + end, valid := scanCanonicalJSONLiteral(raw, pos, "true") + if !valid || !charge(end-pos) { + return 0, 0, false, false + } + return pos, end, false, true + case 'f': + end, valid := scanCanonicalJSONLiteral(raw, pos, "false") + if !valid || !charge(end-pos) { + return 0, 0, false, false + } + return pos, end, false, true + case 'n': + end, valid := scanCanonicalJSONLiteral(raw, pos, "null") + if !valid || !charge(end-pos) { + return 0, 0, false, false + } + return pos, end, false, true + default: + if raw[pos] == '-' || (raw[pos] >= '0' && raw[pos] <= '9') { + end, valid := scanCanonicalJSONNumber(raw, pos) + if !valid || !charge(end-pos) { + return 0, 0, false, false + } + return pos, end, false, true + } + return 0, 0, false, false + } +} + +type canonicalJSONObjField struct { + key string + encKey string + valStart int + valEnd int + plainStr bool + order int +} + +func streamCanonicalJSONValue(w io.Writer, raw string, pos int, depth int, budget *int) (int, bool) { + if depth > canonicalSeedJSONMaxDepth || *budget < 0 { + return 0, false + } + pos = skipCanonicalJSONSpace(raw, pos) + if pos >= len(raw) { + return 0, false + } + switch raw[pos] { + case '"': + end, plain, valid := scanCanonicalJSONString(raw, pos) + if !valid { + return 0, false + } + if plain { + writeStringNoCopy(w, raw[pos:end]) + return end, true + } + var s string + if err := json.Unmarshal(unsafe.Slice(unsafe.StringData(raw[pos:end]), end-pos), &s); err != nil { + return 0, false + } + encoded, err := json.Marshal(s) + if err != nil { + return 0, false + } + _, _ = w.Write(encoded) + return end, true + case '{': + i := skipCanonicalJSONSpace(raw, pos+1) + if i >= len(raw) { + return 0, false + } + if raw[i] == '}' { + writeStringNoCopy(w, "{}") + return i + 1, true + } + var fields []canonicalJSONObjField + order := 0 + for { + keyEnd, keyPlain, valid := scanCanonicalJSONString(raw, i) + if !valid { + return 0, false + } + var decodedKey, encKey string + if keyPlain { + decodedKey = raw[i+1 : keyEnd-1] + encKey = raw[i:keyEnd] + } else { + if err := json.Unmarshal(unsafe.Slice(unsafe.StringData(raw[i:keyEnd]), keyEnd-i), &decodedKey); err != nil { + return 0, false + } + enc, err := json.Marshal(decodedKey) + if err != nil { + return 0, false + } + encKey = string(enc) + } + i = skipCanonicalJSONSpace(raw, keyEnd) + if i >= len(raw) || raw[i] != ':' { + return 0, false + } + vs, ve, plainStr, valid := scanCanonicalJSONValue(raw, i+1, depth+1, budget) + if !valid { + return 0, false + } + fields = append(fields, canonicalJSONObjField{ + key: decodedKey, + encKey: encKey, + valStart: vs, + valEnd: ve, + plainStr: plainStr, + order: order, + }) + order++ + i = skipCanonicalJSONSpace(raw, ve) + if i >= len(raw) { + return 0, false + } + if raw[i] == '}' { + i++ + break + } + if raw[i] != ',' { + return 0, false + } + i = skipCanonicalJSONSpace(raw, i+1) + } + // 按解码后的键名升序排序;若出现同名重复键,直接交由调用方回退到 encoding/json, + // 避免被覆盖字段中的非法数字或转义绕过严格校验。 + slices.SortFunc(fields, func(a, b canonicalJSONObjField) int { + if c := cmp.Compare(a.key, b.key); c != 0 { + return c + } + return cmp.Compare(a.order, b.order) + }) + for idx := 0; idx+1 < len(fields); idx++ { + if fields[idx].key == fields[idx+1].key { + return 0, false + } + } + writeStringNoCopy(w, "{") + for idx, f := range fields { + if idx > 0 { + writeStringNoCopy(w, ",") + } + writeStringNoCopy(w, f.encKey) + writeStringNoCopy(w, ":") + if f.plainStr { + writeStringNoCopy(w, raw[f.valStart:f.valEnd]) + } else { + if _, ok := streamCanonicalJSONValue(w, raw, f.valStart, depth+1, budget); !ok { + return 0, false + } + } + } + writeStringNoCopy(w, "}") + return i, true + case '[': + i := skipCanonicalJSONSpace(raw, pos+1) + if i >= len(raw) { + return 0, false + } + writeStringNoCopy(w, "[") + if raw[i] == ']' { + writeStringNoCopy(w, "]") + return i + 1, true + } + first := true + for { + if !first { + writeStringNoCopy(w, ",") + } + first = false + ve, valid := streamCanonicalJSONValue(w, raw, i, depth+1, budget) + if !valid { + return 0, false + } + i = skipCanonicalJSONSpace(raw, ve) + if i >= len(raw) { + return 0, false + } + if raw[i] == ']' { + writeStringNoCopy(w, "]") + return i + 1, true + } + if raw[i] != ',' { + return 0, false + } + i = skipCanonicalJSONSpace(raw, i+1) + } + case 't': + end, valid := scanCanonicalJSONLiteral(raw, pos, "true") + if !valid { + return 0, false + } + writeStringNoCopy(w, "true") + return end, true + case 'f': + end, valid := scanCanonicalJSONLiteral(raw, pos, "false") + if !valid { + return 0, false + } + writeStringNoCopy(w, "false") + return end, true + case 'n': + end, valid := scanCanonicalJSONLiteral(raw, pos, "null") + if !valid { + return 0, false + } + writeStringNoCopy(w, "null") + return end, true + default: + if raw[pos] == '-' || (raw[pos] >= '0' && raw[pos] <= '9') { + end, valid := scanCanonicalJSONNumber(raw, pos) + if !valid { + return 0, false + } + var num any + if err := json.Unmarshal(unsafe.Slice(unsafe.StringData(raw[pos:end]), end-pos), &num); err != nil { + return 0, false + } + encoded, err := json.Marshal(num) + if err != nil { + return 0, false + } + _, _ = w.Write(encoded) + return end, true + } + return 0, false + } +} + +// trimTrailingSpaceWriter 在流式写入哈希器时暂存末尾空白段,仅在后续出现非空白字符时才刷入底层 writer, +// 使流式哈希结果与 strings.TrimSpace(fullSeed) 对齐,且不在内存中拼接整段大字符串。 +// 调用方每次 Write 传入完整的 UTF-8 片段,起始前缀已保证不含前导空白。 +type trimTrailingSpaceWriter struct { + dst io.Writer + pending []byte +} + +func (w *trimTrailingSpaceWriter) Write(p []byte) (int, error) { + if len(p) == 0 { + return 0, nil + } + trimmed := bytes.TrimRightFunc(p, unicode.IsSpace) + if len(trimmed) == 0 { + w.pending = append(w.pending, p...) + return len(p), nil + } + if len(w.pending) > 0 { + if _, err := w.dst.Write(w.pending); err != nil { + return 0, err + } + w.pending = w.pending[:0] + } + if _, err := w.dst.Write(trimmed); err != nil { + return 0, err + } + if len(trimmed) < len(p) { + w.pending = append(w.pending, p[len(trimmed):]...) + } + return len(p), nil +} diff --git a/backend/internal/service/openai_canonical_seed_json_test.go b/backend/internal/service/openai_canonical_seed_json_test.go new file mode 100644 index 0000000000..92f56ad30c --- /dev/null +++ b/backend/internal/service/openai_canonical_seed_json_test.go @@ -0,0 +1,152 @@ +package service + +import ( + "bytes" + "encoding/json" + "strings" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestWriteCanonicalSeedJSONMatchesNormalizeCompatSeedJSON(t *testing.T) { + t.Parallel() + + cases := []struct { + name string + raw string + wantOK bool + }{ + {"empty", "", true}, + {"plain_string", `"hello world"`, true}, + {"html_and_unicode_string", `"a\u003c\u2028\u2029中文\n\t\"\\"`, true}, + {"numbers", `[0, -0, 1.0, 1e2, -3.5e-2, 42]`, true}, + {"literals", `[true, false, null]`, true}, + {"sorted_object", `{"z": 1, "a": {"d": true, "b": "val"}, "m": [3, 2, 1]}`, true}, + {"escaped_keys", `{"\u0062": 1, "a & 中文"},{"type":"input_image","image_url":"data:image/jpeg;base64,ABCD1234+/=="}]}]}`), + []byte(`{"model":"gpt-6.2-astra","tools":[{"type":"function","name":"f","parameters":{"b":1.0,"a":true}}],"input":[{"type":"input_text","text":"trailing space "}]}`), + []byte(`{"model":"gpt-6.2-astra","input":[{"role":"user","content":{"a":1,"a":2}}]}`), + []byte(`{"model":"gpt-6.2-astra","input":[{"role":"user","content":{"broken":1,}}]}`), + []byte(`prefix{"model":"gpt-6.2-astra","messages":[{"role":"user","content":"hello"}]}suffix`), + } + + for _, isGrok := range []bool{false, true} { + for i, body := range bodies { + gotCur, gotLegacy := deriveOpenAIBodySessionHashes(body, isGrok) + + // 按参考路径计算对照值 + var explicitID string + if len(body) > 0 { + explicitID = strings.TrimSpace(openAIRequestPayloadView(body).Get("prompt_cache_key").String()) + } + if explicitID == "" && isGrok && len(body) > 0 { + explicitID = grokPreviousResponseSessionSeed(body) + } + seed := explicitID + if seed == "" && len(body) > 0 { + seed = deriveOpenAIContentSessionSeed(body) + } + if seed != "" && isGrok { + seed = grokStickyAffinitySeed(seed, body) + } + wantCur, wantLegacy := deriveOpenAISessionHashes(seed) + + require.Equalf(t, wantCur, gotCur, "case %d isGrok=%v currentHash mismatch", i, isGrok) + require.Equalf(t, wantLegacy, gotLegacy, "case %d isGrok=%v legacyHash mismatch", i, isGrok) + } + } +} + +func TestWriteCanonicalSeedJSONDeepObjectExceedsScanBudget(t *testing.T) { + t.Parallel() + + // 深层嵌套对象包裹大字符串应及时触发重扫预算上限,避免平方级扫描放大。 + const depth = 128 + var b strings.Builder + for i := 0; i < depth; i++ { + _, _ = b.WriteString(`{"a":`) + } + _ = b.WriteByte('"') + _, _ = b.WriteString(strings.Repeat("A", 128<<10)) + _ = b.WriteByte('"') + for i := 0; i < depth; i++ { + _ = b.WriteByte('}') + } + + var out bytes.Buffer + require.False(t, writeCanonicalSeedJSON(&out, b.String())) + + // 深层嵌套对象包裹大段空白同样触发预算上限。 + var ws strings.Builder + for i := 0; i < depth; i++ { + _, _ = ws.WriteString(`{"a":`) + } + _ = ws.WriteByte('1') + _, _ = ws.WriteString(strings.Repeat(" ", 128<<10)) + for i := 0; i < depth; i++ { + _ = ws.WriteByte('}') + } + out.Reset() + require.False(t, writeCanonicalSeedJSON(&out, ws.String())) +} + +func TestDeriveOpenAIBodySessionHashesLargeImageZeroCopy(t *testing.T) { + img := strings.Repeat("ABCD1234+/ab", (4<<20)/12) + body := []byte(`{"model":"gpt-6.2-astra","stream":true,"input":[{"type":"message","role":"user","content":[{"type":"input_text","text":"analyze"},{"type":"input_image","image_url":"data:image/jpeg;base64,` + img + `"}]}]}`) + + gotCur, gotLegacy := deriveOpenAIBodySessionHashes(body, false) + wantCur, wantLegacy := deriveOpenAISessionHashes(deriveOpenAIContentSessionSeed(body)) + require.Equal(t, wantCur, gotCur) + require.Equal(t, wantLegacy, gotLegacy) + require.NotEmpty(t, gotCur) + + res := testing.Benchmark(func(b *testing.B) { + b.ReportAllocs() + for i := 0; i < b.N; i++ { + c, l := deriveOpenAIBodySessionHashes(body, false) + if c == "" || l == "" { + b.Fatal("empty hash") + } + } + }) + require.Less(t, res.AllocedBytesPerOp(), int64(16<<10), "流式内容会话哈希在大图输入上应远低于请求体大小") +} diff --git a/backend/internal/service/openai_compact_body_signal.go b/backend/internal/service/openai_compact_body_signal.go index c9af18b879..a5024f5013 100644 --- a/backend/internal/service/openai_compact_body_signal.go +++ b/backend/internal/service/openai_compact_body_signal.go @@ -26,6 +26,21 @@ func MarkOpenAINativeCompactionV2(c *gin.Context) { } } +// normalizeCompactionTriggerInputOrderValidated 在调用方已确认 body 为合法 JSON 对象时 +// 跳过无 compaction_trigger 路径上的重复全量 gjson.ValidBytes 校验。 +func normalizeCompactionTriggerInputOrderValidated(body []byte, validated bool) ([]byte, bool, error) { + if len(body) == 0 { + return body, false, nil + } + if validated && !JSONMayEscapePlainASCII(body) && !bytes.Contains(body, compactionTriggerToken) { + trimmed := bytes.TrimLeft(body, " \t\r\n") + if len(trimmed) > 0 && trimmed[0] == '{' { + return body, false, nil + } + } + return NormalizeCompactionTriggerInputOrder(body) +} + // NormalizeCompactionTriggerInputOrder keeps a single compaction trigger as // the final Responses input item, as required by the upstream v2 wire format. func NormalizeCompactionTriggerInputOrder(body []byte) ([]byte, bool, error) { diff --git a/backend/internal/service/openai_content_session_seed.go b/backend/internal/service/openai_content_session_seed.go index 8524f6d669..42ae142549 100644 --- a/backend/internal/service/openai_content_session_seed.go +++ b/backend/internal/service/openai_content_session_seed.go @@ -2,9 +2,14 @@ package service import ( "bytes" + "crypto/sha256" + "encoding/hex" "encoding/json" + "fmt" + "io" "strings" + "github.com/cespare/xxhash/v2" "github.com/tidwall/gjson" ) @@ -16,43 +21,65 @@ const contentSessionSeedPrefix = "compat_cs_" // only from request fields that remain stable across independent prompts. const contentStablePrefixSessionSeedPrefix = "compat_csp_" -// deriveOpenAIContentSessionSeed builds a stable session seed from an -// OpenAI-format request body. Only fields constant across conversation turns -// are included: model, tools/functions definitions, the leading system/developer -// prompt prefix, instructions (Responses API), and the first user message. -// Supports both Chat Completions (messages) and Responses API (input). -func deriveOpenAIContentSessionSeed(body []byte) string { - if len(body) == 0 { - return "" - } +type openAISessionRootFields struct { + eventType gjson.Result + response gjson.Result + promptCacheKey gjson.Result + previousResponseID gjson.Result + model gjson.Result + tools gjson.Result + functions gjson.Result + instructions gjson.Result + messages gjson.Result + input gjson.Result +} - const ( - modelField = iota - toolsField - functionsField - instructionsField - messagesField - inputField - contentSessionSeedFieldCount - allContentSessionSeedFields = 1< ' ' { + directRoot = false + } + } + if foundRoot { + break } } - return "" + if !foundRoot { + return openAISessionRootFields{}, false, false + } -scanRoot: + const ( + typeBit uint16 = 1 << iota + responseBit + promptCacheKeyBit + previousResponseIDBit + modelBit + toolsBit + functionsBit + instructionsBit + messagesBit + inputBit + allSessionRootBits = typeBit | responseBit | promptCacheKeyBit | previousResponseIDBit | + modelBit | toolsBit | functionsBit | instructionsBit | messagesBit | inputBit + ) + + var seen uint16 nextKeyOffset := 1 parseRawJSONView(root).ForEach(func(key, value gjson.Result) bool { if key.Index < nextKeyOffset || key.Index > len(root) { @@ -65,57 +92,318 @@ scanRoot: } nextKeyOffset = value.Index + len(value.Raw) - field := -1 switch key.Str { + case "type": + if seen&typeBit == 0 { + fields.eventType = value + seen |= typeBit + } + case "response": + if seen&responseBit == 0 { + fields.response = value + seen |= responseBit + } + case "prompt_cache_key": + if seen&promptCacheKeyBit == 0 { + fields.promptCacheKey = value + seen |= promptCacheKeyBit + } + case "previous_response_id": + if seen&previousResponseIDBit == 0 { + fields.previousResponseID = value + seen |= previousResponseIDBit + } case "model": - field = modelField + if seen&modelBit == 0 { + fields.model = value + seen |= modelBit + } case "tools": - field = toolsField + if seen&toolsBit == 0 { + fields.tools = value + seen |= toolsBit + } case "functions": - field = functionsField + if seen&functionsBit == 0 { + fields.functions = value + seen |= functionsBit + } case "instructions": - field = instructionsField + if seen&instructionsBit == 0 { + fields.instructions = value + seen |= instructionsBit + } case "messages": - field = messagesField + if seen&messagesBit == 0 { + fields.messages = value + seen |= messagesBit + } case "input": - field = inputField + if seen&inputBit == 0 { + fields.input = value + seen |= inputBit + } } - if field < 0 { - return true - } - mask := uint8(1 << field) - if seen&mask == 0 { - fields[field] = value - seen |= mask - } - return seen != allContentSessionSeedFields + return seen != allSessionRootBits }) + return fields, directRoot, true +} + +// writeOpenAIContentSessionSeedFromFields 按 deriveOpenAIContentSessionSeed 的字段顺序与格式 +// 将规范化内容直接流式写入 w,返回是否写入了至少一段内容以及是否全程为严格合法 JSON。 +// 任一规范化段无法流式处理时返回 (wrote, false),调用方回退到完整编码路径。 +func writeOpenAIContentSessionSeedFromFields(w io.Writer, fields openAISessionRootFields, prefix string) (wrote bool, ok bool) { + writePrefixOnce := func() { + if !wrote { + writeStringNoCopy(w, prefix) + wrote = true + } + } + writePart := func(s string) { + writePrefixOnce() + writeStringNoCopy(w, s) + } + writeCanonical := func(raw string) bool { + writePrefixOnce() + return writeCanonicalSeedJSON(w, raw) + } + + if model := fields.model.String(); model != "" { + writePart("model=") + writePart(model) + } + + if tools := fields.tools; tools.Exists() && tools.IsArray() && tools.Raw != "[]" { + writePart("|tools=") + if !writeCanonical(tools.Raw) { + return wrote, false + } + } + + if funcs := fields.functions; funcs.Exists() && funcs.IsArray() && funcs.Raw != "[]" { + writePart("|functions=") + if !writeCanonical(funcs.Raw) { + return wrote, false + } + } + + if instr := fields.instructions.String(); instr != "" { + writePart("|instructions=") + writePart(instr) + } + + firstUserCaptured := false + streamFailed := false + + msgs := fields.messages + if msgs.Exists() && msgs.IsArray() { + systemPrefixOpen := true + msgs.ForEach(func(_, msg gjson.Result) bool { + role := msg.Get("role").String() + switch role { + case "system", "developer": + if systemPrefixOpen { + writePart("|system=") + if c := msg.Get("content"); c.Exists() { + if !writeCanonical(c.Raw) { + streamFailed = true + return false + } + } + } + case "user": + systemPrefixOpen = false + if !firstUserCaptured { + writePart("|first_user=") + if c := msg.Get("content"); c.Exists() { + if !writeCanonical(c.Raw) { + streamFailed = true + return false + } + } + firstUserCaptured = true + } + default: + systemPrefixOpen = false + } + return true + }) + } else if inp := fields.input; inp.Exists() { + if inp.Type == gjson.String { + writePart("|input=") + writePart(inp.String()) + } else if inp.IsArray() { + systemPrefixOpen := true + inp.ForEach(func(_, item gjson.Result) bool { + role := item.Get("role").String() + switch role { + case "system", "developer": + if systemPrefixOpen { + writePart("|system=") + if c := item.Get("content"); c.Exists() { + if !writeCanonical(c.Raw) { + streamFailed = true + return false + } + } + } + case "user": + systemPrefixOpen = false + if !firstUserCaptured { + writePart("|first_user=") + if c := item.Get("content"); c.Exists() { + if !writeCanonical(c.Raw) { + streamFailed = true + return false + } + } + firstUserCaptured = true + } + default: + // Match Chat: reminders appended after conversation/tool items + // must not change the identity of an existing session. + systemPrefixOpen = false + } + if !firstUserCaptured && item.Get("type").String() == "input_text" { + writePart("|first_user=") + if text := item.Get("text").String(); text != "" { + writePart(text) + } + firstUserCaptured = true + } + return true + }) + } + } + + if streamFailed { + return wrote, false + } + return wrote, true +} + +// deriveOpenAIBodySessionHashes 在单遍零拷贝顶层扫描中提取显式 body 会话键或流式计算内容兜底哈希, +// 与 explicitOpenAIRequestSessionID + deriveOpenAIContentSessionSeed + deriveOpenAISessionHashes 字节等价。 +func deriveOpenAIBodySessionHashes(body []byte, isGrok bool) (currentHash string, legacyHash string) { + fields, directRoot, ok := scanOpenAISessionRootFields(body) + if !ok { + return "", "" + } + lowerModel := strings.ToLower(strings.TrimSpace(fields.model.String())) + + // 1. 显式 prompt_cache_key(兼容 WS response.* 包装信封);仅在无非空白前导字节时生效,与 openAIRequestPayloadView 一致。 + var explicitID string + if directRoot { + eventType := strings.ToLower(strings.TrimSpace(fields.eventType.String())) + if strings.HasPrefix(eventType, "response.") && fields.response.Exists() && fields.response.IsObject() { + explicitID = strings.TrimSpace(fields.response.Get("prompt_cache_key").String()) + } else { + explicitID = strings.TrimSpace(fields.promptCacheKey.String()) + } + } + + // 2. Grok 分组回退 previous_response_id + if explicitID == "" && isGrok { + if prevID := strings.TrimSpace(fields.previousResponseID.String()); prevID != "" && + ClassifyOpenAIPreviousResponseIDKind(prevID) == OpenAIPreviousResponseIDKindResponseID { + explicitID = "grok-prev-resp:" + prevID + } + } + + if explicitID != "" { + if isGrok { + explicitID = grokStickyAffinitySeedWithModel(explicitID, lowerModel) + } + return deriveOpenAISessionHashes(explicitID) + } + + // 3. 内容兜底:直接流式写入 xxhash + sha256,避免对大内联图片做 Unmarshal/Marshal 与大串拼接。 + prefix := contentSessionSeedPrefix + if isGrok { + prefix = grokStickyAffinitySeedWithModel(contentSessionSeedPrefix, lowerModel) + } + xxh := xxhash.New() + sh := sha256.New() + tw := &trimTrailingSpaceWriter{dst: io.MultiWriter(xxh, sh)} + wrote, streamOK := writeOpenAIContentSessionSeedFromFields(tw, fields, prefix) + if !streamOK { + seed := deriveOpenAIContentSessionSeedFallbackFromFields(fields) + if seed == "" { + return "", "" + } + if isGrok { + seed = grokStickyAffinitySeedWithModel(seed, lowerModel) + } + return deriveOpenAISessionHashes(seed) + } + if !wrote { + return "", "" + } + return fmt.Sprintf("%016x", xxh.Sum64()), hex.EncodeToString(sh.Sum(nil)) +} + +func grokStickyAffinitySeedWithModel(sessionID, lowerModel string) string { + sessionID = strings.TrimSpace(sessionID) + if sessionID == "" { + return "" + } + if lowerModel == "" { + return "grok-affinity:v1:" + sessionID + } + return "grok-affinity:v1:" + lowerModel + ":" + sessionID +} + +// deriveOpenAIContentSessionSeed builds a stable session seed from an +// OpenAI-format request body. Only fields constant across conversation turns +// are included: model, tools/functions definitions, the leading system/developer +// prompt prefix, instructions (Responses API), and the first user message. +// Supports both Chat Completions (messages) and Responses API (input). +func deriveOpenAIContentSessionSeed(body []byte) string { + fields, _, ok := scanOpenAISessionRootFields(body) + if !ok { + return "" + } var b strings.Builder + wrote, streamOK := writeOpenAIContentSessionSeedFromFields(&b, fields, contentSessionSeedPrefix) + if streamOK { + if !wrote { + return "" + } + return b.String() + } - if model := fields[modelField].String(); model != "" { + return deriveOpenAIContentSessionSeedFallbackFromFields(fields) +} + +// deriveOpenAIContentSessionSeedFallbackFromFields 在流式规范化触发回退时, +// 按 normalizeCompatSeedJSON 逐段编码并拼接内容会话种子。 +func deriveOpenAIContentSessionSeedFallbackFromFields(fields openAISessionRootFields) string { + var b strings.Builder + + if model := fields.model.String(); model != "" { _, _ = b.WriteString("model=") _, _ = b.WriteString(model) } - if tools := fields[toolsField]; tools.Exists() && tools.IsArray() && tools.Raw != "[]" { + if tools := fields.tools; tools.Exists() && tools.IsArray() && tools.Raw != "[]" { _, _ = b.WriteString("|tools=") _, _ = b.WriteString(normalizeCompatSeedJSON(json.RawMessage(tools.Raw))) } - if funcs := fields[functionsField]; funcs.Exists() && funcs.IsArray() && funcs.Raw != "[]" { + if funcs := fields.functions; funcs.Exists() && funcs.IsArray() && funcs.Raw != "[]" { _, _ = b.WriteString("|functions=") _, _ = b.WriteString(normalizeCompatSeedJSON(json.RawMessage(funcs.Raw))) } - if instr := fields[instructionsField].String(); instr != "" { + if instr := fields.instructions.String(); instr != "" { _, _ = b.WriteString("|instructions=") _, _ = b.WriteString(instr) } firstUserCaptured := false - msgs := fields[messagesField] + msgs := fields.messages if msgs.Exists() && msgs.IsArray() { systemPrefixOpen := true msgs.ForEach(func(_, msg gjson.Result) bool { @@ -142,7 +430,7 @@ scanRoot: } return true }) - } else if inp := fields[inputField]; inp.Exists() { + } else if inp := fields.input; inp.Exists() { if inp.Type == gjson.String { _, _ = b.WriteString("|input=") _, _ = b.WriteString(inp.String()) @@ -206,7 +494,8 @@ func hasOpenAIContentSessionUserAnchor(body []byte) bool { return false } - if messages := gjson.GetBytes(body, "messages"); messages.Exists() && messages.IsArray() { + root := parseRawJSONView(body) + if messages := root.Get("messages"); messages.Exists() && messages.IsArray() { anchored := false messages.ForEach(func(_, message gjson.Result) bool { if strings.TrimSpace(message.Get("role").String()) != "user" { @@ -218,7 +507,7 @@ func hasOpenAIContentSessionUserAnchor(body []byte) bool { return anchored } - input := gjson.GetBytes(body, "input") + input := root.Get("input") if !input.Exists() { return false } @@ -297,13 +586,14 @@ func deriveOpenAIStablePrefixSessionSeed(body []byte) string { hasStablePrefix = true } - if tools := gjson.GetBytes(body, "tools"); tools.Exists() && tools.IsArray() { + root := parseRawJSONView(body) + if tools := root.Get("tools"); tools.Exists() && tools.IsArray() { appendJSON("tools", tools) } - if funcs := gjson.GetBytes(body, "functions"); funcs.Exists() && funcs.IsArray() { + if funcs := root.Get("functions"); funcs.Exists() && funcs.IsArray() { appendJSON("functions", funcs) } - if instructions := gjson.GetBytes(body, "instructions"); strings.TrimSpace(instructions.String()) != "" { + if instructions := root.Get("instructions"); strings.TrimSpace(instructions.String()) != "" { appendJSON("instructions", instructions) } @@ -318,9 +608,9 @@ func deriveOpenAIStablePrefixSessionSeed(body []byte) string { }) } - if messages := gjson.GetBytes(body, "messages"); messages.Exists() && messages.IsArray() { + if messages := root.Get("messages"); messages.Exists() && messages.IsArray() { appendSystemMessages(messages) - } else if input := gjson.GetBytes(body, "input"); input.Exists() && input.IsArray() { + } else if input := root.Get("input"); input.Exists() && input.IsArray() { appendSystemMessages(input) } diff --git a/backend/internal/service/openai_gateway_forward.go b/backend/internal/service/openai_gateway_forward.go index f78a66b3a8..3f653501f2 100644 --- a/backend/internal/service/openai_gateway_forward.go +++ b/backend/internal/service/openai_gateway_forward.go @@ -44,10 +44,17 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco restrictionResult := s.detectCodexClientRestriction(c, account, body) apiKeyID := getAPIKeyIDFromContext(c) + wsDecision := s.getOpenAIWSProtocolResolver().Resolve(account) + // 仅允许 WS 入站请求走 WS 上游,避免出现 HTTP -> WS 协议混用。 + wsDecision = resolveOpenAIWSDecisionByClientTransport(wsDecision, GetOpenAIClientTransport(c)) // 执行作用域必须取自客户端原始身份:后面的账号 namespace 改写与指纹收敛会改掉 // 请求体里的 client_metadata / prompt_cache_key,用改写后的值取键会让不同会话 // 落到同一个键,也会与 WS 接入路径按原始报文算出的键对不上。 - wsExecutionScope, _ := resolveOpenAIWSExecutionScope(c, body, apiKeyID) + // 仅在真正走 WSv2 上游时解析作用域,避免 HTTP 路径反复扫描大请求体。 + var wsExecutionScope string + if wsDecision.Transport == OpenAIUpstreamTransportResponsesWebsocketV2 { + wsExecutionScope, _ = resolveOpenAIWSExecutionScope(c, body, apiKeyID) + } logCodexCLIOnlyDetection(ctx, c, account, apiKeyID, restrictionResult, body) if restrictionResult.Enabled && !restrictionResult.Matched { MarkOpsClientBusinessLimited(c, OpsClientBusinessLimitedReasonLocalPolicyDenied) @@ -67,7 +74,8 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco if normalized { body = normalizedBody } - legacyIngressBody, legacyIngressChanged, legacyIngressErr := normalizeOpenAIResponsesLegacyIngressWithConfig(s.cfg, body) + bodyValidated := isOpenAIRequestBodyJSONValidated(c) + legacyIngressBody, legacyIngressChanged, legacyIngressErr := normalizeOpenAIResponsesLegacyIngressValidated(s.cfg, body, bodyValidated) if legacyIngressErr != nil { return nil, legacyIngressErr } @@ -110,9 +118,6 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco body = liteBody } } - wsDecision := s.getOpenAIWSProtocolResolver().Resolve(account) - // 仅允许 WS 入站请求走 WS 上游,避免出现 HTTP -> WS 协议混用。 - wsDecision = resolveOpenAIWSDecisionByClientTransport(wsDecision, GetOpenAIClientTransport(c)) passthroughEnabled := account.IsOpenAIPassthroughEnabled() compactPath := isOpenAIResponsesCompactPath(c) if shouldFlattenOpenAIResponsesNamespaces(account, wsDecision.Transport, passthroughEnabled, compactPath) { @@ -125,7 +130,8 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco return nil, err } } - if shouldStripOpenAIResponsesInputNamespaces(account, wsDecision.Transport, passthroughEnabled) { + if shouldStripOpenAIResponsesInputNamespaces(account, wsDecision.Transport, passthroughEnabled) && + bytes.Contains(body, openAIResponsesNamespaceFieldBytes) { keepToolCallNamespaces := shouldKeepOpenAIResponsesToolCallNamespaces( account, wsDecision.Transport, passthroughEnabled, compactPath, body, ) @@ -152,8 +158,8 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco } originalBody := body - rememberOpenCodeInboundBody(c, originalBody) requestView := newOpenAIRequestView(body) + rememberOpenCodeInboundSessionFromView(c, requestView) reqModel, reqStream, promptCacheKey := requestView.Model, requestView.Stream, requestView.PromptCacheKey originalModel := reqModel @@ -162,21 +168,30 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco } if account.IsOpenAIApiKey() { - if normalized, changed, normalizeErr := normalizeOpenAIParallelToolCallsWithoutTools(body, responsesLite); normalizeErr != nil { - return nil, normalizeErr - } else if changed { - body = normalized - originalBody = normalized + apiKeyBodyChanged := false + if !responsesLite && requestView.HasParallelToolCalls { + if normalized, changed, normalizeErr := normalizeOpenAIParallelToolCallsWithoutTools(body, responsesLite); normalizeErr != nil { + return nil, normalizeErr + } else if changed { + body = normalized + originalBody = normalized + apiKeyBodyChanged = true + } } - if normalized, changed, normalizeErr := normalizeOpenAIAPIKeyStoreFalseReasoningReplay(body, isOpenAIResponsesCompactPath(c)); normalizeErr != nil { - return nil, normalizeErr - } else if changed { - body = normalized - originalBody = normalized + if compactPath || requestView.StoreIsFalse { + if normalized, changed, normalizeErr := normalizeOpenAIAPIKeyStoreFalseReasoningReplay(body, compactPath); normalizeErr != nil { + return nil, normalizeErr + } else if changed { + body = normalized + originalBody = normalized + apiKeyBodyChanged = true + } + } + if apiKeyBodyChanged { + requestView = newOpenAIRequestView(body) + reqModel, reqStream, promptCacheKey = requestView.Model, requestView.Stream, requestView.PromptCacheKey + originalModel = reqModel } - requestView = newOpenAIRequestView(body) - reqModel, reqStream, promptCacheKey = requestView.Model, requestView.Stream, requestView.PromptCacheKey - originalModel = reqModel } // 上游协议统一由 resolveUpstreamProtocol 判定(按模型分流时带上游模型目录)。OpenAI API Key 账号只会落到 @@ -196,7 +211,7 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco } SetActualOpenAIUpstreamEndpoint(c, openAIResponsesUpstreamEndpoint) if account.IsOpenAI() && (account.IsOpenAIApiKey() || account.IsOpenAIOAuthLike()) { - normalizedReasoningBody, reasoningChanged, reasoningErr := normalizeOpenAIResponsesReasoningContentReplay(body) + normalizedReasoningBody, reasoningChanged, reasoningErr := normalizeOpenAIResponsesReasoningContentReplayWithInput(body, requestView.Input) if reasoningErr != nil { return nil, fmt.Errorf("normalize OpenAI Responses reasoning content replay: %w", reasoningErr) } @@ -207,7 +222,7 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco reqModel, reqStream, promptCacheKey = requestView.Model, requestView.Stream, requestView.PromptCacheKey originalModel = reqModel } - sanitizedBody, changed, sanitizeErr := sanitizeOpenAIResponsesInputItemIDs(body) + sanitizedBody, changed, sanitizeErr := sanitizeOpenAIResponsesInputItemIDsWithInput(body, requestView.Input) if sanitizeErr != nil { return nil, fmt.Errorf("sanitize OpenAI Responses input item IDs: %w", sanitizeErr) } @@ -220,7 +235,8 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco } } - compatMessagesBridge := isOpenAICompatMessagesBridgeBody(body) + compatMessagesBridge := isOpenAICompatMessagesBridgePromptCacheKey(requestView.PromptCacheKey) || + bytes.Contains(body, []byte(openAICompatClaudeCodeTodoGuardMarker)) setOpenAICompatMessagesBridgeContext(c, compatMessagesBridge) isCodexCLI := openai.IsCodexOfficialClientByHeaders(c.GetHeader("User-Agent"), c.GetHeader("originator")) || (s.cfg != nil && s.cfg.Gateway.ForceCodexCLI) @@ -272,7 +288,7 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco } // 透传分支只需要轻量提取字段,避免热路径全量 Unmarshal。 mappedModel := account.GetMappedModel(reqModel) - reasoningEffort := extractOpenAIReasoningEffortFromBody(body, mappedModel) + reasoningEffort := extractOpenAIReasoningEffortFromView(requestView, mappedModel) // 国产模型默认 effort 补充:也要用 mappedModel 判定是否是 passback-required 上游。 reasoningEffort = ApplyThinkingEnabledFallback(reasoningEffort, body, mappedModel) return s.forwardOpenAIPassthrough( @@ -409,8 +425,7 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco upstreamModel = compactModel } } - instructions := gjson.GetBytes(body, "instructions") - instructionsEmpty := !instructions.Exists() || instructions.Type != gjson.String || strings.TrimSpace(instructions.String()) == "" + instructionsEmpty := requestView.InstructionsEmpty if instructionsEmpty && account.UsesOpenAICodexProtocol() && !compatMessagesBridge && !nativeCNResponses { markPatchSet("instructions", defaultCodexSynthInstructions(upstreamModel)) } @@ -428,12 +443,11 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco logger.LegacyPrintf("service.openai_gateway", "[OpenAI] Upstream model resolved: %s -> %s (account: %s, type: %s, isCodexCLI: %v)", billingModel, upstreamModel, account.Name, account.Type, isCodexCLI) } } - if strings.TrimSpace(gjson.GetBytes(body, "reasoning.effort").String()) == "minimal" { + if requestView.ReasoningEffort == "minimal" { markPatchSet("reasoning.effort", "none") logger.LegacyPrintf("service.openai_gateway", "[OpenAI] Normalized reasoning.effort: minimal -> none (account: %s)", account.Name) } - if strings.TrimSpace(gjson.GetBytes(body, "text.format.type").String()) == "json_schema" || - strings.TrimSpace(gjson.GetBytes(body, "response_format.type").String()) == "json_schema" { + if requestView.TextFormatType == "json_schema" || requestView.ResponseFormatType == "json_schema" { decoded, decodeErr := ensureReqBody() if decodeErr != nil { return nil, decodeErr @@ -527,10 +541,7 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco } // Responses OAuth 与 Chat 兼容入口保持一致:纯文本 system 可以无损提升后删除, // JSON object 模式仍需在 input 中保留 JSON 指令供上游兼容校验。 - omitPromotedSystemMessages := !strings.EqualFold( - strings.TrimSpace(gjson.GetBytes(body, "text.format.type").String()), - "json_object", - ) + omitPromotedSystemMessages := !strings.EqualFold(requestView.TextFormatType, "json_object") codexResult := codexTransformResult{} if compatMessagesBridge { codexResult = applyCodexOAuthTransformWithOptions(decoded, codexOAuthTransformOptions{ @@ -607,12 +618,12 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco } } - if !SupportsVerbosity(upstreamModel) && gjson.GetBytes(body, "text.verbosity").Exists() { + if !SupportsVerbosity(upstreamModel) && requestView.HasTextVerbosity { markPatchDelete("text.verbosity") } if !isCodexCLI { - maxOutputTokens := gjson.GetBytes(body, "max_output_tokens") + maxOutputTokens := requestView.MaxOutputTokens if maxOutputTokens.Exists() { switch account.Platform { case PlatformOpenAI, PlatformDeepseek: @@ -639,20 +650,24 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco // 仅对 OpenAI 平台归一化:Anthropic 合法使用 max_tokens,其 max_output_tokens // 反向转换已在上方 switch 中处理。 if account.Platform == PlatformOpenAI { - if maxTokens := gjson.GetBytes(body, "max_tokens"); maxTokens.Exists() { - if !gjson.GetBytes(body, "max_output_tokens").Exists() { + if maxTokens := requestView.MaxTokens; maxTokens.Exists() { + if !maxOutputTokens.Exists() { markPatchSet("max_output_tokens", maxTokens.Value()) } markPatchDelete("max_tokens") } } - if gjson.GetBytes(body, "max_completion_tokens").Exists() && (account.Type == AccountTypeAPIKey || account.Platform != PlatformOpenAI) { + if requestView.HasMaxCompletionTokens && (account.Type == AccountTypeAPIKey || account.Platform != PlatformOpenAI) { markPatchDelete("max_completion_tokens") } - for _, unsupportedField := range []string{"prompt_cache_retention", "safety_identifier", "prompt_cache_options"} { - if gjson.GetBytes(body, unsupportedField).Exists() { - markPatchDelete(unsupportedField) - } + if requestView.HasPromptCacheRetention { + markPatchDelete("prompt_cache_retention") + } + if requestView.HasSafetyIdentifier { + markPatchDelete("safety_identifier") + } + if requestView.HasPromptCacheOptions { + markPatchDelete("prompt_cache_options") } } // Ollama Cloud(实际 Responses 上游为 ollama.com)输出上限 clamp:对 Codex 与 @@ -664,7 +679,7 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco markPatchSet("max_output_tokens", clampedCap) } if wsDecision.Transport != OpenAIUpstreamTransportResponsesWebsocketV2 && - !account.IsOpenAIApiKey() && gjson.GetBytes(body, "previous_response_id").Exists() { + !account.IsOpenAIApiKey() && requestView.HasPreviousResponseID { markPatchDelete("previous_response_id") } if openAIRequestBodyMayContainEmptyBase64InputImage(body) { @@ -754,7 +769,7 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco } // Run after orphan-output filtering and all request-map rebuilds so a // compaction trigger cannot remain ahead of surviving history items. - if normalizedBody, changed, normalizeErr := NormalizeCompactionTriggerInputOrder(body); normalizeErr != nil { + if normalizedBody, changed, normalizeErr := normalizeCompactionTriggerInputOrderValidated(body, bodyValidated); normalizeErr != nil { return nil, fmt.Errorf("normalize compaction trigger order: %w", normalizeErr) } else if changed { body = normalizedBody @@ -1043,7 +1058,7 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco return nil, wsErr } - reasoningEffort := extractOpenAIReasoningEffortFromBody(body, upstreamModel, billingModel, originalModel) + reasoningEffort := extractOpenAIReasoningEffortFromView(requestView, upstreamModel, billingModel, originalModel) // 国产模型默认 effort 补充:此处 reqModel 已被 mapping 重写为 billingModel。 reasoningEffort = ApplyThinkingEnabledFallback(reasoningEffort, body, reqModel) reasoningEffortValue := "" @@ -1072,7 +1087,7 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco upstreamCtx, releaseUpstreamCtx, startTime.Add(firstOutputTimeout), ) } - syncOpenAIResponsesInstructionsEcho(c, body) + syncOpenAIResponsesInstructionsEchoRaw(c, requestView.HasInstructions, requestView.InstructionsRaw) upstreamReq, err := s.buildUpstreamRequest(upstreamCtx, c, account, body, token, reqStream, promptCacheKey, isCodexCLI) if headerGuard == nil { releaseUpstreamCtx() @@ -1171,6 +1186,7 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco if err != nil { return nil, fmt.Errorf("serialize invalid_encrypted_content retry body: %w", err) } + requestView = newOpenAIRequestView(body) if len(invalidDigests) > 0 { if lineageSessionHash == "" { lineageSessionHash = s.GenerateSessionHash(c, lineageEntryBody) @@ -1197,7 +1213,7 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco c, account, requestedModel, body, resp.StatusCode, upstreamMsg, respBody, compactModelFallbackRetried, ); retry { s.appendOpenAICompactFallbackRetryOps(c, account, resp, respBody, upstreamMsg, false) - fromModel := strings.TrimSpace(gjson.GetBytes(body, "model").String()) + fromModel := requestView.Model body = retryBody requestView = newOpenAIRequestView(body) reqBody = nil @@ -1256,7 +1272,7 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco resp.Body = newResponsesClientToolStreamBody(resp.Body, mapping, maxLineSize, s.cfg) } - serviceTier := extractOpenAIServiceTierFromBody(body) + serviceTier := normalizeOpenAIServiceTier(requestView.ServiceTier) // 上游接受后只保留计费需要的标量,避免响应处理期间继续保活完整 input/tools map。 reqBody = nil diff --git a/backend/internal/service/openai_gateway_request_body.go b/backend/internal/service/openai_gateway_request_body.go index 6267c405c8..16b53fdf11 100644 --- a/backend/internal/service/openai_gateway_request_body.go +++ b/backend/internal/service/openai_gateway_request_body.go @@ -9,7 +9,9 @@ import ( "github.com/Wei-Shaw/sub2api/internal/pkg/openai" "net/http" "strings" + "unicode" "unicode/utf8" + "unsafe" "github.com/MoeForge/moego/ojson" "github.com/Wei-Shaw/sub2api/internal/config" @@ -82,6 +84,29 @@ func shouldPreserveOpenAIResponsesNoneReasoningEffort(account *Account) bool { return baseURL == "" || isOfficialOpenAIModelsBaseURL(baseURL) } +const openAIRequestBodyJSONValidatedKey = "openai_request_body_json_validated" + +// MarkOpenAIRequestBodyJSONValidated 标记当前请求体已通过入口 JSON 语法校验, +// 供下游只读规范化步骤跳过重复的全量 gjson.ValidBytes 扫描。 +func MarkOpenAIRequestBodyJSONValidated(c *gin.Context) { + if c == nil { + return + } + c.Set(openAIRequestBodyJSONValidatedKey, true) +} + +func isOpenAIRequestBodyJSONValidated(c *gin.Context) bool { + if c == nil { + return false + } + v, ok := c.Get(openAIRequestBodyJSONValidatedKey) + if !ok { + return false + } + validated, ok := v.(bool) + return ok && validated +} + // Codex 0.149.0 needs a single advertised effort to directly select a visible // non-reasoning model. Treat that catalog-only "none" value as omission for // compatible upstreams, while preserving official OpenAI request semantics. @@ -89,20 +114,64 @@ func filterOpenAIResponsesNoneReasoningEffortForAccount(account *Account, body [ if len(body) == 0 || shouldPreserveOpenAIResponsesNoneReasoningEffort(account) { return body, nil } + mayEscape := JSONMayEscapePlainASCII(body) + seenReasoning := !bytes.Contains(body, []byte(`"reasoning"`)) && !mayEscape + seenNestedEffort := seenReasoning + seenReasoningEffort := !bytes.Contains(body, []byte(`"reasoning_effort"`)) && !mayEscape + if seenReasoning && seenReasoningEffort { + return body, nil + } + + root := parseRawJSONView(body) + if !root.IsObject() { + return body, nil + } + var reasoning, effortVal, reasoningEffort gjson.Result + root.ForEach(func(key, value gjson.Result) bool { + switch key.Str { + case "reasoning": + if !seenReasoning { + reasoning = value + seenReasoning = true + } + if !seenNestedEffort { + if v := value.Get("effort"); v.Exists() { + effortVal = v + seenNestedEffort = true + } + } + case "reasoning_effort": + if !seenReasoningEffort { + reasoningEffort = value + seenReasoningEffort = true + } + } + return !seenReasoning || !seenNestedEffort || !seenReasoningEffort + }) + + dropNestedNone := effortVal.Type == gjson.String && strings.EqualFold(strings.TrimSpace(effortVal.String()), "none") + dropTopNone := reasoningEffort.Type == gjson.String && strings.EqualFold(strings.TrimSpace(reasoningEffort.String()), "none") + dropEmptyReasoning := reasoning.IsObject() && !gjsonObjectHasMembers(reasoning) + if !dropNestedNone && !dropTopNone && !dropEmptyReasoning { + return body, nil + } out := body - for _, path := range []string{"reasoning.effort", "reasoning_effort"} { - effort := gjson.GetBytes(out, path) - if effort.Type != gjson.String || !strings.EqualFold(strings.TrimSpace(effort.String()), "none") { - continue - } - next, err := sjson.DeleteBytes(out, path) + if dropNestedNone { + next, err := sjson.DeleteBytes(out, "reasoning.effort") if err != nil { - return body, fmt.Errorf("strip %s none placeholder: %w", path, err) + return body, fmt.Errorf("strip reasoning.effort none placeholder: %w", err) } out = next } - if reasoning := gjson.GetBytes(out, "reasoning"); reasoning.IsObject() && len(reasoning.Map()) == 0 { + if dropTopNone { + next, err := sjson.DeleteBytes(out, "reasoning_effort") + if err != nil { + return body, fmt.Errorf("strip reasoning_effort none placeholder: %w", err) + } + out = next + } + if r := parseRawJSONView(out).Get("reasoning"); r.IsObject() && !gjsonObjectHasMembers(r) { next, err := sjson.DeleteBytes(out, "reasoning") if err != nil { return body, fmt.Errorf("strip empty reasoning object: %w", err) @@ -112,6 +181,18 @@ func filterOpenAIResponsesNoneReasoningEffortForAccount(account *Account, body [ return out, nil } +func gjsonObjectHasMembers(value gjson.Result) bool { + if !value.IsObject() { + return false + } + has := false + value.ForEach(func(_, _ gjson.Result) bool { + has = true + return false + }) + return has +} + func deleteOpenAIResponsesNoneReasoningEffortFromObject(account *Account, body map[string]any) { if body == nil || shouldPreserveOpenAIResponsesNoneReasoningEffort(account) { return @@ -483,7 +564,7 @@ func SanitizeOpenAICrossModeFailoverReasoning(body []byte) (sanitized []byte, ch if len(body) == 0 { return body, false, nil } - if !gjson.GetBytes(body, "input").Exists() { + if !parseRawJSONView(body).Get("input").Exists() { return body, false, nil } var decoded map[string]any @@ -705,6 +786,17 @@ func normalizeOpenAIResponsesReasoningContentReplay(body []byte) ([]byte, bool, if !input.IsArray() { return body, false, nil } + return normalizeOpenAIResponsesReasoningContentReplayWithInput(body, input) +} + +func normalizeOpenAIResponsesReasoningContentReplayWithInput(body []byte, input gjson.Result) ([]byte, bool, error) { + if !input.IsArray() { + return body, false, nil + } + inputBytes := unsafe.Slice(unsafe.StringData(input.Raw), len(input.Raw)) + if !bytes.Contains(inputBytes, []byte("reasoning")) && !JSONMayEscapePlainASCII(inputBytes) { + return body, false, nil + } needsNormalization := false input.ForEach(func(_, item gjson.Result) bool { @@ -712,7 +804,7 @@ func normalizeOpenAIResponsesReasoningContentReplay(body []byte) ([]byte, bool, return true } content := item.Get("content") - if content.IsArray() && len(content.Array()) > 0 { + if content.IsArray() && gjsonArrayHasElements(content) { needsNormalization = true return false } @@ -1073,15 +1165,33 @@ func deriveOpenAIReasoningEffortFromModelCandidates(models []string) string { } type openAIRequestView struct { - body []byte - Model string - Stream bool - PromptCacheKey string - PreviousResponseID string - ServiceTier string - ReasoningEffort string - patches []openAIRequestPatch - patchesDisabled bool + body []byte + Model string + Stream bool + PromptCacheKey string + PreviousResponseID string + HasPreviousResponseID bool + ServiceTier string + ReasoningEffort string + ReasoningEffortTop string + MetadataUserID string + HasInstructions bool + InstructionsEmpty bool + InstructionsRaw string + StoreIsFalse bool + HasParallelToolCalls bool + HasTextVerbosity bool + TextFormatType string + ResponseFormatType string + MaxOutputTokens gjson.Result + MaxTokens gjson.Result + HasMaxCompletionTokens bool + HasPromptCacheRetention bool + HasSafetyIdentifier bool + HasPromptCacheOptions bool + Input gjson.Result + patches []openAIRequestPatch + patchesDisabled bool } type openAIRequestPatch struct { @@ -1092,29 +1202,53 @@ type openAIRequestPatch struct { func newOpenAIRequestView(body []byte) openAIRequestView { if len(body) == 0 { - return openAIRequestView{} + return openAIRequestView{InstructionsEmpty: true} } const ( - modelField uint8 = 1 << iota + modelField uint32 = 1 << iota streamField promptCacheKeyField previousResponseIDField serviceTierField reasoningField + reasoningEffortTopField + metadataField + instructionsField + storeField + parallelToolCallsField + textVerbosityField + textFormatTypeField + responseFormatField + maxOutputTokensField + maxTokensField + maxCompletionTokensField + promptCacheRetentionField + safetyIdentifierField + promptCacheOptionsField + inputField allRequestViewFields = modelField | streamField | promptCacheKeyField | - previousResponseIDField | serviceTierField | reasoningField + previousResponseIDField | serviceTierField | reasoningField | reasoningEffortTopField | + metadataField | instructionsField | storeField | parallelToolCallsField | + textVerbosityField | textFormatTypeField | responseFormatField | + maxOutputTokensField | maxTokensField | + maxCompletionTokensField | promptCacheRetentionField | safetyIdentifierField | + promptCacheOptionsField | inputField ) - view := openAIRequestView{body: body} - var seen uint8 + view := openAIRequestView{body: body, InstructionsEmpty: true} + root := parseRawJSONView(body) + if !root.IsObject() { + return view + } + var seen uint32 // parseRawJSONView reads body without copying, so extracted strings alias the // body. They flow into usage logs and async tasks that outlive the request, so // clone them; otherwise a multi-MB body stays alive after its budget is freed. field := func(value gjson.Result) string { return strings.Clone(strings.TrimSpace(value.String())) } - parseRawJSONView(body).ForEach(func(key, value gjson.Result) bool { + root.ForEach(func(key, value gjson.Result) bool { switch key.Str { case "model": if seen&modelField == 0 { @@ -1133,6 +1267,7 @@ func newOpenAIRequestView(body []byte) openAIRequestView { } case "previous_response_id": if seen&previousResponseIDField == 0 { + view.HasPreviousResponseID = true view.PreviousResponseID = field(value) seen |= previousResponseIDField } @@ -1143,8 +1278,94 @@ func newOpenAIRequestView(body []byte) openAIRequestView { } case "reasoning": if seen&reasoningField == 0 { - view.ReasoningEffort = field(value.Get("effort")) - seen |= reasoningField + if effort := value.Get("effort"); effort.Exists() { + view.ReasoningEffort = field(effort) + seen |= reasoningField + } + } + case "reasoning_effort": + if seen&reasoningEffortTopField == 0 { + view.ReasoningEffortTop = field(value) + seen |= reasoningEffortTopField + } + case "metadata": + if seen&metadataField == 0 { + if uid := value.Get("user_id"); uid.Exists() { + view.MetadataUserID = field(uid) + seen |= metadataField + } + } + case "instructions": + if seen&instructionsField == 0 { + view.HasInstructions = true + view.InstructionsRaw = value.Raw + view.InstructionsEmpty = value.Type != gjson.String || strings.TrimSpace(value.String()) == "" + seen |= instructionsField + } + case "store": + if seen&storeField == 0 { + view.StoreIsFalse = value.Type == gjson.False + seen |= storeField + } + case "parallel_tool_calls": + if seen¶llelToolCallsField == 0 { + view.HasParallelToolCalls = true + seen |= parallelToolCallsField + } + case "text": + if value.IsObject() { + if seen&textVerbosityField == 0 && value.Get("verbosity").Exists() { + view.HasTextVerbosity = true + seen |= textVerbosityField + } + if seen&textFormatTypeField == 0 { + if ft := value.Get("format.type"); ft.Exists() { + view.TextFormatType = field(ft) + seen |= textFormatTypeField + } + } + } + case "response_format": + if seen&responseFormatField == 0 && value.IsObject() { + if rt := value.Get("type"); rt.Exists() { + view.ResponseFormatType = field(rt) + seen |= responseFormatField + } + } + case "max_output_tokens": + if seen&maxOutputTokensField == 0 { + view.MaxOutputTokens = value + seen |= maxOutputTokensField + } + case "max_tokens": + if seen&maxTokensField == 0 { + view.MaxTokens = value + seen |= maxTokensField + } + case "max_completion_tokens": + if seen&maxCompletionTokensField == 0 { + view.HasMaxCompletionTokens = true + seen |= maxCompletionTokensField + } + case "prompt_cache_retention": + if seen&promptCacheRetentionField == 0 { + view.HasPromptCacheRetention = true + seen |= promptCacheRetentionField + } + case "safety_identifier": + if seen&safetyIdentifierField == 0 { + view.HasSafetyIdentifier = true + seen |= safetyIdentifierField + } + case "prompt_cache_options": + if seen&promptCacheOptionsField == 0 { + view.HasPromptCacheOptions = true + seen |= promptCacheOptionsField + } + case "input": + if seen&inputField == 0 { + view.Input = value + seen |= inputField } } return seen != allRequestViewFields @@ -1841,7 +2062,7 @@ func normalizeOpenAIPassthroughOAuthBody(body []byte, compact bool) ([]byte, boo changed = true } - if inputResult := gjson.GetBytes(normalized, "input"); inputResult.Exists() { + if inputResult := parseRawJSONView(normalized).Get("input"); inputResult.Exists() { switch { case inputResult.Type == gjson.String: text := inputResult.String() @@ -1912,6 +2133,26 @@ func isOpenAICodexModel(model string) bool { return strings.Contains(strings.ToLower(strings.TrimSpace(model)), "codex") } +func extractOpenAIReasoningEffortFromView(view openAIRequestView, modelCandidates ...string) *string { + reasoningEffort := view.ReasoningEffort + if reasoningEffort == "" { + reasoningEffort = view.ReasoningEffortTop + } + if reasoningEffort != "" { + normalized := normalizeOpenAIReasoningEffortForModel(reasoningEffort, firstNonEmpty(modelCandidates...)) + if normalized == "" { + return nil + } + return &normalized + } + + value := deriveOpenAIReasoningEffortFromModelCandidates(modelCandidates) + if value == "" { + return nil + } + return &value +} + // extractOpenAIReasoningEffortFromBody 按优先级传入模型候选(如 upstreamModel, // billingModel, originalModel):显式 effort 的模型归一化(max 保留判定)用第一个 // 非空候选;body 未携带 effort 时的模型后缀推导依次尝试每个候选——OAuth 的 @@ -1964,14 +2205,82 @@ func explicitRequestedReasoningEffortFromBody(body []byte) string { if latest := latestResponsesInputEffort(body); latest != "" { return latest } - raw := strings.TrimSpace(gjson.GetBytes(body, "reasoning.effort").String()) + if !bytes.Contains(body, []byte("reasoning")) && !bytes.Contains(body, []byte("output_config")) && !JSONMayEscapePlainASCII(body) { + return "" + } + root := parseRawJSONView(body) + if !root.IsObject() { + return "" + } + var ( + reasoningEffort string + reasoningEffortTop string + outputConfigEffort string + seenReasoning bool + seenReasoningTop bool + seenOutputConfig bool + ) + root.ForEach(func(key, value gjson.Result) bool { + switch key.Str { + case "reasoning": + if !seenReasoning { + if effort := value.Get("effort"); effort.Exists() { + seenReasoning = true + reasoningEffort = strings.TrimSpace(effort.String()) + if reasoningEffort != "" { + return false + } + } + } + case "reasoning_effort": + if !seenReasoningTop { + seenReasoningTop = true + reasoningEffortTop = strings.TrimSpace(value.String()) + } + case "output_config": + if !seenOutputConfig { + if effort := value.Get("effort"); effort.Exists() { + seenOutputConfig = true + outputConfigEffort = strings.TrimSpace(effort.String()) + } + } + } + return !seenReasoning || !seenReasoningTop || !seenOutputConfig + }) + if reasoningEffort != "" { + return strings.Clone(reasoningEffort) + } + if reasoningEffortTop != "" { + return strings.Clone(reasoningEffortTop) + } + if outputConfigEffort != "" { + return strings.Clone(outputConfigEffort) + } + return "" +} + +// CanonicalRequestedReasoningEffortWithFields 与 CanonicalRequestedReasoningEffort 语义一致, +// 直接消费入口单次扫描已提取的顶层 effort 字段与模型名,避免对大请求体重复扫描。 +func CanonicalRequestedReasoningEffortWithFields(body []byte, reasoningEffort, reasoningEffortTop, outputConfigEffort string, modelCandidates ...string) *string { + raw := latestResponsesInputEffort(body) if raw == "" { - raw = strings.TrimSpace(gjson.GetBytes(body, "reasoning_effort").String()) + raw = strings.TrimSpace(reasoningEffort) } if raw == "" { - raw = strings.TrimSpace(gjson.GetBytes(body, "output_config.effort").String()) + raw = strings.TrimSpace(reasoningEffortTop) } - return raw + if raw == "" { + raw = strings.TrimSpace(outputConfigEffort) + } + if raw != "" { + return optionalTrimmedStringPtr(normalizeReasoningEffortMappingSource(raw)) + } + for _, model := range modelCandidates { + if value := canonicalReasoningEffortFromModelSuffix(model); value != "" { + return &value + } + } + return nil } // CanonicalRequestedReasoningEffort extracts the client-requested effort before @@ -2089,7 +2398,14 @@ func boundInvalidOpenAIServiceTierValue(raw string) string { // unknown value → *ErrInvalidOpenAIServiceTier (handler maps to HTTP 400), // matching OpenAI's enum validation semantics func ValidateOpenAIServiceTierField(body []byte) (string, error) { - tierResult := gjson.GetBytes(body, "service_tier") + if !bytes.Contains(body, []byte(`"service_tier"`)) && !JSONMayEscapePlainASCII(body) { + return "", nil + } + return ValidateOpenAIServiceTierResult(parseRawJSONView(body).Get("service_tier")) +} + +// ValidateOpenAIServiceTierResult 对已提取的 service_tier 字段值执行枚举校验。 +func ValidateOpenAIServiceTierResult(tierResult gjson.Result) (string, error) { if !tierResult.Exists() || tierResult.Type == gjson.Null { return "", nil } @@ -2102,7 +2418,7 @@ func ValidateOpenAIServiceTierField(body []byte) (string, error) { } norm := normalizedOpenAIServiceTierValue(raw) if norm == "" { - return "", &ErrInvalidOpenAIServiceTier{Value: boundInvalidOpenAIServiceTierValue(raw)} + return "", &ErrInvalidOpenAIServiceTier{Value: strings.Clone(boundInvalidOpenAIServiceTierValue(raw))} } return norm, nil } @@ -2575,8 +2891,9 @@ func openAIRequestBodyMayContainImageInput(body []byte) bool { if len(body) == 0 { return false } - input := gjson.GetBytes(body, "input") - messages := gjson.GetBytes(body, "messages.#-1") + root := parseRawJSONView(body) + input := root.Get("input") + messages := root.Get("messages.#-1") return openAIJSONValueMayContainImageInput(input) || openAIJSONValueMayContainImageInput(messages) } @@ -2604,8 +2921,10 @@ func openAIJSONValueMayContainImageInput(value gjson.Result) bool { return false } +var openAIBase64PrefixBytes = []byte("base64,") + func openAIRequestBodyMayContainEmptyBase64InputImage(body []byte) bool { - if len(body) == 0 || !openAIRequestBodyMayContainInputImageToken(body) { + if len(body) == 0 || !openAIRequestBodyMayContainEmptyBase64DataURI(body) || !openAIRequestBodyMayContainInputImageToken(body) { return false } input := parseRawJSONView(body).Get("input") @@ -2615,6 +2934,58 @@ func openAIRequestBodyMayContainEmptyBase64InputImage(body []byte) bool { return openAIJSONValueMayContainEmptyBase64InputImage(input) } +// openAIRequestBodyMayContainEmptyBase64DataURI 检查请求体是否存在可能解码为空 base64 data URI 的候选片段。 +// 非空 base64 图片在 "base64," 后紧跟 ASCII base64 字符,单字节即可跳过; +// 仅当存在 \u 平面 ASCII 转义、或某个 "base64," 后紧跟纯空白/转义并以引号结束时返回 true。 +func openAIRequestBodyMayContainEmptyBase64DataURI(body []byte) bool { + if JSONMayEscapePlainASCII(body) { + return true + } + rest := body + for { + idx := bytes.Index(rest, openAIBase64PrefixBytes) + if idx < 0 { + return false + } + i := idx + len(openAIBase64PrefixBytes) + for i < len(rest) { + b := rest[i] + switch b { + case '"': + return true + case ' ', '\t', '\n', '\r': + i++ + case '\\': + if i+1 >= len(rest) { + return true + } + switch rest[i+1] { + case 't', 'n', 'r', 'f', 'u': + // 可能是转义空白(如 \n/\t/\u0020/\u3000),继续或保守放行 + if rest[i+1] == 'u' { + return true + } + i += 2 + default: + // 非空白转义(如 \/),不为空 + goto nextMatch + } + default: + if b >= 0x80 { + // 可能是多字节 Unicode 空白,保守交由结构扫描判定 + return true + } + goto nextMatch + } + } + if i >= len(rest) { + return true + } + nextMatch: + rest = rest[idx+len(openAIBase64PrefixBytes):] + } +} + func openAIRequestBodyMayContainInputImageToken(body []byte) bool { if bytes.Contains(body, []byte("input_image")) { return true @@ -2640,10 +3011,41 @@ func openAIJSONValueMayContainEmptyBase64InputImage(value gjson.Result) bool { return found } if value.IsObject() { - if strings.TrimSpace(value.Get("type").String()) == "input_image" && isEmptyBase64DataURI(value.Get("image_url").String()) { + var ( + itemType string + imageURL string + content gjson.Result + seenType bool + seenImageURL bool + seenContent bool + ) + value.ForEach(func(key, v gjson.Result) bool { + switch key.Str { + case "type": + if !seenType { + seenType = true + itemType = strings.TrimSpace(v.String()) + } + case "image_url": + if !seenImageURL { + seenImageURL = true + imageURL = v.String() + } + case "content": + if !seenContent { + seenContent = true + content = v + } + } + return !seenType || !seenImageURL || !seenContent + }) + if itemType == "input_image" && isEmptyBase64DataURI(imageURL) { return true } - return openAIJSONValueMayContainEmptyBase64InputImage(value.Get("content")) + if seenContent { + return openAIJSONValueMayContainEmptyBase64InputImage(content) + } + return false } return false } @@ -2762,7 +3164,22 @@ func isEmptyBase64DataURI(raw string) bool { if !strings.HasPrefix(rest, "base64,") { return false } - return strings.TrimSpace(strings.TrimPrefix(rest, "base64,")) == "" + payload := strings.TrimPrefix(rest, "base64,") + for i := 0; i < len(payload); { + if b := payload[i]; b < 0x80 { + if b != ' ' && b != '\t' && b != '\n' && b != '\r' && b != '\v' && b != '\f' { + return false + } + i++ + continue + } + r, size := utf8.DecodeRuneInString(payload[i:]) + if !unicode.IsSpace(r) { + return false + } + i += size + } + return true } func getOpenAIRequestBodyMap(_ *gin.Context, body []byte) (map[string]any, error) { diff --git a/backend/internal/service/openai_gateway_scan_dedup_test.go b/backend/internal/service/openai_gateway_scan_dedup_test.go new file mode 100644 index 0000000000..aa0c79939b --- /dev/null +++ b/backend/internal/service/openai_gateway_scan_dedup_test.go @@ -0,0 +1,306 @@ +package service + +import ( + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +func TestOpenAIRequestBodyMayContainEmptyBase64DataURI(t *testing.T) { + largeB64 := strings.Repeat("AAAA", 16*1024) + tests := []struct { + name string + body string + prefilter bool + emptyImg bool + }{ + { + name: "non-empty valid base64 images", + body: `{"model":"gpt-6.2-astra","input":[{"type":"message","role":"user","content":[{"type":"input_image","image_url":"data:image/png;base64,` + largeB64 + `"}]}]}`, + prefilter: false, + emptyImg: false, + }, + { + name: "non-empty escaped slash base64", + body: `{"model":"gpt-6.2-astra","input":[{"type":"input_image","image_url":"data:image/jpeg;base64,\/9j\/4AAQ"}]}`, + prefilter: false, + emptyImg: false, + }, + { + name: "empty base64 data uri", + body: `{"model":"gpt-6.2-astra","input":[{"type":"input_image","image_url":"data:image/png;base64,"}]}`, + prefilter: true, + emptyImg: true, + }, + { + name: "ascii whitespace only base64", + body: `{"model":"gpt-6.2-astra","input":[{"type":"input_image","image_url":"data:image/png;base64, \t\n\r "}]}`, + prefilter: true, + emptyImg: true, + }, + { + name: "unicode whitespace escape base64", + body: `{"model":"gpt-6.2-astra","input":[{"type":"input_image","image_url":"data:image/png;base64,\u00a0\u3000"}]}`, + prefilter: true, + emptyImg: true, + }, + { + name: "raw utf8 nbsp whitespace base64", + body: "{\"model\":\"gpt-6.2-astra\",\"input\":[{\"type\":\"input_image\",\"image_url\":\"data:image/png;base64,\u00a0\"}]}", + prefilter: true, + emptyImg: true, + }, + { + name: "unicode escaped base64 keyword", + body: `{"model":"gpt-6.2-astra","input":[{"type":"input_image","image_url":"data:image/png;\u0062ase64,"}]}`, + prefilter: true, + emptyImg: true, + }, + { + name: "fourth image empty after three valid images", + body: `{"model":"gpt-6.2-astra","input":[{"type":"input_image","image_url":"data:image/png;base64,QUFB"},{"type":"input_image","image_url":"data:image/png;base64,QkJC"},{"type":"input_image","image_url":"data:image/png;base64,Q0ND"},{"type":"input_image","image_url":"data:image/png;base64, "}]}`, + prefilter: true, + emptyImg: true, + }, + { + name: "input_image with valid image_url but nested empty content", + body: `{"model":"gpt-6.2-astra","input":[{"type":"input_image","image_url":"data:image/png;base64,QUFB","content":[{"type":"input_image","image_url":"data:image/png;base64,"}]}]}`, + prefilter: true, + emptyImg: true, + }, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + raw := []byte(tc.body) + require.Equal(t, tc.prefilter, openAIRequestBodyMayContainEmptyBase64DataURI(raw)) + require.Equal(t, tc.emptyImg, openAIRequestBodyMayContainEmptyBase64InputImage(raw)) + }) + } +} + +func TestOpenAIRequestViewExpandedFields(t *testing.T) { + body := []byte(`{ + "model": " gpt-6.2-astra ", + "stream": true, + "prompt_cache_key": " pck-1 ", + "previous_response_id": " resp_123 ", + "service_tier": " priority ", + "reasoning": {"effort": " minimal "}, + "reasoning_effort": " high ", + "metadata": {"user_id": " user_99 "}, + "instructions": " follow rules ", + "store": false, + "parallel_tool_calls": true, + "text": {"verbosity": "low", "format": {"type": "json_schema"}}, + "response_format": {"type": "json_object"}, + "max_output_tokens": 4096, + "max_tokens": 2048, + "max_completion_tokens": 1024, + "prompt_cache_retention": "24h", + "safety_identifier": "safe-1", + "prompt_cache_options": {"enabled": true}, + "input": [{"type": "message", "role": "user", "content": "hi"}] + }`) + + view := newOpenAIRequestView(body) + require.Equal(t, "gpt-6.2-astra", view.Model) + require.True(t, view.Stream) + require.Equal(t, "pck-1", view.PromptCacheKey) + require.True(t, view.HasPreviousResponseID) + require.Equal(t, "resp_123", view.PreviousResponseID) + require.Equal(t, "priority", view.ServiceTier) + require.Equal(t, "minimal", view.ReasoningEffort) + require.Equal(t, "high", view.ReasoningEffortTop) + require.Equal(t, "user_99", view.MetadataUserID) + require.True(t, view.HasInstructions) + require.False(t, view.InstructionsEmpty) + require.Equal(t, `" follow rules "`, view.InstructionsRaw) + require.True(t, view.StoreIsFalse) + require.True(t, view.HasParallelToolCalls) + require.True(t, view.HasTextVerbosity) + require.Equal(t, "json_schema", view.TextFormatType) + require.Equal(t, "json_object", view.ResponseFormatType) + require.True(t, view.MaxOutputTokens.Exists()) + require.Equal(t, float64(4096), view.MaxOutputTokens.Value()) + require.True(t, view.MaxTokens.Exists()) + require.Equal(t, float64(2048), view.MaxTokens.Value()) + require.True(t, view.HasMaxCompletionTokens) + require.True(t, view.HasPromptCacheRetention) + require.True(t, view.HasSafetyIdentifier) + require.True(t, view.HasPromptCacheOptions) + require.True(t, view.Input.IsArray()) + + // Escaped keys and first-key precedence match gjson.GetBytes. + escaped := []byte(`{"\u006dodel":"first","model":"second","\u0073tore":false,"instructions":" "}`) + ev := newOpenAIRequestView(escaped) + require.Equal(t, "first", ev.Model) + require.True(t, ev.StoreIsFalse) + require.True(t, ev.HasInstructions) + require.True(t, ev.InstructionsEmpty) + + // Non-object root and empty body return safe zero views with InstructionsEmpty=true. + arrView := newOpenAIRequestView([]byte(`[{"model":"x"}]`)) + require.Empty(t, arrView.Model) + require.True(t, arrView.InstructionsEmpty) + emptyView := newOpenAIRequestView(nil) + require.True(t, emptyView.InstructionsEmpty) + + // Duplicate parent keys: nested lookups follow gjson.GetBytes and continue until child exists. + dupParent := []byte(`{ + "model": "gpt-6.2-astra", + "reasoning": {}, + "reasoning": {"effort": "high"}, + "metadata": {}, + "metadata": {"user_id": "sess-1"}, + "text": {}, + "text": {"verbosity": "low"}, + "text": {"format": {"type": "json_schema"}}, + "response_format": {}, + "response_format": {"type": "json_schema"} + }`) + dv := newOpenAIRequestView(dupParent) + require.Equal(t, "high", dv.ReasoningEffort) + require.Equal(t, "sess-1", dv.MetadataUserID) + require.True(t, dv.HasTextVerbosity) + require.Equal(t, "json_schema", dv.TextFormatType) + require.Equal(t, "json_schema", dv.ResponseFormatType) +} + +func TestFilterOpenAIResponsesNoneReasoningEffortForAccountFastPath(t *testing.T) { + acct := &Account{ + Platform: PlatformOpenAI, + Type: AccountTypeAPIKey, + Credentials: map[string]any{ + "base_url": "https://compat.example.com/v1", + }, + } + + unchanged := []byte(`{"model":"gpt-6.2-astra","reasoning":{"effort":"medium"},"input":[{"type":"message","role":"user","content":"hello"}]}`) + out, err := filterOpenAIResponsesNoneReasoningEffortForAccount(acct, unchanged) + require.NoError(t, err) + require.Equal(t, string(unchanged), string(out)) + + noneNested := []byte(`{"model":"gpt-6.2-astra","reasoning":{"effort":"none"}}`) + out, err = filterOpenAIResponsesNoneReasoningEffortForAccount(acct, noneNested) + require.NoError(t, err) + require.NotContains(t, string(out), "reasoning") + + noneTop := []byte(`{"model":"gpt-6.2-astra","reasoning_effort":"NONE"}`) + out, err = filterOpenAIResponsesNoneReasoningEffortForAccount(acct, noneTop) + require.NoError(t, err) + require.NotContains(t, string(out), "reasoning_effort") + + escapedKey := []byte(`{"model":"gpt-6.2-astra","\u0072easoning":{"effort":"none"}}`) + out, err = filterOpenAIResponsesNoneReasoningEffortForAccount(acct, escapedKey) + require.NoError(t, err) + require.NotContains(t, string(out), "none") + + dupParentEmpty := []byte(`{"model":"gpt-6.2-astra","reasoning":{},"reasoning":{"effort":"none"}}`) + out, err = filterOpenAIResponsesNoneReasoningEffortForAccount(acct, dupParentEmpty) + require.NoError(t, err) + require.Equal(t, `{"model":"gpt-6.2-astra","reasoning":{"effort":"none"}}`, string(out)) +} + +func TestOpenAIResponsesRejectedFieldRetryStateLazyHash(t *testing.T) { + initial := []byte(`{"model":"gpt-6.2-astra","max_output_tokens":100}`) + state := newOpenAIResponsesRejectedFieldRetryState(initial) + require.Nil(t, state.seenBodyHashes) + require.NotNil(t, state.initialBody) + + // Re-submitting initial body hashes lazily and is rejected. + require.False(t, state.Allow(initial)) + require.Nil(t, state.initialBody) + require.Len(t, state.seenBodyHashes, 1) + + retry1 := []byte(`{"model":"gpt-6.2-astra"}`) + require.True(t, state.Allow(retry1)) + require.False(t, state.Allow(retry1)) + + retry2 := []byte(`{"model":"gpt-6.2-astra","stream":true}`) + require.True(t, state.Allow(retry2)) + + // remember() also initializes initialBody hash lazily. + state2 := newOpenAIResponsesRejectedFieldRetryState(initial) + state2.remember(retry1) + require.Nil(t, state2.initialBody) + require.False(t, state2.Allow(initial)) + require.False(t, state2.Allow(retry1)) + require.True(t, state2.Allow(retry2)) +} + +func TestSetOpenAICodexRoutingHintFromBodyNonOAuthStripsHeader(t *testing.T) { + acct := &Account{ + Platform: PlatformOpenAI, + Type: AccountTypeAPIKey, + } + headers := http.Header{} + headers.Set("X-Codex-Routing-Hint", "stale-hint") + + setOpenAICodexRoutingHintFromBody(headers, acct, []byte(`{"model":"gpt-6.2-astra","service_tier":"priority"}`)) + require.Empty(t, headers.Get("X-Codex-Routing-Hint")) +} + +func TestRememberOpenCodeInboundSessionFromView(t *testing.T) { + gin.SetMode(gin.TestMode) + + cases := []struct { + name string + body string + }{ + {name: "prompt_cache_key", body: `{"model":"m","prompt_cache_key":"sess-pck"}`}, + {name: "plain_metadata_user_id", body: `{"model":"m","metadata":{"user_id":"user-plain"}}`}, + {name: "json_metadata_user_id", body: `{"model":"m","metadata":{"user_id":"{\"session_id\":\"sess-json\"}"}}`}, + {name: "empty_body", body: ``}, + } + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + c1, _ := gin.CreateTestContext(httptest.NewRecorder()) + c2, _ := gin.CreateTestContext(httptest.NewRecorder()) + raw := []byte(tc.body) + + rememberOpenCodeInboundBody(c1, raw) + rememberOpenCodeInboundSessionFromView(c2, newOpenAIRequestView(raw)) + + require.Equal(t, openCodeInboundBodies(c1), openCodeInboundBodies(c2)) + }) + } +} + +func TestCanonicalRequestedReasoningEffortWithFields(t *testing.T) { + body := []byte(`{"model":"gpt-6.2-astra-high","reasoning":{"effort":"medium"},"reasoning_effort":"low","output_config":{"effort":"xhigh"}}`) + got := CanonicalRequestedReasoningEffortWithFields(body, "medium", "low", "xhigh", "gpt-6.2-astra-high") + require.NotNil(t, got) + require.Equal(t, "medium", *got) + + got2 := CanonicalRequestedReasoningEffortWithFields(body, "", "low", "xhigh", "gpt-6.2-astra-high") + require.NotNil(t, got2) + require.Equal(t, "low", *got2) + + got3 := CanonicalRequestedReasoningEffortWithFields(body, "", "", "xhigh", "gpt-6.2-astra-high") + require.NotNil(t, got3) + require.Equal(t, "xhigh", *got3) + + got4 := CanonicalRequestedReasoningEffortWithFields([]byte(`{"model":"gpt-6.2-astra-high"}`), "", "", "", "gpt-6.2-astra-high") + require.NotNil(t, got4) + require.Equal(t, "high", *got4) + + cfgUpdate := []byte(`{"model":"gpt-6.2-astra","reasoning":{"effort":"low"},"input":[{"type":"configuration_update","reasoning":{"effort":"max"}}]}`) + got5 := CanonicalRequestedReasoningEffortWithFields(cfgUpdate, "low", "", "", "gpt-6.2-astra") + require.NotNil(t, got5) + require.Equal(t, "max", *got5) + + // Duplicate parent keys in explicitRequestedReasoningEffortFromBody match gjson.GetBytes. + require.Equal(t, "high", explicitRequestedReasoningEffortFromBody([]byte(`{"reasoning":{},"reasoning":{"effort":"high"}}`))) + require.Equal(t, "xhigh", explicitRequestedReasoningEffortFromBody([]byte(`{"output_config":{},"output_config":{"effort":"xhigh"}}`))) +} + +func TestNormalizeOpenAIResponsesLegacyIngressValidatedNonObjectRoot(t *testing.T) { + _, _, err := normalizeOpenAIResponsesLegacyIngressValidated(nil, []byte(`[]`), true) + require.Error(t, err) +} diff --git a/backend/internal/service/openai_gateway_scheduling.go b/backend/internal/service/openai_gateway_scheduling.go index 26fb2802e8..a01ca1aad9 100644 --- a/backend/internal/service/openai_gateway_scheduling.go +++ b/backend/internal/service/openai_gateway_scheduling.go @@ -166,19 +166,27 @@ func (s *OpenAIGatewayService) GenerateSessionHash(c *gin.Context, body []byte) return "" } - sessionID := explicitOpenAIRequestSessionID(c, body) - if sessionID == "" && len(body) > 0 { - sessionID = deriveOpenAIContentSessionSeed(body) + isGrok := isGrokRequestContext(c) + sessionID := explicitOpenAIHeaderSessionID(c) + if sessionID == "" && isGrok { + sessionID = strings.TrimSpace(c.GetHeader(grokConversationIDHeader)) } - if sessionID == "" { + if sessionID != "" { + if isGrok { + sessionID = grokStickyAffinitySeed(sessionID, body) + } + currentHash, legacyHash := deriveOpenAISessionHashes(sessionID) + attachOpenAILegacySessionHashToGin(c, legacyHash) + return currentHash + } + if len(body) == 0 { return "" } - if isGrokRequestContext(c) { - sessionID = grokStickyAffinitySeed(sessionID, body) + currentHash, legacyHash := deriveOpenAIBodySessionHashes(body, isGrok) + if currentHash == "" { + return "" } - - currentHash, legacyHash := deriveOpenAISessionHashes(sessionID) attachOpenAILegacySessionHashToGin(c, legacyHash) return currentHash } diff --git a/backend/internal/service/openai_opencode_session.go b/backend/internal/service/openai_opencode_session.go index 56db8e4c04..2060ef0181 100644 --- a/backend/internal/service/openai_opencode_session.go +++ b/backend/internal/service/openai_opencode_session.go @@ -71,6 +71,18 @@ func rememberOpenCodeInboundBody(c *gin.Context, body []byte) { c.Set(openCodeInboundBodyContextKey, openCodeSessionHintBody(sessionID)) } +func rememberOpenCodeInboundSessionFromView(c *gin.Context, view openAIRequestView) { + if c == nil || len(view.body) == 0 { + return + } + raw := view.PromptCacheKey + if raw == "" { + raw = openCodeSessionIDFromMetadataUserID(view.MetadataUserID) + } + sessionID := sanitizeSessionID(raw) + c.Set(openCodeInboundBodyContextKey, openCodeSessionHintBody(sessionID)) +} + func openCodeInboundBodies(c *gin.Context) [][]byte { if c == nil { return nil diff --git a/backend/internal/service/openai_responses_ingress_compat.go b/backend/internal/service/openai_responses_ingress_compat.go index d7a2adafb8..da397d5c32 100644 --- a/backend/internal/service/openai_responses_ingress_compat.go +++ b/backend/internal/service/openai_responses_ingress_compat.go @@ -1,6 +1,7 @@ package service import ( + "bytes" "encoding/json" "fmt" "strings" @@ -10,6 +11,12 @@ import ( "github.com/tidwall/gjson" ) +var ( + openAILegacyMessagesFieldBytes = []byte(`"messages"`) + openAILegacyPromptFieldBytes = []byte(`"prompt"`) + openAILegacyCommandsFieldBytes = []byte(`"commands"`) +) + // normalizeOpenAIResponsesLegacyIngress accepts the Chat Completions-shaped // payloads that a few Responses clients still emit. Native Responses input is // always authoritative because this path has no separate full-replay attempt. @@ -17,6 +24,37 @@ func normalizeOpenAIResponsesLegacyIngress(body []byte) ([]byte, bool, error) { return normalizeOpenAIResponsesLegacyIngressWithConfig(nil, body) } +func normalizeOpenAIResponsesLegacyIngressValidated(cfg *config.Config, body []byte, validated bool) ([]byte, bool, error) { + if len(body) == 0 { + return body, false, nil + } + if validated { + trimmed := bytes.TrimLeft(body, " \t\r\n") + if len(trimmed) > 0 && trimmed[0] == '{' && + !bytes.Contains(body, openAILegacyMessagesFieldBytes) && + !bytes.Contains(body, openAILegacyPromptFieldBytes) && + !bytes.Contains(body, openAILegacyCommandsFieldBytes) && + !JSONMayEscapePlainASCII(body) { + return body, false, nil + } + view := parseRawJSONView(body) + if view.IsObject() { + hasLegacyField := false + view.ForEach(func(key, _ gjson.Result) bool { + switch key.Str { + case "messages", "prompt", "commands": + hasLegacyField = true + } + return !hasLegacyField + }) + if !hasLegacyField { + return body, false, nil + } + } + } + return normalizeOpenAIResponsesLegacyIngressWithConfig(cfg, body) +} + func normalizeOpenAIResponsesLegacyIngressWithConfig(cfg *config.Config, body []byte) ([]byte, bool, error) { if len(body) == 0 { return body, false, nil diff --git a/backend/internal/service/openai_responses_instructions_echo.go b/backend/internal/service/openai_responses_instructions_echo.go index 72e45397b1..f170555171 100644 --- a/backend/internal/service/openai_responses_instructions_echo.go +++ b/backend/internal/service/openai_responses_instructions_echo.go @@ -26,6 +26,33 @@ type openAIResponsesClientInstructions struct { raw string } +// syncOpenAIResponsesInstructionsEchoRaw 按已提取的上游 instructions 原始 JSON 对比并登记还原值。 +func syncOpenAIResponsesInstructionsEchoRaw(c *gin.Context, hasInstructions bool, rawValue string) { + if c == nil { + return + } + stored, ok := c.Get(openAIResponsesClientInstructionsKey) + if !ok { + return + } + client, ok := stored.(openAIResponsesClientInstructions) + if !ok { + return + } + upstreamRaw := "" + if hasInstructions { + upstreamRaw = rawValue + } + restore := "" + if !openAIResponsesInstructionsRawEqual(client.raw, upstreamRaw) { + restore = client.raw + if restore == "" { + restore = "null" + } + } + c.Set(openAIResponsesInstructionsEchoRestoreKey, restore) +} + // rememberOpenAIResponsesClientInstructions 记录本次转发尝试的客户端原始 // instructions,并清空还原值,使未登记上游请求体的转发分支不做还原。 func rememberOpenAIResponsesClientInstructions(c *gin.Context, body []byte) { @@ -33,8 +60,10 @@ func rememberOpenAIResponsesClientInstructions(c *gin.Context, body []byte) { return } raw := "" - if value := gjson.GetBytes(body, "instructions"); value.Exists() { - raw = compactOpenAIResponsesInstructionsRaw(value.Raw) + if bytes.Contains(body, openAIResponsesInstructionsFieldMarker) || JSONMayEscapePlainASCII(body) { + if value := gjson.GetBytes(body, "instructions"); value.Exists() { + raw = compactOpenAIResponsesInstructionsRaw(value.Raw) + } } c.Set(openAIResponsesClientInstructionsKey, openAIResponsesClientInstructions{raw: raw}) c.Set(openAIResponsesInstructionsEchoRestoreKey, "") @@ -55,8 +84,10 @@ func syncOpenAIResponsesInstructionsEcho(c *gin.Context, upstreamBody []byte) { return } upstreamRaw := "" - if value := gjson.GetBytes(upstreamBody, "instructions"); value.Exists() { - upstreamRaw = value.Raw + if bytes.Contains(upstreamBody, openAIResponsesInstructionsFieldMarker) || JSONMayEscapePlainASCII(upstreamBody) { + if value := gjson.GetBytes(upstreamBody, "instructions"); value.Exists() { + upstreamRaw = value.Raw + } } restore := "" if !openAIResponsesInstructionsRawEqual(client.raw, upstreamRaw) { diff --git a/backend/internal/service/openai_responses_item_id.go b/backend/internal/service/openai_responses_item_id.go index 5fc8bb77d5..43c592f3be 100644 --- a/backend/internal/service/openai_responses_item_id.go +++ b/backend/internal/service/openai_responses_item_id.go @@ -1,8 +1,10 @@ package service import ( + "bytes" "fmt" "strings" + "unsafe" "github.com/tidwall/gjson" "github.com/tidwall/sjson" @@ -62,11 +64,30 @@ func shouldStripOpenAIResponsesNonPairCallID(itemType string) bool { } } +var ( + openAIResponsesIDFieldBytes = []byte(`"id"`) + openAIResponsesCallIDFieldBytes = []byte(`"call_id"`) +) + func sanitizeOpenAIResponsesInputItemIDs(body []byte) ([]byte, bool, error) { + if !bytes.Contains(body, openAIResponsesIDFieldBytes) && !bytes.Contains(body, openAIResponsesCallIDFieldBytes) && !JSONMayEscapePlainASCII(body) { + return body, false, nil + } input := parseRawJSONView(body).Get("input") if !input.IsArray() { return body, false, nil } + return sanitizeOpenAIResponsesInputItemIDsWithInput(body, input) +} + +func sanitizeOpenAIResponsesInputItemIDsWithInput(body []byte, input gjson.Result) ([]byte, bool, error) { + if !input.IsArray() { + return body, false, nil + } + inputBytes := unsafe.Slice(unsafe.StringData(input.Raw), len(input.Raw)) + if !bytes.Contains(inputBytes, openAIResponsesIDFieldBytes) && !bytes.Contains(inputBytes, openAIResponsesCallIDFieldBytes) && !JSONMayEscapePlainASCII(inputBytes) { + return body, false, nil + } type inputItem struct { raw string @@ -78,11 +99,30 @@ func sanitizeOpenAIResponsesInputItemIDs(body []byte) ([]byte, bool, error) { input.ForEach(func(_, item gjson.Result) bool { parsed := inputItem{raw: item.Raw} if item.IsObject() { - itemType := item.Get("type") - id := item.Get("id") + var itemType, id gjson.Result + var seenType, seenID, seenCallID bool + item.ForEach(func(k, v gjson.Result) bool { + switch k.Str { + case "type": + if !seenType { + itemType = v + seenType = true + } + case "id": + if !seenID { + id = v + seenID = true + } + case "call_id": + if !seenCallID { + seenCallID = true + } + } + return !seenType || !seenID || !seenCallID + }) trimmedItemType := strings.TrimSpace(itemType.String()) - parsed.stripCallID = item.Get("call_id").Exists() && shouldStripOpenAIResponsesNonPairCallID(trimmedItemType) - if id.Type == gjson.String { + parsed.stripCallID = seenCallID && shouldStripOpenAIResponsesNonPairCallID(trimmedItemType) + if seenID && id.Type == gjson.String { parsed.stripID = shouldStripOpenAIResponsesInputItemID(trimmedItemType, id.String()) } } diff --git a/backend/internal/service/openai_responses_rejected_field_retry.go b/backend/internal/service/openai_responses_rejected_field_retry.go index f70bdd89ac..eca75c88b9 100644 --- a/backend/internal/service/openai_responses_rejected_field_retry.go +++ b/backend/internal/service/openai_responses_rejected_field_retry.go @@ -32,6 +32,7 @@ var ( type openAIResponsesRejectedFieldRetryState struct { mu sync.Mutex budget *openAIResponsesRejectedFieldRetryBudget + initialBody []byte seenBodyHashes map[[sha256.Size]byte]struct{} } @@ -67,12 +68,18 @@ func newOpenAIResponsesRejectedFieldRetryState(initialBody []byte) *openAIRespon } func newOpenAIResponsesRejectedFieldRetryStateWithBudget(initialBody []byte, budget *openAIResponsesRejectedFieldRetryBudget) *openAIResponsesRejectedFieldRetryState { - state := &openAIResponsesRejectedFieldRetryState{ - budget: budget, - seenBodyHashes: make(map[[sha256.Size]byte]struct{}, maxOpenAIResponsesRejectedFieldRetries+1), + return &openAIResponsesRejectedFieldRetryState{ + budget: budget, + initialBody: initialBody, } - state.remember(initialBody) - return state +} + +func (s *openAIResponsesRejectedFieldRetryState) ensureInitialHashLocked() { + if len(s.initialBody) == 0 { + return + } + s.rememberLocked(s.initialBody) + s.initialBody = nil } func (s *openAIResponsesRejectedFieldRetryState) Allow(nextBody []byte) bool { @@ -81,6 +88,7 @@ func (s *openAIResponsesRejectedFieldRetryState) Allow(nextBody []byte) bool { } s.mu.Lock() defer s.mu.Unlock() + s.ensureInitialHashLocked() bodyHash := sha256.Sum256(nextBody) if _, seen := s.seenBodyHashes[bodyHash]; seen { return false @@ -90,6 +98,9 @@ func (s *openAIResponsesRejectedFieldRetryState) Allow(nextBody []byte) bool { if s.budget.attempts >= maxOpenAIResponsesRejectedFieldRetries { return false } + if s.seenBodyHashes == nil { + s.seenBodyHashes = make(map[[sha256.Size]byte]struct{}, maxOpenAIResponsesRejectedFieldRetries+1) + } s.seenBodyHashes[bodyHash] = struct{}{} s.budget.attempts++ return true @@ -101,6 +112,7 @@ func (s *openAIResponsesRejectedFieldRetryState) remember(body []byte) { } s.mu.Lock() defer s.mu.Unlock() + s.ensureInitialHashLocked() s.rememberLocked(body) } diff --git a/backend/internal/service/openai_routing_hint.go b/backend/internal/service/openai_routing_hint.go index c66b941149..e43e92b21e 100644 --- a/backend/internal/service/openai_routing_hint.go +++ b/backend/internal/service/openai_routing_hint.go @@ -72,6 +72,13 @@ func deleteOpenAIHeaderEqualFold(headers http.Header, name string) { } func setOpenAICodexRoutingHintFromBody(headers http.Header, account *Account, body []byte) { + if headers == nil { + return + } + if account == nil || !account.IsOpenAIOAuthLike() { + deleteOpenAIHeaderEqualFold(headers, openAICodexRoutingHintHeader) + return + } fields := gjson.GetManyBytes(body, "model", "service_tier") setOpenAICodexRoutingHint(headers, account, fields[0].String(), fields[1].String()) } @@ -115,6 +122,12 @@ func logOpenAIRoutingDiagnosticsFromBody( body []byte, wsAffinityDecision string, ) { + if ctx == nil { + ctx = context.Background() + } + if !logger.FromContext(ctx).Core().Enabled(zap.DebugLevel) { + return + } fields := gjson.GetManyBytes(body, "model", "service_tier") logOpenAIRoutingDiagnostics( ctx,