Files
magpie/internal/gateway/fastjson_test.go
T
yetone 5feadabef6 gateway: a long conversation's request costs about a third of the CPU it did, with the same bytes sent on (#1532, #1654)
The gateway reads one request's body a dozen times or more on its way:
modelOf, streamOf, conversationID, requestEffort, bodyEffort,
walkImages and swapImageBlocks (more than once through a group), turnOf's
parse, promptOf, chatToolNames, thinkingOffUnlessAsked, decodeRequest,
and for Responses pairToolItems, orphanedToolOutputs,
hasSealedAgentMessage and askedTier. Each read took a field or two with
json.Unmarshal, which checks the whole input and then steps through every
byte of every string one call at a time, so each read cost as much as
decoding the whole conversation: 74-77% of a request's CPU in pprof, most
of it checkValid and stateInString.

decodeJSON (fastjson.go) is json.Unmarshal for these reads. It checks the
body once with its own validator (json.Valid's grammar and 10000 depth,
8 string bytes at a time), splits objects and arrays at their members
without decoding them, and decodes only what dst has a place for:
strings, booleans, json.RawMessage (copied, as encoding/json does),
structs, pointers, slices and string-keyed maps by their parts, and
everything else (numbers, interfaces, types that decode themselves) by
encoding/json itself. Whatever it doesn't take on exactly as
json.Unmarshal would goes to json.Unmarshal with dst zeroed: invalid
input, a dst already holding something, an embedded field, a ",string"
option, two fields of one name, a key given twice, a value of the wrong
type. A list or object where dst takes a string (a "string or parts"
read) is answered by json.Unmarshal of its opening and close, which gives
the same error at the same offset without reading the rest. The request
paths' json.Unmarshal calls in gateway.go, decide.go, affinity.go,
image_input.go, textcalls.go, anthropic.go, ir.go, prompt.go, chat.go,
chattidy.go and responses.go, and hasSealedAgentMessage and askedTier,
now call it. Nothing that writes a body changed.

Numbers, M4 Pro under load 10-20 from other sessions, BenchmarkLargeRequest
(new: a 2 MB agent conversation with 30 tools, tool calls and results,
through a fake vendor), 20 requests each:

                    CPU in the request's handler    time per request
                    (pprof, per request)            (ns/op)
  anthropic         154ms -> 45ms                   208-212ms -> 52ms
  anthropic, group  178ms -> 51ms                   249-262ms -> 65-67ms
  chat              122ms -> 35ms                   167-254ms -> 50-54ms
  responses         215ms -> 56ms                   294-452ms -> 70ms

TestLargeRequestEndpoints (64 MB padded bodies): 16.8-17.6s -> 2.9-4.8s
(skipping runs of spaces 8 bytes at a time took its last ~5s).

Tests:
- TestUpstreamBodiesUnchanged sends 18 requests (Anthropic, Chat and
  Responses; direct, through a group, translated to each other protocol,
  with images, thinking, escapes, odd spacing, a repeated key, and four
  2 MB conversations) and compares what the vendor gets with
  testdata/upstream_bodies, recorded on the code before this change
  (all 18 identical; three runs agreed). Breaking decodeJSON's \n
  unescape by hand turns the three translated cases holding one red.
- TestDecodeJSONIsUnmarshal / FuzzDecodeJSON compare decodeJSON with
  json.Unmarshal (dst DeepEqual, error nil-ness) for 19 types shaped like
  the gateway's, and jsonValid with json.Valid, over seeds, every cut
  and a changed byte at every place of each seed, and 2.5 minutes of
  fuzzing (~1.75M inputs). Breaking the validator's control-byte check
  by hand turns it red.
- go test -tags nogui -timeout 40m ./... on this commit rebased onto
  origin/main 498b77fbc, with #1667's fix below it: all 48 packages ok
  (gateway 394s).
gofmt -l clean; GOOS=linux and GOOS=windows go vet -tags nogui
./internal/gateway clean.

