diff --git a/backend/internal/handler/openai_codex_call_output_gate_test.go b/backend/internal/handler/openai_codex_call_output_gate_test.go new file mode 100644 index 0000000000..3dbff2d493 --- /dev/null +++ b/backend/internal/handler/openai_codex_call_output_gate_test.go @@ -0,0 +1,63 @@ +//go:build unit + +package handler + +import ( + "math/rand" + "strings" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestCodexCallOutputGateSkipsDeclaredToolsWithoutCandidate(t *testing.T) { + body := []byte(`{"model":"gpt-5","tools":[{"type":"function","name":"automation_update"},{"type":"function","name":"create_thread"}],` + + `"input":[{"type":"function_call","call_id":"c1","name":"shell"},{"type":"function_call_output","call_id":"c1","output":"ok"}]}`) + require.False(t, mayContainCodexCallOutputCandidate(body, "automation_update")) + require.False(t, mayContainCodexCallOutputCandidate(body, "create_thread", "send_message_to_thread")) + for name, normalize := range map[string]func([]byte) ([]byte, bool){ + "page": normalizeCodexPageContext, + "automation": normalizeCodexAutomationBootstrap, + "delegation": normalizeCodexDelegationBootstrap, + } { + t.Run(name, func(t *testing.T) { + allocs := testing.AllocsPerRun(10, func() { + got, changed := normalize(body) + if changed || &got[0] != &body[0] { + t.Fatal("non-candidate body must be returned unchanged") + } + }) + require.Zero(t, allocs) + }) + } +} + +// Whenever the ungated bootstrap path rewrites a body, the gate must admit it. +func TestCodexCallOutputGateAdmitsEveryRewrite(t *testing.T) { + u := func(hex string) string { return `\` + "u" + hex } + output := mustJSON(t, codexAutomationBootstrap("wiki", "never", automationBootstrapPrompt)) + items := []string{ + `{"type":"function_call_output","namespace":"codex_app","name":"automation_update","output":` + output + `}`, + `{"type":"function_call_output","namespace":"codex_app","name":"` + u("0061") + `utomation_update","output":` + output + `}`, + `{"` + u("0074") + `ype":"function_call_output","namespace":"codex_app","name":"automation_update","output":` + output + `}`, + `{"type":"function_call_output","namespace":"codex_app","name":"automation_update","name":"other","output":` + output + `}`, + `{"type":"function_call_output","call_id":"c","output":"ok"}`, + `{"type":"message","role":"user","content":"automation_update function_call_output caf` + u("00e9") + `"}`, + `{"type":"function_call","call_id":"c","name":"automation_update"}`, + } + rng := rand.New(rand.NewSource(11)) + rewrites := 0 + for i := 0; i < 3000; i++ { + var parts []string + for n := rng.Intn(3); n >= 0; n-- { + parts = append(parts, items[rng.Intn(len(items))]) + } + body := []byte(`{"model":"gpt-5","tools":[{"type":"function","name":"automation_update"}],"input":[` + strings.Join(parts, ",") + `]}`) + _, rewritten := normalizeCodexCallOutputBootstrap(body, isCodexAutomationCandidate, false) + if rewritten { + rewrites++ + require.True(t, mayContainCodexCallOutputCandidate(body, "automation_update"), "%s", body) + } + } + require.Positive(t, rewrites) +} diff --git a/backend/internal/handler/openai_gateway_handler.go b/backend/internal/handler/openai_gateway_handler.go index f70bce78b2..8822672422 100644 --- a/backend/internal/handler/openai_gateway_handler.go +++ b/backend/internal/handler/openai_gateway_handler.go @@ -1729,11 +1729,23 @@ func normalizeCodexAutomationBootstrap(body []byte) ([]byte, bool) { // mayContainCodexCallOutputCandidate is a necessary condition for a bootstrap // candidate, checked before the full uniqueness scan and decode. Its type and // tool name are JSON strings, which appear literally unless a \u escape spells -// their letters; without either, normalization cannot change the body. +// their letters; without either, normalization cannot change the body. Escapes +// that real clients emit (control characters, HTML-safe and non-ASCII runes) +// cannot spell those letters and must not force the full decode. +// +// Tool declarations carry the same names, so a literal hit is confirmed by a +// zero-copy scan for an input item of type function_call_output whose name +// starts with one of toolNames. The full path rejects bodies with duplicate +// members, and without duplicates the scan reads the same values as the +// decoder. func mayContainCodexCallOutputCandidate(body []byte, toolNames ...string) bool { - if bytes.Contains(body, []byte(`\u`)) { - return true + if !service.JSONMayEscapePlainASCII(body) && !containsCodexCallOutputLiterals(body, toolNames) { + return false } + return service.ResponsesInputHasFunctionCallOutputNamed(body, toolNames...) +} + +func containsCodexCallOutputLiterals(body []byte, toolNames []string) bool { if !bytes.Contains(body, []byte("function_call_output")) { return false } diff --git a/backend/internal/service/bedrock_request.go b/backend/internal/service/bedrock_request.go index 4fc7fd7213..74df923e63 100644 --- a/backend/internal/service/bedrock_request.go +++ b/backend/internal/service/bedrock_request.go @@ -226,21 +226,21 @@ func PrepareBedrockRequestBodyWithTokens(body []byte, modelID string, betaTokens } logger.LegacyPrintf("service.gateway", "[Bedrock] Injected beta tokens: %v (model=%s ccCompat=%v)", betaTokens, modelID, ccCompat) } else { - body, _ = sjson.DeleteBytes(body, "anthropic_beta") + body, _ = deleteJSONPathIfPresent(body, "anthropic_beta") } // 移除 Bedrock 不支持的 Anthropic 直连 API 专有顶层字段 - body, _ = sjson.DeleteBytes(body, "provider") - body, _ = sjson.DeleteBytes(body, "metadata") + body, _ = deleteJSONPathIfPresent(body, "provider") + body, _ = deleteJSONPathIfPresent(body, "metadata") // 移除 model 字段(Bedrock 通过 URL 指定模型) - body, err = sjson.DeleteBytes(body, "model") + body, err = deleteJSONPathIfPresent(body, "model") if err != nil { return nil, fmt.Errorf("remove model field: %w", err) } // 移除 stream 字段(Bedrock 通过不同端点控制流式,不接受请求体中的 stream 字段) - body, err = sjson.DeleteBytes(body, "stream") + body, err = deleteJSONPathIfPresent(body, "stream") if err != nil { return nil, fmt.Errorf("remove stream field: %w", err) } @@ -256,10 +256,10 @@ func PrepareBedrockRequestBodyWithTokens(body []byte, modelID string, betaTokens if effort := gjson.GetBytes(body, "output_config.effort"); effort.Exists() { body, err = sjson.SetRawBytes(body, "output_config", []byte(`{"effort":`+effort.Raw+`}`)) } else { - body, err = sjson.DeleteBytes(body, "output_config") + body, err = deleteJSONPathIfPresent(body, "output_config") } } else { - body, err = sjson.DeleteBytes(body, "output_config") + body, err = deleteJSONPathIfPresent(body, "output_config") } if err != nil { return nil, fmt.Errorf("normalize output_config field: %w", err) @@ -289,6 +289,16 @@ func ResolveBedrockBetaTokens(betaHeader string, body []byte, modelID string) [] return filterBedrockBetaTokens(betaTokens) } +// deleteJSONPathIfPresent 删除 path 指向的值。sjson 在值不存在时也会先复制整个 +// body 再丢弃,所以先用零拷贝视图确认存在;不存在时原样返回 body。path 只能是 +// gjson 与 sjson 语义一致的简单路径。 +func deleteJSONPathIfPresent(body []byte, path string) ([]byte, error) { + if !parseRawJSONView(body).Get(path).Exists() { + return body, nil + } + return sjson.DeleteBytes(body, path) +} + // convertOutputFormatToInlineSchema 将结构化输出的 JSON schema 内联到最后一条 user message // Bedrock Invoke 不支持 output_format 参数,litellm 的做法是将 schema 追加到用户消息中 // 参考: litellm AmazonAnthropicClaudeMessagesConfig._convert_output_format_to_inline_schema() @@ -402,45 +412,44 @@ func isBedrockClaude45OrNewer(modelID string) bool { func sanitizeBedrockCacheControl(body []byte, modelID string) []byte { isClaude45 := isBedrockClaude45OrNewer(modelID) + // 两段扫描都读零拷贝视图:sjson 每次删除都写入新 buffer,视图所指的旧 body + // 不会被修改;删除只发生在 cache_control 内部,数组下标保持不变。 + // 清理 system 数组中的 cache_control - systemArr := gjson.GetBytes(body, "system") - if systemArr.Exists() && systemArr.IsArray() { - for i, item := range systemArr.Array() { - if !item.IsObject() { - continue + systemArr := parseRawJSONView(body).Get("system") + if systemArr.IsArray() { + i := -1 + systemArr.ForEach(func(_, item gjson.Result) bool { + i++ + if cc := item.Get("cache_control"); item.IsObject() && cc.IsObject() { + body = deleteCacheControlUnsupportedFields(body, fmt.Sprintf("system.%d.cache_control", i), cc, isClaude45) } - cc := item.Get("cache_control") - if !cc.Exists() || !cc.IsObject() { - continue - } - body = deleteCacheControlUnsupportedFields(body, fmt.Sprintf("system.%d.cache_control", i), cc, isClaude45) - } + return true + }) } // 清理 messages 中的 cache_control - messages := gjson.GetBytes(body, "messages") - if !messages.Exists() || !messages.IsArray() { + messages := parseRawJSONView(body).Get("messages") + if !messages.IsArray() { return body } - for mi, msg := range messages.Array() { - if !msg.IsObject() { - continue - } + mi := -1 + messages.ForEach(func(_, msg gjson.Result) bool { + mi++ content := msg.Get("content") - if !content.Exists() || !content.IsArray() { - continue + if !msg.IsObject() || !content.IsArray() { + return true } - for ci, block := range content.Array() { - if !block.IsObject() { - continue + ci := -1 + content.ForEach(func(_, block gjson.Result) bool { + ci++ + if cc := block.Get("cache_control"); block.IsObject() && cc.IsObject() { + body = deleteCacheControlUnsupportedFields(body, fmt.Sprintf("messages.%d.content.%d.cache_control", mi, ci), cc, isClaude45) } - cc := block.Get("cache_control") - if !cc.Exists() || !cc.IsObject() { - continue - } - body = deleteCacheControlUnsupportedFields(body, fmt.Sprintf("messages.%d.content.%d.cache_control", mi, ci), cc, isClaude45) - } - } + return true + }) + return true + }) return body } diff --git a/backend/internal/service/bedrock_stream.go b/backend/internal/service/bedrock_stream.go index a7637b64e4..c66bfb2136 100644 --- a/backend/internal/service/bedrock_stream.go +++ b/backend/internal/service/bedrock_stream.go @@ -188,7 +188,8 @@ func (s *GatewayService) handleBedrockStreamingResponse( // extractBedrockChunkData 从 Bedrock EventStream payload 中提取 Claude SSE 事件数据 // Bedrock payload 格式:{"bytes":""} func extractBedrockChunkData(payload []byte) []byte { - b64 := gjson.GetBytes(payload, "bytes").String() + // 零拷贝读取:b64 只在本函数内解码,解码结果写入新 buffer。 + b64 := parseRawJSONView(payload).Get("bytes").String() if b64 == "" { return nil } diff --git a/backend/internal/service/hot_path_zero_copy_test.go b/backend/internal/service/hot_path_zero_copy_test.go new file mode 100644 index 0000000000..81295e87ae --- /dev/null +++ b/backend/internal/service/hot_path_zero_copy_test.go @@ -0,0 +1,312 @@ +//go:build unit + +package service + +import ( + "fmt" + "math/rand" + "strings" + "testing" + + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" + "github.com/tidwall/sjson" +) + +// jsonUEscape spells the six-byte JSON escape backslash, 'u', hex at run time. +func jsonUEscape(hex string) string { return `\` + "u" + hex } + +// referenceNormalizeCompactionTriggerInputOrder always takes the decode path. +func referenceNormalizeCompactionTriggerInputOrder(body []byte) ([]byte, bool, error) { + if len(body) == 0 { + return body, false, nil + } + var payload map[string]any + if err := decodeOpenAIJSONUseNumber(body, &payload); err != nil { + return body, false, err + } + input, ok := payload["input"].([]any) + if !ok || len(input) == 0 { + return body, false, nil + } + triggerCount := 0 + normalized := make([]any, 0, len(input)) + for _, raw := range input { + item, itemOK := raw.(map[string]any) + if itemOK && item["type"] == "compaction_trigger" { + triggerCount++ + continue + } + normalized = append(normalized, raw) + } + if triggerCount == 0 { + return body, false, nil + } + if triggerCount == 1 { + if last, ok := input[len(input)-1].(map[string]any); ok && last["type"] == "compaction_trigger" { + return body, false, nil + } + } + normalized = append(normalized, map[string]any{"type": "compaction_trigger"}) + payload["input"] = normalized + encoded, err := marshalOpenAIUpstreamJSON(payload) + if err != nil { + return body, false, err + } + return encoded, true, nil +} + +func requireSameCompactionNormalization(t *testing.T, body []byte) { + t.Helper() + got, changed, err := NormalizeCompactionTriggerInputOrder(body) + want, wantChanged, wantErr := referenceNormalizeCompactionTriggerInputOrder(body) + require.Equal(t, wantErr != nil, err != nil, "error mismatch for %s", body) + require.Equal(t, wantChanged, changed, "changed mismatch for %s", body) + require.Equal(t, string(want), string(got), "body mismatch for %s", body) +} + +func TestCompactionTriggerOrderFastPathMatchesDecode(t *testing.T) { + trigger := `{"type":"compaction_trigger"}` + msg := `{"type":"message","role":"user","content":"hi"}` + cases := map[string]string{ + "trigger last": `{"model":"m","input":[` + msg + `,` + trigger + `]}`, + "trigger only": `{"input":[` + trigger + `]}`, + "trigger first": `{"input":[` + trigger + `,` + msg + `]}`, + "two triggers": `{"input":[` + trigger + `,` + msg + `,` + trigger + `]}`, + "token in text, trigger last": `{"input":[{"type":"message","content":"compaction_trigger"},` + trigger + `]}`, + "token only in text": `{"input":[{"type":"message","content":"compaction_trigger"}]}`, + "duplicate input key": `{"input":[` + msg + `,` + trigger + `],"input":[` + msg + `]}`, + "duplicate input key reversed": `{"input":[` + msg + `],"input":[` + msg + `,` + trigger + `]}`, + "duplicate type shadows trigger": `{"input":[` + msg + `,{"type":"compaction_trigger","type":"message"}]}`, + "duplicate type reveals trigger": `{"input":[{"type":"message","type":"compaction_trigger"},` + msg + `]}`, + "escaped trigger last": `{"input":[` + msg + `,{"type":"` + jsonUEscape("0063") + `ompaction_trigger"}]}`, + "escaped key trigger first": `{"input":[{"` + jsonUEscape("0074") + `ype":"compaction_trigger"},` + msg + `]}`, + "non-ascii escape, trigger last": `{"input":[{"type":"message","content":"caf` + jsonUEscape("00e9") + `"},` + trigger + `]}`, + "trigger value not string": `{"input":[` + msg + `,{"type":["compaction_trigger"]}]}`, + "last item not object": `{"input":[` + trigger + `,"compaction"]}`, + "input not array": `{"input":{"type":"compaction_trigger"}}`, + "trailing garbage": `{"input":[` + trigger + `]} x`, + "truncated": `{"input":[` + trigger, + "top-level array": `[{"input":[` + trigger + `]}]`, + "leading whitespace": " \n" + `{"input":[` + msg + `,` + trigger + `]}`, + } + for name, body := range cases { + t.Run(name, func(t *testing.T) { + requireSameCompactionNormalization(t, []byte(body)) + }) + } +} + +func TestCompactionTriggerOrderFastPathMatchesDecodeRandomized(t *testing.T) { + rng := rand.New(rand.NewSource(20261114)) + items := []string{ + `{"type":"compaction_trigger"}`, + `{"type":"message","role":"user","content":"hello"}`, + `{"type":"message","content":"mentions compaction_trigger"}`, + `{"type":"compaction_trigger","type":"message"}`, + `{"type":"message","type":"compaction_trigger"}`, + `{"type":"` + jsonUEscape("0063") + `ompaction_trigger"}`, + `{"type":"reasoning","encrypted_content":"` + jsonUEscape("001b") + `x"}`, + `"compaction_trigger"`, + `{"type":"function_call_output","output":""}`, + } + for i := 0; i < 20000; i++ { + var parts []string + for n := rng.Intn(5); n >= 0; n-- { + parts = append(parts, items[rng.Intn(len(items))]) + } + body := `{"model":"m","input":[` + strings.Join(parts, ",") + `]` + if rng.Intn(5) == 0 { + body += `,"input":[` + items[rng.Intn(len(items))] + `]` + } + body += `}` + if rng.Intn(20) == 0 { + body = body[:rng.Intn(len(body))] + } + requireSameCompactionNormalization(t, []byte(body)) + } +} + +func TestHasCompactionTriggerInInputLiteralGate(t *testing.T) { + require.True(t, HasCompactionTriggerInInput([]byte(`{"input":[{"type":"compaction_trigger"}]}`))) + require.True(t, HasCompactionTriggerInInput([]byte(`{"input":[{"type":"`+jsonUEscape("0063")+`ompaction_trigger"}]}`))) + require.False(t, HasCompactionTriggerInInput([]byte(`{"input":[{"type":"message","content":"caf`+jsonUEscape("00e9")+`"}]}`))) + require.False(t, HasCompactionTriggerInInput([]byte(`{"input":[{"type":"message","content":"compaction_trigger"}]}`))) +} + +func TestResponsesInputHasFunctionCallOutputNamed(t *testing.T) { + cases := []struct { + name string + body string + want bool + }{ + {"declared tool only", `{"tools":[{"type":"function","name":"automation_update"}],"input":[{"type":"function_call_output","call_id":"c","name":"other","output":"ok"}]}`, false}, + {"matching output", `{"input":[{"type":"function_call_output","name":"automation_update","output":"x"}]}`, true}, + {"prefix match", `{"input":[{"type":"function_call_output","name":"codex_apps_selected_page_part_1_of_2"}]}`, true}, + {"escaped key", `{"input":[{"` + jsonUEscape("0074") + `ype":"function_call_output","name":"automation_update"}]}`, true}, + {"escaped value", `{"input":[{"type":"function_call_output","name":"` + jsonUEscape("0061") + `utomation_update"}]}`, true}, + {"type not output", `{"input":[{"type":"function_call","name":"automation_update"}]}`, false}, + {"non-object item", `{"input":["function_call_output automation_update"]}`, false}, + {"input not array", `{"input":{"type":"function_call_output","name":"automation_update"}}`, false}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + require.Equal(t, tc.want, ResponsesInputHasFunctionCallOutputNamed([]byte(tc.body), "automation_update", "codex_apps_selected_page_part_")) + }) + } +} + +// referenceOpenAIRequestBodyHasTools is the scan without the literal gate. +func referenceOpenAIRequestBodyHasTools(body []byte) bool { + if tools := gjson.GetBytes(body, "tools"); tools.IsArray() && len(tools.Array()) > 0 { + return true + } + for _, item := range gjson.GetBytes(body, "input").Array() { + if strings.TrimSpace(item.Get("type").String()) != "additional_tools" { + continue + } + if tools := item.Get("tools"); tools.IsArray() && len(tools.Array()) > 0 { + return true + } + } + return false +} + +func TestOpenAIRequestBodyHasToolsMatchesScan(t *testing.T) { + bodies := []string{ + `{"tools":[{"type":"function","name":"f"}],"input":[]}`, + `{"tools":[],"input":[]}`, + `{"tools":[null]}`, + `{"tools":{},"input":"hi"}`, + `{"input":[{"type":"additional_tools","tools":[{"type":"namespace"}]}]}`, + `{"input":[{"type":" additional_tools ","tools":[{"type":"namespace"}]}]}`, + `{"input":[{"type":"additional_tools","tools":[]}]}`, + `{"input":[{"type":"` + jsonUEscape("0061") + `dditional_tools","tools":[1]}]}`, + `{"input":{"type":"additional_tools","tools":[1]}}`, + `{"input":null}`, + `{"input":"additional_tools"}`, + `{"input":[{"type":"message","content":"caf` + jsonUEscape("00e9") + `"}]}`, + } + for _, body := range bodies { + require.Equal(t, referenceOpenAIRequestBodyHasTools([]byte(body)), openAIRequestBodyHasTools([]byte(body)), body) + } +} + +func TestDeleteJSONPathIfPresent(t *testing.T) { + body := []byte(`{"model":"m","stream":true,"messages":[]}`) + got, err := deleteJSONPathIfPresent(body, "metadata") + require.NoError(t, err) + require.Same(t, &body[0], &got[0], "absent path must return the original buffer") + + for _, path := range []string{"model", "stream", "messages"} { + got, err := deleteJSONPathIfPresent(body, path) + require.NoError(t, err) + want, wantErr := sjson.DeleteBytes(body, path) + require.NoError(t, wantErr) + require.Equal(t, string(want), string(got)) + } + require.Equal(t, `{"model":"m","stream":true,"messages":[]}`, string(body)) + + allocs := testing.AllocsPerRun(20, func() { + _, _ = deleteJSONPathIfPresent(body, "provider") + }) + require.Zero(t, allocs) +} + +// referenceSanitizeBedrockCacheControl is the copying implementation. +func referenceSanitizeBedrockCacheControl(body []byte, modelID string) []byte { + isClaude45 := isBedrockClaude45OrNewer(modelID) + systemArr := gjson.GetBytes(body, "system") + if systemArr.Exists() && systemArr.IsArray() { + for i, item := range systemArr.Array() { + if !item.IsObject() { + continue + } + cc := item.Get("cache_control") + if !cc.Exists() || !cc.IsObject() { + continue + } + body = deleteCacheControlUnsupportedFields(body, fmt.Sprintf("system.%d.cache_control", i), cc, isClaude45) + } + } + messages := gjson.GetBytes(body, "messages") + if !messages.Exists() || !messages.IsArray() { + return body + } + for mi, msg := range messages.Array() { + if !msg.IsObject() { + continue + } + content := msg.Get("content") + if !content.Exists() || !content.IsArray() { + continue + } + for ci, block := range content.Array() { + if !block.IsObject() { + continue + } + cc := block.Get("cache_control") + if !cc.Exists() || !cc.IsObject() { + continue + } + body = deleteCacheControlUnsupportedFields(body, fmt.Sprintf("messages.%d.content.%d.cache_control", mi, ci), cc, isClaude45) + } + } + return body +} + +func TestSanitizeBedrockCacheControlMatchesCopyingScan(t *testing.T) { + rng := rand.New(rand.NewSource(7)) + ccs := []string{ + `{"type":"ephemeral"}`, + `{"type":"ephemeral","scope":"global"}`, + `{"type":"ephemeral","ttl":"5m"}`, + `{"type":"ephemeral","ttl":"1h","scope":"global"}`, + `{"type":"ephemeral","ttl":"30m"}`, + `"ephemeral"`, + } + block := func() string { + switch rng.Intn(4) { + case 0: + return `"plain"` + case 1: + return `{"type":"text","text":"a"}` + default: + return `{"type":"text","text":"b","cache_control":` + ccs[rng.Intn(len(ccs))] + `}` + } + } + blocks := func() string { + var parts []string + for n := rng.Intn(4); n >= 0; n-- { + parts = append(parts, block()) + } + return "[" + strings.Join(parts, ",") + "]" + } + for i := 0; i < 3000; i++ { + var msgs []string + for n := rng.Intn(4); n >= 0; n-- { + switch rng.Intn(4) { + case 0: + msgs = append(msgs, `{"role":"user","content":"text"}`) + case 1: + msgs = append(msgs, `"not an object"`) + default: + msgs = append(msgs, `{"role":"user","content":`+blocks()+`}`) + } + } + body := `{"system":` + blocks() + `,"messages":[` + strings.Join(msgs, ",") + `]}` + for _, model := range []string{"anthropic.claude-sonnet-4-6", "anthropic.claude-3-5-sonnet-20241022-v2:0"} { + want := referenceSanitizeBedrockCacheControl([]byte(body), model) + got := sanitizeBedrockCacheControl([]byte(body), model) + require.Equal(t, string(want), string(got), body) + } + } +} + +func TestExtractBedrockChunkDataReadsEscapedAndPlainBase64(t *testing.T) { + require.Equal(t, "hi", string(extractBedrockChunkData([]byte(`{"bytes":"aGk="}`)))) + require.Equal(t, "?>?", string(extractBedrockChunkData([]byte(`{"bytes":"Pz4\/"}`)))) + require.Nil(t, extractBedrockChunkData([]byte(`{"bytes":""}`))) + require.Nil(t, extractBedrockChunkData([]byte(`{"bytes":"%%%"}`))) + require.Nil(t, extractBedrockChunkData([]byte(`{"other":"aGk="}`))) +} diff --git a/backend/internal/service/json_escape_probe.go b/backend/internal/service/json_escape_probe.go new file mode 100644 index 0000000000..317bbbed7c --- /dev/null +++ b/backend/internal/service/json_escape_probe.go @@ -0,0 +1,71 @@ +package service + +import "bytes" + +// JSONMayEscapePlainASCII reports whether body contains a \u escape that spells a +// printable ASCII character no JSON encoder needs to escape (letters, digits, +// underscore, most punctuation). Only such an escape can hide a keyword made of +// those characters from a literal byte search, so when this returns false a +// bytes.Contains miss for such a keyword is a reliable negative. Keywords that +// contain an ignored character below need their own check. +// +// Escapes that encoders do emit on real traffic are ignored: control +// characters (the ANSI escape in shell output), quote, backslash, apostrophe, +// Go's HTML-safe escapes of <, > and &, and every non-ASCII rune. Large agent +// requests therefore keep their fast paths instead of being fully decoded. A +// malformed or truncated escape is reported as true to stay conservative. +// +// Escapes are consumed pairwise, so an escaped backslash followed by a literal +// u (Windows paths, regexes, code samples) is plain text, not an escape. +func JSONMayEscapePlainASCII(body []byte) bool { + for i := 0; ; { + j := bytes.IndexByte(body[i:], '\\') + if j < 0 { + return false + } + next := i + j + 1 + if next >= len(body) { + return true + } + if body[next] != 'u' { + i = next + 1 + continue + } + if next+5 > len(body) { + return true + } + r, ok := parseJSONHex4(body[next+1 : next+5]) + if !ok || jsonEscapeHidesPlainASCII(r) { + return true + } + i = next + 5 + } +} + +func parseJSONHex4(b []byte) (rune, bool) { + var r rune + for _, c := range b { + switch { + case c >= '0' && c <= '9': + r = r<<4 | rune(c-'0') + case c >= 'a' && c <= 'f': + r = r<<4 | rune(c-'a'+10) + case c >= 'A' && c <= 'F': + r = r<<4 | rune(c-'A'+10) + default: + return 0, false + } + } + return r, true +} + +func jsonEscapeHidesPlainASCII(r rune) bool { + if r < 0x20 || r >= 0x7f { + return false + } + switch r { + case '"', '\\', '<', '>', '&', '\'': + return false + } + return true +} diff --git a/backend/internal/service/json_escape_probe_test.go b/backend/internal/service/json_escape_probe_test.go new file mode 100644 index 0000000000..46b1f1d6d7 --- /dev/null +++ b/backend/internal/service/json_escape_probe_test.go @@ -0,0 +1,38 @@ +//go:build unit + +package service + +import ( + "testing" + + "github.com/stretchr/testify/require" +) + +func TestJSONMayEscapePlainASCII(t *testing.T) { + // U(hex) spells the six-byte JSON escape backslash, 'u', hex. + U := func(hex string) string { return `\` + "u" + hex } + cases := []struct { + name string + body string + want bool + }{ + {"no escapes", `{"input":[{"type":"message","content":"hi"}]}`, false}, + {"ansi control escape from shell output", `{"output":"` + U("001b") + `[31mred` + U("001b") + `[0m"}`, false}, + {"go html-safe escapes", `{"text":"a ` + U("003c") + ` b ` + U("0026") + ` c ` + U("003e") + ` d"}`, false}, + {"quote apostrophe and backslash escapes", `{"text":"` + U("0022") + U("0027") + U("005c") + `"}`, false}, + {"non-ascii and surrogate pair", `{"text":"caf` + U("00e9") + ` ` + U("d83d") + U("de00") + ` ` + U("4e2d") + `"}`, false}, + {"escaped letter hides a keyword", `{"type":"` + U("0063") + `ompaction_trigger"}`, true}, + {"upper-case hex escaped underscore", `{"type":"input` + U("005F") + `image"}`, true}, + {"escaped digit", `{"n":"` + U("0031") + `"}`, true}, + {"escaped backslash before u is literal text", `{"code":"\` + U("0041") + `"}`, false}, + {"escaped backslash in a path", `{"cwd":"C:\\users\\dev","re":"\\u{1F600}"}`, false}, + {"escape after an escaped backslash", `{"t":"\\` + U("0063") + `"}`, true}, + {"truncated escape", `{"t":"` + U("00"), true}, + {"invalid hex", `{"t":"` + U("ZZZZ") + `"}`, true}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + require.Equal(t, tc.want, JSONMayEscapePlainASCII([]byte(tc.body))) + }) + } +} diff --git a/backend/internal/service/openai_call_output_probe.go b/backend/internal/service/openai_call_output_probe.go new file mode 100644 index 0000000000..ff82ea8eb5 --- /dev/null +++ b/backend/internal/service/openai_call_output_probe.go @@ -0,0 +1,35 @@ +package service + +import ( + "strings" + + "github.com/tidwall/gjson" +) + +// ResponsesInputHasFunctionCallOutputNamed reports whether the top-level input +// array holds an object item whose type is "function_call_output" and whose +// name starts with one of namePrefixes. Keys and string values are compared +// after JSON unescaping, through a zero-copy view of body. When a member is +// duplicated, the first occurrence is read; callers that decode the body +// treat duplicate members separately. +func ResponsesInputHasFunctionCallOutputNamed(body []byte, namePrefixes ...string) bool { + input := parseRawJSONView(body).Get("input") + if !input.IsArray() { + return false + } + found := false + input.ForEach(func(_, item gjson.Result) bool { + if !item.IsObject() || item.Get("type").String() != "function_call_output" { + return true + } + name := item.Get("name").String() + for _, prefix := range namePrefixes { + if strings.HasPrefix(name, prefix) { + found = true + return false + } + } + return true + }) + return found +} diff --git a/backend/internal/service/openai_compact_body_signal.go b/backend/internal/service/openai_compact_body_signal.go index a545f1cfd6..f570d3303b 100644 --- a/backend/internal/service/openai_compact_body_signal.go +++ b/backend/internal/service/openai_compact_body_signal.go @@ -67,16 +67,46 @@ func NormalizeCompactionTriggerInputOrder(body []byte) ([]byte, bool, error) { return encoded, true, nil } -// compactionTriggerNeedsDecode lets bodies that cannot hold a trigger skip the -// full decode: the type string appears literally unless a \u escape spells it. -// Such a body must still be a valid JSON object, so decode errors keep -// surfacing from the original path. +var compactionTriggerToken = []byte("compaction_trigger") + +// compactionTriggerNeedsDecode lets bodies whose input order cannot change +// skip the full decode. Without a \u escape that spells plain ASCII, every +// decoded "compaction_trigger" string is a literal occurrence of the token, so: +// - no occurrence means no trigger; +// - a single occurrence that is the type of the last input item, as read +// through the zero-copy view, means the decoder sees either that same item +// as the only trigger or, when a duplicate member shadows it, no trigger. +// +// Either way the body is returned unchanged. Such a body must still be a valid +// JSON object, so decode errors keep surfacing from the original path. func compactionTriggerNeedsDecode(body []byte) bool { - if bytes.Contains(body, []byte("compaction_trigger")) || bytes.Contains(body, []byte(`\u`)) { + if JSONMayEscapePlainASCII(body) { return true } - trimmed := bytes.TrimLeft(body, " \t\r\n") - return len(trimmed) == 0 || trimmed[0] != '{' || !gjson.ValidBytes(body) + switch bytes.Count(body, compactionTriggerToken) { + case 0: + trimmed := bytes.TrimLeft(body, " \t\r\n") + return len(trimmed) == 0 || trimmed[0] != '{' || !gjson.ValidBytes(body) + case 1: + return !compactionTriggerIsLastInputItem(body) || !gjson.ValidBytes(body) + default: + return true + } +} + +// compactionTriggerIsLastInputItem reports whether the last element of the +// top-level input array is an object whose type is "compaction_trigger". +func compactionTriggerIsLastInputItem(body []byte) bool { + input := parseRawJSONView(body).Get("input") + if !input.IsArray() { + return false + } + var last gjson.Result + input.ForEach(func(_, item gjson.Result) bool { + last = item + return true + }) + return last.IsObject() && last.Get("type").String() == "compaction_trigger" } func isOpenAINativeCompactionV2(c *gin.Context) bool { @@ -177,12 +207,17 @@ func applyOpenAICodexBetaFeatures(c *gin.Context, account *Account, h http.Heade // HasCompactionTriggerInInput detects an input item with // type="compaction_trigger". The handler combines this body signal with the // request path and stream flag to distinguish the native remote compaction v2 -// wire from the legacy /responses/compact bridge. +// wire from the legacy /responses/compact bridge. The type string appears +// literally unless a \u escape spells plain ASCII, so other bodies skip the +// structural scan. func HasCompactionTriggerInInput(body []byte) bool { if len(body) == 0 { return false } - input := gjson.GetBytes(body, "input") + if !bytes.Contains(body, compactionTriggerToken) && !JSONMayEscapePlainASCII(body) { + return false + } + input := parseRawJSONView(body).Get("input") if !input.IsArray() { return false } diff --git a/backend/internal/service/openai_gateway_request_body.go b/backend/internal/service/openai_gateway_request_body.go index b7e4514405..ea449fbf35 100644 --- a/backend/internal/service/openai_gateway_request_body.go +++ b/backend/internal/service/openai_gateway_request_body.go @@ -653,19 +653,43 @@ func normalizeOpenAIParallelToolCallsWithoutTools(body []byte, responsesLite boo } // openAIRequestBodyHasTools 同时识别顶层 tools 和 input[].additional_tools。 +// additional_tools 类型字符串只有在字面出现、或被能拼出可见 ASCII 的 \u 转义 +// 拼出时才可能匹配,其余请求体跳过对 input 的结构扫描。 func openAIRequestBodyHasTools(body []byte) bool { - if tools := gjson.GetBytes(body, "tools"); tools.IsArray() && len(tools.Array()) > 0 { + root := parseRawJSONView(body) + if gjsonArrayHasElements(root.Get("tools")) { return true } - for _, item := range gjson.GetBytes(body, "input").Array() { - if strings.TrimSpace(item.Get("type").String()) != "additional_tools" { - continue - } - if tools := item.Get("tools"); tools.IsArray() && len(tools.Array()) > 0 { - return true - } + if !bytes.Contains(body, []byte("additional_tools")) && !JSONMayEscapePlainASCII(body) { + return false } - return false + found := false + isAdditionalToolsWithTools := func(item gjson.Result) bool { + return strings.TrimSpace(item.Get("type").String()) == "additional_tools" && gjsonArrayHasElements(item.Get("tools")) + } + input := root.Get("input") + if !input.IsArray() { + // gjson 把非数组的值当作只含它自身的数组。 + return input.Type != gjson.Null && isAdditionalToolsWithTools(input) + } + input.ForEach(func(_, item gjson.Result) bool { + found = isAdditionalToolsWithTools(item) + return !found + }) + return found +} + +// gjsonArrayHasElements 不分配结果切片地判断数组是否非空。 +func gjsonArrayHasElements(value gjson.Result) bool { + if !value.IsArray() { + return false + } + nonEmpty := false + value.ForEach(func(_, _ gjson.Result) bool { + nonEmpty = true + return false + }) + return nonEmpty } // normalizeOpenAIResponsesReasoningContentReplay removes non-portable @@ -2489,7 +2513,7 @@ func openAIRequestBodyMayContainEmptyBase64InputImage(body []byte) bool { if len(body) == 0 || !openAIRequestBodyMayContainInputImageToken(body) { return false } - input := gjson.GetBytes(body, "input") + input := parseRawJSONView(body).Get("input") if !input.Exists() { return false } @@ -2500,8 +2524,9 @@ func openAIRequestBodyMayContainInputImageToken(body []byte) bool { if bytes.Contains(body, []byte("input_image")) { return true } - // JSON 字符串任意字符都可能被 unicode escape,遇到 \u 时交给 gjson 解码后的结构扫描兜底。 - return bytes.Contains(body, []byte("\\u")) + // JSON 字符串任意字符都可能被 unicode escape;只有能拼出可见 ASCII 字符的 \u + // 才可能藏住 input_image,此时交给 gjson 解码后的结构扫描兜底。 + return JSONMayEscapePlainASCII(body) } func openAIJSONValueMayContainEmptyBase64InputImage(value gjson.Result) bool { diff --git a/backend/internal/service/openai_reasoning_effort_policy.go b/backend/internal/service/openai_reasoning_effort_policy.go index b8f7f3b409..fa023101cf 100644 --- a/backend/internal/service/openai_reasoning_effort_policy.go +++ b/backend/internal/service/openai_reasoning_effort_policy.go @@ -111,11 +111,13 @@ func IsReasoningEffortPolicyDenied(err error) bool { return errors.As(err, &mappingDenied) } +var reasoningEffortSeparatorRemover = strings.NewReplacer("-", "", "_", "", " ", "") + // NormalizeMaxReasoningEffort validates and canonicalizes a group policy value. // Empty means that the group does not impose a ceiling. func NormalizeMaxReasoningEffort(raw string) string { value := strings.ToLower(strings.TrimSpace(raw)) - value = strings.NewReplacer("-", "", "_", "", " ", "").Replace(value) + value = reasoningEffortSeparatorRemover.Replace(value) switch value { case "": return "" diff --git a/backend/internal/service/openai_responses_namespace.go b/backend/internal/service/openai_responses_namespace.go index 17ee436064..3978518ed9 100644 --- a/backend/internal/service/openai_responses_namespace.go +++ b/backend/internal/service/openai_responses_namespace.go @@ -120,7 +120,8 @@ func hasOpenAIResponsesNamespaceToolDeclaration(body []byte) bool { return found } - if hasNamespaceTool(gjson.GetBytes(body, "tools")) { + root := parseRawJSONView(body) + if hasNamespaceTool(root.Get("tools")) { return true } @@ -128,7 +129,7 @@ func hasOpenAIResponsesNamespaceToolDeclaration(body []byte) bool { // tools and into an input.additional_tools carrier. API-key requests are // intentionally not rewritten by normalizeOpenAIResponsesLiteTools, so the // declaration can arrive here only in this form. - input := gjson.GetBytes(body, "input") + input := root.Get("input") if !input.IsArray() { return false } @@ -196,7 +197,9 @@ func stripOpenAIResponsesInputNamespaces(body []byte, keepToolCallNamespaces boo if !bytes.Contains(body, []byte(`"namespace"`)) { return body, nil } - input := gjson.GetBytes(body, "input") + // Zero-copy view: input.Raw aliases body and is only read below; the + // rebuilt array is written into a fresh buffer. + input := parseRawJSONView(body).Get("input") if !input.IsArray() { return body, nil }