Commit Graph
1 Commits
Author SHA1 Message Date
yetone 2481750d92 gateway: a request body is read once into a slice of its declared length, not grown and copied (yg6888 on X: ~1 GB)
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 at
  ba319a758: exit 0, all 68 packages ok (gateway 1498s, agent 1633s).
- After the rebase onto b855cfee9 (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).
2026-10-21 19:17:09 +08:00