From 5feadabef60ae1d39ca7b47118e4d56568bf5de9 Mon Sep 17 00:00:00 2001 From: yetone Date: Mon, 12 Oct 2026 02:58:03 +0800 Subject: [PATCH] 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). --- internal/gateway/affinity.go | 18 +- internal/gateway/anthropic.go | 32 +- internal/gateway/chat.go | 26 +- internal/gateway/chattidy.go | 46 +- internal/gateway/codex_backend.go | 8 +- internal/gateway/decide.go | 18 +- internal/gateway/effort_accounts.go | 2 +- internal/gateway/fastjson.go | 757 ++++++++++++++++++ internal/gateway/fastjson_test.go | 169 ++++ internal/gateway/gateway.go | 44 +- internal/gateway/image_input.go | 30 +- internal/gateway/ir.go | 10 +- internal/gateway/large_body_bench_test.go | 121 +++ internal/gateway/prompt.go | 38 +- internal/gateway/responses.go | 60 +- .../upstream_bodies/anthropic-group.json | 7 + .../upstream_bodies/anthropic-image.json | 1 + .../upstream_bodies/anthropic-thinking.json | 1 + .../upstream_bodies/anthropic-to-chat.json | 1 + .../anthropic-to-responses.json | 1 + .../testdata/upstream_bodies/anthropic.json | 7 + .../testdata/upstream_bodies/chat-group.json | 5 + .../upstream_bodies/chat-to-anthropic.json | 1 + .../testdata/upstream_bodies/chat.json | 5 + .../large-anthropic-group.sha256 | 1 + .../upstream_bodies/large-anthropic.sha256 | 1 + .../upstream_bodies/large-chat.sha256 | 1 + .../large-responses-to-chat.sha256 | 1 + .../upstream_bodies/large-responses.sha256 | 1 + .../upstream_bodies/responses-string.json | 1 + .../responses-to-anthropic.json | 1 + .../upstream_bodies/responses-to-chat.json | 1 + .../testdata/upstream_bodies/responses.json | 8 + internal/gateway/textcalls.go | 12 +- internal/gateway/upstream_bytes_test.go | 151 ++++ 35 files changed, 1415 insertions(+), 172 deletions(-) create mode 100644 internal/gateway/fastjson.go create mode 100644 internal/gateway/fastjson_test.go create mode 100644 internal/gateway/large_body_bench_test.go create mode 100644 internal/gateway/testdata/upstream_bodies/anthropic-group.json create mode 100644 internal/gateway/testdata/upstream_bodies/anthropic-image.json create mode 100644 internal/gateway/testdata/upstream_bodies/anthropic-thinking.json create mode 100644 internal/gateway/testdata/upstream_bodies/anthropic-to-chat.json create mode 100644 internal/gateway/testdata/upstream_bodies/anthropic-to-responses.json create mode 100644 internal/gateway/testdata/upstream_bodies/anthropic.json create mode 100644 internal/gateway/testdata/upstream_bodies/chat-group.json create mode 100644 internal/gateway/testdata/upstream_bodies/chat-to-anthropic.json create mode 100644 internal/gateway/testdata/upstream_bodies/chat.json create mode 100644 internal/gateway/testdata/upstream_bodies/large-anthropic-group.sha256 create mode 100644 internal/gateway/testdata/upstream_bodies/large-anthropic.sha256 create mode 100644 internal/gateway/testdata/upstream_bodies/large-chat.sha256 create mode 100644 internal/gateway/testdata/upstream_bodies/large-responses-to-chat.sha256 create mode 100644 internal/gateway/testdata/upstream_bodies/large-responses.sha256 create mode 100644 internal/gateway/testdata/upstream_bodies/responses-string.json create mode 100644 internal/gateway/testdata/upstream_bodies/responses-to-anthropic.json create mode 100644 internal/gateway/testdata/upstream_bodies/responses-to-chat.json create mode 100644 internal/gateway/testdata/upstream_bodies/responses.json create mode 100644 internal/gateway/upstream_bytes_test.go diff --git a/internal/gateway/affinity.go b/internal/gateway/affinity.go index c845dc2d7..25f313993 100644 --- a/internal/gateway/affinity.go +++ b/internal/gateway/affinity.go @@ -126,7 +126,7 @@ func stickOf(key string) (stick, bool) { return stick{}, false } var saved map[string]savedStick - if json.Unmarshal(b, &saved) != nil { + if decodeJSON(b, &saved) != nil { return stick{}, false } for k, v := range saved { @@ -489,7 +489,7 @@ func seals(body []byte, kinds ...string) [][sha256.Size]byte { var q struct { Input []sealedItem `json:"input"` } - if json.Unmarshal(body, &q) != nil { + if decodeJSON(body, &q) != nil { return nil } var out [][sha256.Size]byte @@ -546,17 +546,17 @@ func withoutRefused(key, who string, body []byte) ([]byte, bool) { return nil, false } var q map[string]json.RawMessage - if json.Unmarshal(body, &q) != nil { + if decodeJSON(body, &q) != nil { return nil, false } var items []json.RawMessage - if json.Unmarshal(q["input"], &items) != nil { + if decodeJSON(q["input"], &items) != nil { return nil, false } kept := items[:0:0] for _, it := range items { var t sealedItem - if json.Unmarshal(it, &t) == nil && sealedKinds[t.Type] && t.Enc != "" && r.seals[sha256.Sum256([]byte(t.Enc))] { + if decodeJSON(it, &t) == nil && sealedKinds[t.Type] && t.Enc != "" && r.seals[sha256.Sum256([]byte(t.Enc))] { continue } kept = append(kept, it) @@ -585,7 +585,7 @@ func withoutCompaction(body []byte) ([]byte, bool) { var q struct { Input []sealedItem `json:"input"` } - if json.Unmarshal(body, &q) != nil { + if decodeJSON(body, &q) != nil { return nil, false } for _, it := range q.Input { @@ -600,11 +600,11 @@ func withoutCompaction(body []byte) ([]byte, bool) { // types. func withoutKinds(body []byte, kinds ...string) ([]byte, bool) { var q map[string]json.RawMessage - if json.Unmarshal(body, &q) != nil { + if decodeJSON(body, &q) != nil { return nil, false } var items []json.RawMessage - if json.Unmarshal(q["input"], &items) != nil { + if decodeJSON(q["input"], &items) != nil { return nil, false } kept := items[:0:0] @@ -612,7 +612,7 @@ func withoutKinds(body []byte, kinds ...string) ([]byte, bool) { var t struct { Type string `json:"type"` } - if json.Unmarshal(it, &t) == nil && slices.Contains(kinds, t.Type) { + if decodeJSON(it, &t) == nil && slices.Contains(kinds, t.Type) { continue } kept = append(kept, it) diff --git a/internal/gateway/anthropic.go b/internal/gateway/anthropic.go index 9269c2984..b2c1b2f8f 100644 --- a/internal/gateway/anthropic.go +++ b/internal/gateway/anthropic.go @@ -110,7 +110,7 @@ type aRequest struct { func parseAnthropic(body []byte) (*Request, error) { var a aRequest - if err := json.Unmarshal(body, &a); err != nil { + if err := decodeJSON(body, &a); err != nil { return nil, fmt.Errorf("invalid request: %v", err) } r := &Request{Model: a.Model, System: stringOrText(a.System), MaxTokens: a.MaxTokens, @@ -128,13 +128,13 @@ func parseAnthropic(body []byte) (*Request, error) { for _, m := range a.Messages { msg := Message{Role: m.Role} var s string - if json.Unmarshal(m.Content, &s) == nil { + if decodeJSON(m.Content, &s) == nil { if s != "" { msg.Parts = append(msg.Parts, Part{Kind: Text, Text: s}) } } else { var blocks []aBlock - if err := json.Unmarshal(m.Content, &blocks); err != nil { + if err := decodeJSON(m.Content, &blocks); err != nil { return nil, fmt.Errorf("invalid message content: %v", err) } var raws []json.RawMessage // each block as the client sent it @@ -158,7 +158,7 @@ func parseAnthropic(body []byte) (*Request, error) { // goes back to Messages whole, and is nothing to // another API (#1445) if raws == nil { - _ = json.Unmarshal(m.Content, &raws) + _ = decodeJSON(m.Content, &raws) } if i < len(raws) { msg.Parts = append(msg.Parts, Part{Kind: Thinking, Sealed: raws[i], SealedBy: sealAnthropic}) @@ -223,7 +223,7 @@ func thinkingOffUnlessAsked(body []byte) []byte { var v struct { Thinking json.RawMessage `json:"thinking"` } - if json.Unmarshal(body, &v) != nil || v.Thinking != nil { + if decodeJSON(body, &v) != nil || v.Thinking != nil { return body } // added at the end, the rest left byte for byte as the agent sent it @@ -266,7 +266,7 @@ func withThinkingOnToolTurns(body []byte) []byte { } var q map[string]json.RawMessage var msgs []json.RawMessage - if json.Unmarshal(body, &q) != nil || json.Unmarshal(q["messages"], &msgs) != nil { + if decodeJSON(body, &q) != nil || decodeJSON(q["messages"], &msgs) != nil { return body } space, _ := json.Marshal(aBlock{Type: "thinking", Thinking: noReasoning}) @@ -275,8 +275,8 @@ func withThinkingOnToolTurns(body []byte) []byte { var m map[string]json.RawMessage var role string var blocks []json.RawMessage - if json.Unmarshal(raw, &m) != nil || json.Unmarshal(m["role"], &role) != nil || role != "assistant" || - json.Unmarshal(m["content"], &blocks) != nil { + if decodeJSON(raw, &m) != nil || decodeJSON(m["role"], &role) != nil || role != "assistant" || + decodeJSON(m["content"], &blocks) != nil { continue } var out []json.RawMessage @@ -285,7 +285,7 @@ func withThinkingOnToolTurns(body []byte) []byte { var t struct { Type string `json:"type"` } - json.Unmarshal(b, &t) + decodeJSON(b, &t) switch t.Type { case "thinking": thought = true @@ -350,7 +350,7 @@ func withoutThinkingOff(body []byte) ([]byte, bool) { var th struct { Type string `json:"type"` } - if json.Unmarshal(body, &q) != nil || json.Unmarshal(q["thinking"], &th) != nil || th.Type != "disabled" { + if decodeJSON(body, &q) != nil || decodeJSON(q["thinking"], &th) != nil || th.Type != "disabled" { return nil, false } delete(q, "thinking") @@ -696,7 +696,7 @@ func withOutputEffort(body []byte, levels []string) []byte { var v struct { OutputConfig map[string]any `json:"output_config"` } - if e == "" || json.Unmarshal(body, &v) != nil { + if e == "" || decodeJSON(body, &v) != nil { return body } oc := v.OutputConfig @@ -950,7 +950,7 @@ func (d *anthropicDecoder) decode(data string, emit func(Event)) error { Type string `json:"type"` } `json:"delta"` } - if json.Unmarshal([]byte(data), &ev) == nil { + if decodeJSON([]byte(data), &ev) == nil { switch ev.Type { case "content_block_start": d.server[ev.Index] = ev.ContentBlock.Type == "server_tool_use" @@ -979,7 +979,7 @@ func (d *anthropicDecoder) decode(data string, emit func(Event)) error { // object with something in it. func fullInput(in json.RawMessage) bool { var m map[string]any - return json.Unmarshal(in, &m) == nil && len(m) > 0 + return decodeJSON(in, &m) == nil && len(m) > 0 } // decodeAnthropic turns an Anthropic event stream into events. @@ -1017,7 +1017,7 @@ func decodeAnthropic(data string, emit func(Event)) error { Message string `json:"message"` } `json:"error"` } - if err := json.Unmarshal([]byte(data), &ev); err != nil { + if err := decodeJSON([]byte(data), &ev); err != nil { return nil // keep going: pings and unknown shapes are harmless } switch ev.Type { @@ -1046,7 +1046,7 @@ func decodeAnthropic(data string, emit func(Event)) error { var whole struct { Block json.RawMessage `json:"content_block"` } - if json.Unmarshal([]byte(data), &whole) == nil && len(whole.Block) > 0 { + if decodeJSON([]byte(data), &whole) == nil && len(whole.Block) > 0 { emit(Event{Kind: KSealed, Name: sealAnthropic, Text: string(whole.Block)}) } } @@ -1455,7 +1455,7 @@ func objectSchema(schema json.RawMessage) json.RawMessage { return schema } var m map[string]any - if json.Unmarshal(schema, &m) != nil || !provider.ObjectRoot(m) { + if decodeJSON(schema, &m) != nil || !provider.ObjectRoot(m) { return schema } b, err := json.Marshal(m) diff --git a/internal/gateway/chat.go b/internal/gateway/chat.go index 687421772..e9ab05eaf 100644 --- a/internal/gateway/chat.go +++ b/internal/gateway/chat.go @@ -66,7 +66,7 @@ type cRequest struct { func parseChat(body []byte) (*Request, error) { var c cRequest - if err := json.Unmarshal(body, &c); err != nil { + if err := decodeJSON(body, &c); err != nil { return nil, fmt.Errorf("invalid request: %v", err) } r := &Request{Model: c.Model, MaxTokens: c.MaxCompletionTokens, Temp: c.Temperature, TopP: c.TopP, @@ -80,10 +80,10 @@ func parseChat(body []byte) (*Request, error) { } r.ThinkOff = strings.EqualFold(strings.TrimSpace(c.ReasoningEffort), "none") var stop string - if json.Unmarshal(c.Stop, &stop) == nil && stop != "" { + if decodeJSON(c.Stop, &stop) == nil && stop != "" { r.Stop = []string{stop} } else { - json.Unmarshal(c.Stop, &r.Stop) + decodeJSON(c.Stop, &r.Stop) } var sys []string for _, m := range c.Messages { @@ -120,7 +120,7 @@ func parseChat(body []byte) (*Request, error) { r.Tools = append(r.Tools, Tool{Name: t.Function.Name, Description: t.Function.Description, Schema: t.Function.Parameters, Strict: t.Function.Strict != nil && *t.Function.Strict}) } var tc string - if json.Unmarshal(c.ToolChoice, &tc) == nil { + if decodeJSON(c.ToolChoice, &tc) == nil { r.ToolChoice = tc } else { var o struct { @@ -129,7 +129,7 @@ func parseChat(body []byte) (*Request, error) { Name string `json:"name"` } `json:"function"` } - if json.Unmarshal(c.ToolChoice, &o) == nil && o.Function.Name != "" { + if decodeJSON(c.ToolChoice, &o) == nil && o.Function.Name != "" { r.ToolChoice = "name:" + o.Function.Name } } @@ -139,7 +139,7 @@ func parseChat(body []byte) (*Request, error) { // chatParts reads a message's content: a string, or an array of parts. func chatParts(raw json.RawMessage) []Part { var s string - if json.Unmarshal(raw, &s) == nil { + if decodeJSON(raw, &s) == nil { if s == "" { return nil } @@ -157,7 +157,7 @@ func chatParts(raw json.RawMessage) []Part { Filename string `json:"filename"` } `json:"file"` } - json.Unmarshal(raw, &items) + decodeJSON(raw, &items) var out []Part for _, it := range items { switch it.Type { @@ -662,7 +662,7 @@ func thinkingEffort(body []byte) []byte { ReasoningEffort *string `json:"reasoning_effort"` Thinking map[string]any `json:"thinking"` } - if json.Unmarshal(body, &v) != nil || v.ReasoningEffort != nil { + if decodeJSON(body, &v) != nil || v.ReasoningEffort != nil { return body } effort, _ := v.Thinking["effort"].(string) @@ -913,7 +913,7 @@ func (d *chatDecoder) decode(data string, emit func(Event)) error { Message string `json:"message"` } `json:"error"` } - if err := json.Unmarshal([]byte(data), &ch); err != nil { + if err := decodeJSON([]byte(data), &ch); err != nil { return nil } if ch.Error != nil { @@ -948,7 +948,7 @@ func (d *chatDecoder) decode(data string, emit func(Event)) error { t += think content = text } else { - json.Unmarshal(c.Delta.Content, &content) + decodeJSON(c.Delta.Content, &content) } if c.Delta.ExtraContent.Google.Thought { t, content = t+content, "" @@ -1001,17 +1001,17 @@ func chatChoiceIndex(raw json.RawMessage) (string, bool) { return "", false } var text string - if json.Unmarshal(raw, &text) == nil { + if decodeJSON(raw, &text) == nil { raw = json.RawMessage(text) } var n json.Number - if json.Unmarshal(raw, &n) != nil { + if decodeJSON(raw, &n) != nil { return "", false } index, err := n.Int64() if err != nil { var f float64 - if json.Unmarshal(raw, &f) != nil || f < 0 || f != float64(int64(f)) { + if decodeJSON(raw, &f) != nil || f < 0 || f != float64(int64(f)) { return "", false } index = int64(f) diff --git a/internal/gateway/chattidy.go b/internal/gateway/chattidy.go index 54347372b..64f2f3356 100644 --- a/internal/gateway/chattidy.go +++ b/internal/gateway/chattidy.go @@ -114,11 +114,11 @@ func tidyLine(line []byte) []byte { return line } var chunk map[string]json.RawMessage - if json.Unmarshal(data, &chunk) != nil { + if decodeJSON(data, &chunk) != nil { return line } var choices []map[string]json.RawMessage - if json.Unmarshal(chunk["choices"], &choices) != nil { + if decodeJSON(chunk["choices"], &choices) != nil { return line } changed := false @@ -128,7 +128,7 @@ func tidyLine(line []byte) []byte { changed = true } var delta map[string]json.RawMessage - if json.Unmarshal(c["delta"], &delta) != nil { + if decodeJSON(c["delta"], &delta) != nil { continue } inDelta := flattenContent(delta, false) @@ -167,13 +167,13 @@ func tidyLine(line []byte) []byte { // keeps it. func withoutEmptyNames(raw json.RawMessage) (json.RawMessage, bool) { var calls []map[string]json.RawMessage - if json.Unmarshal(raw, &calls) != nil { + if decodeJSON(raw, &calls) != nil { return raw, false } changed := false for _, call := range calls { var fn map[string]json.RawMessage - if json.Unmarshal(call["function"], &fn) != nil { + if decodeJSON(call["function"], &fn) != nil { continue } if string(fn["name"]) != `""` { @@ -206,7 +206,7 @@ func partsText(raw json.RawMessage) (text, think string, ok bool) { Text string `json:"text"` Thinking json.RawMessage `json:"thinking"` } - if json.Unmarshal(raw, &parts) != nil { + if decodeJSON(raw, &parts) != nil { return "", "", false } var tb, kb strings.Builder @@ -217,14 +217,14 @@ func partsText(raw json.RawMessage) (text, think string, ok bool) { case "thinking": // Mistral's is a list of text parts; a plain string is taken too var s string - if json.Unmarshal(p.Thinking, &s) == nil { + if decodeJSON(p.Thinking, &s) == nil { kb.WriteString(s) continue } var inner []struct { Text string `json:"text"` } - json.Unmarshal(p.Thinking, &inner) + decodeJSON(p.Thinking, &inner) for _, in := range inner { kb.WriteString(in.Text) } @@ -249,7 +249,7 @@ func flattenContent(m map[string]json.RawMessage, whole bool) bool { } if think != "" { var had string - json.Unmarshal(m["reasoning_content"], &had) + decodeJSON(m["reasoning_content"], &had) m["reasoning_content"], _ = json.Marshal(had + think) } return true @@ -275,17 +275,17 @@ func (t *chatWhole) flush() []byte { return b } var reply map[string]json.RawMessage - if json.Unmarshal(b, &reply) != nil { + if decodeJSON(b, &reply) != nil { return b } var choices []map[string]json.RawMessage - if json.Unmarshal(reply["choices"], &choices) != nil { + if decodeJSON(reply["choices"], &choices) != nil { return b } changed := false for _, c := range choices { var msg map[string]json.RawMessage - if json.Unmarshal(c["message"], &msg) != nil || !flattenContent(msg, true) { + if decodeJSON(c["message"], &msg) != nil || !flattenContent(msg, true) { continue } c["message"], _ = json.Marshal(msg) @@ -314,7 +314,7 @@ var messageReasoning = []string{"reasoning_content", "reasoning", "reasoning_det func reasoningText(m map[string]json.RawMessage) string { for _, f := range messageReasoning[:2] { var s string - if json.Unmarshal(m[f], &s) == nil && s != "" { + if decodeJSON(m[f], &s) == nil && s != "" { return s } } @@ -322,7 +322,7 @@ func reasoningText(m map[string]json.RawMessage) string { Text string `json:"text"` Summary string `json:"summary"` } - json.Unmarshal(m["reasoning_details"], &details) + decodeJSON(m["reasoning_details"], &details) var b strings.Builder for _, d := range details { if d.Text != "" { @@ -355,12 +355,12 @@ func withReasoningOnToolTurns(body []byte) []byte { return editMessages(body, []string{"tool_calls"}, func(m map[string]json.RawMessage) bool { var role string var calls []json.RawMessage - if json.Unmarshal(m["role"], &role) != nil || role != "assistant" || - json.Unmarshal(m["tool_calls"], &calls) != nil || len(calls) == 0 { + if decodeJSON(m["role"], &role) != nil || role != "assistant" || + decodeJSON(m["tool_calls"], &calls) != nil || len(calls) == 0 { return false } var own *string - if json.Unmarshal(m["reasoning_content"], &own) == nil && own != nil { + if decodeJSON(m["reasoning_content"], &own) == nil && own != nil { return false } think := reasoningText(m) @@ -385,17 +385,17 @@ func editMessages(body []byte, fields []string, edit func(m map[string]json.RawM return body } var q map[string]json.RawMessage - if json.Unmarshal(body, &q) != nil { + if decodeJSON(body, &q) != nil { return body } var msgs []json.RawMessage - if json.Unmarshal(q["messages"], &msgs) != nil { + if decodeJSON(q["messages"], &msgs) != nil { return body } changed := false for i, raw := range msgs { var m map[string]json.RawMessage - if json.Unmarshal(raw, &m) != nil || !edit(m) { + if decodeJSON(raw, &m) != nil || !edit(m) { continue } if nb, err := marshalPlain(m); err == nil { @@ -449,7 +449,7 @@ func mistralThinking(body []byte) []byte { delete(m, f) } var role string - json.Unmarshal(m["role"], &role) + decodeJSON(m["role"], &role) if think == "" || role != "assistant" { return true } @@ -460,9 +460,9 @@ func mistralThinking(body []byte) []byte { var list []json.RawMessage var s string switch { - case len(c) > 0 && c[0] == '[' && json.Unmarshal(c, &list) == nil: + case len(c) > 0 && c[0] == '[' && decodeJSON(c, &list) == nil: parts = append(parts, list...) - case json.Unmarshal(c, &s) == nil && s != "": + case decodeJSON(c, &s) == nil && s != "": text, _ := marshalPlain(map[string]string{"type": "text", "text": s}) parts = append(parts, text) } diff --git a/internal/gateway/codex_backend.go b/internal/gateway/codex_backend.go index 29cbd469a..687bf0398 100644 --- a/internal/gateway/codex_backend.go +++ b/internal/gateway/codex_backend.go @@ -372,11 +372,11 @@ 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 json.Unmarshal(body, &request) != nil { + if decodeJSON(body, &request) != nil { return false } var items []json.RawMessage - if json.Unmarshal(request["input"], &items) != nil { + if decodeJSON(request["input"], &items) != nil { return false } for _, raw := range items { @@ -384,7 +384,7 @@ func hasSealedAgentMessage(body []byte) bool { Type string `json:"type"` Content []json.RawMessage `json:"content"` } - if json.Unmarshal(raw, &item) != nil || item.Type != "agent_message" { + if decodeJSON(raw, &item) != nil || item.Type != "agent_message" { continue } for _, content := range item.Content { @@ -392,7 +392,7 @@ func hasSealedAgentMessage(body []byte) bool { Type string `json:"type"` EncryptedContent string `json:"encrypted_content"` } - if json.Unmarshal(content, &part) == nil && part.Type == "encrypted_content" && nativeSealedAgentPayload.MatchString(part.EncryptedContent) { + if decodeJSON(content, &part) == nil && part.Type == "encrypted_content" && nativeSealedAgentPayload.MatchString(part.EncryptedContent) { return true } } diff --git a/internal/gateway/decide.go b/internal/gateway/decide.go index 92d5eac7c..6ecbd88aa 100644 --- a/internal/gateway/decide.go +++ b/internal/gateway/decide.go @@ -193,7 +193,7 @@ func readJev(b []byte, intents []string, levels bool, prev before) (verdict, err Output int `json:"output_tokens"` } `json:"usage"` } - if err := json.Unmarshal(b, &out); err != nil { + if err := decodeJSON(b, &out); err != nil { return verdict{}, answerError{fmt.Errorf("not a System One answer")} } var v verdict @@ -275,7 +275,7 @@ func (s *Server) jevLevelled(ctx context.Context, p provider.Provider, model str Score *float64 `json:"score"` } `json:"answers"` } - if json.Unmarshal(b, &out) != nil || out.Answers["levels"].Noul == nil { + if decodeJSON(b, &out) != nil || out.Answers["levels"].Noul == nil { return levelling{}, answerError{fmt.Errorf("not a System One answer")} } l.levels = *out.Answers["levels"].Noul >= 0.5 @@ -337,7 +337,7 @@ func (s *Server) systemOne(ctx context.Context, p provider.Provider, model strin Output int `json:"output_tokens"` } `json:"usage"` } - _ = json.Unmarshal(b, &use) + _ = decodeJSON(b, &use) var keyID, keyName string if p.Account == nil && p.Key != "" { keyID, keyName = provider.KeyID(p.Key), p.KeyName @@ -411,7 +411,7 @@ func (s *Server) serveSystemOne(w http.ResponseWriter, r *http.Request) { var q struct { Model string `json:"model"` } - if json.Unmarshal(body, &q) != nil { + if decodeJSON(body, &q) != nil { writeError(w, provider.Chat, http.StatusBadRequest, "not a System One request") return } @@ -498,7 +498,7 @@ func (s *Server) serveSystemOne(w http.ResponseWriter, r *http.Request) { Output int `json:"output_tokens"` } `json:"usage"` } - _ = json.Unmarshal(b, &use) + _ = decodeJSON(b, &use) errMsg := "" if status >= 300 { errMsg = provider.APIError(b, fmt.Sprintf("%d %s", status, http.StatusText(status))) @@ -549,7 +549,7 @@ func withEffort(proto provider.Protocol, body []byte, effort string) []byte { OutputConfig map[string]any `json:"output_config"` MaxTokens int `json:"max_tokens"` } - if effort == "" || json.Unmarshal(body, &v) != nil { + if effort == "" || decodeJSON(body, &v) != nil { return body } switch proto { @@ -617,7 +617,7 @@ func requestEffort(proto provider.Protocol, body []byte) string { Effort string `json:"effort"` } `json:"output_config"` } - if json.Unmarshal(body, &v) != nil || v.Thinking == nil || v.Thinking.Type != "enabled" && v.Thinking.Type != "adaptive" { + if decodeJSON(body, &v) != nil || v.Thinking == nil || v.Thinking.Type != "enabled" && v.Thinking.Type != "adaptive" { return "" } if e := effortOf(v.OutputConfig.Effort); e != "" { @@ -676,7 +676,7 @@ func withFixedEffort(proto provider.Protocol, body []byte, effort string) []byte var v struct { Reasoning map[string]any `json:"reasoning"` } - if json.Unmarshal(body, &v) != nil { + if decodeJSON(body, &v) != nil { return body } if v.Reasoning == nil { @@ -691,7 +691,7 @@ func withFixedEffort(proto provider.Protocol, body []byte, effort string) []byte } `json:"thinking"` MaxTokens int `json:"max_tokens"` } - if json.Unmarshal(body, &v) != nil { + if decodeJSON(body, &v) != nil { return body } if effort == "none" { diff --git a/internal/gateway/effort_accounts.go b/internal/gateway/effort_accounts.go index 9ac025342..4d8ccb68a 100644 --- a/internal/gateway/effort_accounts.go +++ b/internal/gateway/effort_accounts.go @@ -167,7 +167,7 @@ func askedTier(body []byte) string { var q struct { Tier string `json:"service_tier"` } - json.Unmarshal(body, &q) + decodeJSON(body, &q) return q.Tier } diff --git a/internal/gateway/fastjson.go b/internal/gateway/fastjson.go new file mode 100644 index 000000000..9eda5f1f0 --- /dev/null +++ b/internal/gateway/fastjson.go @@ -0,0 +1,757 @@ +package gateway + +import ( + "bytes" + "encoding" + "encoding/binary" + "encoding/json" + "errors" + "reflect" + "slices" + "sync" + "unicode" + "unicode/utf16" + "unicode/utf8" +) + +// decodeJSON is json.Unmarshal(data, dst), made for a request body: one +// field of a body of several megabytes is read without decoding the rest. +// encoding/json checks the whole input before decoding any of it, and +// steps through every byte of every string a byte at a time, so each read +// of a field of a long conversation cost as much as decoding all of it, +// and a request was read so a dozen times or more on its way (#1532, +// #1654: 0.1–0.3s of CPU at ~300k tokens). +// +// Here data is checked once (jsonValid, the same grammar as json.Valid), +// split at its members and elements without decoding them, and only the +// values dst has a place for are decoded: strings and booleans here, +// json.RawMessage as their bytes, structs, pointers, slices and maps of +// strings by their parts, and every other value by encoding/json itself. +// dst gets what json.Unmarshal gives it. Whatever this doesn't take on as +// json.Unmarshal would — data that isn't valid JSON, a type that decodes +// itself, an embedded field, a ",string" option, a key given twice, a value +// of the wrong type — goes to json.Unmarshal, dst zeroed first, so its +// 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 { + v := reflect.ValueOf(dst) + if v.Kind() != reflect.Pointer || v.IsNil() || !v.Elem().IsZero() || !jsonValid(data) { + return json.Unmarshal(data, dst) + } + start := skipJSONSpace(data, 0) + if close := misfit(data[start], v.Type().Elem()); close != 0 { + // An array or object where dst can't take one, as a caller trying + // a string first and then a list of parts: encoding/json would + // read all of it to say so. It says the same, at the same offset, + // of the value's opening and its close. + return json.Unmarshal(append(data[:start+1:start+1], close), dst) + } + if err := fillJSON(trimJSON(data), v.Elem()); err != nil { + v.Elem().SetZero() + return json.Unmarshal(data, dst) + } + return nil +} + +// misfit is the closing bracket of the array or object that open starts +// when a value of type t can't hold it, or 0. +func misfit(open byte, t reflect.Type) byte { + for { + if t == rawMessageType || t.Implements(jsonUnmarshalerType) || t.Implements(textUnmarshalerType) || + reflect.PointerTo(t).Implements(jsonUnmarshalerType) || reflect.PointerTo(t).Implements(textUnmarshalerType) { + return 0 + } + if t.Kind() != reflect.Pointer { + break + } + t = t.Elem() + } + switch k := t.Kind(); { + case k == reflect.Interface: + case open == '[' && k != reflect.Slice && k != reflect.Array: + return ']' + case open == '{' && k != reflect.Struct && k != reflect.Map: + return '}' + } + return 0 +} + +// errSlowJSON sends a value to json.Unmarshal (decodeJSON). +var errSlowJSON = errors.New("decoded by encoding/json") + +var ( + rawMessageType = reflect.TypeFor[json.RawMessage]() + jsonUnmarshalerType = reflect.TypeFor[json.Unmarshaler]() + textUnmarshalerType = reflect.TypeFor[encoding.TextUnmarshaler]() + stringType = reflect.TypeFor[string]() + fastFieldsByType sync.Map // reflect.Type → *fastFields + errFastFieldsUnfit = errors.New("struct not decoded field by field") + jsonNull = []byte("null") + jsonTrue, jsonFalse = []byte("true"), []byte("false") +) + +// fastFields are the fields of a struct as encoding/json names them. +type fastFields struct { + names []string + index []int + err error +} + +func jsonFieldsOf(t reflect.Type) *fastFields { + if f, ok := fastFieldsByType.Load(t); ok { + return f.(*fastFields) + } + f := &fastFields{} + for i := range t.NumField() { + sf := t.Field(i) + if sf.Anonymous { + f.err = errFastFieldsUnfit // promoted fields: encoding/json's + break + } + if !sf.IsExported() { + continue + } + tag := sf.Tag.Get("json") + if tag == "-" { + continue + } + name, opts, _ := bytes.Cut([]byte(tag), []byte(",")) + for o := range bytes.SplitSeq(opts, []byte(",")) { + if string(o) == "string" { + f.err = errFastFieldsUnfit + } + } + if !validTagName(string(name)) { + name = []byte(sf.Name) + } + if slices.Contains(f.names, string(name)) { + f.err = errFastFieldsUnfit // encoding/json picks one, or neither + } + f.names = append(f.names, string(name)) + f.index = append(f.index, i) + } + fastFieldsByType.Store(t, f) + return f +} + +// validTagName is encoding/json's isValidTag. +func validTagName(s string) bool { + if s == "" { + return false + } + for _, c := range s { + switch { + case bytes.ContainsRune([]byte("!#$%&()*+-./:;<=>?@[]^_{|}~ "), c): + case !unicode.IsLetter(c) && !unicode.IsDigit(c): + return false + } + } + return true +} + +// field is the field of f that key names, as encoding/json picks it: its +// exact name, or else the first whose name matches without case. +func (f *fastFields) field(key []byte) int { + for i, n := range f.names { + if n == string(key) { + return i + } + } + for i, n := range f.names { + if bytes.EqualFold([]byte(n), key) { + return i + } + } + return -1 +} + +// 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 { + t := v.Type() + if t == rawMessageType { + v.SetBytes(bytes.Clone(raw)) // a copy, as encoding/json makes + return nil + } + if t.Kind() != reflect.Pointer && (t.Implements(jsonUnmarshalerType) || t.Implements(textUnmarshalerType) || + reflect.PointerTo(t).Implements(jsonUnmarshalerType) || reflect.PointerTo(t).Implements(textUnmarshalerType)) { + return json.Unmarshal(raw, v.Addr().Interface()) // it decodes itself + } + null := bytes.Equal(raw, jsonNull) + switch t.Kind() { + case reflect.Pointer: + if null { + v.SetZero() + return nil + } + if t.Implements(jsonUnmarshalerType) || t.Implements(textUnmarshalerType) { + return json.Unmarshal(raw, v.Addr().Interface()) + } + if v.IsNil() { + v.Set(reflect.New(t.Elem())) + } + return fillJSON(raw, v.Elem()) + case reflect.String: + if null { + return nil + } + if raw[0] != '"' { + return errSlowJSON + } + s, ok := unquoteJSON(raw) + if !ok { + return errSlowJSON + } + v.SetString(s) + return nil + case reflect.Bool: + switch { + case null: + case bytes.Equal(raw, jsonTrue): + v.SetBool(true) + case bytes.Equal(raw, jsonFalse): + v.SetBool(false) + default: + return errSlowJSON + } + return nil + case reflect.Struct: + if null { + return nil + } + if raw[0] != '{' { + return errSlowJSON + } + f := jsonFieldsOf(t) + if f.err != nil { + return f.err + } + var seen []bool + var err error + eachMember(raw, func(key, val []byte) bool { + name, ok := unquoteJSON(key) + if !ok { + err = errSlowJSON + return false + } + i := f.field([]byte(name)) + if i < 0 { + return true + } + if seen == nil { + seen = make([]bool, len(f.names)) + } + if seen[i] { + err = errSlowJSON // a key twice: encoding/json merges them + return false + } + seen[i] = true + err = fillJSON(val, v.Field(f.index[i])) + return err == nil + }) + return err + case reflect.Slice: + if t.Elem().Kind() == reflect.Uint8 { + return errSlowJSON // base64, or bytes of a type of their own + } + if null { + v.SetZero() + return nil + } + if raw[0] != '[' { + return errSlowJSON + } + var elems [][]byte + eachElement(raw, func(el []byte) bool { + elems = append(elems, el) + return true + }) + s := reflect.MakeSlice(t, len(elems), len(elems)) + for i, el := range elems { + if err := fillJSON(el, s.Index(i)); err != nil { + return err + } + } + v.Set(s) + return nil + case reflect.Map: + if t.Key() != stringType { + return errSlowJSON + } + if null { + v.SetZero() + return nil + } + if raw[0] != '{' { + return errSlowJSON + } + if v.IsNil() { + v.Set(reflect.MakeMap(t)) + } + var err error + eachMember(raw, func(key, val []byte) bool { + name, ok := unquoteJSON(key) + if !ok { + err = errSlowJSON + return false + } + el := reflect.New(t.Elem()).Elem() + if err = fillJSON(val, el); err != nil { + return false + } + v.SetMapIndex(reflect.ValueOf(name), el) + return true + }) + return err + } + // numbers, interfaces and the rest + return json.Unmarshal(raw, v.Addr().Interface()) +} + +// rawObject is json.Unmarshal(data, &m) for m a map[string]json.RawMessage. +func rawObject(data []byte) (map[string]json.RawMessage, error) { + var m map[string]json.RawMessage + err := decodeJSON(data, &m) + return m, err +} + +// rawArray is json.Unmarshal(data, &a) for a a []json.RawMessage. +func rawArray(data []byte) ([]json.RawMessage, error) { + var a []json.RawMessage + err := decodeJSON(data, &a) + return a, err +} + +func isJSONSpace(c byte) bool { return c == ' ' || c == '\t' || c == '\n' || c == '\r' } + +func skipJSONSpace(data []byte, i int) int { + const spaces = 0x2020202020202020 // a padded body's runs of spaces, 8 at a time + for i+8 <= len(data) && binary.LittleEndian.Uint64(data[i:]) == spaces { + i += 8 + } + for i < len(data) && isJSONSpace(data[i]) { + i++ + } + return i +} + +func trimJSON(data []byte) []byte { + i := skipJSONSpace(data, 0) + j := len(data) + for j-8 >= i && binary.LittleEndian.Uint64(data[j-8:]) == 0x2020202020202020 { + j -= 8 + } + for j > i && isJSONSpace(data[j-1]) { + j-- + } + return data[i:j] +} + +// eachMember calls f with each member of obj, a valid JSON object, its key +// still quoted, until f returns false. +func eachMember(obj []byte, f func(key, val []byte) bool) { + i := skipJSONSpace(obj, 1) + if obj[i] == '}' { + return + } + for { + k := i + i = skipJSONString(obj, i) + key := obj[k:i] + i = skipJSONSpace(obj, i) + i = skipJSONSpace(obj, i+1) // ':' + s := i + i = skipJSONValue(obj, i) + if !f(key, obj[s:i:i]) { + return + } + i = skipJSONSpace(obj, i) + if obj[i] != ',' { + return + } + i = skipJSONSpace(obj, i+1) + } +} + +// eachElement calls f with each element of arr, a valid JSON array, until +// f returns false. +func eachElement(arr []byte, f func(el []byte) bool) { + i := skipJSONSpace(arr, 1) + if arr[i] == ']' { + return + } + for { + s := i + i = skipJSONValue(arr, i) + if !f(arr[s:i:i]) { + return + } + i = skipJSONSpace(arr, i) + if arr[i] != ',' { + return + } + i = skipJSONSpace(arr, i+1) + } +} + +// skipJSONString is the end of the valid JSON string at i. +func skipJSONString(data []byte, i int) int { + i++ + for { + j := bytes.IndexByte(data[i:], '"') + if j < 0 { + return len(data) + } + i += j + n := 0 + for k := i - 1; data[k] == '\\'; k-- { + n++ + } + i++ + if n%2 == 0 { + return i + } + } +} + +// skipJSONValue is the end of the valid JSON value at i. +func skipJSONValue(data []byte, i int) int { + switch data[i] { + case '"': + return skipJSONString(data, i) + case '{', '[': + depth := 0 + for i < len(data) { + switch data[i] { + case '"': + i = skipJSONString(data, i) + continue + case '{', '[': + depth++ + case '}', ']': + depth-- + if depth == 0 { + return i + 1 + } + } + i++ + } + return i + } + for i < len(data) { + switch c := data[i]; { + case c == ',' || c == '}' || c == ']' || isJSONSpace(c): + return i + } + i++ + } + return i +} + +// unquoteJSON is the string a valid JSON string literal holds, as +// encoding/json decodes it (unquoteBytes): invalid UTF-8 and lone +// surrogates become U+FFFD. +func unquoteJSON(q []byte) (string, bool) { + if len(q) < 2 || q[0] != '"' || q[len(q)-1] != '"' { + return "", false + } + s := q[1 : len(q)-1] + r := 0 + for r < len(s) { + c := s[r] + if c == '\\' || c == '"' || c < ' ' { + break + } + if c < utf8.RuneSelf { + r++ + continue + } + rr, size := utf8.DecodeRune(s[r:]) + if rr == utf8.RuneError && size == 1 { + break + } + r += size + } + if r == len(s) { + return string(s), true + } + b := make([]byte, 0, len(s)+2*utf8.UTFMax) + b = append(b, s[:r]...) + for r < len(s) { + switch c := s[r]; { + case c == '\\': + r++ + if r >= len(s) { + return "", false + } + switch s[r] { + default: + return "", false + case '"', '\\', '/', '\'': + b = append(b, s[r]) + r++ + case 'b': + b = append(b, '\b') + r++ + case 'f': + b = append(b, '\f') + r++ + case 'n': + b = append(b, '\n') + r++ + case 'r': + b = append(b, '\r') + r++ + case 't': + b = append(b, '\t') + r++ + case 'u': + r-- + rr := hex4(s[r:]) + if rr < 0 { + return "", false + } + r += 6 + if utf16.IsSurrogate(rr) { + if dec := utf16.DecodeRune(rr, hex4(s[r:])); dec != unicode.ReplacementChar { + r += 6 + b = utf8.AppendRune(b, dec) + break + } + rr = unicode.ReplacementChar + } + b = utf8.AppendRune(b, rr) + } + case c == '"', c < ' ': + return "", false + case c < utf8.RuneSelf: + b = append(b, c) + r++ + default: + rr, size := utf8.DecodeRune(s[r:]) + r += size + b = utf8.AppendRune(b, rr) + } + } + return string(b), true +} + +// hex4 is encoding/json's getu4: the rune of the \uXXXX at s, or -1. +func hex4(s []byte) rune { + if len(s) < 6 || s[0] != '\\' || s[1] != 'u' { + return -1 + } + var r rune + for _, c := range s[2:6] { + switch { + case '0' <= c && c <= '9': + c = c - '0' + case 'a' <= c && c <= 'f': + c = c - 'a' + 10 + case 'A' <= c && c <= 'F': + c = c - 'A' + 10 + default: + return -1 + } + r = r*16 + rune(c) + } + return r +} + +// jsonMaxDepth is encoding/json's maxNestingDepth. +const jsonMaxDepth = 10000 + +// jsonValid is json.Valid, without stepping through each byte by a call: +// the grammar, and the depth past which encoding/json gives up, are its. +func jsonValid(data []byte) bool { + i := skipJSONSpace(data, 0) + i, ok := validJSONValue(data, i, 0) + return ok && skipJSONSpace(data, i) == len(data) +} + +// jsonStringByte marks the bytes that end a run of a string's plain bytes. +var jsonStringByte = func() (t [256]bool) { + for c := range 0x20 { + t[c] = true + } + t['"'], t['\\'] = true, true + return t +}() + +func validJSONValue(data []byte, i, depth int) (int, bool) { + if i >= len(data) { + return i, false + } + switch c := data[i]; { + case c == '"': + return validJSONString(data, i) + case c == '{': + if depth+1 > jsonMaxDepth { + return i, false + } + i = skipJSONSpace(data, i+1) + if i < len(data) && data[i] == '}' { + return i + 1, true + } + for { + if i >= len(data) || data[i] != '"' { + return i, false + } + var ok bool + if i, ok = validJSONString(data, i); !ok { + return i, false + } + i = skipJSONSpace(data, i) + if i >= len(data) || data[i] != ':' { + return i, false + } + i = skipJSONSpace(data, i+1) + if i, ok = validJSONValue(data, i, depth+1); !ok { + return i, false + } + i = skipJSONSpace(data, i) + if i >= len(data) { + return i, false + } + switch data[i] { + case '}': + return i + 1, true + case ',': + i = skipJSONSpace(data, i+1) + default: + return i, false + } + } + case c == '[': + if depth+1 > jsonMaxDepth { + return i, false + } + i = skipJSONSpace(data, i+1) + if i < len(data) && data[i] == ']' { + return i + 1, true + } + for { + var ok bool + if i, ok = validJSONValue(data, i, depth+1); !ok { + return i, false + } + i = skipJSONSpace(data, i) + if i >= len(data) { + return i, false + } + switch data[i] { + case ']': + return i + 1, true + case ',': + i = skipJSONSpace(data, i+1) + default: + return i, false + } + } + case c == 't': + return i + 4, bytes.HasPrefix(data[i:], jsonTrue) + case c == 'f': + return i + 5, bytes.HasPrefix(data[i:], jsonFalse) + case c == 'n': + return i + 4, bytes.HasPrefix(data[i:], jsonNull) + case c == '-' || '0' <= c && c <= '9': + return validJSONNumber(data, i) + } + return i, false +} + +// stopsString says whether any of the 8 bytes of x ends a run of a +// string's plain bytes: a control byte, a quote or a backslash. It may +// say so of a plain byte after one that does, never miss one. +func stopsString(x uint64) bool { + const ones, highs = 0x0101010101010101, 0x8080808080808080 + quote, slash := x^(ones*'"'), x^(ones*'\\') + return ((x-ones*0x20)&^x|(quote-ones)&^quote|(slash-ones)&^slash)&highs != 0 +} + +func validJSONString(data []byte, i int) (int, bool) { + i++ + for i < len(data) { + for i+8 <= len(data) && !stopsString(binary.LittleEndian.Uint64(data[i:])) { + i += 8 + } + if i >= len(data) { + break + } + c := data[i] + if !jsonStringByte[c] { + i++ + continue + } + switch { + case c == '"': + return i + 1, true + case c < 0x20: + return i, false + } + // a backslash + if i+1 >= len(data) { + return i, false + } + switch data[i+1] { + case '"', '\\', '/', 'b', 'f', 'n', 'r', 't': + i += 2 + case 'u': + if i+6 > len(data) { + return i, false + } + for _, h := range data[i+2 : i+6] { + if !('0' <= h && h <= '9' || 'a' <= h && h <= 'f' || 'A' <= h && h <= 'F') { + return i, false + } + } + i += 6 + default: + return i, false + } + } + return i, false +} + +func isDigit(c byte) bool { return '0' <= c && c <= '9' } + +func validJSONNumber(data []byte, i int) (int, bool) { + if data[i] == '-' { + i++ + } + switch { + case i >= len(data): + return i, false + case data[i] == '0': + i++ + case isDigit(data[i]): + for i < len(data) && isDigit(data[i]) { + i++ + } + default: + return i, false + } + if i < len(data) && data[i] == '.' { + i++ + if i >= len(data) || !isDigit(data[i]) { + return i, false + } + for i < len(data) && isDigit(data[i]) { + i++ + } + } + if i < len(data) && (data[i] == 'e' || data[i] == 'E') { + i++ + if i < len(data) && (data[i] == '+' || data[i] == '-') { + i++ + } + if i >= len(data) || !isDigit(data[i]) { + return i, false + } + for i < len(data) && isDigit(data[i]) { + i++ + } + } + return i, true +} diff --git a/internal/gateway/fastjson_test.go b/internal/gateway/fastjson_test.go new file mode 100644 index 000000000..a4ae840dc --- /dev/null +++ b/internal/gateway/fastjson_test.go @@ -0,0 +1,169 @@ +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) }) +} diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index 2afe42766..5ae2a6b7f 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -274,7 +274,7 @@ func ServedBy() Served { Version string `json:"version"` Window bool `json:"window"` } - if json.Unmarshal(b, &info) != nil || info.Name != "magpie" { + if decodeJSON(b, &info) != nil || info.Name != "magpie" { return Served{Running: bytes.Contains(b, []byte(`"magpie"`)), Window: bytes.Contains(b, []byte(`"window":true`))} } return Served{Running: true, Window: info.Window, Version: info.Version} @@ -1238,7 +1238,7 @@ func (s *Server) geminiCount(w http.ResponseWriter, model string, body []byte) { var wrap struct { Inner json.RawMessage `json:"generateContentRequest"` } - if json.Unmarshal(body, &wrap) == nil && len(wrap.Inner) > 0 { + if decodeJSON(body, &wrap) == nil && len(wrap.Inner) > 0 { body = wrap.Inner } req, err := parseGemini(body) @@ -4312,11 +4312,11 @@ func refusedOptional(status int, msg, body []byte) []string { return nil } var m map[string]json.RawMessage - if json.Unmarshal(body, &m) != nil { + if decodeJSON(body, &m) != nil { return nil } var fault any - if json.Unmarshal(msg, &fault) != nil { + if decodeJSON(msg, &fault) != nil { fault = string(msg) } var out []string @@ -4469,7 +4469,7 @@ func refusedInMessages(status int, msg, body []byte) []string { return nil } var fault any - if i := bytes.IndexByte(msg, '{'); i < 0 || json.Unmarshal(msg[i:], &fault) != nil { + if i := bytes.IndexByte(msg, '{'); i < 0 || decodeJSON(msg[i:], &fault) != nil { return nil } var out []string @@ -4849,7 +4849,7 @@ func requiredAllowlist(proto provider.Protocol, body []byte) bool { var q struct { ToolChoice struct{ Type, Mode string } `json:"tool_choice"` } - return json.Unmarshal(body, &q) == nil && q.ToolChoice.Type == "allowed_tools" && q.ToolChoice.Mode == "required" + return decodeJSON(body, &q) == nil && q.ToolChoice.Type == "allowed_tools" && q.ToolChoice.Mode == "required" case provider.Gemini: var q struct { ToolConfig struct { @@ -4859,7 +4859,7 @@ func requiredAllowlist(proto provider.Protocol, body []byte) bool { } `json:"functionCallingConfig"` } `json:"toolConfig"` } - return json.Unmarshal(body, &q) == nil && strings.EqualFold(q.ToolConfig.FunctionCallingConfig.Mode, "ANY") && len(q.ToolConfig.FunctionCallingConfig.AllowedFunctionNames) > 0 + return decodeJSON(body, &q) == nil && strings.EqualFold(q.ToolConfig.FunctionCallingConfig.Mode, "ANY") && len(q.ToolConfig.FunctionCallingConfig.AllowedFunctionNames) > 0 } return false } @@ -5017,7 +5017,7 @@ func streamOf(body []byte) bool { var v struct { Stream bool `json:"stream"` } - json.Unmarshal(body, &v) + decodeJSON(body, &v) return v.Stream } @@ -5028,7 +5028,7 @@ func decodeRequest(body []byte, dst any) error { if len(body) == 0 || body[0] != '{' { return errors.New("invalid request: expected a JSON object") } - if err := json.Unmarshal(body, dst); err != nil { + if err := decodeJSON(body, dst); err != nil { return fmt.Errorf("invalid request: %w", err) } return nil @@ -5091,7 +5091,7 @@ func modelOf(body []byte) string { var v struct { Model string `json:"model"` } - json.Unmarshal(body, &v) + decodeJSON(body, &v) return v.Model } @@ -5217,7 +5217,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. - _ = json.Unmarshal(body, &m) + _ = decodeJSON(body, &m) items := m.Messages geminiContents := len(items) == 0 && len(m.Contents) > 0 if geminiContents { @@ -5225,7 +5225,7 @@ func conversationID(in http.Header, body []byte) string { } if len(items) == 0 && len(m.Input) > 0 && m.Input[0] == '[' { // A malformed input array leaves items empty, and the whole body is hashed. - _ = json.Unmarshal(m.Input, &items) + _ = decodeJSON(m.Input, &items) } first := []byte(m.Input) if len(items) > 0 { @@ -5236,7 +5236,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 json.Unmarshal(it, &r) == nil && (r.Role == "user" || (geminiContents && r.Role == "")) { + if decodeJSON(it, &r) == nil && (r.Role == "user" || (geminiContents && r.Role == "")) { first = it break } @@ -5349,7 +5349,7 @@ func bodyEffort(proto provider.Protocol, body []byte) string { Effort string `json:"effort"` } `json:"output_config"` } - if json.Unmarshal(body, &v) != nil { + if decodeJSON(body, &v) != nil { return "" } switch { @@ -5373,7 +5373,7 @@ func withBodyEffort(proto provider.Protocol, body []byte, effort string) []byte var v struct { OutputConfig map[string]any `json:"output_config"` } - if json.Unmarshal(body, &v) != nil || v.OutputConfig == nil { + if decodeJSON(body, &v) != nil || v.OutputConfig == nil { return body } v.OutputConfig["effort"] = effort @@ -5384,7 +5384,7 @@ func withBodyEffort(proto provider.Protocol, body []byte, effort string) []byte var v struct { Reasoning map[string]any `json:"reasoning"` } - if json.Unmarshal(body, &v) != nil || v.Reasoning == nil { + if decodeJSON(body, &v) != nil || v.Reasoning == nil { return body } v.Reasoning["effort"] = effort @@ -5403,23 +5403,23 @@ func hasReasoningDisabled(body []byte) bool { // accepts when OpenRouter says reasoning is mandatory. func withoutReasoningOff(body []byte) ([]byte, bool) { var fields map[string]json.RawMessage - if json.Unmarshal(body, &fields) != nil { + if decodeJSON(body, &fields) != nil { return nil, false } changed := false var effort string - if json.Unmarshal(fields["reasoning_effort"], &effort) == nil && strings.EqualFold(effort, "none") { + if decodeJSON(fields["reasoning_effort"], &effort) == nil && strings.EqualFold(effort, "none") { delete(fields, "reasoning_effort") changed = true } var reasoning map[string]json.RawMessage - if json.Unmarshal(fields["reasoning"], &reasoning) == nil && reasoning != nil { + if decodeJSON(fields["reasoning"], &reasoning) == nil && reasoning != nil { var enabled bool - if json.Unmarshal(reasoning["enabled"], &enabled) == nil && !enabled { + if decodeJSON(reasoning["enabled"], &enabled) == nil && !enabled { delete(reasoning, "enabled") changed = true } - if json.Unmarshal(reasoning["effort"], &effort) == nil && strings.EqualFold(effort, "none") { + if decodeJSON(reasoning["effort"], &effort) == nil && strings.EqualFold(effort, "none") { delete(reasoning, "effort") changed = true } @@ -5520,7 +5520,7 @@ func withoutLoneToolChoice(body []byte) []byte { var q struct { Tools []json.RawMessage `json:"tools"` } - if json.Unmarshal(body, &q) != nil || len(q.Tools) > 0 { + if decodeJSON(body, &q) != nil || len(q.Tools) > 0 { return body } return withoutFields(body, "tool_choice") diff --git a/internal/gateway/image_input.go b/internal/gateway/image_input.go index 3caf0ba68..991aad182 100644 --- a/internal/gateway/image_input.go +++ b/internal/gateway/image_input.go @@ -68,7 +68,7 @@ func (im imageAt) Current() bool { return im.Last && !im.Tool } // ends the walk. The body is returned as it was when nothing was swapped. func walkImages(proto provider.Protocol, body []byte, swap func(imageAt) (json.RawMessage, error)) ([]byte, error) { var request map[string]json.RawMessage - if json.Unmarshal(body, &request) != nil { + if decodeJSON(body, &request) != nil { return body, nil } turnsKey, contentKey := "messages", "content" @@ -79,26 +79,26 @@ func walkImages(proto provider.Protocol, body []byte, swap func(imageAt) (json.R turnsKey, contentKey = "contents", "parts" } var turns []json.RawMessage - if json.Unmarshal(request[turnsKey], &turns) != nil { + if decodeJSON(request[turnsKey], &turns) != nil { return body, nil } changed := false for i, raw := range turns { var turn map[string]json.RawMessage - if json.Unmarshal(raw, &turn) != nil { + if decodeJSON(raw, &turn) != nil { continue } key := contentKey tool := false var kind string if proto == provider.Responses { - json.Unmarshal(turn["type"], &kind) + decodeJSON(turn["type"], &kind) if kind == "function_call_output" { key, tool = "output", true } } if proto == provider.Chat { - json.Unmarshal(turn["role"], &kind) + decodeJSON(turn["role"], &kind) tool = kind == "tool" } content, swapped, err := swapImageBlocks(proto, turn[key], i == len(turns)-1, tool, swap) @@ -123,17 +123,17 @@ func walkImages(proto provider.Protocol, body []byte, swap func(imageAt) (json.R // Anthropic tool_result's, which are a tool's. func swapImageBlocks(proto provider.Protocol, raw json.RawMessage, last, tool bool, swap func(imageAt) (json.RawMessage, error)) (json.RawMessage, bool, error) { var blocks []json.RawMessage - if json.Unmarshal(raw, &blocks) != nil { + if decodeJSON(raw, &blocks) != nil { return raw, false, nil } swapped := false for i, rawBlock := range blocks { var block map[string]json.RawMessage - if json.Unmarshal(rawBlock, &block) != nil { + if decodeJSON(rawBlock, &block) != nil { continue } var kind string - json.Unmarshal(block["type"], &kind) + decodeJSON(block["type"], &kind) src, isImage := imageSrc(proto, kind, block) if isImage { out, err := swap(imageAt{Src: src, Last: last, Tool: tool}) @@ -149,7 +149,7 @@ func swapImageBlocks(proto provider.Protocol, raw json.RawMessage, last, tool bo // Gemini's function response holds a tool's images in its own parts if proto == provider.Gemini && len(block["functionResponse"]) > 0 { var fr map[string]json.RawMessage - if json.Unmarshal(block["functionResponse"], &fr) == nil && len(fr["parts"]) > 0 { + if decodeJSON(block["functionResponse"], &fr) == nil && len(fr["parts"]) > 0 { content, nested, err := swapImageBlocks(proto, fr["parts"], last, true, swap) if err != nil { return raw, false, err @@ -190,11 +190,11 @@ func imageSrc(proto provider.Protocol, kind string, block map[string]json.RawMes return "", false } var url string - if json.Unmarshal(block["image_url"], &url) != nil { + if decodeJSON(block["image_url"], &url) != nil { var obj struct { URL string `json:"url"` } - json.Unmarshal(block["image_url"], &obj) + decodeJSON(block["image_url"], &obj) url = obj.URL } return url, true @@ -203,7 +203,7 @@ func imageSrc(proto provider.Protocol, kind string, block map[string]json.RawMes return "", false } var url string - json.Unmarshal(block["image_url"], &url) + decodeJSON(block["image_url"], &url) return url, true case provider.Anthropic: if kind != "image" { @@ -215,7 +215,7 @@ func imageSrc(proto provider.Protocol, kind string, block map[string]json.RawMes Data string `json:"data"` URL string `json:"url"` } - json.Unmarshal(block["source"], &src) + decodeJSON(block["source"], &src) switch { case src.Type == "base64" && src.Data != "": return "data:" + src.MediaType + ";base64," + src.Data, true @@ -228,7 +228,7 @@ func imageSrc(proto provider.Protocol, kind string, block map[string]json.RawMes MimeType string `json:"mimeType"` Data string `json:"data"` } - json.Unmarshal(block["inlineData"], &data) + decodeJSON(block["inlineData"], &data) if strings.HasPrefix(data.MimeType, "image/") { return "data:" + data.MimeType + ";base64," + data.Data, true } @@ -236,7 +236,7 @@ func imageSrc(proto provider.Protocol, kind string, block map[string]json.RawMes var file struct { MimeType string `json:"mimeType"` } - if json.Unmarshal(block["fileData"], &file) != nil || file.MimeType == "" || strings.HasPrefix(file.MimeType, "image/") { + if decodeJSON(block["fileData"], &file) != nil || file.MimeType == "" || strings.HasPrefix(file.MimeType, "image/") { return "", true // unknown file types may be images; fail closed } } diff --git a/internal/gateway/ir.go b/internal/gateway/ir.go index eaa83b123..e914a7b7f 100644 --- a/internal/gateway/ir.go +++ b/internal/gateway/ir.go @@ -564,7 +564,7 @@ func stringOrText(raw json.RawMessage) string { return "" } var s string - if json.Unmarshal(raw, &s) == nil { + if decodeJSON(raw, &s) == nil { return s } var blocks []struct { @@ -572,7 +572,7 @@ func stringOrText(raw json.RawMessage) string { Text string `json:"text"` ToolName string `json:"tool_name"` } - if json.Unmarshal(raw, &blocks) == nil { + if decodeJSON(raw, &blocks) == nil { var b strings.Builder for _, x := range blocks { switch x.Type { @@ -609,7 +609,7 @@ func toolOutput(raw json.RawMessage) (string, []Part) { } `json:"source"` ImageURL json.RawMessage `json:"image_url"` } - if len(raw) == 0 || raw[0] != '[' || json.Unmarshal(raw, &blocks) != nil { + if len(raw) == 0 || raw[0] != '[' || decodeJSON(raw, &blocks) != nil { return text, nil } var images []Part @@ -623,11 +623,11 @@ func toolOutput(raw json.RawMessage) (string, []Part) { } case "input_image", "image_url": var u string - if json.Unmarshal(b.ImageURL, &u) != nil { + if decodeJSON(b.ImageURL, &u) != nil { var o struct { URL string `json:"url"` } - json.Unmarshal(b.ImageURL, &o) + decodeJSON(b.ImageURL, &o) u = o.URL } if u != "" { diff --git a/internal/gateway/large_body_bench_test.go b/internal/gateway/large_body_bench_test.go new file mode 100644 index 000000000..14ce35022 --- /dev/null +++ b/internal/gateway/large_body_bench_test.go @@ -0,0 +1,121 @@ +package gateway + +import ( + "bytes" + "encoding/json" + "fmt" + "net/http/httptest" + "strings" + "testing" + + "github.com/yetone/magpie/internal/provider" +) + +// largeConversation is a long agent conversation as its client sends it: +// a system prompt, tools with schemas, and turns of text, tool calls and +// tool results, about words of text in all (~4 bytes a token). +func largeConversation(proto provider.Protocol, model string, words int) []byte { + para := strings.Repeat("The function reads the file, splits it on newlines and returns the lines that match. ", 12) + type schema = map[string]any + var tools []schema + for i := range 30 { + props := schema{"path": schema{"type": "string", "description": "Absolute path to the file " + fmt.Sprint(i)}, "limit": schema{"type": "integer"}} + switch proto { + case provider.Anthropic: + tools = append(tools, schema{"name": fmt.Sprintf("Tool%d", i), "description": para[:400], "input_schema": schema{"type": "object", "properties": props, "required": []string{"path"}}}) + case provider.Chat: + tools = append(tools, schema{"type": "function", "function": schema{"name": fmt.Sprintf("Tool%d", i), "description": para[:400], "parameters": schema{"type": "object", "properties": props, "required": []string{"path"}}}}) + default: + tools = append(tools, schema{"type": "function", "name": fmt.Sprintf("Tool%d", i), "description": para[:400], "parameters": schema{"type": "object", "properties": props, "required": []string{"path"}}}) + } + } + var msgs []any + n := 0 + for turn := 0; n < words*6; turn++ { + id := fmt.Sprintf("call_%04d", turn) + args := fmt.Sprintf(`{"path":"/src/pkg/file%d.go","limit":200}`, turn) + result := para + strings.Repeat("line of code with \"quotes\" and unicode é 漢字\n", 20) + n += len(para)*2 + len(result) + switch proto { + case provider.Anthropic: + msgs = append(msgs, + schema{"role": "user", "content": []any{schema{"type": "text", "text": para}}}, + schema{"role": "assistant", "content": []any{schema{"type": "text", "text": para}, schema{"type": "tool_use", "id": id, "name": "Tool1", "input": json.RawMessage(args)}}}, + schema{"role": "user", "content": []any{schema{"type": "tool_result", "tool_use_id": id, "content": result}}}) + case provider.Chat: + msgs = append(msgs, + schema{"role": "user", "content": para}, + schema{"role": "assistant", "content": para, "tool_calls": []any{schema{"id": id, "type": "function", "function": schema{"name": "Tool1", "arguments": args}}}}, + schema{"role": "tool", "tool_call_id": id, "content": result}) + default: + msgs = append(msgs, + schema{"type": "message", "role": "user", "content": []any{schema{"type": "input_text", "text": para}}}, + schema{"type": "message", "role": "assistant", "content": []any{schema{"type": "output_text", "text": para}}}, + schema{"type": "function_call", "call_id": id, "name": "Tool1", "arguments": args}, + schema{"type": "function_call_output", "call_id": id, "output": result}) + } + } + body := schema{"model": model, "max_tokens": 32000, "stream": false, "tools": tools} + switch proto { + case provider.Anthropic: + msgs[len(msgs)-1] = schema{"role": "user", "content": []any{schema{"type": "text", "text": "go on"}}} + body["system"] = []any{schema{"type": "text", "text": para + para, "cache_control": schema{"type": "ephemeral"}}} + body["messages"] = msgs + case provider.Chat: + msgs[len(msgs)-1] = schema{"role": "user", "content": "go on"} + body["messages"] = append([]any{schema{"role": "system", "content": para + para}}, msgs...) + default: + delete(body, "max_tokens") + body["instructions"] = para + para + body["input"] = msgs + } + b, _ := json.Marshal(body) + return b +} + +func BenchmarkLargeRequest(b *testing.B) { + for _, tc := range []struct { + name, path, model string + proto provider.Protocol + reply string + }{ + {"anthropic", "/v1/messages", "fake/m1", provider.Anthropic, `{"id":"msg_1","type":"message","role":"assistant","model":"m1","content":[{"type":"text","text":"ok"}],"stop_reason":"end_turn","usage":{"input_tokens":7,"output_tokens":1}}`}, + {"anthropic-group", "/v1/messages", "group/g", provider.Anthropic, `{"id":"msg_1","type":"message","role":"assistant","model":"m1","content":[{"type":"text","text":"ok"}],"stop_reason":"end_turn","usage":{"input_tokens":7,"output_tokens":1}}`}, + {"chat", "/v1/chat/completions", "fake/m1", provider.Chat, `{"id":"c1","object":"chat.completion","choices":[{"index":0,"message":{"role":"assistant","content":"ok"},"finish_reason":"stop"}],"usage":{"prompt_tokens":7,"completion_tokens":1}}`}, + {"responses", "/v1/responses", "fake/m1", provider.Responses, `{"id":"r1","object":"response","status":"completed","output":[{"type":"message","role":"assistant","content":[{"type":"output_text","text":"ok"}]}],"usage":{"input_tokens":7,"output_tokens":1}}`}, + } { + b.Run(tc.name, func(b *testing.B) { + b.Setenv("XDG_CONFIG_HOME", b.TempDir()) + b.Setenv("XDG_CACHE_HOME", b.TempDir()) + f := &fake{ctype: "application/json", reply: tc.reply} + up := httptest.NewServer(f) + defer up.Close() + p := provider.Provider{ID: "fake", Name: "Fake", Key: "k", Models: []string{"m1"}} + switch tc.proto { + case provider.Chat: + p.Chat = up.URL + "/v1" + case provider.Responses: + p.Responses = up.URL + "/v1" + case provider.Anthropic: + p.Anthropic = up.URL + } + if err := provider.Save(p); err != nil { + b.Fatal(err) + } + if err := provider.SaveGroup(provider.Group{ID: "g", Name: "G", Members: []string{"fake/m1"}, Routing: provider.Ordered}); err != nil { + b.Fatal(err) + } + body := largeConversation(tc.proto, tc.model, 300_000) + s := New() + b.SetBytes(int64(len(body))) + b.ResetTimer() + for range b.N { + rec := httptest.NewRecorder() + s.Handler().ServeHTTP(rec, httptest.NewRequest("POST", tc.path, bytes.NewReader(body))) + if rec.Code != 200 || f.calls == 0 { + b.Fatalf("%d %s", rec.Code, rec.Body.String()) + } + } + }) + } +} diff --git a/internal/gateway/prompt.go b/internal/gateway/prompt.go index 05a4831a7..f18fa0936 100644 --- a/internal/gateway/prompt.go +++ b/internal/gateway/prompt.go @@ -476,10 +476,10 @@ func filesOfCommand(cmd string) []string { func callOf(name string, input []byte) toolCall { c := toolCall{name: name} var args map[string]json.RawMessage - _ = json.Unmarshal(input, &args) + _ = decodeJSON(input, &args) str := func(k string) string { var s string - if json.Unmarshal(args[k], &s) == nil { + if decodeJSON(args[k], &s) == nil { return s } return "" @@ -498,7 +498,7 @@ func callOf(name string, input []byte) toolCall { } if cmd == "" { var argv []string - if json.Unmarshal(args["command"], &argv) == nil { + if decodeJSON(args["command"], &argv) == nil { cmd = strings.Join(argv, " ") } } @@ -578,11 +578,11 @@ type rawBlock struct { // blocksOf reads content that is a string or a list of blocks. func blocksOf(c json.RawMessage) []rawBlock { var s string - if json.Unmarshal(c, &s) == nil { + if decodeJSON(c, &s) == nil { return []rawBlock{{Type: "text", Text: s}} } var bs []rawBlock - _ = json.Unmarshal(c, &bs) + _ = decodeJSON(c, &bs) return bs } @@ -595,7 +595,7 @@ func (b *promptBuilder) anthropic(body []byte) bool { } `json:"messages"` Tools []json.RawMessage `json:"tools"` } - if json.Unmarshal(body, &req) != nil { + if decodeJSON(body, &req) != nil { return false } for _, s := range blocksOf(req.System) { @@ -609,7 +609,7 @@ func (b *promptBuilder) anthropic(body []byte) bool { var d struct { Name string `json:"name"` } - _ = json.Unmarshal(t, &d) + _ = decodeJSON(t, &d) b.tool(d.Name, rawTokens(t), t) } for _, m := range req.Messages { @@ -695,25 +695,25 @@ func (b *promptBuilder) responses(body []byte) bool { Tools []json.RawMessage `json:"tools"` Previous string `json:"previous_response_id"` } - if json.Unmarshal(body, &req) != nil { + if decodeJSON(body, &req) != nil { return false } b.held = req.Previous != "" var ins string - if json.Unmarshal(req.Instructions, &ins) == nil && ins != "" { + if decodeJSON(req.Instructions, &ins) == nil && ins != "" { b.systemText(ins, "prompt") } for _, t := range req.Tools { b.responsesTool(t) } var s string - if json.Unmarshal(req.Input, &s) == nil { + if decodeJSON(req.Input, &s) == nil { b.newTurn() b.userText(s) return true } var items []json.RawMessage - _ = json.Unmarshal(req.Input, &items) + _ = decodeJSON(req.Input, &items) for _, it := range items { b.responsesItem(it) } @@ -729,7 +729,7 @@ func (b *promptBuilder) responsesTool(t json.RawMessage) { Name string `json:"name"` } `json:"function"` } - _ = json.Unmarshal(t, &d) + _ = decodeJSON(t, &d) name := d.Name if name == "" && d.Function != nil { name = d.Function.Name @@ -778,7 +778,7 @@ func (b *promptBuilder) responsesItem(raw json.RawMessage) { Encrypted string `json:"encrypted_content"` Action json.RawMessage `json:"action"` } - if json.Unmarshal(raw, &it) != nil { + if decodeJSON(raw, &it) != nil { return } if it.Type == "" && it.Role != "" { @@ -840,7 +840,7 @@ func (b *promptBuilder) responsesItem(raw json.RawMessage) { case "function_call_output", "custom_tool_call_output", "local_shell_call_output", "tool_search_output": n := 0 var s string - if json.Unmarshal(it.Output, &s) == nil { + if decodeJSON(it.Output, &s) == nil { n = tokensOf(s) } else { var texts []string @@ -874,14 +874,14 @@ type rPart struct { func responsesContent(c json.RawMessage) []rPart { var s string - if json.Unmarshal(c, &s) == nil { + if decodeJSON(c, &s) == nil { return []rPart{{text: s}} } var ps []struct { Type string `json:"type"` Text string `json:"text"` } - _ = json.Unmarshal(c, &ps) + _ = decodeJSON(c, &ps) out := make([]rPart, 0, len(ps)) for _, p := range ps { out = append(out, rPart{text: p.Text, image: p.Type == "input_image" || p.Type == "input_file" || p.Type == "image_url"}) @@ -908,7 +908,7 @@ func (b *promptBuilder) chatCompletions(body []byte) bool { } `json:"messages"` Tools []json.RawMessage `json:"tools"` } - if json.Unmarshal(body, &req) != nil { + if decodeJSON(body, &req) != nil { return false } for _, t := range req.Tools { @@ -994,7 +994,7 @@ func (b *promptBuilder) gemini(body []byte) bool { Decls []json.RawMessage `json:"functionDeclarations"` } `json:"tools"` } - if json.Unmarshal(body, &req) != nil { + if decodeJSON(body, &req) != nil { return false } if req.System != nil { @@ -1007,7 +1007,7 @@ func (b *promptBuilder) gemini(body []byte) bool { var n struct { Name string `json:"name"` } - _ = json.Unmarshal(d, &n) + _ = decodeJSON(d, &n) b.tool(n.Name, rawTokens(d), d) } } diff --git a/internal/gateway/responses.go b/internal/gateway/responses.go index eac6187ea..565f08b87 100644 --- a/internal/gateway/responses.go +++ b/internal/gateway/responses.go @@ -47,7 +47,7 @@ type rArgs string func (a *rArgs) UnmarshalJSON(b []byte) error { var s string - if json.Unmarshal(b, &s) == nil { + if decodeJSON(b, &s) == nil { *a = rArgs(s) } else if string(b) != "null" { *a = rArgs(b) @@ -114,11 +114,11 @@ func customInput(args string) string { var a struct { Input *string `json:"input"` } - if json.Unmarshal([]byte(args), &a) == nil && a.Input != nil { + if decodeJSON([]byte(args), &a) == nil && a.Input != nil { return *a.Input } var str string - if json.Unmarshal([]byte(args), &str) == nil { + if decodeJSON([]byte(args), &str) == nil { return str } return args @@ -166,7 +166,7 @@ func unsealed(schema json.RawMessage) json.RawMessage { return schema } var v any - if json.Unmarshal(schema, &v) != nil { + if decodeJSON(schema, &v) != nil { return schema } var strip func(any) @@ -224,7 +224,7 @@ type rRequest struct { // in each upstream's own words. A format of plain text stays where it was. func textFormat(text json.RawMessage) (json.RawMessage, *Format) { var fields map[string]json.RawMessage - if json.Unmarshal(text, &fields) != nil { + if decodeJSON(text, &fields) != nil { return text, nil } f := openAIFormat(fields["format"]) @@ -251,7 +251,7 @@ func parseResponses(body []byte) (*Request, error) { // Responses Lite's tools, sent as the first input item (#350) body = liftAdditionalTools(body) var q rRequest - if err := json.Unmarshal(body, &q); err != nil { + if err := decodeJSON(body, &q); err != nil { return nil, fmt.Errorf("invalid request: %v", err) } r := &Request{Model: q.Model, System: q.Instructions, MaxTokens: q.MaxOutputTokens, Temp: q.Temperature, @@ -265,11 +265,11 @@ func parseResponses(body []byte) (*Request, error) { } var found []rTool // what Codex's tool searches found var s string - if json.Unmarshal(q.Input, &s) == nil { + if decodeJSON(q.Input, &s) == nil { r.Messages = append(r.Messages, Message{Role: "user", Parts: []Part{{Kind: Text, Text: s}}}) } else { var items []rItem - if err := json.Unmarshal(q.Input, &items); err != nil { + if err := decodeJSON(q.Input, &items); err != nil { return nil, fmt.Errorf("invalid input: %v", err) } // replied: the conversation has had a turn answered. Codex adds a @@ -341,9 +341,9 @@ func parseResponses(body []byte) (*Request, error) { // collect a streamed response for a non-streaming client. // Retain the original notification, including absent IDs. if rawItems == nil { - _ = json.Unmarshal(q.Input, &rawItems) + _ = decodeJSON(q.Input, &rawItems) } - _ = json.Unmarshal(rawItems[i], &part.Standalone) + _ = decodeJSON(rawItems[i], &part.Standalone) } r.Messages = append(r.Messages, Message{Role: "user", Parts: []Part{part}}) case it.Type == "reasoning": @@ -351,7 +351,7 @@ func parseResponses(body []byte) (*Request, error) { // summary (all magpie gives a client of a translated reply) var b strings.Builder var content []rText - _ = json.Unmarshal(it.Content, &content) + _ = decodeJSON(it.Content, &content) for _, c := range content { if c.Type == "reasoning_text" { b.WriteString(c.Text) @@ -367,7 +367,7 @@ func parseResponses(body []byte) (*Request, error) { // sealed: the item goes back to a Responses API as it // came, id, summary and all (#1445) if rawItems == nil { - _ = json.Unmarshal(q.Input, &rawItems) + _ = decodeJSON(q.Input, &rawItems) } if i < len(rawItems) { part.Sealed, part.SealedBy = rawItems[i], sealResponses @@ -424,7 +424,7 @@ func parseResponses(body []byte) (*Request, error) { } } var tc string - if json.Unmarshal(q.ToolChoice, &tc) == nil { + if decodeJSON(q.ToolChoice, &tc) == nil { r.ToolChoice = tc } else { var o struct { @@ -437,7 +437,7 @@ func parseResponses(body []byte) (*Request, error) { Namespace string `json:"namespace"` } `json:"tools"` } - if json.Unmarshal(q.ToolChoice, &o) == nil { + if decodeJSON(q.ToolChoice, &o) == nil { switch o.Type { case "allowed_tools": if o.Mode != "auto" && o.Mode != "required" { @@ -486,11 +486,11 @@ func parseResponses(body []byte) (*Request, error) { // 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 json.Unmarshal(body, &q) != nil { + if decodeJSON(body, &q) != nil { return body } var input []json.RawMessage - if json.Unmarshal(q["input"], &input) != nil { + if decodeJSON(q["input"], &input) != nil { return body } changed := false @@ -507,7 +507,7 @@ func orphanedToolOutputs(body []byte) []byte { CallID string `json:"call_id"` Output json.RawMessage `json:"output"` } - if json.Unmarshal(raw, &item) != nil { + if decodeJSON(raw, &item) != nil { flush() inCalls = false out = append(out, raw) @@ -580,11 +580,11 @@ func pairToolItems(body []byte) []byte { return body } var q map[string]json.RawMessage - if json.Unmarshal(body, &q) != nil { + if decodeJSON(body, &q) != nil { return body } var input []json.RawMessage - if json.Unmarshal(q["input"], &input) != nil { + if decodeJSON(q["input"], &input) != nil { return body } type item struct { @@ -594,7 +594,7 @@ func pairToolItems(body []byte) []byte { items := make([]item, len(input)) answered := map[string]bool{} for i, raw := range input { - if json.Unmarshal(raw, &items[i]) != nil { + if decodeJSON(raw, &items[i]) != nil { items[i] = item{} } if t := items[i].Type; (t == "function_call_output" || t == "custom_tool_call_output") && items[i].CallID != "" { @@ -656,7 +656,7 @@ func mergeTurns(msgs []Message) []Message { func responsesParts(raw json.RawMessage) []Part { var s string - if json.Unmarshal(raw, &s) == nil { + if decodeJSON(raw, &s) == nil { if s == "" { return nil } @@ -667,7 +667,7 @@ func responsesParts(raw json.RawMessage) []Part { Text string `json:"text"` ImageURL string `json:"image_url"` } - json.Unmarshal(raw, &items) + decodeJSON(raw, &items) var out []Part for _, it := range items { switch it.Type { @@ -708,11 +708,11 @@ func withReasoningText(body []byte) []byte { return body } var q map[string]json.RawMessage - if json.Unmarshal(body, &q) != nil { + if decodeJSON(body, &q) != nil { return body } var items []json.RawMessage - if json.Unmarshal(q["input"], &items) != nil { + if decodeJSON(q["input"], &items) != nil { return body } changed := false @@ -727,7 +727,7 @@ func withReasoningText(body []byte) []byte { Summary []rText `json:"summary"` Content []rText `json:"content"` } - if json.Unmarshal(raw, &it) != nil { + if decodeJSON(raw, &it) != nil { out = append(out, raw) continue } @@ -757,7 +757,7 @@ func withReasoningText(body []byte) []byte { b.WriteString(noReasoning) } var m map[string]json.RawMessage - if json.Unmarshal(raw, &m) != nil { + if decodeJSON(raw, &m) != nil { out = append(out, raw) continue } @@ -790,7 +790,7 @@ func sealedReasoning(p Part) bool { Enc string `json:"encrypted_content"` Content []json.RawMessage `json:"content"` } - return json.Unmarshal(p.Sealed, &it) == nil && it.Enc != "" && len(it.Content) == 0 + return decodeJSON(p.Sealed, &it) == nil && it.Enc != "" && len(it.Content) == 0 } // buildResponses renders a request for a Responses upstream. @@ -893,7 +893,7 @@ func buildResponses(r *Request, model, host string, rejectTemp bool) []byte { } if len(r.Text) > 0 || r.Format != nil { text := map[string]any{} - json.Unmarshal(r.Text, &text) + decodeJSON(r.Text, &text) if r.Format != nil { text["format"] = r.Format.responses() } @@ -1082,7 +1082,7 @@ func (d *responsesDecoder) decode(data string, emit func(Event)) error { } `json:"error"` Message string `json:"message"` } - if err := json.Unmarshal([]byte(data), &ev); err != nil { + if err := decodeJSON([]byte(data), &ev); err != nil { return nil } switch ev.Type { @@ -1130,7 +1130,7 @@ func (d *responsesDecoder) decode(data string, emit func(Event)) error { var whole struct { Item json.RawMessage `json:"item"` } - if json.Unmarshal([]byte(data), &whole) == nil && len(whole.Item) > 0 { + if decodeJSON([]byte(data), &whole) == nil && len(whole.Item) > 0 { emit(Event{Kind: KSealed, Name: sealResponses, ID: ev.Item.ID, Text: string(whole.Item)}) } } diff --git a/internal/gateway/testdata/upstream_bodies/anthropic-group.json b/internal/gateway/testdata/upstream_bodies/anthropic-group.json new file mode 100644 index 000000000..3aacd485b --- /dev/null +++ b/internal/gateway/testdata/upstream_bodies/anthropic-group.json @@ -0,0 +1,7 @@ +{ "max_tokens" : 1024,"model":"m1", "metadata":{"user_id":"u_1"}, + "system":[{"type":"text","text":"You are é \/ \"careful\"\n\ttabs","cache_control":{"type":"ephemeral"}}], + "tools":[{"name":"Read","description":"Reads a file","input_schema":{"type":"object","properties":{"path":{"type":"string"}},"required":["path"]}}], + "messages":[{"role":"user","content":"read it"}, + {"role":"assistant","content":[{"type":"thinking","thinking":"hmm","signature":"c2ln"},{"type":"text","text":"ok 漢字 😀"},{"type":"tool_use","id":"toolu_1","name":"Read","input":{"path":"/a b/c.go","n":1.50e2}}]}, + {"role":"user","content":[{"type":"tool_result","tool_use_id":"toolu_1","content":[{"type":"text","text":"line\u0001one\r\nline two"}]},{"type":"text","text":"go on"}]}], + "temperature":0.70, "stream":false, "unknown_field":{"kept":[1,2,{"x":null}]},"thinking":{"type":"disabled"}} \ No newline at end of file diff --git a/internal/gateway/testdata/upstream_bodies/anthropic-image.json b/internal/gateway/testdata/upstream_bodies/anthropic-image.json new file mode 100644 index 000000000..9ad8834db --- /dev/null +++ b/internal/gateway/testdata/upstream_bodies/anthropic-image.json @@ -0,0 +1 @@ +{"model":"m1","max_tokens":64,"messages":[{"role":"user","content":[{"type":"text","text":"what is this"},{"type":"image","source":{"type":"base64","media_type":"image/png","data":"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg=="}}]}],"thinking":{"type":"disabled"}} \ No newline at end of file diff --git a/internal/gateway/testdata/upstream_bodies/anthropic-thinking.json b/internal/gateway/testdata/upstream_bodies/anthropic-thinking.json new file mode 100644 index 000000000..55ab7897e --- /dev/null +++ b/internal/gateway/testdata/upstream_bodies/anthropic-thinking.json @@ -0,0 +1 @@ +{"model":"m1","max_tokens":2048,"thinking":{"type":"enabled","budget_tokens":1024},"messages":[{"role":"user","content":"think"}],"model":"fake/m1"} \ No newline at end of file diff --git a/internal/gateway/testdata/upstream_bodies/anthropic-to-chat.json b/internal/gateway/testdata/upstream_bodies/anthropic-to-chat.json new file mode 100644 index 000000000..f7cbdb383 --- /dev/null +++ b/internal/gateway/testdata/upstream_bodies/anthropic-to-chat.json @@ -0,0 +1 @@ +{"max_tokens":1024,"messages":[{"content":"You are é / \"careful\"\n\ttabs","role":"system"},{"content":"read it","role":"user"},{"content":"ok 漢字 😀","role":"assistant","tool_calls":[{"function":{"arguments":"{\"path\":\"/a b/c.go\",\"n\":1.50e2}","name":"Read"},"id":"toolu_1","type":"function"}]},{"content":"line\u0001one\r\nline two","role":"tool","tool_call_id":"toolu_1"},{"content":"go on","role":"user"}],"model":"m1","stream":true,"stream_options":{"include_usage":true},"temperature":0.7,"tools":[{"function":{"description":"Reads a file","name":"Read","parameters":{"type":"object","properties":{"path":{"type":"string"}},"required":["path"]}},"type":"function"}]} \ No newline at end of file diff --git a/internal/gateway/testdata/upstream_bodies/anthropic-to-responses.json b/internal/gateway/testdata/upstream_bodies/anthropic-to-responses.json new file mode 100644 index 000000000..5f90c1638 --- /dev/null +++ b/internal/gateway/testdata/upstream_bodies/anthropic-to-responses.json @@ -0,0 +1 @@ +{"input":[{"content":[{"text":"what is this","type":"input_text"},{"image_url":"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==","type":"input_image"}],"role":"user","type":"message"}],"max_output_tokens":64,"model":"m1","store":false,"stream":true} \ No newline at end of file diff --git a/internal/gateway/testdata/upstream_bodies/anthropic.json b/internal/gateway/testdata/upstream_bodies/anthropic.json new file mode 100644 index 000000000..3aacd485b --- /dev/null +++ b/internal/gateway/testdata/upstream_bodies/anthropic.json @@ -0,0 +1,7 @@ +{ "max_tokens" : 1024,"model":"m1", "metadata":{"user_id":"u_1"}, + "system":[{"type":"text","text":"You are é \/ \"careful\"\n\ttabs","cache_control":{"type":"ephemeral"}}], + "tools":[{"name":"Read","description":"Reads a file","input_schema":{"type":"object","properties":{"path":{"type":"string"}},"required":["path"]}}], + "messages":[{"role":"user","content":"read it"}, + {"role":"assistant","content":[{"type":"thinking","thinking":"hmm","signature":"c2ln"},{"type":"text","text":"ok 漢字 😀"},{"type":"tool_use","id":"toolu_1","name":"Read","input":{"path":"/a b/c.go","n":1.50e2}}]}, + {"role":"user","content":[{"type":"tool_result","tool_use_id":"toolu_1","content":[{"type":"text","text":"line\u0001one\r\nline two"}]},{"type":"text","text":"go on"}]}], + "temperature":0.70, "stream":false, "unknown_field":{"kept":[1,2,{"x":null}]},"thinking":{"type":"disabled"}} \ No newline at end of file diff --git a/internal/gateway/testdata/upstream_bodies/chat-group.json b/internal/gateway/testdata/upstream_bodies/chat-group.json new file mode 100644 index 000000000..c401e5eb4 --- /dev/null +++ b/internal/gateway/testdata/upstream_bodies/chat-group.json @@ -0,0 +1,5 @@ +{"model":"m1","messages":[{"role":"system","content":"be brief"},{"role":"user","content":[{"type":"text","text":"look"},{"type":"image_url","image_url":{"url":"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg=="}}]}, + {"role":"assistant","content":null,"tool_calls":[{"id":"call_1","type":"function","function":{"name":"Read","arguments":"{\"path\":\"/x\"}"}}]}, + {"role":"tool","tool_call_id":"call_1","content":"file \"body\"\n"},{"role":"user","content":"go on é"}], + "tools":[{"type":"function","function":{"name":"Read","description":"Reads","parameters":{"type":"object","properties":{"path":{"type":"string"}}}}}], + "tool_choice":"auto","reasoning_effort":"high","temperature":1,"stop":["\n\n"],"stream":false,"user":"u"} \ No newline at end of file diff --git a/internal/gateway/testdata/upstream_bodies/chat-to-anthropic.json b/internal/gateway/testdata/upstream_bodies/chat-to-anthropic.json new file mode 100644 index 000000000..d24458d77 --- /dev/null +++ b/internal/gateway/testdata/upstream_bodies/chat-to-anthropic.json @@ -0,0 +1 @@ +{"max_tokens":28096,"messages":[{"role":"user","content":[{"type":"text","text":"look"},{"type":"image","source":{"type":"base64","media_type":"image/png","data":"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg=="}}]},{"role":"assistant","content":[{"type":"tool_use","id":"call_1","name":"Read","input":{"path":"/x"}}]},{"role":"user","content":[{"type":"tool_result","tool_use_id":"call_1","content":"file \"body\"\n"},{"type":"text","text":"go on é","cache_control":{"type":"ephemeral"}}]}],"model":"m1","stop_sequences":["\n\n"],"stream":true,"system":[{"type":"text","text":"be brief","cache_control":{"type":"ephemeral"}}],"thinking":{"budget_tokens":24000,"type":"enabled"},"tools":[{"description":"Reads","input_schema":{"type":"object","properties":{"path":{"type":"string"}}},"name":"Read"}]} \ No newline at end of file diff --git a/internal/gateway/testdata/upstream_bodies/chat.json b/internal/gateway/testdata/upstream_bodies/chat.json new file mode 100644 index 000000000..c401e5eb4 --- /dev/null +++ b/internal/gateway/testdata/upstream_bodies/chat.json @@ -0,0 +1,5 @@ +{"model":"m1","messages":[{"role":"system","content":"be brief"},{"role":"user","content":[{"type":"text","text":"look"},{"type":"image_url","image_url":{"url":"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg=="}}]}, + {"role":"assistant","content":null,"tool_calls":[{"id":"call_1","type":"function","function":{"name":"Read","arguments":"{\"path\":\"/x\"}"}}]}, + {"role":"tool","tool_call_id":"call_1","content":"file \"body\"\n"},{"role":"user","content":"go on é"}], + "tools":[{"type":"function","function":{"name":"Read","description":"Reads","parameters":{"type":"object","properties":{"path":{"type":"string"}}}}}], + "tool_choice":"auto","reasoning_effort":"high","temperature":1,"stop":["\n\n"],"stream":false,"user":"u"} \ No newline at end of file diff --git a/internal/gateway/testdata/upstream_bodies/large-anthropic-group.sha256 b/internal/gateway/testdata/upstream_bodies/large-anthropic-group.sha256 new file mode 100644 index 000000000..ca00c52c3 --- /dev/null +++ b/internal/gateway/testdata/upstream_bodies/large-anthropic-group.sha256 @@ -0,0 +1 @@ +f20435bc8b9860f1221a097e8b1f12f1d1b99094690387a811c7c6e847dc94c0 diff --git a/internal/gateway/testdata/upstream_bodies/large-anthropic.sha256 b/internal/gateway/testdata/upstream_bodies/large-anthropic.sha256 new file mode 100644 index 000000000..ca00c52c3 --- /dev/null +++ b/internal/gateway/testdata/upstream_bodies/large-anthropic.sha256 @@ -0,0 +1 @@ +f20435bc8b9860f1221a097e8b1f12f1d1b99094690387a811c7c6e847dc94c0 diff --git a/internal/gateway/testdata/upstream_bodies/large-chat.sha256 b/internal/gateway/testdata/upstream_bodies/large-chat.sha256 new file mode 100644 index 000000000..1c6c537ad --- /dev/null +++ b/internal/gateway/testdata/upstream_bodies/large-chat.sha256 @@ -0,0 +1 @@ +f9400fa84e77c783c7d67c4b4380275af3a6859be7d69bc562663e5f5e316b03 diff --git a/internal/gateway/testdata/upstream_bodies/large-responses-to-chat.sha256 b/internal/gateway/testdata/upstream_bodies/large-responses-to-chat.sha256 new file mode 100644 index 000000000..85edc5ee1 --- /dev/null +++ b/internal/gateway/testdata/upstream_bodies/large-responses-to-chat.sha256 @@ -0,0 +1 @@ +ea4a95413224377e614047c41a8abae72aff0f2692ff5751562da720d7701a29 diff --git a/internal/gateway/testdata/upstream_bodies/large-responses.sha256 b/internal/gateway/testdata/upstream_bodies/large-responses.sha256 new file mode 100644 index 000000000..2da193343 --- /dev/null +++ b/internal/gateway/testdata/upstream_bodies/large-responses.sha256 @@ -0,0 +1 @@ +f6101aa753b203fa2716754f7ee9c41b42df317033812ff453e817f41e634ab1 diff --git a/internal/gateway/testdata/upstream_bodies/responses-string.json b/internal/gateway/testdata/upstream_bodies/responses-string.json new file mode 100644 index 000000000..3b7f5cc74 --- /dev/null +++ b/internal/gateway/testdata/upstream_bodies/responses-string.json @@ -0,0 +1 @@ +{"model":"m1","input":"just a string 😀","stream":false} \ No newline at end of file diff --git a/internal/gateway/testdata/upstream_bodies/responses-to-anthropic.json b/internal/gateway/testdata/upstream_bodies/responses-to-anthropic.json new file mode 100644 index 000000000..5627d1c42 --- /dev/null +++ b/internal/gateway/testdata/upstream_bodies/responses-to-anthropic.json @@ -0,0 +1 @@ +{"max_tokens":16384,"messages":[{"role":"user","content":[{"type":"text","text":"hi"},{"type":"image","source":{"type":"base64","media_type":"image/png","data":"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg=="}}]},{"role":"assistant","content":[{"type":"tool_use","id":"call_1","name":"Read","input":{"path":"/x"}}]},{"role":"user","content":[{"type":"tool_result","tool_use_id":"call_1","content":"done\t\"x\""},{"type":"text","text":"go on","cache_control":{"type":"ephemeral"}}]}],"model":"m1","stream":true,"system":[{"type":"text","text":"be brief — ok","cache_control":{"type":"ephemeral"}}],"thinking":{"budget_tokens":10000,"type":"enabled"},"tools":[{"description":"Reads","input_schema":{"type":"object","properties":{"path":{"type":"string"}}},"name":"Read"}]} \ No newline at end of file diff --git a/internal/gateway/testdata/upstream_bodies/responses-to-chat.json b/internal/gateway/testdata/upstream_bodies/responses-to-chat.json new file mode 100644 index 000000000..83c1f9898 --- /dev/null +++ b/internal/gateway/testdata/upstream_bodies/responses-to-chat.json @@ -0,0 +1 @@ +{"messages":[{"content":"be brief — ok","role":"system"},{"content":[{"text":"hi","type":"text"},{"image_url":{"url":"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg=="},"type":"image_url"}],"role":"user"},{"role":"assistant","tool_calls":[{"function":{"arguments":"{\"path\":\"/x\"}","name":"Read"},"id":"call_1","type":"function"}]},{"content":"done\t\"x\"","role":"tool","tool_call_id":"call_1"},{"content":"go on","role":"user"}],"model":"m1","reasoning_effort":"medium","service_tier":"priority","stream":true,"stream_options":{"include_usage":true},"tools":[{"function":{"description":"Reads","name":"Read","parameters":{"type":"object","properties":{"path":{"type":"string"}}}},"type":"function"}]} \ No newline at end of file diff --git a/internal/gateway/testdata/upstream_bodies/responses.json b/internal/gateway/testdata/upstream_bodies/responses.json new file mode 100644 index 000000000..94a85372b --- /dev/null +++ b/internal/gateway/testdata/upstream_bodies/responses.json @@ -0,0 +1,8 @@ +{"model":"m1","instructions":"be brief — ok","service_tier":"priority","reasoning":{"effort":"medium","summary":"auto"}, + "input":[{"type":"message","role":"user","content":[{"type":"input_text","text":"hi"},{"type":"input_image","image_url":"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg=="}]}, + {"type":"reasoning","id":"rs_1","summary":[],"encrypted_content":"ZW5j"}, + {"type":"function_call","call_id":"call_1","name":"Read","arguments":"{\"path\":\"/x\"}"}, + {"type":"function_call_output","call_id":"call_1","output":"done\t\"x\""}, + {"type":"message","role":"user","content":"go on"}], + "tools":[{"type":"function","name":"Read","description":"Reads","parameters":{"type":"object","properties":{"path":{"type":"string"}}}}], + "store":false,"stream":false,"include":["reasoning.encrypted_content"]} \ No newline at end of file diff --git a/internal/gateway/textcalls.go b/internal/gateway/textcalls.go index 12a098c8a..d239d6e00 100644 --- a/internal/gateway/textcalls.go +++ b/internal/gateway/textcalls.go @@ -67,7 +67,7 @@ func chatToolNames(body []byte) map[string]bool { Name string `json:"name"` } `json:"tools"` } - if json.Unmarshal(body, &q) != nil || len(q.Tools) == 0 { + if decodeJSON(body, &q) != nil || len(q.Tools) == 0 { return nil } m := map[string]bool{} @@ -256,7 +256,7 @@ func paramCall(s string, names map[string]bool) (writtenCall, int, bool) { val := strings.Trim(s[n:end], "\r\n") val = strings.TrimSuffix(val, cutMark(val)) var v any - if json.Unmarshal([]byte(strings.TrimSpace(val)), &v) == nil { + if decodeJSON([]byte(strings.TrimSpace(val)), &v) == nil { args[key] = v } else { args[key] = val @@ -301,7 +301,7 @@ func glmCall(s string, names map[string]bool) (writtenCall, int, bool) { } key, val := strings.TrimSpace(s[n+p[2]:n+p[3]]), s[n+p[4]:n+p[5]] var v any - if json.Unmarshal([]byte(strings.TrimSpace(val)), &v) == nil { + if decodeJSON([]byte(strings.TrimSpace(val)), &v) == nil { args[key] = v } else { args[key] = val @@ -344,7 +344,7 @@ func dsmlCall(s, name string, open int, names map[string]bool) (writtenCall, int continue } var v any - if json.Unmarshal([]byte(strings.TrimSpace(val)), &v) == nil { + if decodeJSON([]byte(strings.TrimSpace(val)), &v) == nil { args[p[1]] = v } else { args[p[1]] = val @@ -366,14 +366,14 @@ func callArgs(raw json.RawMessage) (json.RawMessage, bool) { } if raw[0] == '"' { var s string - if json.Unmarshal(raw, &s) != nil { + if decodeJSON(raw, &s) != nil { return nil, false } fixed, _ := escapeRawControls(strings.TrimSpace(s)) raw = json.RawMessage(fixed) } var m map[string]any - if json.Unmarshal(raw, &m) != nil { + if decodeJSON(raw, &m) != nil { return nil, false } b, err := json.Marshal(m) diff --git a/internal/gateway/upstream_bytes_test.go b/internal/gateway/upstream_bytes_test.go new file mode 100644 index 000000000..978627db1 --- /dev/null +++ b/internal/gateway/upstream_bytes_test.go @@ -0,0 +1,151 @@ +package gateway + +import ( + "bytes" + "crypto/sha256" + "encoding/hex" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/yetone/magpie/internal/provider" +) + +// The bodies of these requests, as a vendor gets them, were saved from +// the gateway before it read request bodies with decodeJSON instead of +// json.Unmarshal (#1532, #1654): reading a body faster changes no byte +// of what is sent. UPDATE_UPSTREAM_BODIES=1 saves them again. +func TestUpstreamBodiesUnchanged(t *testing.T) { + const ( + aReply = `{"id":"msg_1","type":"message","role":"assistant","model":"m1","content":[{"type":"text","text":"ok"}],"stop_reason":"end_turn","usage":{"input_tokens":7,"output_tokens":1}}` + cReply = `{"id":"c1","object":"chat.completion","choices":[{"index":0,"message":{"role":"assistant","content":"ok"},"finish_reason":"stop"}],"usage":{"prompt_tokens":7,"completion_tokens":1}}` + rReply = `{"id":"r1","object":"response","status":"completed","output":[{"type":"message","role":"assistant","content":[{"type":"output_text","text":"ok"}]}],"usage":{"input_tokens":7,"output_tokens":1}}` + png = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==" + ) + anthropicBody := `{ "max_tokens" : 1024,"model":"fake/m1", "metadata":{"user_id":"u_1"}, + "system":[{"type":"text","text":"You are é \/ \"careful\"\n\ttabs","cache_control":{"type":"ephemeral"}}], + "tools":[{"name":"Read","description":"Reads a file","input_schema":{"type":"object","properties":{"path":{"type":"string"}},"required":["path"]}}], + "messages":[{"role":"user","content":"read it"}, + {"role":"assistant","content":[{"type":"thinking","thinking":"hmm","signature":"c2ln"},{"type":"text","text":"ok 漢字 😀"},{"type":"tool_use","id":"toolu_1","name":"Read","input":{"path":"/a b/c.go","n":1.50e2}}]}, + {"role":"user","content":[{"type":"tool_result","tool_use_id":"toolu_1","content":[{"type":"text","text":"line\u0001one\r\nline two"}]},{"type":"text","text":"go on"}]}], + "temperature":0.70, "stream":false, "unknown_field":{"kept":[1,2,{"x":null}]}}` + anthropicImage := `{"model":"fake/m1","max_tokens":64,"messages":[{"role":"user","content":[{"type":"text","text":"what is this"},{"type":"image","source":{"type":"base64","media_type":"image/png","data":"` + png + `"}}]}]}` + anthropicThinking := `{"model":"fake/m1","max_tokens":2048,"thinking":{"type":"enabled","budget_tokens":1024},"messages":[{"role":"user","content":"think"}],"model":"fake/m1"}` + chatBody := `{"model":"fake/m1","messages":[{"role":"system","content":"be brief"},{"role":"user","content":[{"type":"text","text":"look"},{"type":"image_url","image_url":{"url":"data:image/png;base64,` + png + `"}}]}, + {"role":"assistant","content":null,"tool_calls":[{"id":"call_1","type":"function","function":{"name":"Read","arguments":"{\"path\":\"/x\"}"}}]}, + {"role":"tool","tool_call_id":"call_1","content":"file \"body\"\n"},{"role":"user","content":"go on é"}], + "tools":[{"type":"function","function":{"name":"Read","description":"Reads","parameters":{"type":"object","properties":{"path":{"type":"string"}}}}}], + "tool_choice":"auto","reasoning_effort":"high","temperature":1,"stop":["\n\n"],"stream":false,"user":"u"}` + responsesBody := `{"model":"fake/m1","instructions":"be brief — ok","service_tier":"priority","reasoning":{"effort":"medium","summary":"auto"}, + "input":[{"type":"message","role":"user","content":[{"type":"input_text","text":"hi"},{"type":"input_image","image_url":"data:image/png;base64,` + png + `"}]}, + {"type":"reasoning","id":"rs_1","summary":[],"encrypted_content":"ZW5j"}, + {"type":"function_call","call_id":"call_1","name":"Read","arguments":"{\"path\":\"/x\"}"}, + {"type":"function_call_output","call_id":"call_1","output":"done\t\"x\""}, + {"type":"message","role":"user","content":"go on"}], + "tools":[{"type":"function","name":"Read","description":"Reads","parameters":{"type":"object","properties":{"path":{"type":"string"}}}}], + "store":false,"stream":false,"include":["reasoning.encrypted_content"]}` + responsesString := `{"model":"fake/m1","input":"just a string 😀","stream":false}` + + for _, tc := range []struct { + name, path, model string + proto provider.Protocol // the vendor's protocol + body string + }{ + {"anthropic", "/v1/messages", "fake/m1", provider.Anthropic, anthropicBody}, + {"anthropic-group", "/v1/messages", "group/g", provider.Anthropic, anthropicBody}, + {"anthropic-image", "/v1/messages", "fake/m1", provider.Anthropic, anthropicImage}, + {"anthropic-thinking", "/v1/messages", "fake/m1", provider.Anthropic, anthropicThinking}, + {"anthropic-to-chat", "/v1/messages", "fake/m1", provider.Chat, anthropicBody}, + {"anthropic-to-responses", "/v1/messages", "group/g", provider.Responses, anthropicImage}, + {"chat", "/v1/chat/completions", "fake/m1", provider.Chat, chatBody}, + {"chat-group", "/v1/chat/completions", "group/g", provider.Chat, chatBody}, + {"chat-to-anthropic", "/v1/chat/completions", "fake/m1", provider.Anthropic, chatBody}, + {"responses", "/v1/responses", "fake/m1", provider.Responses, responsesBody}, + {"responses-string", "/v1/responses", "group/g", provider.Responses, responsesString}, + {"responses-to-chat", "/v1/responses", "fake/m1", provider.Chat, responsesBody}, + {"responses-to-anthropic", "/v1/responses", "fake/m1", provider.Anthropic, responsesBody}, + {"large-anthropic", "/v1/messages", "fake/m1", provider.Anthropic, string(largeConversation(provider.Anthropic, "fake/m1", 30_000))}, + {"large-anthropic-group", "/v1/messages", "group/g", provider.Anthropic, string(largeConversation(provider.Anthropic, "group/g", 30_000))}, + {"large-chat", "/v1/chat/completions", "fake/m1", provider.Chat, string(largeConversation(provider.Chat, "fake/m1", 30_000))}, + {"large-responses", "/v1/responses", "fake/m1", provider.Responses, string(largeConversation(provider.Responses, "fake/m1", 30_000))}, + {"large-responses-to-chat", "/v1/responses", "fake/m1", provider.Chat, string(largeConversation(provider.Responses, "fake/m1", 30_000))}, + } { + t.Run(tc.name, func(t *testing.T) { + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + t.Setenv("XDG_CACHE_HOME", t.TempDir()) + f := &fake{ctype: "application/json"} + up := httptest.NewServer(f) + defer up.Close() + p := provider.Provider{ID: "fake", Name: "Fake", Key: "k", Models: []string{"m1"}} + // a request in another protocol than the vendor's is streamed to it + streamed := !strings.HasSuffix(tc.path, map[provider.Protocol]string{provider.Chat: "/chat/completions", provider.Responses: "/responses", provider.Anthropic: "/messages"}[tc.proto]) + switch tc.proto { + case provider.Chat: + p.Chat, f.reply = up.URL+"/v1", cReply + if streamed { + f.reply = sse(`data: {"id":"c1","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"role":"assistant","content":"ok"},"finish_reason":"stop"}],"usage":{"prompt_tokens":7,"completion_tokens":1}}`, `data: [DONE]`) + } + case provider.Responses: + p.Responses, f.reply = up.URL+"/v1", rReply + if streamed { + f.reply = sse(`data: {"type":"response.created","response":{"id":"r1","model":"m1"}}`, + `data: {"type":"response.output_text.delta","delta":"ok"}`, + `data: {"type":"response.completed","response":{"id":"r1","status":"completed","usage":{"input_tokens":7,"output_tokens":1}}}`) + } + case provider.Anthropic: + p.Anthropic, f.reply = up.URL, aReply + if streamed { + f.reply = sse(`event: message_start`+"\n"+`data: {"type":"message_start","message":{"id":"msg_1","type":"message","role":"assistant","model":"m1","content":[],"usage":{"input_tokens":7,"output_tokens":0}}}`, + `event: content_block_start`+"\n"+`data: {"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}`, + `event: content_block_delta`+"\n"+`data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"ok"}}`, + `event: content_block_stop`+"\n"+`data: {"type":"content_block_stop","index":0}`, + `event: message_delta`+"\n"+`data: {"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":1}}`, + `event: message_stop`+"\n"+`data: {"type":"message_stop"}`) + } + } + if streamed { + f.ctype = "" + } + if err := provider.Save(p); err != nil { + t.Fatal(err) + } + if err := provider.SaveGroup(provider.Group{ID: "g", Name: "G", Members: []string{"fake/m1"}, Routing: provider.Ordered}); err != nil { + t.Fatal(err) + } + rec := httptest.NewRecorder() + New().Handler().ServeHTTP(rec, httptest.NewRequest("POST", tc.path, bytes.NewReader([]byte(tc.body)))) + if rec.Code != 200 || f.calls != 1 { + t.Fatalf("%d after %d calls: %s", rec.Code, f.calls, rec.Body.String()) + } + // a big body is kept by its hash + got := f.got + name := filepath.Join("testdata", "upstream_bodies", tc.name+".json") + if len(got) > 16<<10 { + sum := sha256.Sum256(got) + got = []byte(hex.EncodeToString(sum[:]) + "\n") + name = filepath.Join("testdata", "upstream_bodies", tc.name+".sha256") + } + if os.Getenv("UPDATE_UPSTREAM_BODIES") == "1" { + if err := os.MkdirAll(filepath.Dir(name), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(name, got, 0o644); err != nil { + t.Fatal(err) + } + return + } + want, err := os.ReadFile(name) + if err != nil { + t.Fatal(err) + } + // a Windows checkout may have made its line ends CRLF; none of + // these bodies holds a CR of its own + want = bytes.ReplaceAll(want, []byte("\r\n"), []byte("\n")) + if !bytes.Equal(got, want) { + t.Errorf("the vendor got other bytes than before:\n got %s\nwant %s", got, want) + } + }) + } +}