diff --git a/docs/reference.md b/docs/reference.md index 4ff12e79a..ac161c247 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -1883,9 +1883,12 @@ each of these groups ordered by the share used. renew in the same hours (WorkBuddy's free accounts all at the month's end) go by when their credits left run out after that: the one whose credits are lost first goes first, and one with none that run out - after those whose do. A Claude account + after those whose do. A Claude or ChatGPT account magpie knows nothing of yet goes first once, to learn what it has left - from the answer; any other unknown account goes after those known, + from the answer (a ChatGPT account, while another is known: one whose + usage can't be read is asked so again an hour after its last answer, + until its answers tell its week); any other unknown account goes after + those known, and is still tried when they fail, ahead of any at 90% or more. An account with a month beside its week (Factory) goes by its month: when the month holds less than its weeks add up to (Factory's, by @@ -1920,8 +1923,11 @@ each of these groups ordered by the share used. counts. Accounts whose pace is within a tenth of the highest in their band count as alike, and among them the one magpie sent the fewest tokens lately goes first. A - Claude account not known goes first once, as in Smart; another unknown - account counts as a fresh week. + Claude or ChatGPT account not known goes first once, as in Smart (a + ChatGPT one while another is known); another unknown account counts as + a fresh week. A ChatGPT account whose usage + page can't be read is known from the week its answers tell, until a + reading works again. - **Speed first**: the account, key or group member that answered this model fastest lately first. magpie keeps, in memory, how long each one's streamed answers took to their first token and how many tokens a second diff --git a/internal/gateway/codex_limits.go b/internal/gateway/codex_limits.go index 5aae095c4..7eae7fe74 100644 --- a/internal/gateway/codex_limits.go +++ b/internal/gateway/codex_limits.go @@ -7,6 +7,7 @@ import ( "net/http" "strconv" "strings" + "sync" "time" "github.com/yetone/magpie/internal/provider" @@ -37,6 +38,7 @@ func heardCodexLimits(p provider.Provider, res *http.Response) { } agent, user := p.Account.UsageAgent(), p.Account.User now := time.Now() + noteCodexAnswered(agent, user, now) if ls := codexHeaderLimits(res.Header, now); len(ls) > 0 { noteCodexLimits(agent, user, ls) } @@ -47,6 +49,32 @@ func heardCodexLimits(p provider.Provider, res *http.Response) { } } +// codexLearnAgain is how long a Codex account not known that answered is +// not put first again to be learned (learns): its reply told nothing of +// the week, or the reading still fails. +const codexLearnAgain = time.Hour + +// codexAnswered is when each Codex account last answered, by +// agent/lower-cased user. +var codexAnswered = struct { + sync.Mutex + m map[string]time.Time +}{m: map[string]time.Time{}} + +func noteCodexAnswered(agent, user string, now time.Time) { + codexAnswered.Lock() + codexAnswered.m[agent+"/"+strings.ToLower(user)] = now + codexAnswered.Unlock() +} + +// codexAnsweredLately: user answered within codexLearnAgain of now. +func codexAnsweredLately(agent, user string, now time.Time) bool { + codexAnswered.Lock() + at, ok := codexAnswered.m[agent+"/"+strings.ToLower(user)] + codexAnswered.Unlock() + return ok && now.Sub(at) < codexLearnAgain +} + // codexHeaderLimits are the windows the x-codex-primary-* and // x-codex-secondary-* headers tell; one that doesn't say how long it runs // is left out, as no window read can be told to be it. diff --git a/internal/gateway/routing.go b/internal/gateway/routing.go index 8b530429d..fea72b715 100644 --- a/internal/gateway/routing.go +++ b/internal/gateway/routing.go @@ -2155,10 +2155,26 @@ type left struct { } // learns: c is a subscription whose allowance isn't known yet, of an agent -// that tells it as it answers (Claude Code's rate_limit_event). +// that tells it as it answers (Claude Code's rate_limit_event; a ChatGPT +// account's x-codex-* headers, provider.NoteCodexLimits). A Codex account +// only while it hasn't answered lately (codexAnswered): its reply makes it +// known when it tells the week, and one that told nothing isn't sent +// every request first. Not known and kept after those known, an account +// whose usage can't be read was never sent one, under Use before expiry +// (a whole week ahead of it) and Smart alike (peterpark8527 on Discord). func learns(c candidate, lefts map[allowanceKey]left) bool { - _, known := lefts[c.allowanceKey()] - return !known && c.p.Account != nil && c.p.Account.Agent == "claude" + if _, known := lefts[c.allowanceKey()]; known || c.p.Account == nil { + return false + } + switch c.p.Account.Agent { + case "claude": + return true + case "codex": + // only behind one known: of accounts none known, the order stands, + // and no week is started before it is needed + return len(lefts) > 0 && !codexAnsweredLately(c.p.Account.UsageAgent(), c.p.Account.User, time.Now()) + } + return false } // weigh orders one provider's candidates as its routing says, and tells diff --git a/internal/gateway/weekly_pace_test.go b/internal/gateway/weekly_pace_test.go index 303e1ad25..e30bc979c 100644 --- a/internal/gateway/weekly_pace_test.go +++ b/internal/gateway/weekly_pace_test.go @@ -1,6 +1,8 @@ package gateway import ( + "fmt" + "slices" "strings" "testing" "time" @@ -108,9 +110,13 @@ func TestWeeklyPace(t *testing.T) { if got := order(acct("b@x.com"), acct("a@x.com")); got != "ab" { t.Fatalf("a Sonnet request goes by the general week: %s", got) } - // one not known counts as a fresh week: ahead of one half through its, - // behind one about to lose what it has + // one not known counts as a fresh week once it has answered lately + // (a Codex account not known is asked first before, its reply to tell + // its week: TestUnknownCodexAccountIsAsked): ahead of one half + // through its, behind one about to lose what it has delete(share, "c@x.com") + freshAnswered(t) + noteCodexAnswered("codex", "c@x.com", now) share["a@x.com"] = week(40, 5*24*time.Hour) share["b@x.com"] = week(80, time.Hour) if got := order(acct("a@x.com"), acct("c@x.com"), acct("b@x.com")); got != "bca" { @@ -160,6 +166,7 @@ func TestWeeklyPace(t *testing.T) { share["b@x.com"] = provider.Allowance{{Used: 5, Resets: now.Add(time.Hour), Span: 5 * time.Hour}} // 95 / 1 h share["c@x.com"] = provider.Allowance{{Used: 0, Resets: now.Add(time.Hour), Span: 5 * time.Hour}} // 100 / 1 h delete(share, "d@x.com") + noteCodexAnswered("codex", "d@x.com", now) // answered lately: a fresh week, not asked first if got := order(acct("a@x.com"), acct("d@x.com"), acct("c@x.com"), acct("b@x.com")); got != "cbad" { t.Fatalf("five hours alone go by what they lose at their reset: %s", got) } @@ -231,3 +238,80 @@ func TestWeeklyPace(t *testing.T) { t.Fatalf("least used is most left first: %s", got) } } + +// Eleven ChatGPT accounts under Use before expiry (and Smart), one of them +// not known — its usage reading fails, or named no window: it was a whole +// fresh week (provider.FreshPace) under Use before expiry and after every +// account known under Smart, so with ten others with room it was never +// sent a request, and never known (peterpark8527 on Discord: "有个账号始终 +// 没有被调用"). It goes first while it hasn't answered lately, as a Claude +// account not known does, for its reply to tell its week +// (provider.NoteCodexLimits); once it answered, it goes where its pace, +// as not known, puts it, until it is known or an hour has gone by. +func TestUnknownCodexAccountIsAsked(t *testing.T) { + old := allowances + defer func() { allowances = old }() + freshAnswered(t) + now := time.Now() + share := map[string]provider.Allowance{} + allowances = func(string) map[string]provider.Allowance { return share } + var cs []candidate + for i := range 11 { + user := fmt.Sprintf("u%02d@x.com", i) + cs = append(cs, candidate{p: provider.Provider{ID: "codex", Account: &provider.Account{Agent: "codex", User: user}}, model: "gpt-5.6-sol", rest: "codex#" + user}) + if i == 7 { + continue // its reading never came back + } + share[user] = provider.Allowance{ + {Used: 5, Resets: now.Add(3 * time.Hour), Span: 5 * time.Hour}, + {Used: float64(10 + 5*i), Resets: now.Add(time.Duration(30+10*i) * time.Hour), Span: 7 * 24 * time.Hour}, + } + } + for _, routing := range []string{provider.Pace, ""} { + p := provider.Provider{ID: "codex", Routing: routing} + got, _ := weigh(p, slices.Clone(cs), "gpt-5.6-sol", provider.Chat) + if u := got[0].p.Account.User; u != "u07@x.com" { + t.Fatalf("routing %q: %s first, the account not known is never asked", routing, u) + } + } + noteCodexAnswered("codex", "u07@x.com", now) + for _, routing := range []string{provider.Pace, ""} { + p := provider.Provider{ID: "codex", Routing: routing} + got, _ := weigh(p, slices.Clone(cs), "gpt-5.6-sol", provider.Chat) + if u := got[0].p.Account.User; u == "u07@x.com" { + t.Fatalf("routing %q: answered a moment ago and still first", routing) + } + } + noteCodexAnswered("codex", "u07@x.com", now.Add(-codexLearnAgain-time.Minute)) + p := provider.Provider{ID: "codex", Routing: provider.Pace} + if got, _ := weigh(p, slices.Clone(cs), "gpt-5.6-sol", provider.Chat); got[0].p.Account.User != "u07@x.com" { + t.Fatalf("an hour on, not known still, it isn't asked again: %s", got[0].p.Account.User) + } + // none known (every reading held, or not back yet): the order stands, + // no week started before it is needed + for k := range share { + delete(share, k) + } + noteCodexAnswered("codex", "u00@x.com", now) // not to be asked behind the rest + for _, routing := range []string{provider.Pace, ""} { + p := provider.Provider{ID: "codex", Routing: routing} + got, _ := weigh(p, slices.Clone(cs), "gpt-5.6-sol", provider.Chat) + if u := got[0].p.Account.User; u != "u00@x.com" { + t.Fatalf("routing %q, none known: %s first, not the first listed", routing, u) + } + } +} + +// freshAnswered has no Codex account answered lately, until t ends. +func freshAnswered(t *testing.T) { + t.Helper() + codexAnswered.Lock() + was := codexAnswered.m + codexAnswered.m = map[string]time.Time{} + codexAnswered.Unlock() + t.Cleanup(func() { + codexAnswered.Lock() + codexAnswered.m = was + codexAnswered.Unlock() + }) +} diff --git a/internal/provider/codex_limits.go b/internal/provider/codex_limits.go index b2b08c30c..7115a21ae 100644 --- a/internal/provider/codex_limits.go +++ b/internal/provider/codex_limits.go @@ -26,8 +26,9 @@ type CodexLimit struct { // NoteCodexLimits keeps what a reply said of agent's account user (agent // as its usage is read, Account.UsageAgent) in place of the windows of the // same span last read, for routing (Allowances) and the Usage page alike. -// An account not read yet is left to its reading: a reply names only the -// windows it counts, which isn't the whole of the account. +// An account not read well yet is known from what the reply told, when it +// told the week, until a reading tells the whole of it: a reply names +// only the windows it counts. func NoteCodexLimits(agent, user string, heard []CodexLimit) { if len(heard) == 0 || user == "" { return @@ -52,19 +53,63 @@ func NoteCodexLimits(agent, user string, heard []CodexLimit) { u.Lock() defer u.Unlock() m := u.m[agent] + keep := func(name string, a Allowance) { + // new ones: what was handed out is read without the lock + kept := make(map[string]Allowance, len(m)+1) + for k, v := range m { + kept[k] = v + } + kept[name] = a + u.m[agent] = kept + } for name, a := range m { if !strings.EqualFold(name, user) { continue } - // new ones: what was handed out is read without the lock - kept := make(map[string]Allowance, len(m)) - for k, v := range m { - kept[k] = v + a = heardAllowance(a, heard) + if h, ok := u.heard[key]; ok { + u.heard[key] = heardOnly{h.user, a} } - kept[name] = heardAllowance(a, heard) - u.m[agent] = kept + keep(name, a) return } + // not read: its reading failed, was held, or named no window. What + // the reply told is the account's, until a reading tells it — when + // it tells a budget (the week): kept as not known, the account went + // behind every one known for good under Use before expiry and + // Smart, while the week magpie's own turns started ran out unspent + // (peterpark8527 on Discord) + a := toldAllowance(heard) + if a == nil { + return + } + if u.heard == nil { + u.heard = map[string]heardOnly{} + } + u.heard[key] = heardOnly{user, a} + if m != nil { + keep(user, a) + } +} + +// heardOnly is an account's allowance as only its replies told it. +type heardOnly struct { + user string + a Allowance +} + +// toldAllowance is the allowance heard tells, nil when it tells no +// budget window (a day or longer): the five hours alone don't say what +// the week has left. +func toldAllowance(heard []CodexLimit) Allowance { + if !slices.ContainsFunc(heard, func(h CodexLimit) bool { return h.Span >= budgetSpan }) { + return nil + } + a := make(Allowance, 0, len(heard)) + for _, h := range heard { + a = append(a, Limit{Used: h.Used, Span: h.Span, Resets: h.Resets}) + } + return a } // heardWindows is ws, copied, with each window that counts every model diff --git a/internal/provider/codex_limits_test.go b/internal/provider/codex_limits_test.go index 5264f5d5b..95e45be1b 100644 --- a/internal/provider/codex_limits_test.go +++ b/internal/provider/codex_limits_test.go @@ -11,7 +11,7 @@ func resetUsed(t *testing.T) { reset := func() { usedCache.Lock() usedCache.m, usedCache.at, usedCache.loading = map[string]map[string]Allowance{}, map[string]time.Time{}, map[string]chan struct{}{} - usedCache.stale, usedCache.seen = nil, nil + usedCache.stale, usedCache.seen, usedCache.heard = nil, nil, nil usedCache.Unlock() } reset() @@ -113,3 +113,76 @@ func TestNoteCodexLimitsHoldsTheCap(t *testing.T) { t.Fatal("a reply was taken for a whole reading") } } + +// An account whose reading fails, every minute, is known from what its +// replies tell of its week, until a reading tells it: kept as not known, +// Use before expiry counted it a whole week ahead and Smart put it after +// every account known, so with ten others it was never sent a request +// while the week magpie's own turns started ran out unspent +// (peterpark8527 on Discord, 11 ChatGPT accounts). A reply telling the +// five hours alone makes nothing up; a reading that comes back wins. +func TestNoteCodexLimitsKnowsAnUnreadAccount(t *testing.T) { + signIn(t) + rememberLogins(true) + resetUsed(t) + now := time.Now() + failed := func() { + loginUsageCache.Lock() + loginUsageCache.m = map[string]loginUsageEntry{"codex/me@example.com": {at: time.Now(), + q: SubscriptionQuota{Provider: "codex", Windows: []QuotaWindow{}, Error: "usage: 403"}}} + loginUsageCache.Unlock() + } + readAgain := func() map[string]Allowance { + usedCache.Lock() + usedCache.at["codex"] = time.Time{} + usedCache.Unlock() + Allowances("codex") + for { + usedCache.Lock() + done := usedCache.loading["codex"] + usedCache.Unlock() + if done == nil { + break + } + <-done + } + return Allowances("codex") + } + failed() + if _, ok := readAgain()["me@example.com"]; ok { + t.Fatal("a failed reading is known") + } + NoteCodexLimits("codex", "me@example.com", []CodexLimit{{Used: 10, Span: 5 * time.Hour, Resets: now.Add(time.Hour)}}) + if _, ok := Allowances("codex")["me@example.com"]; ok { + t.Fatal("the five hours alone made the account known") + } + week := now.Add(2 * 24 * time.Hour).Truncate(time.Second) + NoteCodexLimits("codex", "me@example.com", []CodexLimit{ + {Used: 10, Span: 5 * time.Hour, Resets: now.Add(time.Hour)}, + {Used: 20, Span: 7 * 24 * time.Hour, Resets: week}}) + a, ok := Allowances("codex")["me@example.com"] + if !ok { + t.Fatal("a reply telling the week left the account not known") + } + if pc, due := a.Pace("gpt-5.5", now); !due.Equal(week) || pc < 80/48.0-0.01 || pc > 80/48.0+0.01 { + t.Fatalf("pace %v due %v, want 80%% over 48h, due %v", pc, due, week) + } + // its reading fails again: still known from the reply + failed() + if _, ok := readAgain()["me@example.com"]; !ok { + t.Fatal("the next failed reading forgot what the reply told") + } + // a reading comes back: it is the account's + read := now.Add(5 * 24 * time.Hour) + loginUsageCache.Lock() + loginUsageCache.m = map[string]loginUsageEntry{"codex/me@example.com": {at: time.Now(), + q: SubscriptionQuota{Provider: "codex", Windows: []QuotaWindow{{Name: "7 days", Used: 60, ResetsAt: &read, Span: 7 * 24 * time.Hour}}}}} + loginUsageCache.Unlock() + if u, _ := readAgain()["me@example.com"].For("gpt-5.5", now); u != 60 { + t.Fatalf("the reading said 60%%, routing has %v%%", u) + } + failed() + if _, ok := readAgain()["me@example.com"]; ok { + t.Fatal("what a reply told outlived the reading that replaced it") + } +} diff --git a/internal/provider/routing.go b/internal/provider/routing.go index 1ec7dca6e..97441fd18 100644 --- a/internal/provider/routing.go +++ b/internal/provider/routing.go @@ -9,6 +9,7 @@ package provider import ( "context" "fmt" + "maps" "regexp" "slices" "sort" @@ -264,6 +265,10 @@ var usedCache struct { // read: when each account's allowance was last read well, and whether // the last try failed, by agent/user (UsageRead) read map[string]readState + // heard: accounts no reading has told the windows of (it failed, was + // held, or named none) that a reply told them of, by agent/user + // (NoteCodexLimits): known from that until a reading tells them + heard map[string]heardOnly } // firstWait is how long a request waits for an agent's allowances the @@ -796,6 +801,20 @@ func Allowances(agent string) map[string]Allowance { } c.seen[key] = reading{a, now} } + // an account no reading told is known from what its replies + // said, until one does: else Smart and Use before expiry kept + // it, as not known, behind every account known, its week + // running out unspent (peterpark8527 on Discord) + for key, h := range c.heard { + if !strings.HasPrefix(key, agent+"/") { + continue + } + if slices.ContainsFunc(slices.Collect(maps.Keys(all)), func(u string) bool { return strings.EqualFold(u, h.user) }) { + delete(c.heard, key) + } else { + all[h.user] = h.a + } + } if c.stale[agent] { // kept, as weigh counts an account not known unused, but // read again at the next ask diff --git a/internal/routes/routes.go b/internal/routes/routes.go index dea573118..735a8abc6 100644 --- a/internal/routes/routes.go +++ b/internal/routes/routes.go @@ -28,7 +28,8 @@ type Seat struct { // Known: its allowance is known. Used, Soon and Pace are read from it Known bool // Learns: an account not known yet, of an agent that tells what it has - // left as it answers (Claude Code's rate_limit_event) + // left as it answers (Claude Code's rate_limit_event, Codex's x-codex-* + // headers) Learns bool // Used is the share of its allowance used that counts the model, 0–100 Used float64