From e297a8ab27461ed32b03ce8be0f9bf957a2e754d Mon Sep 17 00:00:00 2001 From: yetone Date: Tue, 13 Oct 2026 23:30:24 +0800 Subject: [PATCH] provider: a codex-autoreset.json that can't be read no longer lets a Codex account's auto-use spend a second reset the same week (#2017, ggbdpq) What changed: - autoResets.load read a codex-autoreset.json that didn't parse (a crash leaving it zeroed, as #1505's files were) as "none spent this week", so the next week-used-up look spent another reset, and the write after it took the unreadable bytes with it. Now a file that can't be read or parsed is unknown: the bytes are copied aside as .bad- (as noteResetUsed keeps codex-resets-used.json's), and what was spent is rebuilt from codex-resets-used.json, which records every reset used for a week used up. When that file can't be read either, no account spends one by itself for a week (the longest a lost spend could still count), kept past restarts under a "*" entry. - autoResets.save writes through steady.WriteFile, as every write of magpie's own state does since #1505, and logs a failed write. ggbdpq's patch kept the file aside and made the write durable, but still read the unreadable file as none spent, so its own scenario (a crash, then a restart) still spent a second reset. This takes their patch and fixes the read at the cause. Run: - TestAutoResetUnreadableKeptAside (ggbdpq's) fails on main: "the unreadable file was written over with nothing kept aside". - TestAutoResetUnreadableReadsResetsUsed and TestAutoResetNothingKnownSpendsNone fail on main and on ggbdpq's patch alone: "spent 1 resets, want 0" / "spent 1 resets with nothing known of the week". Cases: an auto-use an hour ago holds off; one 8 days ago, one by hand, or another account's doesn't. - go test -tags nogui ./internal/provider under a temp HOME passes; -race -count=10 -run TestAutoReset passes; gofmt -l clean; go vet, GOOS=linux and GOOS=windows go vet -tags nogui ./internal/provider pass. - Not tried: a real corrupted file from a user (none reported); a real Codex account (checked against the fake ChatGPT server only). Co-authored-by: ggbdpq --- internal/provider/codex_autoreset.go | 76 +++++++++- internal/provider/codex_autoreset_test.go | 172 ++++++++++++++++++++++ 2 files changed, 241 insertions(+), 7 deletions(-) diff --git a/internal/provider/codex_autoreset.go b/internal/provider/codex_autoreset.go index 3179e2c79..f8391d649 100644 --- a/internal/provider/codex_autoreset.go +++ b/internal/provider/codex_autoreset.go @@ -11,6 +11,10 @@ package provider import ( "context" "encoding/json" + "errors" + "fmt" + "io/fs" + "log" "os" "path/filepath" "slices" @@ -19,6 +23,7 @@ import ( "time" "github.com/yetone/magpie/internal/settings" + "github.com/yetone/magpie/internal/steady" ) // CodexAutoReset says whether the Codex account user spends a reset by @@ -118,6 +123,9 @@ func (a *autoResets) use(user string, look func(now time.Time) (week *time.Time, defer a.Unlock() a.load() now := time.Now() + if s, ok := a.spent[autoResetAny]; ok && now.Before(s.Until) { + return ResetOutcome{}, nil + } if s, ok := a.spent[key]; ok { if asked.Before(s.At) { // asked while it was being spent, for the same week used up @@ -160,22 +168,74 @@ func weekUsedUp(windows []QuotaWindow, now time.Time) *time.Time { return nil } -// load reads what was spent, once; a.Lock is held. +// load reads what was spent, once; a.Lock is held. A file that can't be +// read or doesn't parse is unknown, never none: read as none, the week's +// auto-use would spend a second reset (#2017). What was spent is then +// taken from codex-resets-used.json, which keeps every reset used for a +// week used up, and when that can't be read either no account spends one +// by itself for a week, the longest a spend the file held could still +// count. A file that doesn't parse is copied aside, as noteResetUsed keeps +// codex-resets-used.json's, and only then written over. func (a *autoResets) load() { if a.path == a.where() { return } a.path = a.where() a.spent, a.next = map[string]autoResetSpent{}, map[string]time.Time{} - if b, err := os.ReadFile(a.path); err == nil { - _ = json.Unmarshal(b, &a.spent) - if a.spent == nil { - a.spent = map[string]autoResetSpent{} + b, err := os.ReadFile(a.path) + if errors.Is(err, fs.ErrNotExist) { + return + } + kept := false + if err == nil { + if err = json.Unmarshal(b, &a.spent); err == nil { + if a.spent == nil { + a.spent = map[string]autoResetSpent{} + } + return } + aside := a.path + ".bad-" + time.Now().UTC().Format("20060102T150405.000000000") + if werr := os.WriteFile(aside, b, 0o600); werr != nil { + err = fmt.Errorf("%w; keeping it aside: %v", err, werr) + } else { + kept = true + err = fmt.Errorf("%w; kept aside as %s", err, aside) + } + } + if a.spent == nil { + a.spent = map[string]autoResetSpent{} + } + now := time.Now() + uses, uerr := readResetsUsed() + if uerr != nil { + a.spent[autoResetAny] = autoResetSpent{Until: now.Add(autoResetWeek), At: now} + log.Printf("%s: %v; %v too, so no Codex account spends a reset by itself until %s", a.path, err, uerr, now.Add(autoResetWeek).Format(time.RFC3339)) + } else { + for _, u := range uses { + key := strings.ToLower(u.User) + if u.Why != ResetUsedWeek || now.Sub(u.At) >= autoResetWeek || a.spent[key].At.After(u.At) { + continue + } + a.spent[key] = autoResetSpent{Until: u.At.Add(autoResetWeek), At: u.At, Out: ResetOutcome{Code: "reset", Windows: u.Windows}} + } + log.Printf("%s: %v; what was spent is taken from %s", a.path, err, resetsUsedPath()) + } + if kept { + a.save() } } -// save writes it; a.Lock is held. +// autoResetAny stands for every account in spent, when what was spent +// isn't known; autoResetWeek is the longest a spend counts for. +const ( + autoResetAny = "*" + autoResetWeek = 7 * 24 * time.Hour +) + +// save writes it; a.Lock is held. Through steady.WriteFile, as every write +// of magpie's own state is (#1505): a crash mid-write left logins.json and +// plugin-auth.json zeroed at full length, and one here would read as no +// reset spent this week, so the next look spent a second one. func (a *autoResets) save() { now := time.Now() for k, s := range a.spent { // weeks gone by say nothing any more @@ -185,5 +245,7 @@ func (a *autoResets) save() { } b, _ := json.MarshalIndent(a.spent, "", " ") _ = os.MkdirAll(settings.Dir(), 0o755) - _ = os.WriteFile(a.path, append(b, '\n'), 0o644) + if err := steady.WriteFile(a.path, append(b, '\n'), 0o644); err != nil { + log.Printf("writing what a week's auto-use spent to %s: %v", a.path, err) + } } diff --git a/internal/provider/codex_autoreset_test.go b/internal/provider/codex_autoreset_test.go index 2c57deeb7..ee3ac5f9c 100644 --- a/internal/provider/codex_autoreset_test.go +++ b/internal/provider/codex_autoreset_test.go @@ -1,7 +1,14 @@ package provider import ( + "encoding/json" + "net/http" + "net/http/httptest" + "os" + "path/filepath" "slices" + "strings" + "sync/atomic" "testing" "time" @@ -80,3 +87,168 @@ func TestAutoResetKeptPastRestart(t *testing.T) { t.Fatal("what was spent was forgotten") } } + +// A codex-autoreset.json a crash left unreadable (#1505's zeroed file, or +// a half-written one) is copied aside before a use is written over it, as +// codex-resets-used.json's is: read as none it would have the week's +// auto-use spend a second reset, and the write would take the evidence +// with it. The use itself is still kept. +func TestAutoResetUnreadableKeptAside(t *testing.T) { + signIn(t) + if err := SetCodexAutoReset("me@example.com", true); err != nil { + t.Fatal(err) + } + p := autoReset.where() + os.MkdirAll(filepath.Dir(p), 0o755) + bad := strings.Repeat("\x00", 64) // what a hard power-off left of #1505's files + if err := os.WriteFile(p, []byte(bad), 0o644); err != nil { + t.Fatal(err) + } + a := &autoReset + a.Lock() + a.path = "" // read afresh, as a new magpie would + a.Unlock() + + consumed := fakeWeekUsedUp(t) + + if out, err := AutoUseCodexReset(t.Context(), "me@example.com"); err != nil || out.Code != "reset" { + t.Fatalf("the week used up: %+v %v", out, err) + } + aside, _ := filepath.Glob(p + ".bad-*") + if len(aside) != 1 { + t.Fatalf("the unreadable file was written over with nothing kept aside: %v", aside) + } + if kept, _ := os.ReadFile(aside[0]); string(kept) != bad { + t.Fatalf("the copy holds %q, want the unreadable bytes", kept) + } + // and the use itself is kept: read afresh, no second one this week + a.Lock() + a.path = "" // as a new magpie would + a.load() + _, ok := a.spent["me@example.com"] + a.Unlock() + if !ok { + t.Fatal("what was spent was forgotten") + } + fakeCodexResets(t, 2, nil) // would say the week is not used up, if asked + if out, err := AutoUseCodexReset(t.Context(), "me@example.com"); err != nil || out.Code != "" { + t.Fatalf("a second one the same week: %+v %v", out, err) + } + if consumed.Load() != 1 { + t.Fatalf("consumed %d resets, want 1", consumed.Load()) + } +} + +// fakeWeekUsedUp stands in for ChatGPT with an account whose week is used +// up and that holds resets; it counts the resets spent. +func fakeWeekUsedUp(t *testing.T) *atomic.Int32 { + soon := time.Now().Add(20 * time.Minute).UTC().Format(time.RFC3339) + 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": + json.NewEncoder(w).Encode(map[string]any{"plan_type": "pro", + "rate_limit": map[string]any{ + "primary_window": map[string]any{"used_percent": 10, "limit_window_seconds": 18000}, + "secondary_window": map[string]any{"used_percent": 100, "limit_window_seconds": 604800, "reset_at": time.Now().Add(72 * time.Hour).Unix()}, + }, + "rate_limit_reset_credits": map[string]any{"available_count": 2}}) + case "/backend-api/wham/rate-limit-reset-credits": + json.NewEncoder(w).Encode(map[string]any{"available_count": 2, "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 }) + return &consumed +} + +// unreadableAutoReset leaves codex-autoreset.json as #1505's crash left +// its files, zeroed at full length, for a new magpie to read. +func unreadableAutoReset(t *testing.T) { + p := autoReset.where() + os.MkdirAll(filepath.Dir(p), 0o755) + if err := os.WriteFile(p, make([]byte, 64), 0o644); err != nil { + t.Fatal(err) + } + autoReset.Lock() + autoReset.path = "" + autoReset.Unlock() +} + +// A codex-autoreset.json that can't be read is not "none spent" (#2017): +// a reset auto-use spent this week, kept in codex-resets-used.json, still +// holds off a second one the same week, while one from a week ago, or one +// used by hand, doesn't. +func TestAutoResetUnreadableReadsResetsUsed(t *testing.T) { + for name, c := range map[string]struct { + uses []ResetUse + spent int32 + }{ + "auto-used an hour ago": {[]ResetUse{{User: "Me@example.com", At: time.Now().Add(-time.Hour), Why: ResetUsedWeek, Windows: 2}}, 0}, + "auto-used 8 days ago": {[]ResetUse{{User: "me@example.com", At: time.Now().Add(-8 * 24 * time.Hour), Why: ResetUsedWeek}}, 1}, + "used by hand": {[]ResetUse{{User: "me@example.com", At: time.Now().Add(-time.Hour), Why: ResetUsedByHand}}, 1}, + "another account's use": {[]ResetUse{{User: "other@example.com", At: time.Now().Add(-time.Hour), Why: ResetUsedWeek}}, 1}, + } { + t.Run(name, func(t *testing.T) { + signIn(t) + if err := SetCodexAutoReset("me@example.com", true); err != nil { + t.Fatal(err) + } + b, _ := json.Marshal(c.uses) + os.MkdirAll(filepath.Dir(resetsUsedPath()), 0o755) + if err := os.WriteFile(resetsUsedPath(), b, 0o600); err != nil { + t.Fatal(err) + } + unreadableAutoReset(t) + consumed := fakeWeekUsedUp(t) + if _, err := AutoUseCodexReset(t.Context(), "me@example.com"); err != nil { + t.Fatal(err) + } + if consumed.Load() != c.spent { + t.Fatalf("spent %d resets, want %d", consumed.Load(), c.spent) + } + }) + } +} + +// When codex-resets-used.json can't be read either, no account spends a +// reset by itself, past a restart too, until a week has gone by. +func TestAutoResetNothingKnownSpendsNone(t *testing.T) { + signIn(t) + if err := SetCodexAutoReset("me@example.com", true); err != nil { + t.Fatal(err) + } + os.MkdirAll(filepath.Dir(resetsUsedPath()), 0o755) + if err := os.WriteFile(resetsUsedPath(), make([]byte, 32), 0o600); err != nil { + t.Fatal(err) + } + unreadableAutoReset(t) + consumed := fakeWeekUsedUp(t) + for range 2 { + if _, err := AutoUseCodexReset(t.Context(), "me@example.com"); err != nil { + t.Fatal(err) + } + autoReset.Lock() + autoReset.path = "" // as a new magpie would + autoReset.Unlock() + } + if consumed.Load() != 0 { + t.Fatalf("spent %d resets with nothing known of the week", consumed.Load()) + } + autoReset.Lock() + autoReset.load() + s := autoReset.spent[autoResetAny] + autoReset.Unlock() + if d := time.Until(s.Until); d < 6*24*time.Hour || d > autoResetWeek { + t.Fatalf("held off until %v", s.Until) + } +}