From ef6d5ca4002f878a79d32cdf7ac97492812a946f Mon Sep 17 00:00:00 2001 From: yetone Date: Fri, 16 Oct 2026 18:15:50 +0800 Subject: [PATCH] provider: a model's listed APIs, Cline/Kilo free mark and remote price are looked up, not the whole list copied for each, so 2,500 models' /v1/models is 0.8s again (K.Liu on Discord) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit K.Liu: /v1/models with 2,000+ models took 2.8s on 127.0.0.1, where it took 1.6s before, so third-party apps couldn't show the whole list. Cause: 644ad1ed7 (#2094, first in v0.1.1234) has Exposed() ask NoAPIFor of every listed model, and NoAPIFor asks ListedAPIs, which read the saved list through p.live(): catalog.Live copies the list's chat models (Chat) and ListedAPIs scans that copy, once a model. A request that doesn't hold the catalog (/v1/models doesn't) did it 2,500 x 2,500 times, and /v1/models' nativeEndpoints did it again for each row. Bisected with one sandbox HOME (one key provider, 2,500 listed models, all picked), server CPU for 4 requests: v0.1.1207 7.6s, v0.1.1222 8.3s, v0.1.1230 9.0s, v0.1.1232 9.2s, v0.1.1234 18.0s, v0.1.1237 18.0s, main 18.8s. What changed: - catalog: readLive indexes the chat models by id once a parse (filememo keeps it while the file is unchanged); LiveByID gives a model's entries in list order. - provider: ListedAPIs, clineFreeModel, kiloFreeModel and remotePrice, each asked once a model, look the model up through p.liveByID (same p.lists() gate as p.live()) instead of scanning a fresh copy. Same first-match rules as before. Measured, same sandbox HOME, 127.0.0.1, machine at load 40-90: origin/main 4.7-5.9s a request, 18.8-19.6s server CPU for 4; with this 0.6-1.0s, 2.6-3.0s CPU for 4. The /v1/models body, sorted, is byte for byte the same as origin/main's (2,500 models, 2,487 with native_endpoints). Test: TestListedAPIsCostGrowsWithTheList weighs Exposed() for 500 and 2,000 listed models by bytes allocated (not time). On origin/main it fails "allocated 92034888 bytes for 500 models and 1416709568 for 2000: 15.4 times for 4 times the models"; with this it passes (-count=3). Run: gofmt -l clean; go vet -tags nogui for darwin, linux and windows clean. Max's report on Discord ("0.1.1265 所有供应商的额度似乎都无法刷新了") was not reproduced: on v0.1.1265 in a sandbox, key balances and plan cards refresh from the GUI's refresh, /api/usage/quotas and the background loop. The one link found: with Gemini or Antigravity quotas, exposedIDs runs Exposed() for every provider, the same per-model scan this removes, inside /api/usage/quotas' 12s budget. Unconfirmed as their cause; asked them for details. Full suite: set -o pipefail; go test -timeout 45m ./... at 8b84dc902 + this (sandbox HOME, load average 130-320 from other sessions): 63 packages ok; gui red only in TestPanelJoinsFullScreenSpaces (#2450, fixed on main since in 63be47717); agent and gateway timed out at 45m with no failed test. Rerun agent+gateway at -timeout 90m: agent ok (3913.8s); gateway red in TestPluginStreamLargeReplies JSON_fast / JSON_throttled (client timeout, filed #2551) and TestMaxRPMTooLongIs429WithRetryAfter (Retry-After 1 for 2, #1791). An earlier 60m rerun had agent red with the failing test cut from the log and TestDesktopSubagentEffortScope red at 30.77s (passes alone, 12.9s). Both gateway reds pass rerun alone at load ~240 (ok 52.5s). After rebasing onto e733b0722: go vet -tags nogui ./... for darwin, linux and windows clean; internal/catalog and internal/provider ok. --- internal/catalog/live.go | 26 +++++++++- internal/provider/account.go | 8 ++-- internal/provider/cline.go | 8 +--- internal/provider/kilo.go | 8 +--- internal/provider/listed_apis_cost_test.go | 56 ++++++++++++++++++++++ internal/provider/models.go | 9 ++++ internal/provider/remote_magpie.go | 8 +--- 7 files changed, 99 insertions(+), 24 deletions(-) create mode 100644 internal/provider/listed_apis_cost_test.go diff --git a/internal/catalog/live.go b/internal/catalog/live.go index fd6160966..cc8671cb8 100644 --- a/internal/catalog/live.go +++ b/internal/catalog/live.go @@ -38,16 +38,38 @@ type liveFile struct { // merged into Models. A base that can't be asked keeps its own part // from the list saved before (#904). Sides map[string][]Model `json:"sides,omitempty"` + // byID is the chat models by their id, in the list's order, made + // once a read: asked for every model of a list, a copy and a scan of + // the list each time cost 2,500 models' /v1/models seconds (K.Liu on + // Discord) + byID map[string][]Model } func readLive(provider string) (liveFile, error) { return filememo.Read("live models", LivePath(provider), func(b []byte) (liveFile, error) { var f liveFile - err := json.Unmarshal(b, &f) - return f, err + if err := json.Unmarshal(b, &f); err != nil { + return f, err + } + f.byID = map[string][]Model{} + for _, m := range Chat(f.Models) { + f.byID[m.ID] = append(f.byID[m.ID], m) + } + return f, nil }) } +// LiveByID are the models of Live with this id, in the list's order +// (a list may name one twice): what a look through Live finds, without +// the list copied for each model asked about. +func LiveByID(provider, model string) []Model { + f, err := readLive(provider) + if err != nil { + return nil + } + return slices.Clone(f.byID[model]) +} + // Live returns the model list last fetched from the provider, if any: the // models to talk to, without the ones that draw (LiveDrawers). func Live(provider string) (models []Model, fetched time.Time, ok bool) { diff --git a/internal/provider/account.go b/internal/provider/account.go index 486769d41..97ab2c378 100644 --- a/internal/provider/account.go +++ b/internal/provider/account.go @@ -136,10 +136,10 @@ func (p Provider) ListedAPIs(model string) []Protocol { if p.IsPlugin() { return p.pluginAPIs(model) } - // asked for every model of every agent: read once while a request holds - ms, _, _ := p.live() - for _, m := range ms { - if m.ID == model && len(m.APIs) > 0 { + // asked for every model of every agent: looked up, not the list + // copied and scanned for each (2,500 models' /v1/models took 3s) + for _, m := range p.liveByID(model) { + if len(m.APIs) > 0 { out := make([]Protocol, len(m.APIs)) for i, a := range m.APIs { out[i] = Protocol(a) diff --git a/internal/provider/cline.go b/internal/provider/cline.go index 585aa1620..bd72719da 100644 --- a/internal/provider/cline.go +++ b/internal/provider/cline.go @@ -160,12 +160,8 @@ func (p Provider) clineFreeModel(model string) bool { if strings.HasPrefix(model, clineFreePrefix) { return true } - if ms, _, ok := p.live(); ok { - for _, m := range ms { - if m.ID == model { - return m.Free - } - } + if ms := p.liveByID(model); len(ms) > 0 { + return ms[0].Free } return isClineFree(model) } diff --git a/internal/provider/kilo.go b/internal/provider/kilo.go index 209030d69..d9b3e2918 100644 --- a/internal/provider/kilo.go +++ b/internal/provider/kilo.go @@ -192,12 +192,8 @@ func (p Provider) kiloFreeModel(model string) bool { if !p.IsKilo() { return false } - if ms, _, ok := p.live(); ok { - for _, m := range ms { - if m.ID == model { - return m.Free - } - } + if ms := p.liveByID(model); len(ms) > 0 { + return ms[0].Free } return isKiloFree(model) } diff --git a/internal/provider/listed_apis_cost_test.go b/internal/provider/listed_apis_cost_test.go new file mode 100644 index 000000000..22dfed44f --- /dev/null +++ b/internal/provider/listed_apis_cost_test.go @@ -0,0 +1,56 @@ +package provider + +import ( + "fmt" + "os" + "runtime" + "testing" + "time" + + "github.com/yetone/magpie/internal/catalog" +) + +// A provider's model list is weighed model by model (Exposed's NoAPIFor +// since 644ad1ed7, /v1/models' native endpoints), and each look at a +// model's APIs copied and scanned the whole saved list: 2,500 models' +// /v1/models took 3.4s from v0.1.1234, where v0.1.1232 took 1.2s (K.Liu +// on Discord). Four times the models is four times the work, not +// sixteen. +func TestListedAPIsCostGrowsWithTheList(t *testing.T) { + oneHome(t) + cost := func(n int) uint64 { + id := fmt.Sprintf("many-%d", n) + if err := Save(Provider{ID: id, Name: id, Key: "sk-x", Chat: "http://127.0.0.1:1/v1"}); err != nil { + t.Fatal(err) + } + ms := make([]catalog.Model, n) + for i := range ms { + ms[i] = catalog.Model{ID: fmt.Sprintf("model-%04d", i), Name: fmt.Sprintf("Model %d", i), APIs: []string{"chat"}} + } + if err := catalog.SaveLive(id, "http://127.0.0.1:1/v1", ms); err != nil { + t.Fatal(err) + } + // saved a while ago, as a list is when an app asks for it, not + // read again in full for its first seconds + old := time.Now().Add(-time.Minute) + if err := os.Chtimes(catalog.LivePath(id), old, old); err != nil { + t.Fatal(err) + } + p, err := Find(id) + if err != nil { + t.Fatal(err) + } + if got := len(p.Exposed()); got != manyModels { + t.Fatalf("%d models: exposed %d, want %d", n, got, manyModels) + } + var a, b runtime.MemStats + runtime.ReadMemStats(&a) + p.Exposed() + runtime.ReadMemStats(&b) + return b.TotalAlloc - a.TotalAlloc + } + small, large := cost(500), cost(2000) + if large > 8*small { + t.Fatalf("Exposed allocated %d bytes for 500 models and %d for 2000: %.1f times for 4 times the models", small, large, float64(large)/float64(small)) + } +} diff --git a/internal/provider/models.go b/internal/provider/models.go index 527bb8dba..943f42cb5 100644 --- a/internal/provider/models.go +++ b/internal/provider/models.go @@ -155,6 +155,15 @@ func (p Provider) live() ([]catalog.Model, time.Time, bool) { return l.ms, l.at, l.ok } +// liveByID are the models of live with this id: what a look at one +// model, asked for each of a list's, reads instead of the whole list. +func (p Provider) liveByID(model string) []catalog.Model { + if !p.lists() { + return nil + } + return catalog.LiveByID(p.ID, model) +} + // lists says whether the provider's fetched list is its own to read: not // a plugin's, nor a preset's that lists nothing (Preset.NoList). func (p Provider) lists() bool { diff --git a/internal/provider/remote_magpie.go b/internal/provider/remote_magpie.go index 7b067cbee..ac77787b9 100644 --- a/internal/provider/remote_magpie.go +++ b/internal/provider/remote_magpie.go @@ -151,12 +151,8 @@ func (p Provider) remotePrice(model string) (catalog.Price, bool) { if !p.IsRemoteMagpie() { return catalog.Price{}, false } - ms, _, ok := p.live() - if !ok { - return catalog.Price{}, false - } - for _, m := range ms { - if m.ID == model && m.Price != nil { + for _, m := range p.liveByID(model) { + if m.Price != nil { return *m.Price, true } }