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).
This commit is contained in:
@@ -30,7 +30,7 @@ served by a plugin are in [Provider and plugin ownership](provider-plugins.md).
|
||||
|
||||
## Runtime path
|
||||
|
||||
1. `handle(proto)` reads the body and the model (`requestBody`, `requestModel`), then calls `serveAgent`. Every route that reads an agent's body (each API, count_tokens, Gemini's, embeddings, images, videos, System One, the Codex backend path) reads it through `readBoundedRequestBody` in [`request_bounds.go`](../../internal/gateway/request_bounds.go). It decodes a `Content-Encoding` of `gzip` or `zstd` (`decodedBody`; Codex sends zstd to a custom provider's `/v1/responses` too, #1223) and drops the header, so the provider is sent plain JSON. The size limit holds for the decoded bytes (413), and any other encoding is refused 415. `keyLimited` reads a limited key's compressed body the same way, so its reservation is the decoded size. `serveAgent` runs the [middleware](gateway-middleware.md) chain, then `serve`.
|
||||
1. `handle(proto)` reads the body and the model (`requestBody`, `requestModel`), then calls `serveAgent`. Every route that reads an agent's body (each API, count_tokens, Gemini's, embeddings, images, videos, System One, the Codex backend path) reads it through `readBoundedRequestBody` in [`request_bounds.go`](../../internal/gateway/request_bounds.go). It decodes a `Content-Encoding` of `gzip` or `zstd` (`decodedBody`; Codex sends zstd to a custom provider's `/v1/responses` too, #1223) and drops the header, so the provider is sent plain JSON, with one exception: a ChatGPT account's turn (POST `CodexBase`/responses, from the accounts loop in `forwardOnce` or relayed by `codexUpstreamOn`) is compressed again with zstd, as Codex's own client sends it (`provider.CodexCompressed`; openai/codex `responses_request_compression`). It is compressed once the body is final, and again on each try. `/responses/compact`, an API key's requests and every other provider stay plain. Sent plain, a 1.1 MB text-only turn was answered 503 (ylorn on X). The plain body is what magpie keeps and shows, and `codexDropped` judges a reset by the bytes that went on the wire. The size limit holds for the decoded bytes (413), and any other encoding is refused 415. `keyLimited` reads a limited key's compressed body the same way, so its reservation is the decoded size. `serveAgent` runs the [middleware](gateway-middleware.md) chain, then `serve`.
|
||||
2. `serve` redacts secrets in the request (`redacted`; `redact.MaskJSON` leaves ids alone, and what the vendor sealed with a signature, a thinking block, Gemini's thoughts or Responses' encrypted reasoning, goes back as the vendor wrote it: only the values masked elsewhere in the request, and secrets masked before, are put back as their placeholders; a value masked once, at least 8 characters long, is masked again wherever a request has it, as an exact match whatever words are around it, so what the vendor wrote about a placeholder doesn't go back with the value in it, `redact/known.go`), resolves the model to a provider or a group, and refuses what can't be served. A request whose provider and fallbacks, or whose group's models, all skip redaction (`unredactedRoute`, `provider.SkipsRedaction`: set *Send requests unmasked*, `Unredacted`, with every address on this machine or the local network) goes to them as the agent wrote it; the log and recent calls keep the masked body. count_tokens and embeddings follow the same rule.
|
||||
- With *Mask personal data* on, each kind in `redact.Categories` ([`internal/redact/more.go`](../../internal/redact/more.go)) is masked unless the user turned it off (`redactKinds` in settings, `Options.Kinds`). On by default: US SSNs, passport numbers, IBANs that pass mod 97, birthdays next to a word that says so, MAC addresses, and serial numbers next to S/N or the like. Off by default: the user name in a home folder, user@host in a prompt or ssh command, public IPv4 and IPv6 addresses (never private, loopback, link-local, CGNAT or documentation ranges) and cloud bucket names, since agents send them in nearly every request and the model must copy the placeholder exactly inside a path or URL. Context rules run only near their words (`rule.matches`). The Settings rows come from `REDACT_KINDS` in app.js, which `TestRedactKindsAreRedacts` holds to the same ids and defaults.
|
||||
- With *Mask secrets* on, the user's own masking rules (`redactRules`, `redact.Rule`: a placeholder name and a prefix or an RE2 pattern, [`internal/redact/rules.go`](../../internal/redact/rules.go)) run before magpie's. Settings → Privacy adds them, removes them, and edits one in place (`POST /api/settings/redact-rule` with the rule's index and its current value, `editRedactRule` in [`internal/gui/api.go`](../../internal/gui/api.go)). Every rule is checked by `redact.CheckRules` when settings are saved; an edit that doesn't compile, matches the empty string, repeats another rule or names a rule no longer at that index is refused with the rules left as they were. The gateway reads the rules from settings on each request (`redactionOptions`), so a change applies to the next request.
|
||||
|
||||
@@ -698,6 +698,7 @@ func (s *Server) codexUpstreamOn(w http.ResponseWriter, r *http.Request, rest st
|
||||
autoReset := false // a Codex reset looked at, once
|
||||
resetNote := "" // what spending it did, for the request log
|
||||
resets := 0 // times a large request ChatGPT closed on was asked again (#1628)
|
||||
sent := len(body) // the bytes that went, compressed (provider.CodexCompressed)
|
||||
for tries := 0; ; tries++ {
|
||||
ctx := provider.ViaSignedIn(r.Context(), "codex")
|
||||
if on != nil {
|
||||
@@ -727,6 +728,9 @@ func (s *Server) codexUpstreamOn(w http.ResponseWriter, r *http.Request, rest st
|
||||
}
|
||||
// left to the transport, the reply comes back plain for the usage in it
|
||||
req.Header.Del("Accept-Encoding")
|
||||
// a turn to ChatGPT goes zstd-compressed again, as Codex sent it
|
||||
// before magpie read it (ylorn on X); an API key's goes plain
|
||||
sent = provider.CodexCompressed(req, body)
|
||||
if res, err = s.client.Do(req); err != nil {
|
||||
msg := "OpenAI: " + err.Error()
|
||||
if rest == "/responses" {
|
||||
@@ -752,7 +756,7 @@ func (s *Server) codexUpstreamOn(w http.ResponseWriter, r *http.Request, rest st
|
||||
}
|
||||
}
|
||||
}
|
||||
if rest == "/responses" && base != codexAPIBase && res.StatusCode == http.StatusServiceUnavailable && len(body) >= codexDropBody && resets < lastRetries {
|
||||
if rest == "/responses" && base != codexAPIBase && res.StatusCode == http.StatusServiceUnavailable && sent >= codexDropBody && resets < lastRetries {
|
||||
// ChatGPT closed the connection before answering a large
|
||||
// request, which often passes (#1628): asked again after a
|
||||
// moment, as the accounts loop asks its last one again
|
||||
@@ -792,7 +796,7 @@ func (s *Server) codexUpstreamOn(w http.ResponseWriter, r *http.Request, rest st
|
||||
if base != codexAPIBase {
|
||||
// still closed on after that: Codex is told what may help,
|
||||
// at the 503 it asks again for (#1628)
|
||||
res = codexDropped(res, len(body))
|
||||
res = codexDropped(res, sent)
|
||||
}
|
||||
}
|
||||
defer res.Body.Close()
|
||||
|
||||
@@ -0,0 +1,283 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/klauspost/compress/zstd"
|
||||
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
// zstdTurns sends turns to the ChatGPT backend compressed, as the gateway
|
||||
// does outside tests (TestMain leaves them plain for the other fakes).
|
||||
func zstdTurns(t *testing.T) {
|
||||
t.Helper()
|
||||
t.Cleanup(provider.CodexZstdForTests(true))
|
||||
}
|
||||
|
||||
// sentTurn is one request as the stand-in ChatGPT backend got it.
|
||||
type sentTurn struct {
|
||||
path, encoding, account string
|
||||
wire int // bytes on the wire
|
||||
length int64 // Content-Length said
|
||||
body []byte
|
||||
}
|
||||
|
||||
// turnsBackend is a ChatGPT backend that does what ylorn's did (X,
|
||||
// v0.1.1202): a plain body of 1 MiB or more is answered Envoy's 503, the
|
||||
// same body zstd-compressed is served. drop more answers that 503 to a
|
||||
// body whose wire bytes are 1 MiB or more, compressed or not, that many
|
||||
// times. Every request is decoded and kept.
|
||||
func turnsBackend(t *testing.T, drop int) (*[]sentTurn, *sync.Mutex) {
|
||||
t.Helper()
|
||||
var mu sync.Mutex
|
||||
var got []sentTurn
|
||||
up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
wire, _ := io.ReadAll(r.Body)
|
||||
s := sentTurn{path: r.URL.Path, encoding: r.Header.Get("Content-Encoding"), account: r.Header.Get("chatgpt-account-id"),
|
||||
wire: len(wire), length: r.ContentLength, body: wire}
|
||||
if s.encoding == "zstd" {
|
||||
d, _ := zstd.NewReader(nil)
|
||||
b, err := d.DecodeAll(wire, nil)
|
||||
d.Close()
|
||||
if err != nil {
|
||||
t.Errorf("a zstd body that doesn't decode: %v", err)
|
||||
}
|
||||
s.body = b
|
||||
}
|
||||
mu.Lock()
|
||||
got = append(got, s)
|
||||
dropping := len(wire) >= 1<<20 && (s.encoding == "" || drop > 0)
|
||||
if dropping && s.encoding != "" {
|
||||
drop--
|
||||
}
|
||||
mu.Unlock()
|
||||
if !json.Valid(s.body) {
|
||||
t.Errorf("not JSON as the backend reads it (%s): %.80q", s.encoding, s.body)
|
||||
}
|
||||
if dropping {
|
||||
w.Header().Set("Content-Type", "text/plain")
|
||||
w.Header().Set("Server", "cloudflare")
|
||||
w.WriteHeader(http.StatusServiceUnavailable)
|
||||
io.WriteString(w, edgeDropped)
|
||||
return
|
||||
}
|
||||
io.WriteString(w, sse(
|
||||
`data: {"type":"response.created","response":{"id":"r1","model":"gpt-6-luna"}}`,
|
||||
`data: {"type":"response.output_text.delta","delta":"pong"}`,
|
||||
`data: {"type":"response.completed","response":{"id":"r1","usage":{"input_tokens":7,"output_tokens":1}}}`))
|
||||
}))
|
||||
t.Cleanup(up.Close)
|
||||
was := provider.CodexBase
|
||||
provider.CodexBase = up.URL + "/backend-api/codex"
|
||||
t.Cleanup(func() { provider.CodexBase = was })
|
||||
return &got, &mu
|
||||
}
|
||||
|
||||
// textTurn is ylorn's turn: text alone, about n bytes of it, no image.
|
||||
func textTurn(n int) string {
|
||||
line := "The quick brown fox jumps over the lazy dog while magpie relays this text-only request. "
|
||||
b, _ := json.Marshal(map[string]any{"model": "gpt-6-luna", "stream": true, "input": []any{
|
||||
map[string]any{"type": "message", "role": "user", "content": []any{
|
||||
map[string]any{"type": "input_text", "text": strings.Repeat(line, n/len(line)+1)[:n]}}}}})
|
||||
return string(b)
|
||||
}
|
||||
|
||||
// codexPostZstd posts body to the Codex backend path compressed, as Codex
|
||||
// sends it.
|
||||
func codexPostZstd(t *testing.T, path, body string) (int, string) {
|
||||
t.Helper()
|
||||
e, _ := zstd.NewWriter(nil)
|
||||
z := e.EncodeAll([]byte(body), nil)
|
||||
e.Close()
|
||||
rec := httptest.NewRecorder()
|
||||
req := httptest.NewRequest("POST", CodexPath+path, bytes.NewReader(z))
|
||||
req.Header.Set("Content-Encoding", "zstd")
|
||||
req.Header.Set("Authorization", "Bearer chatgpt-token")
|
||||
req.Header.Set("chatgpt-account-id", "acct-1")
|
||||
New().Handler().ServeHTTP(rec, req)
|
||||
return rec.Code, rec.Body.String()
|
||||
}
|
||||
|
||||
// checkZstd says what is wrong with a turn that should have gone as Codex
|
||||
// sends one: zstd, its Content-Length the compressed bytes, and the JSON it
|
||||
// holds asking for model.
|
||||
func checkZstd(t *testing.T, s sentTurn, model string) {
|
||||
t.Helper()
|
||||
if s.encoding != "zstd" {
|
||||
t.Errorf("%s went %q, want zstd as Codex sends it (%d bytes on the wire)", s.path, s.encoding, s.wire)
|
||||
return
|
||||
}
|
||||
if s.length != int64(s.wire) {
|
||||
t.Errorf("Content-Length %d, %d bytes sent", s.length, s.wire)
|
||||
}
|
||||
var q struct {
|
||||
Model string `json:"model"`
|
||||
}
|
||||
if json.Unmarshal(s.body, &q); q.Model != model {
|
||||
t.Errorf("model %q in the decoded body, want %q", q.Model, model)
|
||||
}
|
||||
}
|
||||
|
||||
// ylorn (X, v0.1.1202): a text-only gpt-6-luna turn of 1.1 MB through a
|
||||
// ChatGPT account was answered 503 when sent plain, and 200 sent
|
||||
// zstd-compressed as Codex's own client sends it. Through magpie's
|
||||
// accounts it now goes compressed and is answered; on the old code every
|
||||
// account was asked plain and the agent got the 503.
|
||||
func TestCodexAccountTextTurnGoesZstd(t *testing.T) {
|
||||
zstdTurns(t)
|
||||
codexSignedIn(t, "spare@example.com")
|
||||
got, mu := turnsBackend(t, 0)
|
||||
|
||||
code, body := codexPost(t, textTurn(1100224))
|
||||
if code != 200 || !strings.Contains(body, "pong") {
|
||||
t.Fatalf("status %d, want 200 pong: %.300s", code, body)
|
||||
}
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
if len(*got) != 1 {
|
||||
t.Fatalf("asked %d times, want once", len(*got))
|
||||
}
|
||||
checkZstd(t, (*got)[0], "gpt-6-luna")
|
||||
if (*got)[0].wire >= 64<<10 {
|
||||
t.Errorf("%d bytes sent for 1.1 MB of repeated text", (*got)[0].wire)
|
||||
}
|
||||
}
|
||||
|
||||
// With Codex's own sign-in alone the turn is relayed, and goes compressed
|
||||
// again whether Codex sent it zstd (it does, which magpie reads) or plain.
|
||||
func TestCodexRelayedTextTurnGoesZstd(t *testing.T) {
|
||||
zstdTurns(t)
|
||||
codexSignedIn(t)
|
||||
got, mu := turnsBackend(t, 0)
|
||||
|
||||
for _, send := range []func(*testing.T, string, string) (int, string){
|
||||
codexPostZstd,
|
||||
func(t *testing.T, _ string, body string) (int, string) { return codexPost(t, body) },
|
||||
} {
|
||||
mu.Lock()
|
||||
*got = nil
|
||||
mu.Unlock()
|
||||
code, body := send(t, "/responses", textTurn(1100224))
|
||||
if code != 200 || !strings.Contains(body, "pong") {
|
||||
t.Fatalf("status %d, want 200 pong: %.300s", code, body)
|
||||
}
|
||||
mu.Lock()
|
||||
if len(*got) != 1 {
|
||||
t.Fatalf("asked %d times, want once", len(*got))
|
||||
}
|
||||
checkZstd(t, (*got)[0], "gpt-6-luna")
|
||||
mu.Unlock()
|
||||
}
|
||||
}
|
||||
|
||||
// A turn asked again goes again whole: each try is the same JSON,
|
||||
// compressed, with its own Content-Length. A screenshot's random bytes
|
||||
// don't compress, so the turn is still past 1 MiB on the wire and the
|
||||
// backend's reset of it is asked again (#1628), by the accounts and on
|
||||
// the relay.
|
||||
func TestCodexTurnAskedAgainGoesZstdAgain(t *testing.T) {
|
||||
zstdTurns(t)
|
||||
for _, spares := range [][]string{{"spare@example.com"}, nil} {
|
||||
codexSignedIn(t, spares...)
|
||||
got, mu := turnsBackend(t, 1)
|
||||
turn := screenshotTurn(t, 1600<<10)
|
||||
code, body := codexPost(t, turn)
|
||||
if code != 200 || !strings.Contains(body, "pong") {
|
||||
t.Fatalf("accounts %v: status %d, want 200 pong: %.300s", spares, code, body)
|
||||
}
|
||||
mu.Lock()
|
||||
if len(*got) != 2 {
|
||||
t.Fatalf("accounts %v: asked %d times, want 2", spares, len(*got))
|
||||
}
|
||||
for _, s := range *got {
|
||||
checkZstd(t, s, "gpt-5.5")
|
||||
if !bytes.Equal(s.body, (*got)[0].body) {
|
||||
t.Errorf("accounts %v: the try again sent another body", spares)
|
||||
}
|
||||
}
|
||||
mu.Unlock()
|
||||
}
|
||||
}
|
||||
|
||||
// Codex sends only its turns compressed: /responses/compact goes plain, as
|
||||
// does a Codex signed in with an API key, which goes to OpenAI's API.
|
||||
func TestCodexCompactAndAPIKeyStayPlain(t *testing.T) {
|
||||
zstdTurns(t)
|
||||
codexSignedIn(t)
|
||||
got, mu := turnsBackend(t, 0)
|
||||
codexPostZstd(t, "/responses/compact", `{"model":"gpt-6-luna","input":"hi"}`)
|
||||
mu.Lock()
|
||||
if len(*got) != 1 || (*got)[0].path != "/backend-api/codex/responses/compact" || (*got)[0].encoding != "" {
|
||||
t.Errorf("compact went %+v, want plain", *got)
|
||||
}
|
||||
mu.Unlock()
|
||||
|
||||
api := &fake{t: t}
|
||||
up := httptest.NewServer(api)
|
||||
t.Cleanup(up.Close)
|
||||
was := codexAPIBase
|
||||
codexAPIBase = up.URL + "/v1"
|
||||
t.Cleanup(func() { codexAPIBase = was })
|
||||
rec := httptest.NewRecorder()
|
||||
req := httptest.NewRequest("POST", CodexPath+"/responses", strings.NewReader(`{"model":"gpt-6-luna","stream":true,"input":"hi"}`))
|
||||
req.Header.Set("Authorization", "Bearer sk-test")
|
||||
New().Handler().ServeHTTP(rec, req)
|
||||
if api.path != "/v1/responses" || api.head.Get("Content-Encoding") != "" || !json.Valid(api.got) {
|
||||
t.Errorf("an API key's turn went %s %q: %.80q", api.path, api.head.Get("Content-Encoding"), api.got)
|
||||
}
|
||||
}
|
||||
|
||||
// Another provider's Responses requests go plain, even one at the very
|
||||
// address a ChatGPT account's turns go to: only a ChatGPT account's are
|
||||
// compressed.
|
||||
func TestKeyProviderTurnStaysPlain(t *testing.T) {
|
||||
zstdTurns(t)
|
||||
f := &fake{t: t, reply: sse(
|
||||
`data: {"type":"response.created","response":{"id":"r1","model":"m1"}}`,
|
||||
`data: {"type":"response.completed","response":{"id":"r1","usage":{"input_tokens":7,"output_tokens":1}}}`)}
|
||||
up := setup(t, provider.Responses, f)
|
||||
was := provider.CodexBase
|
||||
provider.CodexBase = up.URL + "/v1"
|
||||
t.Cleanup(func() { provider.CodexBase = was })
|
||||
|
||||
code, body := post(t, "/v1/responses", `{"model":"fake/m1","stream":true,"input":"ping"}`)
|
||||
if code != 200 {
|
||||
t.Fatalf("status %d: %s", code, body)
|
||||
}
|
||||
if f.path != "/v1/responses" || f.head.Get("Content-Encoding") != "" || !json.Valid(f.got) {
|
||||
t.Errorf("a key's turn went %s %q: %.80q", f.path, f.head.Get("Content-Encoding"), f.got)
|
||||
}
|
||||
}
|
||||
|
||||
// Whether a reset is a large request's (#1628) is judged by what went on
|
||||
// the wire: a 1.1 MB text turn goes as a few KB, so the backend closing on
|
||||
// it is its trouble as for any small request, relayed as the 503 it is
|
||||
// after one try and not told as the request's size.
|
||||
func TestCodexResetJudgedByTheBytesSent(t *testing.T) {
|
||||
zstdTurns(t)
|
||||
codexSignedIn(t)
|
||||
tries := 0
|
||||
up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
tries++
|
||||
w.Header().Set("Content-Type", "text/plain")
|
||||
w.WriteHeader(http.StatusServiceUnavailable)
|
||||
io.WriteString(w, edgeDropped)
|
||||
}))
|
||||
t.Cleanup(up.Close)
|
||||
was := provider.CodexBase
|
||||
provider.CodexBase = up.URL + "/backend-api/codex"
|
||||
t.Cleanup(func() { provider.CodexBase = was })
|
||||
|
||||
code, body := codexPost(t, textTurn(1100224))
|
||||
if code != http.StatusServiceUnavailable || strings.Contains(body, "MiB") || tries != 1 {
|
||||
t.Fatalf("status %d after %d tries: %s", code, tries, body)
|
||||
}
|
||||
}
|
||||
@@ -3236,6 +3236,12 @@ func (s *Server) forwardOnce(ctx context.Context, p provider.Provider, to provid
|
||||
if to == provider.Anthropic {
|
||||
s.fitUserBetas(p, req.Header)
|
||||
}
|
||||
sent := len(body)
|
||||
if p.Account != nil && p.Account.Agent == "codex" {
|
||||
// a turn goes zstd-compressed, as Codex's own client sends it;
|
||||
// sent plain, ChatGPT answered a 1.1 MB one 503 (ylorn on X)
|
||||
sent = provider.CodexCompressed(req, body)
|
||||
}
|
||||
res, err := p.Do(s.client, req)
|
||||
if err != nil {
|
||||
return res, err
|
||||
@@ -3246,7 +3252,7 @@ func (s *Server) forwardOnce(ctx context.Context, p provider.Provider, to provid
|
||||
if p.Account != nil && p.Account.Agent == "codex" {
|
||||
// a large request ChatGPT closed the connection on: asked again,
|
||||
// nobody resting for it, and said what may help (#1628)
|
||||
res = codexDropped(res, len(body))
|
||||
res = codexDropped(res, sent)
|
||||
}
|
||||
// what a Codex account's reply says it has used, for its cap (#1295)
|
||||
heardCodexLimits(p, res)
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"testing"
|
||||
|
||||
"github.com/yetone/magpie/internal/agentenv"
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
"github.com/yetone/magpie/internal/testenv"
|
||||
)
|
||||
|
||||
@@ -65,6 +66,9 @@ func isolatedTests(m *testing.M) (int, error) {
|
||||
// searcher goes out through a proxy that cannot reach the test's
|
||||
// servers.
|
||||
testenv.ClearProxy()
|
||||
// The fakes of ChatGPT's backend read turns plain; codex_zstd_test's
|
||||
// send them zstd, as the real one is sent.
|
||||
provider.CodexZstdForTests(false)
|
||||
// Finding an inert CLI also prevents discovery from falling back to
|
||||
// one installed at an absolute system path. Tests can prepend their
|
||||
// own fakes, as fakeClaude does, and still use ordinary shell tools.
|
||||
|
||||
@@ -449,6 +449,7 @@ func warmCodex(ctx context.Context, sign func(context.Context, *http.Request, []
|
||||
if err := sign(ctx, req, body); err != nil {
|
||||
return err
|
||||
}
|
||||
CodexCompressed(req, body) // as Codex sends a turn
|
||||
res, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
return err
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
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.
|
||||
var codexZstd, _ = zstd.NewWriter(nil, zstd.WithEncoderLevel(zstd.SpeedDefault), zstd.WithEncoderCRC(false))
|
||||
|
||||
// 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"
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
package provider
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/klauspost/compress/zstd"
|
||||
)
|
||||
|
||||
// A ChatGPT turn goes as Codex's client sends it (openai/codex
|
||||
// codex-rs/http-client/src/request.rs: zstd level 3, Content-Encoding:
|
||||
// zstd), and only a turn: CodexBase's /responses, POSTed, not already
|
||||
// encoded. Anything else is left as it was.
|
||||
func TestCodexCompressed(t *testing.T) {
|
||||
t.Cleanup(CodexZstdForTests(true))
|
||||
was := CodexBase
|
||||
CodexBase = "https://chatgpt.example/backend-api/codex"
|
||||
t.Cleanup(func() { CodexBase = was })
|
||||
body := bytes.Repeat([]byte(`{"model":"gpt-6-luna","input":"the same words again "}`), 20000)
|
||||
|
||||
req, _ := http.NewRequest("POST", CodexBase+"/responses", bytes.NewReader(body))
|
||||
n := CodexCompressed(req, body)
|
||||
wire, _ := io.ReadAll(req.Body)
|
||||
if req.Header.Get("Content-Encoding") != "zstd" || n != len(wire) || req.ContentLength != int64(n) || n >= len(body)/10 {
|
||||
t.Fatalf("sent %d of %d bytes as %q, Content-Length %d", n, len(body), req.Header.Get("Content-Encoding"), req.ContentLength)
|
||||
}
|
||||
d, _ := zstd.NewReader(nil)
|
||||
defer d.Close()
|
||||
if out, err := d.DecodeAll(wire, nil); err != nil || !bytes.Equal(out, body) {
|
||||
t.Fatalf("decoded %d bytes, err %v", len(out), err)
|
||||
}
|
||||
again, _ := req.GetBody()
|
||||
if b, _ := io.ReadAll(again); !bytes.Equal(b, wire) {
|
||||
t.Error("GetBody gives another body")
|
||||
}
|
||||
|
||||
for _, u := range []string{CodexBase + "/responses/compact", CodexBase + "/models", "https://api.openai.com/v1/responses", "http://127.0.0.1:1/backend-api/codex/responses"} {
|
||||
req, _ := http.NewRequest("POST", u, bytes.NewReader(body))
|
||||
if n := CodexCompressed(req, body); n != len(body) || req.Header.Get("Content-Encoding") != "" {
|
||||
t.Errorf("%s compressed", u)
|
||||
}
|
||||
}
|
||||
req, _ = http.NewRequest("POST", CodexBase+"/responses", bytes.NewReader(body))
|
||||
req.Header.Set("Content-Encoding", "gzip")
|
||||
if n := CodexCompressed(req, body); n != len(body) || req.Header.Get("Content-Encoding") != "gzip" {
|
||||
t.Error("an encoded body encoded again")
|
||||
}
|
||||
}
|
||||
|
||||
// The warm-up "hi" is a turn as Codex's are, and goes compressed too.
|
||||
func TestCodexWarmGoesZstd(t *testing.T) {
|
||||
t.Cleanup(CodexZstdForTests(true))
|
||||
var enc string
|
||||
var got map[string]any
|
||||
fake := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
enc = r.Header.Get("Content-Encoding")
|
||||
d, _ := zstd.NewReader(r.Body)
|
||||
defer d.Close()
|
||||
json.NewDecoder(d).Decode(&got)
|
||||
w.Header().Set("Content-Type", "text/event-stream")
|
||||
io.WriteString(w, "event: response.completed\ndata: {\"type\":\"response.completed\"}\n\n")
|
||||
}))
|
||||
defer fake.Close()
|
||||
was := CodexBase
|
||||
CodexBase = fake.URL + "/backend-api/codex"
|
||||
t.Cleanup(func() { CodexBase = was })
|
||||
|
||||
if err := warmCodex(context.Background(), func(context.Context, *http.Request, []byte) error { return nil }, "gpt-6-luna", ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if enc != "zstd" || got["model"] != "gpt-6-luna" || got["input"] == nil {
|
||||
t.Fatalf("warmed %q: %v", enc, got)
|
||||
}
|
||||
}
|
||||
@@ -24,5 +24,8 @@ func TestMain(m *testing.M) {
|
||||
// never the runner's keychain: a test that wants the Copilot
|
||||
// CLI's token there stands one in itself
|
||||
copilotCLISecret = func(string) string { return "" }
|
||||
// the fakes of ChatGPT's backend read turns plain; codex_zstd's
|
||||
// tests send them as the real one is sent
|
||||
CodexZstdForTests(false)
|
||||
}))
|
||||
}
|
||||
|
||||
@@ -997,7 +997,7 @@ func (d *dispatch) servesItself(ifs *ast.IfStmt) bool {
|
||||
return true
|
||||
}
|
||||
if sel, ok := call.Fun.(*ast.SelectorExpr); ok {
|
||||
if name := sel.Sel.Name; len(name) > len("serve") && name[len("serve")] >= 'A' && name[len("serve")] <= 'Z' {
|
||||
if name := sel.Sel.Name; strings.HasPrefix(name, "serve") && len(name) > len("serve") && name[len("serve")] >= 'A' && name[len("serve")] <= 'Z' {
|
||||
own = true
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user