yg6888 on X: "magpie 占用内存有点高 随时1个g", with a group of 29
accounts and three agents sending at once.
Cause: each reader of a request decodes its turns into json.RawMessage
values (the images walk, the conversation id, the prompt, the edits, the
chat parse), and decodeJSON copied each value it filled, as
encoding/json does. A 1.5 MB conversation allocated ~42.8 MB on its way
through a group. Three agents at once kept the heap in the hundreds of
MB, and the GC ran behind it.
Fix:
- readRequestBody holds the body (holdBody) until the request's context
ends. A RawMessage decodeJSON fills from inside a held body shares the
body's bytes, capped so an append can't write into it. The body must
be at most 16x the value (heldShareMost), so a small value kept past
its request (a cache entry, a signature) never pins a whole body.
Anything not held is still copied: a stream's buffer, a scanner line,
a body built and changed in place. The list is bounded at 64 bodies
(heldBodiesMost) and each leaves it through context.AfterFunc.
- The ratio leaves a long conversation's many small turns copied, so
the two readers that run on every request take them in place:
- conversationID takes the turns with elementsOf, slices of the
body.
- walkImages, which runs several times a request, first scans the
turns without decoding (anyImageBlock/anyImageIn) and returns at
once when there is no image. Keys and kinds are compared with
jsonStringIs, so an escaped "type", a duplicate key, a tool
result, a Responses function_call_output and Gemini's inlineData,
fileData and functionResponse still count.
Numbers: sandbox gateway, fresh process each run, 150 requests of a
1.5 MB conversation, 3 at once through a group, machine load ~250:
peak RSS HeapSys GCs allocated bytes.Clone
before 273 MB 222 MB 117 6416 MB 3635 MB
held bodies 233 MB 186 MB 74 3379 MB 1480 MB
+ id/image scan 223 MB 174 MB 64 2853 MB 927 MB
That is ~42.8 MB allocated per request before and ~19 MB after. What is
still copied comes from the translators (stringOrText, editMessages,
parseChat, responsesContent), unquoteJSON (~670 MB), io.ReadAll
(~480 MB) and rewriteModel (~225 MB). None of these is changed here.
Tests:
- TestRequestBodyRawValuesShareIt, TestDecodeJSONCopiesWhatIsNotHeld and
TestHeldBodiesBounded (fastjson_held_test.go).
- TestImageWalkReadsTextOnlyTurnsInPlace: a 938 KB text-only
conversation allocates under len/8 per walk plus id, and eight image
shapes are still found.
Broken by hand, each red:
- no share cap
- no ratio
- no bound
- no release
- pre-scan removed (8,780,204 B per iteration)
- tool_result skipped (case not found)
- id decoding each turn (1,044,859 B over the 117,265 limit)
- kind compared as raw bytes (the escaped case is not found)
No subsystem page covers decodeJSON.
Run record, the three commits on origin/main d9c6a60d8 (machine load
~270-480, with other sessions' GUI suites running):
- gofmt -l: clean. go vet ./... on darwin, GOOS=windows and
GOOS=linux -tags nogui: exit 0.
- go test ./... -count=1 -timeout 45m (sandbox HOME, 11:02-11:34): 64
ok, 1 FAIL: internal/gui TestCoreScriptBudget, app.js 155 bytes over
from the first ledNum. ledNum was made smaller (1,268,907 of
1,269,000 bytes), then internal/gui -count=1 alone: ok (329 s).
- Before the rebase (723f40778 on 9588501c0): internal/gateway ok
(2064 s), internal/agent ok at -timeout 120m (it timed out at 45m
at load ~700, #2869), internal/gui red only in
TestSetAnswersWhileDevinAndProvidersHang (#1375).
- GUI suite, all 140 files, Chromium and WebKit, every language, at
load 400-840 on 723f40778. Every red was run alone against
9588501c0, and none comes from this change: routing-bodies
(#2559/#2658), routing-keys-fold and routing-model-rest (#2658),
routing-mode-goes WebKit (#2151, head 2/20 vs base 3/20),
routing-request-metrics (#2571), routing-wb-restricted (#1905),
usage-agents-hide (#2276/#2399), usage-fold (#2399), usage-checkin
WebKit Qoder (#2549), usage-refresh (#2184). 5 s first waits under
load were added to #2900. The usage-ledger route-callback race at
page close was filed as #3001.
- After the rebase, each alone in both engines: routing-busy-frames,
routing-intent-entry, routing-key-windows, routing-pause and
usage-ledger were green.
- After the smaller ledNum, each alone, both engines, all languages:
routing-busy-frames 6/0 (one later run lost Chromium's launch at
180 s twice; Chromium alone right after: 3/3), usage-ledger
Chromium 16/16 and WebKit 17/0. usage-ledger-leave and
routing-request-metrics were red in browser launch and 5 s waits on
this head and on d9c6a60d8 alike (#2900, #2571). Added to #2900:
a WebKit zh usage-ledger run hung after a 5 s timeout.
178 lines
5.8 KiB
Go
178 lines
5.8 KiB
Go
package gateway
|
|
|
|
import (
|
|
"compress/gzip"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"net"
|
|
"net/http"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/klauspost/compress/zstd"
|
|
"github.com/yetone/magpie/internal/provider"
|
|
)
|
|
|
|
// Bound a single body and its read time without limiting how long a client
|
|
// may wait for a provider slot or how many streams a team gateway may serve.
|
|
//
|
|
// The limit is on the decoded body. Codex sends the whole conversation on
|
|
// every turn, its screenshots inline as base64, and zstd-compressed to a
|
|
// ChatGPT account, which magpie compresses again on the way out: a long
|
|
// session that read many images went past 128 MB decoded and got magpie's
|
|
// 413 on every retry, while the same turn is a fraction of that on the
|
|
// wire (NeoPengZhile, #1422). 512 MB leaves such a session room and still
|
|
// bounds what one request may hold in memory.
|
|
const (
|
|
defaultBodyLimit = 512 << 20
|
|
defaultBodyTimeout = 60 * time.Second
|
|
)
|
|
|
|
type requestLimits struct {
|
|
body int64
|
|
readTimeout time.Duration
|
|
}
|
|
|
|
func (s *Server) requestBody(w http.ResponseWriter, r *http.Request, from provider.Protocol) ([]byte, bool) {
|
|
return s.readRequestBody(w, r, from, 0)
|
|
}
|
|
|
|
func (s *Server) readRequestBody(w http.ResponseWriter, r *http.Request, from provider.Protocol, limit int64) ([]byte, bool) {
|
|
limits := s.requestLimits
|
|
if limit > 0 {
|
|
limits.body = limit
|
|
}
|
|
body, status, err := readBoundedRequestBody(w, r, limits)
|
|
if err != nil {
|
|
writeError(w, from, status, err.Error())
|
|
return nil, false
|
|
}
|
|
holdBody(r.Context(), body)
|
|
return body, true
|
|
}
|
|
|
|
// idleBody renews the socket deadline on wire bytes, including reads made by
|
|
// decoder initialization. Decompressed output must not keep a stalled socket alive.
|
|
type idleBody struct {
|
|
io.ReadCloser
|
|
controller *http.ResponseController
|
|
idle time.Duration
|
|
}
|
|
|
|
func (b *idleBody) Read(p []byte) (int, error) {
|
|
n, err := b.ReadCloser.Read(p)
|
|
if n > 0 {
|
|
if e := b.controller.SetReadDeadline(time.Now().Add(b.idle)); e != nil && !errors.Is(e, http.ErrNotSupported) {
|
|
return n, e
|
|
}
|
|
}
|
|
return n, err
|
|
}
|
|
|
|
// errBodyEncoding is a Content-Encoding magpie can't decode.
|
|
var errBodyEncoding = errors.New("unsupported Content-Encoding")
|
|
|
|
// decodedBody reads r.Body through its Content-Encoding: Codex sends its
|
|
// bodies zstd, to the ChatGPT backend path and to a custom provider's
|
|
// /v1/responses alike (#1223), and other clients gzip. The header is
|
|
// dropped once decoded, so nothing after this sees or forwards it.
|
|
func decodedBody(r *http.Request) (io.ReadCloser, error) {
|
|
var rd io.ReadCloser = io.NopCloser(r.Body)
|
|
switch enc := strings.ToLower(strings.TrimSpace(r.Header.Get("Content-Encoding"))); enc {
|
|
case "", "identity":
|
|
case "zstd":
|
|
d, err := zstd.NewReader(r.Body, zstd.WithDecoderMaxMemory(defaultBodyLimit))
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
rd = d.IOReadCloser()
|
|
case "gzip", "x-gzip":
|
|
g, err := gzip.NewReader(r.Body)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("request body is not gzip: %w", err)
|
|
}
|
|
rd = g
|
|
default:
|
|
return nil, fmt.Errorf("%w: magpie can't read a %q body; send it as identity, gzip or zstd", errBodyEncoding, enc)
|
|
}
|
|
r.Header.Del("Content-Encoding")
|
|
return rd, nil
|
|
}
|
|
|
|
// Read one bounded body, decoded; callers choose their protocol's error
|
|
// envelope. The limit holds for the decoded bytes too.
|
|
func readBoundedRequestBody(w http.ResponseWriter, r *http.Request, limits requestLimits) ([]byte, int, error) {
|
|
controller := http.NewResponseController(w)
|
|
reject := func(status int, err error) ([]byte, int, error) {
|
|
// Do not let net/http drain a rejected body from a stalled client.
|
|
w.Header().Set("Connection", "close")
|
|
controller.SetReadDeadline(time.Now())
|
|
if r.Body != nil {
|
|
r.Body.Close()
|
|
}
|
|
controller.SetReadDeadline(time.Time{})
|
|
return nil, status, err
|
|
}
|
|
if limits.body <= 0 {
|
|
limits.body = defaultBodyLimit
|
|
}
|
|
if limits.readTimeout <= 0 {
|
|
limits.readTimeout = defaultBodyTimeout
|
|
}
|
|
if r.ContentLength > limits.body {
|
|
return reject(http.StatusRequestEntityTooLarge, overLimit(limits.body))
|
|
}
|
|
if err := controller.SetReadDeadline(time.Now().Add(limits.readTimeout)); err != nil && !errors.Is(err, http.ErrNotSupported) {
|
|
return reject(http.StatusInternalServerError, errors.New("could not set request body deadline"))
|
|
}
|
|
defer controller.SetReadDeadline(time.Time{})
|
|
readFailure := func(err error) ([]byte, int, error) {
|
|
var timeout net.Error
|
|
if errors.As(err, &timeout) && timeout.Timeout() {
|
|
return reject(http.StatusRequestTimeout, errors.New("request body read timed out"))
|
|
}
|
|
return reject(http.StatusBadRequest, err)
|
|
}
|
|
original := r.Body
|
|
r.Body = &idleBody{original, controller, limits.readTimeout}
|
|
defer func() { r.Body = original }()
|
|
rd, err := decodedBody(r)
|
|
if errors.Is(err, errBodyEncoding) {
|
|
return reject(http.StatusUnsupportedMediaType, err)
|
|
}
|
|
if err != nil {
|
|
return readFailure(err)
|
|
}
|
|
defer rd.Close()
|
|
// Limit decoded bytes as well, without allocating from Content-Length.
|
|
body, err := io.ReadAll(io.LimitReader(rd, limits.body+1))
|
|
if int64(len(body)) > limits.body {
|
|
return reject(http.StatusRequestEntityTooLarge, overLimit(limits.body))
|
|
}
|
|
if err != nil {
|
|
return readFailure(err)
|
|
}
|
|
return body, 0, nil
|
|
}
|
|
|
|
// overLimit says a body is over magpie's own limit, and that it is
|
|
// magpie's, not the provider's: an agent shows the message as it comes,
|
|
// and a bare "Payload Too Large" read as the model's or the vendor's
|
|
// (#1422). writeError adds what to do about it.
|
|
func overLimit(limit int64) error {
|
|
return fmt.Errorf("request body is over magpie's gateway limit of %s (decoded); the provider was not asked", sizeWord(limit))
|
|
}
|
|
|
|
// sizeWord is a byte count in MB, or in KB or bytes when it is smaller,
|
|
// for limits set low (a test's, a route's own).
|
|
func sizeWord(n int64) string {
|
|
switch {
|
|
case n >= 1<<20 && n%(1<<20) == 0:
|
|
return fmt.Sprintf("%d MB", n>>20)
|
|
case n >= 1<<10 && n%(1<<10) == 0:
|
|
return fmt.Sprintf("%d KB", n>>10)
|
|
}
|
|
return fmt.Sprintf("%d bytes", n)
|
|
}
|