diff --git a/internal/gateway/claude_persist.go b/internal/gateway/claude_persist.go index db9dc9732..d8200f700 100644 --- a/internal/gateway/claude_persist.go +++ b/internal/gateway/claude_persist.go @@ -296,7 +296,7 @@ func (b *subscriptionBridge) keepForReset(run *subscriptionRun, req *Request, ow } now := time.Now() s := &savedSession{session: cut, sessions: sessions, owner: owner, conv: conv, key: key, tools: tools, - at: now, until: now.Add(quotaShelfFor(owner, msg, now)), tui: tui, appended: appended, cachePrefix: prefix} + at: now, until: onWall(now.Add(quotaShelfFor(owner, msg, now))), tui: tui, appended: appended, cachePrefix: prefix} b.mu.Lock() if old := b.shelf[key]; old != nil { go old.discard() diff --git a/internal/gateway/codex_held.go b/internal/gateway/codex_held.go index dc050548b..acaa45010 100644 --- a/internal/gateway/codex_held.go +++ b/internal/gateway/codex_held.go @@ -84,7 +84,7 @@ func noteCodexHold(who string, status int, header http.Header, body []byte) { windows[k] = slices.Clone(vs) } } - codexHolds.m[who] = codexHold{until: now.Add(d), status: status, why: why, body: append([]byte(nil), body...), ctype: header.Get("Content-Type"), codex: windows} + codexHolds.m[who] = codexHold{until: onWall(now.Add(d)), status: status, why: why, body: append([]byte(nil), body...), ctype: header.Get("Content-Type"), codex: windows} } // codexHeld is who's hold, while it lasts. diff --git a/internal/gateway/codex_limits.go b/internal/gateway/codex_limits.go index 3ecbc29b3..5e9d46fd3 100644 --- a/internal/gateway/codex_limits.go +++ b/internal/gateway/codex_limits.go @@ -106,7 +106,7 @@ func headerLimitsOf(h http.Header, fam string, now time.Time) []provider.CodexLi if at, err := strconv.ParseInt(strings.TrimSpace(h.Get(pre+"reset-at")), 10, 64); err == nil && at > 0 { l.Resets = time.Unix(at, 0) } else if after, err := strconv.ParseInt(strings.TrimSpace(h.Get(pre+"reset-after-seconds")), 10, 64); err == nil && after > 0 { - l.Resets = now.Add(time.Duration(after) * time.Second) + l.Resets = onWall(now.Add(time.Duration(after) * time.Second)) } out = append(out, l) } @@ -146,7 +146,7 @@ func codexEventLimits(data []byte, now time.Time) []provider.CodexLimit { if w.ResetAt > 0 { l.Resets = time.Unix(w.ResetAt, 0) } else if w.ResetAfter > 0 { - l.Resets = now.Add(time.Duration(w.ResetAfter) * time.Second) + l.Resets = onWall(now.Add(time.Duration(w.ResetAfter) * time.Second)) } out = append(out, l) } diff --git a/internal/gateway/draw.go b/internal/gateway/draw.go index 393bb69fa..a5f9131d1 100644 --- a/internal/gateway/draw.go +++ b/internal/gateway/draw.go @@ -1347,7 +1347,7 @@ func restDrawer(c candidate, code int, msg string) { // as the reply's headers told it, not quotaRest's guess d, r.By = min(heard.Resets.Sub(now), longestQuota), "resets" } - r.Until = now.Add(d) + r.Until = onWall(now.Add(d)) restingUntil.Lock() restingUntil.m[r.Key] = r.Until restingUntil.note[r.Key] = r diff --git a/internal/gateway/rest_wall_test.go b/internal/gateway/rest_wall_test.go new file mode 100644 index 000000000..027cd3652 --- /dev/null +++ b/internal/gateway/rest_wall_test.go @@ -0,0 +1,72 @@ +package gateway + +import ( + "net/http" + "strings" + "testing" + "time" + + "github.com/yetone/magpie/internal/provider" +) + +// A rest is kept on the wall clock alone. A time from time.Now() carries +// the monotonic clock too, and Go compares two such times by it; on macOS +// it stops while the computer sleeps, so a rest to 00:40 set the day +// before still held at 09:57 after a night of sleep, 17 hours past the +// time it showed (plugins#1126). Sleep can't be had in a test, so this +// checks what makes it harmless: no rest magpie keeps carries a monotonic +// reading ("m=" in its String). +func TestRestsKeepTheWallClock(t *testing.T) { + monotonic := func(at time.Time) bool { return strings.Contains(at.String(), " m=") } + if !monotonic(time.Now().Add(time.Hour)) { + t.Fatal("time.Now() carries no monotonic reading here: the test proves nothing") + } + codexSignedIn(t) + s := New() + c := candidate{p: provider.Provider{ID: "codex", Account: &provider.Account{Agent: "codex", User: "me@example.com"}}, model: "gpt-6-astra", rest: "codex@me@example.com"} + + quota := []byte(`{"error":{"message":"usage exceeds frequency limit, your usage will reset at ` + + time.Now().Add(14*time.Hour).Format("2006-01-02 15:04:05") + `","type":"usage_limit_reached"}}`) + for _, x := range []struct { + name string + body []byte + code int + }{ + {"quota", quota, http.StatusTooManyRequests}, + {"500", []byte(`{"error":{"message":"An error occurred while processing your request.","type":"server_error"}}`), http.StatusInternalServerError}, + } { + r := s.restAfter(c, x.code, http.Header{}, x.body) + if r.Until.IsZero() { + t.Fatalf("%s: no rest: the test proves nothing", x.name) + } + if monotonic(r.Until) { + t.Errorf("%s: the rest's end %v counts on the monotonic clock", x.name, r.Until) + } + restingUntil.Lock() + for k, until := range restingUntil.m { + if monotonic(until) { + t.Errorf("%s: %s rests to %v on the monotonic clock", x.name, k, until) + } + } + restingUntil.Unlock() + } + + slow := candidate{p: provider.Provider{ID: "codex", Account: &provider.Account{Agent: "codex", User: "slow@example.com"}}, model: "gpt-6-astra", rest: "codex@slow@example.com"} + rested := false + for i := 0; i < slowRests+1; i++ { + if r, ok := restSlow(slow, time.Now()); ok { + rested = true + if monotonic(r.Until) { + t.Errorf("a slow start's rest to %v counts on the monotonic clock", r.Until) + } + } + } + if !rested { + t.Fatal("slow starts never rested: the test proves nothing") + } + + restSearchKey("tavily", "k1", time.Hour, "rate limited", time.Now()) + if r, ok := searchKeyRest("tavily", "k1", time.Now()); !ok || monotonic(r.Until) { + t.Errorf("a search key's rest %v (%v) counts on the monotonic clock", r.Until, ok) + } +} diff --git a/internal/gateway/routing.go b/internal/gateway/routing.go index 2b8564d84..a876d52be 100644 --- a/internal/gateway/routing.go +++ b/internal/gateway/routing.go @@ -1741,7 +1741,7 @@ func (s *Server) restAfterMarked(c candidate, status int, header http.Header, bo } else if a == nil && why != failOther && why != failVerify && why != failRestricted { staleKeyAllowance(c.p) // a key that reads its windows, too } - r.Until = now.Add(d) + r.Until = onWall(now.Add(d)) if a := c.p.Account; a != nil { r.agent, r.user = a.UsageAgent(), a.User } else if why == failQuota { @@ -2056,7 +2056,7 @@ func restSlow(c candidate, now time.Time) (Rest, bool) { if run.n > slowRests { by = "backoff" } - r := Rest{Why: failSlow, Status: http.StatusGatewayTimeout, Until: now.Add(d), By: by, Failures: run.n, Key: id, Model: c.model} + r := Rest{Why: failSlow, Status: http.StatusGatewayTimeout, Until: onWall(now.Add(d)), By: by, Failures: run.n, Key: id, Model: c.model} if a := c.p.Account; a != nil { r.agent, r.user = a.UsageAgent(), a.User } diff --git a/internal/gateway/search_keys.go b/internal/gateway/search_keys.go index 73caa45a8..acf3dc297 100644 --- a/internal/gateway/search_keys.go +++ b/internal/gateway/search_keys.go @@ -78,7 +78,7 @@ func searchRestFor(vendor string, status int, retryAfter string, now time.Time) // restSearchKey sets a key resting for d; a rest it has that ends later // is kept. func restSearchKey(vendor, key string, d time.Duration, why string, now time.Time) { - r := keyRest{Until: now.Add(d), Why: why} + r := keyRest{Until: onWall(now.Add(d)), Why: why} if was, ok := searchKeyRest(vendor, key, now); ok && was.Until.After(r.Until) { return } diff --git a/internal/gateway/wall.go b/internal/gateway/wall.go new file mode 100644 index 000000000..63e37c905 --- /dev/null +++ b/internal/gateway/wall.go @@ -0,0 +1,12 @@ +package gateway + +import "time" + +// onWall gives t on the wall clock alone, for a deadline magpie keeps for +// minutes to days: a rest, a hold, a window's reset. A time from +// time.Now() also carries the monotonic clock, and Go compares two such +// times by it; on macOS it stops while the computer sleeps, so a rest set +// before a night's sleep ran that night longer than the time it shows +// (plugins#1126: a rest to 00:40 still held at 09:57). On the wall clock +// alone, Before, After, Sub and time.Until read the time it says. +func onWall(t time.Time) time.Time { return t.Round(0) }