provider: requests missing together list logins once, and a plan asks OwnPaused of the held list

Every request's routing plan lists the agent's accounts (perKeyEvery
asks AlsoOn, and OwnPaused of the signed-in one), and each list took
logins.json's lock. A write in a request (a token refresh) dropped what
was held, and every request then in flight listed again, one after
another on the lock: 20 requests queued on it in #5104's dump. And
OwnPaused was never held: each ask was its own read under the lock.

heldOf now builds a missed key once a request: the first caller builds,
the others wait for it and take its value. OwnPaused goes through
heldOf under its own key, so a write lists it anew as it does Logins.

Ported from ggbdpq's ecb829370 (#5104). Changed from that patch:
- A waiter takes the build only if nothing changed while it ran: held's
  generation, filememo's generation (settings.Save tells only filememo)
  and the environment. The patch skipped heldFreshLocked on wake and
  kept a build made across a filememo write, so a later caller could get
  settings from before the save.
- A caller outside a request (no Hold) never joins a build; it builds
  fresh, as on main.
- The wait is bounded (heldWait, 5s). A stuck or panicking builder, or
  one waiting on a lock its waiter holds, can't hang the request; the
  waiter builds on its own.
- When a write came during the build, waiters go round again (up to
  heldRounds) so one of them builds and the rest wait, instead of all
  rebuilding at once.
- With heldFor 0 a waiter takes the builder's own result (it is not
  kept, so the patch's waiters found nothing and built again).
- New tests: TestHeldWaiterBuildsAgainAfterAWrite (Changed and
  filememo.Forget), TestHeldWaiterTakesTheBuild, TestHeldWaiterNeverStuck
  (stuck builder, panicking builder). providers-accounts.md says it.

