gateway: a body still arriving at the 2m cut-off is answered 408, and its read ends

heatonz on Discord (Hermes Agent to magpie v0.1.2237 in Docker): about
half the requests to a nested group were stopped after 2m0s "without
routing it to any provider". The held report's one wait was "body 2m0s
(under way)", and 7 handler goroutines sat in net/http body.Read under
waitedBody, idleBody and readSized.

The body read has its own idle limit: 60s with no byte, renewed on each
byte (idleBody), which answers 408. That limit never fired, so bytes were
still coming in gaps under 60s, and the time added up to unroutedMost
in the "body" wait. The watch then answered 504 and blamed routing, and the
handler kept reading the body after the answer until the body ended or
went idle.

Now, when the cut-off lands while the body is being read:
- the answer is 408, saying the body was still arriving from the client,
  how much of it had come and when the last byte did; OpenAI's and
  Anthropic's SDKs send a 408 again at once;
- the read ends with the answer (deadline now, waitedBody refuses further
  reads), so the connection closes with it;
- the held report says "stopped it with 408" and has a "body read: X of
  Y, the last Ns ago" line, which tells a trickle from a stall.

Not changed: the 60s idle limit. The report shows it never fired, so a
shorter one would not have been sure to catch this case, and an
upload that keeps progressing is the client's, not magpie's. The 2m bound stays,
so a trickling client can't hold a handler forever.

Run (mote, at this head on 505d9f6a2):
- go test ./internal/gateway -count=1 -timeout 45m: ok (870s)
- go vet ./internal/gateway for darwin, linux and windows: ok
- TestUnroutedTrickledBodyAnswered408 -count=5: ok
- gofmt -l: clean
Broken by hand:
- the case u.inBody() turned off (the old code): red, 504 "without
  routing it to any provider";
- the read deadline and bodyStopped taken out: red, the connection ended
  10.2s after the 408.
