Files
magpie/internal/provider/fetching_new_test.go
T
yetone 4a6bf80f48 provider: TestFetchingNewForgottenWhileListed forgets Cursor in the page's listing only (#2390)
Red on ubuntu CI at a1f7b8c13 (run 38722019804): "a CLI forgotten while
the accounts were listed, and FetchingNew says none is on its way".

Cause, in the test: its GrokExecutable stand-in forgot Cursor on the
first call made by any goroutine in the process, and Cursor's stand-in
ask answered "nobody" at once. A read another test left running (a usage
refresh, fetchSubscriptionUsage, reads Cursor's identity and then Grok's
account, uncounted, after its caller returned) could take that first
call. Cursor was then forgotten and settled again before FetchNewBehind's
listing read it: both identitiesUnsettled checks were false and nothing
was due, so FetchingNew was rightly false. The code is right in that
interleaving; the test assumed only its own listing reads the accounts.

Fix: the forget fires only on a GrokExecutable call made under
FetchNewBehind (checked on the call's stack), and Cursor's ask answers
only after the test has read FetchingNew, so a foreign read after the
forget can't settle it either. The cleanup releases the ask before it
waits for the fetch.

Broken by hand:
- the old test with a goroutine doing GrokExecutable(); cursorIdentity()
  before FetchNewBehind: red with CI's exact message (0.03s). The fixed
  test with the same injection: green.
- stack gate kept, ask back to answering nobody at once, and a foreign
  cursorIdentity() run right after the forget: red with CI's message.
  The fixed test with the same foreign read: green.
The exact leftover goroutine on CI wasn't captured; goroutine dumps at
the test's start were clean in green runs on macOS and in a Linux arm64
container, so the reader is inferred from who calls both paths.

Run at a1f7b8c13, go1.26.8 darwin/arm64:
- go test -count=1 -timeout 45m ./internal/provider: ok (446.8s)
- go test -race -count=50 -run 'TestFetchingNewForgottenWhileListed$'
  ./internal/provider: ok
- gofmt -l internal/provider: clean
- go vet ./internal/provider/... on darwin, GOOS=linux -tags nogui and
  GOOS=windows: ok
2026-10-15 20:31:03 +08:00

276 lines
8.9 KiB
Go

package provider
import (
"net/http"
"net/http/httptest"
"path/filepath"
"runtime"
"strings"
"sync"
"testing"
"time"
"github.com/yetone/magpie/internal/catalog"
)
// FetchingNew says a fetch is on its way as soon as FetchNewBehind or
// FetchNewSoon has started one, not once its goroutine reaches FetchNew: the
// Providers page reads it straight after FetchNewBehind and stops asking on
// false, so it kept the list it had while the fetch was about to run, and a
// test's cleanup that waited on it let its fetch run into the next test
// (TestProvidersAnswerWhileListsComeIn failed on CI). And a page's poll with
// no account due starts nothing it then counts: counted, each poll found
// the last one's still under way and the page asked for ever. A CLI still
// asked who is signed in is waited for behind the page, counted meanwhile.
// One P keeps a started goroutine from running before FetchingNew is read.
func TestFetchingNewOnceStarted(t *testing.T) {
isolate(t)
home := t.TempDir()
t.Setenv("HOME", home)
t.Setenv("USERPROFILE", home)
t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config"))
t.Setenv("XDG_CACHE_HOME", filepath.Join(home, ".cache"))
reset := func() {
newFetches.Lock()
newFetches.m = map[string]time.Time{}
newFetches.Unlock()
newSoonAt.Store(0)
wbTokens.Lock()
wbTokens.m = map[string]wbCreds{}
wbTokens.Unlock()
forgetAccountCaches()
}
reset()
// the vendor answers once the test lets it
release := make(chan struct{}, 8)
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/v3/config" {
w.WriteHeader(404)
return
}
select {
case <-release:
case <-time.After(5 * time.Second):
}
w.Write([]byte(`{"code":0,"data":{"agents":[{"name":"cli","models":["hy4-preview"]}],
"models":[{"id":"hy4-preview","name":"Hy4 preview"}]}}`))
}))
old := wbEndpoint
wbEndpoint = srv.URL
t.Cleanup(func() {
close(release)
waitFetchingNew(t)
srv.Close()
wbEndpoint = old
reset()
})
future := time.Now().Add(24 * time.Hour).UnixMilli()
writeFile(t, wbAuthFile(home), map[string]any{
"account": map[string]any{"uid": "u1", "nickname": "旅行者"},
"auth": map[string]any{"accessToken": "a", "refreshToken": "r",
"expiresAt": future, "refreshExpiresAt": future, "domain": "www.codebuddy.cn"},
})
forgetAccountCaches()
All()
defer runtime.GOMAXPROCS(runtime.GOMAXPROCS(1))
// the Providers page: the account's list is due
FetchNewBehind(5 * time.Second)
if !FetchingNew() {
t.Fatal("FetchNewBehind started a fetch, and FetchingNew says none is on its way")
}
release <- struct{}{}
waitFetchingNew(t)
// the page asks again with the list in: nothing is due, nothing runs
FetchNewBehind(5 * time.Second)
if FetchingNew() {
t.Fatal("a poll with nothing due keeps FetchingNew up")
}
waitFetchingNew(t)
// the panel, with the list due again
if err := catalog.SaveLive("workbuddy", "", nil); err != nil {
t.Fatal(err)
}
newFetches.Lock()
newFetches.m = map[string]time.Time{}
newFetches.Unlock()
newSoonAt.Store(0)
FetchNewSoon(5 * time.Second)
if !FetchingNew() {
t.Fatal("FetchNewSoon started a fetch, and FetchingNew says none is on its way")
}
release <- struct{}{}
waitFetchingNew(t)
// a FetchNew under way (start-up's) holds the accounts: the page
// doesn't wait on it, and is told lists are on their way
newFetches.Lock()
start := time.Now()
FetchNewBehind(5 * time.Second)
took := time.Since(start)
busy := FetchingNew()
newFetches.Unlock()
if took > time.Second || !busy {
t.Fatalf("behind a FetchNew under way: took %v, fetching %v", took, busy)
}
waitFetchingNew(t)
// a second page asks while the first's fetch still picks the accounts
// due (held on reading them): it starts nothing, and is told lists are
// on their way (tsuixl on #1147)
if err := catalog.SaveLive("workbuddy", "", nil); err != nil {
t.Fatal(err)
}
newFetches.Lock()
newFetches.m = map[string]time.Time{}
newFetches.Unlock()
held.Lock()
first := make(chan struct{})
go func() {
defer close(first)
FetchNewBehind(5 * time.Second)
}()
for deadline := time.Now().Add(5 * time.Second); !fetchingNew.Load(); {
if time.Now().After(deadline) {
held.Unlock()
t.Fatal("the first FetchNewBehind didn't start")
}
runtime.Gosched()
}
FetchNewBehind(5 * time.Second)
busy = FetchingNew()
held.Unlock()
<-first
if !busy {
t.Fatal("a FetchNewBehind behind one still picking the accounts due is told none is on its way")
}
release <- struct{}{}
waitFetchingNew(t)
// the panel's FetchNewSoon lists nothing before it returns, so
// /api/state?last=1 answers at once (#1519) while the accounts' read
// is held, and is counted still
newSoonAt.Store(0)
held.Lock()
soon := make(chan bool)
go func() {
FetchNewSoon(5 * time.Second)
soon <- FetchingNew()
}()
select {
case busy = <-soon:
held.Unlock()
case <-time.After(time.Second):
held.Unlock()
<-soon
t.Fatal("FetchNewSoon waited on the accounts' read")
}
if !busy {
t.Fatal("FetchNewSoon started a fetch, and FetchingNew says none is on its way")
}
waitFetchingNew(t)
// a CLI never asked who is signed in, as after a sign-in forgot it, or
// one still asked: which accounts are due can't be known without
// waiting on it, which the page doesn't (#541); the fetch lists them
// and waits behind the page, which is told lists are on their way until
// it has (yetone on #1147, #1789)
wasDevin, wasFirst := devinStatus, firstAsk
defer func() { devinStatus, firstAsk = wasDevin, wasFirst }()
firstAsk = 5 * time.Second // long, to tell a look's wait from none
for _, asked := range []bool{false, true} {
answer := make(chan struct{})
devinStatus = &cliIdentity{name: "devin-test", exe: func() string { return "" }, read: true,
ask: func() (string, string, bool, error) { <-answer; return "", "", false, nil }}
if asked {
devinStatus.Lock()
devinStatus.waited = true // its look gave up already
devinStatus.refresh()
devinStatus.Unlock()
}
start = time.Now()
FetchNewBehind(5 * time.Second)
took = time.Since(start)
busy = FetchingNew()
if took > time.Second || !busy {
close(answer)
waitFetchingNew(t)
t.Fatalf("with a CLI asked %v who is signed in: took %v, fetching %v", asked, took, busy)
}
close(answer)
waitFetchingNew(t)
}
}
// A CLI forgotten while the Providers page's FetchNewBehind lists the
// accounts (a sign-in finishing then) left its account out of that list:
// the fetch is asked behind the page, which is told lists are on their
// way, not that none is due. The forget is that listing's own, and the CLI
// answers only once the page was told: a read another test left running
// (a usage refresh reads Grok's account, then Cursor's) took the first
// GrokExecutable call, forgot Cursor before the listing read it, and
// Cursor answered nobody at once, so nothing was left to wait on and
// nothing was due (#2390, red on ubuntu CI).
func TestFetchingNewForgottenWhileListed(t *testing.T) {
isolate(t)
home := t.TempDir()
t.Setenv("HOME", home)
t.Setenv("USERPROFILE", home)
t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config"))
t.Setenv("XDG_CACHE_HOME", filepath.Join(home, ".cache"))
newFetches.Lock()
newFetches.m = map[string]time.Time{}
newFetches.Unlock()
newSoonAt.Store(0)
ForgetAccounts()
answer := make(chan struct{})
answered := sync.OnceFunc(func() { close(answer) })
wasCursor, wasDevin, wasGrok := cursorStatus, devinStatus, GrokExecutable
t.Cleanup(func() {
answered()
waitFetchingNew(t)
cursorStatus, devinStatus, GrokExecutable = wasCursor, wasDevin, wasGrok
ForgetAccounts()
})
nobody := func() (string, string, bool, error) { return "", "", false, nil }
now := time.Now()
// asked again once forgotten, Cursor answers after the page was told
cursor := &cliIdentity{name: "cursor-test", exe: func() string { return "" }, read: true, at: now,
ask: func() (string, string, bool, error) { <-answer; return nobody() }}
cursorStatus = cursor
devinStatus = &cliIdentity{name: "devin-test", exe: func() string { return "" }, read: true, at: now, ask: nobody}
// Grok's account is read after Cursor's: the sign-in lands there, in
// the page's own listing, not in anything else reading the accounts
var once sync.Once
GrokExecutable = func() string {
b := make([]byte, 64<<10)
if strings.Contains(string(b[:runtime.Stack(b, false)]), "provider.FetchNewBehind(") {
once.Do(cursor.forget)
}
return ""
}
FetchNewBehind(5 * time.Second)
busy := FetchingNew()
answered()
waitFetchingNew(t)
if !busy {
t.Fatal("a CLI forgotten while the accounts were listed, and FetchingNew says none is on its way")
}
}
// waitFetchingNew waits for the fetches under way to end, the ones started
// in the background included.
func waitFetchingNew(t *testing.T) {
t.Helper()
for deadline := time.Now().Add(10 * time.Second); FetchingNew() || fetchingNew.Load(); {
if time.Now().After(deadline) {
t.Fatal("a fetch still runs after 10s")
}
time.Sleep(5 * time.Millisecond)
}
}