Files
magpie/internal/gateway/request_idle_test.go
T
yetone 75d40ba48b ci: race gateway tests run in chunks taken in turn; 64 MB bodies are 20 MB under -race
The macOS -race gateway step split 3772 tests by sorted name into one
fixed share per core (3 on macos-latest), and the shares ran out of their
20 minutes with no test hung: run 42354008450 at 191f3c0af ended at 12m,
16m and over 20m (shard 2 in TestMediaJSONPastOldBodyLimit/images), and
42350695944 ran all three at ~19m20s. Two causes: the shares were uneven,
and a few tests scan tens of MB byte by byte, which the race detector
makes 14 to 30 times as slow.

Measured on mote (M5 Pro), -race, -test.v, old script, per test (plain
run in brackets): TestLoopGuardLeavesOrdinaryRepliesAlone 104s (7.6s),
TestLargeRequestEndpoints 104s (3.6s), TestRequestTailAfterOldLimit 33s
(4s), TestCodexBodyReadsPastOldLimit 14.6s (0.55s),
TestMediaJSONPastOldBodyLimit 10.7s (0.7s), TestCodexCompressedTailError
10.2s. Sums of test time per share: 487s, 641s, 761s.

- build/race-shards.sh: the tests go in ~118 chunks of about 32 (test N
  in chunk N mod m, so TestCodex..., TestCompaction... spread out), and
  each of the N workers takes the next chunk when it is done (xargs -P).
  Workers end within a chunk of each other. Each chunk logs in its own
  ::group:: with its time; the five slowest are printed at the end. A
  chunk whose process didn't finish counts as failed.
