captureRequestBody wrote the body's first 256 KiB into a bytes.Buffer and then copied the buffer into a string: 512 KiB allocated for every request of 256 KiB or more. It is now one string conversion of the same bytes, and the same truncated flag. BenchmarkLargeRequest, ~2 MB conversation, B/op before → after: anthropic 45.84 → 45.58 MB anthropic-group 57.30 → 57.03 MB chat 36.61 → 36.35 MB responses 46.04 → 45.78 MB In the 60-min soak before (dee5c9d75), Buffer.String was 1.08 GB allocated. TestCaptureRequestBodyLimit now also checks exact sizes (0, 5 and callBodyLimit bytes are not truncated), that a capture allocates at most 1.25× callBodyLimit, and that the capture is a copy, not the body's memory. Broken by hand (the buffer put back): red, "capturing 262144 bytes allocated 524288". 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).
176 lines
4.4 KiB
Go
176 lines
4.4 KiB
Go
package gateway
|
|
|
|
import (
|
|
"bytes"
|
|
"io"
|
|
"net/http"
|
|
"os"
|
|
|
|
"github.com/yetone/magpie/internal/redact"
|
|
"github.com/yetone/magpie/internal/usage"
|
|
)
|
|
|
|
// Recent-call bodies are diagnostics, not an unbounded traffic log. Keeping the
|
|
// first 256 KiB is enough to inspect ordinary prompts and responses while
|
|
// preventing images or long streams from multiplying into tens of MiB across
|
|
// 40 calls.
|
|
const callBodyLimit = 256 << 10
|
|
|
|
// wholeBodyLimit asks a spool for every byte it is given, for a body the OTLP
|
|
// export wants uncut (#538).
|
|
const wholeBodyLimit = -1
|
|
|
|
type capturedBody struct {
|
|
buf bytes.Buffer
|
|
truncated bool
|
|
}
|
|
|
|
func (c *capturedBody) add(p []byte) {
|
|
if c.buf.Len() >= callBodyLimit {
|
|
c.truncated = c.truncated || len(p) > 0
|
|
return
|
|
}
|
|
n := min(len(p), callBodyLimit-c.buf.Len())
|
|
_, _ = c.buf.Write(p[:n])
|
|
if n < len(p) {
|
|
c.truncated = true
|
|
}
|
|
}
|
|
|
|
func (c *capturedBody) text() string { return c.buf.String() }
|
|
|
|
// captureRequestBody is a request's first callBodyLimit bytes, copied once:
|
|
// through a capturedBody it was copied into a buffer and then again into
|
|
// its string, 512 KiB for every request of 256 KiB or more.
|
|
func captureRequestBody(p []byte) (string, bool) {
|
|
return string(p[:min(len(p), callBodyLimit)]), len(p) > callBodyLimit
|
|
}
|
|
|
|
type captureResponseWriter struct {
|
|
http.ResponseWriter
|
|
body capturedBody
|
|
// full: the whole body, for the request archive, when it is on
|
|
full *spool
|
|
// whole: the whole body, for an observer that asks for it uncut (#538)
|
|
whole *spool
|
|
// tools: whether the reply calls a tool, for a turn's end (turns)
|
|
tools *toolScan
|
|
}
|
|
|
|
func (w *captureResponseWriter) Write(p []byte) (int, error) {
|
|
w.body.add(p)
|
|
w.tools.add(p)
|
|
if w.full != nil {
|
|
w.full.add(p)
|
|
}
|
|
if w.whole != nil {
|
|
w.whole.add(p)
|
|
}
|
|
return w.ResponseWriter.Write(p)
|
|
}
|
|
|
|
// spool keeps a body whole for the request archive, beyond the first 256
|
|
// KiB Recent calls holds: in a temporary file, not in memory, up to limit
|
|
// bytes; past that only its size is counted. A negative limit keeps every
|
|
// byte (#538). A file that can't be written leaves what was kept so far, cut.
|
|
type spool struct {
|
|
pattern string // empty uses the request archive
|
|
|
|
f *os.File
|
|
limit, kept int64
|
|
size int64 // every byte that came, kept or not
|
|
failed bool
|
|
}
|
|
|
|
func (s *spool) add(p []byte) {
|
|
s.size += int64(len(p))
|
|
if s.failed || (s.limit >= 0 && s.kept >= s.limit) || len(p) == 0 {
|
|
return
|
|
}
|
|
if s.f == nil {
|
|
pattern := s.pattern
|
|
if pattern == "" {
|
|
pattern = "magpie-archive-*"
|
|
}
|
|
f, err := os.CreateTemp("", pattern)
|
|
if err != nil {
|
|
s.failed = true
|
|
return
|
|
}
|
|
s.f = f
|
|
}
|
|
n := int64(len(p))
|
|
if s.limit >= 0 {
|
|
n = min(n, s.limit-s.kept)
|
|
}
|
|
if _, err := s.f.Write(p[:n]); err != nil {
|
|
s.failed = true
|
|
return
|
|
}
|
|
s.kept += n
|
|
}
|
|
|
|
// cut is whether less than the whole body was kept.
|
|
func (s *spool) cut() bool { return s.kept < s.size }
|
|
|
|
// read is what was kept, the file gone after.
|
|
func (s *spool) read() ([]byte, error) {
|
|
if s.f == nil {
|
|
return nil, nil
|
|
}
|
|
defer s.discard()
|
|
if _, err := s.f.Seek(0, io.SeekStart); err != nil {
|
|
return nil, err
|
|
}
|
|
return io.ReadAll(io.LimitReader(s.f, s.kept))
|
|
}
|
|
|
|
// discard removes the file: nothing is kept.
|
|
func (s *spool) discard() {
|
|
if s.f != nil {
|
|
s.f.Close()
|
|
os.Remove(s.f.Name())
|
|
s.f = nil
|
|
}
|
|
}
|
|
|
|
func (w *captureResponseWriter) Flush() {
|
|
if f, ok := w.ResponseWriter.(http.Flusher); ok {
|
|
f.Flush()
|
|
}
|
|
}
|
|
|
|
// withBodies hands a call's captured request and reply to its usage
|
|
// record while an observer wants them (the OTLP export's bodies, #538) —
|
|
// their secrets scrubbed as the request archive's are, on top of the
|
|
// placeholders Mask secrets puts in — and leaves the record without them
|
|
// otherwise. A call captured whole (usage.WholeBodies) carries them in
|
|
// wholeIn/wholeOut; otherwise the first 256 KiB Recent calls keeps is what
|
|
// goes.
|
|
func withBodies(rec *usage.Record, c *Call) {
|
|
if usage.ObservedBodies() == usage.NoBodies {
|
|
return
|
|
}
|
|
in, inCut := c.RequestBody, c.RequestTruncated
|
|
if c.wholeIn != nil {
|
|
in, inCut = string(c.wholeIn), c.wholeInCut
|
|
}
|
|
out, outCut := c.ResponseBody, c.ResponseTruncated
|
|
if c.wholeOut != nil {
|
|
out, outCut = string(c.wholeOut), c.wholeOutCut
|
|
}
|
|
rec.BodyIn = bodyForExport(in, inCut)
|
|
rec.BodyOut = bodyForExport(out, outCut)
|
|
}
|
|
|
|
func bodyForExport(body string, cut bool) string {
|
|
if body == "" {
|
|
return ""
|
|
}
|
|
body = string(redact.ScrubJSON([]byte(body)))
|
|
if cut {
|
|
body += usage.BodyCut
|
|
}
|
|
return body
|
|
}
|