Files
magpie/internal/gateway/speed.go
T
yetone d9a8148d7c routing: Speed first sends a request to the provider or key that answered the model fastest lately
joeliu96872540 on X: when one model is reachable through several API
channels, they want an option that sends each request to whichever has
been answering fastest, because they compare channel speeds by hand
today. Speed first (`fast`; `fastest` and `speed` also work) is a new
routing beside Free first. It applies to a provider's keys and accounts
(provider editor › Routing) and to a group of one model on several
providers (Routing page › group › Routing).

How it decides. When a streamed answer ends, gateway/speed.go records two
numbers for that account or key and model (restID): the time to first
token and the output tokens per second, as usage.DecodeOf computes them
for the Requests page. Each is a decayed average with a 20m half-life.
After an hour with no answer the record goes stale, and the store holds
at most 4096 records. This is O(1) at the answer choke point, beside
servedCandidate. For a pool routed by BySpeed, weighRouted reads one map
entry per candidate, and only for that pool. The usage history is never
read on a request.

routes.Fastest ranks each awake seat by its estimated time to a
200-token reply: TTFT + 200/TPS. A seat that reported no TPS gets the
median TPS of the others. Seats within 10% of the fastest in their band
keep their listed order, so near-ties don't swap on every request.
Seats with no recent measurement go after the measured ones. One request
in five, counted per pool, goes first to an unmeasured seat, rotating
among them, so each gets measured again. Resting seats go behind the
awake ones, and used-up seats behind those. Rests and failover are the
same as for every other routing.

The request trace gets lateTtft and lateTps, and the row-story sentence
says "answered m fastest lately: first token in 0.8s, 60 tokens a
second". It has a variant for a probe turn and one for when no seat has
been measured yet. i18n covers zh, zh-TW, ja and de. Also updated: the
CLI (`magpie group|provider set <id> routing=fast`, plus a new
`routing=` pair on provider set that refuses manual), the TUI name, the
rotation plugin's Sub, docs/subsystems/gateway-routing.md,
plugin-runtime.md, docs/reference.md and site start.html (en, zh, ja).
There is no new layout: it is one more item in the existing pickers.
app.js stays under its budget with no raise.

Tests:
- routes/fastest_test.go:
  - ordering: fastest first, slow writer loses, alike keep order,
    resting and used-up, median pace, none measured;
  - the probe turn at 5, 10, 15 and 20, rotating between seats;
  - a resting seat never gets a probe turn.
- gateway/speed_test.go:
  - decay, staleness and per-model records, with an injected clock;
  - a group of slowv and fastv routed fast: after the speeds are
    measured and seeded, the request goes to fastv with lateTtft set;
  - the same group routed in order still goes to slowv.
- cli: parseRouting and the provider routing= pair.
- GUI routing-speed-first.test.cjs: the row story for measured,
  no-pace, probe and none, in en, zh, zh-TW, ja and de, in chromium and
  webkit: 40/40.

Broken by hand:
- Fastest returning the listed order: the routes tests and the gateway
  group test go red.
- noteTrySpeed removed: "the streamed answer wasn't measured".
- The client.js case renamed: routing-speed-first 0/20 in chromium.

