mirror of
https://github.com/Wei-Shaw/sub2api.git
synced 2026-12-05 16:07:33 +00:00
sanitizeOpenAIResponsesToolSchemasForPlatform runs on every OpenAI Responses
forward attempt, on WS normalization and on /v1/messages conversion, and its two
passes both ran far more often than they need to:
* the regex-pattern pass was gated on "the body contains '('", and tool
descriptions, code samples and user messages contain parentheses
constantly, so the gate let essentially everything through;
* the parameter-type pass had no gate at all and ran for OpenAI, Anthropic,
Grok and every CN platform.
A 1MiB Codex request therefore walked its body twice with the hand-written
parser before reaching the upstream. Profiling put 92% of that in parseString,
which scanned strings byte by byte while long content strings are most of a
request body.
Changes:
1. parseString skips the plain run of a string eight bytes at a time (SWAR),
stopping only on '"', '\\' or a control byte - exactly the three bytes it has
to stop at. 2.2 GB/s -> 10.5 GB/s.
2. An input item is no longer walked twice. The type probe walked the whole item
and then the item was walked again just to skip it; the probe's end position
is now reused. Messages dominate input history.
3. json.Valid(body) only runs when the walk actually produced an edit. With no
edits the body is returned untouched, so that second full-body validation
proved nothing; patches are still validated after they are applied.
4. Both gates are now necessary conditions that can be proven complete.
hasUnsupportedOpenAIRegexPattern only fires on an unsupported backslash
escape, a trailing backslash, or group syntax "(?"; the first two need a
decoded backslash, which JSON can only spell "\\\\" or \\u005c, and the third
can have either character escaped. The parameter pass only edits a literal
null value or a oneOf/anyOf union, and the union repair accepts any
parameters object containing a backslash, so an escaped keyword such as
"one\\u004ff" counts too - hence the \\u00XX needle.
5. Patterns are checked in place when the JSON span carries no escape, instead
of strconv.Unquote per pattern, and object member names are parsed once into
openAIResponsesJSONKey rather than rescanning the span for every candidate
name.
Benchmark (Apple M5 Pro, 1MiB Codex-shaped body: 30 tools + 1MiB input):
platform entry, OpenAI 7.48ms / 512 allocs -> 96us / 0 allocs
platform entry, Anthropic 3.75ms / 256 allocs -> 66us / 0 allocs
patterns pass 3.71ms / 256 allocs -> 30us / 0 allocs
parameter-types pass 3.69ms / 256 allocs -> 66us / 0 allocs
Existing benchmarks:
..._Patterns_ByteSpanPatch 1586609ns / 2017 allocs -> 915199ns / 17
..._ParameterTypes_ByteSpanPatch 1011697ns / 17 allocs -> 647160ns / 17
Correctness: parseString keeps the previous byte-at-a-time scanner as legacy*
and compares return values and error positions across a corpus plus fuzzing;
the probe reuse asserts that the probe and the skip walk stop at the same byte;
the gates are pinned by the invariant "if the sanitizer changed the body, the
gate must have let it through", over a corpus that spells out every unsupported
pattern shape and fuzzing; dropping the pre-edit json.Valid relies on "the
parser accepts implies encoding/json accepts", which is fuzzed too.
Fuzzing found two bugs in this change, both fixed and kept as regression seeds
under testdata/fuzz: an out-of-range read when a body ended in "\\\\", and a gate
that was narrower than the necessary condition for a pattern whose value is a
lone backslash. The second means such patterns are now cleaned up where the old
gate only caught them by accident, when the body happened to contain a
parenthesis elsewhere.
130 lines
4.0 KiB
Go
130 lines
4.0 KiB
Go
package service
|
|
|
|
import (
|
|
"fmt"
|
|
"strings"
|
|
"testing"
|
|
)
|
|
|
|
// buildToolSchemaBenchmarkBody 造一份贴近真实 Codex 请求的 body:小 tools 数组 +
|
|
// 大 input 历史。description 里带括号,因为真实工具的说明几乎都有。
|
|
func buildToolSchemaBenchmarkBody(targetBytes, tools int, withLookaround bool) []byte {
|
|
var sb strings.Builder
|
|
sb.Grow(targetBytes + 4096)
|
|
write := func(s string) { _, _ = sb.WriteString(s) }
|
|
write(`{"model":"gpt-5.6","stream":true,"instructions":"You are Codex, a coding agent.","tools":[`)
|
|
for i := 0; i < tools; i++ {
|
|
if i > 0 {
|
|
write(",")
|
|
}
|
|
pattern := ""
|
|
if withLookaround && i == 0 {
|
|
pattern = `,"pattern":"(?=x).*"`
|
|
}
|
|
write(fmt.Sprintf(
|
|
`{"type":"function","name":"tool_%d","description":"Runs a shell command (supports pipes).","parameters":{"type":"object","properties":{"query":{"type":"string"%s},"limit":{"type":"integer","minimum":1}},"required":["query"]}}`,
|
|
i, pattern))
|
|
}
|
|
write(`],"input":[`)
|
|
item := `{"type":"message","role":"user","content":[{"type":"input_text","text":"` + strings.Repeat("x", 4000) + `"}]}`
|
|
for i := 0; sb.Len() < targetBytes; i++ {
|
|
if i > 0 {
|
|
write(",")
|
|
}
|
|
write(item)
|
|
}
|
|
write(`]}`)
|
|
return []byte(sb.String())
|
|
}
|
|
|
|
// ungated 是改动前入口在这类 body 上的实际走向:旧的预检查是「body 里有 (」,
|
|
// 而工具说明几乎都带括号,所以请求无一例外走整趟解析。
|
|
func benchmarkToolSchemaEntry(
|
|
b *testing.B, body []byte,
|
|
ungated func([]byte) ([]byte, bool, error),
|
|
gated func([]byte) ([]byte, bool, error),
|
|
) {
|
|
b.Helper()
|
|
b.Run("ungated", func(b *testing.B) {
|
|
b.SetBytes(int64(len(body)))
|
|
b.ReportAllocs()
|
|
for range b.N {
|
|
_, _, _ = ungated(body)
|
|
}
|
|
})
|
|
b.Run("gated", func(b *testing.B) {
|
|
b.SetBytes(int64(len(body)))
|
|
b.ReportAllocs()
|
|
for range b.N {
|
|
_, _, _ = gated(body)
|
|
}
|
|
})
|
|
}
|
|
|
|
func BenchmarkSanitizeOpenAIResponsesToolSchemaPatternsClean1MiB(b *testing.B) {
|
|
body := buildToolSchemaBenchmarkBody(1<<20, 30, false)
|
|
benchmarkToolSchemaEntry(b, body,
|
|
func(in []byte) ([]byte, bool, error) {
|
|
return sanitizeOpenAIResponsesToolSchemas(in, openAIResponsesToolSchemaOptions{removeUnsupportedRegexPatterns: true})
|
|
},
|
|
sanitizeOpenAIResponsesToolSchemaPatterns,
|
|
)
|
|
}
|
|
|
|
func BenchmarkSanitizeOpenAIResponsesToolParameterTypesClean1MiB(b *testing.B) {
|
|
body := buildToolSchemaBenchmarkBody(1<<20, 30, false)
|
|
benchmarkToolSchemaEntry(b, body,
|
|
func(in []byte) ([]byte, bool, error) {
|
|
return sanitizeOpenAIResponsesToolSchemas(in, openAIResponsesToolSchemaOptions{
|
|
replaceNullParameterTypes: true,
|
|
injectObjectUnionRootObjectType: true,
|
|
dropNullRequired: true,
|
|
})
|
|
},
|
|
sanitizeOpenAIResponsesToolParameterTypes,
|
|
)
|
|
}
|
|
|
|
func BenchmarkOpenAIResponsesToolSchemaGates(b *testing.B) {
|
|
body := buildToolSchemaBenchmarkBody(1<<20, 30, false)
|
|
b.Run("unsupported_regex", func(b *testing.B) {
|
|
b.SetBytes(int64(len(body)))
|
|
for range b.N {
|
|
_ = openAIResponsesBodyMayContainUnsupportedRegex(body)
|
|
}
|
|
})
|
|
b.Run("parameter_repair", func(b *testing.B) {
|
|
b.SetBytes(int64(len(body)))
|
|
for range b.N {
|
|
_ = openAIResponsesBodyMayNeedToolParameterRepair(body)
|
|
}
|
|
})
|
|
}
|
|
|
|
// 字符串扫描是解析里最重的一段:请求体的大头是长内容字符串。
|
|
func BenchmarkOpenAIResponsesJSONStringScan(b *testing.B) {
|
|
body := []byte(`"` + strings.Repeat("abcdefgh", 1<<14) + `"`)
|
|
b.Run("legacy", func(b *testing.B) {
|
|
b.SetBytes(int64(len(body)))
|
|
for range b.N {
|
|
_, _, _, _ = legacyParseOpenAIResponsesJSONString(body, 0)
|
|
}
|
|
})
|
|
b.Run("current", func(b *testing.B) {
|
|
b.SetBytes(int64(len(body)))
|
|
for range b.N {
|
|
_ = currentParseOpenAIResponsesJSONString(body, 0)
|
|
}
|
|
})
|
|
}
|
|
|
|
// 平台入口就是三个调用点(HTTP 转发、WS 归一化、/v1/messages 转换)实际走的路径。
|
|
func BenchmarkSanitizeOpenAIResponsesToolSchemasForPlatformClean1MiB(b *testing.B) {
|
|
body := buildToolSchemaBenchmarkBody(1<<20, 30, false)
|
|
b.SetBytes(int64(len(body)))
|
|
b.ReportAllocs()
|
|
for range b.N {
|
|
_, _, _ = sanitizeOpenAIResponsesToolSchemasForPlatform(body, PlatformOpenAI)
|
|
}
|
|
}
|