Files
magpie/internal/gateway/codex_images_test.go
T
yetone 11173c8a20 gateway: a long Computer Use turn fits each screenshot once, not every turn (fflake33 on Discord)
fflake33 (magpie 0.1.1279, macOS) sent Codex Computer Use turns of
570K-680K tokens with hundreds of screenshots through the Responses
route to codex/gpt-6.1-sol: 26.5s and 52.7s of the 41.7s and 71s to the
first token were magpie's own work, sampled in image resize, JPEG
decode/encode and JSON.

The causes, from a pprof CPU and alloc profile of a synthetic turn (160
distinct 2940x1912 JPEG screenshots, 112 MB body):
- codexImagesFit's cache of fitted images was a map cleared at 64
  entries, so past 64 screenshots every image of every turn was decoded,
  resized and JPEG-encoded again: ~19s CPU a turn (triangleResize 42 GB
  allocated over 3 turns).
- It looked each part up by path from the top of the body
  (gjson "input.%d.content.%d"), reading the 112 MB body again for every
  image: ~9s CPU a turn.

What changed:
- codexImagesFit walks the body once (ForEach over items and parts, at
  their offsets) and splices only the changed image strings; the rest of
  the body goes byte for byte as before.
- The cache (fitted) is an LRU keyed by sha256 of the limits and data
  URL, bounded at 256 MB of fitted bytes and 8192 entries, letting go of
  what goes unsent for an hour. It holds the encoded bytes, not the
  base64. A request looks all its images up before keeping any it made,
  so a conversation larger than the budget still finds what was kept
  since its last turn.
- Images not kept are made side by side, at most min(4, GOMAXPROCS) at
  once (each holds ~100 MB for a Retina screenshot); the same image twice
  in one request is made once.
- Sibling: the describer's cache (vision.go sights) was FIFO at 256, so a
  text-only model sent 300 screenshots described every one again each
  turn. It is now LRU at 2048 (a description is a few KB).

Numbers, codex_images_timing_test.go (MAGPIE_TURN_TIMING=1), magpie's
time before the fake upstream had the request, 160-163 screenshots, run
back to back at load ~15-60 on this M-series mac:
- before (de671719a): turns 1-4 31.4s, 30.6s, 31.7s, 35.2s; CPU
  27.5-28.4s per turn (pprof labels per turn)
- after: turn 1 7.5s (18.4s CPU, 160 images made in parallel), turns 2-4
  2.7s, 2.6s, 5.2s; CPU 2.4-2.6s per turn
The ~2.4s left per 112 MB turn is whole-body JSON passes (decodeJSON with
jsonValid and RawMessage clones, parseResponses, codexBody's re-marshal,
~0.4-0.8s each); not changed here, as each needs its byte-for-byte output
re-proven.

echo_ts (Codex through magpie on Copilot ~10x slower, no images): the
same timing test on a Copilot account with no images measured magpie's
local work at ~3ms (33 KB), ~13ms (215 KB) and ~56ms (989 KB) per turn
on the old code at low load, the same on the new. That is not a 10x, so
its cause is elsewhere and is not fixed here.

Tests, each broken by hand and seen red:
- TestCodexScreenshotsAreNotFittedAgainEachTurn: 100 then 101 distinct
  screenshots; the second turn makes only its new one, and sends the
  others as the same bytes. Clear-at-64 restored: "made 65 images again".
- TestCodexFittedImagesPastTheBudget: 30 images over a budget of 10;
  turns 2 and 3 make 20 each, held bytes within budget. Keeping each
  image as it is made: 30 of 30 each turn; budget unchecked: held past it.
- TestCodexFittedImagesLetGoWhenIdle.
- TestManyImagesDescribedOnce: 300 images twice to a text-only model are
  described 300 times. sightsKept 256 restored: 576.

