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.
240 lines
9.1 KiB
Go
240 lines
9.1 KiB
Go
package gateway
|
|
|
|
import (
|
|
"encoding/base64"
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"strings"
|
|
"sync"
|
|
"testing"
|
|
|
|
"github.com/yetone/magpie/internal/catalog"
|
|
"github.com/yetone/magpie/internal/provider"
|
|
"github.com/yetone/magpie/internal/settings"
|
|
)
|
|
|
|
// noVision turns describing off, for a test of images turned away.
|
|
func noVision(t *testing.T) {
|
|
t.Helper()
|
|
s := settings.Load()
|
|
s.Vision = "off"
|
|
if err := settings.Save(s); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
}
|
|
|
|
// eyeUp is an upstream with a text-only model and one that sees: the one
|
|
// that sees describes every image as a red square, or fails when fail is
|
|
// set; what each model is sent is kept.
|
|
type eyeUp struct {
|
|
mu sync.Mutex
|
|
fail bool
|
|
bodies map[string][]string
|
|
}
|
|
|
|
func (u *eyeUp) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
|
body, _ := io.ReadAll(r.Body)
|
|
model := modelOf(body)
|
|
u.mu.Lock()
|
|
if u.bodies == nil {
|
|
u.bodies = map[string][]string{}
|
|
}
|
|
u.bodies[model] = append(u.bodies[model], string(body))
|
|
fail := u.fail
|
|
u.mu.Unlock()
|
|
w.Header().Set("Content-Type", "application/json")
|
|
if strings.HasSuffix(model, "eye") && fail {
|
|
w.WriteHeader(500)
|
|
io.WriteString(w, `{"error":{"message":"eye is down"}}`)
|
|
return
|
|
}
|
|
answer := "ok"
|
|
if strings.HasSuffix(model, "eye") {
|
|
answer = "A red square with the word HELLO in it."
|
|
}
|
|
if strings.Contains(string(body), `"stream":true`) {
|
|
w.Header().Set("Content-Type", "text/event-stream")
|
|
io.WriteString(w, `data: {"id":"x","choices":[{"index":0,"delta":{"role":"assistant","content":"`+answer+`"}}]}`+"\n\n")
|
|
io.WriteString(w, `data: {"id":"x","choices":[{"index":0,"delta":{},"finish_reason":"stop"}],"usage":{"prompt_tokens":1,"completion_tokens":1}}`+"\n\n")
|
|
io.WriteString(w, "data: [DONE]\n\n")
|
|
return
|
|
}
|
|
io.WriteString(w, `{"id":"x","choices":[{"index":0,"message":{"role":"assistant","content":"`+answer+`"},"finish_reason":"stop"}]}`)
|
|
}
|
|
|
|
func (u *eyeUp) sent(model string) []string {
|
|
u.mu.Lock()
|
|
defer u.mu.Unlock()
|
|
return append([]string(nil), u.bodies[model]...)
|
|
}
|
|
|
|
func eyed(t *testing.T) (*Server, *eyeUp) {
|
|
t.Helper()
|
|
fresh(t)
|
|
u := &eyeUp{}
|
|
up := httptest.NewServer(u)
|
|
t.Cleanup(up.Close)
|
|
if err := provider.Save(provider.Provider{ID: "probe", Name: "Probe", Chat: up.URL + "/v1", Key: "key", Models: []string{"text", "eye"}}); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := catalog.SaveLive("probe", up.URL+"/v1", []catalog.Model{
|
|
{ID: "text", ImageInput: imageInputBool(false)},
|
|
{ID: "eye", Images: true, ImageInput: imageInputBool(true)},
|
|
}); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
return New(), u
|
|
}
|
|
|
|
func TestTextOnlyModelIsGivenTheImagesDescription(t *testing.T) {
|
|
s, u := eyed(t)
|
|
cases := []struct{ path, body string }{
|
|
{"/v1/chat/completions", `{"model":"probe/text","messages":[{"role":"user","content":[{"type":"text","text":"read"},{"type":"image_url","image_url":{"url":"data:image/png;base64,aGVsbG8="}}]}]}`},
|
|
{"/v1/responses", `{"model":"probe/text","input":[{"role":"user","content":[{"type":"input_text","text":"read"},{"type":"input_image","image_url":"data:image/png;base64,aGVsbG8="}]}]}`},
|
|
{"/v1/messages", `{"model":"probe/text","max_tokens":16,"messages":[{"role":"user","content":[{"type":"text","text":"read"},{"type":"image","source":{"type":"base64","media_type":"image/png","data":"aGVsbG8="}}]}]}`},
|
|
{"/v1beta/models/probe/text:generateContent", `{"contents":[{"role":"user","parts":[{"text":"read"},{"inlineData":{"mimeType":"image/png","data":"aGVsbG8="}}]}]}`},
|
|
}
|
|
for _, tc := range cases {
|
|
rec := httptest.NewRecorder()
|
|
s.Handler().ServeHTTP(rec, httptest.NewRequest("POST", tc.path, strings.NewReader(tc.body)))
|
|
if rec.Code != 200 {
|
|
t.Errorf("%s: %d %s", tc.path, rec.Code, rec.Body.String())
|
|
}
|
|
}
|
|
got := u.sent("text")
|
|
if len(got) != len(cases) {
|
|
t.Fatalf("text model sent %d requests, want %d", len(got), len(cases))
|
|
}
|
|
for i, b := range got {
|
|
if !strings.Contains(b, "HELLO") || !strings.Contains(b, "probe/eye describes it") || strings.Contains(b, "aGVsbG8=") {
|
|
t.Errorf("%s: text model was sent %s", cases[i].path, b)
|
|
}
|
|
}
|
|
// the same image in four requests is described once
|
|
if n := len(u.sent("eye")); n != 1 {
|
|
t.Fatalf("the image was described %d times", n)
|
|
}
|
|
if !strings.Contains(u.sent("eye")[0], "aGVsbG8=") {
|
|
t.Fatalf("the describer wasn't sent the image: %s", u.sent("eye")[0])
|
|
}
|
|
}
|
|
|
|
func TestVisionSettingPicksTheDescriber(t *testing.T) {
|
|
s, u := eyed(t)
|
|
// a second model that sees, which the setting names
|
|
up2 := &eyeUp{}
|
|
srv := httptest.NewServer(up2)
|
|
t.Cleanup(srv.Close)
|
|
if err := provider.Save(provider.Provider{ID: "other", Name: "Other", Chat: srv.URL + "/v1", Key: "key", Models: []string{"bigeye"}}); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := catalog.SaveLive("other", srv.URL+"/v1", []catalog.Model{{ID: "bigeye", Images: true, ImageInput: imageInputBool(true)}}); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
st := settings.Load()
|
|
st.Vision = "other/bigeye"
|
|
if err := settings.Save(st); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
code, body := postAs(t, s, "", `{"model":"probe/text","messages":[{"role":"user","content":[{"type":"image_url","image_url":"https://example.com/a.png"}]}]}`)
|
|
if code != 200 {
|
|
t.Fatalf("%d %s", code, body)
|
|
}
|
|
if len(u.sent("eye")) != 0 || len(up2.sent("bigeye")) != 1 {
|
|
t.Fatalf("eye asked %d times, bigeye %d", len(u.sent("eye")), len(up2.sent("bigeye")))
|
|
}
|
|
if !strings.Contains(u.sent("text")[0], "other/bigeye describes it") {
|
|
t.Fatalf("text model was sent %s", u.sent("text")[0])
|
|
}
|
|
}
|
|
|
|
func TestImageThatCantBeDescribed(t *testing.T) {
|
|
s, u := eyed(t)
|
|
u.fail = true
|
|
code, body := postAs(t, s, "", `{"model":"probe/text","messages":[{"role":"user","content":[{"type":"text","text":"read"},{"type":"image_url","image_url":{"url":"data:image/png;base64,aGVsbG8="}}]}]}`)
|
|
if code != 502 || !strings.Contains(body, "couldn't describe the image") || len(u.sent("text")) != 0 {
|
|
t.Fatalf("current image: %d %s; text model sent %d", code, body, len(u.sent("text")))
|
|
}
|
|
// an older turn's image that can't be described is left out
|
|
code, body = postAs(t, s, "", `{"model":"probe/text","messages":[{"role":"user","content":[{"type":"image_url","image_url":{"url":"data:image/png;base64,b2xk"}}]},{"role":"assistant","content":"seen"},{"role":"user","content":"and now?"}]}`)
|
|
if code != 200 {
|
|
t.Fatalf("older image: %d %s", code, body)
|
|
}
|
|
if got := u.sent("text"); len(got) != 1 || !strings.Contains(got[0], "couldn't be described") {
|
|
t.Fatalf("text model was sent %v", got)
|
|
}
|
|
// a failure isn't kept
|
|
u.mu.Lock()
|
|
u.fail = false
|
|
u.mu.Unlock()
|
|
if code, body := postAs(t, s, "", `{"model":"probe/text","messages":[{"role":"user","content":[{"type":"image_url","image_url":{"url":"data:image/png;base64,aGVsbG8="}}]}]}`); code != 200 {
|
|
t.Fatalf("after recovery: %d %s", code, body)
|
|
}
|
|
}
|
|
|
|
func TestGroupsTextOnlyMemberIsGivenTheDescription(t *testing.T) {
|
|
s, u := eyed(t)
|
|
if err := provider.SaveGroup(provider.Group{Name: "Mixed", Members: []string{"probe/text", "probe/eye"}, Routing: provider.Ordered}); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
code, body := postAs(t, s, "", `{"model":"group/mixed","messages":[{"role":"user","content":[{"type":"text","text":"read"},{"type":"image_url","image_url":{"url":"data:image/png;base64,aGVsbG8="}}]}]}`)
|
|
if code != 200 {
|
|
t.Fatalf("%d %s", code, body)
|
|
}
|
|
if got := u.sent("text"); len(got) != 1 || !strings.Contains(got[0], "HELLO") {
|
|
t.Fatalf("the group's first member was sent %v", got)
|
|
}
|
|
}
|
|
|
|
func TestDescriberThatCantSeeIsntAskedToDescribe(t *testing.T) {
|
|
s, u := eyed(t)
|
|
// the setting names a text-only model: its own request is turned away,
|
|
// not described by itself again and again
|
|
st := settings.Load()
|
|
st.Vision = "probe/text"
|
|
if err := settings.Save(st); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
code, body := postAs(t, s, "", `{"model":"probe/text","messages":[{"role":"user","content":[{"type":"image_url","image_url":{"url":"data:image/png;base64,aGVsbG8="}}]}]}`)
|
|
if code != 502 || len(u.sent("text")) != 0 {
|
|
t.Fatalf("%d %s; text model sent %d", code, body, len(u.sent("text")))
|
|
}
|
|
}
|
|
|
|
func TestSeerPicksAModelThatSees(t *testing.T) {
|
|
eyed(t)
|
|
if m, ok := seer(); !ok || m != "probe/eye" {
|
|
t.Fatalf("seer = %q %v", m, ok)
|
|
}
|
|
noVision(t)
|
|
if _, ok := seer(); ok {
|
|
t.Fatal("seer with vision off")
|
|
}
|
|
}
|
|
|
|
// A long conversation sends every past screenshot again on each turn
|
|
// (fflake33, Discord: hundreds of them). Each is described once, not again
|
|
// on the next turn once there are more than 256.
|
|
func TestManyImagesDescribedOnce(t *testing.T) {
|
|
s, u := eyed(t)
|
|
const n = 300
|
|
var parts []string
|
|
for i := range n {
|
|
img := base64.StdEncoding.EncodeToString([]byte(fmt.Sprintf("screenshot %d", i)))
|
|
parts = append(parts, `{"type":"input_image","image_url":"data:image/png;base64,`+img+`"}`)
|
|
}
|
|
body := `{"model":"probe/text","input":[{"role":"user","content":[{"type":"input_text","text":"read"},` + strings.Join(parts, ",") + `]}]}`
|
|
for turn := 1; turn <= 2; turn++ {
|
|
rec := httptest.NewRecorder()
|
|
s.Handler().ServeHTTP(rec, httptest.NewRequest("POST", "/v1/responses", strings.NewReader(body)))
|
|
if rec.Code != 200 {
|
|
t.Fatalf("turn %d: %d %.300s", turn, rec.Code, rec.Body.String())
|
|
}
|
|
}
|
|
if got := len(u.sent("eye")); got != n {
|
|
t.Fatalf("%d images described %d times over two turns, want each once", n, got)
|
|
}
|
|
}
|