Files
sub2api/backend/internal/service/openai_responses_namespace.go
T
lishuangqiang 049e0f41b8 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.
2026-11-17 00:10:26 +08:00

299 lines
11 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package service
import (
"bytes"
"encoding/json"
"fmt"
"strings"
"github.com/Wei-Shaw/sub2api/internal/pkg/apicompat"
"github.com/gin-gonic/gin"
"github.com/tidwall/gjson"
"github.com/tidwall/sjson"
)
const openAIResponsesNamespaceNamesContextKey = "openai_responses_namespace_names"
// openAIResponsesNamespaceFieldBytes 是入口预检查用的字面量。带引号可避免匹配到
// 正文里的普通单词;键写成 unicode 转义时无法字节匹配,那条路径不会进入清理逻辑,
// 与改动前一致。
var openAIResponsesNamespaceFieldBytes = []byte(`"namespace"`)
// shouldFlattenOpenAIResponsesNamespaces 判定原生 Responses 转发前是否摊平
// Codex namespace 工具。
//
// 默认不摊平:OAuth 账号的 HTTP 出口恒为 chatgpt.com/backend-api/codex/responses
// (buildUpstreamRequest 只在 API Key 分支读 base_url),也就是 namespace 扩展的
// 定义方本身;Codex 客户端对 WS 与 HTTP 两条传输发送同一份 tools(codex-rs
// client.rs build_responses_request 无传输分支,WS 失败后会 session 级回落 HTTP
// 继续发同样的声明)。摊平只改写工具名,改不掉客户端在 tools 描述与 developer
// 消息里写死的 `to=functions.<namespace>.<tool>` 寻址约定,模型据此寻址必然落空
// (issue #4978);命名空间名还可由 features.multi_agent_v2.tool_namespace 自定义、
// 或由 MCP/connector 动态生成(mcp__codex_apps__gmail),保留名单枚举不完。
//
// compact 端点例外:已知它的 schema 比 /responses 窄(连 input[].namespace 都会报
// Unknown parameter,见 issue #4761),而是否接受 namespace 工具声明没有任何实测
// 证据;compact 只做历史摘要、不需要模型寻址工具,回程也没有工具调用可还原,因此
// 保持 0.1.166 起就在跑的摊平行为,不随本次默认值翻转扩大风险面。
//
// 账号开关 openai_responses_flatten_namespaces 为不认识 namespace 的兼容上游保留
// 退路,打开后恢复旧行为:WSv2 上游原生支持 namespace,且 WS 出口
// (openai_ws_forwarder_v2)原样转发上游事件、不经 HTTP 回程还原,摊平后的平名
// 无法还原会破坏客户端工具匹配,因此实际走 WSv2 分支的请求仍保持 namespace 原样;
// 透传账号先于 WSv2 分支经 HTTP 转发返回,仍需摊平。
func shouldFlattenOpenAIResponsesNamespaces(
account *Account,
transport OpenAIUpstreamTransport,
passthroughEnabled bool,
compactPath bool,
) bool {
if account == nil || !account.IsOpenAIOAuthLike() {
return false
}
if !compactPath && !account.IsOpenAIResponsesFlattenNamespacesEnabled() {
return false
}
if transport == OpenAIUpstreamTransportResponsesWebsocketV2 && !passthroughEnabled {
return false
}
return true
}
// shouldStripOpenAIResponsesInputNamespaces removes residual input item
// namespaces for OpenAI OAuth and API Key HTTP forwarding. Native WSv2 keeps
// namespaces because that protocol supports them and does not restore payloads.
func shouldStripOpenAIResponsesInputNamespaces(account *Account, transport OpenAIUpstreamTransport, passthroughEnabled bool) bool {
if account == nil || (!account.IsOpenAIOAuthLike() && !account.IsOpenAIApiKey()) {
return false
}
if transport == OpenAIUpstreamTransportResponsesWebsocketV2 && !passthroughEnabled {
return false
}
return true
}
// shouldKeepOpenAIResponsesToolCallNamespaces 判定清理 input 残留 namespace 时是否
// 保留工具调用项上的 namespace。
//
// 上游对这个字段有两套互斥要求,判定按「出口 + 端点」而非工具声明内容:
// - /backend-api/codex/responses 会按 namespace 解析历史调用,缺字段直接 400
// `Missing namespace for function_call '...'. Round-trip the model's
// function_call item with its namespace field included.`(issue #4761 回帖),
// 故 OAuth 非 compact 请求必须保留。
// - compact 端点的 schema 不含该字段,携带即 400 `Unknown parameter:
// input[N].namespace`(issue #4761 正文),故 compact 一律清理。
// - API Key 出口默认按标准 Responses API 处理并清理该字段;但当请求本身声明
// namespace 工具时(包括 Responses Lite 的 input[].additional_tools),上游显然
// 使用了 namespace 扩展,此时必须保留调用项上的 namespace,否则声明与历史
// 调用会失配并触发 Missing namespace。
// - 摊平模式下调用项已被改写成平名,残留 namespace 指向的声明已不存在,一律清理。
func shouldKeepOpenAIResponsesToolCallNamespaces(
account *Account,
transport OpenAIUpstreamTransport,
passthroughEnabled bool,
compactPath bool,
body []byte,
) bool {
if account == nil {
return false
}
if compactPath {
return false
}
if account.IsOpenAIApiKey() {
return hasOpenAIResponsesNamespaceToolDeclaration(body)
}
if !account.IsOpenAIOAuthLike() {
return false
}
return !shouldFlattenOpenAIResponsesNamespaces(account, transport, passthroughEnabled, compactPath)
}
func hasOpenAIResponsesNamespaceToolDeclaration(body []byte) bool {
hasNamespaceTool := func(tools gjson.Result) bool {
if !tools.IsArray() {
return false
}
found := false
tools.ForEach(func(_, tool gjson.Result) bool {
if strings.EqualFold(strings.TrimSpace(tool.Get("type").String()), "namespace") {
found = true
return false
}
return true
})
return found
}
// 与 stripOpenAIResponsesInputNamespaces 同理:input 可能很大,用零拷贝视图取值。
root := parseRawJSONView(body)
if hasNamespaceTool(root.Get("tools")) {
return true
}
// Responses Lite moves private namespace declarations out of top-level
// 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 := root.Get("input")
if !input.IsArray() {
return false
}
found := false
input.ForEach(func(_, item gjson.Result) bool {
if !strings.EqualFold(strings.TrimSpace(item.Get("type").String()), "additional_tools") {
return true
}
if hasNamespaceTool(item.Get("tools")) {
found = true
return false
}
return true
})
return found
}
// openAIResponsesToolCallItemTypes 是携带 namespace 的调用项类型集合。与
// removeOpenAIResponsesRejectedNamespaceAtIndex 的反应式白名单保持一致;codex-rs
// protocol/src/models.rs 中只有 FunctionCall 与 CustomToolCall 序列化 namespace,
// 其余类型带该字段一定是非 Codex 客户端或历史残留,清掉才安全。
var openAIResponsesToolCallItemTypes = map[string]bool{
"function_call": true,
"tool_call": true,
"custom_tool_call": true,
"mcp_tool_call": true,
}
func isOpenAIResponsesToolCallItemType(itemType string) bool {
return openAIResponsesToolCallItemTypes[strings.ToLower(strings.TrimSpace(itemType))]
}
func flattenOpenAIResponsesNamespaces(c *gin.Context, body []byte) ([]byte, error) {
if !bytes.Contains(body, openAIResponsesNamespaceFieldBytes) {
return body, nil
}
var requestBody map[string]any
if err := json.Unmarshal(body, &requestBody); err != nil {
return body, fmt.Errorf("decode OpenAI namespace body: %w", err)
}
names, changed, err := apicompat.FlattenResponsesNamespacesExcept(requestBody, map[string]bool{"image_gen": true})
if err != nil {
return body, err
}
if !changed {
return body, nil
}
rebuilt, err := marshalOpenAIUpstreamJSON(requestBody)
if err != nil {
return body, fmt.Errorf("encode OpenAI namespace body: %w", err)
}
setOpenAIResponsesNamespaceNames(c, names)
return rebuilt, nil
}
// stripOpenAIResponsesInputNamespaces removes namespace only from direct input
// array items. Namespace declarations and nested namespace fields are left
// 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, openAIResponsesNamespaceFieldBytes) {
return body, nil
}
input := parseRawJSONView(body).Get("input")
if !input.IsArray() {
return body, nil
}
// inputStart/inputEnd 是 input 数组在 body 里的字节区间。
inputStart := input.Index
inputEnd := inputStart + len(input.Raw)
// 输出缓冲只在首次真正改写时分配,容量按整个 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
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.Delete(item.Raw, "namespace")
if err != nil {
stripErr = err
return false
}
if out == nil {
out = make([]byte, 0, len(body))
out = append(out, body[:inputStart]...)
}
itemStart := item.Index - input.Index
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 out == nil {
return body, 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) {
if c != nil && len(names) > 0 {
c.Set(openAIResponsesNamespaceNamesContextKey, names)
}
}
// clearOpenAIResponsesNamespaceNames 清除上一次尝试登记的摊平名映射。handler 的
// failover 会在同一个 *gin.Context 上重试下一个账号,映射不清会让保留 namespace 的
// 账号拿着上一个账号的摊平名做回程还原。
func clearOpenAIResponsesNamespaceNames(c *gin.Context) {
if c == nil {
return
}
if _, exists := c.Get(openAIResponsesNamespaceNamesContextKey); exists {
c.Set(openAIResponsesNamespaceNamesContextKey, map[string]apicompat.ResponsesNamespaceName(nil))
}
}
func openAIResponsesNamespaceNames(c *gin.Context) map[string]apicompat.ResponsesNamespaceName {
if c == nil {
return nil
}
value, ok := c.Get(openAIResponsesNamespaceNamesContextKey)
if !ok {
return nil
}
names, _ := value.(map[string]apicompat.ResponsesNamespaceName)
return names
}
func restoreOpenAIResponsesNamespacePayload(c *gin.Context, payload []byte) ([]byte, error) {
names := openAIResponsesNamespaceNames(c)
if len(names) == 0 || !json.Valid(payload) {
return payload, nil
}
restored, changed, err := apicompat.RestoreResponsesNamespaceCalls(payload, names)
if err != nil {
return payload, err
}
if changed {
return restored, nil
}
return payload, nil
}