Run: gofmt -l (clean); go vet ./... on darwin, GOOS=linux and
GOOS=windows -tags nogui; go test -race on the gateway's TestCodex*,
TestManyImagesDescribedOnce and TestTextOnlyModel* (ok); full
`set -o pipefail; go test -timeout 45m ./...` at ab88ffd55 (this
change on origin/main 2026-10-18 21:4x): every package ok except
internal/agent, which hit the 45m package timeout under load ~200
(running TestT3CodeKeepsTheUsersSettings at 0s, the known #2544/#2723);
alone with -timeout 90m it is ok (4385s, load ~250-350). gateway ok in
2600s, provider ok in 438s.

Not tried: a real Computer Use session against ChatGPT; Windows or
Linux runs of the timing test.
2026-10-19 00:26:39 +08:00

401 lines
14 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package gateway
import (
"bytes"
"container/list"
"encoding/base64"
"encoding/json"
"fmt"
"image"
"image/color"
"image/jpeg"
"image/png"
"io"
"math/rand/v2"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/tidwall/gjson"
"github.com/yetone/magpie/internal/provider"
)
// The sizes Codex's own client gives images, from openai/codex's tests
// (codex-rs/utils/image/src/image_tests.rs) and a MacBook's full-screen
// screenshot as ylorn's would be.
func TestCodexImageSizeAsCodex(t *testing.T) {
high, original := imageLimits{2048, 2500}, imageLimits{6000, 10000}
for _, c := range []struct {
l imageLimits
w, h, ow, oh int
}{
{high, 64, 32, 64, 32},
{high, 2048, 2048, 1600, 1600},
{high, 2050, 2, 2048, 2},
{original, 6401, 100, 6000, 94},
{original, 4096, 2048, 4096, 2048},
{high, 3456, 2234, 1979, 1280},
} {
if w, h := c.l.size(c.w, c.h); w != c.ow || h != c.oh {
t.Errorf("%v %dx%d → %dx%d, Codex gives %dx%d", c.l, c.w, c.h, w, h, c.ow, c.oh)
}
}
}
// screenshot is a w×h image: black on its left half, white on its right,
// with a red band 64 px tall across the middle — what has to stay where
// it was for the model to read it.
func shotImage(w, h int) *image.RGBA {
m := image.NewRGBA(image.Rect(0, 0, w, h))
for y := 0; y < h; y++ {
for x := 0; x < w; x++ {
c := color.RGBA{255, 255, 255, 255}
if x < w/2 {
c = color.RGBA{0, 0, 0, 255}
}
if y >= h/2-32 && y < h/2+32 {
c = color.RGBA{220, 20, 20, 255}
}
m.SetRGBA(x, y, c)
}
}
return m
}
func shotURL(t *testing.T, m image.Image, format string) string {
t.Helper()
var b bytes.Buffer
if format == "jpeg" {
jpeg.Encode(&b, m, &jpeg.Options{Quality: 95})
} else {
png.Encode(&b, m)
}
return "data:image/" + format + ";base64," + base64.StdEncoding.EncodeToString(b.Bytes())
}
func shotDecode(t *testing.T, url string) (image.Image, string) {
t.Helper()
comma := strings.IndexByte(url, ',')
raw, err := base64.StdEncoding.DecodeString(url[comma+1:])
if err != nil {
t.Fatalf("not base64: %v", err)
}
m, format, err := image.Decode(bytes.NewReader(raw))
if err != nil {
t.Fatalf("not an image: %v", err)
}
return m, format
}
// legible: the halves and the band are where they were, in their colours.
func shotLegible(t *testing.T, m image.Image) {
t.Helper()
b := m.Bounds()
w, h := b.Dx(), b.Dy()
at := func(x, y int) (uint32, uint32, uint32) {
r, g, bl, _ := m.At(x, y).RGBA()
return r >> 8, g >> 8, bl >> 8
}
if r, g, bl := at(w/4, h/4); r > 16 || g > 16 || bl > 16 {
t.Errorf("left half isn't black: %d %d %d", r, g, bl)
}
if r, g, bl := at(3*w/4, 3*h/4); r < 240 || g < 240 || bl < 240 {
t.Errorf("right half isn't white: %d %d %d", r, g, bl)
}
if r, g, bl := at(w/4, h/2); r < 190 || g > 50 || bl > 50 {
t.Errorf("the band isn't red: %d %d %d", r, g, bl)
}
}
func codexAccount() provider.Provider {
return provider.Provider{ID: "codex", Account: &provider.Account{Agent: "codex", User: "me@example.com"}}
}
func responsesWith(parts ...map[string]any) []byte {
b, _ := json.Marshal(map[string]any{"model": "gpt-5.5", "stream": true, "input": []any{
map[string]any{"type": "message", "role": "user", "content": append([]any{
map[string]any{"type": "input_text", "text": "what does this show?"}}, anys(parts)...)},
map[string]any{"type": "function_call_output", "call_id": "c1", "output": []any{
map[string]any{"type": "input_text", "text": "the page"}}},
}})
return b
}
func anys(parts []map[string]any) []any {
out := make([]any, len(parts))
for i, p := range parts {
out[i] = p
}
return out
}
// A screenshot larger than Codex's own client sends goes to a ChatGPT
// account at the size Codex would send it, as a PNG still, and the
// picture in it is the same picture. The rest of the request is the same
// bytes, for the prompt cache.
func TestCodexScreenshotSizedAsCodex(t *testing.T) {
big := shotURL(t, shotImage(3456, 2234), "png")
body := responsesWith(map[string]any{"type": "input_image", "image_url": big})
out := codexImagesFit(codexAccount(), provider.Responses, body)
url := gjson.GetBytes(out, "input.0.content.1.image_url").String()
if !strings.HasPrefix(url, "data:image/png;base64,") {
t.Fatalf("not a PNG: %.40s", url)
}
m, format := shotDecode(t, url)
if format != "png" || m.Bounds().Dx() != 1979 || m.Bounds().Dy() != 1280 {
t.Fatalf("%s %v, Codex sends 1979x1280 png", format, m.Bounds())
}
shotLegible(t, m)
if len(out) >= len(body) {
t.Errorf("%d bytes after, %d before", len(out), len(body))
}
if string(bytes.Replace(out, []byte(url), []byte("IMG"), 1)) != string(bytes.Replace(body, []byte(big), []byte("IMG"), 1)) {
t.Errorf("the rest of the request changed")
}
}
// A JPEG stays a JPEG, at Codex's quality; an image in a tool's output is
// sized too; "original" detail has Codex's larger budget.
func TestCodexImagesSizedInEveryPlace(t *testing.T) {
photo := shotURL(t, shotImage(3000, 3000), "jpeg")
wide := shotURL(t, shotImage(6401, 100), "png")
body := responsesWith(
map[string]any{"type": "input_image", "image_url": photo, "detail": "high"},
map[string]any{"type": "input_image", "image_url": wide, "detail": "original"},
)
body = []byte(strings.Replace(string(body), `{"text":"the page","type":"input_text"}`,
`{"text":"the page","type":"input_text"},{"type":"input_image","image_url":"`+photo+`"}`, 1))
out := codexImagesFit(codexAccount(), provider.Responses, body)
for path, want := range map[string][3]any{
"input.0.content.1.image_url": {"jpeg", 1600, 1600},
"input.0.content.2.image_url": {"png", 6000, 94},
"input.1.output.1.image_url": {"jpeg", 1600, 1600},
} {
url := gjson.GetBytes(out, path).String()
if url == "" {
t.Fatalf("%s gone: %.300s", path, out)
}
m, format := shotDecode(t, url)
if format != want[0] || m.Bounds().Dx() != want[1] || m.Bounds().Dy() != want[2] {
t.Errorf("%s: %s %v, want %v", path, format, m.Bounds(), want)
}
if want[1] == 1600 {
shotLegible(t, m)
}
}
}
// What Codex's client sends as it came goes as it came: an image that
// fits, one with "low" detail (Codex refuses that itself), and anything
// that isn't an image a decoder reads.
func TestCodexImagesThatFitGoAsTheyCame(t *testing.T) {
small := shotURL(t, shotImage(64, 32), "png")
big := shotURL(t, shotImage(3000, 3000), "png")
body := responsesWith(
map[string]any{"type": "input_image", "image_url": small},
map[string]any{"type": "input_image", "image_url": big, "detail": "low"},
map[string]any{"type": "input_image", "image_url": "data:image/png;base64,bm90IGFuIGltYWdl"},
map[string]any{"type": "input_image", "image_url": "https://example.invalid/a.png"},
)
if out := codexImagesFit(codexAccount(), provider.Responses, body); !bytes.Equal(out, body) {
t.Errorf("changed")
}
}
// Only a ChatGPT account's requests are sized: another vendor, an API
// key, or another protocol is sent the image as the agent sent it.
func TestCodexImagesOnlyForChatGPT(t *testing.T) {
body := responsesWith(map[string]any{"type": "input_image", "image_url": shotURL(t, shotImage(3456, 2234), "png")})
for _, c := range []struct {
p provider.Provider
to provider.Protocol
}{
{provider.Provider{ID: "openai"}, provider.Responses},
{provider.Provider{ID: "claude", Account: &provider.Account{Agent: "claude"}}, provider.Responses},
{codexAccount(), provider.Chat},
} {
if out := codexImagesFit(c.p, c.to, body); !bytes.Equal(out, body) {
t.Errorf("%s %v: changed", c.p.ID, c.to)
}
}
}
// An agent other than Codex — Pi's openai-codex, as ylorn's — asking a
// ChatGPT account through magpie: the backend gets the screenshot at
// Codex's size, which takes the turn from past 1 MiB to under it.
func TestCodexAccountGetsScreenshotAtCodexSize(t *testing.T) {
codexSignedIn(t, "spare@example.com")
var got []byte
up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
got, _ = io.ReadAll(r.Body)
io.WriteString(w, sse(
`data: {"type":"response.created","response":{"id":"r1","model":"gpt-5.5"}}`,
`data: {"type":"response.output_text.delta","delta":"a screenshot"}`,
`data: {"type":"response.completed","response":{"id":"r1","usage":{"input_tokens":7,"output_tokens":2}}}`))
}))
t.Cleanup(up.Close)
was := provider.CodexBase
provider.CodexBase = up.URL + "/backend-api/codex"
t.Cleanup(func() { provider.CodexBase = was })
// a photo along its top, which no PNG makes small: the turn past
// 1 MiB, as ylorn's was
shot := shotImage(3456, 2234)
noise := rand.New(rand.NewPCG(1, 2))
for i := 0; i < 160*shot.Stride; i++ {
if i%4 != 3 {
shot.Pix[i] = byte(noise.Uint32())
}
}
body := string(responsesWith(map[string]any{"type": "input_image", "image_url": shotURL(t, shot, "png")}))
body = strings.Replace(body, `"model":"gpt-5.5"`, `"model":"codex/gpt-5.5"`, 1)
if len(body) < 1<<20 {
t.Fatalf("the turn is %d bytes, not past 1 MiB", len(body))
}
rec := httptest.NewRecorder()
New().Handler().ServeHTTP(rec, httptest.NewRequest("POST", "/v1/responses", strings.NewReader(body)))
if rec.Code != 200 || got == nil {
t.Fatalf("status %d: %.300s", rec.Code, rec.Body.String())
}
m, _ := shotDecode(t, gjson.GetBytes(got, "input.0.content.1.image_url").String())
if m.Bounds().Dx() != 1979 || m.Bounds().Dy() != 1280 {
t.Errorf("sent %v, Codex sends 1979x1280", m.Bounds())
}
t.Logf("%d bytes from the agent, %d to ChatGPT", len(body), len(got))
}
// freshFitted gives a test a cache of fitted images of its own, with
// budget bytes, and counts the images made again from here.
func freshFitted(t *testing.T, budget int) func() int64 {
t.Helper()
was, wasBudget := fitted, fittedBudget
fitted, fittedBudget = &fitCache{m: map[[32]byte]*list.Element{}}, budget
t.Cleanup(func() { fitted, fittedBudget = was, wasBudget })
from := refits.Load()
return func() int64 { return refits.Load() - from }
}
// computerUseRequest is a Responses turn with each of shots as a
// Computer Use tool's screenshot, as Codex sends a conversation's every
// past screenshot again on each turn.
func computerUseRequest(shots []string) []byte {
var input []any
for i, shot := range shots {
id := fmt.Sprintf("call_%d", i)
input = append(input,
map[string]any{"type": "function_call", "call_id": id, "name": "computer", "arguments": `{"action":"screenshot"}`},
map[string]any{"type": "function_call_output", "call_id": id, "output": []any{
map[string]any{"type": "input_image", "image_url": shot}}})
}
b, _ := json.Marshal(map[string]any{"model": "gpt-5.5", "stream": true, "input": input})
return b
}
// wideShots are n distinct PNGs wider than Codex sends, each made
// smaller once it is fitted: cheap to make, as a test needs.
func wideShots(t *testing.T, n int) []string {
t.Helper()
out := make([]string, n)
for i := range out {
m := image.NewRGBA(image.Rect(0, 0, 2100, 4))
for x := 0; x < 2100; x++ {
m.SetRGBA(x, i%4, color.RGBA{byte(i), byte(i >> 8), byte(x), 255})
}
out[i] = shotURL(t, m, "png")
}
return out
}
// A long Computer Use conversation (fflake33, Discord: hundreds of
// screenshots) sends every past screenshot again on each turn. Each is
// decoded, resized and written again once; the next turn makes only its
// new one, past the 64 images the cache held, and sends the others as the
// same bytes as before, which the prompt cache needs.
func TestCodexScreenshotsAreNotFittedAgainEachTurn(t *testing.T) {
made := freshFitted(t, fittedBudget)
shots := wideShots(t, 101)
first := codexImagesFit(codexAccount(), provider.Responses, computerUseRequest(shots[:100]))
if n := made(); n != 100 {
t.Fatalf("the first turn made %d images, want 100", n)
}
next := codexImagesFit(codexAccount(), provider.Responses, computerUseRequest(shots))
if n := made() - 100; n != 1 {
t.Errorf("the next turn made %d images again, want only its new one", n)
}
for i := range 100 {
path := fmt.Sprintf("input.%d.output.0.image_url", 2*i+1)
was, now := gjson.GetBytes(first, path).String(), gjson.GetBytes(next, path).String()
if was == shots[i] || now != was {
t.Fatalf("screenshot %d: not the same fitted bytes on the next turn", i)
}
}
m, _ := shotDecode(t, gjson.GetBytes(next, "input.201.output.0.image_url").String())
if m.Bounds().Dx() != 2048 {
t.Errorf("the new screenshot went at %v", m.Bounds())
}
}
// Past what the cache may hold, each turn still finds the screenshots kept
// since the last and makes only the rest again. Keeping each image as it
// is made, in a conversation whose images come in the same order each
// turn, would drop each one just before it is sent again and find none.
// What is held stays within the budget.
func TestCodexFittedImagesPastTheBudget(t *testing.T) {
shots := wideShots(t, 30)
one := len(fitKeyEntry(t, shots[0]).data)
made := freshFitted(t, 10*one+one/2)
body := computerUseRequest(shots)
was := int64(0)
for turn := 1; turn <= 3; turn++ {
codexImagesFit(codexAccount(), provider.Responses, body)
n := made() - was
was += n
if turn == 1 && n != 30 || turn > 1 && n != 20 {
t.Errorf("turn %d made %d of 30 images, with 10 kept", turn, n)
}
fitted.Lock()
held := fitted.bytes
fitted.Unlock()
if held > fittedBudget {
t.Errorf("turn %d: %d bytes held, past the budget of %d", turn, held, fittedBudget)
}
}
}
// fitKeyEntry is shot fitted to Codex's high limits, made directly.
func fitKeyEntry(t *testing.T, shot string) fitEntry {
t.Helper()
e := codexImageRefit(shot[strings.IndexByte(shot, ',')+1:], imageLimits{2048, 2500})
if e.data == nil {
t.Fatal("the screenshot fits as it came")
}
return e
}
// What no request has sent for fittedIdle is let go.
func TestCodexFittedImagesLetGoWhenIdle(t *testing.T) {
made := freshFitted(t, fittedBudget)
shots := wideShots(t, 2)
codexImagesFit(codexAccount(), provider.Responses, computerUseRequest(shots[:1]))
fitted.Lock()
for el := fitted.order.Front(); el != nil; el = el.Next() {
el.Value.(*fitItem).used = time.Now().Add(-fittedIdle - time.Minute)
}
fitted.Unlock()
codexImagesFit(codexAccount(), provider.Responses, computerUseRequest(shots[1:]))
fitted.Lock()
n, held := len(fitted.m), fitted.bytes
fitted.Unlock()
if n != 1 || made() != 2 {
t.Errorf("%d kept after the first went idle, %d made", n, made())
}
if want := len(fitKeyEntry(t, shots[1]).data); held != want {
t.Errorf("%d bytes held, want %d", held, want)
}
}