Files
magpie/internal/gateway/plugin_bunready_test.go
T
yetone 30de93e9e9 plugins: a request whose Bun is still downloading fails at once and fails over (#6735)
hixonchan (kyrierekkok123-del on GitHub): with magpie's own Bun missing
and its download stalled, every plugin-served request hung with zero
bytes, nothing in the log, no timeout and no failover, and `magpie
plugin` hung too. The host's lock (hostMu) was held across Bun's
download, which had no bound on the whole, so every caller waited on it
whatever its context said.

Now:
- Bun is downloaded in the background, once at a time per Bun
  (bunready.go). The host waits for it up to 10s from when it began
  (bunReadyWait); then each call ends with BunNotReadyError, "Bun
  runtime not ready: downloading Bun 1.4.2 (12s so far)…" or "… failed:
  <why>", logged, and the gateway goes on to the group's next member.
- A failed download is said at once for a minute, then tried again;
  installs (plugin.Bun) still wait as long as their context lets.
- hostMu is a channel lock that a caller's context can end (LockCtx);
  the gateway's TryLock polling loops use it.
- When the download fails, a Bun on PATH or in ~/.bun/bin is taken if
  magpie would run it itself: at least BunVersion, not set aside, passing
  the try a new release gets. It is copied in as magpie-bun (#1048).
  magpie's checksummed build stays first; the user's own Bun is better
  than no plugins, and it is what the reporter fell back on by hand.
- Each stage is logged: download started, failed after N, downloaded in
  N, the PATH Bun taken or refused and why.
- Every route through the host gets it: fetch, loader options, sign-in,
  the plugin listing (CLI and GUI). `magpie plugin` prints the list and
  the not-ready reason within ~10s.

Self-restart and env (the reporter's point 4): Reexec, RelaunchBinary and
StartBeside pass os.Environ; only the Mac's bundle relaunch (open -n)
starts with LaunchServices' env. Filed as #6757, not changed here. With
this change MAGPIE_BUN isn't needed.

Tests (each red on the old code with a shim for the new test hooks, logs
kept):
- TestHostWhileBunDownloadStalls: old code, "a caller whose context
  ended still waits on the stalled Bun download"; now not-ready at 2s,
  the 100ms caller returns, then the host starts on the download, asked
  once.
- TestHostAfterBunDownloadFailedSaysWhy: old code, a plain 500 error,
  not BunNotReady; now the 500 is said twice with one ask, Bun() retries.
- TestBunOnPathAfterDownloadFailed: old code failed; now 1.4.2 taken,
  1.0.0 refused.
- TestPluginWhoseBunIsNotReadyFailsOver (gateway, real Handler): old
  code, "group/mixed still unanswered after 20s"; now 200 from the next
  member in 0.84s, and the plugin's own model answers 502 "Bun runtime
  not ready" after ~300ms.

Run on mote at 923cc8747 + this commit (rebased since onto d7cda856a,
a GUI-only library change): gofmt -l clean; go vet ./...,
GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet ./..., go
build, GOOS=linux go build -tags nogui, GOOS=windows go build: ok.
go test -tags nogui -count=1 -timeout 45m ./...: every package ok
(plugin 219s, gateway 1001s) except two untouched by this change:
- internal/usage TestWholeKeptAcrossReset: red on origin/main d7cda856a
  too, 4 of 5 at -count=5 (#6760).
- internal/provider TestRemoveListedAccountLeavesHiddenNamesake: red
  once in the full run, 5 of 5 alone (#6761).
The four new tests pass on Linux (WSL magpie-desktop) and, the two that
run there, on Windows (xiaomi-gpu).

Not tried: a real magpie binary with a really blocked GitHub download
(the gateway test runs the real handler with a stalled release server),
and the Mac relaunch.
2026-11-15 21:26:33 +08:00

107 lines
3.3 KiB
Go

package gateway
import (
"context"
"fmt"
"io"
"net/http"
"net/http/httptest"
"path/filepath"
"strings"
"testing"
"time"
"github.com/yetone/magpie/internal/plugin"
"github.com/yetone/magpie/internal/provider"
"github.com/yetone/magpie/internal/testenv"
)
// A plugin's provider whose Bun is still downloading, the download
// stalled, fails at once and says why, and a routing group goes on to its
// next member, as for any other member that can't answer (#6735): neither
// waits on the download.
func TestPluginWhoseBunIsNotReadyFailsOver(t *testing.T) {
bun := testenv.Bun(t)
fresh(t)
t.Setenv("MAGPIE_BUN", bun)
t.Cleanup(plugin.Settle)
up := testenv.FakeVendor(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
io.ReadAll(r.Body)
w.Header().Set("Content-Type", "text/event-stream")
fmt.Fprint(w, `data: {"id":"c","object":"chat.completion.chunk","model":"fake-1","choices":[{"index":0,"delta":{"role":"assistant","content":"from plugin"},"finish_reason":"stop"}]}`+"\n\ndata: [DONE]\n\n")
}))
defer up.Close()
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
defer cancel()
abs, _ := filepath.Abs("../plugin/testdata/fake/index.js")
if _, err := plugin.Add(ctx, abs); err != nil {
t.Fatal(err)
}
if _, err := plugin.Providers(ctx); err != nil {
t.Fatal(err)
}
st, err := provider.StartPluginSignIn("fakeco", 1, map[string]string{"where": "work", "team": "a"})
if err != nil {
t.Fatal(err)
}
if err := provider.SubmitSignInCallback(st.ID, "good"); err != nil {
t.Fatal(err)
}
if _, err := plugin.Providers(ctx); err != nil {
t.Fatal(err)
}
other := &keyed{}
serveOn(t, "other", "ko", []string{"m"}, other)
if err := provider.SaveGroup(provider.Group{Name: "Mixed", Members: []string{"fakeco/fake-1", "other/m"}, Routing: provider.Ordered}); err != nil {
t.Fatal(err)
}
// now no Bun on hand: magpie's own is to be downloaded, from a release
// that never answers
stalled := make(chan struct{})
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
select {
case <-stalled:
case <-r.Context().Done():
}
}))
t.Cleanup(srv.Close)
t.Cleanup(func() { close(stalled) })
t.Cleanup(plugin.BunReleaseForTest(srv.URL, 300*time.Millisecond))
t.Setenv("MAGPIE_BUN", "")
plugin.Restart()
s := New()
ask := func(model string) (int, string) {
t.Helper()
type reply struct {
code int
body string
}
got := make(chan reply, 1)
go func() {
rec := httptest.NewRecorder()
req := httptest.NewRequest("POST", "/v1/chat/completions", strings.NewReader(`{"model":"`+model+`","messages":[{"role":"user","content":"hello"}]}`))
s.Handler().ServeHTTP(rec, req)
got <- reply{rec.Code, rec.Body.String()}
}()
select {
case r := <-got:
return r.code, r.body
case <-time.After(20 * time.Second):
close(stalled)
stalled = make(chan struct{})
t.Fatalf("%s still unanswered after 20s while Bun downloads", model)
return 0, ""
}
}
if code, body := ask("group/mixed"); code != 200 || !strings.Contains(body, "from ko") {
t.Fatalf("the group with its plugin member's Bun not ready: %d %s", code, body)
}
if code, body := ask("fakeco/fake-1"); code < 500 || !strings.Contains(body, "Bun runtime not ready") {
t.Fatalf("the plugin's model with its Bun not ready: %d %s", code, body)
}
}