diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index 3b7f7ac94..6686e1dd8 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -295,7 +295,7 @@ recorded as a prediction failure (`noPrediction`). - The Providers page shows a subscription account's rests in force on its row there too: `RestsUnder("@")` lists them, `providerJSON.accountRests` gives them by user in lower case (the account's own, and each model's, with `Rest.Model`, `Until`, `By` and the vendor's words, `Rest.Error`), and the row's line says which model, why and when it is back, the vendor's words beside it, with Try now lifting it by its key (`accountRestLines` in app.js). Before, only a key's rest showed there, and a WorkBuddy AI account whose model rested on a 429 "将在 … 重置" read as fine, its credits 82% left (maxleebeta on Discord; `TestRateLimitedModelListedUnderAccount`, `TestAccountRestsInProviderState`, `account-rest.test.cjs`). - A group member let go for no first content within the group's `FirstToken` (`hw.slow` in [`gateway.go`](../../internal/gateway/gateway.go), 504 "no first token in Ns", `failSlow`) doesn't rest the first time: a long prompt is slow to start anywhere. Slow again on the same account's model with no answer from it in between, and within `slowForget` (30 minutes) of its last slow start, that model rests on that account (`restSlow` in [`routing.go`](../../internal/gateway/routing.go), keyed by `restID`, `Rest.Model` set): a minute from the second time (`slowRests`), doubling each time after, up to the provider's rest cap (`RestCapOr(longestRetry)`), and never for a provider whose cap is off. Its answer clears the count (`servedCandidate`). A request its client cancelled counts nothing, as the cancel is read before `hw.slow`. The walk has a total budget, `groupBudget` (540s, under the 600s a client waits): a member asked when little of it is left gets only what is left (`hw.budgeted`), and when it runs out no further member is asked, nothing rests, and the error names the budget (504 "no member of the group answered within its 540s budget", #5113, mycf_711: nine members at 60s took 660s and the client's hang-up was told as the last member's failure; `TestGroupWalkStopsAtItsBudget`). Before it, each new request asked the stalled member first again and waited out the whole `FirstToken` (小八 on Discord: a WorkBuddy account's kimi-k3-1 and glm-5.3 stalled 58 times on the vendor's per-model token limit, 15 times in 17 minutes in one session). The same model on another account and another model on the same account are asked as before (`TestSlowStartsRestTheModelOnItsAccount`, `TestCanceledSlowStartRestsNothing`; the Routing page's story, `routing-went-on.test.cjs`). - A plugin's try that isn't the last candidate is sent with `x-magpie-fallback: 1` (`provider.FallbackHeader`, `withFallback`), so a plugin whose vendor queues the request (Qoder's 10605, CodeArts' `queue-status: queued`) answers a `busy` 503 with Retry-After and the queue's reason at once instead of waiting minutes in the queue, and the next is asked; the last candidate isn't told and waits as the vendor's client does ([provider-plugins](provider-plugins.md#whether-another-candidate-follows), `TestPluginToldAnotherFollows`). -- A 402 is out of credit, unless it speaks of a usage limit (`usedUpWords`) and nothing of money (`creditWords`, `insufficient_quota`): then it is out of quota, and rests only the model when the account's windows say its pool is the one used up (`pooled`). Factory answers Standard's pool used up with 402 "You've reached your weekly standard usage limit (resets in …). Switch to Droid Core …"; read as credit, it rested the account 30 minutes and its Droid Core models with it (#1979). Both the built-in's windows and the plugin's (Standard's `notModels`, Core's `models`) are held to it. As a quota rest it lasts until the time the refusal names (`resetsAfter`: "resets in 0h 19min", "resets in 2d 3h", held to `longestWritten`), else the window's end, else `quotaRest` or the provider's own `quota-rest`, and is lifted once a reading finds the window renewed (`renewed`), which a credit rest never was (`TestFactoryStandardOutLeavesCore`, `TestPaymentRequiredReadByItsWords`, `TestResetsInWords`). An account whose windows weren't read yet (a start, or a reading that failed) can't tell the model's pool from the account's, so it rests whole, and `narrowWhenRead` waits off the request for a reading (`AwaitAllowance`, up to `allowanceWait`) and moves the rest to the model alone (`restID`, the same end) when the reading says its pool is the one used up; no reading in time, or one that says the whole account, leaves the account's rest, as does a rest lifted or made again meanwhile (#2036; `TestFactoryStandardOutLeavesCore`'s unread case, `TestResetsInWords`). The request itself isn't held for the reading: it has failed over already, and the rest's scope only matters to later requests. +- A 402 is out of credit, unless it speaks of a usage limit (`usedUpWords`) and nothing of money (`creditWords`, `insufficient_quota`): then it is out of quota, and rests only the model when the account's windows say its pool is the one used up (`pooled`). Factory answers Standard's pool used up with 402 "You've reached your weekly standard usage limit (resets in …). Switch to Droid Core …"; read as credit, it rested the account 30 minutes and its Droid Core models with it (#1979). Both the built-in's windows and the plugin's (Standard's `notModels`, Core's `models`) are held to it. As a quota rest it lasts until the time the refusal names (`resetsAfter`: "resets in 0h 19min", "resets in 2d 3h", held to `longestWritten`), else the window's end, else `quotaRest` or the provider's own `quota-rest`, and is lifted once a reading finds the window renewed (`renewed`), which a credit rest never was (`TestFactoryStandardOutLeavesCore`, `TestPaymentRequiredReadByItsWords`, `TestResetsInWords`). An account whose windows weren't read yet (a start, or a reading that failed), or whose reading holds a window of some models only (Claude's Opus, Sonnet or Fable week) with none known full, can't tell the model's pool from the account's, so it rests whole, and (`Allowance.Scoped`; `TestClaudeFableWeekRestsFableOnly`, kaitokiku on X: Claude Code's "You've hit your limit" names no window) `narrowWhenRead` waits off the request for a reading (`AwaitAllowance`, up to `allowanceWait`) and moves the rest to the model alone (`restID`, the same end) when the reading says its pool is the one used up; no reading in time, or one that says the whole account, leaves the account's rest, as does a rest lifted or made again meanwhile (#2036; `TestFactoryStandardOutLeavesCore`'s unread case, `TestResetsInWords`). The request itself isn't held for the reading: it has failed over already, and the rest's scope only matters to later requests. - Codex offers its image tool (the `image_gen` namespace, #870) to every magpie provider. When a provider other than a ChatGPT sign-in or openai.com answers a bare 400, `attempt` asks it once more without the tool (`image_tool.go`). This happens both passed through and translated. If that works, the provider is marked unfit for the tool (`tool:image_gen`) and isn't offered it again. If it doesn't, the tool is restored and the 400 stands (#949). - A turn the agent stopped with its tool call still out is replayed by the client with the call and no result, and Google's APIs turn a history whose call turn goes unanswered away with 400, every later turn of the conversation with it. The Gemini build (`buildCodeAssistSent`, which serves a Google sign-in, Vertex AI and a custom provider's Gemini API alike) answers such a call with the synthetic result the chat build pairs an interrupted turn's call with (`pairToolMessages`, #1275), right after the calls (`pairFunctionTurns`, #1560): beside the answers the client sent there, or in a user turn of its own before what the user said, since a turn mixing a `functionResponse` with text is turned away too (#1533), and so is one mixing it with an image: on Vertex AI a tool's images (Codex's view_image) go in a user turn of their own after the response (`buildCodeAssistSent`, Voo_Ler on X); a Claude model on Antigravity gets it in the one tool_result turn. A call with no id counts as answered by a response of its name. A second answer to one call is left out, with the images it carried, before the turns are built (`dropSecondAnswers`, #2262): Google refuses a call turn whose `functionResponse` count differs from its `functionCall` count, and the Chat and Messages builds already keep the first answer. The Responses build (`buildResponses`) leaves it out the same way. A call made again under the same id takes an answer of its own. A Gemini client that keeps no ids answers two calls of one function by name in their order, and each answer goes to its own call (`parseGemini`), not both to the latest. `TestGeminiDropsASecondAnswer`, `TestSecondAnswerDroppedWithItsImages`, `TestGeminiClientUnnamedCallsAnsweredInOrder`. - A request built for a Messages upstream (`buildAnthropic`: a Chat, Responses or Gemini client translated) has its tool exchanges mended after its messages are built (`pairToolBlocks`, #1558, ggbdpq), since Anthropic answers 400 for a `tool_use` the next message doesn't answer and for a `tool_result` naming no call of the message before it. A call left unanswered gets the synthetic interrupted result, `is_error` set, first in the user message after it or in one of its own; a result that answers no call goes as a text block with what it said (its images as they came); a second answer to one call is dropped. A well-formed exchange goes as it was built. An Anthropic client relayed to a Messages upstream isn't mended. [`anthropic_tool_pairing_test.go`](../../internal/gateway/anthropic_tool_pairing_test.go). diff --git a/internal/gateway/claude_fable_week_rest_test.go b/internal/gateway/claude_fable_week_rest_test.go new file mode 100644 index 000000000..570238f8a --- /dev/null +++ b/internal/gateway/claude_fable_week_rest_test.go @@ -0,0 +1,67 @@ +package gateway + +import ( + "context" + "net/http" + "sync" + "testing" + "time" + + "github.com/yetone/magpie/internal/provider" +) + +// A Claude account's Fable week used up rests Fable on it, not the account +// (kaitokiku on X: the account hit its Fable limit with the other weekly +// quota left, and every model 429'd on it). Claude Code's refusal says +// only "You've hit your limit", and its rate_limit_info may not say which +// window (rejected, no rateLimitType: the transcript's own row), so the +// reading held before the refusal still has Fable at 60%. The account +// rests at first; once its windows are read again with the Fable week +// full, the rest is Fable's alone and Opus routes there again. +func TestClaudeFableWeekRestsFableOnly(t *testing.T) { + old, oldAwait := allowances, awaitAllowance + defer func() { allowances, awaitAllowance = old, oldAwait }() + defer narrowing.Wait() + fresh(t) + var mu sync.Mutex + read := map[string]provider.Allowance{} + allowances = func(string) map[string]provider.Allowance { + mu.Lock() + defer mu.Unlock() + return read + } + const user = "fable@example.com" + five, week := time.Now().Add(2*time.Hour).Unix(), time.Now().Add(4*24*time.Hour).Unix() + note := func(fable float64) { + mu.Lock() + defer mu.Unlock() + read = map[string]provider.Allowance{user: provider.ClaudeAllowanceForTest([]provider.ClaudeLimit{ + {Kind: "five_hour", Used: 0.2, ResetsAt: five}, + {Kind: "seven_day", Used: 0.4, ResetsAt: week}, + {Kind: "seven_day_overage_included", Used: fable, ResetsAt: week}, + }, time.Now())} + } + note(0.6) + awaitAllowance = func(_ context.Context, agent, u string) bool { + note(1) + return true + } + acct := func(model string) candidate { + return candidate{p: provider.Provider{ID: "claude", Account: &provider.Account{Agent: "claude", User: user}}, model: model, rest: "claude"} + } + s := &Server{} + fable := acct("claude-fable-5-1") + r := s.restAfter(fable, http.StatusTooManyRequests, http.Header{}, []byte(`{"type":"error","error":{"type":"rate_limit_error","message":"You've hit your limit · resets 5:58am"}}`)) + if r.Why != failQuota { + t.Fatalf("rest: %+v", r) + } + narrowing.Wait() + if got, ok := restingOf(fable); !ok || got.Key != fable.restID() || got.Model != "claude-fable-5-1" { + t.Fatalf("Fable after the reading: %+v %v, want its own rest", got, ok) + } + for _, m := range []string{"claude-opus-5-5", "claude-sonnet-5-5", "claude-haiku-4-5"} { + if _, ok := restingOf(acct(m)); ok { + t.Fatalf("%s rests on an account whose Fable week is used up", m) + } + } +} diff --git a/internal/gateway/routing.go b/internal/gateway/routing.go index 4cb23fedd..70820278e 100644 --- a/internal/gateway/routing.go +++ b/internal/gateway/routing.go @@ -1473,6 +1473,14 @@ func (s *Server) restAfterMarked(c candidate, status int, header http.Header, bo pooled := why == failQuota && c.pooled(now) // and none to tell from: the account rests, narrowed once read (#2036) unread := why == failQuota && c.p.Account != nil && len(allowances(c.p.Account.UsageAgent())[c.p.Account.User]) == 0 + // or read before the model's own window filled: its pool is among them, + // no window known full, and the refusal (Claude Code's "You've hit + // your limit" names no window) may be that pool's. The reading asked + // for below tells (Fable's week used up, the other weekly quota left: + // kaitokiku on X) + if !unread && why == failQuota && !pooled && c.p.Account != nil && c.model != "" && c.full(now).IsZero() { + unread = allowances(c.p.Account.UsageAgent())[c.p.Account.User].Scoped(c.model) + } // a model the key's plan doesn't serve rests alone, counted by itself // (#1235): the key's other models are still served. So does a ZCode // trial entry zcode.z.ai's firewall blocked (zcodeTrialBlocked): the diff --git a/internal/provider/claude_limits.go b/internal/provider/claude_limits.go index b8c2b4938..0021551fa 100644 --- a/internal/provider/claude_limits.go +++ b/internal/provider/claude_limits.go @@ -165,3 +165,23 @@ func keptClaudeWindows(key string) []QuotaWindow { } return out } + +// ClaudeAllowanceForTest is the allowance routing weighs for limits as +// Claude Code told them, for the gateway's tests. +func ClaudeAllowanceForTest(ls []ClaudeLimit, now time.Time) Allowance { + var ws []QuotaWindow + for _, l := range ls { + for _, k := range claudeKinds { + if k.kind != l.Kind { + continue + } + w := QuotaWindow{Name: k.name, Used: l.Used * 100, Span: k.span, Model: k.model} + if l.ResetsAt > 0 { + t := time.Unix(l.ResetsAt, 0) + w.ResetsAt = &t + } + ws = append(ws, w) + } + } + return allowanceOf(ws, now) +} diff --git a/internal/provider/routing.go b/internal/provider/routing.go index b9bba9dfd..0a2cd25b2 100644 --- a/internal/provider/routing.go +++ b/internal/provider/routing.go @@ -689,6 +689,14 @@ func (a Allowance) Full(model string, share float64, now time.Time) time.Time { return t } +// Scoped says whether some window of the allowance counts some models only +// and counts model: Opus's or Fable's own week. A refusal of model with none +// of its windows read full may be that window's, read before it filled. +func (a Allowance) Scoped(model string) bool { + model = strings.ToLower(model) + return slices.ContainsFunc(a, func(l Limit) bool { return (l.Model != "" || l.matches != nil) && l.applies(model) }) +} + // Pooled says whether a refusal of model for its allowance leaves the // account's other models alone: the windows that count model and are full // at share are each of some models only (Opus's own week, Cursor's Other