From 844459e78595acb63dc4d97e0394106cfd9dbfa1 Mon Sep 17 00:00:00 2001 From: lishuangqiang <142634204+lishuangqiang@users.noreply.github.com> Date: Mon, 16 Nov 2026 23:24:26 +0800 Subject: [PATCH] perf(openai): skip the redundant body validation when parsing responses requests The /v1/responses handler validates the request body with gjson.ValidBytes before doing anything else, then hands the same bytes to ParseGatewayRequest, which validates them a second time. After the single-root-walk change the validation is the majority of what that call does: at 1MiB it is about 510us of the remaining 730us. Add ParseGatewayRequestValidated for callers that have already established the body is valid JSON, and use it in the handler, where the only rewrite between the two points is applyOpenAIReasoningEffortPolicyForRequest (sjson, which preserves validity). The validating entry point is unchanged, so invalid JSON keeps producing a clean error everywhere else. ReplaceBody / CloneForBody keep validating as well, because their bytes can differ from the ones a caller validated. Equivalence tests assert the trusted variant produces identical results to the validating one on valid JSON, and the fuzz target checks the same for every input that parses. Benchmark (Apple M5 Pro, 3 allocs unchanged): responses 1MiB: 735us -> 239us anthropic 1MiB: 723us -> 207us (not yet wired: that handler has no earlier validation, so it keeps the validating path) --- .../handler/gateway_handler_responses.go | 4 ++- backend/internal/service/gateway_request.go | 21 ++++++++--- .../gateway_request_scan_benchmark_test.go | 13 ++++++- .../gateway_request_scan_equivalence_test.go | 35 ++++++++++++++++++- 4 files changed, 66 insertions(+), 7 deletions(-) diff --git a/backend/internal/handler/gateway_handler_responses.go b/backend/internal/handler/gateway_handler_responses.go index 165b57867d..f499dba5e8 100644 --- a/backend/internal/handler/gateway_handler_responses.go +++ b/backend/internal/handler/gateway_handler_responses.go @@ -178,8 +178,10 @@ func (h *GatewayHandler) Responses(c *gin.Context) { defer inflightRelease() // Parse request for session hash + // body 已在本函数开头用 gjson.ValidBytes 校验过,之后只经过 sjson 改写 + // (applyOpenAIReasoningEffortPolicyForRequest),合法性保持,因此跳过重复校验。 bodyRef := service.NewRequestBodyRef(body) - parsedReq, _ := service.ParseGatewayRequest(bodyRef, "responses") + parsedReq, _ := service.ParseGatewayRequestValidated(bodyRef, "responses") if parsedReq == nil { parsedReq = &service.ParsedRequest{Model: reqModel, Stream: reqStream, Body: bodyRef} } diff --git a/backend/internal/service/gateway_request.go b/backend/internal/service/gateway_request.go index 1ec3209250..deb11fae90 100644 --- a/backend/internal/service/gateway_request.go +++ b/backend/internal/service/gateway_request.go @@ -316,14 +316,15 @@ func normalizeClaudeCodeLongContextModel(model string) string { } // parseGatewayRequestBody 只做标量和 raw range 轻量解析,不恢复 system/messages 对象图。 -func parseGatewayRequestBody(parsed *ParsedRequest, protocol string) error { +// validate 为 false 时要求调用方已经确认 body 是合法 JSON(见 ParseGatewayRequestValidated)。 +func parseGatewayRequestBody(parsed *ParsedRequest, protocol string, validate bool) error { if parsed == nil || parsed.Body == nil { return fmt.Errorf("empty request body") } parsed.Body.parsed = nil bodyBytes := parsed.Body.Bytes() - if !gjson.ValidBytes(bodyBytes) { + if validate && !gjson.ValidBytes(bodyBytes) { return DescribeInvalidJSON(bodyBytes) } @@ -388,7 +389,7 @@ func parseGatewayRequestBody(parsed *ParsedRequest, protocol string) error { } func refreshGatewayRequestRanges(parsed *ParsedRequest, protocol string) error { - return parseGatewayRequestBody(parsed, protocol) + return parseGatewayRequestBody(parsed, protocol, true) } // DescribeInvalidJSON returns a diagnostic error for a request body that @@ -495,8 +496,20 @@ func normalizeSessionUserAgentFallback(raw string) string { // protocol 指定请求协议格式(domain.PlatformAnthropic / domain.PlatformGemini), // 不同协议使用不同的 system/messages 字段名。 func ParseGatewayRequest(body *RequestBodyRef, protocol string) (*ParsedRequest, error) { + return parseGatewayRequest(body, protocol, true) +} + +// ParseGatewayRequestValidated 与 ParseGatewayRequest 结果相同,但要求调用方已经确认 +// body 是合法 JSON(例如 handler 已对同一份字节做过 gjson.ValidBytes,且此后的改写只 +// 经过 sjson)。它跳过这次全量校验——1 MiB body 上约 510µs,占解析耗时的七成。 +// 非法 JSON 的语义与未校验版本不同,只允许在校验过同一份字节的调用点使用。 +func ParseGatewayRequestValidated(body *RequestBodyRef, protocol string) (*ParsedRequest, error) { + return parseGatewayRequest(body, protocol, false) +} + +func parseGatewayRequest(body *RequestBodyRef, protocol string, validate bool) (*ParsedRequest, error) { parsed := &ParsedRequest{Body: body} - if err := parseGatewayRequestBody(parsed, protocol); err != nil { + if err := parseGatewayRequestBody(parsed, protocol, validate); err != nil { return nil, err } return parsed, nil diff --git a/backend/internal/service/gateway_request_scan_benchmark_test.go b/backend/internal/service/gateway_request_scan_benchmark_test.go index 0b09668d70..82e5634ccc 100644 --- a/backend/internal/service/gateway_request_scan_benchmark_test.go +++ b/backend/internal/service/gateway_request_scan_benchmark_test.go @@ -72,7 +72,18 @@ func BenchmarkParseGatewayRequestScan(b *testing.B) { b.ReportAllocs() for range b.N { parsed := &ParsedRequest{Body: NewRequestBodyRef(body)} - if err := parseGatewayRequestBody(parsed, tc.protocol); err != nil { + if err := parseGatewayRequestBody(parsed, tc.protocol, true); err != nil { + b.Fatal(err) + } + } + }) + // 调用方已经校验过同一份字节时(handler 已做 gjson.ValidBytes,且之后只经 sjson 改写)。 + b.Run(tc.name+"/scan_validated", func(b *testing.B) { + b.SetBytes(int64(len(body))) + b.ReportAllocs() + for range b.N { + parsed := &ParsedRequest{Body: NewRequestBodyRef(body)} + if err := parseGatewayRequestBody(parsed, tc.protocol, false); err != nil { b.Fatal(err) } } diff --git a/backend/internal/service/gateway_request_scan_equivalence_test.go b/backend/internal/service/gateway_request_scan_equivalence_test.go index ca35784c0c..ffe43ec9e9 100644 --- a/backend/internal/service/gateway_request_scan_equivalence_test.go +++ b/backend/internal/service/gateway_request_scan_equivalence_test.go @@ -165,7 +165,7 @@ func parseBoth(t *testing.T, protocol string, body []byte) (parsedSnapshot, pars // 直接调被重构的这一步:ParseGatewayRequest 在失败时返回 nil,无法比较错误路径上的中间状态。 newBody := NewRequestBodyRef(append([]byte(nil), body...)) newParsed := &ParsedRequest{Body: newBody} - newErr := parseGatewayRequestBody(newParsed, protocol) + newErr := parseGatewayRequestBody(newParsed, protocol, true) return snapshotOf(legacyParsed, legacyErr), snapshotOf(newParsed, newErr) } @@ -275,6 +275,30 @@ func TestParseGatewayRequestMatchesLegacyRandomized(t *testing.T) { } } +// 已校验变体只允许在「body 合法」的前提下使用;合法 JSON 上两者必须产出完全相同的结果。 +func TestParseGatewayRequestValidatedMatchesValidatingPath(t *testing.T) { + bodies := []string{ + `{"model":"gpt-5.5","stream":true,"input":[{"type":"message"}]}`, + `{"model":"claude-x[1m]","messages":[],"system":"s","max_tokens":8}`, + `{"metadata":{"user_id":"u"},"thinking":{"type":"enabled"},"output_config":{"effort":" high "}}`, + `{"contents":[],"systemInstruction":{"parts":[]}}`, + `{}`, + } + protocols := []string{"responses", "chat_completions", domain.PlatformAnthropic, domain.PlatformGemini} + for _, body := range bodies { + for _, protocol := range protocols { + validating := &ParsedRequest{Body: NewRequestBodyRef([]byte(body))} + validatingErr := parseGatewayRequestBody(validating, protocol, true) + + trusted := &ParsedRequest{Body: NewRequestBodyRef([]byte(body))} + trustedErr := parseGatewayRequestBody(trusted, protocol, false) + + require.Equal(t, snapshotOf(validating, validatingErr), snapshotOf(trusted, trustedErr), + "body=%s protocol=%s", body, protocol) + } + } +} + func FuzzParseGatewayRequestMatchesLegacy(f *testing.F) { f.Add([]byte(`{"model":"m","stream":true,"input":[]}`), "responses") f.Add([]byte(`{"model":"claude-x[1m]","messages":[],"system":"s"}`), domain.PlatformAnthropic) @@ -289,5 +313,14 @@ func FuzzParseGatewayRequestMatchesLegacy(f *testing.F) { want, got := parseBoth(t, protocol, body) require.Equal(t, want, got, "body=%q protocol=%s", body, protocol) + // 合法 JSON 上,跳过校验不得改变结果。 + if gjson.ValidBytes(body) { + validating := &ParsedRequest{Body: NewRequestBodyRef(append([]byte(nil), body...))} + validatingErr := parseGatewayRequestBody(validating, protocol, true) + trusted := &ParsedRequest{Body: NewRequestBodyRef(append([]byte(nil), body...))} + trustedErr := parseGatewayRequestBody(trusted, protocol, false) + require.Equal(t, snapshotOf(validating, validatingErr), snapshotOf(trusted, trustedErr), + "validated path diverged: body=%q protocol=%s", body, protocol) + } }) }