Skip to content

Every agent's model. One place. Codex on DeepSeek, Claude Code on Kimi, from the menu bar.

provider: a failed read of when Codex resets run out no longer leaves one about to expire unspent for six hours (donutsone on X)

yetone04ec2d710c24
diff --git a/internal/provider/codex_expiring.go b/internal/provider/codex_expiring.go
index 2ab6f84f1..c952b8c81 100644
--- a/internal/provider/codex_expiring.go
+++ b/internal/provider/codex_expiring.go
@@ -18,6 +18,7 @@ package provider
import (
"context"
+ "errors"
"log"
"strings"
"sync"
@@ -48,6 +49,14 @@ var (
resetExpiryFar = 6 * time.Hour
)
+// errResetsUntilUnread: the account holds resets, but when they run out
+// couldn't be read
+var errResetsUntilUnread = errors.New("couldn't read when its resets run out")
+
+// expiringResetDetailsWait is how long the background look waits for when
+// the resets run out (withResetDetailsWait)
+var expiringResetDetailsWait = 30 * time.Second
+
var expiring = expiringResets{next: map[string]time.Time{}, until: map[string]time.Time{}}
type expiringResets struct {
@@ -74,6 +83,12 @@ func (e *expiringResets) check(user string, now time.Time, look func() ([]QuotaW
return ResetOutcome{}, nil
}
windows, resets, err := look()
+ if err == nil && resets != nil && resets.Count > 0 && resets.untilUnread {
+ // held, but when they run out wasn't read: unknown, not never —
+ // taken for "none runs out", the account went unread for
+ // resetExpiryFar and a reset running out within it ran out unspent
+ err = errResetsUntilUnread
+ }
if err != nil {
// tried again by the reset last read, soon when it is near
e.next[key] = now.Add(resetExpiryWatch)
@@ -191,6 +206,7 @@ func SpendExpiringCodexResets(ctx context.Context) {
if _, expiring := CodexAutoResetWhen(user); !expiring {
continue // kept to its week used up (#2078)
}
+ ctx := withResetDetailsWait(ctx, expiringResetDetailsWait)
var who string
out, err := expiring.check(user, time.Now(), func() ([]QuotaWindow, *ResetCredits, error) {
var windows []QuotaWindow
diff --git a/internal/provider/codex_expiring_test.go b/internal/provider/codex_expiring_test.go
index 1b847a3bf..7cfd5c706 100644
--- a/internal/provider/codex_expiring_test.go
+++ b/internal/provider/codex_expiring_test.go
@@ -352,3 +352,127 @@ func TestExpiringSpendReadAgain(t *testing.T) {
}
}
}
+
+// donutsone on X: a reset card ran out unspent with "before one expires"
+// on. A failed read of when the cards run out (the second call, bounded
+// at 4s) gave a nil Until, which check took for "none runs out": the
+// account went unread for resetExpiryFar and the card it had just seen,
+// minutes from running out, was forgotten. Now that read is unknown: the
+// account is looked at again by the card last read, and spends it.
+func TestExpiringResetSpentPastAFailedRead(t *testing.T) {
+ signIn(t)
+ old, oldUntil := expiring.next, expiring.until
+ expiring.next, expiring.until = map[string]time.Time{}, map[string]time.Time{}
+ t.Cleanup(func() { expiring.next, expiring.until = old, oldUntil })
+ soon := time.Now().Add(20 * time.Minute).UTC().Format(time.RFC3339)
+ var used, creditsDown atomic.Bool
+ var consumed atomic.Int32
+ fake := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ switch r.URL.Path {
+ case "/backend-api/wham/usage":
+ week := 0
+ if used.Load() {
+ week = 35
+ }
+ json.NewEncoder(w).Encode(map[string]any{"plan_type": "plus",
+ "rate_limit": map[string]any{
+ "primary_window": map[string]any{"used_percent": 0, "limit_window_seconds": 18000},
+ "secondary_window": map[string]any{"used_percent": week, "limit_window_seconds": 604800, "reset_at": time.Now().Add(72 * time.Hour).Unix()}},
+ "rate_limit_reset_credits": map[string]any{"available_count": 1}})
+ case "/backend-api/wham/rate-limit-reset-credits":
+ if creditsDown.Load() {
+ w.WriteHeader(http.StatusBadGateway)
+ return
+ }
+ json.NewEncoder(w).Encode(map[string]any{"available_count": 1, "credits": []any{
+ map[string]any{"id": "soon", "status": "available", "expires_at": soon},
+ }})
+ case "/backend-api/wham/rate-limit-reset-credits/consume":
+ consumed.Add(1)
+ json.NewEncoder(w).Encode(map[string]any{"code": "reset", "windows_reset": 2})
+ default:
+ w.WriteHeader(404)
+ }
+ }))
+ t.Cleanup(fake.Close)
+ oldBase := CodexBase
+ CodexBase = fake.URL + "/backend-api/codex"
+ t.Cleanup(func() { CodexBase = oldBase })
+ if err := SetCodexAutoResetCase("[email protected]", ResetCaseExpiring, true); err != nil {
+ t.Fatal(err)
+ }
+ due := func() { // the next look's time has come
+ expiring.Lock()
+ expiring.next["[email protected]"] = time.Time{}
+ expiring.Unlock()
+ }
+ wait := func() time.Duration {
+ expiring.Lock()
+ defer expiring.Unlock()
+ return time.Until(expiring.next["[email protected]"])
+ }
+
+ // the card is seen, 20 minutes left, nothing used yet: kept, looked at again soon
+ SpendExpiringCodexResets(t.Context())
+ if consumed.Load() != 0 || wait() > resetExpiryClose {
+ t.Fatalf("spent %d, next look in %v", consumed.Load(), wait())
+ }
+ // the account is used, and the read of when the card runs out fails
+ used.Store(true)
+ creditsDown.Store(true)
+ due()
+ SpendExpiringCodexResets(t.Context())
+ if consumed.Load() != 0 {
+ t.Fatalf("spent %d with the card unread", consumed.Load())
+ }
+ if w := wait(); w > resetExpiryClose {
+ t.Fatalf("a failed read leaves the account for %v, past the card running out", w)
+ }
+ // the next look reads it, and spends it
+ creditsDown.Store(false)
+ due()
+ SpendExpiringCodexResets(t.Context())
+ if consumed.Load() != 1 {
+ t.Fatalf("spent %d, want the card about to run out", consumed.Load())
+ }
+}
+
+// A failed read of when the resets run out is unknown (untilUnread); one
+// that says none does is not.
+func TestCodexResetsUntilUnread(t *testing.T) {
+ var down atomic.Bool
+ fake := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if down.Load() {
+ w.WriteHeader(http.StatusInternalServerError)
+ return
+ }
+ json.NewEncoder(w).Encode(map[string]any{"available_count": 1, "credits": []any{
+ map[string]any{"id": "a", "status": "available"},
+ }})
+ }))
+ t.Cleanup(fake.Close)
+ if r := codexResets(t.Context(), fake.URL, "tok", "", 1); r.Until != nil || r.untilUnread {
+ t.Fatalf("one that never runs out: %+v", r)
+ }
+ down.Store(true)
+ if r := codexResets(t.Context(), fake.URL, "tok", "", 1); r.Until != nil || !r.untilUnread {
+ t.Fatalf("a failed read: %+v", r)
+ }
+ // the background look waits longer than the card's 4s for it
+ slow := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ time.Sleep(200 * time.Millisecond)
+ json.NewEncoder(w).Encode(map[string]any{"available_count": 1, "credits": []any{
+ map[string]any{"id": "a", "status": "available", "expires_at": time.Now().Add(time.Hour).UTC().Format(time.RFC3339)},
+ }})
+ }))
+ t.Cleanup(slow.Close)
+ oldWait := codexResetDetailsTimeout
+ codexResetDetailsTimeout = 50 * time.Millisecond
+ t.Cleanup(func() { codexResetDetailsTimeout = oldWait })
+ if r := codexResets(t.Context(), slow.URL, "tok", "", 1); !r.untilUnread {
+ t.Fatalf("the card's look past its bound: %+v", r)
+ }
+ if r := codexResets(withResetDetailsWait(t.Context(), 10*time.Second), slow.URL, "tok", "", 1); r.Until == nil || r.untilUnread {
+ t.Fatalf("the background look: %+v", r)
+ }
+}
diff --git a/internal/provider/codex_resets.go b/internal/provider/codex_resets.go
index 313db435d..074031ff6 100644
--- a/internal/provider/codex_resets.go
+++ b/internal/provider/codex_resets.go
@@ -22,7 +22,7 @@ import (
// ResetCredits is how many rate-limit resets an account holds and the
// soonest one of them runs out; Until is nil when none does, or when that
-// couldn't be read.
+// couldn't be read (untilUnread then).
type ResetCredits struct {
Count int `json:"count"`
Until *time.Time `json:"until,omitempty"`
@@ -39,6 +39,10 @@ type ResetCredits struct {
// lists them, where it only said the first). Empty when the vendor
// didn't say.
Each []ResetCard `json:"each,omitempty"`
+ // untilUnread: when they run out couldn't be read, so a nil Until is
+ // not known, not "never" — the reset about to run out is looked at
+ // again soon rather than left for hours (SpendExpiringCodexResets)
+ untilUnread bool
}
// ResetCard is one reset: when it runs out (nil: it never does) and, of
@@ -87,9 +91,19 @@ func (r ResetCredits) Words() string {
}
// codexResetDetailsTimeout bounds the second look, at when the resets run
-// out: without it the count alone is shown.
+// out: without it the count alone is shown. The background look at a
+// reset about to run out waits longer (withResetDetailsWait): nobody
+// waits on it, and without it the reset can't be spent in time.
var codexResetDetailsTimeout = 4 * time.Second
+type resetDetailsWaitKey struct{}
+
+// withResetDetailsWait has the reads made with ctx wait up to d for when
+// the resets run out, in place of codexResetDetailsTimeout.
+func withResetDetailsWait(ctx context.Context, d time.Duration) context.Context {
+ return context.WithValue(ctx, resetDetailsWaitKey{}, d)
+}
+
type codexResetCreditsWire struct {
AvailableCount int `json:"available_count"`
Credits []struct {
@@ -156,10 +170,16 @@ func codexResets(ctx context.Context, base, token, accountID string, count int)
return nil
}
out := &ResetCredits{Count: count}
- ctx, cancel := context.WithTimeout(ctx, codexResetDetailsTimeout)
+ wait := codexResetDetailsTimeout
+ if d, ok := ctx.Value(resetDetailsWaitKey{}).(time.Duration); ok {
+ wait = d
+ }
+ ctx, cancel := context.WithTimeout(ctx, wait)
defer cancel()
var w codexResetCreditsWire
- if accountJSON(ctx, base+"/wham/rate-limit-reset-credits", token, codexAccountHeaders(accountID), &w) == nil {
+ if err := accountJSON(ctx, base+"/wham/rate-limit-reset-credits", token, codexAccountHeaders(accountID), &w); err != nil {
+ out.untilUnread = true
+ } else {
out.Until = w.soonest()
// listed only when they are the ones counted: a list that says
// otherwise isn't put on the card as if it were