From b6e82c6c5cebafd6ce96b8b9e76a6a6beefbcb14 Mon Sep 17 00:00:00 2001 From: july_lu Date: Wed, 14 Oct 2026 15:28:27 +0800 Subject: [PATCH] =?UTF-8?q?gateway=20tests:=20a=20Chat=20client's=20reply?= =?UTF-8?q?=20translated=20from=20Anthropic's=20Messages=20streams=20as=20?= =?UTF-8?q?the=20vendor=20sends=20it=20=E2=80=94=20the=20first=20chunk=20w?= =?UTF-8?q?hen=20its=20first=20event=20comes,=20each=20word=20as=20it=20is?= =?UTF-8?q?=20written,=20never=20the=20whole=20reply=20held=20to=20the=20s?= =?UTF-8?q?tream's=20end=20=E2=80=94=20and=20now=20a=20test=20holds=20it?= =?UTF-8?q?=20to=20that.=20A=20reporter's=20OpenAI-format=20client=20on=20?= =?UTF-8?q?Z.ai's=20GLM=20saw=20the=20opposite=20for=20a=20while=20(every?= =?UTF-8?q?=20event=20of=20a=20reply=20in=20one=20burst=20once=20the=20str?= =?UTF-8?q?eam=20ended,=20while=20the=20same=20provider's=20Messages=20rep?= =?UTF-8?q?lies=20streamed=20fine),=20and=20it=20measured=20out=20to=20be?= =?UTF-8?q?=20the=20vendor's=20doing,=20not=20the=20gateway's:=20the=20rep?= =?UTF-8?q?orter's=20own=20request=20bodies,=20replayed=20at=20full=20size?= =?UTF-8?q?=20against=20the=20vendor's=20chat=20and=20Messages=20endpoints?= =?UTF-8?q?=20through=20the=20gateway's=20build=20and=20beside=20it,=20str?= =?UTF-8?q?eamed=20both=20ways=20on=20the=20day.=20Nothing=20locked=20the?= =?UTF-8?q?=20translation's=20pacing,=20though,=20so=20a=20future=20hold?= =?UTF-8?q?=20would=20read=20as=20the=20vendor's=20again.=20TestChatFromAn?= =?UTF-8?q?thropicStreamsAsItComes=20paces=20a=20Messages=20upstream=20at?= =?UTF-8?q?=20200ms=20a=20word=20=E2=80=94=20glm-5.3=20at=20an=20Anthropic?= =?UTF-8?q?-only=20provider,=20and=20a=20Claude=20model=20where=20Chat=20a?= =?UTF-8?q?nd=20Anthropic=20URLs=20both=20sit,=20which=20the=20Messages=20?= =?UTF-8?q?redirect=20takes=20there=20anyway=20=E2=80=94=20and=20wants=20t?= =?UTF-8?q?he=20client's=20first=20chunk=20before=20the=20upstream=20has?= =?UTF-8?q?=20written=20its=20last=20word=20(relative=20to=20the=20upstrea?= =?UTF-8?q?m,=20not=20the=20wall=20clock,=20so=20a=20loaded=20runner's=20s?= =?UTF-8?q?etup=20time=20is=20not=20held=20against=20it),=20at=20least=20t?= =?UTF-8?q?wo=20of=20the=20five=20pauses=20reaching=20it,=20and=20one=20as?= =?UTF-8?q?k=20on=20/v1/messages;=20holding=20every=20event=20of=20the=20c?= =?UTF-8?q?hat=20encoder=20until=20finish=20(as=20the=20report=20read)=20f?= =?UTF-8?q?ails=20it=20on=20both=20branches=20with=20the=20first=20chunk?= =?UTF-8?q?=20at=20the=20stream's=20end.=20And=20the=20keepalive=20table?= =?UTF-8?q?=20that=20walks=20every=20protocol's=20quiet=20stream=20(TestQu?= =?UTF-8?q?ietStreamsKeptAliveEveryProtocol)=20had=20responses,=20anthropi?= =?UTF-8?q?c,=20chat=20and=20anthropic=20from=20chat;=20chat=20from=20anth?= =?UTF-8?q?ropic,=20the=20path=20a=20chat=20client=20on=20a=20Messages-onl?= =?UTF-8?q?y=20provider=20takes,=20was=20the=20row=20missing,=20and=20it?= =?UTF-8?q?=20keeps=20alive=20the=20same=20as=20the=20rest.=20go=20test=20?= =?UTF-8?q?-race=20-count=3D2=20on=20the=20two=20tests,=20go=20vet=20and?= =?UTF-8?q?=20the=20nogui=20build=20pass.=20(#1310)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- internal/gateway/chat_from_anthropic_test.go | 155 +++++++++++++++++++ internal/gateway/quiet_keepalive_test.go | 2 + 2 files changed, 157 insertions(+) create mode 100644 internal/gateway/chat_from_anthropic_test.go diff --git a/internal/gateway/chat_from_anthropic_test.go b/internal/gateway/chat_from_anthropic_test.go new file mode 100644 index 000000000..75d0cb6b9 --- /dev/null +++ b/internal/gateway/chat_from_anthropic_test.go @@ -0,0 +1,155 @@ +package gateway + +import ( + "bufio" + "io" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + "time" + + "github.com/yetone/magpie/internal/provider" +) + +// pacedMessages is an Anthropic Messages upstream that says its reply's +// first event at once, then a word every pace, for the client to be seen +// reading as they come rather than at the reply's end. It notes when its +// first bytes went out and each path it was asked on. +type pacedMessages struct { + pace time.Duration + mu sync.Mutex + paths []string + first time.Time // when the first event was written, zero until then + last time.Time // when the last word was written, zero until then + n int // requests answered +} + +func (p *pacedMessages) ServeHTTP(w http.ResponseWriter, r *http.Request) { + p.mu.Lock() + p.paths = append(p.paths, r.URL.Path) + p.n++ + p.mu.Unlock() + w.Header().Set("Content-Type", "text/event-stream") + w.WriteHeader(200) + io.WriteString(w, "event: message_start\ndata: {\"type\":\"message_start\",\"message\":{\"id\":\"m1\",\"type\":\"message\",\"role\":\"assistant\",\"model\":\"m\",\"content\":[],\"usage\":{\"input_tokens\":1,\"output_tokens\":0}}}\n\n"+ + "event: content_block_start\ndata: {\"type\":\"content_block_start\",\"index\":0,\"content_block\":{\"type\":\"text\",\"text\":\"\"}}\n\n") + w.(http.Flusher).Flush() + p.mu.Lock() + if p.first.IsZero() { + p.first = time.Now() + } + p.mu.Unlock() + for _, s := range []string{"counting ", "the ", "moments ", "as ", "they ", "come"} { + select { + case <-r.Context().Done(): + return + case <-time.After(p.pace): + } + io.WriteString(w, "event: content_block_delta\ndata: {\"type\":\"content_block_delta\",\"index\":0,\"delta\":{\"type\":\"text_delta\",\"text\":\""+s+"\"}}\n\n") + w.(http.Flusher).Flush() + p.mu.Lock() + p.last = time.Now() + p.mu.Unlock() + } + io.WriteString(w, "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\":6}}\n\n"+ + "event: message_stop\ndata: {\"type\":\"message_stop\"}\n\n") + w.(http.Flusher).Flush() +} + +// A Chat client's reply translated from Anthropic's Messages must stream +// as the upstream sends it: its first chunk reaches the client as the +// upstream's first event does, and the words that follow as they are +// written, not the whole reply at its end. A reporter's OpenAI-format +// client on Z.ai's GLM saw exactly that — every event of a reply in one +// burst once the stream ended (measured out to be the vendor's, not the +// gateway's, but the translation's pacing is worth a lock either way), +// while the same upstream's Messages replies streamed fine, so both a +// vendor's model (GLM) and a Claude model, which goes to Messages from +// Chat wherever its provider has that URL, are paced here. +func TestChatFromAnthropicStreamsAsItComes(t *testing.T) { + for _, c := range []struct { + name string + model string + withChat bool // a Chat URL beside the Anthropic one: the Claude model still goes to Messages + }{ + {"glm", "glm-5.3", false}, + {"claude", "claude-sonnet-4-6", true}, + } { + t.Run(c.name, func(t *testing.T) { + fresh(t) + pace := 200 * time.Millisecond + up := &pacedMessages{pace: pace} + srv := httptest.NewServer(up) + t.Cleanup(srv.Close) + p := provider.Provider{ID: "z", Name: "Z", Key: "k", Models: []string{c.model}, Anthropic: srv.URL} + if c.withChat { + p.Chat = srv.URL + "/v1" + } + if err := provider.Save(p); err != nil { + t.Fatal(err) + } + 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":"z/`+c.model+`","stream":true,"messages":[{"role":"user","content":"hi"}]}`)) + if err != nil { + t.Fatal(err) + } + defer resp.Body.Close() + if resp.StatusCode != 200 { + b, _ := io.ReadAll(resp.Body) + t.Fatalf("%d %s", resp.StatusCode, b) + } + var events []time.Duration // when each data line reached the client + var body strings.Builder + rd := bufio.NewReader(resp.Body) + for { + line, err := rd.ReadString('\n') + if strings.HasPrefix(line, "data:") { + events = append(events, time.Since(began)) + } + body.WriteString(line) + if err != nil { + break + } + } + if len(events) == 0 { + t.Fatalf("no events: %s", body.String()) + } + up.mu.Lock() + paths, lastWord, n := append([]string(nil), up.paths...), up.last, up.n + up.mu.Unlock() + if n != 1 || len(paths) != 1 || paths[0] != "/v1/messages" { + t.Fatalf("asked %v (of %d requests), want one on /v1/messages", paths, n) + } + total := events[len(events)-1] + firstChunk := events[0] + // relative to the upstream, not the wall clock: the client's first + // chunk is before the upstream wrote its last word — a held reply + // only arrives once the last word is out + if lastWord.Sub(began) <= 0 || firstChunk > lastWord.Sub(began) { + t.Fatalf("the client's first chunk came at %v, after the upstream's last word at %v — the reply was held: %s", firstChunk, lastWord.Sub(began), body.String()) + } + if total < 4*pace { + t.Fatalf("the stream ran %v, under its four pauses: %s", total, body.String()) + } + gaps := 0 + for i := 1; i < len(events); i++ { + if events[i]-events[i-1] > 120*time.Millisecond { + gaps++ + } + } + if gaps < 2 { + t.Fatalf("%d of the five 200ms pauses reached the client: %s", gaps, body.String()) + } + if !strings.Contains(body.String(), `"counting "`) || !strings.Contains(body.String(), `"come"`) || !strings.Contains(body.String(), "[DONE]") { + t.Fatalf("the reply didn't arrive whole: %s", body.String()) + } + }) + } +} diff --git a/internal/gateway/quiet_keepalive_test.go b/internal/gateway/quiet_keepalive_test.go index ef274f116..5ccd6b2e9 100644 --- a/internal/gateway/quiet_keepalive_test.go +++ b/internal/gateway/quiet_keepalive_test.go @@ -241,6 +241,8 @@ func TestQuietStreamsKeptAliveEveryProtocol(t *testing.T) { func(string) string { return chatRole }, chatText, func(string) string { return chatEnd }}, {"anthropic from chat", "/v1/messages", `{"model":"q/m","stream":true,"max_tokens":100,"messages":[{"role":"user","content":"hi"}]}`, provider.Chat, func(string) string { return chatRole }, chatText, func(string) string { return chatEnd }}, + {"chat from anthropic", "/v1/chat/completions", `{"model":"q/m","stream":true,"messages":[{"role":"user","content":"hi"}]}`, provider.Anthropic, + func(string) string { return anthropicStart + anthropicBlock }, anthropicText, func(string) string { return anthropicEnd }}, } { for _, mid := range []bool{false, true} { t.Run(c.name+map[bool]string{false: " held", true: " mid-reply"}[mid], func(t *testing.T) {