gateway: a held request body is known by where it is, not summed again (#4371)
Each of the dozen decodes, topMember reads and validity checks a request
body goes through summed all its bytes with maphash to find what
validMemo knew of it: about 5% of the gateway's CPU on long Codex
requests (#4371). A body being served (holdBody) is not written while
held, so longBody and jsonValid now know it by its address and length,
check and split it once, and keep that in heldBodies.long until it is
released, as factsOf keeps its facts. Any other long body is summed as
before.
Run on mote at this tree:
- gofmt, go vet (darwin, GOOS=windows, GOOS=linux): ok
- TestHeldBodyIsNotSummed, TestHeldBodyNotJSON, TestDecodeJSON*,
TestRequestBodyRawValuesShareIt, TestTopMember*, TestWithoutTopMember*:
ok 3 of 3 alone, ok under -race
- go test -timeout 45m ./internal/gateway: ok (609s)
- Broken by hand: held lookup skipped -> "a held 84077-byte body was
summed 18 times"; release left the finds kept -> "a released body's
finds were kept".
- BenchmarkHeldBodyDecodes (1.8MB Responses body held, 12 decodes plus 12
topMember reads an op): 3.31ms/op before, 7.9us/op after, allocations
the same (24/op).
Real use: sandbox HOME copied from the owner's, real DeepSeek account,
deepseek-flash, four turns of a 115-123KB history through
/v1/chat/completions with masking on: every reply HTTP 200 (three "ok",
one empty at finish_reason length, the model's reasoning using
max_tokens, as on the old binary).
Not run: the full ./... suite; a real Codex account; Windows and Linux
runs of the tests.
Picked onto 9162277b9 (3 commits, none in internal/gateway/fastjson.go); not run again there.
This commit is contained in:
@@ -95,6 +95,16 @@ var heldBodies struct {
|
||||
list atomic.Pointer[[][]byte]
|
||||
// facts: a held body's bodyFacts, by the body's first byte (factsOf)
|
||||
facts map[*byte]heldFacts
|
||||
// long: what longBody found of a held body, by its first byte
|
||||
long map[*byte]heldLong
|
||||
}
|
||||
|
||||
// heldLong is what longBody found of a held body: valid or not, and its
|
||||
// top level's members.
|
||||
type heldLong struct {
|
||||
n int
|
||||
valid bool
|
||||
members []memberSpan
|
||||
}
|
||||
|
||||
// heldBodiesMost bounds heldBodies: a body past it is decoded with copies, as
|
||||
@@ -144,6 +154,7 @@ func holdBody(ctx context.Context, body []byte) {
|
||||
return
|
||||
}
|
||||
delete(heldBodies.facts, unsafe.SliceData(body))
|
||||
delete(heldBodies.long, unsafe.SliceData(body))
|
||||
next := slices.Delete(slices.Clone(cur), i, i+1)
|
||||
heldBodies.list.Store(&next)
|
||||
})
|
||||
@@ -833,7 +844,10 @@ var topSplit atomic.Pointer[func(data []byte)]
|
||||
// at its top level again by each of the dozen decodes it went through,
|
||||
// each a walk over every byte of the conversation.
|
||||
func longBody(data []byte) (valid bool, members []memberSpan) {
|
||||
s := validSum{len(data), maphash.Bytes(validSeed, data)}
|
||||
if e, held := heldLongOf(data); held {
|
||||
return e.valid, e.members
|
||||
}
|
||||
s := validSum{len(data), validHash(data)}
|
||||
validMemo.Lock()
|
||||
i := slices.IndexFunc(validMemo.sums[:], func(e validEntry) bool { return e.validSum == s })
|
||||
if i >= 0 && validMemo.sums[i].members != nil {
|
||||
@@ -874,6 +888,64 @@ func longBody(data []byte) (valid bool, members []memberSpan) {
|
||||
|
||||
var validSeed = maphash.MakeSeed()
|
||||
|
||||
// validHash is data's sum in validMemo.
|
||||
func validHash(data []byte) uint64 {
|
||||
if f := validHashed.Load(); f != nil {
|
||||
(*f)(data)
|
||||
}
|
||||
return maphash.Bytes(validSeed, data)
|
||||
}
|
||||
|
||||
// validHashed, when set (tests), is told of each body validHash sums.
|
||||
var validHashed atomic.Pointer[func(data []byte)]
|
||||
|
||||
// heldLongOf is what longBody finds of data when data is a body being
|
||||
// served (holdBody), whole, and whether it is one. A held body is not
|
||||
// written while held, so it is known again by where it is, not by a hash
|
||||
// of all its bytes: each of the dozen decodes a request went through
|
||||
// summed its whole body, a twentieth of the gateway's CPU on long Codex
|
||||
// requests (#4371). What is found is kept until the body is released.
|
||||
func heldLongOf(data []byte) (heldLong, bool) {
|
||||
key := unsafe.SliceData(data)
|
||||
heldBodies.Lock()
|
||||
e, ok := heldBodies.long[key]
|
||||
heldBodies.Unlock()
|
||||
if ok && e.n == len(data) {
|
||||
return e, true
|
||||
}
|
||||
l := heldBodies.list.Load()
|
||||
if l == nil || !slices.ContainsFunc(*l, func(b []byte) bool { return unsafe.SliceData(b) == key && len(b) == len(data) }) {
|
||||
return heldLong{}, false
|
||||
}
|
||||
e = heldLong{n: len(data)}
|
||||
if f := validScanned.Load(); f != nil {
|
||||
(*f)(data)
|
||||
}
|
||||
if e.valid = jsonCheck(data); e.valid {
|
||||
if raw := trimJSON(data); raw[0] == '{' {
|
||||
if f := topSplit.Load(); f != nil {
|
||||
(*f)(data)
|
||||
}
|
||||
e.members = []memberSpan{}
|
||||
eachMemberAt(raw, func(k0, k1, v0, v1 int) bool {
|
||||
e.members = append(e.members, memberSpan{k0, k1, v0, v1})
|
||||
return true
|
||||
})
|
||||
}
|
||||
}
|
||||
heldBodies.Lock()
|
||||
defer heldBodies.Unlock()
|
||||
// only while body is held: one released may be freed, and its memory
|
||||
// given to another body that would read as this one (factsOf)
|
||||
if l := heldBodies.list.Load(); l != nil && slices.ContainsFunc(*l, func(b []byte) bool { return unsafe.SliceData(b) == key && len(b) == len(data) }) {
|
||||
if heldBodies.long == nil {
|
||||
heldBodies.long = map[*byte]heldLong{}
|
||||
}
|
||||
heldBodies.long[key] = e
|
||||
}
|
||||
return e, true
|
||||
}
|
||||
|
||||
// validScanned, when set (tests), is told of each body of validMemoMin or
|
||||
// more that jsonValid checks byte by byte.
|
||||
var validScanned atomic.Pointer[func(data []byte)]
|
||||
@@ -885,7 +957,10 @@ func jsonValid(data []byte) bool {
|
||||
if len(data) < validMemoMin {
|
||||
return jsonCheck(data)
|
||||
}
|
||||
s := validSum{len(data), maphash.Bytes(validSeed, data)}
|
||||
if e, held := heldLongOf(data); held {
|
||||
return e.valid
|
||||
}
|
||||
s := validSum{len(data), validHash(data)}
|
||||
validMemo.Lock()
|
||||
known := slices.ContainsFunc(validMemo.sums[:], func(e validEntry) bool { return e.validSum == s })
|
||||
validMemo.Unlock()
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// A body being served is known by where it is, not by a sum of all its
|
||||
// bytes on every decode (#4371): its dozen decodes, its topMember reads
|
||||
// and its validity checks hash none of it, and check and split it once.
|
||||
// Released, the same bytes are summed again, as any other body's.
|
||||
func TestHeldBodyIsNotSummed(t *testing.T) {
|
||||
body := memoBody(t.Name())
|
||||
var sums atomic.Int32
|
||||
f := func(data []byte) {
|
||||
if bytes.Equal(data, body) {
|
||||
sums.Add(1)
|
||||
}
|
||||
}
|
||||
validHashed.Store(&f)
|
||||
t.Cleanup(func() { validHashed.Store(nil) })
|
||||
scans := countScans(t, body)
|
||||
ctx, done := context.WithCancel(context.Background())
|
||||
holdBody(ctx, body)
|
||||
for range 6 {
|
||||
var v struct {
|
||||
Model string `json:"model"`
|
||||
}
|
||||
if err := decodeJSON(body, &v); err != nil || v.Model != t.Name() {
|
||||
t.Fatalf("decode: %v %q", err, v.Model)
|
||||
}
|
||||
if m, found, ok := topMember(body, "model"); !ok || !found || string(m) != `"`+t.Name()+`"` {
|
||||
t.Fatalf("topMember: %q %v %v", m, found, ok)
|
||||
}
|
||||
if !jsonValid(body) {
|
||||
t.Fatal("a held body read as not valid")
|
||||
}
|
||||
}
|
||||
if n := sums.Load(); n != 0 {
|
||||
t.Fatalf("a held %d-byte body was summed %d times", len(body), n)
|
||||
}
|
||||
if n := scans.Load(); n != 1 {
|
||||
t.Fatalf("a held body was checked %d times, want 1", n)
|
||||
}
|
||||
done()
|
||||
// the release runs on its own goroutine (context.AfterFunc)
|
||||
for deadline := time.Now().Add(10 * time.Second); ; {
|
||||
heldBodies.Lock()
|
||||
_, kept := heldBodies.long[&body[0]]
|
||||
heldBodies.Unlock()
|
||||
if !kept {
|
||||
break
|
||||
}
|
||||
if time.Now().After(deadline) {
|
||||
t.Fatal("a released body's finds were kept")
|
||||
}
|
||||
time.Sleep(time.Millisecond)
|
||||
}
|
||||
if !jsonValid(body) || sums.Load() != 1 {
|
||||
t.Fatalf("a released body was not summed again (%d)", sums.Load())
|
||||
}
|
||||
}
|
||||
|
||||
// A held body that isn't JSON is said to be not valid while held, as
|
||||
// before, and decodes to encoding/json's error.
|
||||
func TestHeldBodyNotJSON(t *testing.T) {
|
||||
body := append(memoBody(t.Name()), '}')
|
||||
ctx, done := context.WithCancel(context.Background())
|
||||
defer done()
|
||||
holdBody(ctx, body)
|
||||
for range 2 {
|
||||
if jsonValid(body) {
|
||||
t.Fatal("a held body with a stray } read as valid")
|
||||
}
|
||||
var v struct{ Model string }
|
||||
if err := decodeJSON(body, &v); err == nil {
|
||||
t.Fatal("a held body that isn't JSON decoded")
|
||||
}
|
||||
if _, _, ok := topMember(body, "model"); ok {
|
||||
t.Fatal("topMember read a held body that isn't JSON")
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user