Files
magpie/internal/access/models_test.go
T
yetone 5e7efce3bc gateway: a key held to some models gets its model list as fast as one held to none, its groups read once a list, not once a group (#1762, LumenXY on X)
LumenXY's /v1/models over Tailscale took 12.4s with a gateway key held to
some models and 1.5s with an unheld one, so apps that list models timed
out and showed an empty list.

Cause (pprof, 1,000 models, 500 found groups): keyAllowed checked each
catalog entry on its own. Each group entry called provider.FindGroup,
which builds a new GroupFinder, so every provider's models were read again
(providerEntries, its files stat'ed and settings loaded) once a group.
That was 96% of the request. Each glob in the key's models was also
compiled to a regexp on every check, and a key held to accounts listed
each provider's accounts (Logins, from disk) once a model.

What changed:
- gateway/key_models.go: keyAllowed weighs a list through a keyList made
  for that request alone. It has one GroupFinder and each provider's
  AccountIDs read once. entryAllowed and accountServes are the same
  checks over them. accountServes(who, p, model) stays for decide.go's
  single check.
- access/models.go: globRe keeps each pattern's compiled expression. A
  pattern compiles to the same expression whatever key holds it, so
  nothing kept goes stale. The map is let go of whole past 4096 patterns.
- gui/groups.go: groupsState (the Routing page) called FindGroup once a
  group too, the same class. It now uses one GroupFinder.
Every route that lists models goes through keyAllowed: /v1/models,
/v1/models/{id}, /v1beta/models, /v1/codex/models, Muse's list and the
deciders. The single-model checks (serve, count_tokens, embeddings,
System One, draw, video) ask one group and are unchanged. Nothing is kept
past a request, so a change to a key's models or accounts, a group's
members or an account's own models shows on the next request. No key
limit is loosened. The documented behaviour is unchanged, so no subsystem
page changes.

Tests:
- TestKeyListShowsWhatItDid compares keyAllowed with the old per-entry
  check, kept in the test, for 14 keys over a catalog with found groups,
  named and nested groups, a no-key provider and an account's own models.
  The keys cover exact ids in any case, globs, group/<id>, group/*, a
  group inside one named, accounts, and models with accounts.
- TestKeyListSeesChangesNextRequest goes through /v1/models and
  /v1beta/models on one server while the key's models, the group's members,
  the key's accounts and an account's models change.
- TestModelPatternsKeptCompiled checks each pattern keeps its own
  expression and that past the cap works.
- Broken by hand, each went red: the accounts memo shared across providers
  (ShowsWhatItDid), the GroupFinder kept across requests
  (SeesChangesNextRequest), and the glob cache keyed by the pattern's first
  letter (KeptCompiled).

Numbers, BenchmarkHeldKeyListsModels (2 providers x 500 models, 500 found
groups, M4 Pro):
- held to models: 2.36s before, 55ms after
- held to accounts: 2.35s before, 60ms after
- held to none: 43ms either way

Real use: sandbox magpie on 127.0.0.1:3486 with its own HOME, the same
1,500-entry catalog, a key held to 5 patterns, and curl 3x each:
- held key, /v1/models and /v1beta/models: 27.8-28.7s before, 0.18s after
- unheld key: 0.12s either way
- The held list (212 entries) and the unheld one (1500) were
  byte-identical between the old and new builds.
- Changing the key's models while the server ran showed on the next
  request (10 entries, then 212 again).

Run at origin/main 8f2a314cf:
- go test ./...: every package ok (49), no FAIL
- go test -race -count=3 on the access tests and -count=2 on TestKeyList*,
  TestGatewayKeyModels* and TestGatewayKeyAccounts*
- gofmt -l and go vet ./... (darwin, GOOS=windows); GOOS=linux go vet
  -tags nogui on access, gateway and gui
2026-10-12 16:53:15 +08:00

119 lines
3.7 KiB
Go

package access
import (
"fmt"
"os"
"slices"
"strings"
"testing"
)
func TestModelPatterns(t *testing.T) {
ps := []string{"openai/gpt-5", "anthropic/*", "relay/*-mini"}
for id, want := range map[string]bool{
"openai/gpt-5": true,
"OpenAI/GPT-5": true,
"openai/gpt-5-mini": false,
"anthropic/claude-x": true,
"anthropic/vendor/x": true,
"anthropics/x": false,
"relay/m-mini": true,
"relay/m": false,
"openrouter/anthropic/x": false,
} {
if got := ModelAllowed(ps, id); got != want {
t.Errorf("%s: %v", id, got)
}
}
if !ModelAllowed(nil, "any/thing") {
t.Fatal("no patterns hold a model")
}
who := Identity{Models: ps}
if !who.Restricted() || who.Allows("relay/m", "") || !who.Allows("relay/m", "openai/gpt-5") || (Identity{}).Restricted() || !(Identity{}).Allows("x/y") {
t.Fatal("Identity.Allows")
}
got, err := CleanModels([]string{" openai/gpt-5 ", "", "OPENAI/GPT-5", "anthropic/*"})
if err != nil || !slices.Equal(got, []string{"openai/gpt-5", "anthropic/*"}) {
t.Fatal(got, err)
}
for _, bad := range []string{"gpt-5", "/gpt-5", "openai/", strings.Repeat("a", 300) + "/b"} {
if _, err := CleanModels([]string{bad}); err == nil {
t.Error("accepted", bad)
}
}
}
// A key's models are kept in caller-keys.json, stay through a rotation and
// a restart, reach the gateway with the key, and an older file without
// them reads as every model (#882).
func TestKeyModelsKept(t *testing.T) {
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
secret, err := Update("add-key", Change{Name: "Phone"})
if err != nil {
t.Fatal(err)
}
keys, _ := List()
id := keys[0].ID
if who, ok := Authenticate(secret); !ok || who.Restricted() {
t.Fatal("a new key is held", who)
}
if _, err := Update("models-key", Change{Key: id, Models: []string{"gpt-5"}}); err == nil {
t.Fatal("accepted a model without its provider")
}
if _, err := Update("models-key", Change{Key: "missing", Models: []string{"a/b"}}); err == nil {
t.Fatal("held a missing key")
}
if _, err := Update("models-key", Change{Key: id, Models: []string{"openai/gpt-5", "anthropic/*"}}); err != nil {
t.Fatal(err)
}
b, _ := os.ReadFile(Path())
if !strings.Contains(string(b), `"models": [`) {
t.Fatal("caller-keys.json", string(b))
}
secret, err = Update("rotate-key", Change{Key: id})
if err != nil {
t.Fatal(err)
}
who, ok := Authenticate(secret)
if !ok || !slices.Equal(who.Models, []string{"openai/gpt-5", "anthropic/*"}) || !who.Allows("anthropic/claude") || who.Allows("openai/gpt-4o") {
t.Fatal("authenticated as", who, ok)
}
if _, err := Update("models-key", Change{Key: id}); err != nil {
t.Fatal(err)
}
if who, _ := Authenticate(secret); who.Restricted() {
t.Fatal("every model kept a list", who)
}
if b, _ := os.ReadFile(Path()); strings.Contains(string(b), `"models"`) {
t.Fatal("an empty list written", string(b))
}
}
// A pattern's expression is compiled once and kept (#1762): each pattern
// keeps its own, asked in turn and again, and past the cap as before.
func TestModelPatternsKeptCompiled(t *testing.T) {
for range 2 {
for _, c := range []struct {
p, id string
want bool
}{
{"plan/a*", "plan/abc", true},
{"plan/b*", "plan/abc", false},
{"plan/b*", "PLAN/B1", true},
{"plan/a*", "plan/b1", false},
{"*/x", "a/b/x", true},
{"*/y", "a/b/x", false},
} {
if got := ModelAllowed([]string{c.p}, c.id); got != c.want {
t.Errorf("%s by %s: %v", c.id, c.p, got)
}
}
}
for i := range maxGlobs + 10 {
p := fmt.Sprintf("p%d/*", i)
if !ModelAllowed([]string{p}, fmt.Sprintf("p%d/m", i)) || ModelAllowed([]string{p}, fmt.Sprintf("q%d/m", i)) {
t.Fatal("past the cap", p)
}
}
}