gateway: a decoded struct's keys are read without a string made for each (#3383)
fillJSONIn made a string of every member key of every object it decoded into a struct (unquoteJSON), then a []byte of that string to look the field up, and a []bool for each struct to see a key twice. A Codex request's history is thousands of small objects, so these were a quarter of its allocations. keyName gives a plain ASCII key's bytes between its quotes and leaves any other key to unquoteJSON as before, and the fields seen are bits of a uint64 unless a struct has more than 64 of them. Run at83234fe92+ the previous change + this one: - BenchmarkZZCodexStream (680 KB Codex request, probe not committed), -benchtime 30x -count 3: before ~72,780 allocs/op, 16.42 MB/op; after 54,698 / 54,692 / 54,696 allocs/op (-25%), 16.33 MB/op. - TestDecodeJSONIsUnmarshal gains a non-ASCII key, a fullwidth key and keys with control bytes; TestDecodeJSONKeyTwice checks fillJSON refuses a key twice in a 3-field struct and a 70-field one. Broken by hand: keyName not looking for escapes turns TestDecodeJSONIsUnmarshal and FuzzDecodeJSON red; dropping the twice check in either the bits or the slice path turns TestDecodeJSONKeyTwice red. - go test -fuzz FuzzDecodeJSON -fuzztime 60s: ~966k execs, no failure. At c0b3aadfe (ond7ad3f2a3): - Real account, sandbox HOME with only DeepSeek, through a recording proxy to api.deepseek.com: 5 Codex-UA /v1/responses requests with a tool-call history ond7ad3f2a3and on this; all 10 answered "ok", and the 5 bodies sent upstream are byte-identical. - gofmt clean; GOOS=linux and windows go vet -tags nogui ok. - go test -timeout 45m ./internal/gateway/: ok (449s) at c0b3aadfe
This commit is contained in:
@@ -348,26 +348,35 @@ func fillJSONIn(raw []byte, v reflect.Value, members []memberSpan) error {
|
||||
if f.err != nil {
|
||||
return f.err
|
||||
}
|
||||
var seen []bool
|
||||
// seen is a bit a field, in few or in many when a struct has more
|
||||
// than 64: a []bool made for each struct decoded was one of a
|
||||
// request's commonest allocations
|
||||
var few uint64
|
||||
var many []bool
|
||||
var err error
|
||||
eachMemberIn(raw, members, func(key, val []byte) bool {
|
||||
name, ok := unquoteJSON(key)
|
||||
name, ok := keyName(key)
|
||||
if !ok {
|
||||
err = errSlowJSON
|
||||
return false
|
||||
}
|
||||
i := f.field([]byte(name))
|
||||
i := f.field(name)
|
||||
if i < 0 {
|
||||
return true
|
||||
}
|
||||
if seen == nil {
|
||||
seen = make([]bool, len(f.names))
|
||||
twice := false
|
||||
if len(f.names) <= 64 {
|
||||
twice, few = few&(1<<i) != 0, few|1<<i
|
||||
} else {
|
||||
if many == nil {
|
||||
many = make([]bool, len(f.names))
|
||||
}
|
||||
twice, many[i] = many[i], true
|
||||
}
|
||||
if seen[i] {
|
||||
if twice {
|
||||
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
|
||||
})
|
||||
@@ -630,6 +639,23 @@ func skipJSONValue(data []byte, i int) int {
|
||||
return i
|
||||
}
|
||||
|
||||
// keyName is a member's key as unquoteJSON reads it, without making a
|
||||
// string of it: a plain ASCII key, the kind nearly every key is, is the
|
||||
// bytes between its quotes.
|
||||
func keyName(key []byte) ([]byte, bool) {
|
||||
if len(key) < 2 || key[0] != '"' || key[len(key)-1] != '"' {
|
||||
return nil, false
|
||||
}
|
||||
k := key[1 : len(key)-1]
|
||||
for _, c := range k {
|
||||
if c == '\\' || c == '"' || c < ' ' || c >= utf8.RuneSelf {
|
||||
name, ok := unquoteJSON(key)
|
||||
return []byte(name), ok
|
||||
}
|
||||
}
|
||||
return k, true
|
||||
}
|
||||
|
||||
// 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.
|
||||
|
||||
@@ -2,6 +2,7 @@ package gateway
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"math/rand/v2"
|
||||
"reflect"
|
||||
"strings"
|
||||
@@ -93,6 +94,7 @@ var fjSeeds = []string{
|
||||
`"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":[]}`,
|
||||
`{"modèl":"a non-ASCII key","Model":"fullwidth","MODEL":"b","Model":"c"}`, "{\"mo\x7fdel\":\"d\",\"mo\x1fdel\":1}",
|
||||
}
|
||||
|
||||
func fjCompare(t *testing.T, data []byte) {
|
||||
@@ -154,6 +156,34 @@ func TestDecodeJSONIsUnmarshal(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// A struct marks the fields it has seen in a word's bits, or in a slice
|
||||
// when it has more than 64: a key twice is refused the same in either.
|
||||
func TestDecodeJSONKeyTwice(t *testing.T) {
|
||||
var fields []reflect.StructField
|
||||
for i := range 70 {
|
||||
fields = append(fields, reflect.StructField{Name: fmt.Sprintf("F%d", i), Type: reflect.TypeFor[string](), Tag: reflect.StructTag(fmt.Sprintf(`json:"f%d"`, i))})
|
||||
}
|
||||
wide := reflect.StructOf(fields)
|
||||
for _, s := range []string{`{"f0":"a","f69":"b","f65":"c"}`, `{"f66":"a","f66":"b"}`, `{"f3":"a","F3":"b"}`, `{"f69":1}`} {
|
||||
got, want := reflect.New(wide).Interface(), reflect.New(wide).Interface()
|
||||
gerr, werr := decodeJSON([]byte(s), got), json.Unmarshal([]byte(s), want)
|
||||
if (gerr == nil) != (werr == nil) || !reflect.DeepEqual(got, want) {
|
||||
t.Fatalf("%s: decodeJSON %v %v, json.Unmarshal %v %v", s, got, gerr, want, werr)
|
||||
}
|
||||
}
|
||||
// the fast path's own refusal, which encoding/json then decodes
|
||||
for _, s := range []string{`{"f66":"a","f66":"b"}`, `{"f3":"a","F3":"b"}`} {
|
||||
if err := fillJSON([]byte(s), reflect.New(wide).Elem()); err != errSlowJSON {
|
||||
t.Fatalf("%s: fillJSON %v, want errSlowJSON", s, err)
|
||||
}
|
||||
}
|
||||
for _, s := range []string{`{"model":"a","model":"b"}`, `{"Model":"a","MODEL":"b"}`} {
|
||||
if err := fillJSON([]byte(s), reflect.ValueOf(new(fjBody)).Elem()); err != errSlowJSON {
|
||||
t.Fatalf("%s: fillJSON %v, want errSlowJSON", s, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestDecodeJSONDepth(t *testing.T) {
|
||||
for _, n := range []int{9999, 10000, 10001} {
|
||||
fjCompare(t, []byte(strings.Repeat("[", n)+strings.Repeat("]", n)))
|
||||
|
||||
Reference in New Issue
Block a user