Run (mote, at the pushed tree):
- The patch's two tests on main's product code: red 3 of 3 ("20 listed
  before the first was built", "OwnPaused was not listed once a
  request").
- go test -race -count=20 -cpu 1,2,8 -run 'TestHeldWaiter|
  TestLoginsMissedTogetherListedOnce|TestOwnPausedListedOnceARequest|
  TestLoginsListedOnceARequest|TestHold' ./internal/provider: ok.
- go test ./internal/provider: ok. go vet for darwin, linux, windows;
  gofmt -l clean.
- Nesting: an instrumented run of provider, gui, agent, gateway and
  profile recorded every heldOf inside another build and every heldOf
  made under a file lock. No heldOf key reaches itself (only heldFrom,
  untouched). Under logins.json.lock only "migrations" is asked, and its
  build takes no lock and asks no key; under caller-keys.json.lock the
  keys asked take logins.json.lock only. No build takes caller-keys.json
  .lock. So a waiter never holds a lock its builder needs.
- Half-written files: unchanged readers. logins.json is written through
  temp+rename, sharedLogins keeps the last good list on a bad parse,
  another process's write is seen when loginsMu is taken (Look).

Broken by hand, each red:
- No filememo check on the build: TestHeldWaiterBuildsAgainAfterAWrite
  got "before", built 0 times.
- Unbounded wait: TestHeldWaiterNeverStuck timed out at 60s.
- No take of the builder's result: TestHeldWaiterTakesTheBuild built
  again.

Not tried: a live load of parallel Claude Code requests; two magpie
processes contending for logins.json; Windows and Linux test runs (vet
only).

#5104

Co-authored-by: ggbdpq <67929842+ggbdpq@users.noreply.github.com>
This commit is contained in:
yetone
2026-11-04 17:06:31 +08:00
co-authored by ggbdpq
parent 129baeca01
commit 0e804be29b
6 changed files with 329 additions and 13 deletions
+1 -1
View File
@@ -31,7 +31,7 @@ keys and accounts per request is in [Gateway routing and fallback](gateway-routi
| Native compaction | `NativeCompaction` (`nativeCompaction` in providers.json, the editor's *Compaction* row, `magpie provider set <id> compaction=native\|magpie`; #1099) has Codex's compaction asked of the provider as Codex sent it and its sealed item returned unchanged. Off by default. Only a provider whose wire carries it can be set so (`CarriesCompaction`: a Responses API, a ChatGPT account, GitHub Copilot; not another agent's sign-in or a plugin's), and `CompactsOn(model)` also needs the model asked on Responses. `SetNativeCompaction`, the CLI and the GUI's save refuse it elsewhere. An account keeps it through `Save`'s picks (`withPicks`), and `AddCopy` carries it. The gateway's half is in [gateway-routing](gateway-routing.md). | [`native_compaction.go`](../../internal/provider/native_compaction.go) |
| providers.json | `Path` is `providers.json` in magpie's config folder. A read that fails returns `ErrUnreadable` and is never treated as empty. `store` writes atomically through a rename and drops the cached catalog (`catalog.Touched`). | [`provider.go`](../../internal/provider/provider.go) |
| A provider renamed | `Rename` (the editor's id field, `magpie provider set <id> id=<new>`) keeps the old id in `Was`, so a model still picked by it reaches the provider. Usage is recorded under the id a call went out by and never rewritten; whatever reads it names the provider by its id now through `UsageRenames().Of(id, time)`: the summary, the Requests page (its blocks, the probe rows, other computers' days), the Sessions tab's vias, window holds, `NewPricer`/`NewCoster` and the gateway's `loggedAnswers` (cybercaius on Discord: a renamed provider was listed under both ids). `Visit` hands records out as recorded, so `Of` is taken once. An id another provider takes later (a rename onto it, or `Save` of a new provider under it) moves from the first one's `Was` to its `Gave` with the time (`giveID`): calls recorded under it before then stay the first one's, later ones are the new one's. An id held by a provider or a subscription now is never renamed (`Renamed`), and `freeID` doesn't hand out an id in any `Was`, so adding a vendor again gets `-2`. Ids reused before `Gave` existed have no time and go to whoever holds the id now. A provider deleted (`Delete`) is kept in providers.json's `deleted` with its name, `Was`, `Gave` and when (`provider.Deleted`): its calls stay under its id while no provider has that id, and once one is added under it (or a later deleted one had it) they go to `Deleted.UsageID`, `<id>~<when, UTC>`, so the new provider has only its own (cybercaius on Discord). The Usage page names either by the deleted provider's name and marks it with when it was deleted (`Renames.Gone`, `Named.Deleted`). Deletes before this was kept have no record and go to whoever holds the id now. A deleted provider's calls can be merged into a provider there is now, or named by the user, from a "…" beside the Requests page's Provider filter while it is picked (`ledProviderMore` in `plugins/usage/page.js`, `POST /api/usage/deleted`, `GET /api/usage/deleted/into`; CyberCaius on Discord, who had renamed a provider onto the old id to do it). Both are kept on its `Deleted` record, not in settings and never in the log: `MergeDeleted` sets `Into` and `MergedAt`, `NameDeleted` sets `Label` (`Deleted.Shown`), so a provider added later under the old id inherits neither. `Renames.Both(id, time)` gives the id a call is shown under (`Of`, merges followed) and the one it was made to (`Own`): a merged call is listed, filtered and summed under the target, but priced, held and answered by its own (`Record.priceID`, `block_price.go`'s `as`, window holds, `loggedAnswers`), so a merge moves no cost or token. The target's face lists what is merged into it (`Named.Merged`), and the same "…" parts each again (`into` ""). Renaming the target carries the merge; deleting it ends it (a merge older than the target's deletion is not followed). A providers.json that can't be read keeps the last renames read, not none. The summary and Requests caches key on `Renames.Key`, the vias cache too. | [`rename.go`](../../internal/provider/rename.go), [`block_price.go`](../../internal/usage/block_price.go) |
| The list | `All` merges stored providers with `Accounts()`. An entry with no URL stores the user's picks for an account. The order is `file.Order`. Reads within one request share one build (`Hold`, #746). | [`provider.go`](../../internal/provider/provider.go) |
| The list | `All` merges stored providers with `Accounts()`. An entry with no URL stores the user's picks for an account. The order is `file.Order`. Reads within one request share one build (`Hold`, #746). Requests that miss a build together (a write drops what is held) wait for the first one's build and take it, unless a write came while it was built; a wait is bounded (`heldWait`), so a caller never waits for good. Before, each built again behind `logins.json`'s lock, and requests sat past the 30s unrouted deadline (#5104: `TestLoginsMissedTogetherListedOnce`, `TestHeldWaiterBuildsAgainAfterAWrite`, `TestHeldWaiterNeverStuck`). `OwnPaused` is held the same way, once a request. | [`provider.go`](../../internal/provider/provider.go) |
| Model picks | `Models` are the models the user picked for agents; none means the vendor's list, up to 24 (`Exposed`), unless the user chose Select none (`NoModels`, `magpie provider models <id> none`): then none of its models is served, not to agents, not to any routing group (auto groups included), not by a `provider/model` id, not as a classifier, while its balance and usage are still read (`ServesNone`, #1818). Codex's own list at `/backend-api/codex/models` drops the ChatGPT account's visible models too, as spawn_agent's list of them does, and the list's ETag changes so a running Codex asks again (`CodexNativePicked` in [`codex_models.go`](../../internal/provider/codex_models.go), #2530); the hidden ones Codex runs jobs of its own on (codex-auto-review, gpt-reserve) and other providers' models stay. The editor's serves control names it Usage only, beside Vendor's list and Picked only, and the card says "usage only" (#2068); Picked only from there picks the models the vendor's list serves, to unpick from. A file without `noModels` reads as before, and a pick clears it. With nothing picked and Select none off, Best in family (`BestInFamily`, `magpie provider models <id> best`, the editor's fourth option, Steven on Discord) serves only the newest model of each family the vendor lists, up to 24: the family is the id with its version numbers taken out, a dated snapshot counts as its alias, and sizes and suffixes (-mini, -pro, -8b) stay in the name (`FamilyOf`, `BestInFamily` in [`family.go`](../../internal/catalog/family.go)). A newer one the vendor lists later takes the old one's place with nothing saved. Codex's own list narrows the same way (`CodexNativePicked`). An older one named by its `provider/model` id is still served, as an unpicked one is under Picked only. A pick or Select none clears it, and a file without `bestInFamily` reads as before. `Save` keeps beside new picks the models listed then (`PickedFrom`, `listedWith`), and the same picks saved again keep it. When the picks held every model listed then, one the vendor lists since is served first beside them (`withNewlyListed`, `Picks`); one listed then and left unpicked stays out. Picks saved before `PickedFrom` was kept are taken to hold every model when they hold every one released up to the newest of them (models.dev's `release_date`), so a Claude account whose user picked them all is served Haiku 5.5 (wakaka). The editor and the TUI start from `Picks`, so a later Save keeps the new model. While some picks are set aside (the list is known to be short), a save with new picks keeps the models the earlier `PickedFrom` had beside those listed now, so a model the user saw and left unpicked isn't new when that list has it again; a list short of no pick is taken as it is. A pick a list fetched again stops listing (`Refetch`, `KeepListsFresh`, and a plugin's hourly `KeepPluginsListed`) leaves `Models` for `Delisted` (`dropGonePicks`), not served, and goes back among the picks when a later list has it (`relistPicks`): Our Free Model's plugin lists its account channels' models only once its service has read them after a restart, and its free pools only while they answer, so each magpie update had its user pick every model again (多喝热水 on Discord). Every save keeps `Delisted` but for what it picks again (`delistedWith`); Select none clears it. A provider whose every pick is in `Delisted` serves none of its models for `pickWait` (an hour) from when the last one left (`DelistedAt`, `waitsForPicks`), not the vendor's list; after that, or for picks set aside before `DelistedAt` was kept, the picks are taken as gone for good and the list is served as if none were picked, while they still come back with a list that has them. WorkBuddy AI took its Free plan's deepseek-v4.1-flash off its list for hy3, and an account whose one pick it was got no model in the agents' picker, its row reading "1 image model" (maxleebeta on Discord). `KeepPluginsListed` asks again after `relistSoon` (5 minutes) when a list left a pick out. `TestPluginPicksComeBackWithTheirList`, `TestEveryPickDelistedServesNone`, `TestPicksGoneForGoodServeTheList` and `TestRelayPicksComeBackWithTheirList` cover it. | [`models.go`](../../internal/provider/models.go), [`provider.go`](../../internal/provider/provider.go) |
| List schedule and rules | A provider of the user's own (not an account, a plugin's or a decision-only one) can set `RefreshEvery` (`magpie provider refresh-every <id> 6h`, or 1d, or off, at least 10m) and `AutoInclude` (`magpie provider auto-include <id> 'gpt-*' 're:claude-.*'`, or none; a glob with `*`, or `re:` matching the whole id, both in any case (`compilePattern`; `(?-i)` inside a `re:` makes case matter); a plain id is refused) (#2135). The gateway (`magpie serve` or the app) looks each minute and fetches a list once `Fetched` is that old, through the same `Refetch` as Fetch models (`KeepListsFresh`); a failed fetch waits `min(every, 15m)`. `RefetchTaking` adds to the picks a model the fetch newly lists that a rule matches (`takeMatching`), starting from what is served now (`Exposed`), so nothing served is taken away and a model the user unticks stays out (it is not new to the next fetch). Setting the rules takes the current list's matches. Every save that doesn't set them keeps them, the window's editor among them; the editor has no fields for them yet. A Remote magpie with no `RefreshEvery` is fetched every 10m (`RemoteMagpieEvery`, `RefreshSchedule`), so a model the other magpie lists later (ZCode's GLM-5.3-Trial once its plugin read the gift, 6igsteven on Discord) is served without Fetch models; `off` set on it is kept as `"off"` and asks it only when told (`TestRemoteMagpieListFollowsTheOtherMagpie`). | [`autolist.go`](../../internal/provider/autolist.go), [`models.go`](../../internal/provider/models.go), [`providers_cli.go`](../../internal/cli/providers_cli.go) |
| Keys | Several keys per provider. Requests go to the first key that is on; the gateway moves on when it is out or rate limited. `Key` stays the first, so other code reads it as before. A key can be made for one protocol (`KeyProtocol`). A key made for a protocol its provider has no URL for is skipped (`perKeyBarred`); when every key is, the provider is still tried whole on the URLs it has, and the candidate carries `noURL` so it isn't quiet: Routing's row (`Weighed.NoURL`) says "key set to {api} only, no {api} URL · sent on the others", and the editor's key row shows a "No {api} URL" chip (`keyLacksURL`; #1702, `TestKeyForAProtocolWithNoURLIsSaid`, `key-nourl.test.cjs`). A key's value can be replaced in place (`ReplaceKey`, #1869: a key rotated at the vendor): it keeps its name, place, protocol, weight and on or off, and what was set for it by its fingerprint (`AccountModels`, `AccountProxies`, `AccountConcurrency`) and the gateway keys held to it (`access.ReplaceAccount`) move to the new one; the GUI's `keys/replace` also lifts its rests (`UnrestAll`). Its past requests stay under the old fingerprint, by the same name. A provider may hold thousands of keys (@NetRozee on X: a thousand froze magpie). Nothing goes over its keys once for each key: `KeysOn` drops a repeat by a set, a row's rest keys come from `RestKeys` (whether several are on, found once), and whether each key serves a model from `Serving`, which reads the lists once and keeps each model's keys as a set until the lists are read anew (`keyLists`). `KeysListed` and `ListsRead` count them for the tests (`TestProviderInfoListsKeysOnce`, `TestPerKeyReadsListsOnce`). A provider's keys have their balances, plans and remote limits read `keyReadsAtOnce` (8) at a time (`keySlots`); other providers' beside them. The editor's per-key proxy lines fold as its Accounts list does (`proxyLines`, `provider-many-keys-proxy.test.cjs`). Asking a key's models (`fetchPerKey`) still goes one key after another. | [`keys.go`](../../internal/provider/keys.go) |
+86 -5
View File
@@ -215,32 +215,113 @@ func stampNowFiles() [3]rootStamp {
// for what each row of a page looks up: shared by them, so read only.
func Held[T any](key string, build func() T) T { return heldOf(key, build) }
// heldCall is a build in flight, for the callers that miss it together.
type heldCall struct {
done chan struct{}
// v is what it built, and fresh says nothing was written meanwhile
// (Changed, a plugin's change, filememo.Forget, another environment):
// what a caller waiting on it would have built itself. Both are set
// before done is closed.
v any
fresh bool
}
// heldFlight is the builds in flight by key, held's lock guarding it. A
// write drops what is held, and every request then in flight missed
// together: each built again, one after another, each taking
// logins.json's lock when the one before it let go, 20 requests queued
// on it and the routing plan waiting past its 30s (#5104).
var heldFlight = map[string]*heldCall{}
// heldWait is how long a caller waits on another's build before it
// builds on its own, as each did before (#5104). A build waits on
// nothing of its waiters' today, but one that came to (a build asking,
// deep down, for what waits on it, or for a lock its waiter holds) is
// then a pause, not a request held for good.
var heldWait = 5 * time.Second
// heldRounds is how many builds in a row a caller waits on before it
// builds on its own: each one a write made stale, so that writes coming
// one after another can't keep a request waiting.
const heldRounds = 3
// heldOf is what build gives, built once while a request holds it.
// Callers that miss together build once: the first builds, the rest wait
// for it and take what it built, unless a write came while it was built;
// then one of them builds again (#5104). Outside a request every caller
// builds, as before.
func heldOf[T any](key string, build func() T) T {
held.Lock()
if held.holds == 0 {
held.Unlock()
return build()
}
heldFreshLocked(false)
if h, ok := held.built[key]; ok && time.Since(h.at) < heldFor {
for round := 0; ; round++ {
heldFreshLocked(false)
if h, ok := held.built[key]; ok && time.Since(h.at) < heldFor {
held.Unlock()
return h.v.(T)
}
c := heldFlight[key]
if c == nil {
break
}
held.Unlock()
return h.v.(T)
if round == heldRounds || !c.wait(heldWait) {
return build()
}
if c.fresh {
return c.v.(T)
}
held.Lock()
if held.holds == 0 {
held.Unlock()
return build()
}
}
gen := held.gen
c := &heldCall{done: make(chan struct{})}
heldFlight[key] = c
gen, fgen, env := held.gen, filememo.Gen(), held.env
held.Unlock()
// the build ends for its waiters however it ends: one that panics
// leaves them to build on their own (fresh is false)
defer func() {
held.Lock()
if heldFlight[key] == c {
delete(heldFlight, key)
}
held.Unlock()
close(c.done)
}()
v := build()
held.Lock()
if held.holds > 0 && held.gen == gen {
// a filememo-only write (settings.Save) meanwhile is a write too: kept,
// what was read before it would be given for a second after it
c.v, c.fresh = v, held.gen == gen && filememo.Gen() == fgen && held.env == env
if held.holds > 0 && c.fresh {
if held.built == nil {
held.built = map[string]heldValue{}
}
held.built[key] = heldValue{v, time.Now()}
}
delete(heldFlight, key)
held.Unlock()
return v
}
// wait waits for the build to end, for d at most, and says whether it
// ended.
func (c *heldCall) wait(d time.Duration) bool {
t := time.NewTimer(d)
defer t.Stop()
select {
case <-c.done:
return true
case <-t.C:
return false
}
}
func heldEntries(build func() []Entry) []Entry {
// clipped: a caller's append copies
return heldOf("entries", func() []Entry {
+131
View File
@@ -6,6 +6,8 @@ import (
"runtime"
"slices"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
@@ -440,3 +442,132 @@ func TestAllReadsNoSettingsPerLookWhileHeld(t *testing.T) {
}
}
}
// heldBuilding starts a build of key that waits for its go-ahead, and
// returns once it is under way: a caller missing key now waits on it.
func heldBuilding[T any](t *testing.T, key string, v T) (goAhead func(), got <-chan T) {
t.Helper()
started, ahead, out := make(chan struct{}), make(chan struct{}), make(chan T, 1)
go func() {
out <- heldOf(key, func() T { close(started); <-ahead; return v })
}()
<-started
return sync.OnceFunc(func() { close(ahead) }), out
}
// heldWaiting is a caller missing key while the build above is under
// way, its build counted in n; it returns once that caller waits.
func heldWaiting[T any](t *testing.T, key string, n *atomic.Int64, v T) <-chan T {
t.Helper()
out := make(chan T, 1)
go func() { out <- heldOf(key, func() T { n.Add(1); return v }) }()
for deadline := time.Now().Add(10 * time.Second); ; {
held.Lock()
c := heldFlight[key]
held.Unlock()
if c != nil && waiting() {
return out
}
if time.Now().After(deadline) {
t.Fatal("the second caller never waited on the build")
}
runtime.Gosched()
}
}
// waiting says a goroutine is parked in heldCall.wait: the second
// caller has missed and waits.
func waiting() bool {
buf := make([]byte, 1<<20)
return strings.Contains(string(buf[:runtime.Stack(buf, true)]), "(*heldCall).wait")
}
// A caller that missed while another built takes what was built, unless a
// write came meanwhile: a sign-in, a sign-out or a setting saved while the
// list was built made it stale, and the caller, which may have asked
// after the write, builds again (#5104). A filememo-only write
// (settings.Save tells only filememo) counts too: kept, the value read
// before it was given for a second after it.
func TestHeldWaiterBuildsAgainAfterAWrite(t *testing.T) {
for name, write := range map[string]func(){"Changed": Changed, "filememo.Forget": filememo.Forget} {
t.Run(name, func(t *testing.T) {
release := Hold()
defer release()
dropHeld()
var n atomic.Int64
goAhead, first := heldBuilding(t, "t-write", "before")
defer goAhead()
second := heldWaiting(t, "t-write", &n, "after")
write()
goAhead()
if v := <-first; v != "before" {
t.Fatalf("the builder got %q", v)
}
if v := <-second; v != "after" || n.Load() != 1 {
t.Fatalf("after a write meanwhile: got %q, built %d times; want what is there now, built once", v, n.Load())
}
if v := heldOf("t-write", func() string { return "later" }); v != "after" {
t.Fatalf("what was read before the write was kept: %q", v)
}
})
}
}
// With nothing written meanwhile, a caller that missed while another
// built takes what it built: a value held for no time at all (heldFor 0)
// too, which a look at what was kept would never find.
func TestHeldWaiterTakesTheBuild(t *testing.T) {
old := heldFor
heldFor = 0
defer func() { heldFor = old }()
release := Hold()
defer release()
var n atomic.Int64
goAhead, first := heldBuilding(t, "t-take", 1)
defer goAhead()
second := heldWaiting(t, "t-take", &n, 2)
goAhead()
if v, w := <-first, <-second; v != 1 || w != 1 || n.Load() != 0 {
t.Fatalf("got %d and %d, the second built %d times; want 1, 1 and 0", v, w, n.Load())
}
}
// A build that never ends, or panics, keeps no one waiting for good: a
// waiter builds on its own after heldWait, as every caller did before
// (#5104), and one whose builder panicked builds at once.
func TestHeldWaiterNeverStuck(t *testing.T) {
old := heldWait
heldWait = 50 * time.Millisecond
defer func() { heldWait = old }()
release := Hold()
defer release()
goAhead, _ := heldBuilding(t, "t-stuck", "never")
defer goAhead()
var n atomic.Int64
start := time.Now()
if v := heldOf("t-stuck", func() string { n.Add(1); return "own" }); v != "own" || n.Load() != 1 {
t.Fatalf("got %q, built %d times; want its own", v, n.Load())
}
if d := time.Since(start); d < heldWait {
t.Fatalf("built on its own after %v, before heldWait", d)
}
heldWait = time.Minute
ahead := make(chan struct{})
started := make(chan struct{})
go func() {
defer func() { recover() }()
heldOf("t-panic", func() string { close(started); <-ahead; panic("build") })
}()
<-started
second := heldWaiting(t, "t-panic", &n, "own")
close(ahead)
select {
case v := <-second:
if v != "own" {
t.Fatalf("after a build that panicked: %q", v)
}
case <-time.After(30 * time.Second):
t.Fatal("a build that panicked kept its waiter")
}
}
+15 -3
View File
@@ -6,6 +6,7 @@ import (
"net/http"
"net/http/httptest"
"slices"
"sync"
"testing"
)
@@ -26,11 +27,20 @@ func TestKeepLoginAsChosen(t *testing.T) {
t.Fatal(err)
}
}
used := map[string]float64{}
// the fake's answers read what the test sets next: the usage check
// runs on a request of its own, so the map is guarded (a list built
// sooner reached the fake later, and the race detector said so)
var used struct {
sync.Mutex
m map[string]float64
}
used.m = map[string]float64{}
fake := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
used.Lock()
defer used.Unlock()
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": used[r.Header.Get("chatgpt-account-id")], "limit_window_seconds": 604800}}})
"secondary_window": map[string]any{"used_percent": used.m[r.Header.Get("chatgpt-account-id")], "limit_window_seconds": 604800}}})
}))
defer fake.Close()
old := CodexBase
@@ -83,7 +93,9 @@ func TestKeepLoginAsChosen(t *testing.T) {
t.Fatalf("ranks %v", r)
}
// used up, it stays; the setting outlives a routing change
used["acct-me@example.com"], used["acct-1"] = 100, 100
used.Lock()
used.m["acct-me@example.com"], used.m["acct-1"] = 100, 100
used.Unlock()
if err := SetRouting("codex", Ordered); err != nil {
t.Fatal(err)
}
+87
View File
@@ -46,3 +46,90 @@ func TestLoginsListedOnceARequest(t *testing.T) {
t.Fatalf("outside a request: listed %d times, want 3", n)
}
}
// TestLoginsMissedTogetherListedOnce: a write drops what a request holds,
// and every request in flight lists again — each taking logins.json's
// lock (and, before the list, the agents' sign-ins) one after another, a
// convoy of requests all waiting on the same lock under parallel load
// (#5104). A list missed together is built once: the rest wait for it.
func TestLoginsMissedTogetherListedOnce(t *testing.T) {
signIn(t)
loginsSeenAt.Store(0) // another test's look within 30s would skip this HOME's
release := Hold()
defer func() { release() }()
Logins("codex") // the first list notes the sign-in in logins.json
if ls := Logins("codex"); len(ls) != 1 || ls[0].User != "me@example.com" {
t.Fatalf("codex accounts: %+v", ls)
}
runs := loginsRuns.Load()
dropHeld() // a write magpie made: what is held is listed anew
const n = 20
start := make(chan struct{})
done := make(chan []Login, n)
for range n {
go func() {
<-start
done <- Logins("codex")
}()
}
// the first list builds behind logins.json's lock, held here: who
// lists before the first is built tells the convoy, whatever the
// machine's load — every caller builds again where none waits for
// the one building, and only the one building does otherwise
loginsMu.Lock()
close(start)
var missed int64
for deadline := time.Now().Add(300 * time.Millisecond); time.Now().Before(deadline); {
if missed = loginsRuns.Load() - runs; missed >= 2 {
break
}
time.Sleep(5 * time.Millisecond)
}
loginsMu.Unlock()
for range n {
if ls := <-done; len(ls) != 1 || ls[0].User != "me@example.com" {
t.Fatalf("listed again as %+v", ls)
}
}
if got := loginsRuns.Load() - runs; got != 1 {
t.Fatalf("%d requests missing together listed %d times, want 1 (%d listed before the first was built)", n, got, missed)
}
}
// TestOwnPausedListedOnceARequest: a provider with another account on
// asks OwnPaused of its own for every request's plan, and each ask took
// logins.json's lock and read it again, even while the request held what
// Logins had listed (#5104). An ask lists once a request, as Logins does,
// and a write lists it anew.
func TestOwnPausedListedOnceARequest(t *testing.T) {
signIn(t)
loginsSeenAt.Store(0)
release := Hold()
defer func() { release() }()
Logins("codex") // the first list notes the sign-in in logins.json
p, ok := find(All(), "codex")
if !ok {
t.Fatal("no codex provider")
}
if p.OwnPaused() {
t.Fatal("the only account paused with none to fall back to")
}
held.Lock()
_, cached := held.built["ownPaused\x00codex\x00me@example.com"]
held.Unlock()
if !cached {
t.Fatal("OwnPaused was not listed once a request: it took logins.json's lock again")
}
if err := writeLogins(readLogins()); err != nil {
t.Fatal(err)
}
if p.OwnPaused() {
t.Fatal("paused after a write that paused nothing")
}
held.Lock()
_, cached = held.built["ownPaused\x00codex\x00me@example.com"]
held.Unlock()
if !cached {
t.Fatal("a write did not list OwnPaused anew")
}
}
+9 -4
View File
@@ -101,14 +101,19 @@ func pausedOwn(ls []savedLogin, agent, user string) bool {
// OwnPaused says the provider is the account a Claude Code or Codex agent
// is signed in to, paused while another of its accounts is on (#263): the
// gateway passes over it, the agent staying signed in to it.
// gateway passes over it, the agent staying signed in to it. A request's
// plan asks it of every account provider, each ask its own read of
// logins.json under its lock: listed once a request, as Logins is (#5104),
// and a write lists it anew.
func (p Provider) OwnPaused() bool {
if p.Account == nil || p.Account.token != nil && !p.Account.standIn || !slices.Contains(loginAgents, p.Account.Agent) {
return false
}
loginsMu.Lock()
defer loginsMu.Unlock()
return pausedOwn(readLogins(), p.Account.Agent, p.Account.User)
return heldOf("ownPaused\x00"+p.Account.Agent+"\x00"+p.Account.User, func() bool {
loginsMu.Lock()
defer loginsMu.Unlock()
return pausedOwn(readLogins(), p.Account.Agent, p.Account.User)
})
}
// AlsoOn is a signed-in agent's other accounts that are on, each as a