gateway: a group member whose window can't hold the request isn't asked it (dgqyushen on Discord)

dgqyushen on Discord: OpenCode Zen's free DeepSeek V4.1 Flash (200K)
first in a group and a 1M DeepSeek subscription second, so that the
first 200K go free and past that go to the subscription.

The gateway fell over only on a refusal it reads as too long (#700,
withRoom/failOverflow, tooLongUnsaid past 1.2x the window). A vendor that
refuses a request just past its window without saying why (between 1.0x
and 1.2x) reached the agent as that error while the next member had
room, and every doomed request spent one against the free tier's limits.

roomy (fallback.go), in serve after rules, affinity, the image filter and
pinTo and before probeOne, estimates the request as the overflow path
does (estimate) and leaves out the candidates whose known window
(windowOf: Contexts, the catalog, ContextOf) is no larger, and their
order rows with them. It is a check before sending, not a retry. Kept:
a window not known, a body that doesn't parse, a single model, and a
request no candidate holds (the first is asked, its overflow told to the
agent to compact). A conversation stuck to the small member by affinity
moves once it outgrows it. count_tokens (a count on the first member) and
System One's decision models don't go through serve's candidate path and
are left alone; every generation route (middleware, classify, search,
vision, codex titles/backend, auto groups) goes through serve. No UI
change: a member left out is absent from the route's order.

TestPayloadTooLargeOverWindowTriesMemberWithRoom now expects the members
too small not to be asked at all (c only, one try).

Run:
- go test -tags nogui -p 1 ./internal/gateway -run
  'TestMemberTooSmallIsNotAsked|TestConversationOutgrowingItsMemberMoves|
  TestRoomyLeavesWhatItCantJudge|TestPayloadTooLarge': ok
- the overflow tests (TestPayloadTooLarge, TestOverflow,
  TestContextOverflow, TestEveryVendorsOverflow, TestCodexOverflowInGroup,
  TestStreamOverflow, TestRateLimitNotContextOverflow) with the new ones:
  ok
- gofmt -l clean; go vet ./internal/gateway (darwin); GOOS=linux and
  GOOS=windows go vet -tags nogui ./...: clean; go build darwin, linux,
  windows: ok.
