gateway: a decision provider of several keys asks the next when one is out of quota, at /v1/systemone and as a classifier, in its routing's order (fflake33 on Discord)

A TypeSafe Jev provider with several keys never left its first key when that
one's quota ran out. serveSystemOne and the classifier (askClassifier → askJev)
always sent to p.Key, with no rest and no rotation. Only a decision group
failed over (serveDecisionGroup, askDecisionGroup).

Now the single provider goes the same way as a group:
- decideKeys plans its keys and accounts with s.plan, so Smart or In order,
  rests and barred keys apply. probeOne keeps only the resting one back
  soonest.
- serveDecideTries and askDecideTries (the group's loops, pulled out) ask
  each in turn. A retryable failure that isn't the request's own rests it and
  the next is asked.
- serveSystemOne keeps #905's limits. A gateway key held to some accounts is
  asked only on those (allowedCandidates), and gets 403 keyAccountsError when
  none serves the model.
- A provider whose every key is set not to serve the model is refused 403
  (barredError) instead of being sent on its first key.
- decideSeat is gone; the trace lists every key tried.
- docs/subsystems/gateway-routing.md says so.

Run: go test -p 1 -tags nogui -run 'SystemOne|Decid|Decide|Jev|Classif|
KeyAccount|KeyModel|Disabled|RemoteMagpie|Caller|Usage|Plugin.*Decide|
Barred|Rest|Probe' ./internal/gateway (ok, 124s).
TestDecisionProviderKeysFailOver (Smart and In order) refuses the first key
429 and checks:
- /v1/systemone answers 200 from the second, the trace has two tries and the
  first rests, and one usage row goes to the provider;
- the next request asks only the second;
- the same holds through askClassifier.
Broken by hand: with the old decide.go, decide_group.go and classify.go it
fails "systemone: 429 no capacity for k1" in both. The first version of the
reordering ran the barred check before the held-key one, and
TestGatewayKeyAccountsSystemOne caught the changed 403 message. The held
check now runs first.
gofmt -l clean; GOOS=darwin/linux/windows go vet -tags nogui
./internal/gateway ok.
Not tried against the real TypeSafe API.

Full suite: SUITE_LINE
This commit is contained in:
yetone
2026-10-15 23:08:02 +08:00
parent 01e4268913
commit ecaa7e7dd7
5 changed files with 145 additions and 85 deletions
+10
View File
@@ -209,6 +209,16 @@ for the answer. A group classifier of decision models fails over the same
way (`askDecisionGroup`, `decideRefused` carrying the vendor's status). A
decision group is kept out of the agents' catalog (`groupEntries`), and a
conversation asked of it is refused 400 pointing at `/v1/systemone`.
A single decision provider of several keys or accounts (TypeSafe Jev with
a key out of quota, fflake33 on Discord) is asked the same way, at
`/v1/systemone` (`serveSystemOne`) and as a classifier (`askClassifier` →
`askDecider`): `decideKeys` plans its keys in its routing's order (Smart,
In order), `probeOne` leaves out all but the resting one back soonest, and
`serveDecideTries` / `askDecideTries` ask each in turn as for a group, a
refused one resting. Before, every call went to its first key, whatever the
others' state. A gateway key held to some accounts is asked only on those
(`allowedCandidates`), and refused 403 when none of them serves the model.
`TestDecisionProviderKeysFailOver`.
[`embeddings.go`](../../internal/gateway/embeddings.go) relays retrieval
bodies and options (`serveRetrieval`), and
[`transcribe.go`](../../internal/gateway/transcribe.go) speech-to-text's
+1 -1
View File
@@ -271,7 +271,7 @@ func classifyEffort(model string) string {
// call of its own, at once.
func (s *Server) askClassifier(model string, intents []string, prev before, effort bool, text string) (verdict, error) {
if p, m, ok := provider.Resolve(model); ok && p.DecidesModel(m) {
return s.askJev(p, m, intents, prev, effort, text)
return s.askDecider(p, m, intents, prev, effort, text)
}
// a group of decision models: each in turn (decide_group.go)
if v, ok, err := s.askDecisionGroup(model, intents, prev, effort, text); ok {
+20 -81
View File
@@ -485,97 +485,36 @@ func (s *Server) serveSystemOne(w http.ResponseWriter, r *http.Request) {
writeError(w, provider.Chat, http.StatusForbidden, keyModelError(keyWho, asked))
return
}
// its keys or accounts in its routing's order, each asked until one
// answers (decideKeys): one out of quota rests, and the next takes the
// request (fflake33 on Discord). One the user set not to serve the
// model is never asked; with every one so, the request is refused
cs, pl := s.decideKeys(p, model)
barred := len(cs) == 0 && len(pl.left) > 0 && !slices.ContainsFunc(pl.left, func(w Weighed) bool { return !w.Barred })
// and held to some accounts (#905): the decision model's provider must
// have one the key may use, the call spend landing on it as any's —
// and asked on one such key, not the provider's first, which may be
// one the key may not: of the keys in use, the first the key may use
// and that is let serve the model, the request refused without one.
// A provider with no key asks as it is: an account's tokens, or none
// at all
// have one the key may use and that is let serve the model, the call
// spend landing on it as any's, and only those are asked
if accWho, accHeld := accountHolds(r); accHeld {
if !accountServes(accWho, p, model) {
if !accountServes(accWho, p, model) || barred {
writeError(w, provider.Chat, http.StatusForbidden, keyAccountsError(accWho, asked))
return
}
if p.Account == nil && p.Key != "" {
kept := false
for _, k := range p.KeysOn() {
if q := p.WithKey(k); accountAllowed(accWho, candidate{p: q, model: model}) && p.AccountServes(q.AccountID(), model) {
p, kept = q, true
break
}
}
if !kept {
writeError(w, provider.Chat, http.StatusForbidden, keyAccountsError(accWho, asked))
return
}
var held bool
if cs, pl, held = allowedCandidates(accWho, cs, pl, nil); len(cs) == 0 && held {
writeError(w, provider.Chat, http.StatusForbidden, keyAccountsError(accWho, asked))
return
}
}
seat := decideSeat(p, model)
var used Usage
who := callerOf(r)
tr := s.trace.beginFor(r, Route{Time: start, Agent: who.agent, Session: sessionOf(r.Header), Model: asked, Provider: p.ID,
Order: []Weighed{seat}, Tries: []Try{{ID: seat.ID, Model: model, Start: start}}})
end := func(status int, msg string, tokens int) {
ms := time.Since(start).Milliseconds()
s.trace.update(tr, func(t *Route) {
try := &t.Tries[0]
try.Done, try.Status, try.Millis, try.Error = true, status, ms, msg
if status >= 400 {
try.Fail = failure(status, []byte(msg))
}
t.Done, t.Status, t.Error, t.Millis, t.Tokens = true, status, msg, ms, tokens
t.Usage = routeUsage(p.ID, model, used)
})
}
status, b, header, err := s.postDecide(r.Context(), p, model, body)
ctype := header.Get("Content-Type")
if err != nil {
writeError(w, provider.Chat, http.StatusBadGateway, err.Error())
end(http.StatusBadGateway, err.Error(), 0)
if barred {
writeError(w, provider.Chat, http.StatusForbidden, barredError(asked, pl.left))
return
}
var use struct {
Model string `json:"model"` // the one that answered, when the reply says
Usage struct {
Input int `json:"input_tokens"`
Output int `json:"output_tokens"`
} `json:"usage"`
cs = probeOne(cs) // of those resting, only the one back soonest (#1799)
if len(cs) == 0 {
writeError(w, provider.Chat, http.StatusServiceUnavailable, fmt.Sprintf("no key or account of %s may be asked %s now", p.Name, model))
return
}
_ = decodeJSON(b, &use)
errMsg := ""
if status >= 300 {
errMsg = provider.APIError(b, fmt.Sprintf("%d %s", status, http.StatusText(status)))
}
tokens := use.Usage.Input + use.Usage.Output
used = Usage{Input: use.Usage.Input, Output: use.Usage.Output}
var keyID, keyName string
if p.Account == nil && p.Key != "" {
keyID, keyName = provider.KeyID(p.Key), p.KeyName
}
appendUsage(r, usage.Record{RouteID: tr.ID, Time: start, Agent: who.agent, Via: who.via, Provider: p.ID, Host: p.Where(), Model: model, Requested: asked, Served: use.Model,
ProviderKeyID: keyID, ProviderKeyName: keyName, ProviderAccount: accountOf(p),
Input: use.Usage.Input, Output: use.Usage.Output, Millis: time.Since(start).Milliseconds(), Status: status})
end(status, errMsg, tokens)
if ctype == "" || status < 300 {
ctype = "application/json"
}
w.Header().Set("Content-Type", ctype)
w.WriteHeader(status)
w.Write(b)
}
// decideSeat is the one account a System One request is sent to: a decision
// provider has no pool of conversation keys, only the key it is asked with.
func decideSeat(p provider.Provider, model string) Weighed {
w := Weighed{ID: p.ID, Provider: p.ID, Name: p.Name, Icon: p.Icon, Preset: p.Preset, Model: model, Kind: "provider"}
if p.Key != "" {
w.Kind, w.Who = "key", p.KeyName
if w.Who == "" {
w.Who = provider.Mask(p.Key)
}
}
return w
s.serveDecideTries(w, r, body, asked, start, cs, pl, nil)
}
// withEffort asks a request, in the client's own API, for reasoning at
+44 -3
View File
@@ -129,9 +129,30 @@ func (s *Server) serveDecisionGroup(w http.ResponseWriter, r *http.Request, body
writeError(w, provider.Chat, http.StatusServiceUnavailable, fmt.Sprintf("no key or account of the group %s's decision models may serve them now", g.Name))
return
}
s.serveDecideTries(w, r, body, asked, start, cs, pl, groupRef(g, ms))
}
// decideKeys are a decision provider's keys or accounts that may be asked
// model, in its own routing's order (Smart, In order, In turn…), those
// resting after a failure behind the rest — planned as a chat's are, its
// fallbacks left out: a provider of several keys asked by itself, as a
// group's classifier or at /v1/systemone, fails over among them as a
// decision group's members do (fflake33 on Discord: a TypeSafe Jev key
// out of quota was asked on every turn, the next never).
func (s *Server) decideKeys(p provider.Provider, model string) ([]candidate, planned) {
p.Fallback = nil
return s.plan(p, model, provider.Chat)
}
// serveDecideTries answers a System One request with cs, a decision
// group's keys and accounts or one decision provider's, each in turn until
// one answers, the last one's answer passed on: one that fails as a chat's
// try would rests, and every try is a Try of one route (group is the
// group it was asked by, nil for a provider).
func (s *Server) serveDecideTries(w http.ResponseWriter, r *http.Request, body []byte, asked string, start time.Time, cs []candidate, pl planned, group *GroupRef) {
who := callerOf(r)
tr := s.trace.beginFor(r, Route{Time: start, Agent: who.agent, Session: sessionOf(r.Header), Model: asked, Provider: cs[0].p.ID,
Group: groupRef(g, ms), Order: pl.order, Left: pl.left})
Group: group, Order: pl.order, Left: pl.left})
var skipped []string
for i, c := range cs {
last := i == len(cs)-1
@@ -255,10 +276,30 @@ func (s *Server) askDecisionGroup(model string, intents []string, prev before, e
if len(cs) == 0 {
return verdict{}, true, fmt.Errorf("no decision model of the group %s can be asked now", g.Name)
}
v, err = s.askDecideTries(cs, intents, prev, effort, text)
return v, true, err
}
// askDecider is askClassifier for one decision provider's model: its keys
// or accounts in its routing's order (decideKeys), each asked until one
// answers, as a decision group's are.
func (s *Server) askDecider(p provider.Provider, model string, intents []string, prev before, effort bool, text string) (verdict, error) {
cs, _ := s.decideKeys(p, model)
cs = probeOne(cs) // of those resting, only the one back soonest (#1799)
if len(cs) == 0 {
return verdict{}, fmt.Errorf("no key or account of %s may be asked %s now", p.Name, model)
}
return s.askDecideTries(cs, intents, prev, effort, text)
}
// askDecideTries asks each of cs as Jev is (askJev) until one answers, the
// one that failed resting as it would for a chat; the last one's error
// when none does.
func (s *Server) askDecideTries(cs []candidate, intents []string, prev before, effort bool, text string) (v verdict, err error) {
for _, c := range cs {
if v, err = s.askJev(c.p, c.model, intents, prev, effort, text); err == nil {
servedCandidate(c, 0)
return v, true, nil
return v, nil
}
var refused decideRefused
var answer answerError
@@ -271,5 +312,5 @@ func (s *Server) askDecisionGroup(model string, intents []string, prev before, e
s.decideFailed(c, http.StatusBadGateway, nil, []byte(err.Error()))
}
}
return verdict{}, true, err
return verdict{}, err
}
+70
View File
@@ -177,3 +177,73 @@ func TestDecisionGroupClassifierFailsOver(t *testing.T) {
t.Fatalf("after the rest asked %v", asked)
}
}
// One decision provider of several keys (fflake33 on Discord: TypeSafe Jev,
// Smart, a key out of quota) is asked over its keys in its routing's
// order, at /v1/systemone and as a group's classifier, as a decision
// group's members are: the key refused rests, the next answers, and the
// next request asks the one that answered first.
func TestDecisionProviderKeysFailOver(t *testing.T) {
for _, routing := range []string{"", provider.Ordered} {
t.Run("routing="+routing, func(t *testing.T) {
fresh(t)
f := &decideFleet{status: map[string]int{}}
up := f.serve()
defer up.Close()
for _, p := range []provider.Provider{
{ID: "jev", Name: "TypeSafe Jev", Key: "k1", Keys: []provider.KeyAccount{{Key: "k2"}}, Decide: up.URL + "/v1", Routing: routing},
{ID: "judge", Name: "Judge", Key: "c1", Keys: []provider.KeyAccount{{Key: "c2"}}, Decide: up.URL + "/v1", Routing: routing},
} {
if err := provider.Save(p); err != nil {
t.Fatal(err)
}
}
s := New()
call := func() *httptest.ResponseRecorder {
rec := httptest.NewRecorder()
req := httptest.NewRequest("POST", "/v1/systemone", strings.NewReader(`{"model":"jev/jev-latest","state":{"message":"hi"},"questions":{"intent":{"type":"choice"}}}`))
req.Header.Set("Authorization", "Bearer magpie")
s.Handler().ServeHTTP(rec, req)
return rec
}
// the first key out of quota: the second answers
f.set("k1", 429)
if rec := call(); rec.Code != 200 || !strings.Contains(rec.Body.String(), `"choice":"bug"`) {
t.Fatalf("systemone: %d %s", rec.Code, rec.Body)
}
if got := strings.Join(f.took(), ","); got != "k1,k2" {
t.Fatalf("asked %s, want k1,k2", got)
}
r := s.trace.routes[len(s.trace.routes)-1]
if r.Model != "jev/jev-latest" || r.Group != nil || !r.Done || r.Status != 200 || len(r.Tries) != 2 || r.Tries[0].Rest == nil || r.Tries[1].Rest != nil {
t.Fatalf("route %+v", r)
}
if len(r.Usage) != 1 || r.Usage[0].Provider != "jev" {
t.Fatalf("usage %+v", r.Usage)
}
// it rests: the next request asks the second alone
if rec := call(); rec.Code != 200 {
t.Fatalf("again: %d %s", rec.Code, rec.Body)
}
if got := strings.Join(f.took(), ","); got != "k2" {
t.Fatalf("again asked %s, want k2", got)
}
// as a group's classifier, the same
f.set("c1", 429)
if v, err := s.askClassifier("judge/jev-latest", []string{"feature", "bug"}, before{}, false, "fix this"); err != nil || v.Intent != "bug" {
t.Fatalf("classify: %+v %v", v, err)
}
asked := f.took()
if len(asked) < 2 || asked[0] != "c1" || asked[len(asked)-1] != "c2" {
t.Fatalf("classifier asked %v, want c1 then c2", asked)
}
if _, err := s.askClassifier("judge/jev-latest", []string{"feature", "bug"}, before{}, false, "fix this"); err != nil {
t.Fatal(err)
}
if asked := f.took(); len(asked) == 0 || asked[0] != "c2" {
t.Fatalf("classifier after the rest asked %v, want c2 first", asked)
}
})
}
}