Files
magpie/internal/gateway/member_test.go
T
yetone 9bb1efdde3 gateway: a reply names the model the agent asked for when it went out under another name (issennknight)
issennknight on Discord (#general): an agent asked for deepseek-v4.1-flash,
which goes out as deepseek-v4.1-flash-1017 (settings' ModelIDs). The vendor's
reply said -1017, magpie passed it back, and the agent warned that the model
didn't match.

Before, only MemberModel (#822) or X-Magpie-Response-Model: member rewrote a
reply's model, and only to the group member's id. Now the default is
nameAsked. When magpie sent the request under another name than the agent
asked for (a model's own id, a routing group, a provider/model id), the
reply names the asked model. That covers Chat and Anthropic `model`,
Responses `response.model` (created, in_progress, completed), Anthropic
`message.model` (message_start) and Gemini `modelVersion`, streamed and
whole, translated paths and plugins included: it all goes through serve's
one memberWriter. A vendor that sent back the wire name as asked keeps its
own name, a dated -20261017 too. Usage rows, recent calls and the Routing
page still record served = the vendor's name: the writer sits outside
captureResponseWriter. Claude Code, Claude Desktop and Codex get the asked
name (or the vendor's), never the member's id, as before.

Streams are rewritten one complete line at a time (memberLines). A run
with no "model" in it is written through as the same slice. Only a JSON
reply that has a target at decide time is held whole, which is what
MemberModel already did.

A JSON body that doesn't parse (a reply cut short) goes on as it came.
A request to a remote magpie now sends X-Magpie-Response-Model: vendor
(passOnCaller). That magpie names the vendor's model, as before, so this
one still records what served the call (TestRemoteMagpieGroupNotSwapped
went red without it).

Existing tests that held a native reply byte for byte now expect only
its model renamed to the asked id (namedAs in member_test.go):
passthrough_severed, stream_accounting, refusal, refusal_thinking,
thinking_signature and vertex. The archive keeps the reply as the
vendor sent it, under the vendor's name (archive_test).

Also dropped: the openai-model header code. serve never relays that header,
so the test for it could not pass.

Run (mote, at this head rebased on origin/main 15066f84f):
- go test -tags nogui -count=1 -timeout 45m ./...: every package ok
  except internal/gui: TestSettingsSaveKeepsWhatItDoesNotSend (#4514,
  SearchAll from b09349d17) and TestColdTurnsTaken (#4510). Both are filed,
  and neither touches this change. Three other sessions' suites ran on
  mote at the same time.
  The first full run (base 80bcef18f) had internal/gateway red in 10
  tests: the byte-for-byte tests above, the remote-magpie served test and
  the truncated JSON body. Each one was fixed as described.
- Rebased on 544b91ca8 (no gateway files changed in between): go build ./...,
  go vet, then go test ./internal/gateway ./internal/settings
  ./internal/provider: all ok.
- go vet -tags nogui ./..., GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./...: clean (cgo warnings only); gofmt -l clean.
- go test -race -count=3 on the member and served tests: ok (122s).
- the 10 formerly red tests with TestReplyNames, TestGeminiReplyNames,
  TestMemberLine, TestMemberWriter and Masked, after the rebase: ok.

Red on the old code (the new tests over a git archive of the base):
- TestReplyNamesAskedModel: 36 subtests fail (own id, group and provider
  id, x 6 protocol paths, x streamed or not), e.g. `the reply names
  "deepseek-v4.1-flash-1017", want "deepseek-v4.1-flash"`.
- TestGeminiReplyNamesAskedModel: both subtests fail (modelVersion -1017).

Broken by hand: dropping `|| m.wire == m.asked` from target() fails
"as asked, dated" in 12 subtests.

Real use: Codex 0.165.0 (codex exec --json) under a sandbox HOME and
CODEX_HOME on mote. A fake Responses vendor always answered
deepseek-v4.1-flash-1017, and a tee between Codex and `magpie serve` logged
what Codex got. providers.json had d with deepseek-v4.1-flash and group
fast; settings.json had modelIDs d/deepseek-v4.1-flash ->
deepseek-v4.1-flash-1017.
- old build: the vendor was asked for -1017; Codex got "model":
  "deepseek-v4.1-flash-1017" in response.created, in_progress and completed,
  both for -m deepseek-v4.1-flash and for -m group/fast.
- new build: the vendor was still asked for -1017; Codex got
  "deepseek-v4.1-flash" and "group/fast"; the usage rows still say served
  deepseek-v4.1-flash-1017. Codex answered "pong" both times. Codex 0.165
  itself shows no warning for a body model either way (its "model
  rerouted" reads the openai-model header), so the agent behind the
  report's warning was not the one run.

Not tried: the reporter's own agent (not named) and Claude Code; the
Responses WebSocket path (responses_ws.go's own frames); a compressed
reply, which still goes through as it is; Antigravity's effort-variant
wire, where the wire differs from the asked name on purpose.
2026-11-01 04:51:17 +08:00

368 lines
14 KiB
Go

package gateway
import (
"bufio"
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"net/http/httptest"
"regexp"
"strings"
"sync"
"testing"
"github.com/tidwall/gjson"
"github.com/yetone/magpie/internal/provider"
"github.com/yetone/magpie/internal/settings"
)
// A reply from a group says which member answered it (#822): its
// X-Magpie-Provider and X-Magpie-Model headers always, relayed or
// translated, streamed or not, after a failover too; its body's model the
// group the agent asked for, unless MemberModel (or the request's
// X-Magpie-Response-Model: member) asks for magpie's provider/model id
// there — never for Claude Code or Codex, which read it themselves — or
// X-Magpie-Response-Model: vendor for the vendor's own name.
func TestReplyNamesMember(t *testing.T) {
bodies := map[string]string{
"/v1/messages": `{"model":"group/auto","max_tokens":100,"messages":[{"role":"user","content":"hi"}]`,
"/v1/chat/completions": `{"model":"group/auto","messages":[{"role":"user","content":"hi"}]`,
"/v1/responses": `{"model":"group/auto","input":"hi"`,
}
paths := []struct {
name string
proto provider.Protocol // the vendor's
agent string // the agent's endpoint
}{
{"anthropic", provider.Anthropic, "/v1/messages"},
{"chat", provider.Chat, "/v1/chat/completions"},
{"responses", provider.Responses, "/v1/responses"},
{"chat from anthropic", provider.Anthropic, "/v1/chat/completions"},
{"anthropic from chat", provider.Chat, "/v1/messages"},
{"responses from chat", provider.Chat, "/v1/responses"},
}
const served = "glm-5.3-flash-202606"
for _, pa := range paths {
for _, stream := range []bool{false, true} {
for _, c := range []struct {
name string
on bool // MemberModel
header string // X-Magpie-Response-Model
token string // the agent's key
want string // the model the body names
}{
{"default", false, "", "", "group/auto"},
{"on", true, "", "", "b/glm-5.3-flash"},
{"asked", false, "member", "", "b/glm-5.3-flash"},
{"on, vendor asked", true, "vendor", "", served},
{"vendor asked", false, "vendor", "", served},
{"on, codex", true, "", TokenFor("codex"), "group/auto"},
{"on, claude code", true, "", TokenFor("claude"), "group/auto"},
} {
name := pa.name + "/" + c.name
if stream {
name += "/stream"
}
t.Run(name, func(t *testing.T) {
fresh(t)
// a fails, so b answers after a failover
down := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.Error(w, `{"error":{"message":"overloaded"}}`, 529)
}))
t.Cleanup(down.Close)
up := httptest.NewServer(servedBy(pa.proto, served))
t.Cleanup(up.Close)
for _, p := range []provider.Provider{
{ID: "a", Name: "A", Key: "k", Models: []string{"glm-5.3-flash"}},
{ID: "b", Name: "B", Key: "k", Models: []string{"glm-5.3-flash"}},
} {
url := down.URL
if p.ID == "b" {
url = up.URL
}
switch pa.proto {
case provider.Chat:
p.Chat = url + "/v1"
case provider.Responses:
p.Responses = url + "/v1"
case provider.Anthropic:
p.Anthropic = url
}
if err := provider.Save(p); err != nil {
t.Fatal(err)
}
}
if err := provider.SaveGroup(provider.Group{Name: "auto", Routing: provider.Ordered, Members: []string{"a/glm-5.3-flash", "b/glm-5.3-flash"}}); err != nil {
t.Fatal(err)
}
if c.on {
if err := settings.Save(settings.Settings{MemberModel: true}); err != nil {
t.Fatal(err)
}
}
body := bodies[pa.agent]
if stream {
body += `,"stream":true`
}
req := httptest.NewRequest("POST", pa.agent, strings.NewReader(body+"}"))
if c.header != "" {
req.Header.Set(responseModelHeader, c.header)
}
if c.token != "" {
req.Header.Set("Authorization", "Bearer "+c.token)
}
rec := httptest.NewRecorder()
s := New()
s.Handler().ServeHTTP(rec, req)
if rec.Code != 200 || !strings.Contains(rec.Body.String(), "hi") {
t.Fatalf("%d %s", rec.Code, rec.Body)
}
if r := lastRoute(s); len(r.Tries) != 2 {
t.Fatalf("tries %+v", r.Tries)
}
if p, m := rec.Header().Get(providerHeader), rec.Header().Get(modelHeader); p != "b" || m != "b/glm-5.3-flash" {
t.Errorf("headers say %q %q", p, m)
}
want := c.want
names := modelsNamed(rec.Body.String(), stream)
if len(names) == 0 {
t.Fatalf("no model named in %s", rec.Body)
}
for _, n := range names {
if n != want {
t.Fatalf("the reply names %q, want %q:\n%s", n, want, rec.Body)
}
}
if r := lastRoute(s); r.Served != served {
t.Errorf("the route says %q served it, want the vendor's %q", r.Served, served)
}
})
}
}
}
}
// modelsNamed are the models a reply's body, or each of its events, names.
func modelsNamed(body string, stream bool) []string {
var datas []string
if !stream {
datas = []string{body}
} else {
sc := bufio.NewScanner(strings.NewReader(body))
sc.Buffer(nil, 1<<20)
for sc.Scan() {
if d, ok := strings.CutPrefix(sc.Text(), "data:"); ok {
datas = append(datas, strings.TrimSpace(d))
}
}
}
var out []string
for _, d := range datas {
for _, path := range memberPaths {
if v := gjson.Get(d, path); v.Type == gjson.String {
out = append(out, v.Str)
}
}
}
return out
}
// An event's model is put in place, the rest of the line as it was; a
// line that names none, or isn't JSON, is untouched.
func TestMemberLine(t *testing.T) {
for in, want := range map[string]string{
"data: {\"model\":\"glm\",\"x\":1}\n": "data: {\"model\":\"b/glm\",\"x\":1}\n",
"data:{\"message\":{\"model\":\"glm\"}}\r\n": "data:{\"message\":{\"model\":\"b/glm\"}}\r\n",
"data: {\"response\":{\"id\":\"r\",\"model\":\"glm\"}}": "data: {\"response\":{\"id\":\"r\",\"model\":\"b/glm\"}}",
"data: {\"modelVersion\":\"glm\"}\n": "data: {\"modelVersion\":\"b/glm\"}\n",
"data: [DONE]\n": "data: [DONE]\n",
"event: message_start\n": "event: message_start\n",
"data: {\"delta\":{\"text\":\"\\\"model\\\":\"}}\n": "data: {\"delta\":{\"text\":\"\\\"model\\\":\"}}\n",
} {
if got := string(memberLine([]byte(in), "b/glm")); got != want {
t.Errorf("%q: got %q, want %q", in, got, want)
}
}
}
// A reply names the model the agent asked for whenever the request went
// out under another name, since agents compare the two and warn when they
// differ (issennknight on Discord: deepseek-v4.1-flash, which the user
// lists by that id, went out as deepseek-v4.1-flash-1017 and came back
// so named): a model the user lists by an id of theirs, a group, a
// provider/model id. One that went out under the name asked for keeps
// the vendor's own text, its dated name. The route and the usage log
// keep the vendor's name either way.
func TestReplyNamesAskedModel(t *testing.T) {
paths := []struct {
name string
proto provider.Protocol // the vendor's
agent string // the agent's endpoint
}{
{"anthropic", provider.Anthropic, "/v1/messages"},
{"chat", provider.Chat, "/v1/chat/completions"},
{"responses", provider.Responses, "/v1/responses"},
{"chat from anthropic", provider.Anthropic, "/v1/chat/completions"},
{"anthropic from chat", provider.Chat, "/v1/messages"},
{"responses from chat", provider.Chat, "/v1/responses"},
}
cases := []struct {
name string
asked string
ids map[string]string // settings' ModelIDs
served string // what the vendor's reply says
header string // X-Magpie-Response-Model
want string
}{
{"own id", "deepseek-v4.1-flash", map[string]string{"d/deepseek-v4.1-flash": "deepseek-v4.1-flash-1017"}, "deepseek-v4.1-flash-1017", "", "deepseek-v4.1-flash"},
{"own id, vendor asked", "deepseek-v4.1-flash", map[string]string{"d/deepseek-v4.1-flash": "deepseek-v4.1-flash-1017"}, "deepseek-v4.1-flash-1017", "vendor", "deepseek-v4.1-flash-1017"},
{"group", "group/fast", nil, "deepseek-v4.1-flash-1017", "", "group/fast"},
{"provider id", "d/deepseek-v4.1-flash", nil, "deepseek-v4.1-flash", "", "d/deepseek-v4.1-flash"},
{"as asked, dated", "deepseek-v4.1-flash", nil, "deepseek-v4.1-flash-20261017", "", "deepseek-v4.1-flash-20261017"},
}
for _, pa := range paths {
for _, stream := range []bool{false, true} {
for _, c := range cases {
name := pa.name + "/" + c.name
if stream {
name += "/stream"
}
t.Run(name, func(t *testing.T) {
fresh(t)
var mu sync.Mutex
var sent []string // the models the vendor was asked for
serve := servedBy(pa.proto, c.served)
up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
b, _ := io.ReadAll(r.Body)
mu.Lock()
sent = append(sent, gjson.GetBytes(b, "model").Str)
mu.Unlock()
r.Body = io.NopCloser(bytes.NewReader(b))
serve(w, r)
}))
t.Cleanup(up.Close)
p := provider.Provider{ID: "d", Name: "D", Key: "k", Models: []string{"deepseek-v4.1-flash"}}
switch pa.proto {
case provider.Chat:
p.Chat = up.URL + "/v1"
case provider.Responses:
p.Responses = up.URL + "/v1"
case provider.Anthropic:
p.Anthropic = up.URL
}
if err := provider.Save(p); err != nil {
t.Fatal(err)
}
if err := provider.SaveGroup(provider.Group{Name: "fast", Routing: provider.Ordered, Members: []string{"d/deepseek-v4.1-flash"}}); err != nil {
t.Fatal(err)
}
if c.ids != nil {
if err := settings.Save(settings.Settings{ModelIDs: c.ids}); err != nil {
t.Fatal(err)
}
}
m, _ := json.Marshal(c.asked)
body := `{"model":` + string(m) + `,"max_tokens":100,"messages":[{"role":"user","content":"hi"}]`
if pa.agent == "/v1/responses" {
body = `{"model":` + string(m) + `,"input":"hi"`
}
if stream {
body += `,"stream":true`
}
req := httptest.NewRequest("POST", pa.agent, strings.NewReader(body+"}"))
if c.header != "" {
req.Header.Set(responseModelHeader, c.header)
}
rec := httptest.NewRecorder()
s := New()
s.Handler().ServeHTTP(rec, req)
if rec.Code != 200 || !strings.Contains(rec.Body.String(), "hi") {
t.Fatalf("%d %s", rec.Code, rec.Body)
}
mu.Lock()
t.Logf("sent as %v", sent)
mu.Unlock()
names := modelsNamed(rec.Body.String(), stream)
if len(names) == 0 {
t.Fatalf("no model named in %s", rec.Body)
}
for _, n := range names {
if n != c.want {
t.Fatalf("the reply names %q, want %q:\n%s", n, c.want, rec.Body)
}
}
if r := lastRoute(s); r.Served != c.served {
t.Errorf("the route says %q served it, want the vendor's %q", r.Served, c.served)
}
if calls := s.Recent(); len(calls) == 0 || calls[0].Usage.Served != c.served {
t.Errorf("the log says %+v served it, want the vendor's %q", calls, c.served)
}
})
}
}
}
}
// A Gemini agent asks in the URL, and the reply's modelVersion names that
// model when the request went out under another name.
func TestGeminiReplyNamesAskedModel(t *testing.T) {
for _, stream := range []bool{false, true} {
t.Run(fmt.Sprint("stream ", stream), func(t *testing.T) {
fresh(t)
up := httptest.NewServer(servedBy(provider.Chat, "deepseek-v4.1-flash-1017"))
t.Cleanup(up.Close)
if err := provider.Save(provider.Provider{ID: "d", Name: "D", Key: "k", Chat: up.URL + "/v1", Models: []string{"deepseek-v4.1-flash"}}); err != nil {
t.Fatal(err)
}
if err := settings.Save(settings.Settings{ModelIDs: map[string]string{"d/deepseek-v4.1-flash": "deepseek-v4.1-flash-1017"}}); err != nil {
t.Fatal(err)
}
path := "/v1beta/models/deepseek-v4.1-flash:generateContent"
if stream {
path = "/v1beta/models/deepseek-v4.1-flash:streamGenerateContent?alt=sse"
}
rec := httptest.NewRecorder()
New().Handler().ServeHTTP(rec, httptest.NewRequest("POST", path, strings.NewReader(`{"contents":[{"role":"user","parts":[{"text":"hi"}]}]}`)))
if rec.Code != 200 || !strings.Contains(rec.Body.String(), "hi") {
t.Fatalf("%d %s", rec.Code, rec.Body)
}
names := modelsNamed(rec.Body.String(), stream)
if len(names) == 0 {
t.Fatalf("no model named in %s", rec.Body)
}
for _, n := range names {
if n != "deepseek-v4.1-flash" {
t.Fatalf("the reply names %q:\n%s", n, rec.Body)
}
}
})
}
}
// A run of a stream's lines is named line by line, and a run that names
// no model, or a name of "", is the same slice back.
func TestMemberLines(t *testing.T) {
in := []byte("event: response.created\ndata: {\"response\":{\"model\":\"v\"}}\n\nevent: response.output_text.delta\ndata: {\"delta\":\"hi\"}\n\ndata: {\"model\":\"v\"}\n")
want := "event: response.created\ndata: {\"response\":{\"model\":\"asked\"}}\n\nevent: response.output_text.delta\ndata: {\"delta\":\"hi\"}\n\ndata: {\"model\":\"v\"}\n"
if got := string(memberLines(in, "asked", memberPathsOf(provider.Responses)[1:])); got != want {
t.Errorf("got %q, want %q", got, want)
}
plain := []byte("data: {\"delta\":\"hi\"}\n\n")
if got := memberLines(plain, "asked", memberPaths); &got[0] != &plain[0] {
t.Error("a run with no model was copied")
}
if got := memberLines(in, "", memberPaths); &got[0] != &in[0] {
t.Error("no name copied the run")
}
}
// namedAs is a reply as an agent that asked for asked gets it: every model
// it names is that one (memberWriter), the rest as the vendor wrote it.
func namedAs(reply, asked string) string {
return replyModels.ReplaceAllString(reply, `"$1"$2"`+asked+`"`)
}
var replyModels = regexp.MustCompile(`"(model|modelVersion)"(\s*:\s*)"[^"]*"`)