gateway: a reading that finds a vendor-timed quota rest's window renewed has the vendor asked once
RookieRicardoR on X: a GLM Coding Plan key ran out, they used a reset card (重置卡) on Zhipu's side, and magpie kept answering "limit reached" without asking Zhipu. Zhipu's 1308/1310 names the reset time, so the key rests by "resets" till it and timedHeld answers every request locally. Since #2718 a reading that finds the window less than full (renewed) doesn't lift a rest the vendor timed, only a window truly started again (restarted) does, because a vendor's usage can read low while its refusal stands. A reset bought on the vendor's side moves neither, so it was never noticed before the named time. Now liftRests, on renewal, lets such a hold go once for its named time (askOnRenewalLocked: askAt = now, the rest itself kept, recorded in restingUntil.renewAsked). The next request asks the vendor: an answer clears the rest as any answer does; refused again with the same time, it is held till then whatever later readings say, so #2718's repeated refusals don't come back. This applies to every provider whose windows magpie reads (Zhipu/Z.ai plan quota, sub2api balance URLs, subscriptions) and to quota and credit rests, not rate rests. Where no windows are read, the rest line's "Try now" (Unrest) already asks at once. The same tweet said the same prompt from Pi got Claude Code's earlier DeepSeek reply word for word. magpie keeps no reply to give a later request (classify caches routing verdicts, vision_cache image descriptions, prev_response rebuilds input; held answers are errors only), and magpie sets no temperature or seed for DeepSeek. TestSameRequestIsAskedEveryTime now holds that: the same bytes from Claude Code's and an OpenAI client's protocol, twice each, reach the vendor four times and get its four answers. Run (mote, at this commit on origin/main9494a38b4): - go test ./internal/gateway/ ./internal/provider/ -count=1 -timeout 45m: provider ok (150s); gateway FAIL (987s) on one test only, TestOpenCodeGoOwnFreeModelGetsNothingOfOpenCodes, red the same alone at origin/main9494a38b4(3 of 3) and filed as #7117. The log also has doneHold's "close of closed channel" panic, filed as #6690. - go test ./internal/gateway/ -run 'TestSameRequestIsAskedEveryTime| TestRenewalAsksAVendorTimedRestOnce' -count=2: ok - go test ./internal/gateway/ -run 'TestRenewalAsksAVendorTimedRestOnce| TestReadingKeepsARefusalsRest|TestAutoVisionKeepsOffARefusedAccount| TestKeyBackOnceItsWindowIsNotFull|TestZhipuRestsUntilItsReset|Held|Rest': ok - GOOS=linux and GOOS=windows go vet ./internal/gateway/ ./internal/provider/: ok - gofmt -l: clean Broken by hand: - askOnRenewalLocked's call taken out: TestRenewalAsksAVendorTimedRestOnce red ("the window read renewed, and the key is still held"). - its once-per-time guard taken out: red ("asked again for the same named time"). - a reply cache keyed by path and body wrapped round Handler: TestSameRequestIsAskedEveryTime red ("the vendor was asked 2 times for 4 requests"). Not tried: a real Zhipu reset card or a real GLM account; the test uses a sub2api window and Zhipu's reset wording. Bug 2 was not reproduced with real DeepSeek; the reporter's Requests trace would show both calls.
This commit is contained in:
File diff suppressed because one or more lines are too long
@@ -1616,6 +1616,10 @@ var restingUntil = struct {
|
||||
// found, from whichever page lifted it (zoecats on Discord: Try now
|
||||
// in the provider's editor left Routing at 429 until a restart)
|
||||
lifted map[string]time.Time
|
||||
// renewAsked is, by the key it rests by, the end of a rest the vendor
|
||||
// timed that a reading's renewal had asked again once
|
||||
// (askOnRenewalLocked): not asked so again till another time is named
|
||||
renewAsked map[string]time.Time
|
||||
}{m: map[string]time.Time{}, note: map[string]Rest{}, lifted: map[string]time.Time{}}
|
||||
|
||||
// liftedLocked notes that the rest by key was lifted now, with
|
||||
|
||||
@@ -108,6 +108,7 @@ func noRests() {
|
||||
restingUntil.m = map[string]time.Time{}
|
||||
restingUntil.note = map[string]Rest{}
|
||||
restingUntil.lifted = map[string]time.Time{}
|
||||
restingUntil.renewAsked = nil
|
||||
restingUntil.Unlock()
|
||||
codexHolds.Lock()
|
||||
codexHolds.m = nil
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
// RookieRicardoR on X: the same prompt sent to DeepSeek from Claude Code,
|
||||
// then from Pi, came back with the same words, and the reply was taken for
|
||||
// one magpie kept and gave again. magpie keeps no reply to give a later
|
||||
// request: each request, the same bytes from the same agent too, or from
|
||||
// another agent and protocol, is asked of the vendor, and answered with
|
||||
// what the vendor said to it.
|
||||
func TestSameRequestIsAskedEveryTime(t *testing.T) {
|
||||
fresh(t)
|
||||
var mu sync.Mutex
|
||||
asked := 0
|
||||
up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
io.Copy(io.Discard, r.Body)
|
||||
mu.Lock()
|
||||
asked++
|
||||
n := asked
|
||||
mu.Unlock()
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
text := fmt.Sprintf("answer number %d", n)
|
||||
if strings.HasSuffix(r.URL.Path, "/messages") {
|
||||
fmt.Fprintf(w, `{"id":"msg_%d","type":"message","role":"assistant","model":"deepseek-v4","content":[{"type":"text","text":%q}],"stop_reason":"end_turn","usage":{"input_tokens":3,"output_tokens":3}}`, n, text)
|
||||
return
|
||||
}
|
||||
fmt.Fprintf(w, `{"id":"c%d","object":"chat.completion","model":"deepseek-v4","choices":[{"index":0,"message":{"role":"assistant","content":%q},"finish_reason":"stop"}],"usage":{"prompt_tokens":3,"completion_tokens":3}}`, n, text)
|
||||
}))
|
||||
defer up.Close()
|
||||
if err := provider.Save(provider.Provider{ID: "ds", Name: "DS", Key: "k", Models: []string{"deepseek-v4"},
|
||||
Chat: up.URL + "/v1", Anthropic: up.URL + "/anthropic"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
const prompt = "write a haiku about magpies"
|
||||
claude := `{"model":"ds/deepseek-v4","max_tokens":64,"messages":[{"role":"user","content":"` + prompt + `"}]}`
|
||||
chat := `{"model":"ds/deepseek-v4","messages":[{"role":"user","content":"` + prompt + `"}]}`
|
||||
var replies []string
|
||||
for i, q := range []struct{ path, body string }{
|
||||
{"/v1/messages", claude}, {"/v1/messages", claude}, {"/v1/chat/completions", chat}, {"/v1/chat/completions", chat},
|
||||
} {
|
||||
code, body := post(t, q.path, q.body)
|
||||
if code != http.StatusOK {
|
||||
t.Fatalf("request %d (%s): %d %s", i, q.path, code, body)
|
||||
}
|
||||
replies = append(replies, body)
|
||||
}
|
||||
if asked != len(replies) {
|
||||
t.Fatalf("the vendor was asked %d times for %d requests", asked, len(replies))
|
||||
}
|
||||
for i, body := range replies {
|
||||
if want := fmt.Sprintf("answer number %d", i+1); !strings.Contains(body, want) {
|
||||
t.Errorf("request %d answered %s, want the vendor's own answer to it (%q)", i, body, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
// RookieRicardoR on X: a GLM key refused out of its allowance till the
|
||||
// time Zhipu named, then given a reset (Zhipu's 重置卡) on the vendor's
|
||||
// side, was still answered "limit reached" by magpie on every request
|
||||
// till that time, the vendor never asked. A reading of the key's windows
|
||||
// that finds the one it was out of full no more has the vendor asked once
|
||||
// again; the rest itself stands (#2718), and refused again with the same
|
||||
// time the key is held till it, however often its windows read less than
|
||||
// full.
|
||||
func TestRenewalAsksAVendorTimedRestOnce(t *testing.T) {
|
||||
fresh(t)
|
||||
provider.ForgetBalances()
|
||||
t.Cleanup(provider.ForgetBalances)
|
||||
old := keyAllowance
|
||||
keyAllowance = provider.KeyAllowance // the key's windows as read, here
|
||||
t.Cleanup(func() { keyAllowance = old })
|
||||
reset := time.Now().Add(3 * time.Hour).Truncate(time.Second)
|
||||
var mu sync.Mutex
|
||||
used := 800
|
||||
relay := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
mu.Lock()
|
||||
u := used
|
||||
mu.Unlock()
|
||||
fmt.Fprintf(w, `{"isValid":true,"mode":"quota_limited","status":"active","rate_limits":[{"window":"5h","limit":800,"used":%d,"remaining":%d,"reset_at":%q}]}`, u, 800-u, reset.Format(time.RFC3339))
|
||||
}))
|
||||
defer relay.Close()
|
||||
if err := provider.Save(provider.Provider{ID: "kr", Name: "KR", Key: "sk-r", Models: []string{"glm-5.2"},
|
||||
Chat: relay.URL + "/v1", BalanceURL: relay.URL + "/v1/usage"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
saved, err := provider.Find("kr")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
c := perKey(*saved, "glm-5.2", provider.Chat)[0]
|
||||
t.Cleanup(func() { clearRest(c.restKey()) })
|
||||
provider.KeyBalances(context.Background()) // its five hours read: used up
|
||||
s := &Server{}
|
||||
refusal := []byte(fmt.Sprintf(`{"error":{"message":"Usage limit reached. Your usage will reset at %s UTC+8, upgrade for more","type":"rate_limit_exceeded"}}`,
|
||||
reset.In(zhipuZone).Format("2006-01-02 15:04:05")))
|
||||
refuse := func() {
|
||||
t.Helper()
|
||||
if r := s.restAfter(c, 429, http.Header{}, refusal); r.Why != failQuota || r.By != "resets" {
|
||||
t.Fatalf("refused till %s: rests by %s (%s)", reset.Format(time.TimeOnly), r.By, r.Why)
|
||||
}
|
||||
}
|
||||
held := func() bool {
|
||||
_, _, ok := timedHeld([]candidate{c})
|
||||
return ok
|
||||
}
|
||||
read := func(u int) {
|
||||
mu.Lock()
|
||||
used = u
|
||||
mu.Unlock()
|
||||
provider.ForgetBalances()
|
||||
provider.KeyBalances(context.Background())
|
||||
}
|
||||
refuse()
|
||||
if !held() {
|
||||
t.Fatal("refused till a named time: not held")
|
||||
}
|
||||
read(800) // read again, still used up: nothing changes
|
||||
if !held() {
|
||||
t.Fatal("a reading that still finds the window full let the hold go")
|
||||
}
|
||||
read(0) // the reset bought on the vendor's side
|
||||
if held() {
|
||||
t.Fatal("the window read renewed, and the key is still held till the vendor's time: the vendor is never asked")
|
||||
}
|
||||
if _, ok := restOf(c.restKey()); !ok {
|
||||
t.Fatal("the renewal lifted the rest itself; only the hold is let go (#2718)")
|
||||
}
|
||||
refuse() // asked, and refused again with the same time
|
||||
if !held() {
|
||||
t.Fatal("refused again with the same time: not held")
|
||||
}
|
||||
read(800)
|
||||
read(0) // its windows read less than full again, the same time standing
|
||||
if !held() {
|
||||
t.Fatal("asked again for the same named time: a renewal asks once for it")
|
||||
}
|
||||
}
|
||||
@@ -971,7 +971,10 @@ func liftRests(agent, user string, vendorTill bool) {
|
||||
if r.agent != agent || !strings.EqualFold(r.user, user) || !(r.Why == failQuota || r.By == "window" || r.Why == failCredit && agent == "codex") {
|
||||
continue
|
||||
}
|
||||
if vendorTill != (r.By == "resets" || r.By == "retry-after") {
|
||||
if timed := r.By == "resets" || r.By == "retry-after"; vendorTill != timed {
|
||||
if timed && r.Why != failRate {
|
||||
askOnRenewalLocked(k, r, now)
|
||||
}
|
||||
continue
|
||||
}
|
||||
delete(restingUntil.m, k)
|
||||
@@ -980,6 +983,35 @@ func liftRests(agent, user string, vendorTill bool) {
|
||||
}
|
||||
}
|
||||
|
||||
// askOnRenewalLocked has a rest the vendor gave the time of, out of quota
|
||||
// or credit, asked again once, without lifting it, when a reading of its
|
||||
// windows finds the one it was out of full no more while the time the
|
||||
// vendor named still stands: a reset bought on the vendor's side (Zhipu's
|
||||
// 重置卡, RookieRicardoR on X) renews the window there, and every request
|
||||
// was answered with the refusal till the time it named, the vendor never
|
||||
// asked. The rest stands (#2718: the vendor's usage can say less than full
|
||||
// while its refusal does too), so a pick that keeps off a resting account
|
||||
// still does; only the hold is let go (asksAt), for the next request to
|
||||
// ask. Once for each time the vendor named: refused again with the same
|
||||
// time, the new rest holds till it, whatever readings say, as before.
|
||||
func askOnRenewalLocked(k string, r Rest, now time.Time) {
|
||||
until, ok := restingUntil.m[k]
|
||||
if !ok || !now.Before(until) || restingUntil.renewAsked[k].Equal(until) {
|
||||
return
|
||||
}
|
||||
if restingUntil.renewAsked == nil {
|
||||
restingUntil.renewAsked = map[string]time.Time{}
|
||||
}
|
||||
for x, t := range restingUntil.renewAsked {
|
||||
if !now.Before(t) {
|
||||
delete(restingUntil.renewAsked, x)
|
||||
}
|
||||
}
|
||||
restingUntil.renewAsked[k] = until
|
||||
r.first, r.askAt = false, now
|
||||
restingUntil.note[k] = r
|
||||
}
|
||||
|
||||
// creditsKnown lifts the rests out of its allowance of a ChatGPT account
|
||||
// found to go on past it on credits (provider.OnCredits), whatever time
|
||||
// the refusal named: a turn turned away before magpie knew of the credits
|
||||
|
||||
Reference in New Issue
Block a user