Run at b5a5caff2 (base 5b4dec58e):
- `go test ./... -count=1 -timeout 45m`, alone on the machine, at load
  130-230. Every package is ok except:
  - internal/provider: TestUnreadLoginsWriteErrorsKeepCredentials
    crashes with "close of synctest channel from outside bubble"
    (#3632, open);
  - internal/gui: TestMainWindowCorners and
    TestTrayCellClickReleasedPanel are killed at their deadline under
    load (#1936, #2645).
- gofmt -l is empty. go vet is ok on darwin, on GOOS=linux with -tags
  nogui, and on GOOS=windows for ./internal/....
- GUI files the change reaches, both engines, every language they test,
  all ok: i18n-keys, gui-de, gui-ja, gui-zh-tw, routing-save,
  routing-save-keeps-the-row, builtins, panel-routing,
  panel-routing-pick, panel-routing-providers, panel-routing-hidden,
  routing-key-windows, key-weight, key-weight-fit, group-member-weight,
  routing-weight-chip, account-arrange and routing-speed-first (40/40).
- routing-group-strategy was 4/18: the menu now has 9 items and the test
  still counted 8. Fixed in this commit; rerun, it is 18/18.
- routing-save-blank (a webkit click timeout) and routing-columns (zh
  "side by side") each failed one subtest at load ~200. Rerun alone,
  they are 4/4 each. Both are already filed (#1924, #1612).

Rebased on 8f023b511, where upstream changed gateway.go, app.js, client.js,
the routing plugin's i18n.js and gateway-routing.md; the rebase was clean.
At this head I reran gofmt, go build ./... and go vet (darwin, linux
nogui, windows) on routes, gateway and cli, and go test for routes, cli,
provider and gateway (the routing and speed tests) and for gui -run
Budget: all ok. The GUI files i18n-keys (4/4), routing-speed-first
(40/40) and routing-group-strategy (18/18) also passed.

Not tried:
- A real run against several channels of one model. Speeds come from
  real answers, so the first minutes after a start are in listed order
  plus probes.
- A non-streamed reply is not measured, a sub-millisecond TTFT is not
  counted, and a restart forgets every speed.
- The Windows runtime: only go vet ran for it.
2026-10-27 01:37:38 +08:00

117 lines
3.5 KiB
Go

package gateway
import (
"math"
"sync"
"time"
"github.com/yetone/magpie/internal/usage"
)
// Speed lately, for Speed first (routes.Fastest): of each account or key
// and model (restID), a decayed average of its streamed answers' time to
// first token and of how fast they wrote. Kept in memory, a few numbers
// each, written once as an answer ends (noteSpeed) and read with a map
// lookup per candidate as a pool routed by speed is weighed: the usage
// history is never read for it. A restart forgets them, and each is
// measured again as Fastest's probes give it a turn.
// speedHalfLife: a sample counts half after this, against those since.
// speedStale: this long after its last answer a seat counts as not
// measured lately, and Fastest gives it a turn now and then to be
// measured again, so one that was slow once isn't kept last for good.
const (
speedHalfLife = 20 * time.Minute
speedStale = time.Hour
)
// speedMost bounds the records: past it, those not measured lately go.
const speedMost = 4096
type speedRec struct {
ttft, ttftW float64 // the average ms to the first token, and its samples' weight
tps, tpsW float64 // the average output tokens a second, and its samples' weight
at, tpsAt time.Time // the last sample of each
}
var speeds = struct {
sync.Mutex
m map[string]speedRec // candidate restID → its speed lately
}{m: map[string]speedRec{}}
func decayed(w float64, since time.Duration) float64 {
if since <= 0 {
return w
}
return w * math.Exp2(-since.Seconds()/speedHalfLife.Seconds())
}
// fold is avg of weight w, decayed by since, with x added at weight 1.
func fold(avg, w float64, since time.Duration, x float64) (float64, float64) {
w = decayed(w, since)
return (avg*w + x) / (w + 1), w + 1
}
// noteSpeed records an answer of c's: ttft ms from its try's start to its
// first content, and, when its pace was told, tokens written in w ms
// after it (usage.DecodeOf). A reply that wasn't streamed has no ttft and
// tells nothing.
func noteSpeed(c candidate, ttft int64, tokens int, w int64, now time.Time) {
if ttft <= 0 {
return
}
id := c.restID()
speeds.Lock()
defer speeds.Unlock()
r := speeds.m[id]
r.ttft, r.ttftW = fold(r.ttft, r.ttftW, now.Sub(r.at), float64(ttft))
r.at = now
if tokens > 0 && w > 0 {
r.tps, r.tpsW = fold(r.tps, r.tpsW, now.Sub(r.tpsAt), float64(tokens)*1000/float64(w))
r.tpsAt = now
}
if _, had := speeds.m[id]; !had && len(speeds.m) >= speedMost {
for k, o := range speeds.m {
if now.Sub(o.at) > speedStale {
delete(speeds.m, k)
}
}
}
speeds.m[id] = r
}
// noteTrySpeed is noteSpeed of a try that answered, its pace as
// usage.DecodeOf counts it for the Requests and Usage pages.
func noteTrySpeed(c candidate, t Try, out, reasoning int, now time.Time) {
tokens, w := 0, int64(0)
if !t.ReasoningHidden || t.FirstText > 0 {
tokens, w = usage.DecodeOf(out, reasoning, t.Millis, t.TTFT, t.FirstText, t.Flow, t.FirstReasoning)
}
noteSpeed(c, t.TTFT, tokens, w, now)
}
// speedOf is c's speed lately: its average ms to the first token and
// tokens a second, 0 for what wasn't measured lately.
func speedOf(c candidate, now time.Time) (ttft, tps float64) {
speeds.Lock()
r, ok := speeds.m[c.restID()]
speeds.Unlock()
if !ok {
return 0, 0
}
if now.Sub(r.at) > speedStale {
return 0, 0
}
if !r.tpsAt.IsZero() && now.Sub(r.tpsAt) <= speedStale {
tps = r.tps
}
return r.ttft, tps
}
// forgetSpeeds drops every speed: a test starts anew.
func forgetSpeeds() {
speeds.Lock()
speeds.m = map[string]speedRec{}
speeds.Unlock()
}