- oldBodyLimit (the pre-#118 64 MB) is 20 MB under -race
  (race_on_test.go), 64 MB in the plain run. 20 MB still passes every cut
  below 64 MB (bodyKept's 4 MB, the 8 MB and 16 MB reads); the plain Test
  step on ubuntu and macOS still sends the full 64 MB.
- TestLoopGuardLeavesOrdinaryRepliesAlone is skipped under -race: one
  goroutine feeds one loopGuard (loop_guard.go starts none), so there is
  no race to find; the plain run reads the whole corpus.

After, per test on mote under -race: TestLargeRequestEndpoints 40.7s,
TestRequestTailAfterOldLimit 13.05s, TestCodexBodyReadsPastOldLimit
5.1s, TestMediaJSONPastOldBodyLimit 4.46s, TestCodexCompressedTailError
3.1s, TestLoopGuard skipped: ~210s less race time.
A/B in one window on mote (same commit, binaries built from base and
change, 3 workers, load 15 to 30): old script with old tests 12m59s
wall (red: TestTranslatedStreamKeepsClientAlive, the load-timing test
of #2711/#2737); new script with new tests 10m57s, green, slowest
chunk 62s. On 3-core CI the wall should be about the total over three
plus a chunk, instead of the slowest share.

Broken by hand (wsl-run, Linux): defaultBodyLimit 16<<20 under -race
turns TestCodexBodyReadsPastOldLimit, TestLargeRequestEndpoints and
TestRequestTailAfterOldLimit red (body rejected / 413); defaultBodyLimit
48<<20 in the plain run turns the same three red. So the race run guards
the read-whole path past 16 MB and the plain run still guards 64 MB.
TestCodexCompressedTailError and TestMediaJSONPastOldBodyLimit stay green
with either cap: they never guarded the limit (true before this change).

Run: gofmt -l; on mote GOOS=linux go vet -tags nogui ./..., GOOS=windows
go vet ./..., go vet ./..., go vet -race ./internal/gateway; the seven
touched tests plain on mote (all pass, 21.9s); the whole gateway package
under -race through the new script on mote twice (one red,
TestBurstTellsNoSpeed/responses_from_chat_burst, the load timing of
#2719; the second run green).
Not tried: the race run with a 48 MB cap (it would pass: under -race
nothing now covers 20 to 64 MB, the plain step does); a CI run before
the push.

Fixes #5361
Fixes #5320
2026-11-07 19:45:30 +08:00

155 lines
4.7 KiB
Go

package gateway
import (
"bufio"
"bytes"
"fmt"
"io"
"net"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/yetone/magpie/internal/provider"
)
func TestRequestBodyProgressRenewsIdleDeadline(t *testing.T) {
for _, encoding := range []string{"identity", "gzip", "zstd"} {
t.Run(encoding, func(t *testing.T) {
payload := bytes.Repeat([]byte("body"), 128)
wire := encodedBody(t, payload, encoding)
s := New()
// The idle window is ten times the gap between writes: the
// client and the gateway share one process with the whole
// package's tests, and a loaded runner stalled a 50ms gap past
// a 200ms window, a real idle the gateway rightly refused
// (#2567).
idle := time.Second
gap := idle / 10
s.requestLimits.readTimeout = idle
gw := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
body, ok := s.readRequestBody(w, r, provider.Responses, 0)
if !ok {
return
}
if !bytes.Equal(body, payload) {
t.Error("body changed")
}
io.WriteString(w, "ok")
}))
defer gw.Close()
conn, err := net.Dial("tcp", strings.TrimPrefix(gw.URL, "http://"))
if err != nil {
t.Fatal(err)
}
defer conn.Close()
conn.SetDeadline(time.Now().Add(10 * time.Second))
fmt.Fprintf(conn, "POST / HTTP/1.1\r\nHost: localhost\r\nContent-Length: %d\r\nContent-Encoding: %s\r\n\r\n", len(wire), encoding)
// Sixteen progressing writes take longer than one idle window,
// so only renewing on progress lets the upload finish.
const writes = 16
step := (len(wire) + writes - 1) / writes
start := time.Now()
last, longest := start, time.Duration(0)
for offset := 0; offset < len(wire); offset += step {
time.Sleep(gap)
longest = max(longest, time.Since(last))
last = time.Now()
if _, err := conn.Write(wire[offset:min(offset+step, len(wire))]); err != nil {
break
}
}
if took := time.Since(start); took <= idle {
t.Fatalf("upload took %v, inside one idle window of %v: nothing was renewed", took, idle)
}
res, err := http.ReadResponse(bufio.NewReader(conn), nil)
if err != nil {
t.Fatal(err)
}
defer res.Body.Close()
if res.StatusCode != 200 {
t.Fatalf("progressing upload: %d (longest gap between writes %v, idle window %v)", res.StatusCode, longest, idle)
}
body, err := io.ReadAll(res.Body)
if err != nil || string(body) != "ok" {
t.Fatalf("response: %q, %v", body, err)
}
})
}
}
func TestAdditionalBodyReadersHaveDeadlines(t *testing.T) {
for _, api := range []string{"systemone", "mcp"} {
t.Run(api, func(t *testing.T) {
deadlines := []time.Time{}
w := httptest.NewRecorder()
r := httptest.NewRequest("POST", "/", strings.NewReader(`{}`))
if api == "systemone" {
New().serveSystemOne(deadlineRecorder{w, &deadlines}, r)
} else {
r.SetPathValue("token", "run")
b := &subscriptionBridge{runs: map[string]*subscriptionRun{"run": {}}}
b.mcpCall(deadlineRecorder{w, &deadlines}, r)
}
if len(deadlines) < 2 || deadlines[0].IsZero() || !deadlines[len(deadlines)-1].IsZero() {
t.Fatalf("body deadlines: %v", deadlines)
}
})
}
}
func TestMCPBodyTooLarge(t *testing.T) {
r := httptest.NewRequest("POST", "/", strings.NewReader(`{}`))
r.SetPathValue("token", "run")
r.ContentLength = 17 << 20
w := httptest.NewRecorder()
b := &subscriptionBridge{runs: map[string]*subscriptionRun{"run": {}}}
b.mcpCall(w, r)
if w.Code != 413 {
t.Fatalf("oversize MCP: %d", w.Code)
}
}
func TestMediaJSONPastOldBodyLimit(t *testing.T) {
payload := append(bytes.Repeat([]byte(" "), oldBodyLimit), []byte(`{"model":"fake/m1","prompt":"tail"}`)...)
for _, api := range []string{"images", "videos"} {
t.Run(api, func(t *testing.T) {
r := httptest.NewRequest("POST", "/", bytes.NewReader(payload))
var prompt string
var err error
if api == "images" {
d, e := readDrawing(r)
prompt, err = d.Prompt, e
} else {
f, e := readFilming(r)
prompt, err = f.Prompt, e
}
if err != nil || prompt != "tail" {
t.Fatalf("media body: %q, %v", prompt, err)
}
})
}
}
func TestBodyRejectionErrorShapes(t *testing.T) {
for _, tc := range []struct {
proto provider.Protocol
status int
want string
}{
{provider.Anthropic, 413, `"type":"request_too_large"`},
{provider.Chat, 413, `"type":"request_too_large"`},
{provider.Responses, 413, `"type":"request_too_large"`},
{provider.Gemini, 413, `"status":"INVALID_ARGUMENT"`},
{provider.Gemini, 408, `"status":"DEADLINE_EXCEEDED"`},
} {
w := httptest.NewRecorder()
writeError(w, tc.proto, tc.status, "request body rejected")
if !strings.Contains(w.Body.String(), tc.want) {
t.Fatalf("%s/%d: %s", tc.proto, tc.status, w.Body.String())
}
}
}