diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index 7bf0d8d7b..88297b28b 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -159,7 +159,7 @@ recorded as a prediction failure (`noPrediction`). - Rules and image inputs are handled here too. - A rule is decided as a user's turn begins and held for the rest of it (`ruleFor`, [`rules.go`](../../internal/gateway/rules.go)). What counts as the user's own words is one helper, `userWords`/`userSaid` in [`prompt.go`](../../internal/gateway/prompt.go), which the turn count (`turnIn`), the classifier's question (`userText`), the conversation's key (`firstWords`, in `ruleKey` and the affinity scope), Copilot's Auto (`lastUserText`) and the prompt breakdown's turns (`userSays`) all go by. It drops `` blocks (a `source=` attribute too) and any text that begins as an agent writes for the model alone: Codex's ``, ``, ``, ``, `` and `# AGENTS.md instructions for …`; Claude Code's and ZCode's ``, ``, agent lists ("Available agent types …", "New agent types are now available …"), TodoWrite and task-tool nudges and rewind notices; ZCode's ``; the Codex app's ``. The Codex app's context before `## My request (for Codex):` is dropped and what follows it kept (the `injected` list beside `agentsFor`). A user message with nothing of the user's in it (and no image or file) begins no turn: after an answer or a tool round it carries the turn on (`within`), so the turn's rule and stick hold and the classifier isn't asked; right after the user's words it leaves their turn as it began. The classifier is asked about the last user message that has words of the user's, only those words (`userText`: past 4000 runes, its first 3000 and last 1000). It is told what came before it too (`turnBefore`, @HirotaNagai on X: a short follow-up said alone, 继续 or fix that, came out the hardest kind): the user's message before it, the same way and cut to 1000 runes (`priorCap`: the first 750 and the last 250), and the assistant's last reply between the two, its text parts alone and their last 1000 runes. A tool call's arguments, a tool's result, thinking, a search's hits and the system prompt are never in either, and a reply of only tool calls is none. Jev gets them in its `state` as `previous_user_message` and `previous_assistant_reply` beside `message`, `previous_message_kind` and `previous_message_reasoning`, each only when there is one, and its intent, level and effort instructions name the ones there are (`jevState`, `priorAsk` in [`decide.go`](../../internal/gateway/decide.go)); a classifier asked in words gets them in `` and `` before `` (`writePrior`). Both come from the request the rules parsed, so Privacy masks them as it masks the message, and the answer kept for a message is kept for it with what came before (`classify`'s key). `TestTurnBeforeEachProtocol`, `TestTurnBeforeCuts`, `TestJevIsToldWhatCameBefore`, `TestChatClassifierIsToldWhatCameBefore`, `TestClassifyKeepsAnAnswerPerTurnBefore`, `TestJevSeesTheTurnBefore`. `firstWords` hashes the words of the first user message that has any, so an instruction file or notice the agent changes beside them doesn't move the conversation to a new key and lose its stick mid-turn (#1826: ZCode's TodoWrite nudge classified as a new, harder turn, and three keys for one ZCode session). `TestTurnInSkipsWhatTheAgentPutIn`, `TestUserTextSkipsWhatTheAgentPutIn`, `TestFirstWordsAreWhatTheUserSaid`, `TestIntentHoldsPastWhatTheAgentPutIn`. - A rule's members go first (`ruleOver`, `applyRule`): the members it names, in order, then those the matching rules after it name (`ruleOrder`), each not resting, then the group's others to fail over to. A member that is a group in the group is one member here: its models keep the order the group's own routing planned them, where ranking each by the group's listed order pinned a rotate group's first member on every request the rule put it first (#2407, `TestRuleNamingARotateGroupKeepsItsTurns`). That holds within the turn too, at the group's rule and at each nested group's (`nestedRules`): the one the turn stays on (affinity) stays first while it is of the rule's member that goes first, and the member's others follow it ahead of the group's others, so a failure fails over within the member the rule chose before going outside it. One the turn was kept on outside that member, which took over when the member failed, isn't held there: once one of the member is out of its rest, the turn's next request goes back to it (`Affinity.Why` `rule`). Before #1946 (XcodeFish) a held rule's order wasn't applied to a kept turn at all: a coding-quality member failing mid-turn failed over to coding-fast, the parent's first, and the turn stayed there. `TestHeldRuleFailsOverWithinItsMember`. Two groups in the group may share a model (the same provider, model and effort): it is asked once a request, where the walk met it first, and `provider.Member.Also` keeps its later places, each with its own path, `At` (its place in the walk) and Fast. A rule naming the later group has the model as that group does (`Member.In`, `membersNamed`), in that group's own order, and the nested rules below it, Fast and the first token's wait go by that group's way down (`homed`, `homeCands`). Before #2361 (davisjiahao) such a rule found none of the shared models, read unready, and the group ahead of it answered. A pause rule naming the later group still leaves a shared model to the group ahead of it. `rule_shared_test.go`. - - A classifier's timeout is global (`Settings.ClassifyTimeout`, JSON `classifyTimeout`, seconds, in [`settings.go`](../../internal/settings/settings.go)). Missing or 0 keeps the 8-second default; saving accepts 1–60 seconds or 0 and rejects negative values or values above 60. `Settings.ClassifyWait` bounds a hand-edited value above 60 to 60 seconds and uses the default for a value below 1. `classifyTimeout()` reads it for each call: both `askChat` in [`classify.go`](../../internal/gateway/classify.go) and `askJev` in [`decide.go`](../../internal/gateway/decide.go) give the classifier that time, including its provider's failover. Settings → Models → Replies → *Intent classifier timeout* (`renderReplies` in [`app.js`](../../internal/gui/assets/app.js)) offers 8, 15, 30 and 60 seconds and shows a custom valid value as its own choice. A change applies to the next classifier call, with no restart; the existing fallback, 30-second cooldown (`classifyRest`) and 10-minute answer cache (`classifyKeep`) still apply. + - A classifier's timeout is global (`Settings.ClassifyTimeout`, JSON `classifyTimeout`, seconds, in [`settings.go`](../../internal/settings/settings.go)). Missing or 0 keeps the 8-second default; saving accepts 1–60 seconds or 0 and rejects negative values or values above 60. `Settings.ClassifyWait` bounds a hand-edited value above 60 to 60 seconds and uses the default for a value below 1. `classifyTimeout()` reads it for each call: both `askChat` in [`classify.go`](../../internal/gateway/classify.go) and `askJev` in [`decide.go`](../../internal/gateway/decide.go) give the classifier that time, including its provider's failover. A request shares one such wait across every routing group it goes through (`Server.askWaited`, from the first classifier asked): a nested ruled group asked with less left gets only that, one asked once it is spent goes by its order at once (`waitSpent`, "spent by the routing group above"), and a classifier or decision key cut short that way is not rested (`cutShort`). Each nested level had a whole wait of its own before, so three ruled levels whose classifiers didn't answer held a request past the unrouted watch's 2 minutes, a 504 (heatonz on Discord, v0.1.2215; `TestNestedGroupsShareTheClassifierWait`, `TestDecisionKeyCutShortIsNotRested`). Settings → Models → Replies → *Intent classifier timeout* (`renderReplies` in [`app.js`](../../internal/gui/assets/app.js)) offers 8, 15, 30 and 60 seconds and shows a custom valid value as its own choice. A change applies to the next classifier call, with no restart; the existing fallback, 30-second cooldown (`classifyRest`) and 10-minute answer cache (`classifyKeep`) still apply. - A classifier that can't say which kind a turn is (an error, no answer within `classifyTimeout()`, an answer that isn't a number, or resting `classifyRest` after a failure) leaves a turn whose conversation had an intent, still one of this turn's, with that intent (`Classified.Fallback` is `previous`, its `Error` kept), so the turn goes where the turn before went rather than to the group's first member; with no intent before, no rule with an intent matches, as before. The Routing page says the turn kept it (`classWhy`). The turn's decision itself (`turnRules`) is kept in memory only: after a restart a turn under way waits for the next one and the stick holds it meanwhile. `TestIntentClassifierFailsKeepsThePreviousIntent`, `routing-intent-fallback.test.cjs`. - A group's classifier is asked only for that group's own turns: a request whose model is the group (`group/`, its bare name, or a stand-in an agent's config names it by: Claude Code's tiers, Codex's bare name), or a group in it that its rules or order put first (`nestedRules`). A request for another model or group asks it nothing. The Routing page's card says why the classifier couldn't say the last time *that group* asked it (`GroupClassifierFailure`, kept by `classifiedFor` in `ruleFor`): the classifier's own words and time, resting or not, until it answers that group, and nothing once the group's classifier changed. Keyed by the classifier model alone, a group nothing reached showed another group's failure on a classifier they share (jjt on Discord). A classifier on a subscription out of its quota is not asked of the vendor again until the reset: out of quota, its account rests until the quota comes back (`restAfter`: the time the refusal names, else when the account's window renews), and the classifier's call meanwhile gets that refusal back from magpie, at most once each `classifyRest`. `TestClassifierFailureIsTheGroupsOwn`. - The classifier's requests are magpie's own (#1839). Asked in words, they go out with `RouterAgent`'s User-Agent (`magpie-router/1`), so their records' agent is magpie and `callKind` marks them `routing`; a decision model's (Jev, System One) record is written with `Kind: "routing"` too. They go to the same key or account as any other request and count in its totals, while `usage.Group.Own` (`Record.ByMagpie`: agent `magpie` or one of its `magpie-` User-Agents, with search's and image description's) says how many of an account's, key's or model's calls, tokens and cost were magpie's own. A classifier set to a subscription's model (`modelRef.Sub`, or a group whose first member is one) asks that subscription as every turn begins, twice when it picks both intent and effort in words; the Routing page says so beside it (`classifierSub` in `plugins/routing/client.js`). `TestIntentRoutesATurn`, `TestJevPicksTheIntent`, `TestSummaryCountsMagpiesOwnCallsApart`, `TestByMagpie`, `TestServedRefSaysASubscription`, `own-requests.test.cjs`. diff --git a/internal/gateway/classify.go b/internal/gateway/classify.go index 190782585..9d3cfb152 100644 --- a/internal/gateway/classify.go +++ b/internal/gateway/classify.go @@ -120,6 +120,19 @@ type classifyFailure struct { // numbers: it is up, so it isn't left to rest for it. type answerError struct{ error } +// waitSpent is a classifier not asked, or cut off before its own wait +// was out, because the groups above it in the request spent the +// request's one classifier wait (askWaited): nothing says it is down, so +// it isn't left to rest for it. +type waitSpent struct{ error } + +// cutShort is the waitSpent of a classifier given wait, what was left of +// the request's classifier wait full, that didn't answer in it. +func cutShort(model string, wait, full time.Duration) error { + return waitSpent{fmt.Errorf("%s gave no answer in the %s left of the request's classifier wait of %s, spent by the routing group above", + model, wait.Round(time.Millisecond), full)} +} + // classify is ask's answer for the message, from what was asked before // when it can be: the same message and intents within classifyKeep. A // classifier that failed is left to rest for classifyRest rather than @@ -160,7 +173,7 @@ func classify(ask classifier, model string, intents []string, prev before, effor c.err = err if err != nil { f := classifyFailure{err: err.Error(), at: time.Now()} - if !errors.As(err, new(answerError)) { + if !errors.As(err, new(answerError)) && !errors.As(err, new(waitSpent)) { classified.failed[model] = f } if was, ok := classified.last[model]; !ok || was.err != f.err { @@ -405,26 +418,50 @@ func classifyEffort(model string) string { return fitEffort("none", levels) } +// askWaited is the classifier a request's routing groups ask, each +// question a wait ctx's watch knows of (noteWait): a routing group's +// decision model is asked before the request's route is begun. Every +// group the request goes through, nested ones included, shares the one +// classifier wait Settings gives, from the first one asked: each level +// given the whole wait held a request through three ruled groups three +// waits before routing it, past the unrouted watch's 2 minutes (heatonz +// on Discord, v0.1.2215). A group asked once the wait is spent goes by +// its own order at once, as for a classifier that didn't answer. +func (s *Server) askWaited(ctx context.Context) classifier { + var mu sync.Mutex + var until time.Time + return func(model string, intents []string, prev before, effort bool, text string) (verdict, error) { + mu.Lock() + now := time.Now() + if until.IsZero() { + until = now.Add(classifyTimeout()) + } + left := until.Sub(now) + mu.Unlock() + if left <= 0 { + return verdict{}, waitSpent{fmt.Errorf("%s not asked: the request's classifier wait of %s was spent by the routing group above", model, classifyTimeout())} + } + defer noteWait(ctx, "decision model")() + return s.askClassifierIn(left, model, intents, prev, effort, text) + } +} + // askClassifier asks a decision provider's model through its own API, and // any other model through the gateway itself, as a client would: which of // intents the message is and, when effort, how hard the turn is, each in a // call of its own, at once. -// askWaited is ask with each question a wait ctx's watch knows of -// (noteWait): a routing group's decision model is asked before the -// request's route is begun. -func askWaited(ctx context.Context, ask classifier) classifier { - return func(model string, intents []string, prev before, effort bool, text string) (verdict, error) { - defer noteWait(ctx, "decision model")() - return ask(model, intents, prev, effort, text) - } +func (s *Server) askClassifier(model string, intents []string, prev before, effort bool, text string) (verdict, error) { + return s.askClassifierIn(classifyTimeout(), model, intents, prev, effort, text) } -func (s *Server) askClassifier(model string, intents []string, prev before, effort bool, text string) (verdict, error) { +// askClassifierIn is askClassifier given wait to answer in, all of the +// classifier's wait or what a request has left of it (askWaited). +func (s *Server) askClassifierIn(wait time.Duration, 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.askDecider(p, m, intents, prev, effort, text) + return s.askDecider(wait, 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 { + if v, ok, err := s.askDecisionGroup(wait, model, intents, prev, effort, text); ok { return v, err } var v verdict @@ -435,7 +472,7 @@ func (s *Server) askClassifier(model string, intents []string, prev before, effo go func() { defer wg.Done() var a string - if a, ierr = s.askChat(model, classifyBody(model, classifyEffort(model), intents, prev, text)); ierr == nil { + if a, ierr = s.askChat(wait, model, classifyBody(model, classifyEffort(model), intents, prev, text)); ierr == nil { v.Intent, ierr = readIntent(a, intents) } }() @@ -445,7 +482,7 @@ func (s *Server) askClassifier(model string, intents []string, prev before, effo go func() { defer wg.Done() var a string - if a, eerr = s.askChat(model, effortBody(model, classifyEffort(model), prev, text)); eerr == nil { + if a, eerr = s.askChat(wait, model, effortBody(model, classifyEffort(model), prev, text)); eerr == nil { v.Effort, v.Score, eerr = readEffort(a) } }() @@ -513,9 +550,8 @@ func readEffort(answer string) (string, float64, error) { } // askChat sends a chat model body through the gateway and returns its -// answer's text. -func (s *Server) askChat(model string, body []byte) (string, error) { - wait := classifyTimeout() +// answer's text, if it comes in wait. +func (s *Server) askChat(wait time.Duration, model string, body []byte) (string, error) { ctx, cancel := context.WithTimeout(context.Background(), wait) defer cancel() r, err := http.NewRequestWithContext(ctx, http.MethodPost, "http://magpie/v1/chat/completions", nil) @@ -527,6 +563,9 @@ func (s *Server) askChat(model string, body []byte) (string, error) { w := httptest.NewRecorder() s.serve(w, r, provider.Chat, body) if ctx.Err() != nil { + if full := classifyTimeout(); wait < full { + return "", cutShort(model, wait, full) + } return "", fmt.Errorf("%s gave no answer in %s", model, wait) } var out struct { diff --git a/internal/gateway/decide_group.go b/internal/gateway/decide_group.go index e711a5df2..c017c98d4 100644 --- a/internal/gateway/decide_group.go +++ b/internal/gateway/decide_group.go @@ -261,7 +261,7 @@ func (e decideRefused) Unwrap() error { return e.err } // accounts in the group's order, each asked as Jev is (askJev) until one // answers, the one that failed resting as it would for a chat. ok is false // when model names no decision group. -func (s *Server) askDecisionGroup(model string, intents []string, prev before, effort bool, text string) (v verdict, ok bool, err error) { +func (s *Server) askDecisionGroup(wait time.Duration, model string, intents []string, prev before, effort bool, text string) (v verdict, ok bool, err error) { if !provider.IsGroupRef(model) { return verdict{}, false, nil } @@ -276,20 +276,20 @@ 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) + v, err = s.askDecideTries(wait, 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) { +func (s *Server) askDecider(wait time.Duration, 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) + return s.askDecideTries(wait, cs, intents, prev, effort, text) } // askDecideTries asks each of cs as Jev is (askJev) until one answers, the @@ -297,9 +297,10 @@ func (s *Server) askDecider(p provider.Provider, model string, intents []string, // when none does. Every try shares the one classifier's wait, as Settings // says it is given, its failover included: a try each given the whole // wait held a request N waits before routing it (Jason on Discord, a 2m -// hold). -func (s *Server) askDecideTries(cs []candidate, intents []string, prev before, effort bool, text string) (v verdict, err error) { - wait := classifyTimeout() +// hold). wait is that wait, or what a request has left of it (askWaited): +// a try cut off by less than the whole wait is not rested for it. +func (s *Server) askDecideTries(wait time.Duration, cs []candidate, intents []string, prev before, effort bool, text string) (v verdict, err error) { + full := classifyTimeout() ctx, cancel := context.WithTimeout(context.Background(), wait) defer cancel() for _, c := range cs { @@ -313,6 +314,9 @@ func (s *Server) askDecideTries(cs []candidate, intents []string, prev before, e var refused decideRefused var answer answerError switch { + case wait < full && ctx.Err() != nil && !errors.As(err, &refused) && !errors.As(err, &answer): + // cut off by the request's wait running out, not its own + return verdict{}, cutShort(c.p.Name+"/"+c.model, wait, full) case errors.As(err, &refused): s.decideFailed(c, refused.status, refused.header, refused.body) case errors.As(err, &answer), errors.Is(err, context.Canceled): diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index 87df60506..aa8e2751f 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -2200,12 +2200,11 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro // and the second, its verdict kept or the classifier resting, passed // (CyberCaius on Discord, v0.1.1847). It goes by the group's order, // as a model's check does. - ask := s.askClassifier - if r.Header.Get("User-Agent") == RouterAgent || desktopCheck { - ask = nil - } else { - // a wait magpie knows of, before a route is begun (unrouted.go) - ask = askWaited(r.Context(), ask) + var ask classifier + if r.Header.Get("User-Agent") != RouterAgent && !desktopCheck { + // a wait magpie knows of, before a route is begun (unrouted.go), + // one for every group the request goes through + ask = s.askWaited(r.Context()) } if isGroup && slices.ContainsFunc(ms, func(m provider.Member) bool { return g.Ruled() || slices.ContainsFunc(m.Via, provider.Group.Ruled) diff --git a/internal/gateway/nested_classify_wait_test.go b/internal/gateway/nested_classify_wait_test.go new file mode 100644 index 000000000..4bdf3e3cc --- /dev/null +++ b/internal/gateway/nested_classify_wait_test.go @@ -0,0 +1,142 @@ +package gateway + +import ( + "io" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + "time" + + "github.com/yetone/magpie/internal/provider" +) + +// Routing groups nested in one another, each with rules a decision model +// judges, share one classifier wait for the request, not one each +// (heatonz on Discord, v0.1.2215): each level asked its own classifier +// with the whole wait, so a request through three ruled levels whose +// classifiers didn't answer was held three waits before it was routed, +// past the unrouted watch's bar, and answered 504 "held this request for +// 2m0s without routing it". A level asked after the wait is spent goes by +// its group's order at once, and a classifier cut short by the shared +// wait isn't rested for it: it had less than its own wait. +func TestNestedGroupsShareTheClassifierWait(t *testing.T) { + fresh(t) + resetClassified(t) + was := classifyUnit + classifyUnit = 60 * time.Millisecond // the 8 seconds unset are 480ms + t.Cleanup(func() { classifyUnit = was }) + // three waits are 1.44s, held past 1.1s; one wait routes at ~0.5s + unroutedLimits(t, 50*time.Millisecond, 1100*time.Millisecond) + unknownLimit(t, 30*time.Second) + + a := &keyed{} + serveOn(t, "a", "ka", []string{"m"}, a) + var mu sync.Mutex + asked := map[string]int{} + stop := make(chan struct{}) + serveOn(t, "c", "kc", []string{"cls1", "cls2", "cls3"}, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + b, _ := io.ReadAll(r.Body) + mu.Lock() + for _, m := range []string{"cls1", "cls2", "cls3"} { + if strings.Contains(string(b), `"`+m+`"`) { + asked[m]++ + } + } + mu.Unlock() + // never answers, as a classifier that is down or overloaded + select { + case <-r.Context().Done(): + case <-stop: + } + })) + t.Cleanup(func() { close(stop) }) // runs before the server closes + for _, g := range []provider.Group{ + {ID: "inner", Name: "Inner", Members: []string{"a/m"}, Routing: provider.Ordered, + Classifier: "c/cls3", Rules: []provider.Rule{{Use: "a/m", Intent: "bug"}}}, + {ID: "mid", Name: "Mid", Members: []string{"group/inner"}, Routing: provider.Ordered, + Classifier: "c/cls2", Rules: []provider.Rule{{Use: "group/inner", Intent: "bug"}}}, + {ID: "outer", Name: "Outer", Members: []string{"group/mid"}, Routing: provider.Ordered, + Classifier: "c/cls1", Rules: []provider.Rule{{Use: "group/mid", Intent: "bug"}}}, + } { + if err := provider.SaveGroup(g); err != nil { + t.Fatal(err) + } + } + s := New() + t0 := time.Now() + code, body := postAs(t, s, "nest1", `{"model":"group/outer","messages":[{"role":"user","content":"fix this crash"}]}`) + took := time.Since(t0) + if code != 200 || !strings.Contains(body, "from ka") { + t.Fatalf("after %s: %d %s", took, code, body) + } + r := lastRoute(s) + if r.Rule == nil || r.Rule.Classified == nil || !strings.Contains(r.Rule.Classified.Error, "no answer") { + t.Fatalf("the outer group's classifier: %+v", r.Rule) + } + if len(r.Nested) != 2 { + t.Fatalf("nested rules: %+v", r.Nested) + } + for _, n := range r.Nested { + if n.Rule == nil || n.Rule.Classified == nil || !strings.Contains(n.Rule.Classified.Error, "spent") { + t.Fatalf("%s's classifier, after the wait was spent above it: %+v", n.Group, n.Rule) + } + } + mu.Lock() + if asked["cls1"] == 0 { + t.Errorf("the outer classifier wasn't asked: %v", asked) + } + mu.Unlock() + // only the classifier given its whole wait rests for not answering + classified.Lock() + _, rest1 := classified.failed["c/cls1"] + _, rest2 := classified.failed["c/cls2"] + _, rest3 := classified.failed["c/cls3"] + classified.Unlock() + if !rest1 || rest2 || rest3 { + t.Fatalf("resting: cls1 %v cls2 %v cls3 %v", rest1, rest2, rest3) + } +} + +// A decision model's key cut off by what a request had left of the +// classifier wait isn't rested for it: it was given less than its own +// wait, so the next request asks it first again. +func TestDecisionKeyCutShortIsNotRested(t *testing.T) { + fresh(t) + resetClassified(t) + was := classifyUnit + classifyUnit = 25 * time.Millisecond // the 8 seconds unset are 200ms + t.Cleanup(func() { classifyUnit = was }) + var mu sync.Mutex + var asked []string + stop := make(chan struct{}) + up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + mu.Lock() + asked = append(asked, strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ")) + mu.Unlock() + io.Copy(io.Discard, r.Body) + select { + case <-r.Context().Done(): + case <-stop: + } + })) + t.Cleanup(up.Close) + t.Cleanup(func() { close(stop) }) + if err := provider.Save(provider.Provider{ID: "jw", Name: "JW", Key: "w1", Keys: []provider.KeyAccount{{Key: "w2"}}, Decide: up.URL + "/v1"}); err != nil { + t.Fatal(err) + } + s := New() + _, err := s.askClassifierIn(50*time.Millisecond, "jw/jev-latest", []string{"feature", "bug"}, before{}, false, "fix this") + if err == nil || !strings.Contains(err.Error(), "left of the request's classifier wait") { + t.Fatalf("cut short: %v", err) + } + if _, err := s.askClassifier("jw/jev-latest", []string{"feature", "bug"}, before{}, false, "fix this"); err == nil { + t.Fatal("a decision model that never answers answered") + } + mu.Lock() + defer mu.Unlock() + if len(asked) != 2 || asked[0] != "w1" || asked[1] != "w1" { + t.Fatalf("asked %v: the key cut short was rested", asked) + } +}