gateway: let progressing uploads outlast the routing hold (#4775)
Latest main 9d08993c already classifies an unfinished body as 408, but
still ends a large upload at the two-minute unrouted budget. Credit
actual body-read time at one second per 32 KiB received on the wire,
never more than the time spent reading. Fast uploads cannot bank time
for later internal holds. The idle deadline, unknown-work budget, body
room and size cap remain; a trickle still exhausts the base allowance.
The 408 suggests checking the link/proxy or compacting before retrying.
Red: TestUnroutedProgressingUploadOutlastsMost failed on unchanged main
with HTTP 408 at the scaled 1s hold. Restoring main's budget calculation
via Go overlay with final tests makes all four TLS upload cases fail
with 408 and TestUnroutedUploadTimeIsBounded fail its numeric assertions.
Green: declared/chunked/gzip/zstd TLS tests through Front, idle protection,
rate boundaries and existing unrouted/request-body tests pass (28.267s).
Same selection -race -count=20 passes (547.523s).
Verified on macOS arm64, Go 1.26.8, Bun 1.4.3, temp HOME and pinned Go
caches. gofmt -l and git diff --check clean; native/Linux nogui/Windows
vet and builds pass. Final go test -tags nogui -timeout 45m ./... passes:
87 packages (32 cached), 18 without tests, wall 1152.1s; gateway 734.881s,
plugin 122.229s, claudebridge 3.813s. Individual skips not enumerated.
First full suite had 85 passing packages, gateway 743.006s, and two reds.
The known Bun SOCKS assertion (#2207) is fixed by the preceding unchanged
skygunner patch acb2249e (original a93c613a); its -race -count=20 and all
three vets pass locally. A callback helper timeout is filed as #4782:
its isolated -race -count=20 passes (3.586s) and final suite passes, but
the delayed stage is unresolved, not claimed fixed. Existing macOS C
compiler deprecation/enum warnings remain.
No live gateway, account, or original conversation used. No GUI assets
changed; Playwright not run. Linux/Windows were cross-built/vetted, not
runtime-tested. The original network throughput cause remains unknown.
This commit is contained in:
@@ -368,8 +368,24 @@ recorded as a prediction failure (`noPrediction`).
|
||||
[`redact_phase_test.go`](../../internal/gateway/redact_phase_test.go),
|
||||
`routing-masking.test.cjs`. It is answered 504 after
|
||||
`unroutedUnknown` (30s) held in no wait magpie knows of, or after
|
||||
`unroutedMost` (2m) in all but masking (sharwowwow on X: two minutes of
|
||||
spinning before a 504). Masking's time, its wait for the local model's
|
||||
`unroutedMost` (2m) excluding masking and earned upload time
|
||||
(sharwowwow on X: two minutes of spinning before a 504). An upload
|
||||
earns one second per 32 KiB actually read from the wire, capped at the
|
||||
time spent in body reads (`unmaskedLocked`, `unroutedUploadRate`). A
|
||||
large conversation on a slow link can finish past two minutes (#4775);
|
||||
a trickle still exhausts the base budget. Declared length and decoded
|
||||
bytes earn nothing, and a fast upload cannot bank time for a later
|
||||
internal hold. The 60s wire-idle deadline and 512 MiB decoded size cap
|
||||
still apply ([`request_bounds.go`](../../internal/gateway/request_bounds.go)).
|
||||
An upload that exhausts its allowance is answered 408 with its received
|
||||
byte count and advice to check the link or proxy, compact the conversation
|
||||
or reduce inline images. An internal hold remains a 504; waiting for
|
||||
body room is internal, including before the first read (#4511).
|
||||
`TestUnroutedProgressingUploadOutlastsMost` covers TLS through `Front`
|
||||
with declared, chunked, gzip and zstd bodies;
|
||||
`TestUnroutedUploadCreditKeepsIdleDeadline`, `TestUnroutedUploadTimeIsBounded`
|
||||
and `TestUnroutedTrickledBodyAnswered408` cover the remaining bounds.
|
||||
Masking's time, its wait for the local model's
|
||||
turn with it, counts toward neither (`masked`, `checkMost`): the model
|
||||
is bounded per piece it reads (`classifyTimeout`) and per load, and a
|
||||
480 KB request it took 90s over on an RX 470/580, behind the requests
|
||||
@@ -386,7 +402,7 @@ recorded as a prediction failure (`noPrediction`).
|
||||
report below. What is left is magpie's own work
|
||||
(the catalog, parsing, planning, reading the usage log), ~8.5s at its
|
||||
slowest (a cold catalog sync), so 30s gives it room on a loaded machine.
|
||||
With no route and nothing written, it is answered 504 in its client's
|
||||
With no route and nothing written, the error is sent in its client's
|
||||
protocol, whole (`Content-Length`, `Connection: close`) so the client
|
||||
has it while the handler may still be held; its context ends with
|
||||
`errUnrouted`, its route ends with the error, and the log has every
|
||||
|
||||
@@ -56,10 +56,16 @@ import (
|
||||
// (internal/pii). A 480 KB request on an RX 470/580 took 90s of the
|
||||
// model's work, more on its CPU, and was answered 504 at 2 minutes, its
|
||||
// work thrown away, however often it was sent again (#3682). What isn't
|
||||
// masking still has unroutedMost, so a hook or a describe that hangs
|
||||
// after masking is still answered.
|
||||
// masking still has unroutedMost, with bounded upload credit below, so
|
||||
// a hook or a describe that hangs after masking is still answered.
|
||||
var unroutedShow, unroutedUnknown, unroutedMost = 15 * time.Second, 30 * time.Second, 2 * time.Minute
|
||||
|
||||
// Uploads earn time at 32 KiB/s, only for time actually spent reading
|
||||
// wire bytes. A large conversation over a slow link can finish (#4775),
|
||||
// while a trickle still runs out of the ordinary two-minute hold. The
|
||||
// socket's idle deadline and the decoded body size limit also still hold.
|
||||
const unroutedUploadRate = 32 << 10
|
||||
|
||||
// unroutedWatched is whether a request to path is an agent's turn, which
|
||||
// is given a route once magpie knows where it goes: Chat, Responses,
|
||||
// Messages, Gemini and Codex's own backend. A compaction or a model list
|
||||
@@ -290,18 +296,29 @@ func (u *unroutedHold) masked() {
|
||||
}
|
||||
|
||||
// unmaskedLocked is how long the request has been held other than
|
||||
// masking; wmu is held.
|
||||
// masking and the upload time earned by received bytes; wmu is held.
|
||||
func (u *unroutedHold) unmaskedLocked(now time.Time) time.Duration {
|
||||
d := now.Sub(u.f.start) - u.mexcused
|
||||
if u.mwaits > 0 {
|
||||
d -= now.Sub(u.msince)
|
||||
}
|
||||
for _, k := range u.kinds {
|
||||
if k.kind == "body" {
|
||||
spent := k.spent
|
||||
if k.n > 0 {
|
||||
spent += now.Sub(k.since)
|
||||
}
|
||||
earned := time.Duration(u.bodyRead.Load()) * time.Second / unroutedUploadRate
|
||||
d -= min(spent, earned)
|
||||
break
|
||||
}
|
||||
}
|
||||
return d
|
||||
}
|
||||
|
||||
// checkMost is most's timer: a request held unroutedMost other than
|
||||
// masking is answered for; one masking now is looked at again when that
|
||||
// ends, and one with time left, when that is up.
|
||||
// masking and earned upload time is answered for; one masking now is
|
||||
// looked at again when that ends, and one with time left, when that is up.
|
||||
func (u *unroutedHold) checkMost() {
|
||||
u.wmu.Lock()
|
||||
if u.mwaits > 0 {
|
||||
@@ -533,7 +550,7 @@ func byteWord(n int64) string {
|
||||
// when it had been held for held: the time went to the client sending it,
|
||||
// not to magpie, and it says so.
|
||||
func unroutedBodyMsg(held time.Duration, body string) string {
|
||||
return fmt.Sprintf("magpie stopped this request after %s because its body was still arriving from the client (read: %s), before it could be routed to any provider. The client is sending its body slowly (or a proxy between them is). Send it again. "+heldSay, held, body, heldWhere())
|
||||
return fmt.Sprintf("magpie stopped this request after %s because its body was still arriving from the client (read: %s), before it could be routed to any provider. The upload exhausted its time allowance (32 KiB/s with a two-minute grace period). Check the connection or proxy to magpie, or compact the conversation and reduce inline images before retrying. "+heldSay, held, body, heldWhere())
|
||||
}
|
||||
|
||||
// watchUnrouted watches r, counted as f, until the func it answers is
|
||||
@@ -618,7 +635,8 @@ func (u *unroutedHold) routed() (drop *Route) {
|
||||
// giveUp answers the request with an error, when no route was begun for it
|
||||
// and its handler wrote nothing, ends its context, and says on its route
|
||||
// and in the log what held it. unknown: it was held unroutedUnknown in no
|
||||
// wait magpie knows of, rather than unroutedMost other than masking.
|
||||
// wait magpie knows of, rather than unroutedMost other than masking and
|
||||
// earned upload time.
|
||||
func (u *unroutedHold) giveUp(unknown bool) {
|
||||
f := u.f
|
||||
f.mu.Lock()
|
||||
|
||||
@@ -0,0 +1,163 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"io"
|
||||
"math/rand/v2"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// #4775: the client's upload can outlast the routing hold while wire
|
||||
// bytes are still arriving. Exercise the listener's guards and TLS, with
|
||||
// only a local fake provider. A large first write buys ample rate room;
|
||||
// waiting on the watch's measured body time makes the old cutoff fail.
|
||||
func TestUnroutedProgressingUploadOutlastsMost(t *testing.T) {
|
||||
for _, encoding := range []string{"identity", "chunked", "gzip", "zstd"} {
|
||||
t.Run(encoding, func(t *testing.T) {
|
||||
unroutedLimits(t, 20*time.Millisecond, time.Second)
|
||||
s, up := slowEyed(t, 0)
|
||||
srv := httptest.NewTLSServer(s.Front())
|
||||
defer srv.Close()
|
||||
pr, pw := io.Pipe()
|
||||
defer pr.Close()
|
||||
defer pw.Close()
|
||||
// Incompressible text keeps the compressed wire credit well
|
||||
// above the three seconds spent reading, even under -race.
|
||||
rng := rand.New(rand.NewPCG(1, 2))
|
||||
noise := make([]byte, 192<<10)
|
||||
for i := range noise {
|
||||
noise[i] = byte(rng.Uint32())
|
||||
}
|
||||
body := []byte(`{"model":"probe/text","messages":[{"role":"user","content":"` + base64.StdEncoding.EncodeToString(noise) + `"}]}`)
|
||||
wire := body
|
||||
if encoding != "chunked" {
|
||||
wire = encodedBody(t, body, encoding)
|
||||
}
|
||||
req, err := http.NewRequest("POST", srv.URL+"/v1/chat/completions", pr)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
if encoding != "chunked" {
|
||||
req.ContentLength = int64(len(wire))
|
||||
req.Header.Set("Content-Encoding", encoding)
|
||||
}
|
||||
got := make(chan unroutedReply, 1)
|
||||
finished := make(chan struct{})
|
||||
defer func() {
|
||||
pw.Close()
|
||||
pr.Close()
|
||||
<-finished
|
||||
}()
|
||||
go func() {
|
||||
defer close(finished)
|
||||
res, err := srv.Client().Do(req)
|
||||
if err != nil {
|
||||
got <- unroutedReply{err: err}
|
||||
return
|
||||
}
|
||||
b, err := io.ReadAll(res.Body)
|
||||
res.Body.Close()
|
||||
got <- unroutedReply{res.StatusCode, string(b), err}
|
||||
}()
|
||||
if _, err := io.CopyN(pw, bytes.NewReader(wire), int64(len(wire)-1)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if r := heldPast(t, watchedHold(t, s), 3*unroutedMost, got); r != nil {
|
||||
t.Fatalf("progressing upload cut off before routing: %d %q %v", r.code, r.body, r.err)
|
||||
}
|
||||
if n := watchedHold(t, s).bodyRead.Load(); n != int64(len(wire)-1) {
|
||||
t.Fatalf("upload credit counts %d bytes, want %d wire bytes", n, len(wire)-1)
|
||||
}
|
||||
if len(up.sent("text")) != 0 {
|
||||
t.Fatal("provider asked before the upload finished")
|
||||
}
|
||||
if _, err := pw.Write(wire[len(wire)-1:]); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
pw.Close()
|
||||
r := <-got
|
||||
if r.err != nil || r.code != http.StatusOK {
|
||||
t.Fatalf("completed upload: %d %q %v", r.code, r.body, r.err)
|
||||
}
|
||||
if len(up.sent("text")) != 1 {
|
||||
t.Fatal("completed upload was not sent exactly once")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// A stalled upload still ends on its socket's idle deadline even after
|
||||
// receiving enough bytes to earn additional time at the routing hold.
|
||||
func TestUnroutedUploadCreditKeepsIdleDeadline(t *testing.T) {
|
||||
unroutedLimits(t, 20*time.Millisecond, time.Second)
|
||||
s, up := slowEyed(t, 0)
|
||||
s.requestLimits.readTimeout = 200 * time.Millisecond
|
||||
srv := httptest.NewServer(s.Front())
|
||||
defer srv.Close()
|
||||
conn, err := net.Dial("tcp", strings.TrimPrefix(srv.URL, "http://"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer conn.Close()
|
||||
conn.SetDeadline(time.Now().Add(10 * time.Second))
|
||||
body := unroutedHi + strings.Repeat(" ", 128<<10)
|
||||
fmt.Fprintf(conn, "POST /v1/chat/completions HTTP/1.1\r\nHost: localhost\r\nContent-Type: application/json\r\nContent-Length: %d\r\n\r\n%s", len(body)+1, body)
|
||||
res, err := http.ReadResponse(bufio.NewReader(conn), nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
b, err := io.ReadAll(res.Body)
|
||||
res.Body.Close()
|
||||
if err != nil || res.StatusCode != http.StatusRequestTimeout || !strings.Contains(string(b), "request body read timed out") {
|
||||
t.Fatalf("idle upload: %d %s %v", res.StatusCode, b, err)
|
||||
}
|
||||
if len(up.sent("text")) != 0 {
|
||||
t.Fatal("stalled upload reached the provider")
|
||||
}
|
||||
}
|
||||
|
||||
// Upload time cannot be banked for a later internal hang, nor can the
|
||||
// declared length buy time for bytes the client has not sent. Use fixed
|
||||
// times to pin the rate boundary without a scheduler-dependent race.
|
||||
func TestUnroutedUploadTimeIsBounded(t *testing.T) {
|
||||
now := time.Now()
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
read int64
|
||||
spent time.Duration
|
||||
reading bool
|
||||
want time.Duration
|
||||
}{
|
||||
{"no bytes", 0, 8 * time.Second, true, 10 * time.Second},
|
||||
{"below rate", unroutedUploadRate, 8 * time.Second, true, 9 * time.Second},
|
||||
{"at rate", 8 * unroutedUploadRate, 8 * time.Second, true, 2 * time.Second},
|
||||
{"above rate", 16 * unroutedUploadRate, 8 * time.Second, true, 2 * time.Second},
|
||||
{"between reads", 8 * unroutedUploadRate, 8 * time.Second, false, 2 * time.Second},
|
||||
{"fast body then internal hold", 16 * unroutedUploadRate, time.Second, false, 9 * time.Second},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
k := &waitKind{kind: "body", spent: tc.spent}
|
||||
if tc.reading {
|
||||
k.n, k.spent, k.since = 1, 0, now.Add(-tc.spent)
|
||||
}
|
||||
u := &unroutedHold{f: &inflight{start: now.Add(-10 * time.Second)}, kinds: []*waitKind{k}}
|
||||
u.bodyRead.Store(tc.read)
|
||||
if got := u.unmaskedLocked(now); got != tc.want {
|
||||
t.Fatalf("internal hold = %s, want %s", got, tc.want)
|
||||
}
|
||||
// Unknown-work protection is independent of earned bytes.
|
||||
if got := u.unknownLocked(now); got != 10*time.Second {
|
||||
t.Fatalf("upload bytes excused unknown work: %s", got)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user