diff --git a/internal/provider/account_test.go b/internal/provider/account_test.go index fb215fd17..9cef36e72 100644 --- a/internal/provider/account_test.go +++ b/internal/provider/account_test.go @@ -72,8 +72,14 @@ func signIn(t *testing.T) string { // logins and forgets anything a previous test cached. func isolate(t testing.TB) { t.Helper() + // nor a read a test before it left running, though it isolated nothing + endReadsOut(t, "before the test") oldKeychain, oldBase, oldExe := claudeKeychain, claudeBase, claudeExecutable oldDevin := DevinExecutable + // a read this test leaves running ends with it (#3174): registered + // first, this runs after every other cleanup, with the test's fakes + // let go + t.Cleanup(func() { endReadsOut(t, "after the test") }) claudeKeychain = false claudeExecutable = func() string { return "" } // a Claude sign-in with no Claude Code downloads one: never in a test @@ -268,6 +274,31 @@ func TestAccountsAreProviders(t *testing.T) { } } +// endReadsOut waits for the allowance and usage reads a test left running +// (readsOut). Left to run on, one reads the sign-in in the next test's +// home before that test has written it, and caches that there is none: +// TestClaudeAccountServesModelsListedSinceItsFetch found no Claude +// account, under load only, after TestClaudeAllSignedOutStaysListed's +// InUseLogin left its Allowances read past firstWait (#3174). +func endReadsOut(t testing.TB, when string) { + t.Helper() + deadline := time.After(time.Minute) // a read gives up after 30s + for { + readsOut.Lock() + n, idle := readsOut.n, readsOut.idle + readsOut.Unlock() + if n == 0 { + return + } + select { + case <-idle: + case <-deadline: + t.Errorf("%d allowance or usage reads still ran a minute %s", n, when) + return + } + } +} + // claudeSignIn writes a Claude Code OAuth login into a temp home. func claudeSignIn(t *testing.T, home string, expiry time.Time) string { t.Helper() diff --git a/internal/provider/key_allowance.go b/internal/provider/key_allowance.go index dba6a97a2..7e89c53dc 100644 --- a/internal/provider/key_allowance.go +++ b/internal/provider/key_allowance.go @@ -171,7 +171,8 @@ func KeyAllowance(p Provider) (Allowance, bool) { // last till the user asks, or the key says it is out (#1518) if !e.loading && time.Since(e.at) > age && (e.refused || !readsAsked()) { e.loading = true - go readKeyAllowance(p, id, c.gen) + gen := c.gen + goRead(func() { readKeyAllowance(p, id, gen) }) } return e.a, len(e.a) > 0 } @@ -210,7 +211,7 @@ func readKeyAllowance(p Provider, id string, gen int) { } if e.stale { e.stale, e.loading, e.at = false, true, time.Time{} - go readKeyAllowance(p, id, gen) + goRead(func() { readKeyAllowance(p, id, gen) }) } c.Unlock() if renewed { diff --git a/internal/provider/reads_out_test.go b/internal/provider/reads_out_test.go new file mode 100644 index 000000000..c8345e529 --- /dev/null +++ b/internal/provider/reads_out_test.go @@ -0,0 +1,48 @@ +package provider + +import ( + "context" + "sync/atomic" + "testing" + "time" +) + +// An allowance read Allowances leaves running past firstWait ends with the +// test that started it: left to run on, it read Claude Code's sign-in in the +// next test's home before that test wrote it, cached that there was none, +// and TestClaudeAccountServesModelsListedSinceItsFetch found no Claude +// account (#3174). +func TestReadLeftOutEndsWithItsTest(t *testing.T) { + var ended atomic.Bool + // put back by the outer test: LoginUsageVia waits for the stand-in it + // replaces to return, which would wait the read out for the subtest + t.Cleanup(func() { LoginUsageVia(nil) }) + t.Run("leaves a read out", func(t *testing.T) { + claudeHome(t) + usedCache.Lock() + usedCache.m, usedCache.at, usedCache.loading = map[string]map[string]Allowance{}, map[string]time.Time{}, map[string]chan struct{}{} + usedCache.Unlock() + old := firstWait + firstWait = time.Millisecond + t.Cleanup(func() { firstWait = old }) + release := make(chan struct{}) + LoginUsageVia(func(context.Context, string) map[string]SubscriptionQuota { + <-release + // what the read does once let go takes time a test that + // doesn't wait for it is long gone in + time.Sleep(200 * time.Millisecond) + claudeCredential() + ended.Store(true) + return nil + }) + // run before isolate's: the read is let go as the test ends + t.Cleanup(func() { close(release) }) + Allowances("claude") + if ended.Load() { + t.Fatal("the read ended before the test did: nothing was left out") + } + }) + if !ended.Load() { + t.Fatal("the allowance read Allowances left out ran on after its test") + } +} diff --git a/internal/provider/routing.go b/internal/provider/routing.go index 0c694ae4f..467db2b90 100644 --- a/internal/provider/routing.go +++ b/internal/provider/routing.go @@ -303,6 +303,37 @@ func Unwaited() (release func()) { return sync.OnceFunc(func() { unwaited.Add(-1) }) } +// readsOut counts the allowance and usage reads a caller left running +// in the background (Allowances past firstWait, SubscriptionUsage with a +// stale copy to serve, a key's allowance), for a test to wait for at its +// end: what such a read finds — Claude Code's sign-in in whatever home is +// set by then — lands in the next test's caches otherwise (#3174). +var readsOut struct { + sync.Mutex + n int + idle chan struct{} // closed when n drops to 0 +} + +// goRead runs f as a read left out (readsOut). +func goRead(f func()) { + readsOut.Lock() + if readsOut.n == 0 { + readsOut.idle = make(chan struct{}) + } + readsOut.n++ + readsOut.Unlock() + go func() { + defer func() { + readsOut.Lock() + if readsOut.n--; readsOut.n == 0 { + close(readsOut.idle) + } + readsOut.Unlock() + }() + f() + }() +} + // Allowance is an account's allowance windows as last known. type Allowance []Limit @@ -813,7 +844,7 @@ func Allowances(agent string) map[string]Allowance { done = make(chan struct{}) c.loading[agent] = done began := c.generation - go func() { + goRead(func() { ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) defer cancel() share := renewalShare(agent) // read before the lock: it reads providers.json @@ -899,7 +930,7 @@ func Allowances(agent string) map[string]Allowance { tellStarted(agent, user) } close(done) - }() + }) } _, known := c.m[agent] c.Unlock() diff --git a/internal/provider/subscription_usage.go b/internal/provider/subscription_usage.go index 5f072a96d..d1ce9eda9 100644 --- a/internal/provider/subscription_usage.go +++ b/internal/provider/subscription_usage.go @@ -336,7 +336,7 @@ func SubscriptionUsage(ctx context.Context) []SubscriptionQuota { } readCtx, seq := quotaReading(bg) asked := claudeAskGeneration.Load() - go func() { + goRead(func() { out := fetchSubscriptionUsage(readCtx) noteDailyCredits(out, time.Now()) noteCardHistory(out, time.Now()) @@ -351,7 +351,7 @@ func SubscriptionUsage(ctx context.Context) []SubscriptionQuota { // has it finished, hook and all toldUsage() close(done) - }() + }) } pending := c.pending c.Unlock()