diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index 6a646ec89..6c6df3492 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -40,7 +40,7 @@ served by a plugin are in [Provider and plugin ownership](provider-plugins.md). - A pause rule (`Rule.Pause`, `pause=`; John on Discord: a model of the group paused in its vendor's peak hours) leaves the model it names out of the group while it holds (`provider.PausedOut`, on `ruleClock`): the group's own rules and each nested group's on the way down to a member, a group named taking all its models, and a model named taking it wherever a group in the group has it (#625). It runs before planning, on every request rather than once a turn, so the model is not first, not a failover, and not kept by affinity, and comes back as soon as the hours end. It holds by hours, days and agents only (`cleanRules` refuses another condition), and is not a send-to rule: `Matches`, `MatchRule`, `ThenUses`, `Ruled` and the compaction rules leave it out. A send-to rule naming a paused model finds it unready and the group routes as without it. The trace keeps what was paused (`GroupRef.Paused`), and the Routing page says so. Every model paused answers 503 (`pausedError`) naming each rule. Embeddings go by the same pauses; manual groups have no rules (`Live`), so none pause there. `rules_pause_test.go`. 3. Candidates come from `planGroup` for a group or `plan` for a provider. They are filtered by `sealedReaders` and `allowedCandidates`. An account past its share is held out of the candidates (`capHeld`): a usage cap's share, each window at its own where the account gives it one (`AccountWindowCaps`, willz on Discord: 50% of the five hours, 40% of the week) and at the account's cap otherwise, or 100% of a window for a Codex account set not to spend its credits (`provider.HoldCaps`, `WindowCaps.Of`, `CodexNoCredits`). The account is held while any window is past its own share, and `cappedError` and the trace name the fullest such window's share and cap. When every candidate is held and one held for its credits spends its resets by itself, `autoReset` spends a reset on it and it is tried (`planned.held`); otherwise a capped or barred set returns `cappedError` or `barredError`. Then `affine` moves the conversation's last answerer first, unless it is resting or nearly used up. An `X-Magpie-Account` header (`AccountHeader`) pins the request to one account: only that account is tried, and when it can't answer the caller is told why. 4. The candidate loop calls `attempt` on each candidate in turn, through a `holdWriter`. The writer holds the reply until it is clearly passing. A candidate that fails before anything is sent rests (`failure`): out of credit for 30 minutes, out of quota until reset, rate limited until retry-after, otherwise a minute and longer on repeats. A 400, 403, 404 or 422 that says the model isn't served (`unservedWords`) and says nothing of quota, credit or a rate limit rests only that key's or account's model (`modelRefused`, keyed by `restID`, its backoff counted apart): its other models are still served first in order (#1235, SenseNova's 403 "model is not available in the current token plan"). A 400, 404, 410 or 422 that says the model is retired (`retiredWords`: OpenCode Zen's 410 `ModelDeprecated` "Model exo-free has been deprecated.", whose own model list still names it; MOMO on Discord) rests only that model the same way, is retryable so a group's next member or another provider of it is asked, and is remembered (`provider.Retire`, `retired.json` beside `providers.json`): the model leaves that provider's entries in the catalog (`buildEntries`), so /v1/models, every agent's model list and the found groups go without it, until a request on it is answered again (`Unretire` in `servedCandidate`) or a week has passed. A refresh of the vendor's list doesn't bring it back early, since that list is where it still is. A `provider/model` request for it is still sent. A subscription account that fails any other way with a window full, by magpie's latest reading of its windows, rests until that window renews. Both quota rests and window rests are held to `longestQuota` (8 days), so a reset time read wrong (a year off) doesn't bench the account for that long. The next candidate is then tried. A failed provider waits `fallbackCooldown` (1 minute) at the back. The vendor's safety filter refusing a reply rests nobody, whether it refuses the turn before any of the reply is said or once some of it has been said (`refused`, `refusedAfter`). The ChatGPT backend's 502 "response protection is unavailable" is about the request's content, not the account: the same history fails the same on each of its accounts and models. It rests nobody, isn't tried again after a moment, and isn't asked of the provider's other accounts or models; another provider left in a group is asked once (`protectionRefused`, `elsewhere`). One cause is known (#1270): a history that replays the backend's own `web_search_call` in a request that doesn't declare the `web_search` tool is refused so, whatever the account, model or turn (a plain turn, a thread's description, a compaction, Codex's own text compaction for a custom provider with `tools: []`). Every request to the ChatGPT backend with such a history therefore declares cached-only search (`{"type":"web_search","external_web_access":false}`, `provider.DeclareSearch`): an account's in `codexBody`, Codex's own sign-in relayed in `codexUpstreamOn`. It goes in the tools, or for Responses Lite (its header, `reasoning.context` `all_turns`, or an `additional_tools` item already there), which refuses a top-level `web_search`, in the `additional_tools` item. A request that offered no tools gets `tool_choice` `none` so the model can't search; one with a forced choice keeps it. A history without a search, or a request that declares search already, is relayed unchanged. siwc, API-key requests to openai.com and the legacy `/responses/compact` are left as they were. -5. The last candidate's error reaches the agent. A try that answered is recorded (`served`, `answered`) for routing, affinity and usage. +5. The last candidate's error reaches the agent, with one exception for a group (#1418, `patience.go`). When every member has failed in a way that passes (`busy`: 408, 500, 502, 503, 504 or 529 that isn't a proxy, a quota or response protection, or a 429 that is a short rate limit, not a plan or credit), and nothing of the reply has been sent, the members that failed so are asked again in turn after a pause (`replan`). The pause is `retryPause` doubled each round up to `replanLongest` (30s), and never shorter than the soonest Retry-After; a member whose Retry-After ends past the pause is asked after the others. This goes on for at most `replanRounds` (6) rounds and only while the group's `Patience` lasts, counted from the first time every member had failed, when the agent would have had the error (`waitFrom`; `Group.Waits`: 0 is `PatienceDefault`, 60s; -1, `PatienceOff`, turns it off; at most `PatienceLongest`, 240s). A pause that would end past the budget isn't taken, and the agent gets the error. While another member is busy too, the last one isn't first tried again alone (`passing`): the members take turns, and once the budget has begun, the same-one retries aren't taken either. While the budget lasts, the last candidate's failure is held (`newHoldWriter`), and a streaming agent is kept alive through the pause with SSE comments (`pauseAlive`). The try is traced with `Again` (the pause), `Replan` (how many are asked again) and `Patience` (the budget in seconds). The group editor's "Every member busy" row sets it. A plain provider keeps only the same-one retries `passing` gives the last one left. A try that answered is recorded (`served`, `answered`) for routing, affinity and usage. ## Constraints and failure behavior diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index ecc022520..a6b136983 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -1767,6 +1767,15 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro streams = strings.Contains(r.URL.Path, "streamGenerateContent") } gaveWay := map[string]bool{} // keys and accounts that gave way, full, to one free (laneMate) + // a group's members that failed in a way that passes are asked again, + // once each has been, for up to its Patience (#1418) + var patience time.Duration + if isGroup { + patience = g.Waits() + } + var busyNow []busyTry // the members of this round that failed so + rounds := 0 // the rounds they were asked again in + var waitFrom time.Time // when every member had first failed so for i := 0; i < len(cands); i++ { c := cands[i] if j := s.laneMate(cands, i, isGroup, gaveWay); j > i { @@ -1784,7 +1793,8 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro // for its allowance running out to be told as that one's error // and once the agent has the stream's headers from an earlier try's // keepalives, for a failure to be told as the stream's error - hw := newHoldWriter(w, !last || again < max(lastRetries, rateRetries) || other != nil || kept.sent || autoPicks(c) && repicked < 2) + hw := newHoldWriter(w, !last || again < max(lastRetries, rateRetries) || other != nil || kept.sent || autoPicks(c) && repicked < 2 || + patience > 0 && rounds < replanRounds && (waitFrom.IsZero() || time.Since(waitFrom) < patience)) // Claude's and GPT's reasoning is held for a refusal after it only // while another candidate could answer instead: the last one's // refusal isn't asked again, so holding it only kept a lone relay's @@ -2416,11 +2426,45 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro try.Fail, try.Rest = rest.Why, &rest s.trace.update(tr, func(t *Route) { t.Tries[len(t.Tries)-1] = try }) skipped = append(skipped, c.label()+": "+call.Error) + if patience > 0 && !hw.turnedAway && busy(hw.code(), hw.errBody()) { + busyNow = noteBusy(busyNow, c, hw.header) + } continue } - if wait, ok := passing(hw.code(), hw.header, hw.errBody(), again); ok && !protected && !hw.turnedAway && hw.failed() { + if _, same := passing(hw.code(), hw.header, hw.errBody(), again); last && patience > 0 && !protected && !hw.turnedAway && !hw.refused && hw.failed() && busy(hw.code(), hw.errBody()) && + (len(busyNow) > 0 || !same) { + // every member has failed, each in a way that passes — busy, + // overloaded, rate limited for a moment — with nothing of a + // reply sent: after a pause, longer each round and no shorter + // than a Retry-After, those back by then are asked again in + // turn, while the group's Patience for the request lasts + // (#1418: Codex's turn ended on server_is_overloaded, to be + // told "continue" by hand). Another member busy too, this one + // isn't asked again alone first, as the last one left is: they + // take turns. The patience is counted from the first time + // every member had failed, when the agent would have had the + // error + if waitFrom.IsZero() { + waitFrom = time.Now() + } + busyNow = noteBusy(busyNow, c, hw.header) + if next, wait, ok := replan(busyNow, rounds, waitFrom.Add(patience)); ok { + try.Fail, try.Again, try.Replan, try.Patience = failureOf(c, hw.code(), hw.errBody()), wait.Milliseconds(), len(next), int(patience/time.Second) + s.trace.update(tr, func(t *Route) { t.Tries[len(t.Tries)-1] = try }) + skipped = append(skipped, c.label()+": "+call.Error) + rounds, busyNow = rounds+1, nil + if pauseAlive(r.Context(), w, kept, streams, start, wait) { + cands = append(cands[:i+1:i+1], next...) + continue + } + call.Status, call.Error = 499, "the agent canceled the request" + break + } + } + if wait, ok := passing(hw.code(), hw.header, hw.errBody(), again); ok && !protected && !hw.turnedAway && hw.failed() && waitFrom.IsZero() { // nobody else is left: the same one again, after a moment (not - // what Antigravity turned away: it turns it away again) + // what Antigravity turned away: it turns it away again; nor + // once the group's patience is spent) try.Fail, try.Again = failureOf(c, hw.code(), hw.errBody()), wait.Milliseconds() s.trace.update(tr, func(t *Route) { t.Tries[len(t.Tries)-1] = try }) skipped = append(skipped, c.label()+": "+call.Error) diff --git a/internal/gateway/overload_test.go b/internal/gateway/overload_test.go index 18601010c..901ee3a44 100644 --- a/internal/gateway/overload_test.go +++ b/internal/gateway/overload_test.go @@ -2,7 +2,9 @@ package gateway import ( "io" + "net/http" "net/http/httptest" + "slices" "strings" "testing" "time" @@ -63,3 +65,81 @@ func TestLeadOnlyStreamHeldWhileKeptAlive(t *testing.T) { t.Fatalf("a stream whose agent takes no comment held past %s", holdLongest) } } + +// Every member of a group overloaded at once (#1418: plus-B, then +// sub2api, each server_is_overloaded) isn't the agent's error while the +// group's patience lasts: after a pause each is asked again, and the one +// back by then answers. Before, the last one's 529 ended Codex's turn. +// Patience off, the agent gets it as before; a Retry-After past the +// patience isn't waited for. +func TestGroupWaitsOutEveryMemberOverloaded(t *testing.T) { + overloaded := reply{529, "", `{"error":{"message":"Our servers are currently overloaded. Please try again later.","code":"server_is_overloaded"}}`} + group := func(patience int) (*scripted, *scripted) { + fresh(t) + a := &scripted{replies: []reply{overloaded, {200, "", chatOK}}} + b := &scripted{replies: []reply{overloaded}} + scriptedOn(t, "a", provider.Chat, a) + scriptedOn(t, "b", provider.Chat, b) + if err := provider.SaveGroup(provider.Group{Name: "G", Members: []string{"a/m", "b/m"}, Routing: provider.Ordered, Patience: patience}); err != nil { + t.Fatal(err) + } + return a, b + } + ask := `{"model":"group/g","messages":[{"role":"user","content":"hi"}]}` + + a, b := group(0) + s := New() + code, body := postAs(t, s, "", ask) + if code != 200 || !strings.Contains(body, "hello") || a.n != 2 { + t.Fatalf("%d %s (a %d, b %d)", code, body, a.n, b.n) + } + r := s.trace.routes[len(s.trace.routes)-1] + var replanned *Try + for i := range r.Tries { + if r.Tries[i].Replan > 0 { + replanned = &r.Tries[i] + } + } + if replanned == nil || replanned.Replan != 2 || replanned.Again == 0 || replanned.Patience != provider.PatienceDefault { + t.Fatalf("the trace doesn't say the members were asked again: %+v", r.Tries) + } + if last := r.Tries[len(r.Tries)-1]; last.Status != 200 { + t.Fatalf("tries: %+v", r.Tries) + } + + a, b = group(provider.PatienceOff) + if code, _ := postAs(t, New(), "", ask); code != 529 || a.n != 1 { + t.Fatalf("patience off: %d (a %d, b %d)", code, a.n, b.n) + } + + a, b = group(5) + limited := reply{429, "", `{"error":{"message":"Rate limit reached, please try again shortly"}}`} + a.limited, b.limited = http.Header{"Retry-After": {"9"}}, http.Header{"Retry-After": {"9"}} + a.replies[0], b.replies[0] = limited, limited + began := time.Now() + if code, _ := postAs(t, New(), "", ask); code != 429 || a.n != 1 || time.Since(began) > 3*time.Second { + t.Fatalf("a Retry-After past the patience: %d after %s (a %d, b %d)", code, time.Since(began), a.n, b.n) + } +} + +// What Codex was sent (#1418): plus-B's 200 and frames, then +// server_is_overloaded, and sub2api the same. With patience, the agent's +// stream is the reply of the one asked again, and nothing of the failures. +func TestCodexStreamWaitsOutOverloadedGroup(t *testing.T) { + fresh(t) + failed := reply{200, "text/event-stream", sse(append(slices.Clone(overloadedLead), overloadedFailed)...)} + done := reply{200, "text/event-stream", sse( + `event: response.output_text.delta`+"\n"+`data: {"type":"response.output_text.delta","delta":"hello"}`, + `event: response.completed`+"\n"+`data: {"type":"response.completed","response":{"id":"r1","status":"completed","output":[]}}`)} + a := &scripted{replies: []reply{failed, done}} + b := &scripted{replies: []reply{failed}} + responsesOn(t, "a", a) + responsesOn(t, "b", b) + if err := provider.SaveGroup(provider.Group{Name: "G", Members: []string{"a/m", "b/m"}, Routing: provider.Ordered}); err != nil { + t.Fatal(err) + } + code, body := sendTo(New(), "/v1/responses", `{"model":"group/g","stream":true,"input":"hi"}`) + if code != 200 || !strings.Contains(body, "hello") || strings.Contains(body, "server_is_overloaded") || a.n != 2 { + t.Fatalf("%d %q (a %d, b %d)", code, body, a.n, b.n) + } +} diff --git a/internal/gateway/patience.go b/internal/gateway/patience.go new file mode 100644 index 000000000..5e7ecdcfb --- /dev/null +++ b/internal/gateway/patience.go @@ -0,0 +1,126 @@ +package gateway + +import ( + "context" + "net/http" + "slices" + "time" + + "github.com/yetone/magpie/internal/provider" +) + +// A group's patience (#1418): when every member has failed in a way that +// passes — overloaded, busy, rate limited for a moment — and nothing of a +// reply has gone to the agent, the request isn't ended on the last one's +// error. After a pause, longer each round and never shorter than a +// member's Retry-After, those members are asked again in turn, for as long +// as the group's Patience (provider.Group.Waits) lasts, counted from the +// first time every member had failed, when the agent would have had the +// error. The members take turns: the last one isn't first asked again +// alone, as the last one left of a plain provider is (passing), while +// another member is busy too. A streaming agent is kept alive with SSE +// comments through the pause, as through a held stream. A plain provider, +// which the agent picked as itself, keeps the retries passing gives the +// last one left. + +// replanRounds is how many times the members are asked again, at most, +// whatever the patience left; replanLongest is the longest pause between. +const ( + replanRounds = 6 + replanLongest = 30 * time.Second +) + +// busyTry is a member that failed in a way that passes, and when it may +// be asked again: now, or when its Retry-After says. +type busyTry struct { + c candidate + ready time.Time +} + +// busy says whether a failure is one a member may be over in a moment: +// overloaded, unavailable, timed out, or a rate limit that isn't the +// plan's or the money's. A proxy that refused the connection, a quota used +// up or response protection's 502 isn't. +func busy(status int, body []byte) bool { + switch status { + case 408, 500, 502, 503, 504, 529: + return failure(status, body) == failOther && !protectionRefused(status, body) + case 429: + return failure(status, body) == failRate && !creditWords.Match(body) + } + return false +} + +// noteBusy adds c to the members to ask again, once, with when its vendor +// said it may be asked. +func noteBusy(list []busyTry, c candidate, header http.Header) []busyTry { + if slices.ContainsFunc(list, func(b busyTry) bool { return b.c.restKey() == c.restKey() && b.c.effort == c.effort }) { + return list + } + now := time.Now() + return append(list, busyTry{c: c, ready: now.Add(retryAfter(header, now))}) +} + +// replan is, of the members that failed so in this round, those to ask +// again and the pause before: retryPause doubled each round up to +// replanLongest, and as long as the soonest Retry-After. ok is false when +// the rounds are spent, or the pause would end past by. +func replan(list []busyTry, round int, by time.Time) ([]candidate, time.Duration, bool) { + if len(list) == 0 || round >= replanRounds { + return nil, 0, false + } + now := time.Now() + wait := min(retryPause<<(round+1), replanLongest) + soonest := list[0].ready + for _, b := range list[1:] { + soonest = minTime(soonest, b.ready) + } + wait = max(wait, soonest.Sub(now)) + at := now.Add(wait) + if !at.Before(by) { + return nil, 0, false + } + var next, later []candidate + for _, b := range list { + if b.ready.After(at) { + later = append(later, b.c) // still asking for time: after those back + continue + } + next = append(next, b.c) + } + return append(next, later...), wait, true +} + +func minTime(a, b time.Time) time.Time { + if b.Before(a) { + return b + } + return a +} + +// pauseAlive waits d, keeping a streaming agent alive as a held stream +// does once the request has gone keepHeldAfter without a word. false: the +// agent went away first. +func pauseAlive(ctx context.Context, w http.ResponseWriter, kept *keptAlive, streams bool, start time.Time, d time.Duration) bool { + t := time.NewTimer(d) + defer t.Stop() + var hw *holdWriter + if streams && kept != nil && kept.proto != provider.Gemini { + hw = newHoldWriter(w, true) + hw.alive, hw.streams = kept, true + } + tick := time.NewTicker(min(watchEvery, max(d, time.Millisecond))) + defer tick.Stop() + for { + if hw != nil && time.Since(start) >= keepHeldAfter { + hw.keepAlive() + } + select { + case <-t.C: + return true + case <-ctx.Done(): + return false + case <-tick.C: + } + } +} diff --git a/internal/gateway/trace.go b/internal/gateway/trace.go index b2c1f5755..05b4ba626 100644 --- a/internal/gateway/trace.go +++ b/internal/gateway/trace.go @@ -272,6 +272,12 @@ type Try struct { Error string `json:"error,omitempty"` Rest *Rest `json:"rest,omitempty"` // how long it now sits out; none when it was the last to try Again int64 `json:"again,omitempty"` // ms waited before it was tried again, the last one left + // Replan: every member had failed in a way that passes, so after + // Again the Replan of them that may answer by then were asked again, + // in turn, within the group's Patience (seconds) for the request + // (#1418) + Replan int `json:"replan,omitempty"` + Patience int `json:"patience,omitempty"` // Queued: ms it waited for one of its key's or account's slots, the // provider's MaxConcurrency out already (concurrency.go) Queued int64 `json:"queued,omitempty"` diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index b29d4e6ca..4902da0f9 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -2794,6 +2794,11 @@ const I18N = { "Wait": "一直等", "2 min": "2 分钟", "Slow to start": "迟迟不出字", + "Every member busy": "成员全都忙", + "4 min": "4 分钟", + "When every member has failed with an error that may pass — overloaded, unavailable, rate limited for a moment — and nothing of the reply has reached the agent, each is asked again after a pause, longer each time and never shorter than the vendor asks, for up to {n} more. A streaming agent is kept waiting meanwhile.": "每个成员都失败了、且错误是会过去的那种(过载、暂不可用、短暂限流),而回复还一点都没到智能体时,过一会儿依次再问一遍每个成员,间隔一次比一次长,也不短于厂商要求的等待,最多再等 {n}。流式请求的智能体在此期间会一直被保持等待。", + "When every member has failed, the agent gets the last one's error at once.": "每个成员都失败时,智能体立刻拿到最后一个的错误。", + "{who} answered {status} · {fail}, and every member had failed with an error that may pass, so after {d} the {n} of them are asked again, in turn, before any of the reply reaches {agent}. The group waits up to {p} for one to answer.": "{who} 回了 {status} · {fail},而每个成员都以会过去的错误失败了,所以 {d} 后依次再问这 {n} 个,回复还一点都没到 {agent}。这个分组最多等 {p} 让其中一个回答。", "Largest model's": "最大模型的", "Smallest model's": "最小模型的", "e.g. 200k": "如 200k", @@ -6766,6 +6771,11 @@ const I18N = { "Wait": "一直等", "2 min": "2 分鐘", "Slow to start": "遲遲不出字", + "Every member busy": "成員全都忙", + "4 min": "4 分鐘", + "When every member has failed with an error that may pass — overloaded, unavailable, rate limited for a moment — and nothing of the reply has reached the agent, each is asked again after a pause, longer each time and never shorter than the vendor asks, for up to {n} more. A streaming agent is kept waiting meanwhile.": "每個成員都失敗了、且錯誤是會過去的那種(過載、暫不可用、短暫限流),而回覆還一點都沒到智慧體時,過一會兒依序再問一遍每個成員,間隔一次比一次長,也不短於廠商要求的等待,最多再等 {n}。串流請求的智慧體在此期間會一直被保持等待。", + "When every member has failed, the agent gets the last one's error at once.": "每個成員都失敗時,智慧體立刻拿到最後一個的錯誤。", + "{who} answered {status} · {fail}, and every member had failed with an error that may pass, so after {d} the {n} of them are asked again, in turn, before any of the reply reaches {agent}. The group waits up to {p} for one to answer.": "{who} 回了 {status} · {fail},而每個成員都以會過去的錯誤失敗了,所以 {d} 後依序再問這 {n} 個,回覆還一點都沒到 {agent}。這個分組最多等 {p} 讓其中一個回答。", "Largest model's": "最大模型的", "Smallest model's": "最小模型的", "e.g. 200k": "如 200k", @@ -10711,6 +10721,11 @@ const I18N = { "Wait": "待つ", "2 min": "2 分", "Slow to start": "応答開始が遅いとき", + "Every member busy": "全メンバーが混雑", + "4 min": "4 分", + "When every member has failed with an error that may pass — overloaded, unavailable, rate limited for a moment — and nothing of the reply has reached the agent, each is asked again after a pause, longer each time and never shorter than the vendor asks, for up to {n} more. A streaming agent is kept waiting meanwhile.": "すべてのメンバーが一時的なエラー(過負荷、利用不可、短時間のレート制限)で失敗し、応答がまだエージェントに何も届いていないときは、少し待ってから各メンバーに順に聞き直します。待ち時間は回ごとに長くなり、ベンダーが求める待ち時間より短くはなりません。さらに最大 {n} まで続けます。ストリーミングのエージェントはその間待たせたままにします。", + "When every member has failed, the agent gets the last one's error at once.": "すべてのメンバーが失敗したら、最後のメンバーのエラーをすぐエージェントに返します。", + "{who} answered {status} · {fail}, and every member had failed with an error that may pass, so after {d} the {n} of them are asked again, in turn, before any of the reply reaches {agent}. The group waits up to {p} for one to answer.": "{who} は {status} · {fail} を返し、すべてのメンバーが一時的なエラーで失敗したため、{d} 後にその {n} 件に順に聞き直します。応答はまだ {agent} に何も届いていません。グループはいずれかが答えるまで最大 {p} 待ちます。", "Largest model's": "最大のモデル", "Smallest model's": "最小のモデル", "e.g. 200k": "例: 200k", @@ -14675,6 +14690,11 @@ const I18N = { "Wait": "Warten", "2 min": "2 Min.", "Slow to start": "Langsamer Start", + "Every member busy": "Alle Mitglieder ausgelastet", + "4 min": "4 Min.", + "When every member has failed with an error that may pass — overloaded, unavailable, rate limited for a moment — and nothing of the reply has reached the agent, each is asked again after a pause, longer each time and never shorter than the vendor asks, for up to {n} more. A streaming agent is kept waiting meanwhile.": "Sind alle Mitglieder mit einem vorübergehenden Fehler gescheitert – überlastet, nicht verfügbar, kurz ratenbegrenzt – und hat den Agenten noch nichts von der Antwort erreicht, wird jedes nach einer Pause erneut gefragt, jedes Mal länger und nie kürzer, als der Anbieter verlangt, bis zu {n} lang. Ein streamender Agent wird so lange hingehalten.", + "When every member has failed, the agent gets the last one's error at once.": "Sind alle Mitglieder gescheitert, bekommt der Agent sofort den Fehler des letzten.", + "{who} answered {status} · {fail}, and every member had failed with an error that may pass, so after {d} the {n} of them are asked again, in turn, before any of the reply reaches {agent}. The group waits up to {p} for one to answer.": "{who} antwortete {status} · {fail}, und alle Mitglieder waren mit einem vorübergehenden Fehler gescheitert, daher werden die {n} nach {d} der Reihe nach erneut gefragt, bevor etwas von der Antwort {agent} erreicht. Die Gruppe wartet bis zu {p}, dass eines antwortet.", "Largest model's": "Größtes Modell", "Smallest model's": "Kleinstes Modell", "e.g. 200k": "z. B. 200k", diff --git a/internal/gui/assets/routing.js b/internal/gui/assets/routing.js index a95750467..7466b0e14 100644 --- a/internal/gui/assets/routing.js +++ b/internal/gui/assets/routing.js @@ -819,6 +819,9 @@ return r.tries[i + 1] ? t("{who}: the proxy magpie goes through didn't take the connection, so the request never reached the vendor and goes on to the next. Nothing is wrong with {who}, so it doesn't rest: once the proxy is up it is asked first again.", { who: name }) : t("{who}: the proxy magpie goes through didn't take the connection, so the request never reached the vendor, and nobody is left to try: {agent} gets the error. Start the proxy, or change it in Settings.", { who: name, agent }); + if (tr.replan) + return t("{who} answered {status} · {fail}, and every member had failed with an error that may pass, so after {d} the {n} of them are asked again, in turn, before any of the reply reaches {agent}. The group waits up to {p} for one to answer.", + { who: name, status: tr.status, fail: failWord(tr.fail), d: took(tr.again), n: tr.replan, p: took((tr.patience || 0) * 1000), agent }); if (tr.again) return t("{who} answered {status} · {fail}, and nobody else is left to ask — a failure that may pass, so it is tried again in {d}, before any of the reply reaches {agent}.", { who: name, status: tr.status, fail: failWord(tr.fail), d: took(tr.again), agent }); @@ -2951,6 +2954,14 @@ // in turn goes round already, and a manual group sends to one member // how long a group's member may take to its first token (provider.Group.FirstToken) const FIRST_OPTS = [[0, "Wait"], [30, "30 s"], [60, "1 min"], [120, "2 min"]]; + // how long a request waits for a group whose every member is busy + // (provider.Group.Patience: 0 is the 60s default, -1 off) + const PATIENCE_OPTS = [[-1, "Off"], [0, "1 min"], [120, "2 min"], [240, "4 min"]]; + const patienceOf = (n) => n === 60 ? 0 : n || 0; + const patienceWord = (n) => { + const o = PATIENCE_OPTS.find(([v]) => v === (n || 0)); + return o ? t(o[1]) : took(n * 1000); + }; const sinkable = (routing) => routing !== "rotate" && routing !== "weight" && routing !== "manual"; const AFF_HINT = { "": "A conversation stays with the account or key that answered it while what the vendor cached of it is worth keeping — within a turn always, across turns while it's fresh.", @@ -3058,7 +3069,7 @@ // there, rather than leaving the slot empty. const openGroupEditor = async (g) => { if (groupDirty() && !(await confirmDiscard())) return false; - gEdit = { id: g.id, draft: { name: g.name, members: [...g.members], match: [...(g.match || [])], matched: [...(g.matched || [])], fast: [...(g.fast || [])], off: [...(g.off || [])], routing: g.routing || "", pick: g.pick || "", affinity: g.affinity || "", sink: !!g.sink, firstToken: g.firstToken || 0, context: g.context || 0, classifier: g.classifier || "", effort: g.effort || "", levels: [...(g.levels || [])], rules: (g.rules || []).map((r) => ({ ...r, intent: r.intent || "", agents: [...(r.agents || [])], time: r.time ? { ...r.time, days: [...(r.time.days || [])] } : null })) } }; + gEdit = { id: g.id, draft: { name: g.name, members: [...g.members], match: [...(g.match || [])], matched: [...(g.matched || [])], fast: [...(g.fast || [])], off: [...(g.off || [])], routing: g.routing || "", pick: g.pick || "", affinity: g.affinity || "", sink: !!g.sink, firstToken: g.firstToken || 0, patience: patienceOf(g.patience), context: g.context || 0, classifier: g.classifier || "", effort: g.effort || "", levels: [...(g.levels || [])], rules: (g.rules || []).map((r) => ({ ...r, intent: r.intent || "", agents: [...(r.agents || [])], time: r.time ? { ...r.time, days: [...(r.time.days || [])] } : null })) } }; renderGroups(); return true; }; @@ -3464,7 +3475,7 @@ b.onclick = (e) => { e.stopPropagation(); // the card opens the editor; this picks if (on) return; - groupAction("save", { id: g.id, name: g.name, members: namedOf(g), match: g.match || [], routing: "manual", pick: id, affinity: g.affinity || "", sink: !!g.sink, firstToken: g.firstToken || 0, rules: g.rules || [], effort: g.effort || "", classifier: g.classifier || "", context: g.context || 0, levels: g.levels || [], family: g.family || "", fast: g.fast || [], off: g.off || [] }, + groupAction("save", { id: g.id, name: g.name, members: namedOf(g), match: g.match || [], routing: "manual", pick: id, affinity: g.affinity || "", sink: !!g.sink, firstToken: g.firstToken || 0, patience: g.patience || 0, rules: g.rules || [], effort: g.effort || "", classifier: g.classifier || "", context: g.context || 0, levels: g.levels || [], family: g.family || "", fast: g.fast || [], off: g.off || [] }, t("{name}: every request to {model}", { name: g.name, model: memberName(id) })); }; box.append(b); @@ -3803,6 +3814,15 @@ fw.append(segs(FIRST_OPTS.map(([n, l]) => [n, t(l)]), d.firstToken || 0, (v) => { d.firstToken = +v; drawFirst(); }), fHint); ed.append(el("label", "", t("Slow to start")), fw); drawFirst(); + // every member busy at once: the agent told, or the members asked + // again within a budget (#1418) + const patHint = el("div", "hint"), patW = el("div"); + const drawPatience = () => patHint.textContent = d.patience < 0 + ? t("When every member has failed, the agent gets the last one's error at once.") + : t("When every member has failed with an error that may pass — overloaded, unavailable, rate limited for a moment — and nothing of the reply has reached the agent, each is asked again after a pause, longer each time and never shorter than the vendor asks, for up to {n} more. A streaming agent is kept waiting meanwhile.", { n: patienceWord(d.patience) }); + patW.append(segs(PATIENCE_OPTS.map(([n, l]) => [n, t(l)]), d.patience || 0, (v) => { d.patience = +v; drawPatience(); }), patHint); + ed.append(el("label", "", t("Every member busy")), patW); + drawPatience(); // the window agents are told: the largest member's, the smallest's, or // one the user names (Mikan on Discord) const ctxHint = el("div", "hint"), ctxW = el("div", "ctx-wrap"); @@ -4171,7 +4191,7 @@ if (own && !d.levels.length) return status(t("Pick a level to offer, or leave them to its models"), "warn"); saveBtn.classList.add("busy"); // refused, Add can be pressed again (busy, it takes no clicks) - groupAction("save", { id: idOf(), from: g?.id, name: d.name.trim() || idOf(), members: namedOf(d), match: d.match, routing: d.routing, pick: d.pick || "", affinity: d.affinity, sink: !!d.sink && sinkable(d.routing), firstToken: d.firstToken || 0, rules: d.rules, effort: d.effort, classifier: d.rules.some((r) => r.intent) || d.effort === "auto" ? d.classifier : "", context: d.context || 0, levels: own ? d.levels : [], family: g?.family || "", fast: d.fast.filter((x) => d.members.includes(x)), off: d.off.filter((x) => d.members.includes(x)) }, t(g ? "{name} saved" : "{name} added", { name: d.name.trim() || idOf() })) + groupAction("save", { id: idOf(), from: g?.id, name: d.name.trim() || idOf(), members: namedOf(d), match: d.match, routing: d.routing, pick: d.pick || "", affinity: d.affinity, sink: !!d.sink && sinkable(d.routing), firstToken: d.firstToken || 0, patience: d.patience || 0, rules: d.rules, effort: d.effort, classifier: d.rules.some((r) => r.intent) || d.effort === "auto" ? d.classifier : "", context: d.context || 0, levels: own ? d.levels : [], family: g?.family || "", fast: d.fast.filter((x) => d.members.includes(x)), off: d.off.filter((x) => d.members.includes(x)) }, t(g ? "{name} saved" : "{name} added", { name: d.name.trim() || idOf() })) .then(() => saveBtn.classList.remove("busy")); }; // what goes wrong is said where it is seen, never a click that does nothing diff --git a/internal/gui/tests/group-patience.test.cjs b/internal/gui/tests/group-patience.test.cjs new file mode 100644 index 000000000..3f6e58a82 --- /dev/null +++ b/internal/gui/tests/group-patience.test.cjs @@ -0,0 +1,128 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// A routing group whose every member is busy at once — overloaded, +// unavailable, rate limited for a moment — asks them again within a budget +// rather than handing the agent the last one's error (#1418, Aliceonly). +// The group editor's "Every member busy" row picks Off, 1 min (the +// default, saved as 0), 2 min or 4 min, its hint saying what each does; +// saved, the group is sent with patience in seconds, -1 for off. In +// English and Chinese, Chromium and WebKit; every string has its Chinese, +// Traditional Chinese, Japanese and German. +const assert = require("node:assert/strict"); +const fs = require("node:fs/promises"); +const path = require("node:path"); +const { test } = require("node:test"); +const { chromium, webkit } = require("playwright"); + +const assets = path.resolve(__dirname, "../assets"); +const models = [ + { id: "plus-b/gpt-6.1-sol", name: "gpt-6.1-sol", providerName: "Plus B", icon: "generic" }, + { id: "sub2api/gpt-6.1-sol", name: "gpt-6.1-sol", providerName: "sub2api", icon: "generic" }, +]; +const members = models.map((m) => m.id); +const saved = { patience: 0 }; +const groups = () => ({ + models, pools: [], + groups: [{ id: "sol", name: "Sol", members, routing: "order", ready: true, patience: saved.patience, + memberInfo: members.map((id) => ({ id, ready: true })) }], +}); + +const words = { + en: { edit: "Edit", save: "Save", label: "Every member busy", off: "Off", def: "1 min", four: "4 min", on: "each is asked again after a pause", offHint: "gets the last one's error at once" }, + zh: { edit: "编辑", save: "保存", label: "成员全都忙", off: "关闭", def: "1 分钟", four: "4 分钟", on: "依次再问一遍每个成员", offHint: "立刻拿到最后一个的错误" }, +}; + +function serve(lang, posts) { + const state = { agents: [{ id: "codex", name: "Codex", path: "/test/codex", fields: [] }], profiles: [], settings: { lang, theme: "light" } }; + return async (r) => { + const url = new URL(r.request().url()); + const json = (data) => r.fulfill({ json: data }); + if (url.pathname === "/boot.js") return r.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` }); + if (url.pathname === "/wails/runtime.js") return r.fulfill({ contentType: "text/javascript", body: "export const Window = {};" }); + if (url.pathname === "/api/state") return json(state); + if (url.pathname === "/api/plugins") return json({ plugins: [] }); + if (url.pathname === "/api/gateway/trace") { + if (url.searchParams.get("wait")) return new Promise(() => {}); // nothing more comes + return json({ mine: true, now: new Date().toISOString(), seq: 1, totals: { requests: 0, rerouted: 0, errors: 0 }, routes: [] }); + } + if (url.pathname === "/api/gateway/history") return json({ cut: false, days: [], routes: [] }); + if (url.pathname === "/api/groups") return json(groups()); + if (url.pathname.startsWith("/api/groups/")) { + const body = JSON.parse(r.request().postData() || "{}"); + posts.push({ path: url.pathname, body }); + saved.patience = body.patience || 0; + return json(groups()); + } + if (url.pathname === "/api/providers") return json({ providers: [], presets: [], excluded: [], gateway: { running: true, window: true, url: "http://127.0.0.1:3999" } }); + if (url.pathname.startsWith("/api/")) return json({}); + const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname); + const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)]; + await r.fulfill({ body: await fs.readFile(file), contentType }); + }; +} + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + for (const lang of ["en", "zh"]) { + const w = words[lang]; + test(`${engine} ${lang}: a group waits out every member busy`, async (t) => { + saved.patience = 0; + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + const page = await (await browser.newContext({ viewport: { width: 1100, height: 2000 }, reducedMotion: "reduce" })).newPage(); + t.after(async () => { + if (process.env.ARTIFACT_DIR) { + await fs.mkdir(process.env.ARTIFACT_DIR, { recursive: true }); + await page.screenshot({ path: path.join(process.env.ARTIFACT_DIR, `${engine}-${lang}-group-patience.png`) }); + } + await browser.close(); + }); + page.setDefaultTimeout(5000); + const errors = [], posts = []; + page.on("pageerror", (e) => errors.push(e.message)); + await page.route("**/*", serve(lang, posts)); + await page.goto("http://magpie.test/?view=routing"); + const card = page.locator(".rt-group", { hasText: "Sol" }); + await card.waitFor(); + + const save = async () => { + const ed = page.locator(".rt-gedit"); + await ed.locator("button.primary", { hasText: w.save }).click(); + await page.waitForFunction(() => !document.querySelector(".rt-gedit")); + return posts.filter((p) => p.path === "/api/groups/save").at(-1).body; + }; + const open = async () => { + await card.locator("button", { hasText: w.edit }).click(); + const row = page.locator(".rt-gedit label", { hasText: w.label }).locator("xpath=following-sibling::div[1]"); + await row.waitFor(); + return row; + }; + let row = await open(); + assert.equal(await row.locator(".opt.on").textContent(), w.def, "1 min by default"); + assert((await row.locator(".hint").textContent()).includes(w.on)); + await row.locator(".opt", { hasText: w.four }).click(); + assert((await row.locator(".hint").textContent()).includes(lang === "zh" ? "4 分" : "4 min")); + assert.equal((await save()).patience, 240); + + row = await open(); + assert.equal(await row.locator(".opt.on").textContent(), w.four, "the editor opens at what was saved"); + await row.locator(".opt", { hasText: w.off }).click(); + assert((await row.locator(".hint").textContent()).includes(w.offHint)); + assert.equal((await save()).patience, -1); + + row = await open(); + assert.equal(await row.locator(".opt.on").textContent(), w.off); + await row.locator(".opt", { hasText: w.def }).click(); + assert.equal((await save()).patience, 0, "the default is saved as none set"); + + const missing = await page.evaluate(() => { + const keys = [ + "Off", "1 min", "2 min", "4 min", "Every member busy", + "When every member has failed, the agent gets the last one's error at once.", + "When every member has failed with an error that may pass — overloaded, unavailable, rate limited for a moment — and nothing of the reply has reached the agent, each is asked again after a pause, longer each time and never shorter than the vendor asks, for up to {n} more. A streaming agent is kept waiting meanwhile.", + "{who} answered {status} · {fail}, and every member had failed with an error that may pass, so after {d} the {n} of them are asked again, in turn, before any of the reply reaches {agent}. The group waits up to {p} for one to answer.", + ]; + return ["zh", "zh-TW", "ja", "de"].flatMap((l) => keys.filter((k) => !I18N[l][k]).map((k) => l + ": " + k)); + }); + assert.deepEqual(missing, [], "every string has its translations"); + assert.deepEqual(errors, []); + }); + } +} diff --git a/internal/provider/group.go b/internal/provider/group.go index 32a210fb0..4202aba76 100644 --- a/internal/provider/group.go +++ b/internal/provider/group.go @@ -26,6 +26,7 @@ import ( "regexp" "slices" "strings" + "time" "github.com/yetone/magpie/internal/catalog" "github.com/yetone/magpie/internal/settings" @@ -107,11 +108,32 @@ func (g Group) Live() Group { return g } -// Group is a routing group. +// PatienceOff, PatienceDefault and PatienceLongest are a group's +// Patience: none, the seconds a group waits that hasn't set it, and the +// most it may. +const ( + PatienceOff = -1 + PatienceDefault = 60 + PatienceLongest = 240 +) + +// Waits is how long a request to the group may be kept for its members to +// come back (Patience), 0 for not at all. +func (g Group) Waits() time.Duration { + switch { + case g.Patience < 0: + return 0 + case g.Patience == 0: + return PatienceDefault * time.Second + } + return time.Duration(min(g.Patience, PatienceLongest)) * time.Second +} + // ContextSmallest is a group's Context when agents are told the window of // its smallest member. const ContextSmallest = -1 +// Group is a routing group. type Group struct { ID string `json:"id"` Name string `json:"name"` @@ -137,6 +159,14 @@ type Group struct { // waits as long as it takes. The last one left is always waited for, // and the slow one doesn't rest. FirstToken int `json:"firstToken,omitempty"` + // Patience is how many seconds more a request may be kept, once every + // member has failed and nothing of a reply has been sent, for the + // members that failed in a way that passes — + // busy, overloaded, rate limited for a moment — to be asked again + // after a pause, in turn, until one answers (#1418). 0 is + // PatienceDefault; PatienceOff gives the agent the last one's error + // once each has been asked. + Patience int `json:"patience,omitempty"` // Off are the members switched off: kept where they are in the // order, with their rules, but sent nothing until switched on again, // so trying a group without one doesn't mean taking it out. @@ -845,6 +875,10 @@ func SaveGroup(g Group) error { g.Name = g.ID } g.FirstToken = max(g.FirstToken, 0) + if g.Patience < 0 { + g.Patience = PatienceOff + } + g.Patience = min(g.Patience, PatienceLongest) if g.Context < 0 { g.Context = ContextSmallest }