mirror of
https://github.com/Wei-Shaw/sub2api.git
synced 2026-12-05 16:07:33 +00:00
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.