Files
magpie/internal/gateway/small_kept_test.go
T
yetone 243aa709b2 gateway: AutoVision and the searcher's pick keep each provider's ranked models until a list, a provider or a setting changes
Why: a live heap profile of the app (yg6888 on X, ~1 GB held) had
36 GB allocated, and 5.3 GB of it was under seer -> autoVision ->
smallModelWhere. 4.8 GB of that came through agent.magpieModels
(provider.Described, asked for every agent's model list: dsh every 30s,
and the window's state). Each AutoVision did three things for every
provider that was on:
- built its Exposed list twice: once in smallReady, then again only to
  read the picked model's price;
- asked spentModel (perKeyBarred, 1.4 GB) about every candidate model,
  before picking one;
- copied the list three times in pickSmall.
The searcher's pick (searcherReady, Searchers, chosenSearcher) goes
through the same smallReady. For a Remote magpie it asked
p.Available() once per model (remoteSearch).

What changed:
- rankSmall puts the candidates in pickSmall's order once. pickSmall of
  any subset is the first of that subset in this order, and
  TestRankSmallIsPickSmall checks that against the old pickSmall over
  2000 random lists and subsets. smallReadyOf then asks spentModel in
  rank order and stops at the first model with allowance. The model it
  picks, and whether it is ready, are the same as before. Usually only
  one model is asked.
- The candidate carries its cost, so smallModelWhere no longer builds
  Exposed a second time.
- keptSmallCands keeps each provider's ranked candidates in
  stamped[smallKey, []smallCand]. The key is the provider id, the
  signed-in account (agent, user, plan, home) and which filter ("sees",
  "search"). Entries are dropped when provider.StampNow moves, or
  after stampedFor (1 minute).
- provider.StampNow (hold.go, added with dsh's round) is made of:
  - held.gen, which Changed moves: a provider saved, an account,
    catalog.SaveLive/Touched/Reset, a plugin's change;
  - filememo.Gen (settings.Save and every other write this process
    makes);
  - environSum;
  - the time and size of the providers' file, the settings file and the
    catalog's cache file, so a write by another magpie (the CLI) counts
    too.
  The one-minute backstop covers what nothing signals: a list another
  magpie fetched, or another program changing an existing account's
  model list. A new account is a new key, so it is seen at once (within
  provider.Accounts' own 30s).
- Whether a model is out of its allowance (spentModel) is still asked
  on every call, never kept. Two callers building one key at the same
  time each build it. Nothing waits on another, and nothing is built
  under the lock.

Measured on the real path: a sandbox HOME with the live
~/.cache/magpie/models.json (5.8 MB, 231 providers) copied in, 12 API
key providers (openrouter, anthropic, openai, google, deepseek,
nano-gpt, vercel, kilo, requesty, aihubmix, zenmux, poe), and the
catalog.Provider fix 4f044c24c applied to both sides. The benchmark is
go test -bench, -benchtime 2s, not committed. The pick is
requesty/mimo-v2.6-flash before and after.

| Benchmark | Before | After |
| --- | --- | --- |
| AutoVision | 769.7 ms, 22,075,218 B, 73,732 allocs/op | 7.3 ms, 238,201 B, 1,134 allocs/op |
| AutoVision under provider.Hold | 347.8 ms, 21,532,432 B, 69,061 allocs/op | 2.1 ms, 85,207 B, 244 allocs/op |

What is left is mostly provider.All, which reads the accounts.

Tests:
- TestAutoVisionDoesNotBuildListsAgain: AllocsPerRun of AutoVision and
  searcherModel with 4 and with 400 listed models. It allows 50
  allocations of difference: 521 against 527.
  - Broken by hand (stamped.get always builds), it went red at 611
    against 1055.
- TestAutoVisionSeesEachChange checks that each change is picked up:
  - picks changed through provider.Save;
  - a vendor's list re-fetched with new prices (catalog.SaveLive);
  - providers.json rewritten directly, as another magpie would;
  - settings.Save moving the stamp;
  - a Codex sign-in written into the same HOME.
  Broken by hand (the stamp ignored, only the minute kept), it went red
  at "AutoVision = "" after Haiku and Gemini were enabled". Run with the
  other AutoVision tests, TestAutoVisionPassesOverOneOut went red too.
- TestAutoVisionKeptListsAskAllowanceEachTime checks that a used-up
  Codex account is seen on the very next call.

Run:
- gofmt -l internal/: clean.
- GOOS=linux and GOOS=windows go vet -tags nogui ./...: clean.
- set -o pipefail; go test -count=1 -timeout 45m ./internal/gateway/
  ./internal/provider/ ./internal/catalog/ ./internal/gui/, at load
  ~400 (other sessions' suites), with 4f044c24c applied:
  - gateway ok 2259.7s, provider ok 821.8s, catalog ok 16.5s.
  - gui FAIL in two tests that fail the same way without this change.
    Each was run alone, with these files reverted, on 28bcd4f7e:
    - TestMainWindowCorners: the real AppKit window was killed at its
      40s deadline, alone too (#1936, #2645).
    - TestSetAnswersWhileDevinAndProvidersHang: setting slow/slow-1
      took 10.9s against its 10s bound. Alone it took 3.3 to 5.4s with
      this change and 4.6 to 5.9s without it, passing 3 of 3 (#1375).
- The new tests were run again after the split into two commits:
  go test -run 'TestInfoCounts|TestAutoVision|TestRankSmall|Searcher'
  ./internal/gateway/: ok.
2026-10-20 20:32:05 +08:00

248 lines
8.6 KiB
Go

package gateway
import (
"cmp"
"encoding/base64"
"fmt"
"math/rand/v2"
"os"
"path/filepath"
"slices"
"strings"
"testing"
"time"
"github.com/yetone/magpie/internal/catalog"
"github.com/yetone/magpie/internal/provider"
"github.com/yetone/magpie/internal/settings"
)
// manyEyes is a key of a router listing n models that see, the cheapest a
// small model of a big vendor; all of them enabled, or three. (All reads
// the providers' file each time, which is as long as what is enabled.)
func manyEyes(t *testing.T, n int, all bool) {
t.Helper()
fresh(t)
var ms []catalog.Model
var every []string
for i := range n {
id := fmt.Sprintf("vendor%d/model-%d", i, i)
if i == n-1 {
id = "google/gemini-3-flash"
}
ms = append(ms, catalog.Model{ID: id, Images: true, ImageInput: imageInputBool(true), Price: &catalog.Price{Input: float64(n - i), Output: 1}})
every = append(every, id)
}
ids := []string{ms[0].ID, ms[1].ID, "google/gemini-3-flash"}
if all {
ids = every
}
if err := provider.Save(provider.Provider{ID: "eyes", Name: "Eyes", Chat: "http://eyes.invalid/v1", Key: "k", Models: ids}); err != nil {
t.Fatal(err)
}
if err := catalog.SaveLive("eyes", "http://eyes.invalid/v1", ms); err != nil {
t.Fatal(err)
}
}
// AutoVision is asked for every agent's list of models (provider.Described,
// dsh's every 30s, the window's state), and built every provider's list
// again each time, twice, then asked whether each of its models was out of
// its allowance: 5.3 GB of a day's 36 GB of allocations. Asked again with
// nothing changed, it costs the same whatever the lists' length.
func TestAutoVisionDoesNotBuildListsAgain(t *testing.T) {
allocs := func(n int) float64 {
manyEyes(t, n, false)
if got := AutoVision(); got != "eyes/google/gemini-3-flash" {
t.Fatalf("AutoVision = %q of %d", got, n)
}
return testing.AllocsPerRun(20, func() { AutoVision() })
}
few, many := allocs(4), allocs(400)
t.Logf("allocations an AutoVision: %.0f with 4 models, %.0f with 400", few, many)
if many > few+50 {
t.Fatalf("AutoVision made %.0f allocations with 400 models, %.0f with 4: the lists are built again", many, few)
}
// and the searcher's pick, built the same way
p, err := provider.Find("eyes")
if err != nil {
t.Fatal(err)
}
searcherModel(*p)
if a := testing.AllocsPerRun(20, func() { searcherModel(*p) }); a > 50 {
t.Fatalf("searcherModel made %.0f allocations with 400 models", a)
}
}
// What AutoVision keeps is built again when what it was built of changes:
// a provider saved (its picks), a vendor's list fetched, an account signed
// in, the settings and the providers' file written by another magpie.
func TestAutoVisionSeesEachChange(t *testing.T) {
routerUp(t, "text")
if m := AutoVision(); m != "" {
t.Fatalf("AutoVision = %q with no model that sees enabled", m)
}
// a provider saved: Haiku enabled
p, err := provider.Find("router")
if err != nil {
t.Fatal(err)
}
p.Models = []string{"text", "anthropic/claude-haiku-5.5", "google/gemini-3-flash"}
if err := provider.Save(*p); err != nil {
t.Fatal(err)
}
if m := AutoVision(); m != "router/google/gemini-3-flash" {
t.Fatalf("AutoVision = %q after Haiku and Gemini were enabled", m)
}
// the vendor's list fetched anew: Haiku the cheaper now
if err := catalog.SaveLive("router", p.Chat, []catalog.Model{
{ID: "text", ImageInput: imageInputBool(false), Price: &catalog.Price{Input: 0.1, Output: 0.1}},
{ID: "anthropic/claude-haiku-5.5", Images: true, ImageInput: imageInputBool(true), Price: &catalog.Price{Input: 0.1, Output: 0.2}},
{ID: "google/gemini-3-flash", Images: true, ImageInput: imageInputBool(true), Price: &catalog.Price{Input: 0.3, Output: 2.5}},
}); err != nil {
t.Fatal(err)
}
if m := AutoVision(); m != "router/anthropic/claude-haiku-5.5" {
t.Fatalf("AutoVision = %q after the list priced Haiku the cheaper", m)
}
// the providers' file written by another magpie (magpie provider
// edit in a terminal): Haiku taken out
b, err := os.ReadFile(provider.Path())
if err != nil {
t.Fatal(err)
}
other := strings.Replace(string(b), `"anthropic/claude-haiku-5.5",`, "", 1)
if other == string(b) {
t.Fatalf("no Haiku pick in %s", b)
}
if err := os.WriteFile(provider.Path(), []byte(other), 0o600); err != nil {
t.Fatal(err)
}
if m := AutoVision(); m != "router/google/gemini-3-flash" {
t.Fatalf("AutoVision = %q after another magpie took Haiku out", m)
}
// a setting saved moves what it is kept by
before := provider.StampNow()
st := settings.Load()
st.Searcher = "off"
if err := settings.Save(st); err != nil {
t.Fatal(err)
}
if provider.StampNow() == before {
t.Fatal("a setting saved left the stamp where it was")
}
// an account signed in, in this same home: Codex's tier goes first
if err := catalog.SaveLive("codex", provider.CodexBase, []catalog.Model{{ID: "gpt-6.1-sol", Images: true, ImageInput: imageInputBool(true)}}); err != nil {
t.Fatal(err)
}
home, _ := os.UserHomeDir()
os.MkdirAll(filepath.Join(home, ".codex"), 0o755)
claims := func(m map[string]any) string {
return "h." + base64.RawURLEncoding.EncodeToString(mustJSON(m)) + ".s"
}
auth := map[string]any{"auth_mode": "chatgpt", "tokens": map[string]any{
"id_token": claims(map[string]any{"email": "me@example.com"}),
"access_token": claims(map[string]any{"exp": time.Now().Add(time.Hour).Unix(), "who": "acct-1"}),
"refresh_token": "r-acct-1", "account_id": "acct-1"}}
if err := os.WriteFile(filepath.Join(home, ".codex", "auth.json"), mustJSON(auth), 0o600); err != nil {
t.Fatal(err)
}
provider.ForgetAccounts() // the 30s accounts are looked for again in
t.Cleanup(provider.ForgetAccounts)
if m := AutoVision(); m != "codex/gpt-6.1-sol" {
t.Fatalf("AutoVision = %q after Codex was signed in", m)
}
}
// A model out of its allowance is passed over as soon as it is, though
// the lists are kept: what is out is asked each time.
func TestAutoVisionKeptListsAskAllowanceEachTime(t *testing.T) {
codexSignedIn(t)
used := map[string]float64{"me@example.com": 20}
capUsage(t, used)
if err := catalog.SaveLive("codex", provider.CodexBase, []catalog.Model{{ID: "gpt-6.1-sol", Images: true, ImageInput: imageInputBool(true)}}); err != nil {
t.Fatal(err)
}
if got, ready := autoVision(); got != "codex/gpt-6.1-sol" || !ready {
t.Fatalf("autoVision = %q %v", got, ready)
}
used["me@example.com"] = 100
if got, ready := autoVision(); got != "codex/gpt-6.1-sol" || ready {
t.Fatalf("autoVision = %q %v with the only account used up", got, ready)
}
}
// rankSmall's order is pickSmall's pick of every subset, as pickSmall
// was before the ranking: the first of a subset is its pick.
func TestRankSmallIsPickSmall(t *testing.T) {
pickSmall := func(ms []catalog.Model) string {
if big := slices.DeleteFunc(slices.Clone(ms), func(m catalog.Model) bool {
v, _, ok := strings.Cut(m.ID, "/")
return ok && !slices.Contains([]string{"anthropic", "openai", "google", "x-ai"}, v)
}); len(big) > 0 {
ms = big
}
cost := func(m catalog.Model) float64 {
if m.Price == nil {
return 1e9
}
return m.Price.Input + m.Price.Output
}
cheapest := func(ms []catalog.Model) string {
if len(ms) == 0 {
return ""
}
return slices.MinFunc(ms, func(a, b catalog.Model) int { return cmp.Compare(cost(a), cost(b)) }).ID
}
small := slices.DeleteFunc(slices.Clone(ms), func(m catalog.Model) bool {
l := strings.ReplaceAll(strings.ToLower(m.ID), "gemini", "")
return !strings.Contains(l, "haiku") && !strings.Contains(l, "mini") && !strings.Contains(l, "flash")
})
if id := cheapest(small); id != "" {
return id
}
return cheapest(ms)
}
r := rand.New(rand.NewPCG(1, 2))
vendors := []string{"", "anthropic/", "openai/", "google/", "x-ai/", "meta/", "qwen/"}
names := []string{"claude-haiku-5", "gpt-6-mini", "gemini-3-flash", "gemini-3-pro", "big", "o9", "llama"}
for range 2000 {
var ms []catalog.Model
for i := range r.IntN(8) + 1 {
m := catalog.Model{ID: fmt.Sprintf("%s%s-%d", vendors[r.IntN(len(vendors))], names[r.IntN(len(names))], i)}
if r.IntN(4) > 0 {
m.Price = &catalog.Price{Input: float64(r.IntN(3)), Output: float64(r.IntN(3))}
}
ms = append(ms, m)
}
cs := rankSmall(ms)
if cs[0].id != pickSmall(ms) {
t.Fatalf("rankSmall's first %q, pickSmall %q of %v", cs[0].id, pickSmall(ms), ms)
}
// a subset: those not spent
keep := map[string]bool{}
var sub []catalog.Model
for _, m := range ms {
if r.IntN(2) == 0 {
keep[m.ID] = true
sub = append(sub, m)
}
}
first := ""
for _, c := range cs {
if keep[c.id] {
first = c.id
break
}
}
if first != pickSmall(sub) {
t.Fatalf("rankSmall's first of a subset %q, pickSmall %q of %v", first, pickSmall(sub), sub)
}
}
}