gateway: spawn_agent is widened without writing the whole Codex body again (#3394)

Codex sends spawn_agent with every request, so spawnAgentModels ran on
each one: it decoded the whole body into a map, decoded every input
item into a map, and encoded the body again, so a long conversation
was walked three times a request, and went upstream with its keys
sorted. It now takes tools (and input, only when it holds a
tool_search_output) with topMember, widens them as before, and puts
the new values back in place (withMembers); every other byte goes on
as Codex sent it. Only a tool_search_output item is decoded and
written again (moreSpawnItem); an input with an item that isn't an
object no longer stops the others being widened.

Run:
- A 1.6MB body (Codex 0.162.0's tools from testdata, 300 tool outputs),
  30 calls in a scratch test not committed: 16.4ms a call before, 2.3ms
  after.
- Real DeepSeek account in a sandbox HOME, magpie serve on 3482, 12
  streamed /v1/responses requests of a synthetic 1.5MB conversation with
  Codex 0.162.0's real tools and a codex_cli_rs/0.162.1 User-Agent (so
  the spawn path runs), CPU time from ps, two rounds each: d792e7ce4
  0.90s and 0.92s, this 0.78s and 0.78s, about 75ms -> 65ms a request.
  All 48 answered 200. Without the Codex User-Agent the two are the
  same (0.67s and 0.65s), as they should be.
- New TestSpawnAgentModelsLeavesTheRestAsSent: red on the old code
  (the body came back with its keys sorted), green now.
  TestSpawnAgentNamesEveryModel and ...AfterToolSearch green.
- go test ./internal/gateway -run 'Spawn|ToolSearch|Codex': ok. The
  whole gateway package passed at d792e7ce4 (398s), not at this commit.
- gofmt -l clean; GOOS=linux and windows go vet -tags nogui ./internal/gateway ok.
This commit is contained in:
yetone
2026-10-25 00:47:16 +08:00
parent d3fb381afe
commit b97e0aa2a2
2 changed files with 108 additions and 22 deletions
+82 -22
View File
@@ -51,13 +51,17 @@ func spawnAgentModels(r *http.Request, body []byte, lead string, codexPath bool)
if len(choices) == 0 {
return body
}
var q map[string]json.RawMessage
if json.Unmarshal(body, &q) != nil {
// Codex sends spawn_agent on every request, so only the members that
// change are decoded and put back, the rest of the body (the
// conversation) left as it is: decoding the whole body and encoding it
// again walked the conversation twice a request (#3394).
tools, _, ok := topMember(body, "tools")
if !ok {
return body
}
changed := false
if tools, ok := moreSpawnTools(q["tools"], choices); ok {
q["tools"], changed = tools, true
set := map[string][]byte{}
if t, ok := moreSpawnTools(tools, choices); ok {
set["tools"] = t
}
// A model that can search tools is handed spawn_agent only when it
// searches for it: Codex defers its multi-agent V1 tools behind
@@ -66,27 +70,83 @@ func spawnAgentModels(r *http.Request, body []byte, lead string, codexPath bool)
// in a tool_search_output, not in tools (Gearclickist on Discord, after
// v0.1.1214). Codex sends that output as it got it on every turn, so
// it is widened the same way on each.
var input []map[string]json.RawMessage
if json.Unmarshal(q["input"], &input) == nil {
in := false
for _, it := range input {
var kind string
json.Unmarshal(it["type"], &kind)
if kind != "tool_search_output" {
continue
}
if tools, ok := moreSpawnTools(it["tools"], choices); ok {
it["tools"], in = tools, true
}
}
if in {
q["input"], changed = rawJSON(input), true
if input, found, _ := topMember(body, "input"); found && bytes.Contains(input, []byte("tool_search_output")) {
if in, ok := moreSpawnInput(input, choices); ok {
set["input"] = in
}
}
if !changed {
if len(set) == 0 {
return body
}
return rawJSON(q)
return withMembers(body, set)
}
// moreSpawnInput is input, a request's input list, with each
// tool_search_output's spawn_agent naming choices too; false when there is
// none to widen. Only those items are decoded and written again.
func moreSpawnInput(input []byte, choices []spawnChoice) ([]byte, bool) {
raw := trimJSON(input)
if len(raw) == 0 || raw[0] != '[' {
return input, false
}
var out []byte
last := 0
i := skipJSONSpace(raw, 1)
for raw[i] != ']' {
at := i
i = skipJSONValue(raw, i)
if el := raw[at:i]; el[0] == '{' && bytes.Contains(el, []byte("tool_search_output")) {
if it, ok := moreSpawnItem(el, choices); ok {
out = append(append(out, raw[last:at]...), it...)
last = i
}
}
if i = skipJSONSpace(raw, i); raw[i] == ',' {
i = skipJSONSpace(raw, i+1)
}
}
if out == nil {
return input, false
}
return append(out, raw[last:]...), true
}
// moreSpawnItem is el, an input item, when it is a tool_search_output whose
// spawn_agent can name more choices, written again naming them.
func moreSpawnItem(el []byte, choices []spawnChoice) ([]byte, bool) {
var it map[string]json.RawMessage
if json.Unmarshal(el, &it) != nil {
return nil, false
}
var kind string
json.Unmarshal(it["type"], &kind)
if kind != "tool_search_output" {
return nil, false
}
tools, ok := moreSpawnTools(it["tools"], choices)
if !ok {
return nil, false
}
it["tools"] = tools
return rawJSON(it), true
}
// withMembers is body, a valid JSON object, with the members set names
// given set's values, every other byte of it as it was (a name the body
// has twice is given the value at both).
func withMembers(body []byte, set map[string][]byte) []byte {
raw := trimJSON(body)
out := make([]byte, 0, len(raw)+len(set["tools"])+len(set["input"]))
last := 0
eachMemberAt(raw, func(k0, k1, v0, v1 int) bool {
name, ok := unquoteJSON(raw[k0:k1])
if v, has := set[name]; ok && has {
out = append(append(out, raw[last:v0]...), v...)
last = v1
}
return true
})
return append(out, raw[last:]...)
}
// moreSpawnTools is raw, a list of tools (a request's, or the ones a
@@ -258,3 +258,29 @@ func TestSpawnAgentNamesEveryModelAfterToolSearch(t *testing.T) {
namesAll(t, searchedSpawnDescription(t, upstream))
})
}
// Codex sends spawn_agent on every request, so widening it must not
// decode the conversation and write it again (#3394): the body goes on as
// Codex sent it, its members in their order, but for the tools.
func TestSpawnAgentModelsLeavesTheRestAsSent(t *testing.T) {
up := setup(t, provider.Responses, &fake{t: t})
if err := provider.Save(provider.Provider{ID: "fake", Name: "Fake", Key: "k", Responses: up.URL + "/v1", Models: []string{"m1", "m2"}}); err != nil {
t.Fatal(err)
}
var q map[string]json.RawMessage
if err := json.Unmarshal([]byte(codexSpawnRequest(t, "fake/m1")), &q); err != nil {
t.Fatal(err)
}
// a conversation as Codex writes it: unsorted keys, < > & as they are
input := `[{"type":"message","role":"user","content":[{"type":"input_text","text":"a <b> & c ` + strings.Repeat("x", 300000) + `"}]}]`
body := []byte(`{"model":"fake/m1", "input":` + input + `, "tools":` + string(q["tools"]) + `,"stream":true}`)
req := httptest.NewRequest("POST", "/v1/responses", nil)
got := spawnAgentModels(req, body, "fake/m1", false)
if !strings.Contains(spawnDescription(t, got), "- `fake/m2`") {
t.Fatalf("spawn_agent not widened:\n%s", spawnDescription(t, got))
}
prefix := `{"model":"fake/m1", "input":` + input + `, "tools":`
if !strings.HasPrefix(string(got), prefix) || !strings.HasSuffix(string(got), `,"stream":true}`) {
t.Fatalf("the rest of the body changed: %.200s … %.200s", got, got[max(0, len(got)-200):])
}
}