gateway: a Claude stream held for its reasoning keeps the agent alive with SSE comments, and a request whose agent went away is recorded as canceled, not as a 200 done (#751, margbug01 on v0.1.679: Alma → magpie → Claude Code (Claude Max, claude-opus-5-5) ended with "No LLM streaming data for 240000ms", while the routing record said 200, about 240000 ms, TTFT about 4.3 s, 8 tokens out, done with no error) — for a Claude model, refusesAfterThinking, a stream that holds nothing but reasoning is held for up to holdThinking (4 minutes) so that a refusal after it can still go to another account (#248). Everything written meanwhile was held with it: message_start, the thinking deltas and the protocol keepalives relay sends every 15s (#436). The agent got no byte at all, and Alma's idle timeout for a reasoning model (60s ×4 = 240s, reset by any SSE line, comments included) ran out first. The hold is on for nearly every first try (!last || again < retries || …), so one Claude account alone was enough. The TTFT on the record is the held stream's first event, not a byte delivered. Now, once a stream has been held for its thinking or safety buffering past keepHeldAfter (holdLongest, 15s), holdWriter.keepAlive sends the agent the stream's 200 and headers once, then a ": keepalive" comment every keepaliveEvery while the stream stays held. The comment is not an event in any protocol and says nothing of the reasoning, and no model text is made up. The keptAlive is the request's and is shared by its tries. A refusal after the comments still goes to the next member: its pass() skips the headers already sent, and its stream follows in the same response. Once headers are out, a failure can no longer be a status, so the gateway's writeErrors inside the try loop go through failTo and holdWriter.release goes through streamError, which tell it as the stream's own error event (Anthropic event: error, Responses response.failed, Chat's error chunk). The last try's writer is held too once headers are out. A Responses agent (Codex) doesn't count comments, but its 300s timeout outlasts the 4-minute hold.

When the agent went away, serveSubscription's AfterFunc stopped Claude Code, but relay still called enc.finish(), which wrote message_stop to the gone writer. holdWriter.see took that as the reply made whole (ended), so serve's `r.Context().Err() != nil && !hw.ended` check, which records 499 "the agent canceled the request" with Fail canceled, was skipped and the request was recorded as 200 done. see now ignores a stream end written once the request's context is done, and the bridge logs "Claude Code run on <model> stopped: the client went away <t> into the reply".
TestHeldThinkingKeepsTheAgentAlive sends claude-opus-5-5 thinking that goes on (pings every 10ms until the client hears a keepalive, else 3s) through a group over a real HTTP gateway. It covers three cases: a refusal after it, where the client gets ": keepalive" before b's answer in the same stream, with one message_start, no reasoning text and Tries[0] refused; an answer after it, which arrives whole after the comments; and a refusal with nobody left, which arrives as a 200 stream with event: error. TestClientGoneRecordedAsCanceled checks a holdWriter whose context is canceled before message_stop, and a fake Claude Code run (fakeClaudeCalling's hang) stopped mid-reply through serveClaudeSubscription writing to a holdWriter. With keepAlive's call and see's context check taken out, both fail: the client heard nothing until the upstream gave up waiting at 3s, and ended was set. go vet, builds (darwin, GOOS=linux, GOOS=windows), go test -tags nogui -count=1 ./... under a temp HOME, and -race on the gateway's refusal, thinking, keepalive and cancel tests all pass. Not tried with real Claude Code, a real Claude Max account or Alma. Not changed: --thinking-display summarized is passed only when the request names an effort, so Claude Code's own thinking display is otherwise left at the API's default; relay's keepalives stop 5 minutes after the last event (keepaliveLongest); and Gemini clients get no keepalive.
This commit is contained in:
yetone
2026-10-04 14:11:24 +08:00
parent 8031edc78b
commit 3eae3ee7fb
4 changed files with 292 additions and 9 deletions
+6 -1
View File
@@ -1775,7 +1775,12 @@ func (s *Server) serveSubscription(w http.ResponseWriter, r *http.Request, from
// a caller gone before the reply is whole won't carry it on: its agent
// is stopped at once, not left to answer no one and wait on tool calls
// it never handed over
gone := context.AfterFunc(r.Context(), run.abort)
began := time.Now()
gone := context.AfterFunc(r.Context(), func() {
// said in the log, as the routing trace says it with a 499 (#751)
log.Printf("%s run on %s stopped: the client went away %s into the reply", name, model, time.Since(began).Round(time.Millisecond))
run.abort()
})
defer gone()
return relay(w, r, from, name, req, events, usage, run.abort, func(said, stop string, ok bool) {
gone()
+70 -1
View File
@@ -15,8 +15,10 @@ package gateway
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"regexp"
"slices"
@@ -857,6 +859,14 @@ type holdWriter struct {
ended bool // the stream's last event was written: the reply is whole
tail []byte // the end of the last write, for a marker split across two
// ctx is the agent's request: a stream's last event written once it
// has gone reached nobody, and doesn't make the reply whole (#751)
ctx context.Context
// alive is the request's, shared by its tries: a stream held for its
// reasoning keeps the agent from its idle timeout with SSE comments
// meanwhile (#751)
alive *keptAlive
first firstToken // when its first content and text came (#196)
@@ -894,6 +904,11 @@ func (h *holdWriter) WriteHeader(code int) {
}
func (h *holdWriter) pass() {
if h.alive != nil && h.alive.sent {
// the agent has the stream's headers already, from keepAlive
h.passing = true
return
}
dst := h.w.Header()
for k, v := range h.header {
if k != resetsHeader && k != refusedHeader { // magpie's own notes, for restAfter and settle
@@ -931,7 +946,7 @@ var streamEnds = [][]byte{
// see notes a stream's last event going by. An agent may hang up as soon as
// it has that — Codex does — and a reply it had whole is not canceled.
func (h *holdWriter) see(b []byte) {
if h.ended {
if h.ended || h.ctx != nil && h.ctx.Err() != nil {
return
}
buf := append(h.tail, b...)
@@ -1029,6 +1044,54 @@ func (h *holdWriter) scan() {
}
if h.held.Len() > holdMost || time.Since(h.since) > longest {
h.flow()
return
}
if (h.thinking || h.buffered) && time.Since(h.since) >= keepHeldAfter {
h.keepAlive()
}
}
// keepHeldAfter is how long a stream held for its reasoning waits before
// its agent is first kept alive, as long as a stream with nothing in it
// is held (holdLongest); a refusal after it still goes to another account,
// whose stream follows the comments in the same response.
var keepHeldAfter = holdLongest
// keptAlive is what a request's held streams have sent its agent ahead of
// a reply: the stream's headers and SSE comments, nothing of the reply.
type keptAlive struct {
proto provider.Protocol
sent bool // the stream's 200 and headers went out
at time.Time // the last comment
}
// keepAlive tells the agent of a stream held past keepHeldAfter for its
// reasoning that it goes on, every keepaliveEvery: held for up to
// holdThinking (4 minutes), the agent heard nothing at all, and Alma's
// idle timeout for a reasoning model, 240s, ended the turn first (#751). A
// comment is no event in any protocol, so another account may still answer
// after it, its stream going on in the same response (pass).
func (h *holdWriter) keepAlive() {
a := h.alive
if a == nil || time.Since(a.at) < keepaliveEvery {
return
}
if !a.sent {
dst := h.w.Header()
for k, v := range h.header {
if k != resetsHeader && k != refusedHeader && k != "Content-Length" {
dst[k] = v
}
}
dst.Set("Content-Type", "text/event-stream; charset=utf-8")
h.w.WriteHeader(http.StatusOK)
a.sent = true
}
// no blank line after it, as sseWriter.comment
_, _ = io.WriteString(h.w, ": keepalive\n")
a.at = time.Now()
if f, ok := h.w.(http.Flusher); ok {
f.Flush()
}
}
@@ -1101,6 +1164,12 @@ func (h *holdWriter) release() {
if h.passing || h.status == 0 {
return
}
if h.alive != nil && h.alive.sent && !h.stream {
// an error status, once the agent has a stream: told as its error
h.passing = true
streamError(h.w, h.alive.proto, h.status, provider.APIError(h.held.Bytes(), http.StatusText(h.status)))
return
}
h.pass()
h.w.Write(h.held.Bytes())
h.Flush()
+35 -7
View File
@@ -1343,13 +1343,18 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
providerKeyID, providerKeyName, providerAccount := "", "", ""
var other *Try // the first failure that wasn't an allowance run out
autoReset := false // a Codex or Claude reset looked at, once a request
// what the tries' held streams sent the agent ahead of a reply (#751)
kept := &keptAlive{proto: from}
for i := 0; i < len(cands); i++ {
c := cands[i]
last := i == len(cands)-1
// the last one's failure is held too when an earlier one failed,
// for its allowance running out to be told as that one's error
hw := newHoldWriter(w, !last || again < max(lastRetries, rateRetries) || other != nil)
// and once the agent has the stream's headers from an earlier try's
// keepalives, for a failure to be told as the stream's error
hw := newHoldWriter(w, !last || again < max(lastRetries, rateRetries) || other != nil || kept.sent)
hw.thinkingShown = !refusesAfterThinking(c.model)
hw.ctx, hw.alive = r.Context(), kept
call.Provider, call.To, call.Usage = c.p.ID, "", Usage{}
model = c.model
where = c.p.Where()
@@ -1381,7 +1386,7 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
}
see, _ := seeing()
call.Status = 502
writeError(w, from, 502, fmt.Sprintf("model %q can't see images, and %s couldn't describe the image for it: %v", c.p.ID+"/"+c.model, see, err))
failTo(w, kept, from, 502, fmt.Sprintf("model %q can't see images, and %s couldn't describe the image for it: %v", c.p.ID+"/"+c.model, see, err))
break
}
attemptBody = b
@@ -1623,7 +1628,7 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
continue
}
call.Status, call.Error = http.StatusBadRequest, effortError(c, sent, takes, call.Error)
writeError(w, from, call.Status, call.Error)
failTo(w, kept, from, call.Status, call.Error)
break
}
}
@@ -1756,7 +1761,7 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
// nobody is left: the agent is told it was refused, as a
// request it shouldn't send again as it is, not handed an empty
// reply it would ask again for, paying for each
writeError(w, from, refusedStatus, call.Error)
failTo(w, kept, from, refusedStatus, call.Error)
} else if f := failure(call.Status, []byte(call.Error)); other != nil && !hw.passing && call.Status >= 400 && (f == failQuota || f == failCredit) {
// the last one left is out of its allowance, but one before it
// failed otherwise: the agent is told that one's error, not
@@ -1766,14 +1771,14 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
try.Fail = f
s.trace.update(tr, func(t *Route) { t.Tries[len(t.Tries)-1] = try })
call.Status, call.Error = other.Status, other.Error
writeError(w, from, call.Status, call.Error)
failTo(w, kept, from, call.Status, call.Error)
break
} else if outgrew {
// in the agent's own words for it, for it to compact
writeError(w, from, call.Status, hw.failMsg)
failTo(w, kept, from, call.Status, hw.failMsg)
} else if !hw.passing && hw.code() == http.StatusRequestEntityTooLarge {
// No member left took the body; only now add the byte-limit hint.
writeError(w, from, call.Status, call.Error)
failTo(w, kept, from, call.Status, call.Error)
} else {
hw.release()
if hw.passing {
@@ -3801,6 +3806,29 @@ func writeJSON(w http.ResponseWriter, status int, v any) {
enc.Encode(v)
}
// failTo answers the agent with an error: as writeError does, or as its
// stream's error once a held stream sent it the stream's headers to keep
// it alive (keepAlive), where a status can no longer be said.
func failTo(w http.ResponseWriter, a *keptAlive, proto provider.Protocol, status int, msg string) int {
if a == nil || !a.sent {
return writeError(w, proto, status, msg)
}
streamError(w, proto, status, msg)
return status
}
// streamError writes an error as an event of the client's stream, its
// headers already sent.
func streamError(w http.ResponseWriter, proto provider.Protocol, status int, msg string) {
sw := newSSEWriter(w)
sw.begun = true
ev := Event{Kind: KError, Text: msg, Status: status}
if tooLong(status, msg) {
ev.Code = "context_length_exceeded"
}
makeEncoder(proto, sw, &Request{}).event(ev)
}
// writeError answers in the client's own error shape.
func writeError(w http.ResponseWriter, proto provider.Protocol, status int, msg string) int {
typ := "api_error"
+181
View File
@@ -0,0 +1,181 @@
package gateway
import (
"bufio"
"context"
"io"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strconv"
"strings"
"sync"
"testing"
"time"
"github.com/yetone/magpie/internal/provider"
)
// thinkingOn serves Claude thinking at length: its first events, then
// Anthropic's pings until heard is closed (or 3s), then the rest of reply.
func thinkingOn(t *testing.T, id, reply string, heard <-chan struct{}) {
t.Helper()
events := strings.SplitAfter(reply, "\n\n")
up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
io.ReadAll(r.Body)
w.Header().Set("Content-Type", "text/event-stream")
f := w.(http.Flusher)
io.WriteString(w, events[0]+events[1]+events[2])
f.Flush()
for wait := time.After(3 * time.Second); ; {
select {
case <-heard:
case <-wait:
case <-time.After(10 * time.Millisecond):
io.WriteString(w, "event: ping\ndata: {\"type\": \"ping\"}\n\n")
f.Flush()
continue
}
break
}
for _, ev := range events[3:] {
io.WriteString(w, ev)
}
}))
t.Cleanup(up.Close)
if err := provider.Save(provider.Provider{ID: id, Name: strings.ToUpper(id), Key: "k", Models: []string{"claude-opus-5-5"}, Anthropic: up.URL}); err != nil {
t.Fatal(err)
}
}
// ask posts claudeCodeAsk to the gateway over HTTP and reads the reply as
// it comes, closing heard once a keepalive arrived.
func ask(t *testing.T, s *Server, heard chan struct{}) (int, string) {
t.Helper()
gw := httptest.NewServer(s.Handler())
t.Cleanup(gw.Close)
resp, err := http.Post(gw.URL+"/v1/messages", "application/json", strings.NewReader(claudeCodeAsk))
if err != nil {
t.Fatal(err)
}
defer resp.Body.Close()
var once sync.Once
var body strings.Builder
rd := bufio.NewReader(resp.Body)
for {
line, err := rd.ReadString('\n')
body.WriteString(line)
if strings.HasPrefix(line, ": keepalive") {
once.Do(func() { close(heard) })
}
if err != nil {
break
}
}
return resp.StatusCode, body.String()
}
// Claude thinking for longer than the agent's idle timeout through a
// group, where its stream is held for a refusal to go to another account
// (#248): the agent heard nothing for up to four minutes, and Alma's 240s
// timeout for a reasoning model ended the turn first (#751). It is kept
// alive with comments meanwhile, which say nothing of the reasoning, and a
// refusal after them still goes to the next member, whose answer follows
// in the same stream.
func TestHeldThinkingKeepsTheAgentAlive(t *testing.T) {
fresh(t)
keepFast(t, keepaliveGap, 20*time.Millisecond, keepaliveLongest)
k := keepHeldAfter
keepHeldAfter = 30 * time.Millisecond
t.Cleanup(func() { keepHeldAfter = k })
heard := make(chan struct{})
thinkingOn(t, "a", anthropicThoughtThenRefused, heard)
b := &scripted{replies: []reply{{200, "text/event-stream", anthropicAnswer}}}
scriptedOn(t, "b", provider.Anthropic, b)
refusalGroup(t, "a/claude-opus-5-5", "b/m")
s := New()
code, body := ask(t, s, heard)
alive := strings.Index(body, ": keepalive")
if code != 200 || alive < 0 || !strings.Contains(body[alive:], "from b") || strings.Contains(body, "user wants") || strings.Contains(body, `"refusal"`) || b.n != 1 {
t.Fatalf("%d %q (b %d)", code, body, b.n)
}
if strings.Count(body, "event: message_start") != 1 {
t.Fatalf("one reply in the stream: %q", body)
}
r := lastRoute(s)
if len(r.Tries) != 2 || r.Tries[0].Fail != failRefused || r.Status != 200 {
t.Fatalf("tries: %+v", r.Tries)
}
// thinking that goes on to its answer comes through whole after them
fresh(t)
heard = make(chan struct{})
thinkingOn(t, "a", anthropicThoughtThenAnswered, heard)
scriptedOn(t, "b", provider.Anthropic, &scripted{replies: []reply{{200, "text/event-stream", anthropicAnswer}}})
refusalGroup(t, "a/claude-opus-5-5", "b/m")
code, body = ask(t, New(), heard)
alive = strings.Index(body, ": keepalive")
if code != 200 || alive < 0 || !strings.Contains(body[alive:], `"thinking":"hm"`) || !strings.Contains(body, "from a") || strings.Contains(body, "from b") {
t.Fatalf("answered: %d %q", code, body)
}
// refused with nobody left: the stream's error, as its 200 went out
fresh(t)
heard = make(chan struct{})
thinkingOn(t, "a", anthropicThoughtThenRefused, heard)
refusalGroup(t, "a/claude-opus-5-5")
code, body = ask(t, New(), heard)
if code != 200 || !strings.Contains(body, ": keepalive") || !strings.Contains(body, "event: error") || strings.Contains(body, "user wants") {
t.Fatalf("refused, nobody left: %d %q", code, body)
}
}
// A stream's last event written after the agent went away reached nobody:
// the reply isn't whole, and the request is recorded as canceled (499), not
// as a 200 done (#751, a Claude Code run stopped by Alma's timeout).
func TestClientGoneRecordedAsCanceled(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
h := newHoldWriter(httptest.NewRecorder(), false)
h.ctx = ctx
h.Header().Set("Content-Type", "text/event-stream")
h.Write([]byte(sse(`event: message_start` + "\n" + `data: {"type":"message_start","message":{"id":"m"}}`)))
cancel()
h.Write([]byte(sse(`event: message_stop` + "\n" + `data: {"type":"message_stop"}`)))
if h.ended {
t.Fatal("a stream ended after its agent left taken as whole")
}
// Claude Code's run stopped mid-reply, written to the holdWriter the
// gateway gives it: relay still ends the stream it was encoding
// (message_stop), which isn't the reply made whole
dir := fakeClaudeCalling(t)
s := New()
t.Cleanup(s.subscription.abortAll)
ctx, cancel = context.WithCancel(context.Background())
defer cancel()
go func() {
for deadline := time.Now().Add(3 * time.Second); time.Now().Before(deadline); time.Sleep(10 * time.Millisecond) {
b, _ := os.ReadFile(filepath.Join(dir, "hang.pid"))
if pid, _ := strconv.Atoi(strings.TrimSpace(string(b))); pid != 0 {
time.Sleep(200 * time.Millisecond) // its reply under way
break
}
}
cancel()
}()
rec := httptest.NewRecorder()
h = newHoldWriter(rec, false)
h.ctx = ctx
p := provider.Provider{ID: "claude", Account: &provider.Account{Agent: "claude", User: "u"}}
body := `{"model":"claude-sonnet-5","max_tokens":100,"stream":true,"messages":[{"role":"user","content":"hang on"}]}`
var u Usage
s.serveClaudeSubscription(h, httptest.NewRequest("POST", "/v1/messages", strings.NewReader(body)).WithContext(ctx), provider.Anthropic, p, "claude-sonnet-5", []byte(body), &u)
if !strings.Contains(rec.Body.String(), "thinking it over") || !strings.Contains(rec.Body.String(), "message_stop") {
t.Fatalf("the run's reply: %q", rec.Body.String())
}
if h.ended {
t.Fatal("a Claude Code run stopped as its agent left taken as a whole reply, recorded as a 200")
}
}