Files
magpie/internal/provider/codex_zstd.go
T
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

79 lines
3.2 KiB
Go

package provider
import (
"bytes"
"io"
"net/http"
"net/url"
"strings"
"sync/atomic"
"github.com/klauspost/compress/zstd"
)
// Codex's own client sends a ChatGPT account's turns to the backend
// zstd-compressed, and nothing else: read in openai/codex at a9b08151,
// codex-rs/core/src/client.rs responses_request_compression (the
// enable_request_compression feature, on by default in
// codex-rs/features/src/lib.rs, a ChatGPT sign-in, the OpenAI provider)
// and codex-rs/http-client/src/request.rs, which compresses the body at
// level 3 and sets Content-Encoding: zstd. Only POST /responses is: an API
// key, another provider, /responses/compact and /models go plain.
//
// ylorn (X, v0.1.1202): a text-only gpt-6-luna turn of 1100224 bytes sent
// plain was answered 503, the same turn zstd-compressed (259 bytes) 200,
// and through magpie, which decoded Codex's zstd and sent the backend
// plain JSON, 503 again.
// codexZstd is level 3 (klauspost's SpeedDefault, "roughly equivalent to
// the default Zstandard mode (level 3)"), without the frame checksum,
// which libzstd leaves off by default. EncodeAll is safe to share.
// Codex's codex-rs/http-client/src/request.rs uses
// zstd::stream::encode_all(.., 3), whose unknown-size stream has a 2 MiB
// window. Keep turns within that client envelope too.
var codexZstd, _ = zstd.NewWriter(nil,
zstd.WithEncoderLevel(zstd.SpeedDefault),
zstd.WithEncoderCRC(false),
zstd.WithWindowSize(2<<20),
)
// codexZstdOff leaves turns plain, for tests alone: the fake backends of
// most of the gateway's and provider's tests read the body as it comes, so
// those packages' TestMain sets it (CodexZstdForTests(false)), and the
// tests of the compression clear it again.
var codexZstdOff atomic.Bool
// CodexZstdForTests sets whether turns to the ChatGPT backend go
// compressed, for a test, and returns what puts it back.
func CodexZstdForTests(on bool) (restore func()) {
was := codexZstdOff.Swap(!on)
return func() { codexZstdOff.Store(was) }
}
// CodexCompressed sends req's body, body, zstd-compressed as Codex's own
// client sends it, when req is a turn to the ChatGPT backend
// (CodexBase/responses), and as it is otherwise. It is called once the
// body is final and signed, and returns the bytes that go on the wire. The
// body is still the plain body everywhere magpie keeps or shows it.
func CodexCompressed(req *http.Request, body []byte) int {
if req.Method != http.MethodPost || codexZstdOff.Load() || !codexTurnURL(req.URL) {
return len(body)
}
if enc := req.Header.Get("Content-Encoding"); enc != "" && !strings.EqualFold(enc, "identity") {
return len(body) // already encoded: as Codex, never twice
}
z := codexZstd.EncodeAll(body, make([]byte, 0, len(body)/8+64))
req.Body = io.NopCloser(bytes.NewReader(z))
req.GetBody = func() (io.ReadCloser, error) { return io.NopCloser(bytes.NewReader(z)), nil }
req.ContentLength = int64(len(z))
req.Header.Del("Content-Length")
req.Header.Set("Content-Encoding", "zstd")
return len(z)
}
// codexTurnURL is CodexBase's /responses, where Codex sends a turn.
func codexTurnURL(u *url.URL) bool {
base, err := url.Parse(CodexBase)
return err == nil && u != nil && strings.EqualFold(u.Host, base.Host) && u.Path == base.Path+"/responses"
}