Files
magpie/internal/plugin/modelsdev_wait_test.go
T
yetone 194b2fd3c5 plugin: the host keeps models.dev's catalog through a half-written refresh, and #1928's start test leaves a loaded runner room (#1928 review)
Review of Totopo27's bfd56fab (the commit before this one), which makes the
plugin host start without waiting on models.dev and read the catalog again
once it is written.

What this changes on top of it:
- host.js mdev(): catalog.Sync writes models.json in place, so a host
  listing providers during a refresh could read it half written. That
  read replaced the catalog it had with {}, and the Go side kept that
  list until its next refresh. A read that fails now keeps what was read
  before (a failed read means unknown) and is tried again next time.
  TestHostKeepsTheCatalogThroughAHalfWrite: red with bfd56fab's mdev()
  ("a catalog read half written dropped the catalog read before"), green
  with this.
- TestHostStartDoesNotWaitOnHangingModelsDev bounded a real bun host start
  by 3s, which a loaded runner can exceed. It now allows 15s within a 25s
  context: the old blocking start still fails it (the hanging sync holds
  the start until the context ends).

What was run at this head (Go 1.26.8, worktree of origin/main 429698f96,
private GOCACHE, sandbox HOME):
- gofmt -l: clean. go vet ./... (darwin), GOOS=linux go vet -tags nogui
  ./..., GOOS=windows go vet ./...; go build, GOOS=linux go build -tags
  nogui, GOOS=windows go build: all ok.
- go test -tags nogui -count=1 ./...: every package ok except
  internal/agent and internal/gateway, which hit the default 10m timeout
  at load average ~190, internal/edit's TestTOMLBigFileParsesInLinearTime
  (1.27s against a 1s bound, filed as #2219; passes alone -count=3) and
  gateway's TestIntentClassifierFails (#1829, passes alone -count=3).
  internal/agent, internal/gateway, internal/plugin, internal/catalog
  then ran with -timeout 60m: all ok.
- go test -race -count=20 on the three new plugin tests and on catalog's
  TestSync*: ok. -race -count=10 again with this commit's test: ok.
- A throwaway test dumping goroutines after the start and background-sync
  tests (and their Settle): none of hangModelsDev, syncLock or startOn's
  goroutine left.
- Broken by hand on bfd56fab, each red: forgetProviders() after the
  background sync removed (TestHostBackgroundSyncForgetsProviders);
  SyncIfMissing's Source() re-check removed
  (TestSyncIfMissingSkipsFetchWhenCacheAppearsWhileLocked, 1 request);
  ctx dropped from the lock wait (TestSyncHonorsContextLockWait, in 1s);
  mdev()'s read-once caching put back
  (TestHostReloadsCatalogWhenFileAppears); the blocking 30s sync put back
  in startOn (both subtests, startOn failed on the deadline after 30s).

Not tried: a real models.dev outage end to end in the GUI; the Windows
box. with_sync_in_flight still sleeps 50ms for its Sync to take the lock,
so it may test the "alone" case on a slow runner; it can't go red from it.
2026-10-14 23:52:15 +08:00

333 lines
9.0 KiB
Go

package plugin
import (
"context"
"net"
"net/http"
"os"
"path/filepath"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/yetone/magpie/internal/catalog"
"github.com/yetone/magpie/internal/testenv"
)
var (
hangInitOnce sync.Once
hangEnabled atomic.Bool
hangStopMu sync.Mutex
hangStopCh chan struct{}
)
func installHangTransport() {
hangInitOnce.Do(func() {
tr, ok := http.DefaultTransport.(*http.Transport)
if !ok {
return
}
orig := tr.DialContext
tr.DialContext = func(ctx context.Context, network, addr string) (net.Conn, error) {
if hangEnabled.Load() && (addr == "models.dev:443" || strings.HasPrefix(addr, "models.dev:")) {
hangStopMu.Lock()
stop := hangStopCh
hangStopMu.Unlock()
if stop != nil {
select {
case <-ctx.Done():
return nil, ctx.Err()
case <-stop:
return nil, context.Canceled
}
}
}
if orig != nil {
return orig(ctx, network, addr)
}
return (&net.Dialer{}).DialContext(ctx, network, addr)
}
})
}
// hangModelsDev wraps http.DefaultTransport's DialContext so dials to
// models.dev:443 block until the request's context is canceled or the test ends.
func hangModelsDev(t *testing.T) {
t.Helper()
installHangTransport()
stop := make(chan struct{})
hangStopMu.Lock()
hangStopCh = stop
hangStopMu.Unlock()
hangEnabled.Store(true)
t.Cleanup(func() {
hangEnabled.Store(false)
close(stop)
})
}
// startBound is how long a host start may take here: far under the 25s
// the hanging models.dev held it for before, and far over a bun start on a
// loaded runner, so the test is red only for the wait it is about.
const startBound = 15 * time.Second
// TestHostStartDoesNotWaitOnHangingModelsDev (#1928): with no cached catalog,
// a hanging models.dev server must not stall startOn, both when alone and when
// another catalog.Sync is already holding the lock in flight.
func TestHostStartDoesNotWaitOnHangingModelsDev(t *testing.T) {
bun := testenv.Bun(t)
hangModelsDev(t)
sandbox(t)
catalog.Reset()
t.Run("alone", func(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 25*time.Second)
defer cancel()
start := time.Now()
h, _, err := startOn(ctx, bun)
if err != nil {
t.Fatalf("startOn failed: %v", err)
}
defer h.stop()
elapsed := time.Since(start)
if elapsed >= startBound {
t.Fatalf("startOn took %v; want fast start not waiting on models.dev", elapsed)
}
})
t.Run("with_sync_in_flight", func(t *testing.T) {
syncCtx, syncCancel := context.WithTimeout(context.Background(), 10*time.Second)
defer syncCancel()
// Start a Sync that holds the lock while hanging on models.dev
syncStarted := make(chan struct{})
syncDone := make(chan struct{})
go func() {
close(syncStarted)
defer close(syncDone)
_ = catalog.Sync(syncCtx)
}()
<-syncStarted
time.Sleep(50 * time.Millisecond) // ensure Sync acquired lock
ctx, cancel := context.WithTimeout(context.Background(), 25*time.Second)
defer cancel()
start := time.Now()
h, _, err := startOn(ctx, bun)
if err != nil {
t.Fatalf("startOn failed with sync in flight: %v", err)
}
defer h.stop()
elapsed := time.Since(start)
if elapsed >= startBound {
t.Fatalf("startOn took %v with sync in flight; want fast start without blocking", elapsed)
}
syncCancel()
<-syncDone
})
}
// TestHostReloadsCatalogWhenFileAppears verifies that if the host starts
// before models.json exists on disk, it dynamically reloads models.dev when the
// catalog file appears or updates.
func TestHostReloadsCatalogWhenFileAppears(t *testing.T) {
sandbox(t)
catalog.Reset()
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
defer cancel()
abs, err := filepath.Abs("testdata/fake/index.js")
if err != nil {
t.Fatal(err)
}
if _, err := Add(ctx, abs); err != nil {
t.Fatal(err)
}
// Before catalog exists, Providers returns only the plugin's own models
psBefore, err := Providers(ctx)
if err != nil {
t.Fatalf("Providers before cache: %v", err)
}
if len(psBefore) != 1 || psBefore[0].ID != "fakeco" {
t.Fatalf("Providers before cache = %+v", psBefore)
}
hasModel := func(ps []Provider, id string) bool {
for _, m := range ps[0].Models {
if m.ID == id {
return true
}
}
return false
}
if hasModel(psBefore, "mdev-fake-model") {
t.Fatal("mdev-fake-model present before cache was written")
}
// Write models.json to CachePath
p := catalog.CachePath()
if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil {
t.Fatal(err)
}
catalogJSON := `{"fakeco":{"id":"fakeco","name":"FakeCo ModelsDev","models":{"mdev-fake-model":{"id":"mdev-fake-model"}}}}`
if err := os.WriteFile(p, []byte(catalogJSON), 0o644); err != nil {
t.Fatal(err)
}
t.Cleanup(func() { os.Remove(p) })
// Invalidate Go-side cache so it asks the host again
forgetProviders()
psAfter, err := Providers(ctx)
if err != nil {
t.Fatalf("Providers after cache: %v", err)
}
if len(psAfter) != 1 || psAfter[0].ID != "fakeco" {
t.Fatalf("Providers after cache = %+v", psAfter)
}
if !hasModel(psAfter, "mdev-fake-model") {
t.Fatalf("mdev-fake-model missing in Models after models.json appeared; host.js did not reload catalog: %+v", psAfter[0].Models)
}
}
// TestHostBackgroundSyncForgetsProviders verifies that when a background
// catalog sync succeeds, it calls forgetProviders() so Cached() serves the
// newly available models.dev models without requiring manual cache invalidation.
func TestHostBackgroundSyncForgetsProviders(t *testing.T) {
sandbox(t)
catalog.Reset()
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
defer cancel()
abs, err := filepath.Abs("testdata/fake/index.js")
if err != nil {
t.Fatal(err)
}
syncRelease := make(chan struct{})
wasSync := syncCatalog
syncCatalog = func(ctx context.Context) error {
select {
case <-syncRelease:
case <-ctx.Done():
return ctx.Err()
}
p := catalog.CachePath()
if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil {
return err
}
catalogJSON := `{"fakeco":{"id":"fakeco","name":"FakeCo ModelsDev","models":{"mdev-fake-model":{"id":"mdev-fake-model"}}}}`
return os.WriteFile(p, []byte(catalogJSON), 0o644)
}
t.Cleanup(func() { syncCatalog = wasSync })
if _, err := Add(ctx, abs); err != nil {
t.Fatal(err)
}
// First call to Providers starts the host (triggering background syncCatalog).
// Because syncCatalog is waiting on syncRelease, models.json is not on disk yet.
psBefore, err := Providers(ctx)
if err != nil {
t.Fatalf("Providers before sync: %v", err)
}
hasModel := func(ps []Provider, id string) bool {
if len(ps) == 0 {
return false
}
for _, m := range ps[0].Models {
if m.ID == id {
return true
}
}
return false
}
if hasModel(psBefore, "mdev-fake-model") {
t.Fatal("mdev-fake-model present before catalog sync completed")
}
// Release syncCatalog to write models.json and return nil (which calls forgetProviders()).
close(syncRelease)
catalogSyncing.Wait()
// Cached() triggers background refresh when !provGood.
Cached()
Refreshed()
psAfter := Cached()
if !hasModel(psAfter, "mdev-fake-model") {
t.Fatalf("mdev-fake-model missing in Cached() after background sync; forgetProviders() was not called: %+v", psAfter)
}
}
// TestHostKeepsTheCatalogThroughAHalfWrite: catalog.Sync writes
// models.json in place, so a refresh can be read half written. That reading
// is unknown, not an empty catalog: the host keeps the catalog it read
// before, rather than listing the plugins' providers without it (which
// the Go side would keep until its next refresh), and reads the file again
// once it is whole, even within the same mtime.
func TestHostKeepsTheCatalogThroughAHalfWrite(t *testing.T) {
sandbox(t)
catalog.Reset()
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
defer cancel()
abs, err := filepath.Abs("testdata/fake/index.js")
if err != nil {
t.Fatal(err)
}
if _, err := Add(ctx, abs); err != nil {
t.Fatal(err)
}
p := catalog.CachePath()
if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil {
t.Fatal(err)
}
t.Cleanup(func() { os.Remove(p) })
whole := `{"fakeco":{"id":"fakeco","name":"FakeCo ModelsDev","models":{"mdev-fake-model":{"id":"mdev-fake-model"}}}}`
write := func(s string, at time.Time) {
if err := os.WriteFile(p, []byte(s), 0o644); err != nil {
t.Fatal(err)
}
if err := os.Chtimes(p, at, at); err != nil {
t.Fatal(err)
}
}
has := func() bool {
forgetProviders()
ps, err := Providers(ctx)
if err != nil {
t.Fatal(err)
}
for _, m := range ps[0].Models {
if m.ID == "mdev-fake-model" {
return true
}
}
return false
}
before := time.Now().Add(-2 * time.Minute).Truncate(time.Second)
refresh := before.Add(time.Minute)
write(whole, before)
if !has() {
t.Fatal("the catalog's model isn't listed")
}
write(whole[:40], refresh)
if !has() {
t.Fatal("a catalog read half written dropped the catalog read before")
}
write(whole, refresh)
if !has() {
t.Fatal("the whole catalog isn't read once the half write is done")
}
}