ac4af582301a4e8a29245dbba767eba31334ddf9
10
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
e710160df1 |
gateway: a request body a little over a doubling is not copied whole again for its last bytes (#5281)
readSized grows its slice by doubling up to the declared length. A body just over a power of two was read into 1+2+...+512 MB and then copied whole into a final 516 MB slice for its last 4 MB: about 1.5 GB allocated and copied outside the body's wait, which counts toward the 30s unrouted cut. TestCodexGeneratedImagesPastOldLimit sends such a 516 MB turn and was answered 504 on main CI's Race step (34s). Now, once the declared length is within a quarter of the next doubling, the slice grows straight to it. The worst case over all lengths goes from 3x the body allocated to 2.6x (computed over every length up to 600 MB in 16 KB steps). A body shorter than it said is still capped by what it declared. Run on mote: - new TestRequestBodyNotCopiedForItsLastBytes (4 MB + 64 KB in 64 KB reads, at most twice its size allocated): red on the old code, 11600416 bytes for 4259840; green on the fix. - go test -race -run 'TestCodexGeneratedImagesPastOldLimit|TestRequestBody| TestDecodeJSON|TestJSONValid|Held|TestReadSized|LargeBody|OldLimit' ./internal/gateway: ok 114.9s, with this commit and the two after it. - go vet ./internal/gateway on darwin, GOOS=linux and GOOS=windows: ok. gofmt -l: clean. - The full suite and race shards are recorded in the last commit of this set. Not tried: a real Codex client sending a 516 MB turn. |
||
|
|
fd85c0a1e9 |
gateway: a test's memory root reads nothing of the machine it runs on (#5118)
TestCodexBodyLimitFromMemory's "unknown" case is red on every Linux
machine with more than 8 GiB: ubuntu CI ("unknown: 998 MiB" in the Test
job at
|
||
|
|
694f4a6d65 |
gateway: a Codex turn of its own reads past 512 MB, to a sixteenth of the machine's memory (dallascao)
dallascao on Discord: generating images in Codex and revising them again
and again, magpie answered 413 "request body is over magpie's gateway
limit of 512 MB (decoded); the provider was not asked" on
127.0.0.1:3425/backend-api/codex/responses, while Codex signed in to
OpenAI directly went on. The count was right: Codex keeps each image it
generated in the conversation (a function_call_output input_image, a
~3 MB PNG as ~4 MB base64; codex-rs ext/image-generation to_response_item,
and history keeps image_generation_call results), and over HTTP sends the
conversation whole every turn, so ~130 images is 512 MB decoded. To
OpenAI directly Codex uses its WebSocket and sends a delta.
- Codex's own path (codexBackend, the Codex relay, the Responses
WebSocket's read limit, keyLimited on CodexPath) reads to
codexBodyLimit: a sixteenth of the machine's memory (memLimit, else
proc.MemTotal), 512 MB at least, 2 GB at most. 16 GB: 1024 MB,
24 GB: 1536 MB, 32 GB+: 2048 MB, 8 GB or unknown: 512 MB as before.
It is still the bomb guard: nothing decodes past it, and the zstd
decoder keeps its window bound.
- A turn for a magpie model ("provider/model") on that path is held to
the 512 MB of every other route once its model is read: it is
translated, at several times its size. Its 413 says one of Codex's own
models takes up to codexBodyLimit; writeError's /compact hint stays.
- provider.codexNamesBad read tools/input/tool_choice with
GetManyBytes, which copied the whole input (the body's size: 300 MB of
a 300 MB turn in the alloc profile). It reads in place now.
Cost at the largest input (mote, a relayed gpt-5.5 turn of random
~3 MB images, heap objects sampled every 5ms, load ~350): 300 MB took
4.7s, 600 MB 7.7s, 1000 MB 11.9s, peak heap 1.5 to 2.1 GB past the
body's own bytes. The rest of the cost is io.ReadAll growing the decoded
body and fillJSONIn/exchangeOf; bodyRoom still runs a body bigger than
its room alone.
Run at the pushed head (mote): gofmt -l clean; GOOS=linux and
GOOS=windows go vet ./internal/gateway ./internal/provider ok;
go test -timeout 45m ./internal/provider ok, ./internal/gateway ok but
TestCompactionOverByteCapEveryTime, red in the full package run only
(#4862, filed before this; passes alone 3 of 3 here).
TestRequestBodyTooLarge/codex now sends codexBodyLimit+1.
- TestCodexGeneratedImagesPastOldLimit (16 GB machine fixture, a 516 MB
turn of generated images in Codex's shape): reaches the fake ChatGPT
backend whole in ~6s; the same turn for x/gpt-5 is 413 naming
"one of Codex's own models takes up to 1024 MB".
- TestCodexBodyLimitFromMemory: 2/8/16/24/64 GiB and unknown memory.
Broken by hand: codexBackend reading with limit 0 (the old code) makes
TestCodexGeneratedImagesPastOldLimit red with the reporter's 413; the
magpie-model check turned off makes it red (404 from routing, not 413).
Not tried: the reporter's own session or a real Codex image-generation
run through magpie; a turn past 1 GB on a 16 GB machine; the WebSocket's
raised read limit has no test of its own.
|
||
|
|
0c17aac2d7 |
gateway: large request bodies wait their turn for a share of memory (#4004)
One request's limit (512 MB decoded) bounded no sum. Each body is held while its request is served, with what is made from it (the model rewritten, a translation to Chat, a plugin's base64 line), and on jihuayu's 2 GiB server Codex turns of ~45 MiB side by side held the Go heap at ~500 MiB and the plugin host at ~500 MiB, into swap. bodyRoom now holds a request body of 1 MiB or more to a share of the memory magpie may use: a thirty-second of memLimit on Linux (the cgroup's limit, else MemTotal), of the computer's memory elsewhere, 64 MiB at least; no bound where memory isn't known. A request takes room on its Content-Length before its body is read, so the ones waiting don't hold theirs, and on the body read (a compressed one is bigger than it said). It waits first come first served, a body bigger than the room runs alone, the room is given back when the request ends, and a body that waits 100s is answered 503 saying what is held and that the provider was not asked. The wait is a known one to the pre-routing watch (noteWait), which otherwise answered it 504 at 30s. Small bodies, an agent's ordinary turns, pass without counting. On jihuayu's 1,670 MiB server that is one ~45 MiB body at a time. Measured on mote, 8 concurrent 44 MiB Responses turns to a Chat-only fake provider (largeConversation, 1s upstream), peak Go HeapInuse sampled every 5ms: no room 2,166-2,396 MiB, all 8 in ~2.1s; a 64 MiB room 459 MiB, all 8 answered 200 in 13.5s. One such turn alone peaks at 337 MiB (the translation's own copies, next). Run first at |
||
|
|
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 ( |
||
|
|
077c472053 |
gateway: a zstd request body is decoded by a decoder kept between requests
Codex sends every turn's body zstd. decodedBody made a new zstd decoder
for each one, with the package's default concurrency: it started a
stream goroutine and allocated its window and block buffers on every
request. In the procmem profile (a sandbox `magpie web` on main, three
Codex-style sessions sending zstd /v1/responses every 2-4s plus Chat and
Messages traffic, ~1,000 requests in 10 minutes) that was 1.74 GB of the
9.8 GB allocated, all under zstd.(*Decoder).startStreamDecoder.
Now a sync.Pool keeps decoders (concurrency 1, the same 512 MB memory
bound), as sessions' packed reads do since
|
||
|
|
68133754a3 |
gateway: a request's body is read in place, not copied by every reader (yg6888 on X: ~1 GB)
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
|
||
|
|
1a44670302 |
gateway: a long Codex session full of images is read up to 512 MB, and magpie's 413 says it is magpie's limit and to /compact (#1422, NeoPengZhile)
NeoPengZhile's Codex (signed in to ChatGPT, through /backend-api/codex/ responses) got "413 Payload Too Large: request body exceeds gateway limit" on all five reconnects in a long session that had read many images; a new session worked. Codex sends the whole conversation every turn, screenshots inline as base64, zstd-compressed; magpie's limit is on the decoded body and was 128 MB, while magpie compresses a ChatGPT turn again on the way out, so the backend sees about what Codex alone would send. The message didn't say whose limit it was or what to do. What changed: - request_bounds.go: defaultBodyLimit 128 MB -> 512 MB (decoded, which also sets the zstd decoder's memory cap). Every route that reads with the default gets it, keyLimited's read among them, so a limited key isn't held to the old number first. Routes with their own lower limit (System One 16 MB, a Claude subscription's 16 MB) keep it. - overLimit: magpie's own 413 says "request body is over magpie's gateway limit of 512 MB (decoded); the provider was not asked". - gateway.go writeError: the hint added to a 413 now says it is a byte limit, not the model's context, and to /compact (Codex, Claude Code) or start a new conversation. - request_bounds_test.go: TestRequestBodyTooLarge uses defaultBodyLimit+1 in place of a literal 129 MB. - docs/subsystems/gateway-routing.md says so. Run: go test ./internal/gateway/ -count=1 (ok, 354s), with the new TestImageHeavyCodexTurnIsRead (a zstd body of inline images decoding to 136 MB on Codex's backend path, read with the default limits) and TestOverLimitSaysWhoseAndWhatToDo; go test ./internal/gui/ (ok); go vet ./... on darwin, GOOS=linux -tags nogui and GOOS=windows; gofmt -l. Broken by hand: the limit back at 128 MB -> TestImageHeavyCodexTurnIsRead fails with the 413; the old "exceeds gateway limit" message, or the old hint, -> TestOverLimitSaysWhoseAndWhatToDo fails. Not tried: the reporter's real session, or how big a turn the ChatGPT backend itself takes; the test's images repeat, so its wire size is far smaller than real screenshots'. Peak memory for a turn near 512 MB was not measured. |
||
|
|
b6f33753ce |
gateway: a gzip or zstd request body is read on every route, so Codex with a custom provider on /v1/responses no longer gets "expected a JSON object" (#1223)
Only the Codex backend path decoded a Content-Encoding (codexReader); /v1/responses, /v1/chat/completions, /v1/messages, count_tokens, Gemini's routes, embeddings, images, videos and System One read the compressed bytes as JSON. Codex sends zstd to a custom provider's /v1/responses by default. readBoundedRequestBody now always decodes (decodedBody, moved from codexReader): identity, gzip and zstd are read, the header is dropped so the provider gets plain JSON, the size limit holds for the decoded bytes (413), and any other encoding is refused 415 naming it. keyLimited reads a limited key's compressed body the same way, so its reservation is the decoded size, not the compressed one. Verified: request_encoding_test.go posts real gzip and zstd bodies to a running httptest server of New().Handler() on every route. Without the change TestEncodedBodiesOnEveryRoute and TestEncodedEmbeddingsBody fail with 400 "expected a JSON object" / "the body isn't a JSON object", TestEncodedBodyInflatedPastLimit gets 400 instead of 413, TestUnknownBodyEncodingRefused gets 400/502 instead of 415, and with only key_limit.go reverted TestKeyLimitReservesDecodedBody fails "held at 19 tokens for a 40061-byte body sent as 79 bytes". gofmt; go vet -tags nogui ./internal/gateway for GOOS linux, windows, darwin; go test -tags nogui ./internal/gateway (temp HOME, pinned caches) ok; the new tests -race -count=5 ok. Not tried with the real Codex CLI. |
||
|
|
74fa1ca51d |
gateway: bound individual body reads without limiting streams (#553)
* gateway: bound individual body reads without limiting streams * gateway: renew upload deadlines on progress and cover remaining body readers |