Files
sub2api/backend/internal/service/json_escape_probe_test.go
T
feeeei ade20f4e47 perf(gateway): 请求体热点路径改用零拷贝读取,减少整段解码与复制
大请求体上,几个只读检查一遇到任意 \u 转义就整段解码,gjson.GetBytes 会复制整段
input/messages,sjson 删除不存在的键时也会先复制整个 body。

- 新增 JSONMayEscapePlainASCII:成对扫描 JSON 转义,只有能拼出可见 ASCII 的 \u 才让
  字面量快速判断失效;控制字符、HTML 安全转义和非 ASCII 字符的转义不再触发完整解码。
  用于 codex bootstrap / page context 候选、compaction_trigger、input_image、
  additional_tools 的快速判断。
- OpenAI Responses:
  - namespace 声明、tools 判断、空 base64 图片、compaction_trigger 检测与 namespace
    剥离改用 parseRawJSONView,不再复制整段 input/tools。
  - compaction_trigger 只字面出现一次且是 input 最后一项的 type 时跳过完整解码。
  - codex 调用输出候选在字面量命中后,用零拷贝视图确认 input 中确有对应名字的
    function_call_output 项;只在工具声明里出现同名时不再做唯一性扫描和完整解码。
- Bedrock:
  - 顶层字段删除前先用零拷贝视图确认存在。
  - cache_control 清理和流事件 bytes 字段改用零拷贝读取。
- NormalizeMaxReasoningEffort 复用包级 strings.Replacer。

合法 JSON 上行为不变,新增测试与总走解码/复制的参考实现做差分比较。只在非法或病态
body 上有差异:嵌套超过 10000 层且只含非 ASCII 转义、或 trigger 已在末尾时,不再报
解码深度错误(gjson 校验没有深度上限,无字面量 body 原本即如此);开头带非 JSON
前缀的非法 body,零拷贝视图读不到其后的对象,这类 body 随后仍被 JSON 校验拒绝。
2026-11-15 00:05:38 +08:00

39 lines
1.6 KiB
Go

//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)))
})
}
}