gateway: a Chat request's call ids and messages are read without copying them
Every Chat attempt ran chatCallIDs, which decoded the whole body into maps of json.RawMessage to see whether a call lacked an id: each level (the body, its messages, each message) was copied, ~3.8 MB a request for a 2 MB conversation, and silentAssistantsOut copied the body once more. editMessages and silentAssistantsOut now decode with decodeJSONView, sharing the body's bytes: an edit replaces a member, never writes into one, keeps none past its return, and a changed body is marshalled anew. chatCallIDs first scans the raw body (callIDsSet): when every call has a non-empty string id there is nothing to give, as a tool message is only given the id of a call that had none. BenchmarkLargeRequest/chat (mica, 200x, count 3): 23.4 -> 21.8 ms, 23.8 -> 16.4 MB and 69.4k -> 38.1k allocs a request. Anthropic and Responses unchanged (22.7 ms, 21.2 / 22.0 MB). TestCallIDsSetNeverSkipsAnEdit holds callIDsSet to the decode over 20000 random conversations (escaped keys and roles, null, numeric and empty ids, non-object calls), each answer and edits 1000+ times. Broken by hand (every id counted as set): red; restored: green. Dropping the tool-message check stayed green, which is why it isn't there. Real account (mote, sandbox HOME, deepseek/deepseek-chat through /v1/chat/completions with tools): paired call 200 "It's 18°C and sunny in Paris."; unpaired 200; empty call and tool_call_id 200 "It's 18°C and sunny in Paris right now." (the id given). Run (mica, at fcb88a13c; rebased since onto main, which changed only internal/update): gofmt -l clean, go vet ./internal/gateway for darwin, linux and windows, go test -count=1 -timeout 45m ./internal/gateway ok (949s). Real DeepSeek Chat with tools (paired, unpaired, empty call ids): 200 each.
This commit is contained in:
@@ -0,0 +1,85 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"math/rand/v2"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// TestCallIDsSetNeverSkipsAnEdit holds callIDsSet to giveCallIDs: a body
|
||||
// it calls set comes back from the decode byte for byte. The ids, roles
|
||||
// and keys are drawn so both answers, and edits, come often.
|
||||
func TestCallIDsSetNeverSkipsAnEdit(t *testing.T) {
|
||||
r := rand.New(rand.NewPCG(5, 6))
|
||||
pick := func(xs ...string) string { return xs[r.IntN(len(xs))] }
|
||||
id := func() string {
|
||||
return pick(`"call_1"`, `"call_2"`, `""`, `null`, `7`, `"cx"`, `{}`)
|
||||
}
|
||||
set, unset, edited := 0, 0, 0
|
||||
for range 20000 {
|
||||
var msgs []string
|
||||
for range 1 + r.IntN(6) {
|
||||
switch r.IntN(5) {
|
||||
case 0:
|
||||
msgs = append(msgs, `{"role":"user","content":"hi"}`)
|
||||
case 1, 2:
|
||||
var calls []string
|
||||
for range r.IntN(3) {
|
||||
c := `{"type":"function","function":{"name":"f","arguments":"{}"}`
|
||||
if r.IntN(8) > 0 {
|
||||
c += `,` + pick(`"id"`, `"id"`, `"ID"`) + `:` + id()
|
||||
}
|
||||
calls = append(calls, c+`}`)
|
||||
}
|
||||
m := `{"role":` + pick(`"assistant"`, `"assistant"`, `"user"`) + `,"content":null`
|
||||
switch r.IntN(6) {
|
||||
case 0:
|
||||
m += `,"tool_calls":null`
|
||||
case 1:
|
||||
m += `,"tool_calls":` + pick(`{}`, `"x"`, `[1]`)
|
||||
default:
|
||||
m += `,"tool_calls":[` + strings.Join(calls, ",") + `]`
|
||||
}
|
||||
msgs = append(msgs, m+`}`)
|
||||
case 3:
|
||||
m := `{"role":` + pick(`"tool"`, `"tool"`) + `,"content":"ok"`
|
||||
if r.IntN(6) > 0 {
|
||||
m += `,` + pick(`"tool_call_id"`, `"tool_call_id"`) + `:` + id()
|
||||
}
|
||||
msgs = append(msgs, m+`}`)
|
||||
default:
|
||||
msgs = append(msgs, pick(`7`, `null`, `{"role":"tool"}`, `{"role":7,"tool_calls":[{"id":""}]}`))
|
||||
}
|
||||
}
|
||||
body := []byte(`{"model":"m","messages":[` + strings.Join(msgs, ",") + `]}`)
|
||||
if !json.Valid(body) {
|
||||
t.Fatalf("invalid fixture %s", body)
|
||||
}
|
||||
got := giveCallIDs(bytes.Clone(body))
|
||||
changed := !bytes.Equal(got, body)
|
||||
if changed {
|
||||
edited++
|
||||
}
|
||||
if callIDsSet(body) {
|
||||
set++
|
||||
if changed {
|
||||
t.Fatalf("callIDsSet(%s) but the decode gives\n%s", body, got)
|
||||
}
|
||||
} else {
|
||||
unset++
|
||||
}
|
||||
if out := chatCallIDs(bytes.Clone(body)); !bytes.Equal(out, got) {
|
||||
t.Fatalf("chatCallIDs(%s) = %s, want %s", body, out, got)
|
||||
}
|
||||
}
|
||||
if set < 1000 || unset < 1000 || edited < 1000 {
|
||||
t.Fatalf("set %d, unset %d, edited %d: the test reaches too little", set, unset, edited)
|
||||
}
|
||||
for _, b := range []string{`{"model":"m"}`, `{"messages":null}`, `{"messages":{}}`, `[]`} {
|
||||
if got := chatCallIDs([]byte(b)); string(got) != b {
|
||||
t.Errorf("chatCallIDs(%s) = %s", b, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -20,6 +20,14 @@ import (
|
||||
// Chat request, relayed or translated, a plugin's included. A body whose
|
||||
// calls all have ids comes back byte for byte.
|
||||
func chatCallIDs(body []byte) []byte {
|
||||
if callIDsSet(body) {
|
||||
return body
|
||||
}
|
||||
return giveCallIDs(body)
|
||||
}
|
||||
|
||||
// giveCallIDs is chatCallIDs past its check, decoding every message.
|
||||
func giveCallIDs(body []byte) []byte {
|
||||
at := -1
|
||||
var open []string // the latest call turn's made ids no result has taken yet
|
||||
return editMessages(body, []string{"tool_calls"}, func(m map[string]json.RawMessage) bool {
|
||||
@@ -179,3 +187,57 @@ func wholeNamedCall(msg map[string]json.RawMessage) bool {
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// callIDsSet says, without decoding body, that chatCallIDs has nothing to
|
||||
// give: every call has a non-empty string id, so no tool message after
|
||||
// one is given an id either. False is "maybe": the decode decides.
|
||||
// Nearly every request with tools is so, and decoding each message to
|
||||
// see was ~17% of a 2 MB Chat request's CPU.
|
||||
func callIDsSet(body []byte) bool {
|
||||
msgs, found, valid := topMember(body, "messages")
|
||||
if !valid || !found || len(msgs) == 0 || msgs[0] != '[' {
|
||||
return !found && valid
|
||||
}
|
||||
set := func(v []byte) bool {
|
||||
s, ok := stringBytes(v)
|
||||
return ok && len(s) > 0
|
||||
}
|
||||
all := true
|
||||
eachElement(msgs, func(el []byte) bool {
|
||||
if el[0] != '{' {
|
||||
all = false
|
||||
return false
|
||||
}
|
||||
var calls []byte
|
||||
eachMember(el, func(k, v []byte) bool {
|
||||
if keyIs(k, "tool_calls") {
|
||||
calls = v
|
||||
}
|
||||
return true
|
||||
})
|
||||
if len(calls) == 0 || string(calls) == "null" {
|
||||
return true
|
||||
}
|
||||
if calls[0] != '[' {
|
||||
all = false
|
||||
return false
|
||||
}
|
||||
eachElement(calls, func(c []byte) bool {
|
||||
if c[0] != '{' {
|
||||
all = false
|
||||
return false
|
||||
}
|
||||
var id []byte
|
||||
eachMember(c, func(k, v []byte) bool {
|
||||
if keyIs(k, "id") {
|
||||
id = v
|
||||
}
|
||||
return true
|
||||
})
|
||||
all = set(id)
|
||||
return all
|
||||
})
|
||||
return all
|
||||
})
|
||||
return all
|
||||
}
|
||||
|
||||
@@ -897,7 +897,7 @@ func silentAssistantsOut(body []byte) []byte {
|
||||
return body
|
||||
}
|
||||
var q map[string]json.RawMessage
|
||||
if decodeJSON(body, &q) != nil || !anySilentAssistant(q["messages"]) {
|
||||
if decodeJSONView(body, &q) != nil || !anySilentAssistant(q["messages"]) {
|
||||
return body
|
||||
}
|
||||
dec := json.NewDecoder(bytes.NewReader(q["messages"]))
|
||||
@@ -1028,7 +1028,10 @@ func withoutMessageReasoning(body []byte, fields []string) []byte {
|
||||
// editMessages hands each message of a Chat request whose JSON names any
|
||||
// of fields to edit, and puts back those edit reports it changed; every
|
||||
// other message keeps its bytes. The body comes back as it was if nothing
|
||||
// changed.
|
||||
// changed. What it decodes shares body's bytes (decodeJSONView): an edit
|
||||
// replaces a member, never writes into one, and keeps none past its
|
||||
// return, and a changed body is marshalled anew. A copy of each level
|
||||
// was ~3.8 MB a request for a 2 MB Chat conversation.
|
||||
func editMessages(body []byte, fields []string, edit func(m map[string]json.RawMessage) bool) []byte {
|
||||
has := false
|
||||
for _, f := range fields {
|
||||
@@ -1038,17 +1041,17 @@ func editMessages(body []byte, fields []string, edit func(m map[string]json.RawM
|
||||
return body
|
||||
}
|
||||
var q map[string]json.RawMessage
|
||||
if decodeJSON(body, &q) != nil {
|
||||
if decodeJSONView(body, &q) != nil {
|
||||
return body
|
||||
}
|
||||
var msgs []json.RawMessage
|
||||
if decodeJSON(q["messages"], &msgs) != nil {
|
||||
if decodeJSONView(q["messages"], &msgs) != nil {
|
||||
return body
|
||||
}
|
||||
changed := false
|
||||
for i, raw := range msgs {
|
||||
var m map[string]json.RawMessage
|
||||
if decodeJSON(raw, &m) != nil || !edit(m) {
|
||||
if decodeJSONView(raw, &m) != nil || !edit(m) {
|
||||
continue
|
||||
}
|
||||
if nb, err := marshalPlain(m); err == nil {
|
||||
|
||||
Reference in New Issue
Block a user