readBoundedRequestBody read every body with io.ReadAll. In Go 1.26 that reads into growing chunks, then copies them into one final slice, so each body was allocated about twice. With a declared Content-Length (and no Content-Encoding to decode), readSized now reads into one slice of that length. The length is the client's word, so it is not trusted: - the first allocation is at most 1 MiB (sizedReadFirst); the slice doubles from there, up to the declared length; - a client that declares 512 MB and sends 5 bytes costs at most sizedReadFirst; - a body longer than declared is read whole, still under the body limit (the LimitReader around it); - with no length, or an encoded body, it is io.ReadAll as before. BenchmarkLargeRequest, ~2 MB conversation, B/op before → after: anthropic 55.37 → 53.81 MB anthropic-group 66.82 → 65.26 MB chat 44.83 → 43.27 MB responses 55.37 → 53.81 MB 1.56 MB less per request, about 0.8× the body. In the 60-min soak before (dee5c9d75), io.ReadAll was 8.2 GB of 106.7 GB allocated. Tests (request_sized_test.go): - TestRequestBodyReadOnceAtItsLength: an 800 KB body allocates at most 1.1× its size and comes back with cap == len, where io.ReadAll allocates at least 1.5×. - TestRequestBodyLengthNotTrusted: the 512 MB lie, a longer body, a read error, and no length. - TestRequestBodyReadAtItsLengthServed: through a real handler, and a gzip body still decodes. Broken by hand (always io.ReadAll): red, "cap 802816 for a body of 800000" and "cap 622592". Run (darwin arm64, go1.26.8, sandbox HOME, load 40 to 90 from other sessions' suites): - go test ./... -count=1 -timeout 45m on the series' final tree atba319a758: exit 0, all 68 packages ok (gateway 1498s, agent 1633s). - After the rebase ontob855cfee9(two redact commits): go test ./internal/redact ./internal/gateway -count=1 -timeout 45m, both ok (gateway 917s). - go test -race -count=3 on the Held, ReadersOfAHeldBody, RecentRing, RequestBody, CaptureRequest, folder, WorkPlace, WorkDir and Turn tests: ok, after TestReadersOfAHeldBodyParseItOnce's byte bound was skipped under -race (the third commit says why); that test and TestHeldFactsGoWithTheirBody then passed -count=30 with and without -race. - Each commit alone: go vet ./internal/gateway and gofmt -l clean. - Final tree: gofmt -l clean; go vet ./... for darwin, GOOS=windows and GOOS=linux -tags nogui, all exit 0. Not tried: a second 60-minute soak after the series (the one before is the "before" here; the "after" numbers are the benchmark's), the GUI suite (nothing in it changed), Windows and Linux test runs (vet only).
130 lines
4.2 KiB
Go
130 lines
4.2 KiB
Go
package gateway
|
|
|
|
import (
|
|
"bytes"
|
|
"compress/gzip"
|
|
"errors"
|
|
"io"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"runtime"
|
|
"strings"
|
|
"testing"
|
|
|
|
"github.com/yetone/magpie/internal/provider"
|
|
)
|
|
|
|
// chunked hands its bytes out a piece at a time, as a socket does.
|
|
type chunked struct {
|
|
b []byte
|
|
size int
|
|
}
|
|
|
|
func (c *chunked) Read(p []byte) (int, error) {
|
|
if len(c.b) == 0 {
|
|
return 0, io.EOF
|
|
}
|
|
n := copy(p[:min(len(p), c.size)], c.b)
|
|
c.b = c.b[n:]
|
|
return n, nil
|
|
}
|
|
|
|
// allocated is the bytes f allocates.
|
|
func allocated(f func()) uint64 {
|
|
var before, after runtime.MemStats
|
|
runtime.GC()
|
|
runtime.ReadMemStats(&before)
|
|
f()
|
|
runtime.ReadMemStats(&after)
|
|
return after.TotalAlloc - before.TotalAlloc
|
|
}
|
|
|
|
// An agent's whole conversation, sent with its length, is read into one
|
|
// slice of its own size: io.ReadAll read it into chunks and copied them
|
|
// into a slice of their sum, twice the body on every turn (yg6888 on X:
|
|
// ~1 GB).
|
|
func TestRequestBodyReadOnceAtItsLength(t *testing.T) {
|
|
sent := bytes.Repeat([]byte("0123456789abcdef"), 50_000) // 800 KB
|
|
var got []byte
|
|
var err error
|
|
once := allocated(func() { got, err = readSized(&chunked{sent, 32 << 10}, int64(len(sent))) })
|
|
if err != nil || !bytes.Equal(got, sent) {
|
|
t.Fatalf("read %d bytes, %v", len(got), err)
|
|
}
|
|
if cap(got) != len(got) {
|
|
t.Fatalf("cap %d for a body of %d", cap(got), len(got))
|
|
}
|
|
if limit := uint64(len(sent)) * 11 / 10; once > limit {
|
|
t.Fatalf("an %d-byte body allocated %d bytes to read", len(sent), once)
|
|
}
|
|
// the measure tells the two apart
|
|
if all := allocated(func() { io.ReadAll(&chunked{sent, 32 << 10}) }); all < uint64(len(sent))*3/2 {
|
|
t.Fatalf("io.ReadAll allocated only %d for %d bytes: the check above shows nothing", all, len(sent))
|
|
}
|
|
|
|
// larger than the first slice: its final slice is still its own size
|
|
big := bytes.Repeat(sent, 4)
|
|
got, err = readSized(&chunked{big, 64 << 10}, int64(len(big)))
|
|
if err != nil || !bytes.Equal(got, big) || cap(got) != len(got) {
|
|
t.Fatalf("a %d-byte body read as %d (cap %d), %v", len(big), len(got), cap(got), err)
|
|
}
|
|
}
|
|
|
|
// Content-Length is the client's word: a body shorter than it said costs
|
|
// no more than the first slice, one longer reads on, a failed read is
|
|
// returned as io.ReadAll returns it, and no length is io.ReadAll.
|
|
func TestRequestBodyLengthNotTrusted(t *testing.T) {
|
|
var got []byte
|
|
lied := allocated(func() { got, _ = readSized(strings.NewReader("short"), defaultBodyLimit) })
|
|
if string(got) != "short" {
|
|
t.Fatalf("read %q", got)
|
|
}
|
|
if lied > sizedReadFirst+64<<10 {
|
|
t.Fatalf("a client that said 512 MB and sent 5 bytes made magpie allocate %d bytes", lied)
|
|
}
|
|
long := strings.Repeat("y", 5000)
|
|
if got, err := readSized(&chunked{[]byte(long), 700}, 10); err != nil || string(got) != long {
|
|
t.Fatalf("a body longer than it said read as %d bytes, %v", len(got), err)
|
|
}
|
|
if got, err := readSized(io.MultiReader(strings.NewReader("abc"), failedBodyReader{}), 100); !errors.Is(err, io.ErrUnexpectedEOF) || string(got) != "abc" {
|
|
t.Fatalf("failed read: %q, %v", got, err)
|
|
}
|
|
if got, err := readSized(strings.NewReader("abc"), -1); err != nil || string(got) != "abc" {
|
|
t.Fatalf("no length: %q, %v", got, err)
|
|
}
|
|
}
|
|
|
|
// Through the server: a body sent as it is is read at its length; an
|
|
// encoded one, whose Content-Length is the wire's, is decoded whole.
|
|
func TestRequestBodyReadAtItsLengthServed(t *testing.T) {
|
|
sent := strings.Repeat(`{"role":"user","content":"hi"},`, 20_000)
|
|
var got []byte
|
|
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
got, _ = New().requestBody(w, r, provider.Chat)
|
|
}))
|
|
defer srv.Close()
|
|
resp, err := http.Post(srv.URL, "application/json", strings.NewReader(sent))
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
resp.Body.Close()
|
|
if string(got) != sent || cap(got) != len(got) {
|
|
t.Fatalf("read %d bytes (cap %d) of %d", len(got), cap(got), len(sent))
|
|
}
|
|
|
|
var gz bytes.Buffer
|
|
zw := gzip.NewWriter(&gz)
|
|
zw.Write([]byte(sent))
|
|
zw.Close()
|
|
req, _ := http.NewRequest("POST", srv.URL, &gz)
|
|
req.Header.Set("Content-Encoding", "gzip")
|
|
resp, err = http.DefaultClient.Do(req)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
resp.Body.Close()
|
|
if string(got) != sent {
|
|
t.Fatalf("a gzip body of %d bytes read as %d", len(sent), len(got))
|
|
}
|
|
}
|