Broken by hand: the roomy call in serve commented out:
TestMemberTooSmallIsNotAsked red (400 "FREE: Invalid request
parameters"), TestConversationOutgrowingItsMemberMoves red (free 2,
paid 0), TestPayloadTooLargeOverWindowTriesMemberWithRoom red (a 1, c 1,
2 tries); restored, all green.
Not run: the whole internal/gateway package (the run failed to build,
"no space left on device", the disk at 0 GB free) and the full suite
(left to the batch's run). Not tried against the real OpenCode Zen.
Known: the estimate is bytes/4, so mostly-CJK text counts high and a
member may be passed over a little early.

Full suite: SUITE_LINE
This commit is contained in:
yetone
2026-10-15 23:08:03 +08:00
parent 62020b9c26
commit 0f398c4895
5 changed files with 222 additions and 3 deletions
+2
View File
@@ -112,6 +112,7 @@ recorded as a prediction failure (`noPrediction`).
- The order of the steps a request's accounts go through, how much the accounts' own order (*Make first*) counts under each routing, and how often an allowance is read are described for users in [How magpie picks an account](../reference.md#how-magpie-picks-an-account). Smart compares renewals window by window, biggest first, each truncated to the hour (`weighRouted`), so the order decides only when every window falls in the same hour. A window's renewal is its reset, or, when what it has left runs out sooner or it has no reset, that moment (`Limit.RunsOut`, from `QuotaWindow.RunsOutAt`; `Allowance.Renewal`): the WorkBuddy plugin (0.1.14) sends it on its Credits window as the soonest end of a package with credits left (cdredfox on X). Only Smart reads it; Weekly pace, the 90%/98% tiers and rests go by the window's share and reset as before. A row on the Routing page says the share used (the fullest window's, `Allowance.For`) with when that same window renews (`Allowance.Fullest`, the trace's `usedRenews`), not the biggest window's: a Factory account 32% into its week and 16% into its month reads "32% used · renews in 3 days" while Smart still ranks it by its month (#1778). A route from before `usedRenews` says when only for an account of one window. Affinity keeps a conversation on an account at 90–97%: only `SpentShareOf` (98%, 100% In order) stops it (`affine`), while the 90% tier (`lowShare`) orders only conversations nobody has answered.
- A turn's end is told to the app for the "Task done alert" notification (itieniu on X, `turndone.go`). The trace follows each agent session's turn (`turns`, keyed by agent and session): a request is of the turn unless it has a `Kind` or is a Claude Code subagent's (`agentTurnOf`), and its reply is scanned on the way to the agent for a tool call in any wire format (`toolScan`, a JSON value such as `"type":"tool_use"` or `"finish_reason":"tool_calls"`, never a key or text). The turn is done when no request of it is going, the last reply was whole, under 400 and called no tool, and nothing more came for `turnQuiet` (4s); a session idle past `turnStale` (30m) starts over. Only a turn that ran at least `settings.TurnDoneAlert` seconds is told (`TurnDone`, set by the GUI; nil under `magpie serve`, so nothing is followed). The ChatGPT backend path (`codexBackend`) is followed the same way. `TestTurnDoneSaidAtTheTurnsEnd`, `TestTurnDoneCodexBackend`, `TestToolScan`, `turn-done.test.cjs`.
- A resting candidate is tried last (`restLast`). Of the resting candidates, a request asks only the one whose rest ends soonest, the first in order on a tie (`probeOne`, #1799). The others aren't asked by that request, so a member that is down isn't asked by every request its rest was meant to spare it from, and a group that is down whole takes one upstream request per request, not one per member. Every ready candidate is still asked in its order. A lone candidate is tried even while it rests, because there is no other. The trace still lists every member, the resting ones with their rest. Only rests are read, and a failure about the request's content or its model rests no member (a model refusal rests only `restID`), so neither leaves a member out. The same applies in `count_tokens`, embeddings and rerank, image accounts and a group's System One decision models. A Codex reset (`autoReset`) still looks over every candidate. This is like AxonHub's error-aware load balancing: the rest and its backoff are the penalty that decays, and the member back soonest is the one asked to show it is back. Keys out of their allowance aren't asked even so, not even the one back soonest or a lone one (#1772: four Ollama Cloud keys out for the week, each asked again and refused on every request). When every candidate left is a key (not a subscription account, whose resets `autoReset` may spend) resting out of quota or credit after a 429 or 402, none is asked. The first one's refusal is given again (`quotaHeld`, its words kept in the rest's `said`), saying when it is asked again. The last key left rests too when it is refused so, as the keys before it do. Any 429 that reaches the agent without a vendor `Retry-After`, while every candidate tried is resting, carries one: the seconds until the first of them is back (`soonestBack`). A quota refusal with no word of when it is back rests `quotaRest` (15 minutes), or the provider's own `quotaRest` in minutes (`Provider.QuotaRestFor`, at most `MaxQuotaRest`, 8 days; `magpie provider quota-rest <id> 7d`), or until the time of day the user said its allowance comes back (`QuotaResetAt`, `Provider.OwnQuotaRest`; `magpie provider quota-rest <id> until 08:00`, or `until 00:00+08:00` on the vendor's clock; #2008, a free tier's "today's free-model token quota"). Whichever of the two was set last counts. A time the vendor names stands over it, and so does its `Retry-After`, unless that was more than `longestWait` (an hour) and so cut to it while the user's own rest is longer: then the user's stands (`TestQuotaRestsUntilTheTimeOfDaySet`). A key listed in `keys` as well as in `key` is one candidate (`KeysOn`), not asked twice. `TestAllRestingAnswersFromRest`, `TestOwnQuotaRest`, `TestQuotaHeldOnlyForKeysOutOfAllowance`, `TestFirstKeyListedTwiceAskedOnce`.
- A member whose model is known to take less than the request isn't asked it (`roomy` in [`fallback.go`](../../internal/gateway/fallback.go), in `serve` after the rules, affinity, the image filter and `pinTo`, before `probeOne`; dgqyushen on Discord: OpenCode Zen's free DeepSeek V4.1 Flash, 200K, first in a group and a 1M subscription of it second). It is a check before sending, not a retry: the request's tokens are estimated as the overflow fall-over does (`estimate`, bytes/4 over text, tool arguments and schemas), and a candidate whose window (`windowOf`: the provider's `Contexts`, the catalog, `ContextOf`) is known and no larger is left out of the candidates and of the trace's order. Asked, such a member only refuses, and a refusal that doesn't say why, for a request short of `tooLongUnsaid`'s 1.2 margin, reached the agent as the vendor's error while the next member had room; it also spent a request against the member's limits. A conversation kept on a member by affinity moves once it outgrows it. Nothing is left out when its window isn't known, when the body doesn't parse, when only one model is among the candidates, or when no candidate holds the request: then the first is asked, and its overflow reaches the agent as one, to compact (`withRoom`, `failOverflow` and `tooLongUnsaid` stay for the window the estimate misses, which counts low on code and high on CJK text). A body shorter than four bytes per token of the least window isn't parsed. `count_tokens` (a count on the group's first member, not a send) and System One's decision models (short decision text) don't go through it. The Routing page shows a member left out so only by its absence from the route's order. `TestMemberTooSmallIsNotAsked`, `TestConversationOutgrowingItsMemberMoves`, `TestRoomyLeavesWhatItCantJudge`.
- Routing decides who goes first only when nobody has answered the conversation yet. Affinity keeps the answerer while its cache is worth it. Auto mode keeps it across turns while the last reply read from the cache and wrote to it at least `cacheWorth` (1024) tokens between them (the usage's `CacheRead` plus `CacheWrite`, passed to `answered`) and the cache isn't cold (`cacheCold`, 5 minutes). Past 5 minutes it stays while the vendor said it keeps at least `cacheWorth` tokens of the conversation for an hour (`hourCache`, #2302): a reply with Anthropic's 1-hour writes (`cache_creation.ephemeral_1h_input_tokens`, the usage's `CacheWrite1h`, as Claude Code asks of a subscription) keeps what it read plus those for `cacheHour`, a later reply on the same account and model that reads all of it starts the hour again, and one that reads less (moved, compacted) drops it. The stick keeps it on disk too (`cacheHour`, `cacheHourAt`), and a group's rules keep the turn's effort the same hour (`keepsEffort`). Vendors that report no 1-hour write are unchanged. `TestAffinityKeepsAnHourCachePastFiveMinutes`, `TestHourCacheAfter`. What was written counts: a first turn reads nothing and writes the whole prompt (Anthropic's `cache_creation_input_tokens`), and the second turn stays to read it rather than moving as `no-cache` and building it again elsewhere (vilicvane on Discord). The stick keeps both, on disk too (`affinity.json`'s `cacheWrite`, absent in a file from before and read as 0, so such a stick is judged by its read alone), and the trace's `Affinity.CacheWrite` lets the Routing page say what was read and what was written. A vendor that keeps a prompt cached without reporting it (OpenAI's automatic prefix cache, Gemini) says neither of a turn that read none, so the prompt that turn was sent (the usage's `Input`) stands for the write and its second turn stays too; a reply that reports no usage at all counts as no cache, as before. `TestAffinityKeepsACacheJustWritten`, `TestAffinityKeepsACacheTheVendorKeptSilently`, `routing-affinity-cache-write.test.cjs`.
- Strict (`strict`, #1797, miniers) never moves a conversation to another key or account (`who`). Its stick is kept as session's is, and while it is fresh `affine` keeps only the candidates of that `who` (`strictOnly`): its other models stay, so a group's rules still pick among them, but no other account, key or provider is asked, and a resting or spent one is asked anyway. A failure there reaches the agent and rests the account as a non-lone candidate's would (`strictAlone`), so new conversations go elsewhere. Before planning, `strictKeep` takes the stuck account back from what holds new conversations off it: a usage cap (`pl.capped`, `capHeldOnly`), so the conversation goes on past it. An account held for credits it may not spend is answered 429 naming the account and Strict, and nothing reaches the vendor, rather than moved. An account removed, switched off, barred, or not allowed for the calling key is gone, and the conversation moves as under session. The trace says `strict` even with one candidate. `strict_affinity_test.go`, `stays-strict.test.cjs`.
- In turn (`rotate`), a conversation nobody has answered yet goes to the key, account or model the fewest other conversations of the provider's model or the group answered in the last `heldFor` (30 minutes) are on (`leastHeld`, #946). Ties, resting ones and a group with a group in it keep routing's order. With session affinity, two sessions of one group so stay on different models.
@@ -702,6 +703,7 @@ the row of the entry that id reaches, with its label, under the bare id.
```sh
go test -tags nogui ./internal/gateway -run 'TestGroupAsksOneRestingMemberNotEach|TestLoneRestingMemberStillAsked|TestRetrievalGroupAsksOneRestingMember|TestProbeOne|TestLoop|TestLongReplyThatDoesNotLoop|TestQuiet|TestSilentHeld|TestRotateSpreadsSessions|TestRouting|TestSmartRouting|TestFallback|TestNoFallbackForOtherErrors|TestLastFallbackErrorReachesTheAgent|TestRateLimitedSinksToTheBack|TestGroupRateLimitedSinks|TestAffinity|TestSeveralKeysOnTakeOverFromEachOther|TestModelNotInPlanRestsTheModelNotTheKey|TestSubscriptionAccountsTakeOver|TestGroup|TestTrace|TestImageTool|TestCodexNoCredits|TestWindowCapsHoldTheAccount|TestAccountCap|TestClaudeGoesOnMessagesWhereTheRelayHasThem|TestAutoRelaysOnTheClientsOwnAPI|TestSearchOfferedStaysOnTheClientsAPI|TestSearchFollowsTheSearchersProxy|TestCodexSearchAnsweredOnResponses|TestAgentEffortOnCursorLocal|TestAzureCompactionWithoutMagpiesReasoning|TestCodexCompact|TestProtection|TestSearchedConversation|TestUnsearchedConversationUnchanged|TestNotAnAPIReply|TestAPIReplyUntouched|TestCodexBackendWebPage|TestSub2APIKeyLimitIsQuota|TestKeysWeighedByTheirWindows|TestGroupWeighsKeyWindows|TestKeyOutOfItsWindowRestsUntilReset|TestKeyPoolErrorDoesNotRestForWindow|TestKeyBackOnceItsWindowIsNotFull|TestRestingKeyReadAgainInAnOrderedGroup|TestClaudeAccountBackOnceItsWindowRenews|TestThinkingStreams|TestHeldThinkingKeepsTheAgentAlive|TestCodexHeardWithinItsIdleTimeout|TestRefusalAfterThinkingFailsOver|TestGeminiEmptyRepliesAskedAgain|TestLocalUnredacted|TestCORS|TestForeignPagesRefused|TestAIStudioThinking|TestGeminiThoughtsThroughLocalProxy|TestGeminiRefusedLevel|TestGeminiThinkingOffAtItsLowest|TestThinkingOff|TestTranslatedEffortLoggedAsSent|TestTranslatedThinkingOffRefused|TestSub2APIThinkingOffRefused|TestRefusesThinkingOff|TestClaudeFiveFiveThinkingOffOnTheWire|TestSamplingAsTheModelTakesIt|TestHaikuFiveFiveSamplingOnTheWire|TestGeminiThoughtsMarkedInExtraContent|TestGeminiThinkingLevelRefused|TestGeminiMinimalRefusedTwiceAtOnce|TestPassthroughGeminiMinimalRefused|TestPassthroughEffortNoneRefused|TestPassthroughMinimalRefusedNoneTaken|TestOtherOffNamed|TestClaudeSignInNotToldItsSignInFailed|TestSignInWriterReleasesA403|TestSignInBetaStaysWithMagpie|TestStructuredOutput|TestResponsesTextKeepsVerbosityBesideFormat|TestRefusedFormatToldInWords|RPM|TestQueued|TestCustomGeminiUpstream|TestWholeNums|TestGrokCalls|TestOnlyGrokCalls|TestGrokModel|TestGrokPluginCalls'
go test -tags nogui ./internal/gateway -run 'TestMemberTooSmallIsNotAsked|TestConversationOutgrowingItsMemberMoves|TestRoomyLeavesWhatItCantJudge|TestPayloadTooLarge|TestOverflow|TestContextOverflow'
go test -tags nogui ./internal/gateway -run 'TestVertex'
go test -tags nogui ./internal/gateway -run 'TestPublicAddr|TestEditImageURL|TestPrivateDialer'
go test -tags nogui ./internal/gateway ./internal/provider ./internal/cli ./internal/gui -run 'TestDisabled|TestModelDisableCmd'
+77 -2
View File
@@ -1234,10 +1234,16 @@ func tooLongUnsaid(p provider.Provider, model string, tokens, status int, body [
// the one set for all the provider's models is no larger than the model's
// own, #2112), else the one set for all of them.
func windowOf(p provider.Provider, model string) int {
return windowIn(provider.Served, p, model)
}
// windowIn is windowOf with the catalog read from served, for a caller
// that weighs several models to read it once.
func windowIn(served func() []provider.Entry, p provider.Provider, model string) int {
if n := p.Contexts[model]; n > 0 {
return n
}
for _, e := range provider.Served() {
for _, e := range served() {
if e.Group == "" && e.Provider.ID == p.ID && (e.Model == model || e.ID == model) && e.Context > 0 {
return e.Context
}
@@ -1292,7 +1298,7 @@ func withRoom(left []candidate, c candidate, tokens int) []candidate {
if x.p.ID == c.p.ID && x.model == c.model {
continue
}
if w := windowOf(x.p, x.model); w > 0 && tokens >= w {
if !holds(x, tokens) {
continue
}
out = append(out, x)
@@ -1300,6 +1306,75 @@ func withRoom(left []candidate, c candidate, tokens int) []candidate {
return out
}
// holds is whether c's model may hold a request of about tokens: its
// window isn't known, or is larger.
func holds(c candidate, tokens int) bool {
w := windowOf(c.p, c.model)
return w <= 0 || tokens < w
}
// roomy leaves out, before any is asked, the candidates whose model is
// known to take less than the request (dgqyushen on Discord: OpenCode
// Zen's free DeepSeek V4.1 Flash, 200K, first in a group with a 1M
// subscription of it second). Asked, such a member only refuses it, a
// request spent against its limits, and a refusal that doesn't say why,
// for a request short of tooLongUnsaid's margin past the window, reached
// the agent as the vendor's error while the next member had room. The
// request's size is estimate's, which mostly counts low (four bytes a
// token), so a member is passed over only when the request is past its
// window by that count; one nearer may still be refused and falls over
// (withRoom). A model whose window isn't known is kept, a
// request that doesn't parse leaves every one, and so does one no
// candidate holds: the first is asked, and the agent told it overflowed,
// to compact.
func roomy(cs []candidate, pl planned, from provider.Protocol, body []byte) ([]candidate, planned) {
if len(cs) < 2 {
return cs, pl
}
served := sync.OnceValue(provider.Served) // the catalog, read once
least, windows := 0, map[string]int{}
key := func(c candidate) string { return c.p.ID + "\x00" + c.model }
for _, c := range cs {
if _, ok := windows[key(c)]; ok {
continue
}
w := windowIn(served, c.p, c.model)
windows[key(c)] = w
if w > 0 && (least == 0 || w < least) {
least = w
}
}
// one model has nothing to choose between, and a body shorter than
// the least window can't estimate past it: neither is parsed
if len(windows) < 2 || least == 0 || len(body)/4 < least {
return cs, pl
}
req, err := parse(from, body)
if err != nil {
return cs, pl
}
tokens := estimate(req)
var out []candidate
var order []Weighed
parallel := len(pl.order) == len(cs)
for i, c := range cs {
if w := windows[key(c)]; w > 0 && tokens >= w {
continue
}
out = append(out, c)
if parallel {
order = append(order, pl.order[i])
}
}
if len(out) == 0 || len(out) == len(cs) {
return cs, pl
}
if parallel {
pl.order = order
}
return out, pl
}
// matesFirst puts first, of the candidates left, the other keys or
// accounts of the member c is of — its model, at its effort — that aren't
// resting: what one account's safety filter refused, another may answer
+3
View File
@@ -2131,6 +2131,9 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
return
}
}
// a member whose model is known to take less than the request isn't
// asked: it would only refuse it
cands, pl = roomy(cands, pl, from, body)
// of those resting, only the one back soonest is asked (#1799); the
// whole list still finds a Codex account to spend a reset on
all := cands
+3 -1
View File
@@ -145,7 +145,9 @@ func TestPayloadTooLargeOverWindowTriesMemberWithRoom(t *testing.T) {
s := New()
code, body := postAs(t, s, "", `{"model":"group/g","messages":[{"role":"user","content":"`+strings.Repeat("word ", 2400)+`"}]}`)
route := lastRoute(s)
if code != 200 || !strings.Contains(body, "hello") || a.n != 1 || b.n != 0 || c.n != 1 || len(route.Tries) != 2 || route.Tries[0].Status != 400 || route.Tries[0].Fail != failOverflow || route.Tries[0].Rest != nil {
// text past a's and b's windows isn't sent them at all (roomy): only
// c, which holds it, is asked
if code != 200 || !strings.Contains(body, "hello") || a.n != 0 || b.n != 0 || c.n != 1 || len(route.Tries) != 1 || route.Tries[0].ID != "c" {
t.Fatalf("text overflow: %d %s (a %d, b %d, c %d), tries %+v", code, body, a.n, b.n, c.n, route.Tries)
}
}
+137
View File
@@ -0,0 +1,137 @@
package gateway
import (
"net/http/httptest"
"slices"
"strings"
"testing"
"github.com/yetone/magpie/internal/provider"
)
// roomyMember saves a provider id serving model m on s, its window
// window tokens (0: not known).
func roomyMember(t *testing.T, id string, window int, s *scripted) {
t.Helper()
up := httptest.NewServer(s)
t.Cleanup(up.Close)
p := provider.Provider{ID: id, Name: strings.ToUpper(id), Key: "k", Chat: up.URL + "/v1", Models: []string{"m"}}
if window > 0 {
p.Contexts = map[string]int{"m": window}
}
if err := provider.Save(p); err != nil {
t.Fatal(err)
}
}
// A group's member whose model is known to take less than the request
// isn't asked it (dgqyushen on Discord: OpenCode Zen's free DeepSeek V4.1
// Flash, 200K, first, and a 1M subscription of it second). Asked, the
// free one only refuses it, and a refusal that doesn't say why, for a
// request not far enough past the window to be taken as too long for it
// (tooLongUnsaid's margin), reached the agent as the vendor's error while
// the next member had room. A request it holds still goes to it first.
func TestMemberTooSmallIsNotAsked(t *testing.T) {
fresh(t)
// the free member refuses a request past its window the way some
// vendors do, without saying it is too long
unsaid := `{"error":{"message":"Invalid request parameters"}}`
free := &scripted{replies: []reply{{400, "", unsaid}}}
paid := &scripted{replies: []reply{{200, "", chatOK}}}
roomyMember(t, "free", 2000, free)
roomyMember(t, "paid", 10000, paid)
if err := provider.SaveGroup(provider.Group{Name: "G", Members: []string{"free/m", "paid/m"}, Routing: provider.Ordered}); err != nil {
t.Fatal(err)
}
s := New()
past := strings.Repeat("word ", 1760) // about 2200 tokens as estimated
code, body := postAs(t, s, "", `{"model":"group/g","messages":[{"role":"user","content":"`+past+`"}]}`)
r := lastRoute(s)
if code != 200 || !strings.Contains(body, "hello") || free.n != 0 || paid.n != 1 {
t.Fatalf("past the free member's window: %d %s (free %d, paid %d)", code, body, free.n, paid.n)
}
if len(r.Tries) != 1 || r.Tries[0].ID != "paid" {
t.Fatalf("tries %+v", r.Tries)
}
if slices.ContainsFunc(r.Order, func(w Weighed) bool { return w.Provider == "free" }) {
t.Fatalf("the free member is still in the order: %+v", r.Order)
}
// a request it holds goes to it, first
free.replies = []reply{{200, "", chatOK}}
free.n, paid.n = 0, 0
code, body = postAs(t, s, "", `{"model":"group/g","messages":[{"role":"user","content":"hi"}]}`)
if code != 200 || free.n != 1 || paid.n != 0 {
t.Fatalf("within the window: %d %s (free %d, paid %d)", code, body, free.n, paid.n)
}
}
// A conversation that began on the free member, and is kept there by
// affinity, moves once it has grown past that member's window.
func TestConversationOutgrowingItsMemberMoves(t *testing.T) {
fresh(t)
free := &scripted{replies: []reply{{200, "", chatOK}}}
paid := &scripted{replies: []reply{{200, "", chatOK}}}
roomyMember(t, "free", 2000, free)
roomyMember(t, "paid", 10000, paid)
if err := provider.SaveGroup(provider.Group{Name: "G", Members: []string{"free/m", "paid/m"}, Routing: provider.Ordered}); err != nil {
t.Fatal(err)
}
s := New()
if code, body := postAs(t, s, "conv", `{"model":"group/g","messages":[{"role":"user","content":"hi"}]}`); code != 200 || free.n != 1 {
t.Fatalf("first turn: %d %s (free %d)", code, body, free.n)
}
big := strings.Repeat("word ", 2400)
code, body := postAs(t, s, "conv", `{"model":"group/g","messages":[{"role":"user","content":"hi"},{"role":"assistant","content":"hello"},{"role":"user","content":"`+big+`"}]}`)
if code != 200 || free.n != 1 || paid.n != 1 {
t.Fatalf("grown: %d %s (free %d, paid %d)", code, body, free.n, paid.n)
}
}
// What the check leaves alone: a member whose window isn't known, a
// request no member holds (the first is asked, and the agent told it
// overflowed, to compact), and one whose size can't be estimated.
func TestRoomyLeavesWhatItCantJudge(t *testing.T) {
fresh(t)
over := `{"error":{"message":"This model's maximum context length is 2000 tokens","code":"context_length_exceeded"}}`
unknown := &scripted{replies: []reply{{200, "", chatOK}}}
small := &scripted{replies: []reply{{400, "", over}}}
smaller := &scripted{replies: []reply{{400, "", over}}}
roomyMember(t, "unknown", 0, unknown)
roomyMember(t, "small", 2000, small)
roomyMember(t, "smaller", 1500, smaller)
for _, g := range []provider.Group{
{Name: "Unknown", Members: []string{"unknown/m", "small/m"}, Routing: provider.Ordered},
{Name: "None", Members: []string{"small/m", "smaller/m"}, Routing: provider.Ordered},
} {
if err := provider.SaveGroup(g); err != nil {
t.Fatal(err)
}
}
s := New()
big := strings.Repeat("word ", 2400)
code, body := postAs(t, s, "", `{"model":"group/unknown","messages":[{"role":"user","content":"`+big+`"}]}`)
if code != 200 || unknown.n != 1 || small.n != 0 {
t.Fatalf("window not known: %d %s (unknown %d, small %d)", code, body, unknown.n, small.n)
}
code, body = postAs(t, s, "", `{"model":"group/none","messages":[{"role":"user","content":"`+big+`"}]}`)
if code != 400 || !strings.Contains(body, "context_length_exceeded") || small.n != 1 || smaller.n != 0 {
t.Fatalf("no member holds it: %d %s (small %d, smaller %d)", code, body, small.n, smaller.n)
}
// a body that doesn't parse is no estimate: every candidate is left
cs := []candidate{
{p: provider.Provider{ID: "small", Contexts: map[string]int{"m": 2000}}, model: "m", rest: "small"},
{p: provider.Provider{ID: "big", Contexts: map[string]int{"m": 10000}}, model: "m", rest: "big"},
}
pl := planned{order: []Weighed{{ID: "small"}, {ID: "big"}}}
got, gotPl := roomy(cs, pl, provider.Chat, []byte(`{"messages":[`+strings.Repeat(`"word `, 4000)))
if len(got) != 2 || len(gotPl.order) != 2 {
t.Fatalf("unparsed: %d candidates, order %+v", len(got), gotPl.order)
}
// and one that does leaves the small one out, its order with it
got, gotPl = roomy(cs, pl, provider.Chat, []byte(`{"model":"g","messages":[{"role":"user","content":"`+big+`"}]}`))
if len(got) != 1 || got[0].rest != "big" || len(gotPl.order) != 1 || gotPl.order[0].ID != "big" {
t.Fatalf("parsed: %+v, order %+v", got, gotPl.order)
}
}