Files
magpie/internal/imagemcp/big_image_test.go
T
yetone f0dc9ea695 imagemcp, gateway: a 4K image a relay answers by URL is saved, and one that can't be downloaded is answered with its URL, not lost (#1576, david-zdw)
What the reporter saw: generate_image (magpie mcp image) failed on 4K and
2048x1152 with "image 1: context deadline exceeded" and "no image: context
deadline exceeded", while the same request to /v1/images/generations came
back in ~40 s, and usage.jsonl showed the upstream's 200. Their relay
answers with a URL whatever response_format says.

Two causes, one per error:

- "image 1: context deadline exceeded" was generate_image's own download
  of the URL (imagemcp.download): 2 minutes for the whole of it, on
  http.DefaultTransport, which knows the global proxy but not a provider's
  own (#237). A 10 MB PNG that was still coming was cut, and the error
  dropped the URL of an image already drawn and paid for. Any earlier
  image of n was saved but not said either.
- "no image: context deadline exceeded" (the usage log's 502s at
  300002-300032 ms) was the gateway's drawTimeout (5 min) expiring while
  it read a vendor's answer that had already begun: sendWith passed the
  bare context error up. The vendor really took over 5 minutes there;
  this commit doesn't change that limit, it says what happened.

What changed:

- gateway: an images caller that asks response_format "b64_json" gets the
  image itself. One the vendor gave only a URL for is fetched by the
  gateway's own client, through the provider's proxy (p.Via), after the
  draw and outside drawTimeout. One that can't be fetched is answered by
  its URL, as before, never dropped. A caller that asks no format still
  gets the URL. Nothing is sent to the vendor differently.
- gateway.FetchImage: an image download gives up when nothing has come
  for ImageStall (1 min) or it has taken ImageLongest (5 min), and says
  which and how much had come. A slow download goes on while it moves.
  The edits' fetchPicture uses it too.
- gateway: a vendor that began answering but hadn't finished in
  drawTimeout is a 504 "<name> began answering after Ns (200 OK) but
  hadn't sent all of its answer in 5m0s", not a 502 "context deadline
  exceeded".
- imagemcp: asks for b64_json; downloads a URL the gateway still hands it
  with FetchImage; an image it can't have is answered with the vendor's
  URL to download it from, beside the ones saved (an error only when
  none was). Its client to the gateway waits ToolTimeout (11 min), past
  the draw and the fetch together, not 6 minutes.

What was run:

- Reproduced on the old code: the new TestFourKImageByURLIsSaved (a real
  3840x2160 PNG, 9.8 MB, served by URL in 256 KB pieces over ~4 s) with
  the old download's 2-minute cap scaled to 1 s fails with the
  reporter's exact "image 1: context deadline exceeded"; the stalled
  case fails the same way, with no URL in the error.
- Broke each part by hand and watched its test go red: no inline fetch,
  fetch not through the provider's proxy, the bare deadline message, the
  stall timer not reset (a total cap again), a lost image ending the
  call, the MCP not asking b64_json.
- go test ./internal/imagemcp/ ./internal/gateway/ ; the full
  go test -tags nogui ./... ; gofmt -l ; GOOS=linux and GOOS=windows
  go vet on both packages.
- On the Windows box (Windows 11 x64): imagemcp.test.exe all passed, and
  gateway.test.exe for the new tests and the images/ModelScope tests.

Not tried: the reporter's relay itself (never contacted), and a real
4K draw end to end. Why their URL took over 2 minutes from the MCP when
their own download took 7.5 s isn't known from here: a provider proxy
the MCP didn't use is one way it happens; a slow file host is another.
Both are covered now.
2026-10-11 14:59:23 +08:00

197 lines
7.0 KiB
Go

package imagemcp
import (
"bytes"
"encoding/base64"
"encoding/json"
"image"
"image/color"
pngenc "image/png"
"math/rand/v2"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"sync"
"testing"
"time"
"github.com/yetone/magpie/internal/gateway"
)
// fourK is a real 3840x2160 PNG of about the size #1576's relay sent
// (10.6 MB): a gradient with noise over part of it, which doesn't compress.
var fourK = sync.OnceValue(func() []byte {
const w, h = 3840, 2160
img := image.NewNRGBA(image.Rect(0, 0, w, h))
r := rand.New(rand.NewPCG(1576, 1))
for y := range h {
noisy := y%5 < 2
for x := range w {
c := color.NRGBA{uint8(x * 255 / w), uint8(y * 255 / h), 128, 255}
if noisy {
c.R, c.G, c.B = uint8(r.Uint32()), uint8(r.Uint32()), uint8(r.Uint32())
}
img.SetNRGBA(x, y, c)
}
}
var b bytes.Buffer
(&pngenc.Encoder{CompressionLevel: pngenc.BestSpeed}).Encode(&b, img)
return b.Bytes()
})
// slowFile serves b in 256 KB pieces, every gap apart, as a vendor's
// file host far away does; with stallAfter > 0 it sends that much and
// then nothing more.
func slowFile(b []byte, gap time.Duration, stallAfter int) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "image/png")
for off := 0; off < len(b); off += 256 << 10 {
if stallAfter > 0 && off >= stallAfter {
select {
case <-r.Context().Done():
case <-time.After(10 * time.Second):
}
return
}
w.Write(b[off:min(off+256<<10, len(b))])
w.(http.Flusher).Flush()
time.Sleep(gap)
}
}
}
// urlGateway answers every images request with the URLs, whatever
// response_format asked (#1576's relay ignores it), and keeps the bodies.
type urlGateway struct {
mu sync.Mutex
urls []string
body []string
}
func (g *urlGateway) ServeHTTP(w http.ResponseWriter, r *http.Request) {
var b bytes.Buffer
b.ReadFrom(r.Body)
g.mu.Lock()
g.body = append(g.body, b.String())
g.mu.Unlock()
var data []map[string]string
for _, u := range g.urls {
data = append(data, map[string]string{"url": u})
}
json.NewEncoder(w).Encode(map[string]any{"model": "one2api/gpt-image-2.5-sunburst", "data": data})
}
func initialized(t *testing.T, g http.Handler, project string) *client {
c := start(t, g, project)
c.call("initialize", map[string]any{"protocolVersion": "2025-06-18", "capabilities": map[string]any{"roots": map[string]any{}}, "clientInfo": map[string]any{"name": "dsh-mcp-client", "version": "1"}})
return c
}
// await calls generate_image and waits on generation_result for its answer.
func (c *client) await(args map[string]any) (map[string]any, string) {
c.t.Helper()
r := c.call("tools/call", map[string]any{"name": "generate_image", "arguments": args})
for range 400 {
out := text(r)
i := strings.Index(out, `with id "`)
if r["isError"] == true || i < 0 {
return r, out
}
id := out[i+len(`with id "`):]
id = id[:strings.Index(id, `"`)]
r = c.call("tools/call", map[string]any{"name": "generation_result", "arguments": map[string]any{"id": id}})
}
c.t.Fatalf("never done: %v", r)
return nil, ""
}
func shorterWaits(t *testing.T, stall time.Duration) {
wasWithin, wasStall := answerWithin, gateway.ImageStall
answerWithin, gateway.ImageStall = 200*time.Millisecond, stall
t.Cleanup(func() { answerWithin, gateway.ImageStall = wasWithin, wasStall })
}
// #1576: a relay drew the 4K image in 40 s and answered with its URL, and
// generate_image lost it, "image 1: context deadline exceeded": its own
// download of the 10.6 MB had 2 minutes in all, whether or not it was still
// coming. A download that keeps coming now goes on to the end (here the
// cap that was is played by a stall 4 times shorter than the download),
// and the gateway was asked for the image itself.
func TestFourKImageByURLIsSaved(t *testing.T) {
big := fourK()
if len(big) < 9<<20 {
t.Fatalf("the 4K image is %d bytes, not about 10.6 MB", len(big))
}
t.Logf("the 4K PNG is %.1f MB", float64(len(big))/(1<<20))
shorterWaits(t, time.Second)
files := httptest.NewServer(slowFile(big, 100*time.Millisecond, 0)) // ~4 s in all
t.Cleanup(files.Close)
g := &urlGateway{urls: []string{files.URL + "/4k.png"}}
project := t.TempDir()
c := initialized(t, g, project)
began := time.Now()
r, out := c.await(map[string]any{"prompt": "a 4K city", "size": "3840x2160", "path": "city.png"})
saved := filepath.Join(project, "city.png")
if r["isError"] == true || !strings.Contains(out, saved) {
t.Fatalf("after %s: %s", time.Since(began).Round(time.Millisecond), out)
}
if took := time.Since(began); took < 3*time.Second {
t.Fatalf("the download took %s, not the slow one this is about", took)
}
if b, _ := os.ReadFile(saved); !bytes.Equal(b, big) {
t.Fatalf("saved %d bytes of %d", len(b), len(big))
}
if !strings.Contains(g.body[0], `"response_format":"b64_json"`) {
t.Fatalf("the gateway was asked %s", g.body[0])
}
}
// The same image as b64_json (what the gateway now answers) is saved whole.
func TestFourKImageAsB64IsSaved(t *testing.T) {
big := fourK()
shorterWaits(t, time.Second)
g := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
json.NewEncoder(w).Encode(map[string]any{"model": "one2api/gpt-image-2.5-sunburst", "data": []map[string]string{{"b64_json": base64.StdEncoding.EncodeToString(big)}}})
})
project := t.TempDir()
c := initialized(t, g, project)
r, out := c.await(map[string]any{"prompt": "a 4K city", "size": "3840x2160", "path": "city.png"})
saved := filepath.Join(project, "city.png")
if r["isError"] == true || !strings.Contains(out, saved) {
t.Fatalf("%s", out)
}
if b, _ := os.ReadFile(saved); !bytes.Equal(b, big) {
t.Fatalf("saved %d bytes of %d", len(b), len(big))
}
}
// A download that stops is given up when nothing has come for ImageStall,
// and the image, drawn and paid for, is answered by where the vendor keeps
// it; one of two that came is saved and said beside it.
func TestStalledDownloadSaysWhereTheImageIs(t *testing.T) {
big := fourK()
shorterWaits(t, 300*time.Millisecond)
stuck := httptest.NewServer(slowFile(big, 0, 3<<20))
t.Cleanup(stuck.Close)
fine := httptest.NewServer(slowFile(big, 0, 0))
t.Cleanup(fine.Close)
project := t.TempDir()
c := initialized(t, &urlGateway{urls: []string{stuck.URL + "/a.png"}}, project)
r, out := c.await(map[string]any{"prompt": "a 4K city", "path": "city.png"})
if r["isError"] != true || !strings.Contains(out, stuck.URL+"/a.png") || !strings.Contains(out, "nothing came for 300ms, after 3.0 MB") {
t.Fatalf("%v: %s", r["isError"], out)
}
c = initialized(t, &urlGateway{urls: []string{fine.URL + "/a.png", stuck.URL + "/b.png"}}, project)
r, out = c.await(map[string]any{"prompt": "two cities", "n": 2, "path": "two.png"})
if r["isError"] == true || !strings.Contains(out, filepath.Join(project, "two-1.png")) || !strings.Contains(out, "Not saved: image 2") || !strings.Contains(out, stuck.URL+"/b.png") {
t.Fatalf("%s", out)
}
if b, _ := os.ReadFile(filepath.Join(project, "two-1.png")); !bytes.Equal(b, big) {
t.Fatalf("saved %d bytes of %d", len(b), len(big))
}
}