Files
magpie/internal/gateway/rest_write_test.go
T
yetone 27099f9fc5 gateway: a vendor's named quota time replaces magpie's guess, though sooner (#3289)
ggbdpq's change keeps the later of two rests. That also kept a quota
rest magpie only guessed (a refusal naming no time: quotaRest's 15
minutes, asked again a minute on, askAt set) when the same refusal
came back naming its time, 2 minutes say: the account sat out the
guess. A guessed rest now gives way to the same kind's vendor-named
time ("resets" or "retry-after"); another kind's shorter rest (#3289's
429 minute beside a 402) still doesn't shorten it.
TestNamedQuotaTimeReplacesAGuess.

Reviewed and landed as one batch of 12 commits (gua's #4593, #3269,
#3881, #2887, #3289, #2718, #2855, Edward4226's #2718 key-path
sibling, and four review follow-ups). Run for the batch, whose last
commit's tree is 5d58a75f3:
- Full suite before the rebase (base d307aa648, wsl-run magpie-desktop,
  go test -tags nogui -count=1 -timeout 45m ./...): 81 packages ok. Reds,
  all with issues and none in code this batch touches: internal/agent
  TestInstalledVersion, TestGrokInstalled, TestOmpDetectedWithPiDir
  (#4033, #3548, #3141); gateway TestUnroutedHeldReportSaved (#4300);
  gui TestSettingsSaveKeepsWhatItDoesNotSend (#4514) and
  TestColdTurnsTaken (#4510); provider
  TestClaudeAccountServesModelsListedSinceItsFetch (#3174). Run alone at
  origin/main 573b21f4b, TestGrokInstalled, TestOmpDetectedWithPiDir
  and TestSettingsSaveKeepsWhatItDoesNotSend are red there too. The
  other four pass there alone.
- After the rebase onto origin/main 573b21f4b, at this tree:
  internal/usage, update, gateway and provider ok. In internal/agent,
  the #4033/#3141 install-detection reds plus TestCopilotFolderFrom-
  AnIDEPluginIsNotTheCLI and TestZedAppPath. Those two are flaky the
  same way at origin/main (-count=10 alone: 4 and 5 of 10 red) and are
  already listed in #4033. The #3269 tests (TestCopilotLauncher*) pass
  5 of 5.
- Rebased onto origin/main ef63ef4a2. The #2855 commit met 0b9727ec9
  (#2974) in responses.go: the streamed item's done now takes both, the
  upstream's own id (thinkUp) and the made-over item; and in
  gateway-routing.md main's paragraph is kept with #2855's clause. That
  matches gua's latest head (range-diff: context only). At tree d7c76c6fa:
  internal/gateway, provider, usage, redact and update ok; vet
  GOOS=linux -tags nogui ./internal/..., darwin and GOOS=windows for
  gateway and provider.
- Rebased last onto origin/main d8f7d089f (5 commits: internal/agent
  and GUI files only). At tree 0d4bfd8c8, the pushed one: internal/agent's
  TestCopilotLauncher*, TestClaude*, TestOwn* and TestVSCode* ok, -count=3;
  TestCopilotFolderFromAnIDEPluginIsNotTheCLI red once there, as it is at
  main (#4033). Vet of internal/agent: darwin, linux and windows.
- gofmt -l clean. On mote: go vet darwin, GOOS=linux -tags nogui and
  GOOS=windows.
- Broken by hand, each turning its guard red: the lift gate
  (TestReadingKeepsARefusalsRest, TestAutoVisionKeepsOffARefusedAccount);
  the named-time condition (TestNamedQuotaTimeReplacesAGuess); the
  filter-chain hop (WholeReply/glm-5.3-flash); Edward's aAt
  (TestKeyAllowanceElapsedResetStartsAgain); and the old
  magpieMadeReasoning, which panics in TestMadeReasoningSaysItsTextOnce/
  no_summary. Every new test of gua's is red at base d307aa648.
Not tried: real OpenAI, DeepSeek, GLM or ChatGPT accounts; a real VS Code
1.144 install on Windows; a GUI run (no GUI files are touched).
2026-11-01 07:06:19 +08:00

122 lines
5.0 KiB
Go

package gateway
import (
"net/http"
"testing"
"time"
"github.com/yetone/magpie/internal/provider"
)
// Concurrent requests on one provider can fail differently: a 402 out of
// credit rests the account for half an hour, and a 429 answering at the
// same moment — the first request still holding the vendor's only slot —
// rests it for the minute a rate limit starts at. Written last, the
// shorter rest used to replace the longer one (#3289, wjq990112), and the
// account was asked again as soon as it ended, refused, and rested again,
// round after round. A rest that ends later stands, as one narrowed to a
// model keeps the longer of the two; a longer rest still replaces a
// shorter one.
func TestShorterRestDoesNotReplaceLongerOne(t *testing.T) {
forgetRouting()
old := allowances
allowances = func(string) map[string]provider.Allowance {
return map[string]provider.Allowance{
"me@x.com": {{Used: 5, Span: 30 * 24 * time.Hour}},
}
}
oldStale := staleAllowance
staleAllowance = func(string, string) {}
defer func() { allowances, staleAllowance = old, oldStale }()
acct := candidate{
p: provider.Provider{ID: "sub2tok", Account: &provider.Account{Agent: "factory", User: "me@x.com"}},
model: "glm-5.3-flash",
rest: "sub2tok#me@x.com",
}
s := &Server{}
s.Unrest(acct.restKey())
credit := s.restAfter(acct, http.StatusPaymentRequired, http.Header{}, []byte(`{"error":{"message":"insufficient_balance"}}`))
if credit.Why != failCredit || credit.By != "credit" {
t.Fatalf("a 402 insufficient_balance rests by %q (%s), not credit", credit.By, credit.Why)
}
h := http.Header{}
h.Set("Retry-After", "1")
rate := s.restAfter(acct, http.StatusTooManyRequests, h, []byte(`{"error":{"message":"Rate limit exceeded","type":"rate_limit_error"}}`))
if rate.Why != failRate {
t.Fatalf("the 429 rests as %s, not rate", rate.Why)
}
r, ok := restOf(acct.restKey())
if !ok {
t.Fatal("the account rests no more")
}
if r.Why != failCredit {
t.Fatalf("the rate rest replaced the credit rest: resting by %q (%s)", r.By, r.Why)
}
if d := time.Until(r.Until); d < creditRest-time.Minute {
t.Fatalf("resting %v, not the credit rest of about %v", d.Round(time.Second), creditRest)
}
// a longer rest still replaces a shorter one
quota := s.restAfter(acct, http.StatusTooManyRequests, http.Header{}, []byte(`{"error":{"type":"usage_limit_reached","resets_in_seconds":691200}}`))
if quota.Why != failQuota || quota.By != "resets" {
t.Fatalf("the 8-day refusal rests by %q (%s), not resets", quota.By, quota.Why)
}
if r, ok := restOf(acct.restKey()); !ok || r.Why != failQuota || time.Until(r.Until) < 7*24*time.Hour {
t.Fatalf("the longer quota rest didn't take: %v (%s), %v", ok, r.Why, time.Until(r.Until).Round(time.Minute))
}
}
// A quota rest magpie only guessed (a refusal that named no time: the
// 15 minutes of quotaRest, asked again a minute on) gives way to the same
// refusal's time when the vendor names one later, though it is sooner:
// the guess stood in for the vendor's word. Another kind's shorter rest
// still doesn't shorten it.
func TestNamedQuotaTimeReplacesAGuess(t *testing.T) {
forgetRouting()
old := allowances
allowances = func(string) map[string]provider.Allowance { return nil }
oldStale := staleAllowance
staleAllowance = func(string, string) {}
defer func() { allowances, staleAllowance = old, oldStale }()
acct := candidate{
p: provider.Provider{ID: "sub2tok", Account: &provider.Account{Agent: "factory", User: "me@x.com"}},
model: "glm-5.3-flash",
rest: "sub2tok#me@x.com",
}
s := &Server{}
s.Unrest(acct.restKey())
t.Cleanup(func() { s.Unrest(acct.restKey()) })
guess := s.restAfter(acct, http.StatusTooManyRequests, http.Header{}, []byte(`{"error":{"type":"usage_limit_reached","message":"You have hit your usage limit"}}`))
if guess.Why != failQuota || guess.By != "quota" || guess.askAt.IsZero() {
t.Fatalf("the refusal naming no time rests by %q (%s), askAt %v: not a guess", guess.By, guess.Why, guess.askAt)
}
// a rate limit's minute doesn't shorten the guess
h := http.Header{}
h.Set("Retry-After", "1")
if rate := s.restAfter(acct, http.StatusTooManyRequests, h, []byte(`{"error":{"message":"Rate limit exceeded","type":"rate_limit_error"}}`)); rate.Why != failRate {
t.Fatalf("the 429 rests as %s, not rate", rate.Why)
}
if r, ok := restOf(acct.restKey()); !ok || r.Why != failQuota || r.By != "quota" {
t.Fatalf("a rate limit's minute replaced the quota guess: %v %q (%s)", ok, r.By, r.Why)
}
named := s.restAfter(acct, http.StatusTooManyRequests, http.Header{}, []byte(`{"error":{"type":"usage_limit_reached","resets_in_seconds":120}}`))
if named.Why != failQuota || named.By != "resets" {
t.Fatalf("the refusal naming 2 minutes rests by %q (%s), not resets", named.By, named.Why)
}
r, ok := restOf(acct.restKey())
if !ok || r.By != "resets" {
t.Fatalf("the vendor's own time didn't replace magpie's guess: %v %q", ok, r.By)
}
if d := time.Until(r.Until); d > 3*time.Minute || d < time.Minute {
t.Fatalf("resting %v, not the vendor's 2 minutes", d.Round(time.Second))
}
}