diff --git a/internal/gateway/affinity.go b/internal/gateway/affinity.go index d2ba0a859..69be6226e 100644 --- a/internal/gateway/affinity.go +++ b/internal/gateway/affinity.go @@ -798,7 +798,7 @@ func withoutRefused(key, who string, body []byte) ([]byte, bool) { return nil, false } var q map[string]json.RawMessage - if decodeJSON(body, &q) != nil { + if decodeJSONView(body, &q) != nil { return nil, false } items, isList := inputList(q["input"]) @@ -808,7 +808,7 @@ func withoutRefused(key, who string, body []byte) ([]byte, bool) { kept := items[:0:0] for _, it := range items { var t sealedItem - if decodeJSON(it, &t) == nil && sealedKinds[t.Type] && t.Enc != "" && r.seals[sha256.Sum256([]byte(t.Enc))] { + if decodeJSONView(it, &t) == nil && sealedKinds[t.Type] && t.Enc != "" && r.seals[sha256.Sum256([]byte(t.Enc))] { continue } kept = append(kept, it) @@ -852,7 +852,7 @@ func withoutCompaction(body []byte) ([]byte, bool) { // types. func withoutKinds(body []byte, kinds ...string) ([]byte, bool) { var q map[string]json.RawMessage - if decodeJSON(body, &q) != nil { + if decodeJSONView(body, &q) != nil { return nil, false } items, isList := inputList(q["input"]) @@ -864,7 +864,7 @@ func withoutKinds(body []byte, kinds ...string) ([]byte, bool) { var t struct { Type string `json:"type"` } - if decodeJSON(it, &t) == nil && slices.Contains(kinds, t.Type) { + if decodeJSONView(it, &t) == nil && slices.Contains(kinds, t.Type) { continue } kept = append(kept, it) diff --git a/internal/gateway/codex_backend.go b/internal/gateway/codex_backend.go index 8cf8be00c..dc2463463 100644 --- a/internal/gateway/codex_backend.go +++ b/internal/gateway/codex_backend.go @@ -501,7 +501,7 @@ func leadFirst(scope, parent string, cands []candidate, pl planned) ([]candidate // fields (including ordinary model history) keep their existing handling. func hasSealedAgentMessage(body []byte) bool { var request map[string]json.RawMessage - if decodeJSON(body, &request) != nil { + if decodeJSONView(body, &request) != nil { return false } items, isList := inputList(request["input"]) @@ -513,7 +513,7 @@ func hasSealedAgentMessage(body []byte) bool { Type string `json:"type"` Content json.RawMessage `json:"content"` } - if decodeJSON(raw, &item) != nil || item.Type != "agent_message" { + if decodeJSONView(raw, &item) != nil || item.Type != "agent_message" { continue } for _, content := range elementsOf(trimJSON(item.Content)) { diff --git a/internal/gateway/fastjson.go b/internal/gateway/fastjson.go index 370807817..744aeb31d 100644 --- a/internal/gateway/fastjson.go +++ b/internal/gateway/fastjson.go @@ -38,7 +38,17 @@ import ( // error, and what it leaves in dst, are encoding/json's own. So does a dst // that already holds something, which encoding/json decodes into in ways // of its own (a slice's old elements are decoded over, not replaced). -func decodeJSON(data []byte, dst any) error { +func decodeJSON(data []byte, dst any) error { return decodeJSONIn(data, dst, false) } + +// decodeJSONView is decodeJSON for a reader that keeps nothing it decodes +// past its return and writes none of it: every raw value shares data's +// bytes, capped, where decodeJSON copies what isn't a big share of a held +// body. A body a route has rewritten is held by nobody, so each reader of +// a rewritten Codex request copied its whole input to look at it: 1.4 of +// the 16.4 MB a 680 KB request allocated (#3383). +func decodeJSONView(data []byte, dst any) error { return decodeJSONIn(data, dst, true) } + +func decodeJSONIn(data []byte, dst any, share bool) error { v := reflect.ValueOf(dst) if v.Kind() != reflect.Pointer || v.IsNil() || !v.Elem().IsZero() { return json.Unmarshal(data, dst) @@ -60,7 +70,7 @@ func decodeJSON(data []byte, dst any) error { // of the value's opening and its close. return json.Unmarshal(append(data[:start+1:start+1], close), dst) } - if err := fillJSONIn(trimJSON(data), v.Elem(), members); err != nil { + if err := fillJSONIn(trimJSON(data), v.Elem(), members, share); err != nil { v.Elem().SetZero() return json.Unmarshal(data, dst) } @@ -279,14 +289,15 @@ func (f *fastFields) field(key []byte) int { // fillJSON decodes raw, a whole valid JSON value, into v; errSlowJSON or // another error leaves it to encoding/json. -func fillJSON(raw []byte, v reflect.Value) error { return fillJSONIn(raw, v, nil) } +func fillJSON(raw []byte, v reflect.Value, share bool) error { return fillJSONIn(raw, v, nil, share) } // fillJSONIn is fillJSON with where raw's members are, when known -// (longBody): a struct or map at raw's top is filled from them. -func fillJSONIn(raw []byte, v reflect.Value, members []memberSpan) error { +// (longBody): a struct or map at raw's top is filled from them. share +// is decodeJSONView's: every raw value is raw's own bytes. +func fillJSONIn(raw []byte, v reflect.Value, members []memberSpan, share bool) error { t := v.Type() if t == rawMessageType { - if inHeldBody(raw) { + if share || inHeldBody(raw) { // the request's own body, which nothing writes to: shared, // and capped so an append to it can't write over the body v.SetBytes(raw[:len(raw):len(raw)]) @@ -312,7 +323,7 @@ func fillJSONIn(raw []byte, v reflect.Value, members []memberSpan) error { if v.IsNil() { v.Set(reflect.New(t.Elem())) } - return fillJSONIn(raw, v.Elem(), members) + return fillJSONIn(raw, v.Elem(), members, share) case reflect.String: if null { return nil @@ -377,7 +388,7 @@ func fillJSONIn(raw []byte, v reflect.Value, members []memberSpan) error { err = errSlowJSON // a key twice: encoding/json merges them return false } - err = fillJSON(val, v.Field(f.index[i])) + err = fillJSON(val, v.Field(f.index[i]), share) return err == nil }) return err @@ -399,7 +410,7 @@ func fillJSONIn(raw []byte, v reflect.Value, members []memberSpan) error { }) s := reflect.MakeSlice(t, len(elems), len(elems)) for i, el := range elems { - if err := fillJSON(el, s.Index(i)); err != nil { + if err := fillJSON(el, s.Index(i), share); err != nil { return err } } @@ -427,7 +438,7 @@ func fillJSONIn(raw []byte, v reflect.Value, members []memberSpan) error { return false } el := reflect.New(t.Elem()).Elem() - if err = fillJSON(val, el); err != nil { + if err = fillJSON(val, el, share); err != nil { return false } v.SetMapIndex(reflect.ValueOf(name), el) diff --git a/internal/gateway/fastjson_test.go b/internal/gateway/fastjson_test.go index 127d1bab8..48b7637da 100644 --- a/internal/gateway/fastjson_test.go +++ b/internal/gateway/fastjson_test.go @@ -1,6 +1,7 @@ package gateway import ( + "bytes" "encoding/json" "fmt" "math/rand/v2" @@ -8,6 +9,7 @@ import ( "strings" "testing" "time" + "unsafe" "github.com/yetone/magpie/internal/provider" ) @@ -134,6 +136,10 @@ func fjCompare(t *testing.T, data []byte) { if !reflect.DeepEqual(got, want) { t.Fatalf("%T %q:\n decodeJSON %#v\n json.Unmarshal %#v", got, data, got, want) } + view := mk() + if verr := decodeJSONView(data, view); (verr == nil) != (werr == nil) || !reflect.DeepEqual(view, want) { + t.Fatalf("%T %q:\n decodeJSONView %#v %v\n json.Unmarshal %#v %v", view, data, view, verr, want, werr) + } } } @@ -173,17 +179,48 @@ func TestDecodeJSONKeyTwice(t *testing.T) { } // the fast path's own refusal, which encoding/json then decodes for _, s := range []string{`{"f66":"a","f66":"b"}`, `{"f3":"a","F3":"b"}`} { - if err := fillJSON([]byte(s), reflect.New(wide).Elem()); err != errSlowJSON { + if err := fillJSON([]byte(s), reflect.New(wide).Elem(), false); err != errSlowJSON { t.Fatalf("%s: fillJSON %v, want errSlowJSON", s, err) } } for _, s := range []string{`{"model":"a","model":"b"}`, `{"Model":"a","MODEL":"b"}`} { - if err := fillJSON([]byte(s), reflect.ValueOf(new(fjBody)).Elem()); err != errSlowJSON { + if err := fillJSON([]byte(s), reflect.ValueOf(new(fjBody)).Elem(), false); err != errSlowJSON { t.Fatalf("%s: fillJSON %v, want errSlowJSON", s, err) } } } +// decodeJSONView's raw values are the bytes it read, capped, however +// small a share of them: a rewritten body, which nobody holds, is read +// without a copy of its input. +func TestDecodeJSONViewShares(t *testing.T) { + body := []byte(`{"model":"m","input":[{"type":"message","content":[{"type":"input_text","text":"hi"}]},{"type":"function_call_output","call_id":"c","output":"ok"}],"tools":[]}`) + var q map[string]json.RawMessage + if err := decodeJSONView(body, &q); err != nil { + t.Fatal(err) + } + var item struct { + Content json.RawMessage `json:"content"` + } + in := elementsOf(q["input"]) + if err := decodeJSONView(in[0], &item); err != nil { + t.Fatal(err) + } + for name, raw := range map[string]json.RawMessage{"input": q["input"], "tools": q["tools"], "content": item.Content} { + i := bytes.Index(body, raw) + if i < 0 || unsafe.SliceData(raw) != unsafe.SliceData(body[i:]) || cap(raw) != len(raw) { + t.Fatalf("%s %s: not body's own bytes, capped", name, raw) + } + } + var copied map[string]json.RawMessage + if err := decodeJSON(body, &copied); err != nil { + t.Fatal(err) + } + if unsafe.SliceData(copied["tools"]) == unsafe.SliceData(body[bytes.Index(body, []byte(`[]`)):]) { + t.Fatal("decodeJSON shared a body nobody holds") + } +} + func TestDecodeJSONDepth(t *testing.T) { for _, n := range []int{9999, 10000, 10001} { fjCompare(t, []byte(strings.Repeat("[", n)+strings.Repeat("]", n))) diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index 9668dc59f..b605dd956 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -6667,7 +6667,7 @@ func conversationID(in http.Header, body []byte) string { Contents json.RawMessage `json:"contents"` } // An undecodable body still gets an id: the hash of the whole body. - _ = decodeJSON(body, &m) + _ = decodeJSONView(body, &m) // The turns are the body's own bytes, not a copy of each: this runs on // every request, and a 1.5 MB conversation's copy was ~2.8 MB of each // request's allocations (yg6888 on X). @@ -6688,7 +6688,7 @@ func conversationID(in http.Header, body []byte) string { Role string `json:"role"` } // Gemini treats an omitted role as user; Chat and Responses do not. - if decodeJSON(it, &r) == nil && (r.Role == "user" || (geminiContents && r.Role == "")) { + if decodeJSONView(it, &r) == nil && (r.Role == "user" || (geminiContents && r.Role == "")) { first = it break } diff --git a/internal/gateway/responses.go b/internal/gateway/responses.go index 94d98d4a9..c70f7bbba 100644 --- a/internal/gateway/responses.go +++ b/internal/gateway/responses.go @@ -594,7 +594,7 @@ func joinToolRuns(body []byte) []byte { return body } var q map[string]json.RawMessage - if decodeJSON(body, &q) != nil { + if decodeJSONView(body, &q) != nil { return body } input, isList := inputList(q["input"]) @@ -608,7 +608,7 @@ func joinToolRuns(body []byte) []byte { } items := make([]item, len(input)) for i, raw := range input { - if decodeJSON(raw, &items[i]) != nil { + if decodeJSONView(raw, &items[i]) != nil { items[i] = item{} } } @@ -696,7 +696,7 @@ func joinToolRuns(body []byte) []byte { // requiring paired outputs still need the delivered text, without a fake call ID. func orphanedToolOutputs(body []byte) []byte { var q map[string]json.RawMessage - if decodeJSON(body, &q) != nil { + if decodeJSONView(body, &q) != nil { return body } input, isList := inputList(q["input"]) @@ -717,7 +717,7 @@ func orphanedToolOutputs(body []byte) []byte { CallID string `json:"call_id"` Output json.RawMessage `json:"output"` } - if decodeJSON(raw, &item) != nil { + if decodeJSONView(raw, &item) != nil { flush() inCalls = false out = append(out, raw) @@ -790,7 +790,7 @@ func pairToolItems(body []byte) []byte { return body } var q map[string]json.RawMessage - if decodeJSON(body, &q) != nil { + if decodeJSONView(body, &q) != nil { return body } input, isList := inputList(q["input"]) @@ -804,7 +804,7 @@ func pairToolItems(body []byte) []byte { items := make([]item, len(input)) answered := map[string]bool{} for i, raw := range input { - if decodeJSON(raw, &items[i]) != nil { + if decodeJSONView(raw, &items[i]) != nil { items[i] = item{} } if t := items[i].Type; (t == "function_call_output" || t == "custom_tool_call_output") && items[i].CallID != "" { @@ -914,7 +914,7 @@ func withReasoningText(body []byte) []byte { return body } var q map[string]json.RawMessage - if decodeJSON(body, &q) != nil { + if decodeJSONView(body, &q) != nil { return body } items, isList := inputList(q["input"]) @@ -930,7 +930,7 @@ func withReasoningText(body []byte) []byte { Summary []rText `json:"summary"` Content []rText `json:"content"` } - if decodeJSON(raw, &it) != nil { + if decodeJSONView(raw, &it) != nil { continue } kinds[i] = stepKindOf(it.Type, it.Role) @@ -946,7 +946,7 @@ func withReasoningText(body []byte) []byte { b.WriteString(noReasoning) } var m map[string]json.RawMessage - if decodeJSON(raw, &m) != nil { + if decodeJSONView(raw, &m) != nil { continue } m["content"], _ = json.Marshal([]map[string]string{{"type": "reasoning_text", "text": b.String()}})