gateway: a held or relayed stream is kept alive for 30 minutes, then ended with an error (Wing8Aqua on X)

Wing8Aqua on X (magpie 0.1.4111, Ubuntu): asking Claude Fable 5.2 ended
with "pi-ai stream idle timeout after 300000ms". A stream the gateway
passes through as it is (or holds before its headers) got a comment each
keepaliveEvery of vendor silence, but only for keepaliveLongest (5
minutes) since the vendor was last heard. After that the client got no
bytes and no error, so an agent's own idle timer ended it. A translated
stream is already kept alive for translatedQuietLongest (30 minutes), and
the Claude bridge for as long as its Claude Code works (#5043).

holdWriter.keepQuiet now keeps up its comments for translatedQuietLongest.
Past that the vendor is taken as stuck (endStuck): the client gets a 504
"<provider> sent nothing for <d>; the request was ended", as its stream's
error event once the reply has passed or as a status before it, and
serve records the try and tries nothing again after so long a wait.

Note that the reporter's message is DeepSeek Harness's (dsh-llm-pi-ai). Its
watchdog re-arms only on content events, so no keepalive reaches it, and
the 300000 is the route's streamIdleTimeoutMs. magpie writes 600000 into
the dsh routes it makes (dshIdleWait, since v0.1.2464) and keeps a value
already there. This change covers byte-counting clients (pi, Claude Code,
Codex). It does not change dsh.

Tests: TestQuietClaudeStreamKeptAlivePastFiveMinutes (Messages relay,
quiet after message_start and before its headers, keepaliveLongest at
100ms, 1.5s of silence: the client never goes 500ms without a byte, the
reply is whole, and the vendor is asked once) and
TestQuietClaudeStreamStuckEndsWithAnError (silence past
translatedQuietLongest: an error event naming the provider, no reply after
it, one request). TestQuietKeptAliveOnlySoLong now expects the error.

Run at this tree (rebased on a265632da):
- gofmt -l internal/gateway: clean.
- mote-run go vet ./internal/gateway, plus GOOS=linux and GOOS=windows: ok.
- mote-run go test ./internal/gateway -run
  'TestQuiet|TestSilentHeld|TestTranslatedStream|TestKeep|Loop|Slow|Hold': ok.
- wsl-run (Ubuntu 24.04) go test ./internal/gateway -run
  'TestQuiet|TestSilentHeld|TestTranslatedStream|TestKeep|Hold': ok.
- Broken by hand: restoring keepQuiet's keepaliveLongest bound turns
  both new tests (all four subtests) and TestQuietKeptAliveOnlySoLong red.
- Real pi 1.5.2 on mote in a sandbox HOME (httpIdleTimeoutMs 2000),
  through a test gateway to a fake Claude relay quiet for 6s after
  message_start, with keepaliveLongest at 300ms. Old bound: "terminated:
  Body Timeout Error (UND_ERR_BODY_TIMEOUT)". New: "answered". With
  translatedQuietLongest at 1s and the relay quiet 20s, pi prints "Relay
  sent nothing for 1s; the request was ended (504 ...)". This was a
  temporary test, not committed.

Not run before the push: the whole internal/gateway package and the full
suite. mote was at load 20-28 and mica had another session's full suite.
They run next, and any red gets its own issue.
Not tried: real dsh, and a real Fable 5.2 account (the route the reporter
uses is unknown).
This commit is contained in:
yetone
2026-11-18 11:08:46 +08:00
parent a265632dae
commit 53db3e3891
5 changed files with 255 additions and 23 deletions
File diff suppressed because one or more lines are too long
+49 -6
View File
@@ -2717,6 +2717,12 @@ type holdWriter struct {
// takes; slow says it took longer, and was let go with nothing sent
firstWait time.Duration
slow bool
// stuck says the vendor said nothing for translatedQuietLongest
// while the agent was kept alive (keepQuiet), and the try was let go:
// the agent is told so as an error, never left with silence
stuck string
// name is the provider's, for what stuck tells the agent
name string
// budgeted says firstWait was cut to what was left of the walk's
// total time (groupBudget), so its running out is the budget's end,
// not this member being slow (#5113)
@@ -2863,7 +2869,7 @@ func (h *holdWriter) Write(b []byte) (int, error) {
if h.slow {
return 0, errSlowStart
}
if h.looped != "" || h.relooped {
if h.looped != "" || h.relooped || h.stuck != "" {
return 0, errLooped
}
if h.handedOver {
@@ -3850,8 +3856,13 @@ func (h *holdWriter) watch() func() {
}
// keepQuiet keeps the agent of a stream alive with SSE comments while the
// vendor says nothing, every keepaliveEvery for up to keepaliveLongest
// since it last did: a vendor that sent its 200 and response.created, then
// vendor says nothing, every keepaliveEvery for up to translatedQuietLongest
// since it last did, as a translated reply's client is kept
// (keepThroughSilence), and then ends the try with an error the agent is
// told (endStuck). It stopped at keepaliveLongest (5 minutes) and left the
// agent with nothing: a Claude relay that took longer than that before its
// headers, or quiet mid-reply, had pi's 300s idle timeout end the request
// with no word of why (Wing8Aqua on X). A vendor that sent its 200 and response.created, then
// nothing while it reasoned, had the stream held with none of it sent,
// and Cloudflare in front of a remote magpie ended the request at 125s
// (524) with the agent sent nothing at all; one quiet mid-reply was reset
@@ -3859,11 +3870,12 @@ func (h *holdWriter) watch() func() {
// comments only (keepAlive), none of the try, which another account may
// still answer instead; passed, a comment goes between two lines of it.
func (h *holdWriter) keepQuiet() {
if h.slow || h.relooped || h.ended || h.alive == nil || h.alive.proto == provider.Gemini || h.ctx != nil && h.ctx.Err() != nil {
if h.slow || h.relooped || h.ended || h.stuck != "" || h.alive == nil || h.alive.proto == provider.Gemini || h.ctx != nil && h.ctx.Err() != nil {
return
}
if !h.heard.IsZero() && time.Since(h.heard) >= keepaliveLongest {
return // a stream stuck this long is left for a timeout to end
if !h.heard.IsZero() && time.Since(h.heard) >= translatedQuietLongest {
h.endStuck(time.Since(h.heard))
return
}
if !h.passing && h.stream && h.failure == 0 && !h.whole && !h.wantWhole && h.held.Len() > 0 && h.alive.tooQuiet(0) {
// a stream held while its vendor is quiet: Codex would hang up
@@ -3891,6 +3903,37 @@ func (h *holdWriter) keepQuiet() {
}
}
// endStuck lets a try go whose vendor said nothing for quiet
// (translatedQuietLongest), its agent kept alive all that time. Passing,
// the agent's stream ends with the error as its own event, after a blank
// line, as cutLoop ends one; held, the gateway tells it (stuck, failTo),
// and nobody else is asked: the agent has waited that long already.
func (h *holdWriter) endStuck(quiet time.Duration) {
name := h.name
if name == "" {
name = "the provider"
}
d := quiet.Round(time.Second)
if d == 0 {
d = quiet.Round(time.Millisecond)
}
h.stuck = fmt.Sprintf("%s sent nothing for %s; the request was ended", name, d)
if h.passing && strings.HasPrefix(h.w.Header().Get("Content-Type"), "text/event-stream") {
proto := h.alive.proto
if h.atLine {
io.WriteString(h.w, "\n")
} else {
io.WriteString(h.w, "\n\n")
}
streamError(h.w, proto, "", http.StatusGatewayTimeout, h.stuck)
h.ended = true
h.flush()
}
if h.stop != nil {
h.stop()
}
}
// started says whether the try has begun its reply, or ended, as far as
// watch need know: its first content, anything sent on to the agent,
// a failure, or a reply that isn't streamed.
+16 -2
View File
@@ -4408,7 +4408,7 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
// at once instead of waiting in the queue (FallbackHeader)
ctx = withFallback(ctx)
}
hw.stop = stop
hw.stop, hw.name = stop, c.p.Name
if magpieAsks(r) {
// another magpie asked: its log is told the tier this
// one sent (stampTier)
@@ -4711,6 +4711,19 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
s.trace.update(tr, func(t *Route) { t.Tries[len(t.Tries)-1] = try })
break
}
if hw.stuck != "" {
// the vendor said nothing for translatedQuietLongest while the
// agent was kept alive (keepQuiet): it is told so, and nobody
// else is asked after it has waited that long
call.Status, call.Error = http.StatusGatewayTimeout, hw.stuck
try.Status, try.Error = call.Status, call.Error
watched.attempt(call, try, c.p.ID, sent, hw, capture)
s.trace.update(tr, func(t *Route) { t.Tries[len(t.Tries)-1] = try })
if !hw.ended {
failTo(w, kept, from, call.Status, hw.stuck)
}
break
}
if hw.slow {
// no first content in the group's FirstToken, and nothing of
// it sent: the next member is asked, and this one doesn't
@@ -10064,7 +10077,8 @@ var keepaliveEvery, keepaliveLongest = 15 * time.Second, 5 * time.Minute
// translatedQuietLongest is how long a translated reply's upstream may
// say nothing at all, its stream open, while magpie keeps the client
// alive every keepaliveEvery (keepThroughSilence). A reply that comes in
// alive every keepaliveEvery (keepThroughSilence), and a reply passed
// through or held is kept so too (keepQuiet). A reply that comes in
// one burst at its end (claude-opus-5-5 at effort max, a relay that
// buffers) is silent for its whole generation, which runs past 10
// minutes, longer than the 10 minutes magpie gives a vendor for its
+20 -14
View File
@@ -184,10 +184,11 @@ func TestSilentHeldStreamStillFailsOver(t *testing.T) {
}
}
// A vendor quiet for longer than keepaliveLongest (the held stream's
// comments) and translatedQuietLongest (a translated stream's own,
// keepThroughSilence) is no longer covered for: the comments stop, for a
// stuck stream to end at a timeout.
// A vendor quiet for longer than translatedQuietLongest, which both the
// held stream's comments (keepQuiet) and a translated stream's own
// (keepThroughSilence) cover, is let go: the client is told so as its
// stream's error, not left with comments that stop and then silence
// (Wing8Aqua on X; TestQuietClaudeStreamStuckEndsWithAnError).
func TestQuietKeptAliveOnlySoLong(t *testing.T) {
fresh(t)
quietFast(t)
@@ -199,25 +200,30 @@ func TestQuietKeptAliveOnlySoLong(t *testing.T) {
quietOn(t, "fixture", quietCreated+quietDelta("hel"), quietDelta("lo")+quietDone, never)
gw := httptest.NewServer(New().Handler())
t.Cleanup(gw.Close)
began := time.Now()
resp, err := http.Post(gw.URL+"/v1/chat/completions", "application/json",
strings.NewReader(`{"model":"fixture/gpt-test","stream":true,"messages":[{"role":"user","content":"hi"}]}`))
if err != nil {
t.Fatal(err)
}
defer resp.Body.Close()
b, _ := io.ReadAll(resp.Body) // the vendor goes on after 3s
// counted from its first words, as readQuiet: the held stream's before
// them are kept for 200ms of their own
b, _ := io.ReadAll(resp.Body) // the vendor would go on after 3s
took := time.Since(began)
body := string(b)
i, j := strings.Index(body, "hel"), strings.Index(body, `"lo"`)
if i < 0 || j < i {
i := strings.Index(body, "hel")
if i < 0 || strings.Contains(body, `"lo"`) {
t.Fatalf("%q", body)
}
// 200ms at one each 40ms is 5, from each of the two keepers, the
// held stream's and the translated stream's, with room; one that
// never stopped sends ~75 in the 3s
if n := strings.Count(body[i:j], ": keepalive"); n == 0 || n > 16 {
t.Fatalf("%d keepalives in 3s, kept for 200ms: %q", n, body)
if !strings.Contains(body[i:], "Fixture sent nothing for") || !strings.Contains(body[i:], `"error"`) {
t.Fatalf("the stuck vendor's stream ended with no error: %q", body)
}
if took >= 2500*time.Millisecond {
t.Fatalf("ended after %v, the vendor's own 3s: it wasn't let go", took)
}
// kept alive until then: 200ms at one each 40ms, from each keeper,
// with room
if n := strings.Count(body[i:], ": keepalive"); n == 0 || n > 24 {
t.Fatalf("%d keepalives: %q", n, body)
}
}
+169
View File
@@ -0,0 +1,169 @@
package gateway
import (
"bufio"
"io"
"net/http"
"net/http/httptest"
"strings"
"sync/atomic"
"testing"
"time"
"github.com/yetone/magpie/internal/provider"
)
const (
stuckStart = "event: message_start\ndata: {\"type\":\"message_start\",\"message\":{\"id\":\"m1\",\"type\":\"message\",\"role\":\"assistant\",\"model\":\"m\",\"content\":[],\"usage\":{\"input_tokens\":3,\"output_tokens\":0}}}\n\n"
stuckRest = "event: content_block_start\ndata: {\"type\":\"content_block_start\",\"index\":0,\"content_block\":{\"type\":\"text\",\"text\":\"\"}}\n\n" +
"event: content_block_delta\ndata: {\"type\":\"content_block_delta\",\"index\":0,\"delta\":{\"type\":\"text_delta\",\"text\":\"answered\"}}\n\n" +
"event: content_block_stop\ndata: {\"type\":\"content_block_stop\",\"index\":0}\n\n" +
"event: message_delta\ndata: {\"type\":\"message_delta\",\"delta\":{\"stop_reason\":\"end_turn\"},\"usage\":{\"output_tokens\":1}}\n\n" +
"event: message_stop\ndata: {\"type\":\"message_stop\"}\n\n"
)
// quietClaude serves a Claude relay on Messages that, for each request,
// sends its headers and head (none at all with noHead), says nothing for
// quiet, and then the rest of its reply. asked counts its requests.
func quietClaude(t *testing.T, head string, noHead bool, quiet time.Duration) *atomic.Int32 {
t.Helper()
asked := new(atomic.Int32)
up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
io.ReadAll(r.Body)
asked.Add(1)
if !noHead {
w.Header().Set("Content-Type", "text/event-stream")
w.WriteHeader(http.StatusOK)
io.WriteString(w, head)
w.(http.Flusher).Flush()
}
select {
case <-time.After(quiet):
case <-r.Context().Done():
return
}
if noHead {
w.Header().Set("Content-Type", "text/event-stream")
io.WriteString(w, stuckStart)
}
io.WriteString(w, stuckRest)
}))
t.Cleanup(up.Close)
if err := provider.Save(provider.Provider{ID: "relay", Name: "Relay", Key: "k", Models: []string{"claude-fable-5-2"}, Anthropic: up.URL}); err != nil {
t.Fatal(err)
}
return asked
}
// askQuietClaude streams a Messages request for relay/claude-fable-5-2, as pi
// and dsh ask a Claude, and tells the body and the longest the client
// went without a byte, from the request on.
func askQuietClaude(t *testing.T) (string, time.Duration, time.Duration) {
t.Helper()
gw := httptest.NewServer(New().Handler())
t.Cleanup(gw.Close)
began := time.Now()
resp, err := http.Post(gw.URL+"/v1/messages", "application/json",
strings.NewReader(`{"model":"relay/claude-fable-5-2","stream":true,"max_tokens":100,"messages":[{"role":"user","content":"hi"}]}`))
if err != nil {
t.Fatal(err)
}
defer resp.Body.Close()
last := time.Now()
gap := last.Sub(began)
var b strings.Builder
rd := bufio.NewReader(resp.Body)
for {
line, err := rd.ReadString('\n')
if line != "" {
gap = max(gap, time.Since(last))
last = time.Now()
b.WriteString(line)
}
if err != nil {
break
}
}
return b.String(), gap, time.Since(began)
}
// Wing8Aqua on X: pi asked Claude Fable 5.2 through magpie and gave up
// with "stream idle timeout after 300000ms". A relayed Claude stream, held
// before its headers or quiet after message_start, was kept alive with
// comments for keepaliveLongest (5 minutes) after the vendor was last
// heard, then left with nothing, and pi's 300s idle timeout ended it at
// ~10 minutes with no word of why. It is kept alive as long as a
// translated stream is (translatedQuietLongest): here the old 5 minutes
// is 100ms, the vendor is quiet for 1.5s, and the client, whose idle
// timeout stands for pi's, must never go 500ms without a byte.
func TestQuietClaudeStreamKeptAlivePastFiveMinutes(t *testing.T) {
for _, c := range []struct {
name string
head string
noHead bool
}{
{"quiet after message_start", stuckStart, false},
{"quiet before its headers", "", true},
} {
t.Run(c.name, func(t *testing.T) {
fresh(t)
quietFast(t)
keepaliveLongest = 100 * time.Millisecond
was := translatedQuietLongest
translatedQuietLongest = 10 * time.Second
t.Cleanup(func() { translatedQuietLongest = was })
asked := quietClaude(t, c.head, c.noHead, 1500*time.Millisecond)
body, gap, _ := askQuietClaude(t)
if !strings.Contains(body, "answered") || !strings.Contains(body, "message_stop") {
t.Fatalf("the reply didn't come whole:\n%s", body)
}
if gap >= 500*time.Millisecond {
t.Fatalf("the client heard nothing for %v while the vendor was quiet (an idle timeout of 500ms ends it):\n%s", gap, body)
}
if n := asked.Load(); n != 1 {
t.Fatalf("the vendor was asked %d times, want 1", n)
}
})
}
}
// A vendor that says nothing for translatedQuietLongest while the client
// is kept alive is let go, and the client is told so in its own protocol,
// naming the provider: before, the comments stopped and the client met
// only its own idle timeout. Nobody is asked again after so long a wait.
func TestQuietClaudeStreamStuckEndsWithAnError(t *testing.T) {
for _, c := range []struct {
name string
head string
noHead bool
}{
{"quiet after message_start", stuckStart, false},
{"quiet before its headers", "", true},
} {
t.Run(c.name, func(t *testing.T) {
fresh(t)
quietFast(t)
keepaliveLongest = 100 * time.Millisecond
was := translatedQuietLongest
translatedQuietLongest = 400 * time.Millisecond
t.Cleanup(func() { translatedQuietLongest = was })
asked := quietClaude(t, c.head, c.noHead, 5*time.Second)
body, gap, took := askQuietClaude(t)
if !strings.Contains(body, "event: error") || !strings.Contains(body, "Relay sent nothing for") {
t.Fatalf("no error told the client of the stuck vendor:\n%s", body)
}
if strings.Contains(body, "answered") {
t.Fatalf("the reply went on after its error:\n%s", body)
}
if took >= 4*time.Second {
t.Fatalf("the stream ended after %v, with the vendor's own end at 5s: it wasn't let go", took)
}
if gap >= 300*time.Millisecond {
t.Fatalf("the client heard nothing for %v before the error:\n%s", gap, body)
}
if n := asked.Load(); n != 1 {
t.Fatalf("the vendor was asked %d times, want 1", n)
}
})
}
}