Files
magpie/internal/gateway/nettrace_test.go
T
yetone f5dd4e1423 routing: a try a plugin or Claude Code sent says why it has no time split
"Where the time went" needs magpie's own client to send the request
(TryNet). A plugin sends its own through the plugin host, and a Claude
subscription's goes through Claude Code, so those tries never have a
split, and the page showed nothing in its place, which read as a
request that lost its details (Discord, lute).

A try now records who sent it when magpie didn't (Try.SentBy: "plugin"
or "claude", from sentBy), and the request's story says it under a
done, answered try with no timing: "Its plugin sent this request
itself, so magpie can't split its time" (or Claude Code), in every
language.

Run (mote, go1.26.8, Node 22, Playwright 1.62.0):
- TestPluginTrySaysWhoSentIt: red without the gateway.go line (SentBy
  empty), green with it. TestSentBy, TestTryTellsWhereItsTimeWent,
  TestCursorPlugin*: ok.
- go test ./internal/gateway ./internal/usage -count=1 -timeout 45m:
  ok (gateway 502s, usage 16s).
- node --test routing-time-went (now checks the plugin try's line and
  that a routed try has none), routing-masking, i18n-keys, routing-js,
  routing-time, routing-went-on, routing-steps-cap: 57 of 58 ok in
  Chromium and WebKit, every language. The red is
  routing-steps-cap's WebKit ResizeObserver error, red the same at
  8cbd0a9c9 without this change and listed in #4304.
- go vet for darwin, linux (-tags nogui), windows: ok. gofmt -l: clean.
Not tried: a real plugin or Claude subscription request in the app.

The three commits' full package runs were at base 8cbd0a9c9. Rebased
onto fb2e11e28 (#4308, which changed codex_backend.go), this head ran:
go vet ./internal/gateway for darwin, linux (-tags nogui), windows: ok;
go test ./internal/gateway -run 'TestCodex|TestMasking|TestNoMasking|
TestPluginTrySaysWhoSentIt|TestSentBy|TestTryTellsWhereItsTimeWent|
Revoked': ok.
2026-10-30 01:56:03 +08:00

122 lines
4.4 KiB
Go

package gateway
import (
"crypto/tls"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/yetone/magpie/internal/provider"
)
// heldHeaders holds each request for hold before its headers, as a vendor
// thinking before it answers, then streams a reply.
type heldHeaders struct{ hold time.Duration }
func (h heldHeaders) ServeHTTP(w http.ResponseWriter, r *http.Request) {
io.ReadAll(r.Body)
time.Sleep(h.hold)
w.Header().Set("Content-Type", "text/event-stream")
io.WriteString(w, chatStreamOK)
}
// A try says where its time went up to the reply's first byte (TryNet):
// a new connection's DNS, connect and TLS, writing the request, and the
// vendor's wait before its headers, which is where a vendor's slow start
// shows and not as magpie's (Discord, Magic_zero). The next request on
// the open connection spends none of the three. The route has the
// usage record's split of the time before the request went out.
func TestTryTellsWhereItsTimeWent(t *testing.T) {
fresh(t)
const hold = 300 * time.Millisecond
up := httptest.NewTLSServer(heldHeaders{hold: hold})
t.Cleanup(up.Close)
// by name, so the resolver is asked
base := strings.Replace(up.URL, "127.0.0.1", "localhost", 1) + "/v1"
if err := provider.Save(provider.Provider{ID: "a", Name: "A", Key: "k", Models: []string{"m"}, Chat: base}); err != nil {
t.Fatal(err)
}
s := New()
tr := &http.Transport{TLSClientConfig: &tls.Config{InsecureSkipVerify: true}}
t.Cleanup(tr.CloseIdleConnections)
s.client = &http.Client{Transport: tr}
ask := func() (Route, TryNet) {
t.Helper()
code, body := postAs(t, s, "", `{"model":"a/m","stream":true,"messages":[{"role":"user","content":"hi"}]}`)
if code != 200 || !strings.Contains(body, "from b") {
t.Fatalf("%d %s", code, body)
}
r := lastRoute(s)
if len(r.Tries) != 1 || r.Tries[0].Net == nil {
t.Fatalf("no timing: %+v", r.Tries)
}
return r, *r.Tries[0].Net
}
r, n := ask()
t.Logf("a new connection: %+v", n)
// the vendor's wait is the hold, give or take the machine
holdMs := float64(hold.Milliseconds())
if n.Wait < holdMs-1 || n.Wait > holdMs+5000 {
t.Fatalf("wait %v for a %v hold: %+v", n.Wait, hold, n)
}
if n.Reused || n.TLS <= 0 || n.Asks != 1 || n.Before != 0 {
t.Fatalf("a new connection: %+v", n)
}
// each step is in the time to the first byte, in order
if sum := n.Own + n.Pool + n.DNS + n.Connect + n.TLS + n.Send + n.Wait; sum > n.Head+1 {
t.Fatalf("steps %v over the %v to the first byte: %+v", sum, n.Head, n)
}
if try := r.Tries[0]; float64(try.TTFT) < n.Head-1 || float64(try.Millis) < n.Head-1 {
t.Fatalf("first byte %v after the first token %d or the end %d", n.Head, try.TTFT, try.Millis)
}
if r.Sent <= 0 || r.Own <= 0 || r.Sent > r.TTFT || r.Own > r.Sent {
t.Fatalf("route: sent %d own %d ttft %d", r.Sent, r.Own, r.TTFT)
}
// the open connection carries the next one
_, n = ask()
if !n.Reused || n.DNS != 0 || n.Connect != 0 || n.TLS != 0 || n.Wait < holdMs-1 {
t.Fatalf("the open connection: %+v", n)
}
}
// A try that sent nothing through Go's client (a plugin's own fetch) has
// no timing, rather than one made of nothing.
func TestTryNetWithoutARequest(t *testing.T) {
var n netTrace
if got := n.timing(time.Now(), 0); got != nil {
t.Fatalf("%+v", got)
}
}
// lute on Discord: some requests on the Routing page said where their
// time went and some didn't. A plugin sends its request itself, through
// its host, so magpie has no timing for it: its try says who sent it,
// which the page shows in the timing's place.
func TestPluginTrySaysWhoSentIt(t *testing.T) {
pid := besideFake(t, "cursor", &cursorUp{})
r := postProto(t, New(), "/v1/chat/completions", `{"model":"`+pid+`/fake-1","messages":[{"role":"user","content":"hi"}]}`)
if len(r.Tries) != 1 || r.Tries[0].Net != nil || r.Tries[0].SentBy != "plugin" {
t.Fatalf("tries %+v", r.Tries)
}
}
// Who sent a try: a plugin, Claude Code for a Claude subscription, and
// magpie itself, whose try has its timing, for the rest.
func TestSentBy(t *testing.T) {
for _, c := range []struct {
p provider.Provider
want string
}{
{provider.Provider{ID: "claude", Account: &provider.Account{Agent: "claude", User: "u"}}, "claude"},
{provider.Provider{ID: "codex", Account: &provider.Account{Agent: "codex", User: "u"}}, ""},
{provider.Provider{ID: "a"}, ""},
} {
if got := sentBy(c.p); got != c.want {
t.Errorf("sentBy(%s) = %q, want %q", c.p.ID, got, c.want)
}
}
}