Skip to content

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

Merged
Wei-Shaw merged 2 commits into
Wei-Shaw:mainfrom
lishuangqiang:perf/openai-namespace-strip-copies
Nov 20, 2026
Merged

Wei-Shaw merged 2 commits into
Wei-Shaw:mainfrom
lishuangqiang:perf/openai-namespace-strip-copies

Conversation

@lishuangqiang

Copy link
Copy Markdown
Contributor

背景

stripOpenAIResponsesInputNamespaces 在 OpenAI OAuth / API Key 的每次 HTTP 转发尝试上都会跑(openai_gateway_forward.go:132)。它的入口预检查只有 bytes.Contains(body, "\"namespace\""),而 Codex 客户端在普通请求的 tools 里就带 image_gen namespace 声明——预检查对主流流量必然放行,即使 input 里没有需要清理的字段。

修改

三处可以省掉的整块拷贝:

  1. gjson.GetBytes(body, "input") → parseRawJSONView(body).Get("input")。前者会把 input 数组物化成一份拷贝(1 MiB body 上每次请求 1 MiB 分配),后者是零拷贝视图。
  2. sjson.SetRawBytes → 直接组装输出。原来先把新 input 拼进 bytes.Buffer,再交给 SetRawBytes 分配第二份完整 body;现在按 prefix + 改写后的 input + suffix 一次写进按 body 大小预留的缓冲,总共一份。
  3. sjson.DeleteBytes([]byte(item.Raw), ...) → sjson.Delete(item.Raw, ...),省掉每个待改 item 的 []byte 转换。

hasOpenAIResponsesNamespaceToolDeclaration 用同样的方式读 input(API Key 账号每请求都会走到),一并改掉。

收益

Apple M5 Pro,-benchmem,legacy = 改动前的实现(benchmark 里两个变体同一次运行对比):

用例 改前 改后
1 MiB tools_only 545 µs / 1,056,768 B / 1 alloc 495 µs / 0 B / 0 alloc
1 MiB strip_first 882 µs / 3,170,624 B / 8 allocs 548 µs / 1,056,936 B / 4
1 MiB strip_last 841 µs / 3,170,624 B / 8 allocs 556 µs / 1,056,928 B / 4
8 MiB strip_first 5.95 ms / 25,190,720 B / 8 4.30 ms / 8,396,960 B / 4

no-op 路径(Codex 常态)不再分配;改写路径从三份完整副本降到一份。

行为保证

  • 差分测试把改动前的实现原样保留为 legacy*,比较输出字节、错误、以及是否原样返回了传入的 slice,覆盖 36 组语料(重复键、\u 转义键、嵌套 namespace 字段、非对象 item、keepToolCallNamespaces 两种取值、input 缺失/非数组/重复、非法 JSON),外加 3000 组确定性随机组合与一个 fuzz 目标(约 146 万次执行通过)。
  • 合法 JSON 上输出与旧实现逐字节一致。

一处有意保留的差异

在非法 JSON 上,gjson.GetBytes 与 gjson.Parse 对同一个键返回的区间不同:前者一路扫到结尾,后者遇到非法结构就停。典型例子:

输入:  0{"input"[{ "namespace"00
旧实现: 0{"input"[{ "namespace"     ← 尾部被截断
新实现: 0{"input"[{ "namespace"00   ← 原样返回,放弃改写

新实现选择不改写无法解析的片段。该函数只有一个调用点,且拿到的 body 已被 handler 校验过,这条路径在生产上不可达;行为已用单独用例固定。

Fixes #8869

…paces

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.
@Lenoud

Lenoud commented Nov 17, 2026

Copy link
Copy Markdown

补充一组生产环境数据,供评估这类拷贝在超大 Codex 请求体上的影响。

场景

  • sub2api v0.2.21 → v0.2.22,Kubernetes 单副本,上游为 OpenAI OAuth(Codex)账号。
  • 单个 Codex 长会话通过 HTTP 入站调用 /v1/responses(stream=true,gpt-6.1-sol),按代码会走到 stripOpenAIResponsesInputNamespaces。
  • 请求体从约 168 MB 增长到约 200 MB(content_length 约 200,250,501)。对应上下文只有约 35 万 token,绝大部分是 cache_read,请求体中大部分不是计费文本。

内存实测
取新 Pod 处理第一个大请求时的 working set 增量。当时只有这一个大请求在处理,没有上一个请求的残留。

版本 请求体 working set 每 MB 请求体
v0.2.21 168.5 MB 349 → 2238 MiB 约 11.2 MiB
v0.2.22 200.0 MB 125 → 2241 MiB 约 10.6 MiB

v0.2.22 的零拷贝改动对这条 OpenAI Responses 路径只改善了约 5%。

后果

  • 原来容器上限 2Gi、未设置 GOMEMLIMIT。接连两个这样的请求就会被 OOMKilled;客户端在服务恢复后立即重发,14 分钟内被杀 6 次,形成崩溃循环。
  • 改为 4Gi 并设置 GOMEMLIMIT=3600MiB 后稳定。v0.2.22 上 20 分钟内处理了 17 个 200 MB 级请求,内存峰值约 2.6 GiB。
  • 多个 200 MB 的上传重叠时,默认 1 GiB 的 request_body_memory_budget_bytes 返回 503 + Retry-After: 1,起到了保护作用。

与本 PR 的关系
v0.2.22 已经包含读取 input 的零拷贝视图。在此基础上,本 PR 把改写分支从 rebuilt 缓冲 + sjson.SetRawBytes 两份大拷贝减为一份按 body 大小预留的缓冲。在 200 MB 级请求体上,这相当于每次转发尝试少分配约 200 MB,failover 重试时会成倍放大。

我们没有保存请求体,无法从日志确认这些请求是否命中改写分支(input 中是否存在需要清理的 namespace)。合并发版后,我们可以按同样口径复测并回报结果。

@Wei-Shaw
Wei-Shaw merged commit 67b2df8 into Wei-Shaw:main Nov 20, 2026
7 checks passed
@github-actions github-actions Bot locked and limited conversation to collaborators Nov 20, 2026
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Perf] stripOpenAIResponsesInputNamespaces 改写时复制三份完整 body,no-op 时也白拷一份 input

3 participants