Skip to content

Every agent's model. One place. Codex on DeepSeek, Claude Code on Kimi, from the menu bar.

gateway: a Codex Lite request is no longer decoded whole, nor parsed twice for its facts

yetone254461829bc2
diff --git a/internal/gateway/additional_tools.go b/internal/gateway/additional_tools.go
index 09dae3287..9f4cf75e2 100644
--- a/internal/gateway/additional_tools.go
+++ b/internal/gateway/additional_tools.go
@@ -84,29 +84,45 @@ const liteNamespace = "functions"
// liftAdditionalTools is a Responses request with its additional_tools items
// moved into its tools, or the request as it was when it has none.
+//
+// Only the additional_tools items and the tools are decoded; every other
+// item, and every other member of the request, goes byte for byte as it
+// came. Decoding the whole conversation into maps to move one item cost
+// ~7.5 times the body on every read of a Lite request, and each Codex
+// request was read so twice (its turn and its folder): ~110 MB of a
+// 4 MB conversation, held at once by each request in flight, so a few
+// subagents at once took the app toward 2 GB (XiaoYin_OK on X).
func liftAdditionalTools(body []byte) []byte {
if !bytes.Contains(body, []byte(`"additional_tools"`)) {
return body
}
- dec := json.NewDecoder(bytes.NewReader(body))
- dec.UseNumber()
- var m map[string]any
- if dec.Decode(&m) != nil || m == nil {
+ in, found, ok := topMember(body, "input")
+ if !ok || !found || len(in) == 0 || in[0] != '[' {
return body
}
- items, ok := m["input"].([]any)
- if !ok {
- return body
+ var tools []any
+ if raw, has, _ := topMember(body, "tools"); has {
+ if t, ok := decodeAny(raw).([]any); ok {
+ tools = t
+ }
}
- tools, _ := m["tools"].([]any)
have := toolsByName(tools)
- kept := items[:0:0]
- lifted := false
- for _, it := range items {
- im, _ := it.(map[string]any)
- if im["type"] != "additional_tools" {
+ var kept [][]byte
+ lifted, bad := false, false
+ eachElement(in, func(it []byte) bool {
+ if ty, ok := stringBytes(memberOrNil(it, "type")); !ok || string(ty) != "additional_tools" {
+ // a call the model made to one of Codex's own tools, under the
+ // namespace they were grouped in, is the plain call it now is
+ if ns, ok := stringBytes(memberOrNil(it, "namespace")); ok && string(ns) == liteNamespace {
+ it = withoutTopMember(it, "namespace")
+ }
kept = append(kept, it)
- continue
+ return true
+ }
+ im, _ := decodeAny(it).(map[string]any)
+ if im == nil {
+ bad = true
+ return false
}
lifted = true
more, _ := im["tools"].([]any)
@@ -126,26 +142,63 @@ func liftAdditionalTools(body []byte) []byte {
}
tools = addTool(tools, have, tm)
}
- }
- if !lifted {
+ return true
+ })
+ if !lifted || bad {
return body
}
- // a call the model made to one of Codex's own tools, under the
- // namespace they were grouped in, is the plain call it now is
- for _, it := range kept {
- if im, _ := it.(map[string]any); im != nil && im["namespace"] == liteNamespace {
- delete(im, "namespace")
- }
- }
- m["input"] = kept
+ var toolsJSON []byte
if len(tools) > 0 {
- m["tools"] = tools
+ t, err := marshalPlain(tools)
+ if err != nil {
+ return body
+ }
+ toolsJSON = t
+ }
+ // written once, at its size: the input with the kept items, the tools
+ // given again, every other byte of the body as it was
+ raw := trimJSON(body)
+ out := make([]byte, 0, len(raw)+len(toolsJSON)+len(`,"tools":`))
+ last, hadTools := 0, false
+ eachMemberAt(raw, func(k0, k1, v0, v1 int) bool {
+ switch key := raw[k0:k1]; {
+ case keyIs(key, "input"):
+ out = append(append(out, raw[last:v0]...), '[')
+ for i, it := range kept {
+ if i > 0 {
+ out = append(out, ',')
+ }
+ out = append(out, it...)
+ }
+ out = append(out, ']')
+ last = v1
+ case keyIs(key, "tools"):
+ hadTools = true
+ if toolsJSON != nil {
+ out = append(append(out, raw[last:v0]...), toolsJSON...)
+ last = v1
+ }
+ }
+ return true
+ })
+ out = append(out, raw[last:len(raw)-1]...)
+ if toolsJSON != nil && !hadTools {
+ out = append(append(out, `,"tools":`...), toolsJSON...)
}
- out, err := marshalPlain(m)
- if err != nil {
- return body
+ return append(out, '}')
+}
+
+// decodeAny is raw, a valid JSON value, decoded as encoding/json decodes
+// into an any, its numbers as they were written; nil when it doesn't
+// decode.
+func decodeAny(raw []byte) any {
+ dec := json.NewDecoder(bytes.NewReader(raw))
+ dec.UseNumber()
+ var v any
+ if dec.Decode(&v) != nil {
+ return nil
}
- return out
+ return v
}
// toolsByName is a request's tools by their names, a hosted tool without
diff --git a/internal/gateway/affinity.go b/internal/gateway/affinity.go
index ee53490ae..cec23797f 100644
--- a/internal/gateway/affinity.go
+++ b/internal/gateway/affinity.go
@@ -453,11 +453,15 @@ func strictOnly(cs []candidate, pl planned, at int) ([]candidate, planned) {
}
// affine puts first whoever answered the conversation last, while its
-// affinity says to keep it there.
-func affine(scope, mode string, rotate bool, in http.Header, from provider.Protocol, body []byte, cs []candidate, pl planned) ([]candidate, planned, *Affinity, string) {
+// affinity says to keep it there. Its turn is counted in written, the body
+// as the agent wrote it, which the turn's folder is read from too
+// (dirOf): one parse of a held body serves both (factsOf), where counting
+// it in the masked body parsed the conversation a second time, ~27 MB
+// more for each 4 MB Codex request in flight.
+func affine(scope, mode string, rotate bool, in http.Header, from provider.Protocol, body, written []byte, cs []candidate, pl planned) ([]candidate, planned, *Affinity, string) {
key := scope + "|" + conversationID(in, body)
a := &Affinity{Mode: mode}
- a.Turn, a.Within = turnOf(from, body)
+ a.Turn, a.Within = turnOf(from, written)
sticks.Lock()
st, had := stickOf(key)
sticks.Unlock()
diff --git a/internal/gateway/fastjson.go b/internal/gateway/fastjson.go
index 14f56f991..a39c59880 100644
--- a/internal/gateway/fastjson.go
+++ b/internal/gateway/fastjson.go
@@ -118,9 +118,9 @@ func holdBody(ctx context.Context, body []byte) {
if old != nil {
cur = *old
}
- if len(cur) >= heldBodiesMost {
+ if len(cur) >= heldBodiesMost || slices.ContainsFunc(cur, func(b []byte) bool { return unsafe.SliceData(b) == unsafe.SliceData(body) }) {
heldBodies.Unlock()
- return
+ return // held already: one release ends it
}
next := append(slices.Clip(cur), body)
heldBodies.list.Store(&next)
diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go
index efbcccd88..390186b3e 100644
--- a/internal/gateway/gateway.go
+++ b/internal/gateway/gateway.go
@@ -1667,6 +1667,13 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
body = rewriteModel(body, asked)
plain = rewriteModel(plain, asked)
}
+ // the body as the agent wrote it is rarely the one read (requestModel,
+ // spawnAgentModels and the Lite lift each write a new one), and its
+ // turn, folder and git are read from it two or three times (affine,
+ // dirOf, a pause by folder): held, one parse serves them all
+ // (factsOf), where each read parsed the whole conversation again,
+ // ~27 MB a time for a 4 MB Codex request (XiaoYin_OK on X)
+ holdBody(r.Context(), plain)
capture := &captureResponseWriter{ResponseWriter: w}
if wholeBodies {
capture.whole = &spool{limit: wholeBodyLimit, pattern: "magpie-whole-*"}
@@ -2197,7 +2204,7 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
// (#63): its reasoning, sealed by the account that wrote it, is refused
// by another.
before := len(cands)
- cands, pl, aff, stuck := affine(scope, mode, rotate, r.Header, from, body, cands, pl)
+ cands, pl, aff, stuck := affine(scope, mode, rotate, r.Header, from, body, plain, cands, pl)
// a strict conversation left with its own account of several: its
// failure rests the account as it would with the others still there,
// for new conversations to go elsewhere meanwhile (#1797)
diff --git a/internal/gateway/lite_lift_test.go b/internal/gateway/lite_lift_test.go
new file mode 100644
index 000000000..2e8dc0957
--- /dev/null
+++ b/internal/gateway/lite_lift_test.go
@@ -0,0 +1,222 @@
+package gateway
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "net/http/httptest"
+ "os"
+ "reflect"
+ "strings"
+ "sync"
+ "testing"
+
+ "github.com/yetone/magpie/internal/provider"
+ "github.com/yetone/magpie/internal/settings"
+)
+
+// liteConversation is largeConversation(Responses) in Codex's Lite shape:
+// its tools in a first additional_tools item, in the "functions"
+// namespace, and the model's calls to them under it.
+func liteConversation(t testing.TB, words int) []byte {
+ var m map[string]any
+ if err := json.Unmarshal(largeConversation(provider.Responses, "gpt-5.6", words), &m); err != nil {
+ t.Fatal(err)
+ }
+ tools := m["tools"]
+ delete(m, "tools")
+ in := m["input"].([]any)
+ for _, it := range in {
+ if im := it.(map[string]any); im["type"] == "function_call" {
+ im["namespace"] = "functions"
+ }
+ }
+ m["input"] = append([]any{map[string]any{"type": "additional_tools", "tools": []any{map[string]any{"type": "namespace", "name": "functions", "tools": tools}}}}, in...)
+ b, err := json.Marshal(m)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return b
+}
+
+// A Lite request's tools are lifted as they were when the whole request
+// was decoded to move them (liftWhole, the code before): the same request
+// once decoded. What isn't moved goes byte for byte as it came: an item's
+// keys in their order, its escapes as written.
+func TestLiteLiftMovesOnlyTheTools(t *testing.T) {
+ codex, err := os.ReadFile("testdata/context/codex.json")
+ if err != nil {
+ t.Fatal(err)
+ }
+ merged := `{"model":"m","tools":[{"type":"function","name":"shell","parameters":{"type":"object"}},
+ {"type":"namespace","name":"mcp__probe","tools":[{"type":"function","name":"write"}]}],
+ "input":[{"type":"additional_tools","tools":[
+ {"type":"namespace","name":"functions","tools":[{"type":"function","name":"shell","description":"again"}]},
+ {"type":"namespace","name":"mcp__probe","tools":[{"type":"function","name":"read"},{"type":"function","name":"write"}]}]},
+ {"type":"message","role":"user","content":"hi"}]}`
+ asSent := `{"role":"user","type":"message","content":[{"type":"input_text","text":"café <b> & 1.50"}]}`
+ call := `{"type":"function_call","namespace":"functions","name":"shell","arguments":"{\"cmd\":[\"ls\"]}","call_id":"c1"}`
+ kept := `{"stream":true,"model":"gpt-5.6","input":[{"type":"additional_tools","tools":[{"type":"namespace","name":"functions","tools":[{"type":"function","name":"shell"}]}]},` +
+ asSent + `,` + call + `],"z":{"b":1,"a":2.50}}`
+ for name, body := range map[string]string{
+ "codex": string(codex),
+ "merged": merged,
+ "kept": kept,
+ "conversation": string(liteConversation(t, 2_000)),
+ "none": `{"model":"m","input":[{"type":"message","role":"user","content":"additional_tools"}]}`,
+ "no input": `{"model":"m","additional_tools":[]}`,
+ "not a list": `{"model":"m","input":"additional_tools"}`,
+ "bad item": `{"model":"m","input":[{"type":"additional_tools","tools":[]},1,"x",null]}`,
+ } {
+ got, want := liftAdditionalTools([]byte(body)), liftWhole([]byte(body))
+ var g, w any
+ if json.Unmarshal(got, &g) != nil || json.Unmarshal(want, &w) != nil || !reflect.DeepEqual(g, w) {
+ t.Errorf("%s: lifted\n%s\nthe whole decode lifted\n%s", name, got, want)
+ }
+ if again := liftAdditionalTools(got); !bytes.Equal(again, got) {
+ t.Errorf("%s: lifted twice: %s", name, again)
+ }
+ }
+ out := string(liftAdditionalTools([]byte(kept)))
+ for _, part := range []string{asSent, `"z":{"b":1,"a":2.50}`, `{"type":"function_call","name":"shell"`} {
+ if !strings.Contains(out, part) {
+ t.Errorf("%s isn't as it came in %s", part, out)
+ }
+ }
+}
+
+// Lifting a Lite request's tools allocates about the request, not the
+// conversation decoded into maps and written again: ~7.5 times a 1.3 MB
+// body on every read of it, twice a request (XiaoYin_OK on X: the app
+// near 2 GB after a day of Codex).
+func TestLiteLiftAllocatesAboutTheBody(t *testing.T) {
+ body := liteConversation(t, 200_000)
+ least := ^uint64(0)
+ // the fewest of a few tries: another goroutine's allocations count in
+ // TotalAlloc too (#3283)
+ for range 3 {
+ least = min(least, allocated(func() { liftAdditionalTools(body) }))
+ }
+ if least > uint64(len(body))*2 {
+ t.Fatalf("lifting a %d-byte Lite request allocated %d bytes (%.1f×)", len(body), least, float64(least)/float64(len(body)))
+ }
+}
+
+// A served request whose masked body differs from what its agent wrote
+// has its conversation parsed once for its turn and its folder, not once
+// for each: the turn was counted in the masked body, the folder read from
+// the written one, two parses of the whole conversation for every
+// request in flight.
+func TestMaskedRequestParsedOnceForItsFacts(t *testing.T) {
+ const key = "sk-proj-abcdEFGH1234ijklMNOP5678qrst"
+ t.Setenv("XDG_CONFIG_HOME", t.TempDir())
+ t.Setenv("XDG_CACHE_HOME", t.TempDir())
+ f := &fake{ctype: "application/json", reply: `{"id":"r1","object":"response","status":"completed","output":[{"type":"message","role":"assistant","content":[{"type":"output_text","text":"ok"}]}],"usage":{"input_tokens":7,"output_tokens":1}}`}
+ up := httptest.NewServer(f)
+ defer up.Close()
+ if err := provider.Save(provider.Provider{ID: "fake", Name: "Fake", Key: "k", Models: []string{"m1"}, Responses: up.URL + "/v1"}); err != nil {
+ t.Fatal(err)
+ }
+ if err := settings.Save(settings.Settings{Redact: true}); err != nil {
+ t.Fatal(err)
+ }
+ var m map[string]any
+ json.Unmarshal(liteConversation(t, 20_000), &m)
+ m["model"] = "fake/m1"
+ m["instructions"] = "Working directory: /work/" + t.Name() + "\nkey " + key
+ body, _ := json.Marshal(m)
+ var mu sync.Mutex
+ parsed := 0
+ seen := func(b []byte) {
+ if len(b) > len(body)/2 {
+ mu.Lock()
+ parsed++
+ mu.Unlock()
+ }
+ }
+ factsParsed.Store(&seen)
+ defer factsParsed.Store(nil)
+ rec := httptest.NewRecorder()
+ // a served request's context ends, as net/http's does: a body is held
+ // only while one can (holdBody)
+ ctx, done := context.WithCancel(context.Background())
+ defer done()
+ New().Handler().ServeHTTP(rec, httptest.NewRequest("POST", "/v1/responses", bytes.NewReader(body)).WithContext(ctx))
+ if rec.Code != 200 || f.calls == 0 {
+ t.Fatalf("%d %s", rec.Code, rec.Body)
+ }
+ if strings.Contains(string(f.got), key) {
+ t.Fatal("the key went unmasked: the request isn't one masking changed")
+ }
+ mu.Lock()
+ defer mu.Unlock()
+ if parsed != 1 {
+ t.Fatalf("the conversation was parsed %d times for its turn and folder", parsed)
+ }
+}
+
+// liftWhole is liftAdditionalTools as it was: the whole request decoded
+// into maps, the tools moved, and all of it written again.
+func liftWhole(body []byte) []byte {
+ if !bytes.Contains(body, []byte(`"additional_tools"`)) {
+ return body
+ }
+ dec := json.NewDecoder(bytes.NewReader(body))
+ dec.UseNumber()
+ var m map[string]any
+ if dec.Decode(&m) != nil || m == nil {
+ return body
+ }
+ items, ok := m["input"].([]any)
+ if !ok {
+ return body
+ }
+ tools, _ := m["tools"].([]any)
+ have := toolsByName(tools)
+ kept := items[:0:0]
+ lifted := false
+ for _, it := range items {
+ im, _ := it.(map[string]any)
+ if im["type"] != "additional_tools" {
+ kept = append(kept, it)
+ continue
+ }
+ lifted = true
+ more, _ := im["tools"].([]any)
+ for _, t := range more {
+ tm, _ := t.(map[string]any)
+ if tm == nil {
+ continue
+ }
+ if tm["type"] == "namespace" && tm["name"] == liteNamespace {
+ nested, _ := tm["tools"].([]any)
+ for _, n := range nested {
+ if nm, _ := n.(map[string]any); nm != nil {
+ tools = addTool(tools, have, nm)
+ }
+ }
+ continue
+ }
+ tools = addTool(tools, have, tm)
+ }
+ }
+ if !lifted {
+ return body
+ }
+ // a call the model made to one of Codex's own tools, under the
+ // namespace they were grouped in, is the plain call it now is
+ for _, it := range kept {
+ if im, _ := it.(map[string]any); im != nil && im["namespace"] == liteNamespace {
+ delete(im, "namespace")
+ }
+ }
+ m["input"] = kept
+ if len(tools) > 0 {
+ m["tools"] = tools
+ }
+ out, err := marshalPlain(m)
+ if err != nil {
+ return body
+ }
+ return out
+}
diff --git a/internal/gateway/login_switch_test.go b/internal/gateway/login_switch_test.go
index 81d7479da..627ffb0fb 100644
--- a/internal/gateway/login_switch_test.go
+++ b/internal/gateway/login_switch_test.go
@@ -30,13 +30,13 @@ func TestLoginSwitchKeepsEachAccountItself(t *testing.T) {
h.Set("x-claude-code-session-id", "login-switch-209")
body := []byte(`{"messages":[{"role":"user","content":"hi"}]}`)
pl := planned{order: make([]Weighed, 2)}
- _, _, _, key := affine("t", provider.AffinitySession, false, h, provider.Anthropic, body, []candidate{a, b}, pl)
+ _, _, _, key := affine("t", provider.AffinitySession, false, h, provider.Anthropic, body, body, []candidate{a, b}, pl)
answered(key, a, 1, Usage{})
servedCandidate(a, 5000)
// signed in to b now
a2, b2 := acct("[email protected]", "claude@[email protected]"), acct("[email protected]", "claude")
- cs, _, aff, _ := affine("t", provider.AffinitySession, false, h, provider.Anthropic, body, []candidate{b2, a2}, planned{order: make([]Weighed, 2)})
+ cs, _, aff, _ := affine("t", provider.AffinitySession, false, h, provider.Anthropic, body, body, []candidate{b2, a2}, planned{order: make([]Weighed, 2)})
if cs[0].p.Account.User != "[email protected]" || !aff.Kept {
t.Fatalf("the conversation went to %s (kept %v, %s)", cs[0].p.Account.User, aff.Kept, aff.Why)
}
diff --git a/internal/gateway/lone_allowance_test.go b/internal/gateway/lone_allowance_test.go
index 3e88f364c..fbb65c2e7 100644
--- a/internal/gateway/lone_allowance_test.go
+++ b/internal/gateway/lone_allowance_test.go
@@ -69,10 +69,10 @@ func TestLoneSpentKeyKeepsItsConversation(t *testing.T) {
h := http.Header{}
h.Set("x-claude-code-session-id", "lone-spent-1016")
body := []byte(`{"messages":[{"role":"user","content":"hi"}]}`)
- _, _, _, key := affine("t", provider.AffinitySession, false, h, provider.Chat, body, cs, pl)
+ _, _, _, key := affine("t", provider.AffinitySession, false, h, provider.Chat, body, body, cs, pl)
answered(key, c, 1, Usage{})
t.Cleanup(func() { sticks.Lock(); delete(sticks.m, key); sticks.Unlock() })
- got, _, aff, _ := affine("t", provider.AffinitySession, false, h, provider.Chat, body, cs, pl)
+ got, _, aff, _ := affine("t", provider.AffinitySession, false, h, provider.Chat, body, body, cs, pl)
if got[0].rest != "kimi-code-cn" || aff.Why == "spent" || !aff.Kept {
t.Fatalf("kept %v, why %s", aff.Kept, aff.Why)
}
diff --git a/internal/gateway/parse_memo.go b/internal/gateway/parse_memo.go
index a7d326cac..78c12e214 100644
--- a/internal/gateway/parse_memo.go
+++ b/internal/gateway/parse_memo.go
@@ -1,6 +1,7 @@
package gateway
import (
+ "sync/atomic"
"unsafe"
"github.com/yetone/magpie/internal/provider"
@@ -59,6 +60,9 @@ func factsOf(proto provider.Protocol, body []byte) bodyFacts {
// readFacts parses body for its bodyFacts.
func readFacts(proto provider.Protocol, body []byte) bodyFacts {
+ if f := factsParsed.Load(); f != nil {
+ (*f)(body)
+ }
req, err := parse(proto, body)
if err != nil {
return bodyFacts{}
@@ -75,3 +79,6 @@ type heldFacts struct {
proto provider.Protocol
facts bodyFacts
}
+
+// factsParsed, when set (tests), is told of each body readFacts parses.
+var factsParsed atomic.Pointer[func(body []byte)]