Files
magpie/internal/access/models.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

106 lines
2.8 KiB
Go

package access
import (
"errors"
"regexp"
"slices"
"strings"
"sync"
)
// CleanModels is a key's model list as kept (#882): each pattern trimmed,
// empty and repeated ones dropped. A pattern names a provider and a model,
// "<provider>/<model>", every model of one, "<provider>/*", or a routing
// group, "group/<name>".
func CleanModels(in []string) ([]string, error) {
var out []string
for _, m := range in {
m = strings.TrimSpace(m)
if m == "" || slices.ContainsFunc(out, func(o string) bool { return strings.EqualFold(o, m) }) {
continue
}
if !strings.Contains(m, "/") || strings.HasPrefix(m, "/") || strings.HasSuffix(m, "/") {
return nil, errors.New("A key's model is <provider>/<model> or <provider>/*, like openai/gpt-5 or anthropic/*: " + m)
}
if len(m) > 300 {
return nil, errors.New("A key's model is at most 300 characters")
}
out = append(out, m)
}
if len(out) > 500 {
return nil, errors.New("A key can list at most 500 models")
}
return out, nil
}
// Restricted says the key may use only the models or accounts it lists.
func (who Identity) Restricted() bool { return len(who.Models) > 0 || len(who.Accounts) > 0 }
// Allows says one of ids is among the key's models; any, for a key that
// lists none. The accounts a key may be held to say nothing of its
// models: they hold the candidates of a plan, not its models.
func (who Identity) Allows(ids ...string) bool {
if len(who.Models) == 0 {
return true
}
for _, id := range ids {
if id != "" && ModelAllowed(who.Models, id) {
return true
}
}
return false
}
// ModelAllowed says id ("<provider>/<model>") matches one of patterns,
// letter case aside; a "*" in a pattern stands for any run of characters,
// slashes too. No patterns allow every model.
func ModelAllowed(patterns []string, id string) bool {
if len(patterns) == 0 {
return true
}
for _, p := range patterns {
if strings.EqualFold(p, id) {
return true
}
if strings.Contains(p, "*") && globRe(p).MatchString(id) {
return true
}
}
return false
}
// globs keeps each pattern's expression compiled, as a model list asks
// for every model of it (#1762): a pattern is its expression whatever key
// holds it, so none is ever stale. It is let go of whole past maxGlobs.
var globs struct {
sync.Mutex
m map[string]*regexp.Regexp
}
const maxGlobs = 4096
func globRe(p string) *regexp.Regexp {
globs.Lock()
re, ok := globs.m[p]
globs.Unlock()
if ok {
return re
}
re = compileGlob(p)
globs.Lock()
if globs.m == nil || len(globs.m) >= maxGlobs {
globs.m = map[string]*regexp.Regexp{}
}
globs.m[p] = re
globs.Unlock()
return re
}
func compileGlob(p string) *regexp.Regexp {
parts := strings.Split(p, "*")
for i, s := range parts {
parts[i] = regexp.QuoteMeta(s)
}
return regexp.MustCompile("(?is)^" + strings.Join(parts, ".*") + "$")
}