Files
magpie/internal/gateway/codex_autoreset.go
T
yetone 5a94eec3ae gateway: a request held 30s before routing in no known wait is answered then
sharwowwow on X: "转圈两分钟才报 504,这个超时阈值本身就很折磨人。网关要是能
早点失败、早点给明确错误,排查能省不少时间。" A request held before any
route was answered 504 only after unroutedMost (2m), whatever held it.

Now the time a request spends in a wait magpie knows of is added up as it
happens (noteWait/waited, the union of overlapping waits), and a request
held unroutedUnknown (30s) outside them gets the same 504 and message
then. unroutedMost (2m) stays the cap for one in known waits. Known waits,
each read from the code between counted and noteRoute:
- the request's body arriving: r.Body is wrapped (waitedBody), so every
  read of it (keyLimited, requestBody, readRequestBody) counts;
- masking (noteMasking);
- System One's or the decision model's classifier (askWaited);
- an image's description (seenBody);
- Codex's auto reset before the route (autoReset);
- plugins' gateway hooks / plugin host start (GatewayBegin) and JS
  gateway middleware (Begin, Request);
- every notePhase (slot, rpm, upstream); these come after the route for
  watched requests today, so it only guards a future change.
What is left is magpie's own work (catalog build, parsing, planning,
affine, reading the usage log), ~8.5s at its slowest (a cold catalog
sync); 30s is about three times that, with room for a loaded machine.
The log says "30s of it in no wait magpie knows of".

Run at this tree (rebased on origin/main 9120acaff):
- gofmt -l internal/gateway: clean.
- go vet ./internal/gateway/... on darwin, GOOS=linux, GOOS=windows: ok.
- go test -timeout 45m ./internal/gateway/...: ok (478.0s).
  Also ok on the earlier bases a5ce158e5 (655.8s) and 7d075df9d (448.1s).
Not run: the full go test ./... and go vet ./..., because the machine's
disk was full (under 1GB free for over 20 minutes; a build and one
gateway run failed with "no space left on device", every red naming it). No -race run.

Broken by hand, each test red, then restored:
- without the 30s answer (u.giveUp(true)),
  TestUnroutedUnknownHoldAnsweredSooner: not answered before unroutedMost;
- without the body wrap, TestUnroutedSlowBodyNotCutOff: answered 504
  while its body was still arriving;
- without masking's excuse, TestUnroutedMaskingNotCutOff: answered 504
  while it was masked.
TestUnroutedSlotWaitNotCutOff stays green without notePhase's excuse (the
slot wait is after the route); it guards that a slot wait is never cut.

Not tried: no test of its own for the classifier, auto reset, gateway
hook, JS middleware or image-description excuses; no run in the real app
or against a real provider.
2026-10-26 19:04:27 +08:00

101 lines
3.5 KiB
Go

package gateway
// A Codex rate-limit reset spent by itself: when everyone a request could
// go to is out of their allowance, a ChatGPT account the user lets spend
// its resets, its weekly window used up, spends one and is asked again
// (provider.AutoUseCodexReset has the rules).
import (
"context"
"log"
"slices"
"strings"
"time"
"github.com/yetone/magpie/internal/provider"
)
// autoResetTimeout bounds the look at an account's week and the reset.
var autoResetTimeout = 20 * time.Second
// autoReset spends a reset of one of cands' Codex accounts, c — the last
// one, just out of its allowance — first: only when every other one of
// them sits out too. held are accounts left out as they won't spend their
// credits (planned.held): they sit out, and are out of their allowance as
// c is, so one of them may spend one after cands'. It says which account it
// was and what spending did.
func (s *Server) autoReset(ctx context.Context, cands []candidate, c candidate, held []candidate) (candidate, provider.ResetOutcome, bool) {
// spent before a route is begun: a wait magpie knows of (unrouted.go)
defer noteWait(ctx)()
for _, x := range cands {
if x.restKey() == c.restKey() {
continue
}
_, resting := restOf(x.restKey())
if !resting && x.restID() != x.restKey() {
_, resting = restOf(x.restID())
}
if !resting {
return candidate{}, provider.ResetOutcome{}, false
}
}
seen := map[string]bool{}
for _, x := range append(append([]candidate{c}, cands...), held...) {
a := x.p.Account
if a == nil || a.User == "" || seen[x.restKey()] || !provider.AutoResetsWeek(a.Agent, a.User) {
continue
}
seen[x.restKey()] = true
if out, ok := autoResetOf(ctx, a.Agent, a.User); ok {
s.Unrest(x.restKey())
x.capped = nil // its windows started again: held no more
return x, out, true
}
}
return candidate{}, provider.ResetOutcome{}, false
}
// autoResetSignedIn is autoReset for a request relayed with Codex's own
// sign-in, the only account there is.
func (s *Server) autoResetSignedIn(ctx context.Context) (string, provider.ResetOutcome, bool) {
who, ok := provider.CodexSignedIn()
if !ok || !provider.AutoResetsWeek("codex", who) {
return "", provider.ResetOutcome{}, false
}
out, ok := autoResetOf(ctx, "codex", who)
if ok {
s.Unrest("codex@" + strings.ToLower(who))
}
return who, out, ok
}
// autoResetOf spends one of agent's account user's resets if its rules
// let it, and says whether the windows started again.
func autoResetOf(ctx context.Context, agent, user string) (provider.ResetOutcome, bool) {
ctx, cancel := context.WithTimeout(ctx, autoResetTimeout)
defer cancel()
out, err := provider.AutoUseCodexReset(ctx, user)
switch {
case err != nil:
log.Printf("%s reset for %s not used: %v", agent, user, err)
case out.Code == "reset":
log.Printf("%s reset used for %s, its week used up: %s", agent, user, out.Text())
case out.Code != "":
log.Printf("%s reset for %s not used: %s", agent, user, out.Text())
}
return out, err == nil && out.Code == "reset"
}
// unhold moves the account c of a plan's left, held as it won't spend its
// credits, to its order: a reset started its windows again, and it is
// tried.
func unhold(order, left []Weighed, c candidate) ([]Weighed, []Weighed) {
i := slices.IndexFunc(left, func(w Weighed) bool { return w.ID == c.rest && w.NoCredits })
if i < 0 {
return order, left
}
w := left[i]
w.Unlisted, w.Capped, w.CapBack, w.NoCredits = false, 0, nil, false
return append(slices.Clip(order), w), slices.Delete(slices.Clone(left), i, i+1)
}