Also probed, through s.Front() on a real socket with a 500ms idle limit,
each answered 408 at the idle limit, never held to the cut-off:
- headers then a stalled body;
- Expect: 100-continue and no body (magpie sends the 100, then 408);
- a Content-Length 50 bytes past the body sent;
- a second request on a kept-alive connection, stalled or with Expect.
heatonz says it happens with Hermes and magpie on one machine too, so no
network hop is involved. None of those three shapes holds a read for
2m, so the bytes were trickling from the client.
Not tried: Hermes Agent itself; why it sends its body that slowly is
unknown. The next held report's "body read" line will show it.
This commit is contained in:
yetone
2026-10-31 01:32:57 +08:00
parent f03ed8c26e
commit e2d7d1f54a
3 changed files with 185 additions and 8 deletions
+5 -2
View File
@@ -118,9 +118,9 @@ func HeldReport(name string) (string, error) {
}
// heldReport is the report of u's request, held for held and stopped.
func (s *Server) heldReport(u *unroutedHold, held time.Duration, who, asked, where string) string {
func (s *Server) heldReport(u *unroutedHold, held time.Duration, status int, who, asked, where string) string {
var b strings.Builder
fmt.Fprintf(&b, "magpie held a request before routing it, and stopped it with 504\n\n")
fmt.Fprintf(&b, "magpie held a request before routing it, and stopped it with %d\n\n", status)
fmt.Fprintf(&b, "time: %s\n", time.Now().UTC().Format(time.RFC3339))
fmt.Fprintf(&b, "magpie: %s (%s/%s, served by %s)\n", cmpOr(Version, "dev"), runtime.GOOS, runtime.GOARCH, cmpOr(Serves, "?"))
fmt.Fprintf(&b, "request: %s %s\n", u.r.Method, u.r.URL.Path)
@@ -128,6 +128,9 @@ func (s *Server) heldReport(u *unroutedHold, held time.Duration, who, asked, whe
fmt.Fprintf(&b, "agent: %s\n", who)
fmt.Fprintf(&b, "held: %s,%s\n", held, where)
fmt.Fprintf(&b, "known waits:%s\n", cmpOr(strings.TrimPrefix(u.waitsSaid(), ";"), " none"))
// a slow body from a body that stopped coming: what had come, and
// when the last of it did
fmt.Fprintf(&b, "body read: %s\n", u.bodySaid())
bodyRoom.mu.Lock()
fmt.Fprintf(&b, "body room: %d of %d bytes held (%s), %d waiting\n", bodyRoom.held, bodyRoom.room, cmpOr(bodyRoom.why, "unset"), len(bodyRoom.queue))
bodyRoom.mu.Unlock()
+79 -6
View File
@@ -207,6 +207,12 @@ type unroutedHold struct {
// masking counts the maskings under way for it: one held there waits
// for Settings → Privacy's local model, and its error says so
masking atomic.Int32
// the body as it arrives (waitedBody): the bytes read, when the last
// came (unix nanoseconds), and stopped once magpie answered for it
// while it was still arriving, so its handler reads no more of it
bodyRead atomic.Int64
bodyLast atomic.Int64
bodyStopped atomic.Bool
// the waits magpie knows it is in (noteWait), under wmu: how many are
// under way, since when one has been, the time spent in one before
@@ -439,9 +445,64 @@ type waitedBody struct {
}
func (b waitedBody) Read(p []byte) (int, error) {
if b.u.bodyStopped.Load() {
return 0, errBodyStopped
}
done := b.u.wait("body")
defer done()
return b.ReadCloser.Read(p)
n, err := b.ReadCloser.Read(p)
if n > 0 {
b.u.bodyRead.Add(int64(n))
b.u.bodyLast.Store(time.Now().UnixNano())
}
return n, err
}
// errBodyStopped is a body read after magpie answered for its request
// while the body was still arriving.
var errBodyStopped = errors.New("magpie stopped reading this request's body: it was still arriving when magpie answered for it")
// inBody is whether u's request is reading its body now.
func (u *unroutedHold) inBody() bool {
u.wmu.Lock()
defer u.wmu.Unlock()
for _, k := range u.kinds {
if k.kind == "body" {
return k.n > 0
}
}
return false
}
// bodySaid is how much of u's request's body had come, and when the last
// of it did: "12 KB of 3 MB, the last 2s ago".
func (u *unroutedHold) bodySaid() string {
n, of := u.bodyRead.Load(), ""
if d := u.r.ContentLength; d > 0 {
of = " of " + byteWord(d)
}
if n == 0 {
return "none" + of
}
return fmt.Sprintf("%s%s, the last %s ago", byteWord(n), of, time.Since(time.Unix(0, u.bodyLast.Load())).Round(100*time.Millisecond))
}
// byteWord is n bytes in B, KB or MB.
func byteWord(n int64) string {
switch {
case n >= 1<<20:
return fmt.Sprintf("%.1f MB", float64(n)/(1<<20))
case n >= 1<<10:
return fmt.Sprintf("%.1f KB", float64(n)/(1<<10))
}
return fmt.Sprintf("%d bytes", n)
}
// unroutedBodyMsg is the error of a request whose body was still arriving
// 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())
}
// watchUnrouted watches r, counted as f, until the func it answers is
@@ -535,17 +596,29 @@ func (u *unroutedHold) giveUp(unknown bool) {
return
}
held := time.Since(f.start).Round(time.Second)
msg, where := unroutedMsg(held, u.masking.Load() > 0), ""
msg, where, status := unroutedMsg(held, u.masking.Load() > 0), "", http.StatusGatewayTimeout
switch {
case unknown:
where = fmt.Sprintf(" %s of it in no wait magpie knows of", unroutedUnknown)
case u.masking.Load() > 0:
where = " masking it"
case u.inBody():
// the client was still sending it (heatonz on Discord: 2m0s
// "without routing" with the body half in): a 408 says whose
// the time was, and an SDK sends it again at once
where = " its body still arriving (" + u.bodySaid() + ")"
msg, status = unroutedBodyMsg(held, u.bodySaid()), http.StatusRequestTimeout
}
if !u.w.answer(unroutedProto(u.r.URL.Path), http.StatusGatewayTimeout, msg) {
if !u.w.answer(unroutedProto(u.r.URL.Path), status, msg) {
f.mu.Unlock()
return // the handler is answering
}
if status == http.StatusRequestTimeout {
// and the handler reads no more of it: its read ends now, not at
// the next idle limit, and the connection goes with the answer
u.bodyStopped.Store(true)
_ = http.NewResponseController(u.w.w).SetReadDeadline(time.Now())
}
u.ended = true
if u.shown == nil {
u.showLocked()
@@ -553,14 +626,14 @@ func (u *unroutedHold) giveUp(unknown bool) {
shown := u.shown
f.mu.Unlock()
u.s.trace.update(shown, func(r *Route) {
r.Done, r.Status, r.Error, r.Millis = true, http.StatusGatewayTimeout, msg, time.Since(r.Time).Milliseconds()
r.Done, r.Status, r.Error, r.Millis = true, status, msg, time.Since(r.Time).Milliseconds()
})
// the report is taken while it is still held: once its context ends,
// what held it lets go, and the stacks would show it gone
asked, _ := u.asked.Load().(string)
who := cmpOr(u.agent, cmpOr(f.agent, "?"))
where = cmpOr(where, " not masking it")
report := u.s.heldReport(u, held, who, asked, where)
report := u.s.heldReport(u, held, status, who, asked, where)
u.cancel(errUnrouted)
name, err := writeHeld(report)
saved := ""
@@ -570,7 +643,7 @@ func (u *unroutedHold) giveUp(unknown bool) {
saved = "; its report is " + filepath.Join(HeldDir(), name)
u.s.trace.update(shown, func(r *Route) { r.Held = name })
}
log.Printf("gateway: %s %s for %s from %s held %s before routing,%s%s; stopped with 504%s%s", u.r.Method, u.r.URL.Path, cmpOr(asked, "?"), who, held, where, u.waitsSaid(), saved, unroutedStacks())
log.Printf("gateway: %s %s for %s from %s held %s before routing,%s%s; stopped with %d%s%s", u.r.Method, u.r.URL.Path, cmpOr(asked, "?"), who, held, where, u.waitsSaid(), status, saved, unroutedStacks())
}
// unroutedMsg is the error of a request held for held before routing:
+101
View File
@@ -0,0 +1,101 @@
package gateway
import (
"bufio"
"fmt"
"io"
"net"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
)
// heatonz on Discord (Hermes Agent to magpie in Docker): requests held
// 2m0s "without routing it to any provider", the report's one wait "body
// 2m0s (under way)". A body that keeps coming, a byte at a time and never
// idle for the read's own limit, reached unroutedMost while it was still
// being read. It is answered 408, saying the body was still arriving and
// how much had come, and its read ends with the answer: the handler
// doesn't go on reading a body nobody will route.
func TestUnroutedTrickledBodyAnswered408(t *testing.T) {
t.Setenv("XDG_CACHE_HOME", t.TempDir())
unroutedLimits(t, 20*time.Millisecond, 500*time.Millisecond)
s, _ := slowEyed(t, 0)
srv := httptest.NewServer(s.Handler())
t.Cleanup(srv.Close)
// 40 bytes a second for 400 bytes: ten seconds, far past unroutedMost
body := unroutedHi + strings.Repeat(" ", 400-len(unroutedHi))
conn, err := net.Dial("tcp", strings.TrimPrefix(srv.URL, "http://"))
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { conn.Close() })
conn.SetDeadline(time.Now().Add(20 * time.Second))
fmt.Fprintf(conn, "POST /v1/chat/completions HTTP/1.1\r\nHost: 127.0.0.1\r\nContent-Type: application/json\r\nContent-Length: %d\r\n\r\n", len(body))
stop := make(chan struct{})
t.Cleanup(func() { close(stop) })
go func() {
for i := 0; i < len(body); i++ {
select {
case <-stop:
return
case <-time.After(25 * time.Millisecond):
}
if _, err := conn.Write([]byte{body[i]}); err != nil {
return
}
}
}()
br := bufio.NewReader(conn)
res, err := http.ReadResponse(br, nil)
if err != nil {
t.Fatal(err)
}
b, _ := io.ReadAll(res.Body)
res.Body.Close()
answered := time.Now()
if res.StatusCode != http.StatusRequestTimeout || !strings.Contains(string(b), "its body was still arriving") || !strings.Contains(string(b), "of 400 bytes, the last") {
t.Fatalf("a body still arriving at unroutedMost was answered %d %s", res.StatusCode, b)
}
// the connection ends with the answer, long before the body would
if _, err := br.ReadByte(); err != io.EOF && !isClosedConn(err) {
t.Fatalf("after the 408 the connection read %v, not its end", err)
}
if waited := time.Since(answered); waited > 3*time.Second {
t.Fatalf("the connection ended %v after the 408: its handler read on", waited)
}
// the model isn't read yet, so its route names none; the report is
// saved after the answer
for deadline := time.Now().Add(10 * time.Second); ; time.Sleep(10 * time.Millisecond) {
for _, r := range routesOf(s, "") {
if r.Held == "" {
continue
}
if r.Status != http.StatusRequestTimeout {
t.Errorf("its route says %d", r.Status)
}
text, err := HeldReport(r.Held)
if err != nil {
t.Fatal(err)
}
for _, want := range []string{"stopped it with 408", "body read: ", "of 400 bytes, the last", "body still arriving"} {
if !strings.Contains(text, want) {
t.Errorf("the report doesn't say %q:\n%.1500s", want, text)
}
}
return
}
if time.Now().After(deadline) {
t.Fatal("no route names the report")
}
}
}
func isClosedConn(err error) bool {
return err != nil && (strings.Contains(err.Error(), "connection reset") || strings.Contains(err.Error(), "closed"))
}