Files
magpie/internal/gateway/active.go
T
yetone 27a0458de1 gateway: /v1/magpie/concurrency lists each request in flight, its agent, model, start and phase, for a status bar's hover (#2132, bigbitbox)
The concurrency read now carries `active` beside requests/waiting/tools:
one entry per agent request counted for Busy, oldest first, [] when idle:
id, agent, model and provider (once routed, from the routing trace),
session when the agent sends one, started and ms, route (the trace id),
and phase only where the gateway knows it: "slot" waiting in a key's or
account's queue, "rpm" waiting for room in the minute, "upstream" while a
try is out at the vendor. No prompt, reply or key. The entry lives on the
request's context from `counted` (so a GET, this poll included, is never
listed), routing ties it to its first route in trace.beginFor, and
lanes.take / rpms.wait / the try loop note the phase, putting the one
before back when they return. Access is the endpoint's: this machine,
another with a gateway key, never a held key (TestHeldKeyToldNoAccounts).
Nothing in routing or limits reads it.

Run (worktree on e98440ae6, sandbox HOME, GOCACHE pinned):
- TestConcurrencyListsEachRequest (new): one request out and one of the
  same agent waiting for a one-slot provider; checks agent, model,
  provider, session, phase upstream/slot, no prompt or key, [] idle and
  after. Broken by hand, each goes red: active left out ("active left
  out or null"), the slot phase removed ("never one out and one
  waiting"), noteRoute removed (model/provider empty), the upstream
  phase removed (phase "").
- go test -race -count=5 -run 'TestConcurrency|TestBusy|TestMaxConcurrency|TestMaxRPM|TestHeldKey' ./internal/gateway: ok
- go test -tags nogui ./internal/gateway (-timeout 28m; 1394s on a loaded
  machine, the default 10m timeout cut the first run short), ./internal/proc,
  ./internal/usageapi: ok
- gofmt -l, go vet, GOOS=linux go vet -tags nogui, GOOS=windows go vet
  on ./internal/gateway: clean
Not run: the full `go test ./...` (disk tight), a real SketchyBar hover;
no GUI change.
2026-10-15 01:13:18 +08:00

132 lines
3.9 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). 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
}
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: agentOf(r), 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.
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)
return func() { 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)
}
}
// 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
}