Files
magpie/internal/gateway/active.go
T
yetoneandCanda15 0f1b40bbc4 gateway: a reply in flight shows on Routing how much has arrived and roughly its tokens (#4951, Canda15)
A long or reasoning reply looked stuck on the Routing page. A request still
out now shows, on its row and beside the account answering it, the bytes
the agent has had, "≈ n tokens" once a rate is learned, and how long ago
content last came; after 15s with no content the account's dot stops
pulsing. Nothing stays once the request is done.

Ported from Canda15's 7f7bdb189 (github.com/Canda15/magpie), the idea and
the per-protocol content extractors kept, the hot path and storage
reworked:
- every write to the agent passes captureResponseWriter.Write, which calls
  liveRow.observe; the row hangs on the request's inflight (an atomic
  pointer), not a context value made per request
- rates are in memory only (256 pairs); the fork wrote a JSON file under
  the estimate lock on every finished request
- a whole JSON reply is counted in bytes only: the fork held and decoded up
  to 8 MiB of it at the end; a stream is cut into lines in place, only a
  line cut by a write's end is copied, a line over 1 MiB passed over, and
  each event decoded once (the fork ran json.Valid then Unmarshal)
- the reply's kind comes from its first byte, not a header read on every
  write; the keepalive check allocates nothing (the fork split each write)
- everything a row counts is under its own lock, and inflight.tr is read
  under f.mu; the estimate is in float64 (the int64 product overflowed)
- the route's Seq is bumped on every write and traceGather batches the
  wake-ups; the fork's global throttle could drop the last update before
  a pause
- learned only from a streamed reply that did not fail and had the
  vendor's output tokens
- left out: the finished row's "Received" metric and the ended caption
  (layout restraint; an ended row has its own metrics), a duplicate
  "Received" i18n key, the receive-monitor doc (the design is in
  gateway-routing.md now), the fork's xmod and Windows CI commits
The Routing plugin and i18n.js are outside TestCoreScriptBudget.

