perf(openai): stop copying the whole input array when stripping namespaces

stripOpenAIResponsesInputNamespaces runs on every OpenAI OAuth / API-key HTTP
forward attempt. Its entry check only proves that the *body* contains a
namespace literal, and Codex clients advertise the image_gen namespace tool on
ordinary requests, so the check passes for most traffic and the function runs
even when there is nothing to strip.

Three avoidable copies showed up in that path:

1. gjson.GetBytes(body, "input") materialises the input array. On a 1MiB body
   that is a 1MiB allocation on every request, including the no-op case.
   Use the zero-copy parse view (parseRawJSONView) instead.
2. The rewrite built the new input array in a buffer and then handed it to
   sjson.SetRawBytes, which allocates a second full body copy. Assemble the
   output directly instead: prefix + rewritten array + suffix in one buffer
   sized to the body.
3. sjson.DeleteBytes([]byte(item.Raw), ...) converted each changed item to a
   byte slice first. Use the string form.

hasOpenAIResponsesNamespaceToolDeclaration reads input the same way and gets
the same treatment; it runs for API-key accounts on every request.

Benchmark (Apple M5 Pro, -benchmem), legacy = the previous implementation:

  1MiB tools_only    545us / 1056768 B / 1 alloc  ->  495us / 0 B / 0 alloc
  1MiB strip_first   882us / 3170624 B / 8 allocs ->  548us / 1056936 B / 4
  1MiB strip_last    841us / 3170624 B / 8 allocs ->  556us / 1056928 B / 4
  8MiB strip_first  5.95ms / 25190720 B / 8       -> 4.30ms / 8396960 B / 4

So the no-op path stops allocating entirely and the rewriting path copies one
body instead of three.

Behaviour is unchanged for valid JSON: equivalence tests keep the previous
implementation as legacy* and compare output bytes, errors and whether the
input slice was returned untouched, across 36 bodies (duplicate keys, escaped
keys, nested namespace fields, non-object items, keep-tool-call mode, missing
or non-array input) plus 3000 randomized combinations and a fuzz target.

One deliberate difference, pinned by a test: on input that is not valid JSON,
gjson.GetBytes and gjson.Parse return different spans for the same key, and
the new implementation refuses to rewrite an unparseable fragment instead of
truncating it. The only caller forwards a body that the handler has already
validated, so this path is not reachable in production.
This commit is contained in:
lishuangqiang committed 2026-11-17 00:10:26 +08:00
1 parent 9cd1a1eb21
commit 049e0f41b8
3 files changed
+284 -25

No files matched your search

