gateway: a request over a provider's byte cap is asked again with its oldest images left out (EDwinpzy)
EDwinpzy on Discord (v0.1.2605, Windows, Codex Desktop, compaction on auto/deepseek-v4.1-flash through Command Code): a long session full of screenshots could not compact. Command Code refused the summary request with 400 "Request body is 40.1 MB, over the 32 MB limit for one request (33554432 bytes)". That is not a 413, so summaryTooLarge never sent it to the text-only ask, and Codex's compaction failed three times. The compaction guard then held it for five minutes, and after that the same 40 MB body was sent again. Agent turns of the same session hit the cap the same way. What changed (internal/gateway/body_cap.go, wired in forward and forwardOnce): - byteCapRefusal: a 413, or a refusal of any other status whose words say the body is over a size limit. A 401, 403, 429 or a context overflow (tooLong) never counts. - refitOverCap (forward): the cap is taken from the refusal (the smallest size it names below what was sent, else 3/4 of what was sent) and kept per provider id. The request is then asked again, fitted to 3/4 of the cap, at most three times. - To fit a request, the oldest history images are replaced one by one, each with a text part: "[An earlier image was left out here to keep this request under its size limit.]" (it names neither magpie nor the vendor). The latest user message's images, and every text including tool output, are kept. Every other byte of the body stays as it was. Covers Responses, Chat, Anthropic and Gemini. - withinCap (forwardOnce): once a cap is known, a later request near it is fitted before it goes, so each turn doesn't pay a refusal first. - When leaving out every earlier image still doesn't fit, or every size is refused, the agent gets a 413 request_too_large naming the size, the cap and what was kept. Codex reads that as context_length_exceeded, and its compaction goes on to plainCompact and localSummary instead of sending the same body into the guard's hold. Every route that calls serve goes through forward, including magpie's own: compaction, titles, the classifier, search, vision and the Codex fallback turn. So all of them are fitted. Not changed: magpie's own requests still run no gateway hooks, so a plugin's onRequest doesn't see compaction (EDwinpzy's other ask). Running them there changes the plugin contract: a recall plugin's context would land in summaries and titles, and onResponse would see calls the user never sent. Filed as #4847, and written in gateway-request-hooks.md. gateway-routing.md describes the byte-cap fitting. Tests (body_cap_test.go), built from the reporter's shape: a ~40 MB Codex session of 20 ~2 MB screenshots, from view_image tool outputs and pasted user images, and a latest user message with its own screenshot. The fake upstream refuses anything over 32 MiB with the reporter's literal 400 body. No network. - TestCompactionOverByteCapLeavesOutOldImages (Responses and Chat upstreams): Codex gets the model's SUMMARY. The second ask is under 24 MiB, the oldest screenshot is replaced by the marker, SHOT19 (the latest user message's image) is kept, and every user text and tool output text is kept. - TestTurnOverByteCapLeavesOutOldImages: a turn is fitted the same way, and the next turn goes fitted with one upstream call. - TestOverByteCapNothingToLeaveOut: every image is in the latest message. The body is sent once, and Codex gets context_length_exceeded with "over the 32.0 MB 1017dp takes in one request ... no earlier image". - TestCompactionOverByteCapEveryTime: refused at every size. Asks get smaller, there are at most 6 calls, and it ends in a local summary with no image in it. - TestByteCapRefusal and TestWithoutOldImagesEachProtocol: the classifier (TPM 429, context overflow, 401 and an invalid-schema 400 are not caps), statedCap, and the Chat, Anthropic and Gemini splices. Run on mote (Go 1.26.8, macOS) at this change onb61121503: - go test -count=1 -timeout 45m ./internal/gateway: every test passes except TestCodexPoolSaysTheClientsVersion, which is #4807 (red in a full package run on mote, passes alone; this change doesn't touch Codex's identity). - the targeted -run of ByteCap, CodexCompactTooLarge, DeepSeekByteCap and CodexCompactOther: ok. - GOOS=linux and GOOS=windows go vet -tags nogui ./...: ok. gofmt -l internal/: clean. After the rebase ontof5c956b84(three commits, none in internal/gateway): Linux and Windows vet of gateway and provider, and the byte-cap, compaction and DeepSeek tests above again: ok. Broken by hand on mote: - without refitOverCap, withinCap and the post-loop 413, the compaction, turn and nothing-to-leave-out tests fail with the reporter's 400; - without withinCap alone, the next turn is asked twice; - without the 413 after the loop, TestCompactionOverByteCapEveryTime fails with Codex's compaction answered 400. Not tried: a real Command Code account (or any vendor's real cap), a real Codex Desktop session, and a Windows run (nothing here is OS-specific). The cap is kept in memory only, so after a restart the first oversized request is refused once more before it is fitted. Reported-by: EDwinpzy (Discord #feedback)
This commit is contained in:
@@ -114,7 +114,11 @@ bounded hook timeout. Request-owned state is released after notification.
|
||||
- `internal/gateway/middleware.go`: `gatewayHooks`, before routing and around the
|
||||
middleware, so `onResponse` sees what the agent got. `serveAgent` runs it for
|
||||
every agent request; Codex's own ChatGPT sign-in passthrough
|
||||
(`codex_backend.go`) runs it without the synchronous middleware.
|
||||
(`codex_backend.go`) runs it without the synchronous middleware. The
|
||||
requests magpie makes on its own call `serve` directly and run no hooks:
|
||||
Codex's compaction and its fallback turn, titles, System One's
|
||||
classifier, search and vision (#4847). A request over a provider's byte
|
||||
cap is fitted in the gateway itself, not by a hook (`body_cap.go`).
|
||||
- `internal/gateway/gateway_hooks.go`: bounded response observation and
|
||||
`gatewayReply`, a stream made one reply.
|
||||
- `internal/plugin/gateway_test.go` and `internal/gateway/gateway_hook_test.go`:
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,391 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"github.com/tidwall/gjson"
|
||||
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
// A provider's cap on the bytes of one request.
|
||||
//
|
||||
// Codex sends the whole conversation on every turn, its screenshots inline
|
||||
// as base64, and its compaction's summary request is that conversation
|
||||
// too. Past a vendor's byte cap — Command Code's "Request body is 40.1 MB,
|
||||
// over the 32 MB limit for one request (33554432 bytes)" (EDwinpzy on
|
||||
// Discord, a Codex session of many screenshots), Anthropic's 32 MB
|
||||
// request_too_large, DeepSeek's 413 — every turn and every compaction was
|
||||
// refused, the same body asked again until the compaction guard held it
|
||||
// (compactFails), and the conversation could neither compact nor go on.
|
||||
//
|
||||
// A refusal that says the body is too large (byteCapRefusal) teaches the
|
||||
// provider's cap: the one it states, or else three quarters of what was
|
||||
// sent. The request is then sent again with the oldest images of its
|
||||
// history left out, each replaced by a short text saying so, until it is
|
||||
// under three quarters of the cap — room for the conversation to grow a
|
||||
// few turns before more go, so its prompt cache isn't broken on every
|
||||
// turn. The latest user message's images stay, and no text is touched:
|
||||
// a tool's output keeps its words, only an image in it can go. Later
|
||||
// requests to the provider are fitted the same way before they are sent
|
||||
// (forwardOnce). Every route through serve goes through forward — the
|
||||
// agent's turns, Codex's compaction, titles, the classifier, search and
|
||||
// vision stand-ins — so each is fitted alike.
|
||||
//
|
||||
// When leaving every earlier image out still doesn't bring it under, the
|
||||
// request isn't sent again: the refusal goes on as a 413 saying how large
|
||||
// the request is, the cap, and that the latest images and the text were
|
||||
// kept, which Codex takes as its cue to compact (streamError) and
|
||||
// codexCompact as its cue to ask the summary as text (summaryTooLarge).
|
||||
|
||||
// bodyCapWords are a vendor's words for a request body over its byte
|
||||
// cap, not a conversation over the model's window (tooLong) nor a rate.
|
||||
var bodyCapWords = regexp.MustCompile(`(?i)request[ _](body|entity|payload)( size)?( is| was)? (too large|too big|over|larger than|exceeds?|exceeded)|request body is [\d.]+ ?[kmg]i?b|payload too large|entity too large|request_too_large|(body|request|payload) (size )?(exceeds?|exceeded|is over|is larger than) (the )?(max|limit|\d)|length limit exceeded|maximum allowed number of bytes|limit for one request|(max(imum)?|request) (request |body )*size (limit )?(exceeded|of)`)
|
||||
|
||||
// byteCapRefusal is a provider's refusal of a request for its bytes: a
|
||||
// 413 that doesn't say the model's window is full, or any other refusal
|
||||
// (Command Code's came as its own status) whose words say the body is
|
||||
// over a limit. A sign-in's refusal or a rate limit is never one.
|
||||
func byteCapRefusal(status int, errBody []byte) bool {
|
||||
if status < 400 || status == http.StatusUnauthorized || status == http.StatusForbidden || status == http.StatusTooManyRequests {
|
||||
return false
|
||||
}
|
||||
words := string(wordsOf(errBody))
|
||||
if tooLong(status, words) {
|
||||
return false
|
||||
}
|
||||
return status == http.StatusRequestEntityTooLarge || bodyCapWords.MatchString(words)
|
||||
}
|
||||
|
||||
// capSizes are the sizes a refusal names: "33554432 bytes", "32 MB",
|
||||
// "32MiB", "40.1 MB".
|
||||
var capSizes = regexp.MustCompile(`(?i)(\d+(?:\.\d+)?)\s*(bytes|b|kb|kib|mb|mib|gb|gib)\b`)
|
||||
|
||||
// statedCap is the cap a refusal names: the smallest size in its words
|
||||
// under what was sent (the body's own size is often named beside it). A
|
||||
// megabyte is 2^20 bytes, as "32 MB … (33554432 bytes)" counts it; the
|
||||
// request is fitted well under the cap anyway (capRoom). 0 when it names
|
||||
// none.
|
||||
func statedCap(errBody []byte, sent int) int {
|
||||
least := 0
|
||||
for _, m := range capSizes.FindAllStringSubmatch(string(wordsOf(errBody)), -1) {
|
||||
f, err := strconv.ParseFloat(m[1], 64)
|
||||
if err != nil || f <= 0 {
|
||||
continue
|
||||
}
|
||||
unit := map[string]float64{"bytes": 1, "b": 1, "kb": 1 << 10, "kib": 1 << 10, "mb": 1 << 20, "mib": 1 << 20, "gb": 1 << 30, "gib": 1 << 30}[strings.ToLower(m[2])]
|
||||
n := int(f * unit)
|
||||
if n < 1<<10 || n >= sent {
|
||||
continue // not a body's cap, or the body itself
|
||||
}
|
||||
if least == 0 || n < least {
|
||||
least = n
|
||||
}
|
||||
}
|
||||
return least
|
||||
}
|
||||
|
||||
// bodyCaps are the byte caps providers refused requests over, by
|
||||
// provider id, for as long as magpie runs.
|
||||
type bodyCaps struct {
|
||||
mu sync.Mutex
|
||||
m map[string]int
|
||||
}
|
||||
|
||||
func (c *bodyCaps) of(id string) int {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
return c.m[id]
|
||||
}
|
||||
|
||||
// learn keeps the smaller of n and the cap known before.
|
||||
func (c *bodyCaps) learn(id string, n int) int {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
if c.m == nil {
|
||||
c.m = map[string]int{}
|
||||
}
|
||||
if old := c.m[id]; old > 0 && old <= n {
|
||||
return old
|
||||
}
|
||||
c.m[id] = n
|
||||
return n
|
||||
}
|
||||
|
||||
// capRoom is what a request is fitted to under a cap: three quarters of
|
||||
// it. capNear is how near the cap a request may come before it is fitted.
|
||||
func capRoom(n int) int { return n / 4 * 3 }
|
||||
func capNear(n int) int { return n / 10 * 9 }
|
||||
|
||||
// withinCap is body as it goes to p: fitted under the cap p refused a
|
||||
// larger request over, when one is known and body comes near it.
|
||||
func (s *Server) withinCap(p provider.Provider, to provider.Protocol, path string, body []byte) []byte {
|
||||
out, left := s.capFit(p, to, path, body)
|
||||
if left > 0 {
|
||||
log.Printf("%s: the request is %s, over the %s it takes in one request; the %d oldest images left out (%s)", p.Name, mb(len(body)), mb(s.bodyCaps.of(p.ID)), left, mb(len(out)))
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// capFit is withinCap without its log line: body fitted under p's known
|
||||
// cap, and how many images were left out for it.
|
||||
func (s *Server) capFit(p provider.Provider, to provider.Protocol, path string, body []byte) ([]byte, int) {
|
||||
n := s.bodyCaps.of(p.ID)
|
||||
if n <= 0 || len(body) <= capNear(n) || countsTokens(path) {
|
||||
return body, 0
|
||||
}
|
||||
out, left, ok := withoutOldImages(to, body, capRoom(n))
|
||||
if !ok {
|
||||
return body, 0
|
||||
}
|
||||
return out, left
|
||||
}
|
||||
|
||||
// refitOverCap is forward's answer to res, a refusal of body for its
|
||||
// bytes (byteCapRefusal): the cap learned, and the request sent again
|
||||
// with its oldest images left out, as often as that brings it lower and
|
||||
// is refused again. When nothing more can go, the refusal is said as a
|
||||
// 413 that names the size, the cap and what was kept.
|
||||
func (s *Server) refitOverCap(ctx context.Context, p provider.Provider, to provider.Protocol, path string, body []byte, in http.Header, res *http.Response) (*http.Response, error) {
|
||||
var err error
|
||||
for range 3 {
|
||||
if res.StatusCode < 400 || countsTokens(path) {
|
||||
return res, nil
|
||||
}
|
||||
b := peekError(res)
|
||||
if !byteCapRefusal(res.StatusCode, b) {
|
||||
return res, nil
|
||||
}
|
||||
// what forwardOnce sent: body as it fits it
|
||||
was, _ := s.capFit(p, to, path, codexImagesFit(p, to, body))
|
||||
sent := len(was)
|
||||
n := statedCap(b, sent)
|
||||
if n == 0 {
|
||||
n = capRoom(sent) // it said no number: less than was sent
|
||||
}
|
||||
n = s.bodyCaps.learn(p.ID, n)
|
||||
fitted, left, ok := withoutOldImages(to, body, capRoom(n))
|
||||
if !ok || len(fitted) >= sent {
|
||||
res.Body.Close()
|
||||
return overCap(res, b, p, len(body), statedCap(b, len(body)), images(to, body)), nil
|
||||
}
|
||||
log.Printf("%s refused a request of %s (HTTP %d: %s); asking again with the %d oldest images left out (%s)", p.Name, mb(sent), res.StatusCode, provider.APIError(b, ""), left, mb(len(fitted)))
|
||||
res.Body.Close()
|
||||
// fitted is under capNear already, so forwardOnce sends it as it is
|
||||
if res, err = s.forwardOnce(ctx, p, to, path, fitted, in); err != nil {
|
||||
return res, err
|
||||
}
|
||||
}
|
||||
if res.StatusCode >= 400 {
|
||||
b := peekError(res)
|
||||
if byteCapRefusal(res.StatusCode, b) {
|
||||
// refused as often as it was asked smaller: said as a 413, so
|
||||
// Codex's compaction asks as text (summaryTooLarge)
|
||||
res.Body.Close()
|
||||
return overCap(res, b, p, len(body), statedCap(b, len(body)), images(to, body)), nil
|
||||
}
|
||||
}
|
||||
return res, nil
|
||||
}
|
||||
|
||||
// peekError is the first MiB of res's error body, res.Body left to read
|
||||
// it all again.
|
||||
func peekError(res *http.Response) []byte {
|
||||
b, _ := io.ReadAll(io.LimitReader(res.Body, 1<<20))
|
||||
res.Body = readCloser{io.MultiReader(bytes.NewReader(b), res.Body), res.Body}
|
||||
return b
|
||||
}
|
||||
|
||||
// overCap is a byte-cap refusal said as a 413 with what it is about: the
|
||||
// request's size, the provider's cap when it named one, and that leaving
|
||||
// out its earlier images didn't bring it under.
|
||||
func overCap(res *http.Response, errBody []byte, p provider.Provider, size, n, imgs int) *http.Response {
|
||||
said := provider.APIError(errBody, http.StatusText(res.StatusCode))
|
||||
limit := "what " + p.Name + " takes in one request"
|
||||
if n > 0 {
|
||||
limit = fmt.Sprintf("the %s %s takes in one request", mb(n), p.Name)
|
||||
}
|
||||
why := "it has no earlier image to leave out"
|
||||
if imgs > 0 {
|
||||
why = "even with its earlier images left out; the latest message's images and every text, tool output included, are kept"
|
||||
}
|
||||
msg := fmt.Sprintf("%s (HTTP %d: the request is %s, over %s, %s)", said, res.StatusCode, mb(size), limit, why)
|
||||
out, _ := json.Marshal(map[string]any{"type": "error", "error": map[string]any{"type": "request_too_large", "message": msg}})
|
||||
h := res.Header.Clone()
|
||||
h.Set("Content-Type", "application/json")
|
||||
h.Del("Content-Length")
|
||||
h.Del("Content-Encoding")
|
||||
return &http.Response{
|
||||
Status: "413 Request Entity Too Large", StatusCode: http.StatusRequestEntityTooLarge,
|
||||
Proto: res.Proto, ProtoMajor: res.ProtoMajor, ProtoMinor: res.ProtoMinor,
|
||||
Header: h, Body: io.NopCloser(bytes.NewReader(out)), ContentLength: int64(len(out)), Request: res.Request,
|
||||
}
|
||||
}
|
||||
|
||||
// imageLeftOut is what stands where an image was left out. It goes to the
|
||||
// vendor, so it names neither magpie nor the vendor.
|
||||
const imageLeftOut = "[An earlier image was left out here to keep this request under its size limit.]"
|
||||
|
||||
// capImage is one image of a request's history: where its JSON object sits
|
||||
// and what it is replaced with.
|
||||
type capImage struct {
|
||||
at, end int
|
||||
with string
|
||||
}
|
||||
|
||||
// historyOf is where a protocol's conversation sits in its body.
|
||||
func historyOf(to provider.Protocol) string {
|
||||
switch to {
|
||||
case provider.Responses:
|
||||
return "input"
|
||||
case provider.Gemini:
|
||||
return "contents"
|
||||
}
|
||||
return "messages"
|
||||
}
|
||||
|
||||
// imageWith is the part an image of the protocol is replaced with, ""
|
||||
// when part is no image.
|
||||
func imageWith(to provider.Protocol, part gjson.Result) string {
|
||||
text, _ := json.Marshal(imageLeftOut)
|
||||
switch to {
|
||||
case provider.Responses:
|
||||
if part.Get("type").String() == "input_image" {
|
||||
return `{"type":"input_text","text":` + string(text) + `}`
|
||||
}
|
||||
case provider.Chat:
|
||||
if t := part.Get("type").String(); t == "image_url" || t == "input_image" {
|
||||
return `{"type":"text","text":` + string(text) + `}`
|
||||
}
|
||||
case provider.Anthropic:
|
||||
if part.Get("type").String() == "image" {
|
||||
return `{"type":"text","text":` + string(text) + `}`
|
||||
}
|
||||
case provider.Gemini:
|
||||
for _, k := range []string{"inlineData", "inline_data"} {
|
||||
d := part.Get(k)
|
||||
mt := d.Get("mimeType").String() + d.Get("mime_type").String()
|
||||
if d.IsObject() && strings.HasPrefix(mt, "image/") {
|
||||
return `{"text":` + string(text) + `}`
|
||||
}
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// latestUser is the index of the history's latest user message: one the
|
||||
// user wrote, not a tool's results (Anthropic's tool_result blocks,
|
||||
// Gemini's functionResponse parts, Responses' function_call_output), nor
|
||||
// Codex's compaction prompt that codexCompact puts last. -1 for none.
|
||||
func latestUser(to provider.Protocol, items []gjson.Result) int {
|
||||
for i := len(items) - 1; i >= 0; i-- {
|
||||
it := items[i]
|
||||
if it.Get("role").String() != "user" {
|
||||
continue
|
||||
}
|
||||
if to == provider.Responses && it.Get("type").Exists() && it.Get("type").String() != "message" {
|
||||
continue
|
||||
}
|
||||
content := it.Get("content")
|
||||
if to == provider.Gemini {
|
||||
content = it.Get("parts")
|
||||
}
|
||||
said, own := "", !content.IsArray()
|
||||
if !content.IsArray() {
|
||||
said = content.String()
|
||||
}
|
||||
content.ForEach(func(_, part gjson.Result) bool {
|
||||
switch {
|
||||
case part.Get("type").String() == "tool_result" || part.Get("functionResponse").Exists() || part.Get("function_response").Exists():
|
||||
default:
|
||||
own = true
|
||||
said += part.Get("text").String()
|
||||
}
|
||||
return true
|
||||
})
|
||||
if own && strings.TrimSpace(said) != strings.TrimSpace(codexCompactPrompt) {
|
||||
return i
|
||||
}
|
||||
}
|
||||
return -1
|
||||
}
|
||||
|
||||
// historyImages are the images of body's history, oldest first, that may
|
||||
// be left out: inline ones (of 1 KB or more, which a link never is), not
|
||||
// the latest user message's.
|
||||
func historyImages(to provider.Protocol, body []byte) []capImage {
|
||||
var items []gjson.Result
|
||||
getIn(body, historyOf(to)).ForEach(func(_, it gjson.Result) bool {
|
||||
items = append(items, it)
|
||||
return true
|
||||
})
|
||||
keep := latestUser(to, items)
|
||||
var out []capImage
|
||||
var walk func(v gjson.Result, depth int)
|
||||
walk = func(v gjson.Result, depth int) {
|
||||
if depth > 6 || !v.IsObject() && !v.IsArray() {
|
||||
return
|
||||
}
|
||||
if v.IsObject() {
|
||||
if with := imageWith(to, v); with != "" {
|
||||
end := v.Index + len(v.Raw)
|
||||
if len(v.Raw) >= 1<<10 && v.Index > 0 && end <= len(body) && string(body[v.Index:end]) == v.Raw {
|
||||
out = append(out, capImage{at: v.Index, end: end, with: with})
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
v.ForEach(func(_, c gjson.Result) bool {
|
||||
walk(c, depth+1)
|
||||
return true
|
||||
})
|
||||
}
|
||||
for i, it := range items {
|
||||
if i != keep {
|
||||
walk(it, 0)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// images counts what historyImages finds.
|
||||
func images(to provider.Protocol, body []byte) int { return len(historyImages(to, body)) }
|
||||
|
||||
// withoutOldImages is body under most bytes with the fewest of its oldest
|
||||
// history images left out, each replaced by imageLeftOut; the rest of it
|
||||
// byte for byte as it came. ok is false, and body as it came, when
|
||||
// leaving every one out doesn't bring it under.
|
||||
func withoutOldImages(to provider.Protocol, body []byte, most int) (out []byte, left int, ok bool) {
|
||||
if len(body) <= most {
|
||||
return body, 0, true
|
||||
}
|
||||
imgs := historyImages(to, body)
|
||||
need, n := len(body)-most, 0
|
||||
for n < len(imgs) && need > 0 {
|
||||
need -= imgs[n].end - imgs[n].at - len(imgs[n].with)
|
||||
n++
|
||||
}
|
||||
if need > 0 {
|
||||
return body, 0, false
|
||||
}
|
||||
var b bytes.Buffer
|
||||
b.Grow(len(body))
|
||||
last := 0
|
||||
for _, im := range imgs[:n] {
|
||||
b.Write(body[last:im.at])
|
||||
b.WriteString(im.with)
|
||||
last = im.end
|
||||
}
|
||||
b.Write(body[last:])
|
||||
return b.Bytes(), n, true
|
||||
}
|
||||
@@ -0,0 +1,257 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
// commandCodeCap is Command Code's refusal of a Codex session's
|
||||
// compaction (EDwinpzy on Discord, v0.1.2605, Codex Desktop on Windows,
|
||||
// auto/deepseek-v4.1-flash): the history held many screenshots, and the
|
||||
// summary request was over the vendor's byte cap. It came under a status
|
||||
// of its own, not 413.
|
||||
const commandCodeCap = `{"error":{"message":"Request body is 40.1 MB, over the 32 MB limit for one request (33554432 bytes)","type":"commandcode_error","code":400}}`
|
||||
|
||||
const commandCodeMost = 32 << 20
|
||||
|
||||
// screenshot is a ~2 MB screenshot's data URL, its n in it so each is
|
||||
// told apart.
|
||||
func screenshot(n int) string {
|
||||
return fmt.Sprintf("data:image/png;base64,SHOT%02d", n) + strings.Repeat("iVBORw0KGgo", 190_000)
|
||||
}
|
||||
|
||||
// screenshotSession is the reporter's shape: a Codex session of twenty
|
||||
// screenshots, ~42 MB, each read by a tool (view_image's output) or
|
||||
// pasted into a user message, then the latest user message with a
|
||||
// screenshot of its own. compact ends it in Codex's compaction trigger.
|
||||
func screenshotSession(compact bool) string {
|
||||
var b strings.Builder
|
||||
b.WriteString(`{"model":"fake/m1","stream":true,"store":false,"prompt_cache_key":"thread-shots","input":[`)
|
||||
for i := range 19 {
|
||||
if i%2 == 0 {
|
||||
fmt.Fprintf(&b, `{"type":"message","role":"user","content":[{"type":"input_text","text":"look at screen %d"},{"type":"input_image","image_url":"%s"}]},`, i, screenshot(i))
|
||||
continue
|
||||
}
|
||||
fmt.Fprintf(&b, `{"type":"function_call","call_id":"call_%d","name":"view_image","arguments":"{\"path\":\"shot%d.png\"}"},`, i, i)
|
||||
fmt.Fprintf(&b, `{"type":"function_call_output","call_id":"call_%d","output":[{"type":"input_text","text":"tool output %d kept"},{"type":"input_image","image_url":"%s"}]},`, i, i, screenshot(i))
|
||||
fmt.Fprintf(&b, `{"type":"message","role":"assistant","content":[{"type":"output_text","text":"seen %d"}]},`, i)
|
||||
}
|
||||
fmt.Fprintf(&b, `{"type":"message","role":"user","content":[{"type":"input_text","text":"the latest ask"},{"type":"input_image","image_url":"%s"}]}`, screenshot(19))
|
||||
if compact {
|
||||
b.WriteString(`,{"type":"compaction_trigger"}`)
|
||||
}
|
||||
b.WriteString(`]}`)
|
||||
return b.String()
|
||||
}
|
||||
|
||||
// postResponses posts body to the gateway's /v1/responses as Codex.
|
||||
func postResponses(t *testing.T, s *Server, body string) (int, string) {
|
||||
t.Helper()
|
||||
gw := httptest.NewServer(s.Handler())
|
||||
t.Cleanup(gw.Close)
|
||||
req, _ := http.NewRequest("POST", gw.URL+"/v1/responses", strings.NewReader(body))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("User-Agent", codexUA)
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
b, _ := io.ReadAll(resp.Body)
|
||||
return resp.StatusCode, string(b)
|
||||
}
|
||||
|
||||
// underCap checks a request sent after the cap was learned: under it, the
|
||||
// oldest screenshots left out with the marker, the latest user message's
|
||||
// screenshot and every text kept.
|
||||
func underCap(t *testing.T, sent []byte) {
|
||||
t.Helper()
|
||||
s := string(sent)
|
||||
if len(sent) > commandCodeMost*3/4 {
|
||||
t.Errorf("sent %d bytes, over three quarters of the cap", len(sent))
|
||||
}
|
||||
if strings.Contains(s, "SHOT00") || !strings.Contains(s, imageLeftOut) {
|
||||
t.Error("the oldest screenshot wasn't left out with the marker")
|
||||
}
|
||||
if !strings.Contains(s, "SHOT19") {
|
||||
t.Error("the latest user message's screenshot was left out")
|
||||
}
|
||||
for i := range 19 {
|
||||
want := fmt.Sprintf("look at screen %d", i)
|
||||
if i%2 == 1 {
|
||||
want = fmt.Sprintf("tool output %d kept", i)
|
||||
}
|
||||
if !strings.Contains(s, want) {
|
||||
t.Errorf("text %q is gone", want)
|
||||
}
|
||||
}
|
||||
if strings.Contains(s, "This is the conversation so far") {
|
||||
t.Error("asked as text, not as the conversation with its later images")
|
||||
}
|
||||
}
|
||||
|
||||
// Codex's compaction of a session over the vendor's byte cap was refused
|
||||
// every time, three times, and then held for five minutes by the guard;
|
||||
// the same oversized request again after that. Now the request is asked
|
||||
// again with its oldest screenshots left out, and Codex gets the model's
|
||||
// summary.
|
||||
func TestCompactionOverByteCapLeavesOutOldImages(t *testing.T) {
|
||||
for _, proto := range []provider.Protocol{provider.Responses, provider.Chat} {
|
||||
t.Run(string(proto), func(t *testing.T) {
|
||||
up := &capped{proto: proto, most: commandCodeMost, status: 400, ctype: "application/json", body: commandCodeCap}
|
||||
cappedOn(t, up)
|
||||
code, body := codexPost(t, screenshotSession(true))
|
||||
if code != 200 {
|
||||
t.Fatalf("Codex's compaction failed: %d %.400s", code, body)
|
||||
}
|
||||
if got := compactedText(t, body); got != "SUMMARY" {
|
||||
t.Fatalf("summary %q", got)
|
||||
}
|
||||
calls := up.calls()
|
||||
if len(calls) != 2 || len(calls[0]) <= commandCodeMost {
|
||||
t.Fatalf("asked %d times (first %d bytes)", len(calls), len(calls[0]))
|
||||
}
|
||||
underCap(t, calls[1])
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// A turn of the same session is fitted as its compaction is, and the next
|
||||
// turn to the same provider goes fitted at once: the cap is learned.
|
||||
func TestTurnOverByteCapLeavesOutOldImages(t *testing.T) {
|
||||
fresh(t)
|
||||
up := &capped{proto: provider.Responses, most: commandCodeMost, status: 400, ctype: "application/json", body: commandCodeCap}
|
||||
cappedOn(t, up)
|
||||
s := New()
|
||||
code, body := postResponses(t, s, screenshotSession(false))
|
||||
if code != 200 || !strings.Contains(body, "SUMMARY") {
|
||||
t.Fatalf("the turn failed: %d %.400s", code, body)
|
||||
}
|
||||
calls := up.calls()
|
||||
if len(calls) != 2 {
|
||||
t.Fatalf("asked %d times", len(calls))
|
||||
}
|
||||
underCap(t, calls[1])
|
||||
code, body = postResponses(t, s, screenshotSession(false))
|
||||
if code != 200 || !strings.Contains(body, "SUMMARY") {
|
||||
t.Fatalf("the next turn failed: %d %.400s", code, body)
|
||||
}
|
||||
if calls = up.calls(); len(calls) != 3 {
|
||||
t.Fatalf("the next turn was asked %d times, not once fitted", len(calls)-2)
|
||||
}
|
||||
underCap(t, calls[2])
|
||||
}
|
||||
|
||||
// When the latest user message alone is over the cap there is nothing to
|
||||
// leave out: the same body isn't sent again, and Codex is told it is a
|
||||
// byte cap (context_length_exceeded, its cue to compact), with the size
|
||||
// and the cap; another client gets a 413 saying so.
|
||||
func TestOverByteCapNothingToLeaveOut(t *testing.T) {
|
||||
var b strings.Builder
|
||||
b.WriteString(`{"model":"fake/m1","stream":true,"input":[{"type":"message","role":"user","content":[{"type":"input_text","text":"all of these"}`)
|
||||
for i := range 20 {
|
||||
fmt.Fprintf(&b, `,{"type":"input_image","image_url":"%s"}`, screenshot(i))
|
||||
}
|
||||
b.WriteString(`]}]}`)
|
||||
fresh(t)
|
||||
up := &capped{proto: provider.Responses, most: commandCodeMost, status: 400, ctype: "application/json", body: commandCodeCap}
|
||||
cappedOn(t, up)
|
||||
code, body := postResponses(t, New(), b.String())
|
||||
if code != 200 || failedCode(body) != "context_length_exceeded" {
|
||||
t.Fatalf("Codex wasn't told to compact: %d %.600s", code, body)
|
||||
}
|
||||
for _, want := range []string{"over the 32 MB limit", "over the 32.0 MB 1017dp takes in one request", "no earlier image"} {
|
||||
if !strings.Contains(body, want) {
|
||||
t.Errorf("Codex's error lacks %q: %.600s", want, body)
|
||||
}
|
||||
}
|
||||
if n := len(up.calls()); n != 1 {
|
||||
t.Fatalf("the same body was sent %d times", n)
|
||||
}
|
||||
}
|
||||
|
||||
// A plain refusal of a large request, a rate limit, or the model's window
|
||||
// full is not a byte cap, and nothing is left out for it.
|
||||
func TestByteCapRefusal(t *testing.T) {
|
||||
for _, c := range []struct {
|
||||
status int
|
||||
body string
|
||||
want bool
|
||||
}{
|
||||
{400, commandCodeCap, true},
|
||||
{500, commandCodeCap, true},
|
||||
{413, nginx413, true},
|
||||
{413, deepseekBodyCap, true},
|
||||
{413, `{"type":"error","error":{"type":"request_too_large","message":"Request exceeds the maximum size"}}`, true},
|
||||
{400, deepseekOverflow, false},
|
||||
{429, `{"error":{"message":"Request too large for gpt-4o on tokens per min (TPM): Limit 30000"}}`, false},
|
||||
{400, `{"error":{"message":"Invalid tool schema"}}`, false},
|
||||
{401, commandCodeCap, false},
|
||||
} {
|
||||
if got := byteCapRefusal(c.status, []byte(c.body)); got != c.want {
|
||||
t.Errorf("%d %.60s: %v", c.status, c.body, got)
|
||||
}
|
||||
}
|
||||
if n := statedCap([]byte(commandCodeCap), 42<<20); n != 32<<20 {
|
||||
t.Errorf("stated cap %d", n)
|
||||
}
|
||||
if n := statedCap([]byte(deepseekBodyCap), 42<<20); n != 0 {
|
||||
t.Errorf("stated cap %d of none", n)
|
||||
}
|
||||
}
|
||||
|
||||
// Each protocol's images are left out where it keeps them, the latest
|
||||
// user message's kept and the rest of the body as it came.
|
||||
func TestWithoutOldImagesEachProtocol(t *testing.T) {
|
||||
img := strings.Repeat("A", 4096)
|
||||
for _, c := range []struct {
|
||||
to provider.Protocol
|
||||
body string
|
||||
}{
|
||||
{provider.Chat, `{"messages":[{"role":"user","content":[{"type":"image_url","image_url":{"url":"data:image/png;base64,OLD` + img + `"}}]},{"role":"tool","tool_call_id":"c","content":[{"type":"text","text":"tool text"},{"type":"image_url","image_url":{"url":"data:image/png;base64,MID` + img + `"}}]},{"role":"user","content":[{"type":"text","text":"now"},{"type":"image_url","image_url":{"url":"data:image/png;base64,NEW` + img + `"}}]}]}`},
|
||||
{provider.Anthropic, `{"messages":[{"role":"user","content":[{"type":"image","source":{"type":"base64","media_type":"image/png","data":"OLD` + img + `"}}]},{"role":"user","content":[{"type":"tool_result","tool_use_id":"t","content":[{"type":"text","text":"tool text"},{"type":"image","source":{"type":"base64","media_type":"image/png","data":"MID` + img + `"}}]}]},{"role":"user","content":[{"type":"text","text":"now"},{"type":"image","source":{"type":"base64","media_type":"image/png","data":"NEW` + img + `"}}]}]}`},
|
||||
{provider.Gemini, `{"contents":[{"role":"user","parts":[{"inlineData":{"mimeType":"image/png","data":"OLD` + img + `"}}]},{"role":"user","parts":[{"functionResponse":{"name":"f","response":{"text":"tool text"}}},{"inlineData":{"mimeType":"image/png","data":"MID` + img + `"}}]},{"role":"user","parts":[{"text":"now"},{"inlineData":{"mimeType":"image/png","data":"NEW` + img + `"}}]}]}`},
|
||||
} {
|
||||
t.Run(string(c.to), func(t *testing.T) {
|
||||
out, left, ok := withoutOldImages(c.to, []byte(c.body), len(c.body)-6000)
|
||||
s := string(out)
|
||||
if !ok || left != 2 || strings.Contains(s, "OLD") || strings.Contains(s, "MID") || !strings.Contains(s, "NEW") || !strings.Contains(s, "tool text") || strings.Count(s, imageLeftOut) != 2 {
|
||||
t.Fatalf("ok %v, %d left out: %.300s", ok, left, s)
|
||||
}
|
||||
if _, _, ok := withoutOldImages(c.to, []byte(c.body), 4000); ok {
|
||||
t.Fatal("fitted under what the latest message alone holds")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// A provider that refuses the summary request however small its images
|
||||
// make it: asked smaller three times, then said as a 413, so the
|
||||
// compaction is asked as text and then made without a model, not sent
|
||||
// again into the compaction guard's hold.
|
||||
func TestCompactionOverByteCapEveryTime(t *testing.T) {
|
||||
up := &capped{proto: provider.Responses, most: 0, status: 400, ctype: "application/json", body: commandCodeCap}
|
||||
cappedOn(t, up)
|
||||
code, body := codexPost(t, screenshotSession(true))
|
||||
if code != 200 {
|
||||
t.Fatalf("Codex's compaction failed: %d %.400s", code, body)
|
||||
}
|
||||
if got := compactedText(t, body); !strings.Contains(got, "the latest ask") || strings.Contains(got, "iVBORw0KGgo") {
|
||||
t.Fatalf("local summary: %.300s", got)
|
||||
}
|
||||
calls := up.calls()
|
||||
if len(calls) > 6 {
|
||||
t.Fatalf("asked %d times", len(calls))
|
||||
}
|
||||
for i := 1; i < 4 && i < len(calls); i++ {
|
||||
if len(calls[i]) >= len(calls[i-1]) {
|
||||
t.Fatalf("ask %d (%d bytes) no smaller than the one before (%d)", i, len(calls[i]), len(calls[i-1]))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -484,6 +484,9 @@ type Server struct {
|
||||
// get in a row, for a compaction that keeps failing to stop being
|
||||
// asked (codex_compact_guard.go, #2274)
|
||||
compactFails compactFails
|
||||
// bodyCaps are the byte caps providers refused a request over
|
||||
// (body_cap.go)
|
||||
bodyCaps bodyCaps
|
||||
// codexTurns is the model each Codex last had a turn of its own
|
||||
// answered on, by caller (codexMemoryStandIn)
|
||||
codexTurns sync.Map
|
||||
@@ -4849,6 +4852,11 @@ func (s *Server) forward(ctx context.Context, p provider.Provider, to provider.P
|
||||
}
|
||||
}()
|
||||
res, err = s.forwardOnce(ctx, p, to, path, body, in)
|
||||
if err == nil && res.StatusCode >= 400 {
|
||||
// a body over the provider's byte cap: asked again with its
|
||||
// oldest images left out, or said as a 413 (body_cap.go)
|
||||
res, err = s.refitOverCap(ctx, p, to, path, body, in, res)
|
||||
}
|
||||
if err == nil && mantleRoutes(p, to) {
|
||||
res, err = s.mantleReroute(ctx, p, to, path, body, in, res)
|
||||
}
|
||||
@@ -4915,6 +4923,9 @@ func (s *Server) forwardOnce(ctx context.Context, p provider.Provider, to provid
|
||||
body = kimiLockedSampling(p, to, body)
|
||||
body = clinePin(p, to, body)
|
||||
body = codexImagesFit(p, to, body)
|
||||
// under the byte cap the provider refused a larger request over,
|
||||
// its oldest images left out (body_cap.go)
|
||||
body = s.withinCap(p, to, path, body)
|
||||
if to == provider.Responses {
|
||||
// whatever the route, Claude's blocks never reach a Responses API
|
||||
body = withoutClaudeSeals(body)
|
||||
|
||||
Reference in New Issue
Block a user