Files
magpie/internal/gateway/trace.go
T
yetone c816c9f828 routing: a request answered by another model than the one asked for is marked, from the model the vendor's reply names (v on Discord #feedback: 模型路由情况其实有的时候还是想知道的,比如之前 openai 会把 sol 降智到 luna 这样的,现在只有走 s2a 和 newapi 这些网关服务才能明确看到) — magpie read the tokens off each reply but not the model it says answered, so a vendor serving sol's requests with luna looked, on the Routing page, like sol answering. The reply's model is now kept as it goes by, never delayed or changed: on a relayed reply by the usage sniffer, which already reads every event and JSON body (Chat Completions' model in its JSON and each chunk, the Responses API's response.model in response.created/completed and model in its JSON, Anthropic's message.model in message_start and model in its JSON); on a translated one from the decoders' start event, which already carried it (Chat, Responses, Anthropic, and Gemini Code Assist's modelVersion), streamed or collected; on a Claude subscription's from the CLI's message_start; and on Codex's own models relayed to the ChatGPT backend. It goes in Usage.Served (and so the request log), each try's Served and the route's (the last try's, when it answered), with Swapped when it is another model than the one the try sent the vendor. Vendors mostly echo a dated or pinned name, which is the same model: the names are compared without a maker or path prefix (openai/, models/, Bedrock's us.anthropic.), case, and a version at the end — a date (-2025-08-07, -20250929, -06-05), a build number (-0613, -001), Bedrock's -v1:0, -latest, -preview — so gpt-5 answered as gpt-5-2025-08-07 or claude-3-5-sonnet-latest as claude-3-5-sonnet-20241022 is not marked, while gpt-5 as gpt-5-mini, gpt-5 as gpt-5.1, claude-opus-4 as claude-opus-4-1-… and deepseek-v3 as deepseek-v2 are. A reply that names no model marks nothing. The Routing page's Requests list puts an amber "served luna" (实际 luna) tag by the answer, its title saying what it means, and the request's story a line "requested sol · served luna" (请求 sol · 实际 luna) with the same sentence; no border stripe, and picking the request leaves the page where it is. Cursor, Devin, Kiro and Qoder name the model they were asked for themselves, so they are never marked.
Tested with new internal/gateway/served_test.go: TestServedModelRecorded (fake vendors in each protocol, streamed and not, relayed — Anthropic, Chat, Responses — and translated — Chat from Anthropic, Anthropic from Chat, Anthropic from Responses — each answering luna (marked), sol-2026-01-01 and models/SOL (not): the route, its try and the request log keep the name, Swapped as said), TestServedModelUnnamed, TestSwappedModel (the names above), TestSniffServedModel and TestCodexOwnModelServedTraced; and new internal/gui/tests/routing-served.test.cjs in Chromium and WebKit, en and zh (the tag on the swapped request alone, whole and in its row, no left border, its title; the story's line; a click that doesn't move the page; the dated and unnamed ones unmarked). With three requests alone the Routing page above the list jiggles by a few to 70px in WebKit on its own (on main too, with no served model in the fixture), so the fixture lists six. go build -tags nogui (and GOOS=linux, GOOS=windows), go test -tags nogui ./... and all GUI tests (80) pass. Not tested against a real vendor serving another model.
2026-09-29 19:41:29 +08:00

366 lines
13 KiB
Go

package gateway
// The routing trace: what routing did with each request, as it did it, for
// the Gateway view to play back. Every account or key in the order it was
// weighed and what put it there — the share of its allowance used and when
// that renews, the tokens it served lately, whose turn it was, why it
// rests — then each try, what it answered, and how long one that failed
// now sits out. It's recorded where the decisions are made, from the same
// values they are made with; nothing is worked out again afterwards.
import (
"context"
"regexp"
"strings"
"sync"
"time"
"github.com/yetone/magpie/internal/provider"
)
// traceKeep is how many requests the trace keeps.
const traceKeep = 60
// Route is one request's way through routing.
type Route struct {
Seq int64 `json:"seq"` // the trace's count when it last changed
ID int64 `json:"id"`
Time time.Time `json:"time"`
Agent string `json:"agent"`
Kind string `json:"kind,omitempty"` // what the call is for, as Call's
Model string `json:"model"` // as the agent asked
Effort string `json:"effort,omitempty"` // the reasoning the agent asked for; "" for none
Provider string `json:"provider"` // the provider the model resolved to
Group *GroupRef `json:"group,omitempty"` // the routing group the agent asked for
Rule *RuleHit `json:"rule,omitempty"` // the group's rules for it, when it has any
// Nested: the rules of the groups in the group, down the way to the
// one that went first, each as it decided
Nested []NestedRule `json:"nested,omitempty"`
Affinity *Affinity `json:"affinity,omitempty"` // its conversation, and whether it stayed put
Order []Weighed `json:"order"` // who was to try it, first first
Left []Weighed `json:"left,omitempty"`
Tries []Try `json:"tries"`
Done bool `json:"done"`
Status int `json:"status,omitempty"`
Error string `json:"error,omitempty"`
Millis int64 `json:"ms,omitempty"`
Tokens int `json:"tokens,omitempty"`
Output int `json:"out,omitempty"` // of Tokens, the reply's
// TTFT: ms from the request to its reply's first content (text,
// reasoning or a tool call), FirstText to its first text, as Millis
// counts: streamed replies only (#196)
TTFT int64 `json:"ttft,omitempty"`
FirstText int64 `json:"firstText,omitempty"`
// Served: the model the reply says answered, as the last try has it;
// Swapped: another than the one that try asked for
Served string `json:"served,omitempty"`
Swapped bool `json:"swapped,omitempty"`
}
// GroupRef is the routing group a request asked for.
type GroupRef struct {
ID string `json:"id"`
Name string `json:"name"`
Routing string `json:"routing"`
Affinity string `json:"affinity"`
Auto bool `json:"auto,omitempty"`
Members []string `json:"members"` // those ready, as provider/model[:effort fixed on it]
// Subs: the groups in the group, at any depth, outermost first
Subs []SubGroup `json:"subs,omitempty"`
// Via: for each of Members, the groups in the group it is of, as
// "fast>cheap" ("" for the group's own), when it has groups in it
Via []string `json:"via,omitempty"`
}
// SubGroup is a routing group in the group a request asked for.
type SubGroup struct {
ID string `json:"id"`
Name string `json:"name"`
Routing string `json:"routing"`
In string `json:"in"` // the group it is in
Rules int `json:"rules,omitempty"` // how many rules it has
}
// NestedRule is a group in the group's rules, as they decided.
type NestedRule struct {
Group string `json:"group"`
Name string `json:"name"`
Rule *RuleHit `json:"rule"`
}
// groupRef is the trace's g, with its models ms.
func groupRef(g provider.Group, ms []provider.Member) *GroupRef {
ref := &GroupRef{ID: g.ID, Name: g.Name, Routing: g.Routing, Affinity: g.Affinity, Auto: g.Auto}
seen := map[string]bool{}
for _, m := range ms {
ref.Members = append(ref.Members, provider.WithMemberEffort(m.Provider.ID+"/"+m.Model, m.Effort))
ref.Via = append(ref.Via, strings.Join(m.Groups(), ">"))
in := g.ID
for _, v := range m.Via {
if !seen[v.ID] {
seen[v.ID] = true
ref.Subs = append(ref.Subs, SubGroup{ID: v.ID, Name: v.Name, Routing: v.Routing, In: in, Rules: len(v.Rules)})
}
in = v.ID
}
}
if len(ref.Subs) == 0 {
ref.Via = nil
}
return ref
}
// Weighed is one account or key as routing weighed it.
type Weighed struct {
ID string `json:"id"` // what rests after a failure
Provider string `json:"provider"`
Name string `json:"name"` // the provider's
Icon string `json:"icon,omitempty"`
Preset string `json:"preset,omitempty"`
Who string `json:"who,omitempty"` // the account, or the key's name or its masked self
Kind string `json:"kind"` // "account", "key", or "provider" when it has one
Agent string `json:"agent,omitempty"`
Plan string `json:"plan,omitempty"`
Model string `json:"model"`
Fixed string `json:"fixed,omitempty"` // the effort the group's member it is of is fixed at
Routing string `json:"routing"` // its provider's: "", order, rotate, usage
Fallback bool `json:"fallback,omitempty"`
Shared bool `json:"shared,omitempty"` // its provider has more than one on
Known bool `json:"known,omitempty"` // the vendor said what the account has left
Learns bool `json:"learns,omitempty"` // not known, but its answer will tell
Used float64 `json:"used"` // share of the allowance counting the model, used
Renews []time.Time `json:"renews,omitempty"` // when those windows renew, the biggest first
Tokens float64 `json:"tokens,omitempty"` // least used: tokens it served lately
Turn bool `json:"turn,omitempty"` // in turn: it was this one's turn
Fit int `json:"fit,omitempty"` // keyFit
Speaks provider.Protocol `json:"speaks,omitempty"` // a key made for one protocol only
Rest *Rest `json:"rest,omitempty"` // resting after a failure, when the request came
Unlisted bool `json:"unlisted,omitempty"`
// Aside: a key made for another protocol than the keys routed over,
// tried only after them
Aside bool `json:"aside,omitempty"`
// Via: the groups in the group it is of, outermost first, when it is
// of a group in the group asked for
Via []string `json:"via,omitempty"`
}
// Try is one candidate trying the request.
type Try struct {
ID string `json:"id"`
Model string `json:"model,omitempty"` // the model it was asked for: a group's members may share a provider's keys
Effort string `json:"effort,omitempty"` // the reasoning it was sent at, fitted to its model's levels; "" for none
Picked bool `json:"picked,omitempty"` // Effort is the turn's pick, in place of the agent's
// Fixed: the effort the group's member it went to is fixed at, which
// Effort is (fitted to the model's levels) whatever was asked
Fixed string `json:"fixed,omitempty"`
Start time.Time `json:"start"`
Done bool `json:"done"`
Status int `json:"status,omitempty"`
Millis int64 `json:"ms,omitempty"`
// TTFT: ms from Start to its reply's first content, FirstText to its
// first text, when it streamed any (#196)
TTFT int64 `json:"ttft,omitempty"`
FirstText int64 `json:"firstText,omitempty"`
// Served: the model its reply said answered, when it named one;
// Swapped: another model than Model, not just its dated name
Served string `json:"served,omitempty"`
Swapped bool `json:"swapped,omitempty"`
Fail string `json:"fail,omitempty"` // why it failed, as rest tells it
Error string `json:"error,omitempty"`
Rest *Rest `json:"rest,omitempty"` // how long it now sits out; none when it was the last to try
Again int64 `json:"again,omitempty"` // ms waited before it was tried again, the last one left
}
type planned struct {
order, left []Weighed
}
func weighed(c candidate, p provider.Provider, wg weighing, fallback bool, from provider.Protocol) Weighed {
w := Weighed{ID: c.rest, Provider: p.ID, Name: p.Name, Icon: p.Icon, Preset: p.Preset, Model: c.model, Fixed: c.effort,
Routing: p.Routing, Fallback: fallback, Shared: c.rest != p.ID}
switch {
case c.p.Account != nil:
w.Kind, w.Who, w.Agent, w.Plan = "account", c.p.Account.User, c.p.Account.Agent, c.p.Account.Plan
case c.rest != p.ID:
w.Kind, w.Who = "key", c.p.KeyName
if w.Who == "" {
w.Who = provider.Mask(c.p.Key)
}
w.Fit, w.Speaks = keyFit(c.p, c.model, from), c.p.KeyProtocol
default:
w.Kind = "provider"
}
if l, ok := wg.lefts[c.allowanceKey()]; ok {
w.Known, w.Used, w.Renews = true, l.used, l.renews
} else if wg.lefts != nil {
w.Learns = learns(c, wg.lefts)
}
if wg.tokens != nil {
w.Tokens = wg.tokens[c.rest]
}
return w
}
// trace keeps the last requests' routes, and wakes those waiting for more.
type trace struct {
mu sync.Mutex
seq int64
ids int64
routes []*Route
wake chan struct{}
totals Totals
}
// Totals count the requests routed since the gateway started.
type Totals struct {
Requests int `json:"requests"` // answered, one way or the other
Rerouted int `json:"rerouted"` // tries that failed and handed the request on
Errors int `json:"errors"` // requests whose agent got an error
}
// TraceState is the routes changed since a seq, and the totals.
type TraceState struct {
Seq int64 `json:"seq"`
Routes []Route `json:"routes"`
Totals Totals `json:"totals"`
}
func (t *trace) changed() {
t.seq++
if t.wake != nil {
close(t.wake)
t.wake = nil
}
}
func (t *trace) begin(r Route) *Route {
t.mu.Lock()
defer t.mu.Unlock()
if t.ids == 0 {
// ids go on from one run to the next, the history keeping them
// all: counted on from the time the gateway began
t.ids = time.Now().UnixMilli()
}
t.ids++
r.ID = t.ids
if r.Tries == nil {
r.Tries = []Try{}
}
rp := &r
t.routes = append(t.routes, rp)
if len(t.routes) > traceKeep {
t.routes = t.routes[len(t.routes)-traceKeep:]
}
t.changed()
rp.Seq = t.seq
return rp
}
// update changes a route under the lock.
func (t *trace) update(r *Route, f func(r *Route)) {
if r == nil {
return
}
t.mu.Lock()
defer t.mu.Unlock()
done := r.Done
f(r)
if r.Done && !done {
t.totals.Requests++
for i, try := range r.Tries {
if try.Rest != nil && i < len(r.Tries)-1 { // the last rests with nobody after it (failVerify)
t.totals.Rerouted++
}
}
if r.Status >= 400 {
t.totals.Errors++
}
if keepRoutes {
c := *r
c.Order = append([]Weighed(nil), r.Order...)
c.Left = append([]Weighed(nil), r.Left...)
c.Tries = append([]Try{}, r.Tries...)
go saveRoute(c)
}
}
t.changed()
r.Seq = t.seq
}
// Trace is the routes changed after seq, oldest first. With none, it waits
// up to wait for one.
func (s *Server) Trace(ctx context.Context, after int64, wait time.Duration) TraceState {
t := &s.trace
deadline := time.NewTimer(wait)
defer deadline.Stop()
for {
t.mu.Lock()
if t.seq < after {
after = 0 // the gateway started over since
}
st := TraceState{Seq: t.seq, Routes: []Route{}, Totals: t.totals}
for _, r := range t.routes {
if r.Seq > after {
c := *r
c.Order = append([]Weighed(nil), r.Order...)
c.Left = append([]Weighed(nil), r.Left...)
c.Tries = append([]Try{}, r.Tries...)
st.Routes = append(st.Routes, c)
}
}
if len(st.Routes) > 0 || wait <= 0 {
t.mu.Unlock()
return st
}
if t.wake == nil {
t.wake = make(chan struct{})
}
wake := t.wake
t.mu.Unlock()
select {
case <-wake:
case <-deadline.C:
return st
case <-ctx.Done():
return st
}
}
}
// Which model answered: a vendor may serve a request with another model
// than the one asked for — a cheaper one when it's busy — and its reply
// says so in its model field. Most echo the name asked for, or its dated
// or pinned version (gpt-5 as gpt-5-2025-08-07, claude-sonnet-4-5 as
// claude-sonnet-4-5-20250929, gemini-2.5-pro as models/gemini-2.5-pro-001),
// which is the same model.
// versionTail is what a vendor puts after a model's name for the version
// it answered with: a date, a build number, Bedrock's v1:0, latest,
// preview. Not v3 alone: deepseek-v3 is another model than deepseek-v2.
var versionTail = regexp.MustCompile(`(?:[-_@:](?:\d{4}-\d{2}-\d{2}|\d{2}-\d{2}|\d{6,8}|\d{3,4}|v\d+:\d+|latest|preview|exp))+$`)
// vendorDot is Bedrock's region and maker before a model's name
// (us.anthropic.claude-…).
var vendorDot = regexp.MustCompile(`^(?:[a-z]{2,4}\.)?(?:anthropic|amazon|meta|mistral|cohere|ai21|deepseek|qwen|openai|google|moonshotai|minimax|zai)\.`)
// bareModel is a model's name without its maker or path, its version or
// its case.
func bareModel(m string) string {
m = strings.ToLower(strings.TrimSpace(m))
if i := strings.LastIndexByte(m, '/'); i >= 0 {
m = m[i+1:]
}
m = vendorDot.ReplaceAllString(m, "")
if loc := versionTail.FindStringIndex(m); loc != nil && loc[0] > 0 {
m = m[:loc[0]]
}
return m
}
// swapped reports whether served is another model than sent: not the same
// name, however dated, pinned or prefixed.
func swapped(sent, served string) bool {
a, b := bareModel(sent), bareModel(served)
return a != "" && b != "" && a != b
}