gateway tests: a Chat client's reply translated from Anthropic's Messages streams as the vendor sends it — the first chunk when its first event comes, each word as it is written, never the whole reply held to the stream's end — and now a test holds it to that. A reporter's OpenAI-format client on Z.ai's GLM saw the opposite for a while (every event of a reply in one burst once the stream ended, while the same provider's Messages replies streamed fine), and it measured out to be the vendor's doing, not the gateway's: the reporter's own request bodies, replayed at full size against the vendor's chat and Messages endpoints through the gateway's build and beside it, streamed both ways on the day. Nothing locked the translation's pacing, though, so a future hold would read as the vendor's again. TestChatFromAnthropicStreamsAsItComes paces a Messages upstream at 200ms a word — glm-5.3 at an Anthropic-only provider, and a Claude model where Chat and Anthropic URLs both sit, which the Messages redirect takes there anyway — and wants the client's first chunk before the upstream has written its last word (relative to the upstream, not the wall clock, so a loaded runner's setup time is not held against it), at least two of the five pauses reaching it, and one ask on /v1/messages; holding every event of the chat encoder until finish (as the report read) fails it on both branches with the first chunk at the stream's end. And the keepalive table that walks every protocol's quiet stream (TestQuietStreamsKeptAliveEveryProtocol) had responses, anthropic, chat and anthropic from chat; chat from anthropic, the path a chat client on a Messages-only provider takes, was the row missing, and it keeps alive the same as the rest. go test -race -count=2 on the two tests, go vet and the nogui build pass. (#1310)
This commit is contained in:
@@ -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())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -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) {
|
||||
|
||||
Reference in New Issue
Block a user