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>
114 lines
4.0 KiB
Go
114 lines
4.0 KiB
Go
package gateway
|
|
|
|
import (
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"strings"
|
|
"testing"
|
|
|
|
"github.com/yetone/magpie/internal/provider"
|
|
)
|
|
|
|
// 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, proto provider.Protocol, events ...string) {
|
|
t.Helper()
|
|
up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
io.ReadAll(r.Body)
|
|
hj, ok := w.(http.Hijacker)
|
|
if !ok {
|
|
panic("no hijacker")
|
|
}
|
|
conn, buf, err := hj.Hijack()
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
defer conn.Close()
|
|
body := strings.Join(events, "")
|
|
fmt.Fprintf(buf, "HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nContent-Length: %d\r\n\r\n", len(body)+100)
|
|
io.WriteString(buf, body)
|
|
buf.Flush()
|
|
}))
|
|
t.Cleanup(up.Close)
|
|
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)
|
|
}
|
|
}
|
|
|
|
const (
|
|
anthropicStart = "event: message_start\n" +
|
|
"data: {\"type\":\"message_start\",\"message\":{\"id\":\"msg_1\",\"model\":\"m\",\"usage\":{\"input_tokens\":3,\"output_tokens\":1}}}\n\n"
|
|
anthropicText = "event: content_block_delta\n" +
|
|
"data: {\"type\":\"content_block_delta\",\"index\":0,\"delta\":{\"type\":\"text_delta\",\"text\":\"hel\"}}\n\n"
|
|
anthropicStop = "event: message_delta\n" +
|
|
"data: {\"type\":\"message_delta\",\"delta\":{\"stop_reason\":\"end_turn\"},\"usage\":{\"output_tokens\":2}}\n\n" +
|
|
"event: message_stop\n" +
|
|
"data: {\"type\":\"message_stop\"}\n\n"
|
|
)
|
|
|
|
// A client waiting on one JSON answer was handed whatever arrived before the
|
|
// upstream died, as if the reply were whole.
|
|
func TestTranslateBufferedSeveredUpstream(t *testing.T) {
|
|
fresh(t)
|
|
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)
|
|
}
|
|
if !strings.Contains(body, "UP:") {
|
|
t.Fatalf("error does not name the provider: %s", body)
|
|
}
|
|
}
|
|
|
|
// A streaming client got a synthetic happy ending - finish reason, usage,
|
|
// [DONE] - over a reply the upstream never finished.
|
|
func TestTranslateStreamSeveredUpstream(t *testing.T) {
|
|
fresh(t)
|
|
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)
|
|
}
|
|
if !strings.Contains(body, `"error"`) {
|
|
t.Fatalf("no error event in the stream: %s", body)
|
|
}
|
|
if strings.Contains(body, "[DONE]") || strings.Contains(body, `"finish_reason":"stop"`) {
|
|
t.Fatalf("a severed stream was finished as if complete: %s", body)
|
|
}
|
|
}
|
|
|
|
// A stream the upstream finished properly still translates end to end,
|
|
// error-free and complete.
|
|
func TestTranslateStreamCompleteUpstream(t *testing.T) {
|
|
fresh(t)
|
|
up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
io.ReadAll(r.Body)
|
|
w.Header().Set("Content-Type", "text/event-stream")
|
|
io.WriteString(w, anthropicStart+anthropicText+anthropicStop)
|
|
}))
|
|
t.Cleanup(up.Close)
|
|
p := provider.Provider{ID: "up", Name: "UP", Key: "k", Models: []string{"m"}, Anthropic: up.URL}
|
|
if err := provider.Save(p); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
|
|
code, body := postAs(t, New(), "", `{"model":"up/m","stream":true,"messages":[{"role":"user","content":"hi"}]}`)
|
|
if code != 200 || !strings.Contains(body, "[DONE]") || strings.Contains(body, `"error"`) {
|
|
t.Fatalf("streamed: status %d; body: %s", code, body)
|
|
}
|
|
code, body = postAs(t, New(), "", `{"model":"up/m","messages":[{"role":"user","content":"hi"}]}`)
|
|
if code != 200 || !strings.Contains(body, `"hel"`) || strings.Contains(body, `"error"`) {
|
|
t.Fatalf("buffered: status %d; body: %s", code, body)
|
|
}
|
|
}
|