@@ -14,6 +14,11 @@ import (
const openAIResponsesNamespaceNamesContextKey = "openai_responses_namespace_names"
// openAIResponsesNamespaceFieldBytes 是入口预检查用的字面量。带引号可避免匹配到
// 正文里的普通单词;键写成 unicode 转义时无法字节匹配,那条路径不会进入清理逻辑,
// 与改动前一致。
var openAIResponsesNamespaceFieldBytes = []byte(`"namespace"`)
// shouldFlattenOpenAIResponsesNamespaces 判定原生 Responses 转发前是否摊平
// Codex namespace 工具。
//
@@ -120,6 +125,7 @@ func hasOpenAIResponsesNamespaceToolDeclaration(body []byte) bool {
return found
}
// 与 stripOpenAIResponsesInputNamespaces 同理:input 可能很大,用零拷贝视图取值。
root := parseRawJSONView(body)
if hasNamespaceTool(root.Get("tools")) {
return true
@@ -163,7 +169,7 @@ func isOpenAIResponsesToolCallItemType(itemType string) bool {
}
func flattenOpenAIResponsesNamespaces(c *gin.Context, body []byte) ([]byte, error) {
if !bytes.Contains(body, []byte(`"namespace"`)) {
if !bytes.Contains(body, openAIResponsesNamespaceFieldBytes) {
return body, nil
}
var requestBody map[string]any
@@ -190,22 +196,28 @@ func flattenOpenAIResponsesNamespaces(c *gin.Context, body []byte) ([]byte, erro
// untouched. Rebuilding the input array once keeps this linear for long
// histories and avoids decoding JSON numbers through float64.
//
// 读取走 parseRawJSONView(零拷贝 string 视图)而不是 gjson.GetBytes:后者会把
// input 数组物化成一份拷贝,而这个函数在 Codex 流量上几乎每个请求都会进来
// (tools 里就有 namespace 声明,入口预检查必然放行),未改动时那份拷贝纯属浪费。
//
// keepToolCallNamespaces 保留工具调用项(function_call / custom_tool_call 等)上的
// namespace,让 Codex 调用能按上游要求原样回传;判定见
// shouldKeepOpenAIResponsesToolCallNamespaces。
func stripOpenAIResponsesInputNamespaces(body []byte, keepToolCallNamespaces bool) ([]byte, error) {
if !bytes.Contains(body, []byte(`"namespace"`)) {
if !bytes.Contains(body, openAIResponsesNamespaceFieldBytes) {
return body, nil
}
// 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
}
// inputStart/inputEnd 是 input 数组在 body 里的字节区间。
inputStart := input.Index
inputEnd := inputStart + len(input.Raw)
var rebuilt bytes.Buffer
changed := false
// 输出缓冲只在首次真正改写时分配,容量按整个 body 预留,prefix + 改写后的数组 +
// suffix 一次写完,不再额外走一遍 sjson.SetRawBytes(那会再拷一份完整 body)。
var out []byte
// Offsets below are relative to input.Raw, not the full request body.
copyFrom := 0
var stripErr error
@@ -214,35 +226,30 @@ func stripOpenAIResponsesInputNamespaces(body []byte, keepToolCallNamespaces boo
(keepToolCallNamespaces && isOpenAIResponsesToolCallItemType(item.Get("type").String())) {
return true
}
itemBody, err := sjson.DeleteBytes([]byte(item.Raw), "namespace")
itemBody, err := sjson.Delete(item.Raw, "namespace")
if err != nil {
stripErr = err
return false
}
if !changed {
// Allocate only on the first change; copy unchanged spans without
// traversing their items again or converting them to byte slices.
rebuilt.Grow(len(input.Raw))
changed = true
if out == nil {
out = make([]byte, 0, len(body))
out = append(out, body[:inputStart]...)
}
itemStart := item.Index - input.Index
_, _ = rebuilt.WriteString(input.Raw[copyFrom:itemStart])
_, _ = rebuilt.Write(itemBody)
out = append(out, input.Raw[copyFrom:itemStart]...)
out = append(out, itemBody...)
copyFrom = itemStart + len(item.Raw)
return true
})
if stripErr != nil {
return body, fmt.Errorf("delete OpenAI input namespace: %w", stripErr)
}
if !changed {
if out == nil {
return body, nil
}
_, _ = rebuilt.WriteString(input.Raw[copyFrom:])
stripped, err := sjson.SetRawBytes(body, "input", rebuilt.Bytes())
if err != nil {
return body, fmt.Errorf("replace OpenAI input after namespace deletion: %w", err)
}
return stripped, nil
out = append(out, input.Raw[copyFrom:]...)
out = append(out, body[inputEnd:]...)
return out, nil
}
func setOpenAIResponsesNamespaceNames(c *gin.Context, names map[string]apicompat.ResponsesNamespaceName) {
@@ -10,7 +10,9 @@ import (
"github.com/tidwall/gjson"
)
func BenchmarkStripOpenAIResponsesInputNamespaces(b *testing.B) {
type stripFunc func(body []byte, keep bool) ([]byte, error)
func benchmarkStripOpenAIResponsesInputNamespaces(b *testing.B, variant string, fn stripFunc) {
for _, size := range []int{1 << 20, 8 << 20} {
message := `{"type":"message","content":"` + strings.Repeat("x", size) + `"}`
call := `{"type":"function_call","namespace":"files","name":"search"}`
@@ -20,15 +22,16 @@ func BenchmarkStripOpenAIResponsesInputNamespaces(b *testing.B) {
keep bool
stripIndex int
}{
// tools 里带 namespace 声明、input 里没有:Codex 常态,入口预检查必然放行。
{"tools_only", message, false, -1},
{"nested_only", `{"content":{"namespace":"nested"}},` + message, false, -1},
{"keep_calls", call + "," + message, true, -1},
{"strip_first", call + "," + message, false, 0},
{"strip_last", message + "," + call, false, 1},
} {
b.Run(fmt.Sprintf("%s/%dMiB", tc.name, size>>20), func(b *testing.B) {
b.Run(fmt.Sprintf("%s/%s/%dMiB", variant, tc.name, size>>20), func(b *testing.B) {
body := []byte(`{"tools":[{"type":"namespace","name":"files","tools":[]}],"input":[` + tc.input + `]}`)
out, err := stripOpenAIResponsesInputNamespaces(body, tc.keep)
out, err := fn(body, tc.keep)
if err != nil {
b.Fatal(err)
}
@@ -43,7 +46,7 @@ func BenchmarkStripOpenAIResponsesInputNamespaces(b *testing.B) {
b.SetBytes(int64(len(body)))
b.ResetTimer()
for i := 0; i < b.N; i++ {
out, err = stripOpenAIResponsesInputNamespaces(body, tc.keep)
out, err = fn(body, tc.keep)
if err != nil {
b.Fatal(err)
}
@@ -53,3 +56,11 @@ func BenchmarkStripOpenAIResponsesInputNamespaces(b *testing.B) {
}
}
}
func BenchmarkStripOpenAIResponsesInputNamespaces(b *testing.B) {
benchmarkStripOpenAIResponsesInputNamespaces(b, "current", stripOpenAIResponsesInputNamespaces)
}
func BenchmarkStripOpenAIResponsesInputNamespacesLegacy(b *testing.B) {
benchmarkStripOpenAIResponsesInputNamespaces(b, "legacy", legacyStripOpenAIResponsesInputNamespaces)
}
@@ -0,0 +1,241 @@
package service
import (
"bytes"
"fmt"
"strings"
"testing"
"github.com/stretchr/testify/require"
"github.com/tidwall/gjson"
"github.com/tidwall/sjson"
)
// legacyStripOpenAIResponsesInputNamespaces 是改动前的逐字副本,作为差分基准。
func legacyStripOpenAIResponsesInputNamespaces(body []byte, keepToolCallNamespaces bool) ([]byte, error) {
if !bytes.Contains(body, []byte(`"namespace"`)) {
return body, nil
}
input := gjson.GetBytes(body, "input")
if !input.IsArray() {
return body, nil
}
var rebuilt bytes.Buffer
changed := false
copyFrom := 0
var stripErr error
input.ForEach(func(_, item gjson.Result) bool {
if !item.IsObject() || !item.Get("namespace").Exists() ||
(keepToolCallNamespaces && isOpenAIResponsesToolCallItemType(item.Get("type").String())) {
return true
}
itemBody, err := sjson.DeleteBytes([]byte(item.Raw), "namespace")
if err != nil {
stripErr = err
return false
}
if !changed {
rebuilt.Grow(len(input.Raw))
changed = true
}
itemStart := item.Index - input.Index
_, _ = rebuilt.WriteString(input.Raw[copyFrom:itemStart])
_, _ = rebuilt.Write(itemBody)
copyFrom = itemStart + len(item.Raw)
return true
})
if stripErr != nil {
return body, fmt.Errorf("delete OpenAI input namespace: %w", stripErr)
}
if !changed {
return body, nil
}
_, _ = rebuilt.WriteString(input.Raw[copyFrom:])
stripped, err := sjson.SetRawBytes(body, "input", rebuilt.Bytes())
if err != nil {
return body, fmt.Errorf("replace OpenAI input after namespace deletion: %w", err)
}
return stripped, nil
}
type stripSnapshot struct {
err string
output string
unchanged bool // 是否原样返回了传入的 slice(两个实现都应如此)
}
func stripSnapshotOf(out []byte, err error, body []byte) stripSnapshot {
snap := stripSnapshot{}
if err != nil {
snap.err = err.Error()
}
snap.output = string(out)
if len(out) == len(body) && len(body) > 0 && &out[0] == &body[0] {
snap.unchanged = true
}
if len(out) == 0 && len(body) == 0 {
snap.unchanged = true
}
return snap
}
func stripBoth(t *testing.T, input string, keep bool) (stripSnapshot, stripSnapshot) {
t.Helper()
legacyBody := []byte(input)
legacyOut, legacyErr := legacyStripOpenAIResponsesInputNamespaces(legacyBody, keep)
newBody := []byte(input)
newOut, newErr := stripOpenAIResponsesInputNamespaces(newBody, keep)
return stripSnapshotOf(legacyOut, legacyErr, legacyBody), stripSnapshotOf(newOut, newErr, newBody)
}
func TestStripOpenAIResponsesInputNamespacesMatchesLegacy(t *testing.T) {
escape := string(rune(92))
cases := []string{
``,
`{}`,
`{"model":"gpt-5.5"}`,
// 无 namespace:入口预检查直接返回
`{"input":[{"type":"message","content":"hi"}]}`,
// namespace 只在 tools 里(Codex 常态)
`{"tools":[{"type":"namespace","name":"image_gen"}],"input":[{"type":"message","content":"hi"}]}`,
// namespace 嵌套在 item 内容里,不是数组项的直接字段
`{"input":[{"content":{"namespace":"nested"}}]}`,
`{"tools":[{"type":"namespace"}],"input":[{"content":{"namespace":"nested"}}]}`,
// 真正要改写
`{"input":[{"type":"function_call","namespace":"files","name":"search"}]}`,
`{"input":[{"namespace":"files"},{"type":"message","content":"hi"}]}`,
`{"input":[{"type":"message","content":"hi"},{"namespace":"files"}]}`,
`{"input":[{"namespace":"a"},{"namespace":"b"},{"namespace":"c"}]}`,
`{"input":[{"namespace":null}]}`,
`{"input":[{"namespace":["x"]}]}`,
`{"input":[{"namespace":"files","namespace":"dup"}]}`,
// 工具调用项在 keep 模式下的区分
`{"input":[{"type":"function_call","namespace":"files"}]}`,
`{"input":[{"type":"custom_tool_call","namespace":"files"}]}`,
`{"input":[{"type":"mcp_tool_call","namespace":"files"}]}`,
`{"input":[{"type":"tool_call","namespace":"files"}]}`,
`{"input":[{"type":"message","namespace":"files"}]}`,
`{"input":[{"type":"FUNCTION_CALL","namespace":"files"}]}`,
// 非对象 item
`{"input":["x",null,{"namespace":"files"},42]}`,
// input 不是数组 / 缺失
`{"input":{"namespace":"x"}}`,
`{"input":"namespace"}`,
`{"input":null}`,
`{"namespace":"top"}`,
// 重复 input 键:两边都取第一个
`{"input":[{"namespace":"first"}],"input":[{"namespace":"second"}]}`,
`{"input":[],"input":[{"namespace":"second"}]}`,
// 转义的键与值
`{"` + escape + `u0069nput":[{"namespace":"files"}]}`,
`{"input":[{"namespace":"fi` + escape + `u006ces"}]}`,
// 大内容与 unicode
`{"input":[{"namespace":"files","content":"` + strings.Repeat("x", 4096) + `"},{"type":"message","content":"中文 😀"}]}`,
// item 内部同时有直接 namespace 与嵌套 namespace
`{"input":[{"namespace":"files","content":{"namespace":"nested"}}]}`,
// 非法 JSON
`{"input":[{"namespace":"files"}]`,
`{"input":[{"namespace":"files"},`,
// 根不是对象
`[{"namespace":"files"}]`,
`"namespace"`,
}
for _, tc := range cases {
for _, keep := range []bool{false, true} {
t.Run(fmt.Sprintf("%s/keep=%v", truncateForName(tc), keep), func(t *testing.T) {
want, got := stripBoth(t, tc, keep)
if !gjson.ValidBytes([]byte(tc)) {
// 畸形输入上 gjson.GetBytes 与 gjson.Parse 返回的区间不同:
// 前者会一路扫到结尾,后者遇到非法结构就停。本实现走后者,因此在
// 无法解析的片段上不改写(更保守),只比较错误。
require.Equal(t, want.err, got.err, "input=%q keep=%v", tc, keep)
return
}
require.Equal(t, want, got, "input=%q keep=%v", tc, keep)
})
}
}
}
func truncateForName(s string) string {
if len(s) > 40 {
return s[:40] + "..."
}
if s == "" {
return "empty"
}
return s
}
// 组合随机:多个 item、namespace 位置随机、keep 随机。
func TestStripOpenAIResponsesInputNamespacesMatchesLegacyRandomized(t *testing.T) {
items := []string{
`{"type":"message","content":"hi"}`,
`{"namespace":"files"}`,
`{"type":"function_call","namespace":"files","name":"search"}`,
`{"type":"custom_tool_call","namespace":"files"}`,
`{"content":{"namespace":"nested"}}`,
`{"namespace":"files","content":"` + strings.Repeat("y", 200) + `"}`,
`{"namespace":null}`,
`"literal"`,
`42`,
`null`,
}
prefixes := []string{
`{"input":[`,
`{"tools":[{"type":"namespace"}],"input":[`,
`{"metadata":{"user_id":"u"},"input":[`,
}
seed := uint64(0x243f6a8885a308d3)
next := func() uint64 {
seed ^= seed << 13
seed ^= seed >> 7
seed ^= seed << 17
return seed
}
for i := 0; i < 3000; i++ {
n := int(next()%5) + 1
parts := make([]string, 0, n)
for j := 0; j < n; j++ {
parts = append(parts, items[int(next()%uint64(len(items)))])
}
body := prefixes[int(next()%uint64(len(prefixes)))] + strings.Join(parts, ",") + `]}`
keep := next()%2 == 0
want, got := stripBoth(t, body, keep)
require.Equal(t, want, got, "iteration=%d keep=%v body=%s", i, keep, body)
}
}
// 畸形输入的行为差异有明确用例固定,避免后续误改:
func TestStripOpenAIResponsesInputNamespacesMalformedRootIsConservative(t *testing.T) {
const malformed = `0{"input"[{ "namespace"00`
out, err := stripOpenAIResponsesInputNamespaces([]byte(malformed), true)
require.NoError(t, err)
require.Equal(t, malformed, string(out), "改写在无法解析的片段上必须放弃")
}
func FuzzStripOpenAIResponsesInputNamespaces(f *testing.F) {
f.Add([]byte(`{"input":[{"namespace":"files"}]}`), false)
f.Add([]byte(`{"tools":[{"type":"namespace"}],"input":[{"type":"message"}]}`), true)
f.Add([]byte(`{"input":[{"type":"function_call","namespace":"files"}]}`), true)
f.Add([]byte(`{"input":"namespace"}`), false)
f.Fuzz(func(t *testing.T, body []byte, keep bool) {
legacyBody := append([]byte(nil), body...)
newBody := append([]byte(nil), body...)
legacyOut, legacyErr := legacyStripOpenAIResponsesInputNamespaces(legacyBody, keep)
newOut, newErr := stripOpenAIResponsesInputNamespaces(newBody, keep)
require.Equal(t, fmt.Sprint(legacyErr), fmt.Sprint(newErr), "body=%q", body)
if legacyErr != nil || !gjson.ValidBytes(body) {
// 畸形输入两个 gjson API 的取值区间不同,见表驱动测试里的说明。
return
}
require.Equal(t, string(legacyOut), string(newOut), "body=%q keep=%v", body, keep)
})
}