Files
magpie/internal/imagemcp/big_image_test.go
T
JoeyWu-tech d5d72a82af imagemcp, davsync: slow-download tests leave room for growing the download's buffer (#3419)
TestFourKImageByURLIsSaved, TestStalledDownloadSaysWhereTheImageIs and
TestSlowTransferIsNotCutShort shorten a download watchdog to 1 s or
300 ms. Each watchdog is put back when bytes come, and the time it
counts includes this process storing them: FetchImage's buf.Write, and
the GET's io.ReadAll, which in Go 1.26 fills fresh chunks half the size
of what has come. At the real 60 s that is nothing. At 1 s and 300 ms
these went red here, beside a full suite on a Linux box, with the line
never stopped:
  big_image_test.go:153: after 4.096s: image 1 was drawn but couldn't
    be downloaded (nothing came for 1s, after 4.2 MB)
  big_image_test.go:207: image 1 ... (nothing came for 300ms, after
    8.2 MB), the 4K image that comes in full
  big_image_test.go:207: image 1 ... (nothing came for 300ms, after
    0.0 MB), the same
  stall_test.go:180: slow download: the server sent and took nothing
    for 1s (GET): the line or the server stopped (twice)
A probe beside a full suite wrote 256 KB pieces into a bytes.Buffer up
to 10 MB, as FetchImage does. Of 262,440 writes, 20 were held over
300 ms: 19 grew the buffer from 8 to 16 MB (up to 1.3 s), and one was a
fresh buffer's first write (2.7 s). A goroutine sleeping 10 ms beside
them woke at most 57 ms late, so the time went into the memory, not
into waiting to run. A second probe touched fresh memory: 16 MB was
held up to 454 ms, 4 MB up to 278 ms, 1 MB and 256 KB at most 1 ms.

Now:
- TestFourKImageByURLIsSaved: the stall is 5 s (was 1 s), and the 4K
  image comes in 256 KB pieces 200 ms apart (was 100 ms), about 8 s,
  so the download still outlasts the stall that plays #1576's 2-minute
  cap. The check that it was the slow one is now "longer than the
  stall" (was 3 s).
- TestStalledDownloadSaysWhereTheImageIs: the stall is 1 s (was
  300 ms), the stuck server sends 1 MB before it stops (was 3 MB), and
  the image that comes in full is the small png the other tests serve
  (was the 9.8 MB 4K one, whose buffer the 8.2 MB red was growing).
- TestSlowTransferIsNotCutShort: the backup is 2 MB at 512 KB/s, 64 KB
  every 125 ms (was 24 MB at 6.4 MB/s), still about 4 s each way under
  the same 1 s watchdog; the largest fresh chunk the read back fills is
  then under 1 MB.

