Files
magpie/internal/davsync/stall_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

257 lines
7.8 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 davsync
import (
"bytes"
"context"
"errors"
"io"
"net"
"net/http"
"net/http/httptest"
"strconv"
"sync"
"testing"
"time"
)
// shortStall makes the watchdogs short for a test.
func shortStall(t *testing.T, stall, meta time.Duration) {
s, m := stallAfter, metaLimit
stallAfter, metaLimit = stall, meta
t.Cleanup(func() { stallAfter, metaLimit = s, m })
}
// slowDAV is a WebDAV server on a slow line: the backup goes both ways in
// chunks of chunk bytes every gap, or stops after stopAt bytes for good. A
// PUT is answered tail after its body is all in: the time the last of it,
// handed over by magpie, would take to cross the line.
type slowDAV struct {
chunk int
gap time.Duration
tail time.Duration
stopAt int // 0: never
quiet chan struct{} // closed when the test is done with a stopped server
mu sync.Mutex
stored []byte
}
// stop holds the request without a byte either way until the client gives
// up, or the test ends (a server doesn't see a client gone before it has
// read the body).
func (s *slowDAV) stop(r *http.Request) {
select {
case <-r.Context().Done():
case <-s.quiet:
}
}
func (s *slowDAV) ServeHTTP(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case http.MethodPut:
var got bytes.Buffer
got.Grow(int(r.ContentLength))
buf := make([]byte, s.chunk)
for {
if s.stopAt > 0 && got.Len() >= s.stopAt {
s.stop(r) // the line went quiet
return
}
n, err := io.ReadFull(r.Body, buf)
got.Write(buf[:n])
if err != nil {
break
}
time.Sleep(s.gap)
}
time.Sleep(s.tail)
s.mu.Lock()
s.stored = got.Bytes()
s.mu.Unlock()
w.Header().Set("ETag", `"v1"`)
w.WriteHeader(http.StatusCreated)
case http.MethodHead:
s.mu.Lock()
w.Header().Set("Content-Length", strconv.Itoa(len(s.stored)))
s.mu.Unlock()
w.WriteHeader(http.StatusOK)
case http.MethodGet:
s.mu.Lock()
data := s.stored
s.mu.Unlock()
w.Header().Set("Content-Length", strconv.Itoa(len(data)))
w.Header().Set("ETag", `"v1"`)
w.WriteHeader(http.StatusOK)
for i := 0; i < len(data); i += s.chunk {
if s.stopAt > 0 && i >= s.stopAt {
s.stop(r)
return
}
w.Write(data[i:min(i+s.chunk, len(data))])
w.(http.Flusher).Flush()
time.Sleep(s.gap)
}
default:
w.WriteHeader(http.StatusMethodNotAllowed)
}
}
// narrowLine serves h, and gives the client that reaches it, with the
// line's buffers held small. The system hands a writer room in bursts: Linux wakes it once a third
// of its send buffer has drained and opens the receiver's window by as much,
// and with the MBs it tunes both up to on a fast loopback, a body moving at
// 6.4 MB/s went 150–290 ms between two of magpie's writes, which a test's
// watchdog of 300 ms didn't always outlast though the line never stopped (at
// the real 60 s that is a line under ~25 KB/s). Small buffers keep the
// bursts to a chunk or two; what sits in buffers after the body is handed
// over is the server's tail.
func narrowLine(t *testing.T, h http.Handler) (*httptest.Server, *http.Client) {
const buffer = 128 << 10
srv := httptest.NewUnstartedServer(h)
srv.Listener = narrowListener{srv.Listener, buffer}
srv.Start()
t.Cleanup(srv.Close)
tr := http.DefaultTransport.(*http.Transport).Clone()
dial := tr.DialContext
tr.DialContext = func(ctx context.Context, network, addr string) (net.Conn, error) {
c, err := dial(ctx, network, addr)
if err == nil {
err = narrow(c, buffer)
}
return c, err
}
t.Cleanup(tr.CloseIdleConnections)
return srv, &http.Client{Transport: stallTransport{tr}}
}
type narrowListener struct {
net.Listener
buffer int
}
func (l narrowListener) Accept() (net.Conn, error) {
c, err := l.Listener.Accept()
if err == nil {
err = narrow(c, l.buffer)
}
return c, err
}
// narrow keeps both ways of a connection small: the PUT goes up through the
// client's send buffer and the server's receive buffer, the GET comes down
// through the other two, and on macOS a download through the tuned-up pair
// burst as the upload had (run 37693090857: "took nothing for 300ms (GET)").
func narrow(c net.Conn, buffer int) error {
tc := c.(*net.TCPConn)
if err := tc.SetReadBuffer(buffer); err != nil {
return err
}
return tc.SetWriteBuffer(buffer)
}
// A backup that takes far longer than the watchdog to go up and come back
// down, but never stops moving, is written and read in full (#657: 43 MB
// at 305 KB/s took 2.4 minutes, and a sync was given 2).
func TestSlowTransferIsNotCutShort(t *testing.T) {
// a second, not the 300 ms the other stall tests use: a macOS runner
// can stop the whole test for a few hundred ms, and here the line never
// stops, so such a pause is all a shorter watchdog would catch (red
// on macOS in run 37693090857, near the end of the GET)
shortStall(t, time.Second, time.Second)
// the PUT's last bytes cross the line twice the watchdog after magpie
// has handed them all over
s := &slowDAV{chunk: 64 << 10, gap: 125 * time.Millisecond, tail: 2 * stallAfter}
srv, client := narrowLine(t, s)
d, err := newDAV(Config{URL: srv.URL})
if err != nil {
t.Fatal(err)
}
d.client = client
// 2 MB at 512 KB/s: about 4 s each way. Not more: the read back fills
// fresh buffers half as big as what has come, the watchdog counts that
// time too, and beside a full suite on a Linux box a 24 MB backup's GET
// went off ("took nothing for 1s (GET)") though the line never stopped.
data := bytes.Repeat([]byte("magpie skill "), (2<<20)/13)
ctx := context.Background()
start := time.Now()
if _, err := d.put(ctx, data, ""); err != nil {
t.Fatalf("slow upload: %v", err)
}
up := time.Since(start)
start = time.Now()
got, _, err := d.get(ctx, version{})
if err != nil {
t.Fatalf("slow download: %v", err)
}
down := time.Since(start)
if !bytes.Equal(got, data) {
t.Fatalf("read back %d bytes of %d", len(got), len(data))
}
if up < 3*stallAfter || down < 3*stallAfter {
t.Fatalf("the transfers (%s up, %s down) weren't slow enough to test anything", up, down)
}
}
// A server that stops in the middle, either way, fails the sync soon after
// it stops, saying so — not after however long a sync may take.
func TestStalledTransferFailsPromptly(t *testing.T) {
shortStall(t, 300*time.Millisecond, 300*time.Millisecond)
data := bytes.Repeat([]byte("x"), 32<<20) // more than the system buffers hold
for _, way := range []string{"up", "down"} {
t.Run(way, func(t *testing.T) {
s := &slowDAV{chunk: 64 << 10, gap: 10 * time.Millisecond, quiet: make(chan struct{})}
if way == "up" {
s.stopAt = 1 << 20
} else {
s.stored = data
s.stopAt = 1 << 20
}
srv := httptest.NewServer(s)
defer srv.Close()
defer close(s.quiet)
d, err := newDAV(Config{URL: srv.URL})
if err != nil {
t.Fatal(err)
}
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()
start := time.Now()
if way == "up" {
_, err = d.put(ctx, data, "")
} else {
_, _, err = d.get(ctx, version{})
}
took := time.Since(start)
var st *errStalled
if !errors.As(err, &st) {
t.Fatalf("%v after %s, want a stall", err, took)
}
if took > 10*time.Second {
t.Fatalf("a stall took %s to tell", took)
}
})
}
}
// A request that moves only a little (PROPFIND, MKCOL…) has metaLimit in
// all, however it trickles.
func TestMetadataRequestHasALimit(t *testing.T) {
shortStall(t, 300*time.Millisecond, 300*time.Millisecond)
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
select {
case <-time.After(5 * time.Second):
case <-r.Context().Done():
}
}))
defer srv.Close()
d, err := newDAV(Config{URL: srv.URL})
if err != nil {
t.Fatal(err)
}
start := time.Now()
err = d.mkcol(context.Background())
var st *errStalled
if !errors.As(err, &st) || time.Since(start) > 3*time.Second {
t.Fatalf("%v after %s, want the limit", err, time.Since(start))
}
}