Run on mote at this head unless named: gofmt -l; go vet (darwin),
GOOS=linux -tags nogui and GOOS=windows go vet ./...; go build ./...;
go test -race on the live tests; go test ./internal/gateway ./internal/gui
(gateway ok; gui red only on TestCoreScriptBudget, #5139, 1533907 >
1533802 before this change and untouched by it, and
TestMainWindowCorners/macOS_26_SDK, #3949); routing-live-bytes.test.cjs and i18n-keys in Chromium and
WebKit, en/zh/zh-TW/ja/de, 1100 and 420px (24/24); every routing-* and
panel-routing* GUI file with i18n-keys in WSL Linux (Chromium all green;
WebKit reds in 12 files, the same class at origin/main 7dd2434d3 run
the same way: 25 there, 28 here, the sets differing by timing samples;
routing-live-patch alone red 2 of 3 on main, 1 of 3 here; filed as
#4121, #4520, #5156, #2174).

Rebased onto 38f4f74e6 (gateway.go, trace.go and the Routing plugin
moved): build, gateway vet, the live tests, routing-live-bytes and
i18n-keys run again there, green (24/24).

Broken by hand, each red, then put back:
- no observe in capture.Write: TestLiveCountsARealStream
- commentOnly never true: TestLiveHeartbeatIsBytesNotContent,
  TestCommentOnlyTellsHeartbeatsApart
- learning from failed replies: TestRatesLearnFromRepliesTheVendorFinished
- a whole reply read as a stream: TestContentCounterLeavesAWholeReply
- no Seq bump in liveBytes: TestLiveWritesReachTheRoute
- no quiet class, no per-second repaint: routing-live-bytes 0/20

Not tried: a real vendor's stream in the running app; the ChatGPT backend
chain (codex_backend.go) writes past the capture writer and isn't counted;
the full Go and GUI suites run after the tag.

Co-authored-by: Canda15 <124772373+Canda15@users.noreply.github.com>
2026-11-04 19:39:08 +08:00

196 lines
6.0 KiB
Go

package gateway
import (
"context"
"net/http"
"sort"
"sync"
"sync/atomic"
"time"
)
// Active is one agent request in flight, as /v1/magpie/concurrency lists
// it for a status bar's hover (#2132, bigbitbox): which agent asked, for
// which model, since when, and where it stands. It holds no prompt, reply
// or key. Model and Provider are the routing trace's, once the request has
// been routed; Phase is said only when the gateway knows it: "slot" while
// it waits in a key's or account's queue (MaxConcurrency), "rpm" while it
// waits for room in the minute (MaxRPM), "upstream" while a try is out at
// the vendor (the request sent, or its reply streaming), "redact" while
// it is masked (noteRedacting: the rules, and the local model with its
// wait for a turn). A request served another way (a subscription bridge,
// a title helper) has none.
type Active struct {
ID int64 `json:"id"`
Agent string `json:"agent"`
Model string `json:"model,omitempty"`
Provider string `json:"provider,omitempty"`
Session string `json:"session,omitempty"`
Started time.Time `json:"started"`
Millis int64 `json:"ms"`
Phase string `json:"phase,omitempty"`
Route int64 `json:"route,omitempty"` // its routing trace's id
}
// inflight is a request counted for Busy, kept on its context so routing
// can tell it its route and its phase.
type inflight struct {
id int64
agent string
session string
start time.Time
route atomic.Pointer[Route]
phase atomic.Value // string
// begun: every route begun for it, the first its own, for endBroken
mu sync.Mutex
begun []*Route
// unrouted: its watch while no route is begun for it (unrouted.go)
unrouted *unroutedHold
// tr: the trace its routes are in, for the phase they say (under mu)
tr *trace
// redaction: its maskings, their phase and time (redact_phase.go)
redaction redaction
// live: its reply counted as it reaches the agent (live.go)
live atomic.Pointer[liveRow]
}
type inflightKey struct{}
// inflights are the requests counted for Busy, by id.
type inflights struct {
mu sync.Mutex
seq int64
m map[int64]*inflight
}
// add counts r in and answers it with its inflight on its context, and the
// func that counts it out.
func (l *inflights) add(r *http.Request) (*http.Request, func()) {
f := &inflight{agent: callerFrom(r).agent, session: sessionOf(r.Header), start: time.Now()}
l.mu.Lock()
if l.m == nil {
l.m = map[int64]*inflight{}
}
l.seq++
f.id = l.seq
l.m[f.id] = f
l.mu.Unlock()
return r.WithContext(context.WithValue(r.Context(), inflightKey{}, f)), func() {
l.mu.Lock()
delete(l.m, f.id)
l.mu.Unlock()
}
}
// inflightOf is ctx's request in flight, nil when it isn't counted.
func inflightOf(ctx context.Context) *inflight {
f, _ := ctx.Value(inflightKey{}).(*inflight)
return f
}
// notePhase says where ctx's request in flight stands now, and answers the
// func that puts back where it stood before: a try out at the vendor whose
// own requests wait for room in the minute (rpmTransport) is out at the
// vendor again once they go.
//
// A phase is a wait magpie knows of (noteWait): one before a route is
// begun has unroutedMost, not unroutedUnknown.
func notePhase(ctx context.Context, phase string) (restore func()) {
f := inflightOf(ctx)
if f == nil {
return func() {}
}
was, _ := f.phase.Load().(string)
f.phase.Store(phase)
// masking's phase is named by noteMasking's own wait
kind := phase
if phase == phaseRedact {
kind = ""
}
waited := noteWait(ctx, kind)
return func() { waited(); f.phase.Store(was) }
}
// noteRoute ties ctx's request in flight to its routing trace, the first
// route begun for it: the one for what the agent asked.
func noteRoute(ctx context.Context, rt *Route) {
if f := inflightOf(ctx); f != nil {
f.route.CompareAndSwap(nil, rt)
f.mu.Lock()
f.begun = append(f.begun, rt)
var shown *Route
if f.unrouted != nil {
shown = f.unrouted.routed()
}
f.mu.Unlock()
if shown != nil {
// the route that showed it while it waited gives way to its own
f.unrouted.s.trace.drop(shown)
}
}
}
// panicEnded is what a route ended by endBroken says.
const panicEnded = "magpie broke off this request: an internal error (in magpie's log)"
// endBroken ends every route begun for f that its handler left in flight
// when it panicked, and each of their tries still out: net/http recovers
// the panic and drops the connection, but a route not done shows as still
// answering on the Routing page and counts as in progress for good, and
// the trace never trims it (#2386).
func (s *Server) endBroken(f *inflight) {
if f == nil {
return
}
f.mu.Lock()
begun := append([]*Route(nil), f.begun...)
f.mu.Unlock()
for _, rt := range begun {
s.trace.update(rt, func(r *Route) {
if r.Done {
return
}
ms := time.Since(r.Time).Milliseconds()
for i := range r.Tries {
if t := &r.Tries[i]; !t.Done {
t.Done, t.Status, t.Error, t.Millis = true, http.StatusInternalServerError, panicEnded, time.Since(t.Start).Milliseconds()
}
}
r.Done, r.Status, r.Error, r.Millis = true, http.StatusInternalServerError, panicEnded, ms
})
}
}
// Active lists the agent requests in flight now, the oldest first; empty,
// never nil, when there are none.
func (s *Server) Active() []Active {
s.active.mu.Lock()
fs := make([]*inflight, 0, len(s.active.m))
for _, f := range s.active.m {
fs = append(fs, f)
}
s.active.mu.Unlock()
now := time.Now()
out := make([]Active, 0, len(fs))
for _, f := range fs {
a := Active{ID: f.id, Agent: f.agent, Session: f.session, Started: f.start, Millis: now.Sub(f.start).Milliseconds()}
if p, _ := f.phase.Load().(string); p != "" {
a.Phase = p
}
if rt := f.route.Load(); rt != nil {
s.trace.mu.Lock()
a.Route, a.Model, a.Provider = rt.ID, rt.Model, rt.Provider
if rt.Agent != "" {
a.Agent = rt.Agent
}
if a.Session == "" {
a.Session = rt.Session
}
s.trace.mu.Unlock()
}
out = append(out, a)
}
sort.Slice(out, func(i, j int) bool { return out[i].ID < out[j].ID })
return out
}