gateway: a relayed stream cut mid-line sends no half event ahead of its error (#2580)

A passthrough stream the upstream reset inside an event (YonQua: Z.ai's
glm-5.3 under pi) sent the half event's data line on to the client, and
pi's SSE parser died on its JSON ("malformed server-sent event JSON")
before it reached the error event magpie appended after it (#2446 put
that event on its own line; the half line ahead of it was still there).

passthrough's write now holds a stream's last unended line back until
its rest arrives; only lines that ended go out as they come. A reply
that ends whole puts the held line out as it came. When a failure is
appended (streamFailure, or the finish_reason filled in for Gemini's
OpenAI-compatible API) the held line is dropped first, unless its data
parses (whole JSON, or [DONE]): that one is no half event and goes out
before the failure, as on main. A non-stream reply is written unheld.

Changes made to gua2100's patch (ggbdpq/magpie hunt/2580-midstream-reset
30288fe28), both regressions it brought, each red with the patch as
posted:
- a gathered stream (a plugin's Responses account asked for one body,
  plugins#112) returned before the held line was put out, so a stream
  whose response.completed had no newline after it became a 502 "ended
  before it was complete": TestGrokPluginNonStreamLastLineUnended.
- a reset after an event's JSON was whole but before its newline dropped
  that whole event, which main delivers:
  TestChatStreamCutAfterWholeEventKeepsIt.

Tests: TestChatStreamCutMidLineLeavesNoHalfEvent (gua2100's; severed
gained a Chat shape) red on origin/main 5c1ccec4a's gateway.go:
"passthrough_severed_test.go:190: a half event the upstream never ended
went to the client as data". The two above pass on main and fail on the
posted patch. Broken by hand: dropHalf's parse check made always true
(every half line kept), TestChatStreamCutMidLineLeavesNoHalfEvent red
again; restored, green.

Run at this head (rebased on 82ff88933), on mote: go test -tags nogui
-count=1 -run for the new tests and their neighbours
(TestChatStreamCut*, TestGrokPlugin*, TestPassthroughStream*,
TestPassthroughResponses*, TestLoopCutMidLine, TestGeminiCompat*,
TestTranslate*SeveredUpstream, TestStreamCut*, TestGeminiRelayEndedShort,
TestGatheredTextOnlyStream, TestPluginStreamLargeReplies, TestKeepalive*,
TestRequestBodyProgressRenewsIdleDeadline, and #1475's TestNameless* and
TestWhole* beside it) ok (27.6s); gofmt -l clean. At the review tree
(5c1ccec4a): go vet -tags nogui ./internal/gateway on darwin,
GOOS=linux, GOOS=windows clean. Not run before the push: the whole
gateway package and ./... (the package runs in the background after).

Not tried: a real Z.ai stream reset mid-line, a real pi client; a
translated route (the translators read events with readSSE and write
whole events of their own, so they don't forward a half line).

Co-authored-by: ggbdpq <ggbdpq@gmail.com>
This commit is contained in:
yetone
2026-10-31 09:34:29 +08:00
co-authored by ggbdpq
parent 82ff889338
commit df1c3dace3
6 changed files with 157 additions and 14 deletions
File diff suppressed because one or more lines are too long
+64 -7
View File
@@ -5478,11 +5478,56 @@ func (s *Server) passthrough(w http.ResponseWriter, r *http.Request, p provider.
// client reads one event it can't parse where the protocol's error was
// meant (TestPassthroughStreamCutMidLine)
atLine := true
// pending is the line the upstream has begun but not ended: a stream
// read stops there on a failure, and what of it went out already is
// data the client's SSE parser dies on — a half event's JSON doesn't
// parse — so the error event appended after it is never reached
// (#2580: a stream Z.ai reset mid-line reached pi as "malformed
// server-sent event JSON"). Only lines that ended go out as they
// come; the half line waits for its rest, unheld puts it out when
// the reply ends whole, and dropHalf throws it away when the failure
// is appended, for no client can read it and the error is what there
// is left to say
var pending []byte
write := func(b []byte) (int, error) {
if len(b) > 0 {
atLine = b[len(b)-1] == '\n'
if !sse {
if len(b) > 0 {
atLine = b[len(b)-1] == '\n'
}
return w.Write(b)
}
return w.Write(b)
pending = append(pending, b...)
i := bytes.LastIndexByte(pending, '\n')
var err error
if i >= 0 {
_, err = w.Write(pending[:i+1])
pending = pending[i+1:]
atLine = true
}
return len(b), err
}
// unheld puts out the half line a whole reply ended inside: it goes
// as it came, as a stream the upstream itself ended short
unheld := func() {
if len(pending) > 0 {
w.Write(pending)
pending = nil
}
}
// dropHalf throws the line still pending away, unless it is a whole
// event's data the upstream stopped short of ending (its JSON parses,
// or [DONE]): that one is no half event, and goes out as before, with
// apart putting the blank line after it
dropHalf := func() {
if l := bytes.TrimSpace(pending); bytes.HasPrefix(l, []byte("data:")) {
if d := bytes.TrimSpace(l[5:]); string(d) == "[DONE]" || json.Valid(d) {
unheld()
atLine = false
return
}
}
pending = pending[:0]
atLine = true
}
// apart is what goes before an event magpie appends: a blank line,
// after the line still pending if the upstream's last write stopped
@@ -5619,6 +5664,10 @@ func (s *Server) passthrough(w http.ResponseWriter, r *http.Request, p provider.
sniff.settleWhole()
}
if gather != nil {
// the gathered stream is read here, not by the client: it gets
// every byte, a last line the upstream never ended included, as
// readSSE reads an event that ends with the body
unheld()
cut := ""
if rerr != nil && rerr != io.EOF {
cut = cutMidReply(p.Name, rerr)
@@ -5631,7 +5680,10 @@ func (s *Server) passthrough(w http.ResponseWriter, r *http.Request, p provider.
unfinished := proto == provider.Chat && sniff.failed == "" && sniff.u.Stop == "" && saysItsEnd(p, proto, upstream)
if fin := sniff.tail.finish(); sse && unfinished && fin != "" && (rerr == nil || rerr == io.EOF) && r.Context().Err() == nil {
// only the finish_reason was lost, after the generation was done
// (chatTail): the client gets it, and the reply is whole
// (chatTail): the client gets it, and the reply is whole. The
// event the upstream began and never ended has no rest coming:
// dropped when it is nothing a client can parse (dropHalf)
dropHalf()
w.Write(append(apart(), "data: "+string(finishChunk(fin))+"\n\n"...))
if !sniff.ended {
w.Write([]byte("data: [DONE]\n\n"))
@@ -5657,9 +5709,11 @@ func (s *Server) passthrough(w http.ResponseWriter, r *http.Request, p provider.
failed = p.Name + ": " + errEndedShort.Error()
}
if failed != "" {
// what is appended begins after a blank line: the event still
// pending is left to stand, and the failure is read as an
// event of its own (TestPassthroughStreamEndsOnLineEnd)
// what is appended begins after a blank line, as an event of
// its own (TestPassthroughStreamEndsOnLineEnd); the half
// event the upstream left is dropped (#2580): a client
// reading it dies on its JSON before the error is reached
dropHalf()
w.Write(append(apart(), streamFailure(proto, failed)...))
if f != nil {
f.Flush()
@@ -5667,6 +5721,9 @@ func (s *Server) passthrough(w http.ResponseWriter, r *http.Request, p provider.
return res.StatusCode, failed, true
}
}
if sse {
unheld()
}
return res.StatusCode, sniff.failed, true
}
+61 -1
View File
@@ -5,6 +5,8 @@ import (
"net/http/httptest"
"strings"
"testing"
"github.com/yetone/magpie/internal/provider"
)
// postMessages sends an Anthropic Messages request to the gateway, as dsh's
@@ -24,7 +26,7 @@ func postMessages(t *testing.T, body string) (int, string) {
// retry and which says nothing of what went wrong (#370).
func TestPassthroughStreamSeveredUpstream(t *testing.T) {
fresh(t)
severed(t, anthropicStart, anthropicText)
severed(t, provider.Anthropic, anthropicStart, anthropicText)
code, body := postMessages(t, `{"model":"up/m","stream":true,"max_tokens":8,"messages":[{"role":"user","content":"hi"}]}`)
if code != 200 {
t.Fatalf("status = %d, want 200; body: %s", code, body)
@@ -165,3 +167,61 @@ func TestPassthroughResponsesBigLastEvent(t *testing.T) {
t.Fatalf("a whole stream with a big last event was changed: %d, %d bytes added", code, len(body)-len(reply))
}
}
// The upstream reset inside an event (#2580: Z.ai cut a glm-5.3 stream
// mid-line under pi): the half event went to the client as data, and the
// client's SSE parser died reading it — "malformed server-sent event
// JSON" — so the error event magpie appended after it was never reached,
// and the turn failed without a word of what went wrong. A line the
// upstream never ended is no event of its own: the client reads the
// events that were whole and then the error, nothing it has to fail on.
func TestChatStreamCutMidLineLeavesNoHalfEvent(t *testing.T) {
fresh(t)
severed(t, provider.Chat, sse(chatThink("glm-5.3", "thinking")),
`data: {"id":"c1","model":"glm-5.3","choices":[{"index":0,"delta":{"reasoning_content":"the VM program itself hit an undefined`)
code, body := post(t, "/v1/chat/completions", `{"model":"up/m","stream":true,"messages":[{"role":"user","content":"hi"}]}`)
if code != 200 {
t.Fatalf("status = %d, want 200; body: %s", code, body)
}
if !strings.Contains(body, "connection lost mid-reply") {
t.Fatalf("a cut Chat stream ended without the error event: %s", body)
}
if strings.Contains(body, "undefined") {
t.Fatalf("a half event the upstream never ended went to the client as data: %s", body[max(0, len(body)-300):])
}
// every event the client reads parses, the error included: the
// stream is one a strict SSE reader goes through to the end of
readSSE(strings.NewReader(body), func(_, data string) error {
if data != "[DONE]" && !json.Valid([]byte(data)) {
t.Errorf("an event the client reads is no JSON: %q", data)
}
return nil
})
}
// A reset that comes after an event's JSON is whole but before the line
// ends leaves no half event: that event parses, so it goes to the client
// as before, and the error after it is an event of its own. Only a line
// whose data doesn't parse is dropped (#2580).
func TestChatStreamCutAfterWholeEventKeepsIt(t *testing.T) {
fresh(t)
severed(t, provider.Chat, sse(chatThink("glm-5.3", "thinking")), `data: `+chatText("glm-5.3", "kept to the end"))
code, body := post(t, "/v1/chat/completions", `{"model":"up/m","stream":true,"messages":[{"role":"user","content":"hi"}]}`)
if code != 200 {
t.Fatalf("status = %d, want 200; body: %s", code, body)
}
if !strings.Contains(body, "connection lost mid-reply") {
t.Fatalf("a cut Chat stream ended without the error event: %s", body)
}
var got []string
readSSE(strings.NewReader(body), func(_, data string) error {
if data != "[DONE]" && !json.Valid([]byte(data)) {
t.Errorf("an event the client reads is no JSON: %q", data)
}
got = append(got, data)
return nil
})
if !strings.Contains(strings.Join(got, "\n"), "kept to the end") {
t.Fatalf("the last whole event was dropped: %q", body)
}
}
@@ -323,6 +323,26 @@ func TestGrokPluginNonStreamEndedShort(t *testing.T) {
}
}
// A gathered stream whose last line the upstream never ended, its
// response.completed with no newline after it, is still read whole: a
// relayed stream holds an unended line back from the client (#2580), but
// what is gathered is read here, every byte of it.
func TestGrokPluginNonStreamLastLineUnended(t *testing.T) {
done := `{"id":"r1","object":"response","status":"completed","model":"grok-4.7","output":[{"type":"message","id":"msg_1","role":"assistant","status":"completed","content":[{"type":"output_text","text":"Found it.","annotations":[]}]}],"usage":{"input_tokens":5,"output_tokens":3,"total_tokens":8}}`
pid := besideFake(t, "grok", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
io.ReadAll(r.Body)
w.Header().Set("Content-Type", "text/event-stream")
io.WriteString(w, sse(`event: response.created`+"\n"+`data: {"type":"response.created","response":{"id":"r1","object":"response","status":"in_progress","output":[]}}`)+
`event: response.completed`+"\n"+`data: {"type":"response.completed","response":`+done+`}`)
}))
body := `{"model":"` + pid + `/fake-resp","stream":false,"input":"hi"}`
rec := httptest.NewRecorder()
New().Handler().ServeHTTP(rec, httptest.NewRequest("POST", "/v1/responses", strings.NewReader(body)))
if rec.Code != 200 || !strings.Contains(rec.Body.String(), "Found it.") {
t.Fatalf("%d %s", rec.Code, rec.Body)
}
}
// A stream whose response.completed names no output, and which sent no
// output_item.done either, still gives the client the text it streamed.
func TestGatheredTextOnlyStream(t *testing.T) {
+1 -1
View File
@@ -41,7 +41,7 @@ func TestStreamCutSaysConnection(t *testing.T) {
if err := provider.Save(provider.Provider{ID: "go", Name: "OpenCode Go", Key: "k", Models: []string{"m"}, Chat: up.URL + "/v1"}); err != nil {
t.Fatal(err)
}
severed(t, anthropicStart, anthropicText) // up/m, spoken to in Messages: the reply translated
severed(t, provider.Anthropic, anthropicStart, anthropicText) // up/m, spoken to in Messages: the reply translated
cases := []struct{ model, name string }{{"go/m", "OpenCode Go"}, {"up/m", "UP"}}
var wg sync.WaitGroup
+10 -4
View File
@@ -14,7 +14,7 @@ import (
// severed speaks HTTP until it doesn't: it writes headers that promise more
// body than it sends, delivers the events given, then closes the connection.
// The client's stream read fails the way an upstream dying mid-reply fails.
func severed(t *testing.T, events ...string) {
func severed(t *testing.T, proto provider.Protocol, events ...string) {
t.Helper()
up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
io.ReadAll(r.Body)
@@ -33,7 +33,13 @@ func severed(t *testing.T, events ...string) {
buf.Flush()
}))
t.Cleanup(up.Close)
p := provider.Provider{ID: "up", Name: "UP", Key: "k", Models: []string{"m"}, Anthropic: up.URL}
p := provider.Provider{ID: "up", Name: "UP", Key: "k", Models: []string{"m"}}
switch proto {
case provider.Chat:
p.Chat = up.URL + "/v1"
default:
p.Anthropic = up.URL
}
if err := provider.Save(p); err != nil {
t.Fatal(err)
}
@@ -54,7 +60,7 @@ const (
// upstream died, as if the reply were whole.
func TestTranslateBufferedSeveredUpstream(t *testing.T) {
fresh(t)
severed(t, anthropicStart, anthropicText)
severed(t, provider.Anthropic, anthropicStart, anthropicText)
code, body := postAs(t, New(), "", `{"model":"up/m","messages":[{"role":"user","content":"hi"}]}`)
if code != 502 {
t.Fatalf("status = %d, want 502; body: %s", code, body)
@@ -68,7 +74,7 @@ func TestTranslateBufferedSeveredUpstream(t *testing.T) {
// [DONE] - over a reply the upstream never finished.
func TestTranslateStreamSeveredUpstream(t *testing.T) {
fresh(t)
severed(t, anthropicStart, anthropicText)
severed(t, provider.Anthropic, anthropicStart, anthropicText)
code, body := postAs(t, New(), "", `{"model":"up/m","stream":true,"messages":[{"role":"user","content":"hi"}]}`)
if code != 200 {
t.Fatalf("status = %d, want 200; body: %s", code, body)