Not tried: real vendor traffic; Windows and Linux runs (vet only).
2026-10-12 03:28:16 +08:00

170 lines
6.0 KiB
Go

package gateway
import (
"encoding/json"
"math/rand/v2"
"reflect"
"strings"
"testing"
"time"
"github.com/yetone/magpie/internal/provider"
)
// The types a request body is decoded into, in the shapes they take.
type fjBlock struct {
Type string `json:"type"`
Text string `json:"text"`
ID string `json:"id,omitempty"`
Input json.RawMessage `json:"input"`
Content json.RawMessage `json:"content"`
Source *struct {
Type string `json:"type"`
Data string `json:"data"`
} `json:"source"`
Cache map[string]string `json:"cache_control"`
}
type fjBody struct {
Model string `json:"model"`
Stream bool `json:"stream"`
MaxTok int `json:"max_tokens"`
Temp *float64
System json.RawMessage `json:"system"`
Messages []struct {
Role string `json:"role"`
Content json.RawMessage `json:"content"`
Blocks []fjBlock `json:"blocks"`
} `json:"messages"`
Tools []map[string]json.RawMessage `json:"tools"`
Thinking *struct {
Type string `json:"type"`
Budget int `json:"budget_tokens"`
} `json:"thinking"`
Meta map[string]any `json:"metadata"`
Any any `json:"any"`
Bytes []byte `json:"bytes"`
Arr [2]string `json:"arr"`
Args rArgs `json:"args"`
At *time.Time `json:"at"`
When time.Time `json:"when"`
Ptrs []*fjBlock `json:"ptrs"`
Strs []string `json:"strs"`
ignored string
Skip string `json:"-"`
Untagged string
}
type fjEmbed struct {
fjBlock
Extra string `json:"extra"`
}
type fjNumStr struct {
N int `json:"n,string"`
}
type fjClash struct {
A string `json:"X"`
X string
}
var fjSeeds = []string{
`{}`, `[]`, `null`, `true`, `"x"`, `1`, ` {"model" : "m" } `,
`{"model":"claude","stream":true,"max_tokens":32000,"messages":[{"role":"user","content":"hi"},{"role":"assistant","content":[{"type":"text","text":"a\nb"}],"blocks":[{"type":"tool_use","id":"t","input":{"a":[1,2,{"b":null}]}}]}]}`,
`{"Model":"fold","MODEL":"again"}`,
`{"model":"a","model":"b"}`,
`{"messages":null,"tools":[],"thinking":null,"system":null}`,
`{"messages":[null,{"role":null}],"ptrs":[null,{"type":"x"}]}`,
`{"model":1}`, `{"stream":"yes"}`, `{"messages":{}}`, `{"tools":[1]}`,
`{"model":"\u00e9\ud83d\ude00\ud800x\u0000\"\\\/\b\f\n\r\t"}`,
"{\"model\":\"\xff\xfe raw invalid utf8 \xe6\xbc\"}",
`{"mod\u0065l":"escaped key","str\u0073":["a"]}`,
`{"metadata":{"user_id":"u","n":1.5e3,"deep":{"a":[true,false,null]}},"any":[1,"a",{}]}`,
`{"bytes":"aGVsbG8=","arr":["a","b","c"],"args":{"k":"v"},"Temp":0.5}`,
`{"args":"{\"k\":1}","Untagged":"u","Skip":"s","ignored":"i"}`,
`{"tools":[{"name":"a","input_schema":{"type":"object"}},{"name":"b"}]}`,
`{"messages":[{"blocks":[{"source":{"type":"base64","data":"AAA"},"cache_control":{"type":"ephemeral"}}]}]}`,
`{"model":"x"} trailing`, `{"model":"x",}`, `{"model":}`, `[1,]`, `{"a":01}`, `{"a":-}`, `{"a":1.}`, `{"a":1e}`,
`{"a":"\x"}`, `{"a":"\u12g4"}`, "{\"a\":\"\x01\"}", `{"a":tru}`, `{"a" "b"}`, `{`, `"`, ``, ` `,
`{"extra":"e","type":"t"}`, `{"n":"12"}`, `{"x":"1"}`, `{"X":"2"}`,
`{"at":"2024-01-01T00:00:00Z","when":"2024-02-01T00:00:00+08:00","model":"m"}`, `{"at":null,"when":null}`, `{"at":1}`, `{"args":null}`,
` [1, {"a":"b"}] `, " \t {\"model\":\"m\"} \n ", " {\"model\" : \"m\"} \x00", "\n{\"a\":[\"x\"]}", `[{"type":"text"},"s"]`,
`"a long string with no escapes at all, past eight bytes"`, `"sevené then \"quoted\" \\ and \t past eight"`,
"\"a control byte \x1f deep in a long string\"", "\"\x7f\x80 high bytes \xc3\xa9 \xe2\x82\xac in a long string\"",
`{"strs":["a",null,"b"]}`, `{"strs":"notarray"}`, `{"metadata":null}`, `{"metadata":[]}`,
}
func fjCompare(t *testing.T, data []byte) {
t.Helper()
if got, want := jsonValid(data), json.Valid(data); got != want {
t.Fatalf("jsonValid(%q) = %v, json.Valid %v", data, got, want)
}
for _, mk := range []func() any{
func() any { return new(fjBody) },
func() any { return new(fjBlock) },
func() any { return new([]fjBlock) },
func() any { return new(map[string]json.RawMessage) },
func() any { return new([]json.RawMessage) },
func() any { return new(json.RawMessage) },
func() any { return new(any) },
func() any { return new(string) },
func() any { return new(*string) },
func() any { return new(bool) },
func() any { return new(int) },
func() any { return new([]string) },
func() any { return new(map[string]string) },
func() any { return new(rArgs) },
func() any { return new(fjEmbed) },
func() any { return new(fjNumStr) },
func() any { return new(fjClash) },
func() any { return new(*fjBody) },
func() any {
return &fjBody{Model: "old", Strs: []string{"a", "b", "c"}, Ptrs: []*fjBlock{{Type: "old"}}}
},
} {
got, want := mk(), mk()
gerr := decodeJSON(data, got)
werr := json.Unmarshal(data, want)
if (gerr == nil) != (werr == nil) {
t.Fatalf("%T %q: decodeJSON error %v, json.Unmarshal %v", got, data, gerr, werr)
}
if !reflect.DeepEqual(got, want) {
t.Fatalf("%T %q:\n decodeJSON %#v\n json.Unmarshal %#v", got, data, got, want)
}
}
}
func TestDecodeJSONIsUnmarshal(t *testing.T) {
for _, s := range fjSeeds {
fjCompare(t, []byte(s))
}
for _, proto := range []provider.Protocol{provider.Anthropic, provider.Chat, provider.Responses} {
fjCompare(t, largeConversation(proto, "m", 2000))
}
// every cut and every one-byte change of a real body
r := rand.New(rand.NewPCG(1, 2))
for _, s := range fjSeeds {
for i := range len(s) {
fjCompare(t, []byte(s[:i]))
b := []byte(s)
b[i] = "{}[]\",:\\ nul0e.-x\xff"[r.IntN(18)]
fjCompare(t, b)
}
}
}
func TestDecodeJSONDepth(t *testing.T) {
for _, n := range []int{9999, 10000, 10001} {
fjCompare(t, []byte(strings.Repeat("[", n)+strings.Repeat("]", n)))
fjCompare(t, []byte(`{"any":`+strings.Repeat("[", n)+strings.Repeat("]", n)+`}`))
}
}
func FuzzDecodeJSON(f *testing.F) {
for _, s := range fjSeeds {
f.Add([]byte(s))
}
f.Fuzz(func(t *testing.T, data []byte) { fjCompare(t, data) })
}