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
206 lines
7.2 KiB
Go
206 lines
7.2 KiB
Go
package gateway
|
|
|
|
import (
|
|
"bytes"
|
|
"compress/gzip"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"net/http/httptest"
|
|
"strings"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/klauspost/compress/zstd"
|
|
"github.com/yetone/magpie/internal/provider"
|
|
)
|
|
|
|
// largeBodyRoom lifts the cut on a request held before routing, under
|
|
// -race only, for a test that serves a body of 20 MB or more: the race
|
|
// detector made the scans of a 64MB body before routing take 20s on an M5
|
|
// Pro and near 60s on CI, where without it they take under a second, so
|
|
// the 30s cut answered 504 (#3957). Without -race the cut stays, and a
|
|
// slower scan still fails the test.
|
|
func largeBodyRoom(t *testing.T) {
|
|
if raceOn {
|
|
unknownLimit(t, 10*time.Minute)
|
|
unroutedLimits(t, unroutedShow, 10*time.Minute)
|
|
}
|
|
}
|
|
|
|
func encodedBody(t *testing.T, body []byte, encoding string) []byte {
|
|
t.Helper()
|
|
switch encoding {
|
|
case "gzip":
|
|
var buf bytes.Buffer
|
|
w := gzip.NewWriter(&buf)
|
|
if _, err := w.Write(body); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := w.Close(); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
return buf.Bytes()
|
|
case "zstd":
|
|
w, err := zstd.NewWriter(nil)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
defer w.Close()
|
|
return w.EncodeAll(body, nil)
|
|
default:
|
|
return body
|
|
}
|
|
}
|
|
|
|
func TestCodexBodyReadsPastOldLimit(t *testing.T) {
|
|
for _, encoding := range []string{"identity", "gzip", "zstd"} {
|
|
for _, delta := range []int{-1, 0, 1} {
|
|
t.Run(fmt.Sprintf("%s/%+d", encoding, delta), func(t *testing.T) {
|
|
body := bytes.Repeat([]byte("x"), oldBodyLimit+delta)
|
|
copy(body[len(body)-4:], "END!")
|
|
// Hide the reader's length, as with a chunked request.
|
|
r := httptest.NewRequest("POST", CodexPath+"/responses", struct{ io.Reader }{bytes.NewReader(encodedBody(t, body, encoding))})
|
|
r.Header.Set("Content-Encoding", encoding)
|
|
got, ok := New().readRequestBody(httptest.NewRecorder(), r, provider.Responses, 0)
|
|
if !ok {
|
|
t.Fatal("body rejected")
|
|
}
|
|
if !bytes.Equal(got, body) {
|
|
t.Fatalf("read %d bytes, want all %d bytes including the tail", len(got), len(body))
|
|
}
|
|
})
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestLargeRequestEndpoints(t *testing.T) {
|
|
largeBodyRoom(t)
|
|
const payload = `{"model":"fake/m1","input":"END!","messages":[{"role":"user","content":"END!"}],"contents":[{"role":"user","parts":[{"text":"END!"}]}]}`
|
|
// Padding keeps the test about reading the whole body, not token limits.
|
|
body := append(bytes.Repeat([]byte(" "), oldBodyLimit), payload...)
|
|
for _, tc := range []struct {
|
|
path string
|
|
proto provider.Protocol
|
|
count bool
|
|
}{
|
|
{CodexPath + "/responses", provider.Responses, false},
|
|
{"/v1/responses", provider.Responses, false},
|
|
{"/v1/chat/completions", provider.Chat, false},
|
|
{"/v1/messages", provider.Anthropic, false},
|
|
{"/v1/messages/count_tokens", provider.Anthropic, true},
|
|
{"/v1beta/models/fake/m1:generateContent", provider.Chat, false},
|
|
{"/v1beta/models/fake/m1:countTokens", provider.Chat, true},
|
|
} {
|
|
t.Run(tc.path, func(t *testing.T) {
|
|
f := &fake{t: t, ctype: "application/json", reply: `{"id":"ok","input_tokens":7,"choices":[{"message":{"role":"assistant","content":"ok"},"finish_reason":"stop"}],"output":[],"content":[]}`}
|
|
if strings.HasSuffix(tc.path, ":generateContent") {
|
|
f.ctype = "text/event-stream"
|
|
f.reply = sse(`data: {"choices":[{"delta":{"content":"ok"},"finish_reason":null}]}`, `data: {"choices":[{"delta":{},"finish_reason":"stop"}]}`, `data: [DONE]`)
|
|
}
|
|
setup(t, tc.proto, f)
|
|
s := New()
|
|
// The same prompt without transport padding provides the count control.
|
|
control := httptest.NewRecorder()
|
|
s.Handler().ServeHTTP(control, httptest.NewRequest("POST", tc.path, strings.NewReader(payload)))
|
|
if control.Code != 200 {
|
|
t.Fatalf("control: %d %s", control.Code, control.Body.String())
|
|
}
|
|
f.calls = 0
|
|
f.got = nil
|
|
rec := httptest.NewRecorder()
|
|
s.Handler().ServeHTTP(rec, httptest.NewRequest("POST", tc.path, bytes.NewReader(body)))
|
|
if rec.Code != 200 {
|
|
t.Fatalf("large: %d %s", rec.Code, rec.Body.String())
|
|
}
|
|
if tc.count && rec.Body.String() != control.Body.String() {
|
|
t.Fatalf("count changed: %s / %s", rec.Body.String(), control.Body.String())
|
|
}
|
|
if strings.HasSuffix(tc.path, ":countTokens") {
|
|
if f.calls != 0 {
|
|
t.Fatal("Gemini counting should remain local")
|
|
}
|
|
} else if f.calls != 1 || !bytes.Contains(f.got, []byte("END!")) {
|
|
t.Fatalf("upstream calls=%d; tail present=%v", f.calls, bytes.Contains(f.got, []byte("END!")))
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
type bodyReadError struct{}
|
|
|
|
func (bodyReadError) Read([]byte) (int, error) { return 0, errors.New("body read failed") }
|
|
|
|
func TestRequestTailAfterOldLimit(t *testing.T) {
|
|
largeBodyRoom(t)
|
|
const payload = `{"model":"fake/m1","input":"hi","messages":[],"contents":[]}`
|
|
body := append([]byte(payload), bytes.Repeat([]byte(" "), oldBodyLimit-len(payload))...)
|
|
for _, path := range []string{CodexPath + "/responses", "/v1/responses", "/v1/messages/count_tokens", "/v1beta/models/fake/m1:generateContent"} {
|
|
for _, tail := range []string{"whitespace", "second-object", "read-error"} {
|
|
t.Run(path+"/"+tail, func(t *testing.T) {
|
|
f := &fake{t: t, ctype: "application/json", reply: `{"id":"ok","input_tokens":7,"choices":[{"message":{"role":"assistant","content":"ok"},"finish_reason":"stop"}],"output":[],"content":[]}`}
|
|
proto := provider.Responses
|
|
if strings.Contains(path, "count_tokens") {
|
|
proto = provider.Anthropic
|
|
}
|
|
if strings.Contains(path, "v1beta") {
|
|
proto = provider.Chat
|
|
}
|
|
if proto == provider.Chat {
|
|
f.ctype = "text/event-stream"
|
|
f.reply = sse(`data: {"choices":[{"delta":{"content":"ok"},"finish_reason":null}]}`, `data: {"choices":[{"delta":{},"finish_reason":"stop"}]}`, `data: [DONE]`)
|
|
}
|
|
setup(t, proto, f)
|
|
s := New()
|
|
var suffix io.Reader = strings.NewReader(" \n")
|
|
if tail == "second-object" {
|
|
suffix = strings.NewReader(`{"extra":true}`)
|
|
}
|
|
if tail == "read-error" {
|
|
suffix = bodyReadError{}
|
|
}
|
|
rec := httptest.NewRecorder()
|
|
s.Handler().ServeHTTP(rec, httptest.NewRequest("POST", path, io.MultiReader(bytes.NewReader(body), suffix)))
|
|
if tail == "whitespace" {
|
|
if rec.Code != 200 || f.calls != 1 {
|
|
t.Fatalf("valid whitespace: %d, calls=%d", rec.Code, f.calls)
|
|
}
|
|
} else if rec.Code != 400 || f.calls != 0 {
|
|
t.Fatalf("%s: status=%d, calls=%d", tail, rec.Code, f.calls)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestCodexCompressedTailError(t *testing.T) {
|
|
largeBodyRoom(t)
|
|
const payload = `{"model":"fake/m1","input":"hi"}`
|
|
body := append([]byte(payload), bytes.Repeat([]byte(" "), oldBodyLimit-len(payload))...)
|
|
for _, encoding := range []string{"gzip", "zstd"} {
|
|
for _, damage := range []string{"checksum", "truncated"} {
|
|
t.Run(encoding+"/"+damage, func(t *testing.T) {
|
|
wire := encodedBody(t, body, encoding)
|
|
if damage == "truncated" {
|
|
wire = wire[:len(wire)-1]
|
|
} else {
|
|
pos := len(wire) - 1
|
|
if encoding == "gzip" {
|
|
pos = len(wire) - 8
|
|
}
|
|
wire[pos] ^= 0xff
|
|
}
|
|
f := &fake{t: t}
|
|
setup(t, provider.Responses, f)
|
|
r := httptest.NewRequest("POST", CodexPath+"/responses", bytes.NewReader(wire))
|
|
r.Header.Set("Content-Encoding", encoding)
|
|
rec := httptest.NewRecorder()
|
|
New().Handler().ServeHTTP(rec, r)
|
|
if rec.Code != 400 || f.calls != 0 {
|
|
t.Fatalf("status=%d, upstream calls=%d", rec.Code, f.calls)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
}
|