What was run (tree 8e4ecb44, on b437e4ad):
  -count=10 of the three tests: ok (TestFourKImageByURLIsSaved 8.2 s on
  average, TestStalledDownloadSaysWhereTheImageIs 2.0 s,
  TestSlowTransferIsNotCutShort 9.9 s)
  broken by hand, with this change:
    FetchImage's stall not put back when bytes come (a 5 s cap on the
    whole download):
      big_image_test.go:157: after 5.003s: image 1 was drawn but
      couldn't be downloaded (nothing came for 5s, after 6.2 MB)
    FetchImage's stall never ending a download (the stopped one is
    kept until its server gives up, and saved):
      big_image_test.go:209: <nil>: Generated with ..., saved to: ...
    davsync's watchdog not put back when bytes move:
      stall_test.go:177: slow upload: ... the server sent and took
      nothing for 1s (PUT)
    no room once the PUT's body is all handed over (allSent):
      stall_test.go:177: the same
  gofmt -l internal/imagemcp internal/davsync: nothing
  GOOS=linux, darwin, windows go vet -tags nogui ./internal/imagemcp
  ./internal/davsync: exit 0
  full suite, go test -tags nogui -count=1 -timeout 45m ./...
  (go1.26.8, 469 s): 62 packages ok, internal/imagemcp and
  internal/davsync among them. 13 reds in 7 packages, none in a file
  this change touches:
    internal/agent TestInstalledVersion, TestOmpDetectedWithPiDir,
    TestCopilotFolderFromAnIDEPluginIsNotTheCLI and
    TestQoderSettingsFromAnIDEPluginIsNotTheCLI: proc.Look keeps "not
    found" for a tool written in the tick of its folder's last change
    (#3141).
    internal/agent TestReasonixCLIRequiresSupportedNativeVersion and
    TestReasonixCLIRecoversAfterProbeTimeout: their fixture build under
    /tmp meets a /tmp/.git that isn't a repository of this user's
    ("error obtaining VCS status: exit status 128").
    internal/claudebridge TestCallbackGoesPastTheAgentsProxy,
    internal/gateway TestClaudeToolCallbackOnANonLoopbackAddress,
    internal/gui TestGatewayHeldByAContainer and
    TestGatewayFixQuitsOnlyAMagpie: the processes this run started had
    their outgoing connections sent through a proxy (graftcp).
    internal/edit TestWriteAtomicReadOnlyHardLink and internal/testenv
    TestProgram: umask 077 here; the fixtures' own modes go through it
    (0444 is written as 0400).
    internal/netproxy TestBunProxyLoginWithReservedCharacters: Bun
    1.3.11 on PATH names port 80 in the request line (#3397).

Not changed:
  - The watchdogs. At their real 60 s a buffer's growth is far inside
    them; only a test's shortened one meets it.
  - pii's TestFetchStall (200 ms): its watchdog times a fresh 256 KB
    buffer and one read of 1000 bytes, at most 1 ms in the probe. Not
    seen red here.
  - davsync's TestStalledTransferFailsPromptly and
    TestMetadataRequestHasALimit (300 ms): a stall that comes early
    still passes them, since they check that a stall is told, and soon.
  - A pause like the 2.7 s one would still trip the 1 s watchdogs of
    TestStalledDownloadSaysWhereTheImageIs and
    TestSlowTransferIsNotCutShort. It came once in the probe's 7.5
    minutes.
Not tried: macOS, Windows.

Landed by yetone in a batch of Coffemon's patches from the issues.
What was run, go1.26.8, on origin/main cc81ad4ea, then again at
70a0c387c (gofmt, the three vets, the changed tests, umask 077):
- mote (macOS 27): gofmt -l clean; go vet, GOOS=linux go vet -tags
  nogui and GOOS=windows go vet ./...: ok. edit and testenv at umask
  077; agent, provider, library and gateway with an empty .git above
  TMPDIR; davsync, imagemcp, plugin, library, edit, testenv whole; the
  changed tests in agent, provider, gateway and gui; the timing tests
  -count=10 (gateway, davsync, imagemcp) and -count=5 (agent): all ok.
  TestCoreScriptBudget ok: core 1,536,751 of 1,537,034, app.js
  1,312,975 of 1,315,316, no budget raised.
- Red on the old code: on origin/main, TestWriteAtomicReadOnlyHardLink
  at umask 077 and two Reasonix tests under an empty .git; on Linux
  (wsl-run) TestProgram at umask 077 with the old program.go. With
  each fix's code taken back to main's, the Gemini imageConfig tests,
  TestPluginToldWhereTheAgentWorks, TestSkillRepoTraced,
  TestTaggedHooksAlone, TestMainURL/TestMainView and update-auto,
  plugin-github-hooks, plugins-more-discover, plugin-namesake were
  red. Broken by hand: claudeKeyed always true (both
  OwnEndpointNeverAsked tests red), claudeAsk a no-op
  (TestClaudeFirstWriteAsksTheProxy red), GitAt taking any .git folder
  (the three TestGitOnDisk tests red).
- GUI: 123 files (plugins*, update-*, panel/tray/start/context, i18n,
  gui-zh-tw/ja/de and every file that evals app.js parts) in WebKit on
  Linux (wsl-run). 11 files had reds (click-scroll, panel-fold,
  plugin-card-update, plugin-github, plugin-move*, segs-glide,
  tray-totals, update-*), and run again side by side they fail the
  same on origin/main d80d75f30 (79 pass, 26 fail here; 78 and 27
  there). They are click-scroll guards ("the click must not scroll
  the page"), varying by language from run to run (#4385).
  copilot-ghe's route-after-close red is #1949, seen on main 244d80e23
  too. In Chromium on mote, Chromium segfaulted partway through files
  (#4125): context-map, context-scroll-end and context-tune fail the
  same on origin/main 0911a65e7, so the batch's own files
  (plugin-namesake, update-auto, plugins-more-discover,
  plugin-github-hooks) ran in Chromium on Linux: 62 of 62.
- Full suite (go test -tags nogui -count=1 -timeout 45m ./..., mote)
  at 472a0608f (on 70a0c387c): every package ok but internal/gateway,
  whose five reds were #4362's (Antigravity turned-away and
  TestCodexSpentGrokFailingIsTold), fixed on main in d80d75f30. After
  the rebase on 244d80e23 the five pass, and gofmt, the three vets
  and the targeted runs above were run again: ok. In Linux the
  sign-in, copilot, plugin-github*, plugins-more-discover,
  plugin-namesake, plugin-gateway, update-auto, quota-refresh-order
  and i18n files ran in both engines: 475 pass, 4 fail (copilot-ghe
  #1949, plugin-github's click scroll, both red on main too).
- Rebased again on c7171a256, over its budget fix e94bf7a08: gofmt, vet of
  gui, gateway, provider and plugin, TestCoreScriptBudget (core
  1,536,265 of 1,536,586 with the batch's last commit, statusTErr and settingsErr), the Gemini,
  GitOnDisk and plugin tests, and in Linux both engines i18n-keys,
  update-mirror, plugin-namesake, plugins-more-discover,
  plugin-github-hooks and update-auto (138 of 138): ok.
Not tried: the whole GUI suite (mote's WebKit wouldn't launch and its
Chromium segfaulted, #4125); macOS WebKit; the real app's window.
2026-10-30 15:53:22 +08:00

252 lines
9.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"
"github.com/yetone/magpie/internal/settings"
)
// 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, ""
}
// fetchLocal lets these tests' vendor, a server on this computer, be
// downloaded from: the user's fetchPrivate naming loopback.
func fetchLocal(t *testing.T) {
t.Helper()
was := settings.Load()
st := was
st.FetchPrivate = []string{"127.0.0.1"}
if err := settings.Save(st); err != nil {
t.Fatal(err)
}
t.Cleanup(func() { settings.Save(was) })
}
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 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))
// The stall also counts the time this process takes to grow the
// download's buffer. Beside a full suite on a Linux box, a write that
// grew one was held up to 2.7 s, and a 1 s stall went off at 4.2 MB of
// a download that never stopped.
shorterWaits(t, 5*time.Second)
fetchLocal(t)
files := httptest.NewServer(slowFile(big, 200*time.Millisecond, 0)) // ~8 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 <= gateway.ImageStall {
t.Fatalf("the download took %s, no longer than the stall: 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()
// A second, and a small image for the one that comes in full: the
// stall also counts the time this process takes to grow the download's
// buffer, and at 300 ms, beside a full suite on a Linux box, it went off
// at 8.2 MB of a 4K image that was still coming, and once at 0.0 MB.
shorterWaits(t, time.Second)
fetchLocal(t)
stuck := httptest.NewServer(slowFile(big, 0, 1<<20))
t.Cleanup(stuck.Close)
fine := httptest.NewServer(slowFile(png, 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 1s, after 1.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, png) {
t.Fatalf("saved %d bytes of %d", len(b), len(png))
}
}
// The URL an image is answered by is the vendor's, and what the model was
// steered to draw can steer it: one on this computer or its network is
// not downloaded unless the user's fetchPrivate names it, and the answer
// says where the image is.
func TestVendorImageAtPrivateAddressNotFetched(t *testing.T) {
shorterWaits(t, time.Second)
var hits sync.Mutex
n := 0
inside := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
hits.Lock()
n++
hits.Unlock()
w.Write([]byte("\x89PNG\r\n\x1a\n secret"))
}))
t.Cleanup(inside.Close)
project := t.TempDir()
c := initialized(t, &urlGateway{urls: []string{inside.URL + "/admin.png"}}, project)
r, out := c.await(map[string]any{"prompt": "a city", "path": "city.png"})
if r["isError"] != true || !strings.Contains(out, "private address") || !strings.Contains(out, inside.URL+"/admin.png") {
t.Fatalf("%v: %s", r["isError"], out)
}
hits.Lock()
defer hits.Unlock()
if n != 0 {
t.Fatalf("the private server was asked %d times", n)
}
if _, err := os.Stat(filepath.Join(project, "city.png")); err == nil {
t.Fatal("something was saved")
}
}