gateway: /v1/magpie/concurrency tells the whole gateway's requests in flight, waiting and tool turns, 0 when idle, with or without a limit (#2132, bigbitbox)

A status bar (SketchyBar) polling /v1/magpie/concurrency got
{"data":{},"object":"concurrency"} with no limit set: the lanes hold only
keys and accounts with a limit, so an idle gateway and a busy one with no
limits read the same. The answer now carries, beside data:
- requests: Busy().Requests, every agent request in flight, those waiting
  for a slot among them; a GET (this poll included) is never counted;
- waiting: how many of those wait for a slot, summed over the lanes;
- tools: Claude subscription turns waiting on their caller's tool results.
Each is 0 when idle. Access is unchanged: this machine, another only with a
gateway key, a held key refused (refuseHeld). docs/reference.md says so
beside the usage API.

Run: TestConcurrencyTellsTheWholeGateway (new) fails without the change
("idle: tools = <nil>, want 0 (map[data:map[] object:concurrency])") and
passes with it, -count=5; it covers no limit anywhere (the reporter's
case), and three in flight on a one-slot provider with one waiting.
gofmt -l (nothing); go vet, GOOS=linux go vet -tags nogui, GOOS=windows go
vet on internal/gateway (ok). go test -tags nogui -count=1 ./internal/gateway
in a sandbox HOME: ok in 835s with -timeout 40m (on 0ad9661b6; the default
10m ran out while three other gateway suites ran on this machine), then
the concurrency, busy, held-key and LAN tests -count=3 after rebasing on
63ad2b7c7 (ok).
Not tried: SketchyBar itself.
This commit is contained in:
yetone
2026-10-14 16:05:13 +08:00
parent 1015fbab7f
commit 3b6ca05571
3 changed files with 127 additions and 2 deletions
+12
View File
@@ -1726,6 +1726,18 @@ only with a gateway key. A key held to a budget, to some models or to some
accounts is told its own calls alone: `/v1/magpie/usage` refuses it with a
403, and `/v1/magpie/usage/requests` keeps only its rows and filter lists.
What is in flight now, for a status bar such as SketchyBar (#2132):
`GET /v1/magpie/concurrency` answers `requests`, every agent request the
gateway is working on, whether or not any limit is set (those waiting for a
slot among them); `waiting`, how many of those wait for a slot under a
provider's or account's limit; and `tools`, Claude Code turns run through a
Claude subscription that wait on their caller's tool results, which are not
requests. Each is `0` when idle. `data` is each limited key's or account's
own count, empty when no limit is set. The read asks no vendor and isn't
counted itself, so it can be polled every second. It answers as
`/v1/magpie/quotas` does: this machine, another only with a gateway key,
and never a held key.
An app that calls its vendor itself, not through magpie, can report those
calls so the Usage page counts them: `POST /v1/magpie/usage/requests` with
`Content-Type: application/json`. The body is one record or an array of up
+101
View File
@@ -1,6 +1,7 @@
package gateway
import (
"encoding/json"
"io"
"net/http"
"net/http/httptest"
@@ -86,3 +87,103 @@ func TestBusy(t *testing.T) {
t.Fatalf("a run ended: %+v", b)
}
}
// /v1/magpie/concurrency tells the whole gateway's requests in flight with
// no limit set anywhere (#2132, a status bar polling it): 0 when idle,
// never left out, the poll itself not counted, and the requests waiting
// for a slot counted among them and told apart.
func TestConcurrencyTellsTheWholeGateway(t *testing.T) {
fresh(t)
var hold sync.WaitGroup
started, release := make(chan struct{}, 4), make(chan struct{})
up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
io.Copy(io.Discard, r.Body)
w.Header().Set("Content-Type", "text/event-stream")
io.WriteString(w, `data: {"id":"c","object":"chat.completion.chunk","model":"m","choices":[{"index":0,"delta":{"role":"assistant","content":"hel"}}]}`+"\n\n")
w.(http.Flusher).Flush()
started <- struct{}{}
<-release
io.WriteString(w, `data: {"id":"c","object":"chat.completion.chunk","model":"m","choices":[{"index":0,"delta":{"content":"lo"},"finish_reason":"stop"}]}`+"\n\ndata: [DONE]\n\n")
}))
defer up.Close()
one := 1
if err := provider.Save(provider.Provider{ID: "free", Name: "Free", Key: "k", Chat: up.URL + "/v1", Models: []string{"m"}}); err != nil {
t.Fatal(err)
}
if err := provider.Save(provider.Provider{ID: "one", Name: "One", Key: "k", Chat: up.URL + "/v1", Models: []string{"m"}, MaxConcurrency: &one}); err != nil {
t.Fatal(err)
}
s := New()
gw := httptest.NewServer(s.Handler())
defer gw.Close()
let := sync.OnceFunc(func() { close(release) })
defer hold.Wait()
defer let()
read := func() map[string]any {
t.Helper()
res, err := http.Get(gw.URL + "/v1/magpie/concurrency")
if err != nil {
t.Fatal(err)
}
defer res.Body.Close()
var out map[string]any
if err := json.NewDecoder(res.Body).Decode(&out); err != nil || res.StatusCode != 200 {
t.Fatalf("concurrency: %d %v", res.StatusCode, err)
}
return out
}
want := func(when string, requests, waiting float64) {
t.Helper()
out := read()
for k, v := range map[string]float64{"requests": requests, "waiting": waiting, "tools": 0} {
if got, ok := out[k].(float64); !ok || got != v {
t.Fatalf("%s: %s = %v, want %v (%v)", when, k, out[k], v, out)
}
}
}
want("idle", 0, 0)
send := func(model string) {
hold.Add(1)
go func() {
defer hold.Done()
res, err := http.Post(gw.URL+"/v1/chat/completions", "application/json", strings.NewReader(`{"model":"`+model+`","stream":true,"messages":[{"role":"user","content":"hi"}]}`))
if err == nil {
io.Copy(io.Discard, res.Body)
res.Body.Close()
}
}()
}
// one with no limit anywhere, as the reporter's gateway has
send("free/m")
<-started
want("one request, no limit", 1, 0)
// two on a provider of one slot: one out, one waiting
send("one/m")
<-started
send("one/m")
deadline := time.Now().Add(5 * time.Second)
waiting := func() (n int) {
for _, ln := range s.Lanes() {
n += ln.Waiting
}
return n
}
for waiting() != 1 {
if time.Now().After(deadline) {
t.Fatalf("the second never waited: %v", s.Lanes())
}
time.Sleep(10 * time.Millisecond)
}
want("three in flight, one waiting", 3, 1)
let()
hold.Wait()
deadline = time.Now().Add(5 * time.Second)
for s.Busy().Requests != 0 && time.Now().Before(deadline) {
time.Sleep(10 * time.Millisecond)
}
want("done", 0, 0)
}
+14 -2
View File
@@ -233,7 +233,13 @@ type Lane struct {
// concurrency tells each key's or account's Lane. It names the accounts,
// so it answers as quotas does: this machine, or one with the key of the
// gateway shared on the local network.
// gateway shared on the local network. Beside them it tells the whole
// gateway's count, limit or none (#2132, for a status bar): requests is
// every agent request in flight, the ones waiting for a slot among them
// (Busy.Requests, a GET like this one never counted), waiting is how many
// of those wait for a slot, and tools the Claude Code turns waiting on
// their caller's tool results, which are not requests. Each is 0 when
// idle, never left out.
func (s *Server) concurrency(w http.ResponseWriter, r *http.Request) {
if !local(r) && !sharedWith(r) {
writeError(w, provider.Chat, http.StatusForbidden, "magpie's concurrency is told to another machine only when magpie is shared on the local network and the request carries its API key")
@@ -242,7 +248,13 @@ func (s *Server) concurrency(w http.ResponseWriter, r *http.Request) {
if refuseHeld(w, r, heldRefused) {
return
}
writeJSON(w, 200, map[string]any{"object": "concurrency", "data": s.Lanes()})
lanes := s.Lanes()
waiting := 0
for _, ln := range lanes {
waiting += ln.Waiting
}
b := s.Busy()
writeJSON(w, 200, map[string]any{"object": "concurrency", "data": lanes, "requests": b.Requests, "waiting": waiting, "tools": b.Tools})
}
// Lanes is how each key or account with requests out or waiting under a