Commit Graph
5 Commits
Author SHA1 Message Date
yetone 106a245502 gateway: a request's body goes once it is answered, not when its stream ends (#3383)
The transport holds a request until its reply's body is closed, a
stream's whole length, and with it the bytes.Reader body and the GetBody
NewRequest made over it. So every streaming request kept the body it
sent upstream alive to its end: for a Claude Code request translated to
Chat, the marshalled body (marshalRaw/appendHTMLEscaped in the report's
heap, 503 MB live).

provider.SetBody gives a request a body whose reader drops its bytes
once read and whose GetBody reads them again until provider.LetGo.
forwardOnce lets go once its retries (RetryOneAuth, RetryZhipuCoding)
are done; Codex's zstd turn, Copilot Auto's model swap and Gemini's Code
Assist envelope set their bodies the same way, so LetGo reaches them.

Run (worktree perf-stack, on the four commits before it, over
origin/main 137187a40):
- a heap probe, 8 Claude Code requests of 4.7 MB held mid-stream to a
  Chat upstream: 152 MB held before, 88 MB after; the rest is the body
  as it came (another member) and as read (a continuation). Anthropic
  to Anthropic holds the body once, 41 MB.
- TestStreamingRequestsLetTheirSentBodyGo (bar 3x the body each) and
  TestSetBodyLetsItsBytesGo: green; red with LetGo commented out of
  forwardOnce ("8 streaming requests of 4 MB hold 166 MB, 4.2 times the
  body each") and with LetGo storing nothing ("the request holds its
  body's bytes after it was answered").
- go test ./internal/provider/ ./internal/redact/ ok; ./internal/gateway
  -run 'Mask|Redact|Codex|Copilot|Gemini|Google|Antigravity|Zhipu|Auth|
  Retry|Stream|Continu' ok; GOOS=linux and windows vet -tags nogui
  clean, gofmt clean. The full suite runs at the pushed head.
Not tried: a real vendor; the bytes on the wire are the same.
2026-10-24 21:00:05 +08:00
yetone a2e98cd799 gateway: a streamed Codex turn goes to ChatGPT over its WebSocket (brickhao)
brickhao on Discord: long Codex turns through magpie died with "stream
closed before response.completed". Their network (FlClash) cuts a
streamed HTTP reply from chatgpt.com at about 120 s: 120.7 s through
magpie, 121.5 s over HTTP without magpie. Codex's own WebSocket to the
same backend ran to the end twice (124.5 s, 131.4 s). magpie has no
120 s timer of its own (no WriteTimeout, 10 min to the first header).
The cut is on the leg from magpie to chatgpt.com, which was always
HTTP. Codex answers magpie's 426 by falling back to HTTP, and over
loopback that is harmless.

What changed: codexSocket, first in upstreamTransport, sends a POST to
CodexBase/responses with "stream":true over the backend's WebSocket, as
codex-rs does (ResponseCreateWsRequest, build_websocket_headers).
- Handshake: the turn's headers plus OpenAI-Beta:
  responses_websockets=2026-02-06. x-codex-turn-state and the
  responses-lite header go in client_metadata instead. The message is
  the body (zstd decoded) with "type":"response.create" ahead of it.
- Frames come back as the SSE the HTTP route sends.
  codex.rate_limits and codex.response.metadata are also given as the
  x-codex-* and x-codex-turn-state headers. websocket_timing is dropped.
- An error frame ahead of the reply becomes its HTTP status and body,
  so account rests and failover work as before.
- These go over HTTP: a refused handshake (and the host stays on HTTP
  for 10 min, unless the refusal was 401/429/5xx),
  websocket_connection_limit_reached, and a body that isn't a streamed
  turn.
- A socket closed before the end reads as a cut stream.
- Both Codex's own sign-in passthrough and magpie's ChatGPT accounts
  take this path. Codex identity, instructions and prompts are
  unchanged. coder/websocket is now a direct dependency (it was
  indirect).

Run:
- gofmt -l clean; go vet darwin, GOOS=linux -tags nogui, GOOS=windows ok.
- go test -race -count=3 of the five new tests: ok.
- go test -timeout 45m at 1a5911612 (rebased on origin/main c551a2299),
  sandbox HOME: internal/gateway ok 760.9s, internal/agent ok 596.8s,
  internal/provider ok 172.5s. The rest of ./... was not run before the push.
- Real: a sandbox magpie (this tree, 127.0.0.1:3488, sandbox HOME and
  CODEX_HOME, a copy of the Codex access token with the refresh token
  blanked so nothing could rotate). A curl turn on gpt-6-luna came back
  200 with codex.rate_limits in the SSE (which only the socket sends)
  and the x-codex-* headers. Real Codex CLI 0.162.1 (codex exec,
  xhigh) through it: a 6121-word reply over 165 s ended whole, exit 0.
  Codex logged its own 426 from magpie and fell back, as expected.

Broken by hand:
- socket off in the tests: all four socket tests red (the reply cut
  before response.completed, no handshake, 200 not 429).
- error-frame mapping off: TestCodexSocketErrorIsItsStatus red.
- turn-state into client_metadata off: TestCodexTurnGoesOverWebSocket
  red.

Not tried:
- brickhao's network: this network doesn't cut at 120 s, so the 165 s
  turn shows the socket carries a long turn whole, not that it gets
  past their cut.
- A real turn on a magpie-saved ChatGPT account (fake only).
- Through an HTTP or SOCKS proxy for real.
- Windows/Linux runs.
2026-10-23 23:59:55 +08:00
yetone 9b72add51d provider: Codex's zstd encoder keeps two coders, not one per core, and holds ~9 MB instead of ~80
A live gateway (v0.1.1290, 48 minutes up, ~50 Claude Code and Codex
sessions on a 14-core Mac) had a 288 MB heap, and 74 MB of it was the
shared zstd encoder that compresses ChatGPT turns: klauspost's EncodeAll
keeps a coder per GOMAXPROCS, and each keeps its 4 MiB history (2 MiB
window) and tables for the life of the process (pprof inuse_space:
fastBase.ensureHist 56 MB, encoderOptions.encoder 17.8 MB).

The encoder now keeps two coders (WithEncoderConcurrency(2)) in
low-memory mode (WithLowerEncoderMem). A 1 MiB turn encodes in about
half a millisecond, so two keep up. Neither option changes the frame:
measured on 28 concurrent 1 MiB turns on this Mac:

  default         retained 84.1 MB  13.2ms  28054 bytes  round-trips
  conc2+lowmem    retained  8.9 MB  13.8ms  28054 bytes  round-trips

TestCodexZstdHoldsLittle sets GOMAXPROCS 16, encodes 28 turns at once
and fails above 24 MB. With the two options removed by hand it fails
("the encoder holds 88 MB after 28 turns at once"); with them it passes
(-count=5).

Run on 129d8b08a + this change, macOS, load ~100-115:
- go test -run 'TestCodexZstd|TestCodexCompressed|TestCodexWarmGoesZstd'
  -count=3 ./internal/provider/: ok
- go vet ./internal/provider/, GOOS=linux go vet -tags nogui, GOOS=windows
  go vet -tags nogui on the package: ok; gofmt -l: clean
- go test -timeout 45m ./...: every package ok except internal/agent,
  which ran out at 2709.7s (#2544, the same timeout at load). That package
  alone on the same tree: ok in 1363.1s. TestOwnProviderNamedAsMagpies,
  at the deadline, passes alone in 17.9s.

The frames are byte for byte the old ones: the default and the new
encoder compressed 303 bodies from this Mac's own ~/.codex/sessions
rollouts (whole, cut at 1 MiB and at 3 MiB, read locally, sent nowhere)
to identical bytes. So what reaches the backend is unchanged; a live
Codex turn through the new build was not run.
2026-10-19 18:02:56 +08:00
yetoneandpc418 0eab029ea7 provider: a ChatGPT account's turn is zstd-compressed with at most Codex's own 2 MiB window, not 8 MiB (#2739, pc418)
codexZstd (internal/provider/codex_zstd.go) set no window, so klauspost's
encoder declared its default 8 MiB (and, single-segment, up to the body
size below that) on every turn magpie re-compresses for the ChatGPT
backend: the accounts loop (forwardOnce), the native relay
(codexUpstreamOn) and warm-up all go through CodexCompressed. Codex's own
client never sends that: openai/codex ce0323f2
codex-rs/http-client/src/request.rs compresses with
zstd::stream::encode_all(Cursor, 3); zstd 0.13.3 (Codex's Cargo.lock)
copy_encode streams through Encoder::new(dest, 3) with the size unknown,
which libzstd 1.5.7 gives level 3's windowLog 21 (2 MiB). pc418's
15,173,526-byte image-heavy turn got 400 in the 8 MiB frame and 200 at
2 MiB; a later replay of the 8 MiB bytes was taken, so this matches the
client's envelope rather than proving a backend limit. Level and checksum
are unchanged. Cost: a large turn is bigger on the wire at 2 MiB with
SpeedDefault (pc418's turn 7.59 MB -> 12.44 MB; libzstd -3 gives 9.78 MB).

Reviewed and run (reviewer, at this commit on 89521b03d):
- Source checked: request.rs on openai/codex main ce0323f2 (encode_all,
  level 3), Cargo.lock zstd 0.13.3, zstd-rs v0.13.3 copy_encode.
- libzstd check: a 9.4 MB fixture with a 3 MiB random block repeated
  ~4 MiB apart. `zstd -3` from stdin: Window Size 2.00 MiB, 6,293,668 B.
  The old encoder's frame: 8.00 MiB window, 4,297,564 B, and
  `zstd -d --memory=2MB` refuses it ("Window size larger than maximum:
  8388608 > 2097152"). This commit's frame: 2.00 MiB window, 8,377,219 B,
  and `zstd -d --memory=2MB` decodes it to the same bytes. (For the record,
  SpeedBetterCompression at 2 MiB gave 6,293,661 B, libzstd's size; not
  changed here.)
- TestCodexCompressedLargeImageTurn fails with the option removed:
  "zstd frame window = 8388608 bytes, want at most 2 MiB"; passes with it.
- The gateway zstd tests in gateway-routing.md's commands pass;
  -race -count=3 on the new test passes.
- gofmt -l clean; go vet ./... and -tags nogui (darwin), GOOS=linux and
  GOOS=windows go vet -tags nogui ./...: clean; go build, GOOS=linux go
  build -tags nogui, GOOS=windows go build: ok.
- Full suite: see the #2727 commit after this one, run at that head with
  both changes.
- Not run: a real ChatGPT account through magpie (pc418 ran real native
  relay and account-pool image turns at 2 MiB: 200 each).

Co-authored-by: pc418 <271863285+pc418@users.noreply.github.com>
2026-10-17 23:02:36 +08:00
yetone 8f2a314cf9 gateway: a ChatGPT account's turn goes zstd-compressed, as Codex's own client sends it (ylorn on X)
ylorn (X, v0.1.1202) sent a text-only gpt-6-luna turn of 1,100,224 bytes
straight to chatgpt.com/backend-api/codex/responses. Sent plain it got 503.
The same turn zstd-compressed (259 B) got 200. magpie decodes Codex's
inbound zstd and sent the backend plain JSON, so the turn got 503 through
magpie too.

What Codex does (openai/codex a9b08151, 2026-10-11):
- codex-rs/core/src/client.rs:1704-1712 responses_request_compression:
  Zstd only with the enable_request_compression feature, a sign-in that
  uses_codex_backend, and the OpenAI provider.
- client.rs:1780: used for the POST /responses stream only.
  /responses/compact and /models go plain.
- codex-rs/features/src/lib.rs:1411-1416: the feature is Stable and on by
  default.
- codex-rs/protocol/src/auth.rs:54-63: uses_codex_backend is true for the
  ChatGPT sign-ins and false for ApiKey and Bedrock.
- codex-rs/codex-api/src/endpoint/responses.rs:130-147 sets it for
  /responses.
- codex-rs/http-client/src/request.rs:196-217 compresses with
  zstd encode_all at level 3, sets Content-Encoding: zstd, and never
  compresses twice.

What changed:
- provider.CodexCompressed compresses a body sent to CodexBase/responses
  with klauspost zstd, already a dependency. It uses SpeedDefault (about
  level 3) and no frame checksum, like libzstd's default. It sets
  Content-Encoding, Body, GetBody and ContentLength to the compressed
  bytes, and returns the wire size.
  - It is called once the body is final and signed: in forwardOnce for a
    codex account, in codexUpstreamOn (the relay) on every try (so a try
    again or a body without an unreadable image is compressed afresh), and
    in warmCodex.
  - Unchanged: /responses/compact, an sk- key's requests to api.openai.com,
    every key provider (even one at the same URL), and a body already
    encoded.
  - The plain body is still what magpie keeps, masks, traces and shows.
- codexDropped (#1628, a2b96139c/8029d98b7) judges "large request" by the
  bytes sent on the wire. A text turn that compresses to a few KB and is
  reset is a small request's 503, not a "MiB" hint asked again. A
  screenshot's random bytes stay past 1 MiB, and those are still asked
  again.
- The gateway and provider TestMains leave turns plain
  (CodexZstdForTests), since their fake backends read the body as JSON.
  The new tests turn it on.
- TestAsksOwnBackendAgreesWithTheGatewayDispatch read any call whose sixth
  letter is upper case (CodexCompressed) as a serveX dispatch. It now
  needs the "serve" prefix. Removing "kiro" from asksOwnBackend still
  turns it red.
- docs/subsystems/gateway-routing.md: the "sent plain JSON" line now names
  this exception.

Tests: internal/gateway/codex_zstd_test.go covers the accounts loop, the
relay (inbound zstd and plain), a try again after a drop, compact and an
API key plain, a key provider at the same URL plain, and a reset judged by
wire bytes. internal/provider/codex_zstd_test.go covers the round trip,
GetBody, Content-Length and the URLs left alone. Broken by hand, each went
red:
- no compression in forwardOnce: Account and AskedAgain
- no compression in the relay: Relayed, AskedAgain and JudgedByBytes
- no account guard: KeyProviderTurnStaysPlain
- compact compressed: CompactAndAPIKeyStayPlain
- the drop judged by len(body): JudgedByTheBytesSent

Real account (the owner's ChatGPT sign-in, gpt-6-luna, 1,100,279 B
text-only body, 391 B zstd):
- Direct to chatgpt.com, twice: plain 200/200, zstd 200/200. ylorn's 503
  did NOT reproduce from here (a2b96139c also saw 0.5-20 MiB served). The
  change rests on the official client's behaviour.
- Through a sandbox magpie (own HOME, :3486) via a byte-counting CONNECT
  proxy:
  - Old build: relay-zstd, relay plain and the account path were 200, 200,
    200, with 3,321,579 B uploaded to chatgpt.com.
  - New build: 200, 200, 200, with 13,362 B uploaded. Each 1.1 MB turn now
    goes as a few KB, as Codex sends it.

Run at origin/main e21ea07e4:
- go test ./... was all ok after the dispatch-test fix. The provider,
  agent and gateway packages were rerun.
- go test -race -count=3 on the new tests.
- gofmt -l is clean.
- go vet: darwin and windows ./... ok. linux ok for the changed packages.
  linux ./... fails the same on clean e21ea07e4 (wails v3's cgo-only Linux
  files, cross-vet from macOS).
2026-10-12 16:09:52 +08:00