providers: a provider list looks at the stamps, plugin logins, client shapes and accounts once a request
/api/providers took ~25ms of CPU a call with the owner's real config (25 providers, plugins signed in), polled by every open window. Its profile had file system calls at about half, each repeated for every provider the list shows: - StampNow stat'ed providers.json, settings.json and the catalog for every provider (KeptListing); under a request's Hold it is looked at once. - plugin.ListedAt was asked for every plugin provider's Listed(); once a request (heldOf "plugin-listed"). - pluginLogins took logins.json's lock, a file opened across magpies, for every plugin even with nothing to change. It now settles the list as read first, and takes the lock and settles again from a fresh read only when something changes. - clientShape read and parsed client-shapes.json for every relay a list shows (TestsAs); parsed once until the file changes (filememo), a copy given out. - Logins(agent) took the same lock for every provider, twice with its account models; listed once an agent a request, a copy each, listed anew after a write (writePrivate's filememo.Forget). Run (on mote unless named): - go test ./internal/provider ./internal/gui -timeout 45m: provider ok (102s) with the new tests; gui red on TestMainWindowCorners (macOS 27, #3949) and on TestSettingsSaveKeepsWhatItDoesNotSend, red on main sinceb09349d17, fixed by #4514's commit before this one. - At the pushed head (rebased one84870f17): go test ./internal/provider ok (100.7s), ./internal/plugin ok (102.7s), TestLoginsListedOnceARequest -count=5 ok (it now clears the 30s look another test left), gui TestSettingsSaveKeepsWhatItDoesNotSend and TestCoreScriptBudget ok; GOOS=linux and windows go vet ./internal/provider ok. Then rebased onto3defaf662(internal/agent dsh.go only); not rerun. - New tests: TestStampLooksOnceARequest, TestClientShapeParsedOnceUntilWritten, TestLoginsListedOnceARequest, and TestAccountListsCopyNoLoginsUnchanged now counts the lock. Broken by hand, each goes red: "51 stamps in one request looked 51 times, want 1", "30 asks parsed the file 30 times", "20 plugin lists with nothing to change took the lock 20 times", "20 lists in one request listed 20 times". - GOOS=linux and windows go vet ./internal/provider: ok. gofmt clean. - Real config, on this Mac: a copy of the owner's ~/.config/magpie in an offline sandbox HOME (proxy :9), 200 GET /api/providers each: v0.1.2541 5.04s CPU (25.2ms a call, median 22.5ms wall), this change 4.55s (22.8ms, median 20.3ms). The profile's stats under StampNow fell from 2.17s to 0.34s. Not run: the full ./... suite; GUI (browser) tests, as nothing the page gets changed. What is left in the profile: StepFun's sign-in file, sync.json, plugin icons and agent detection, each read once a request.
This commit is contained in:
@@ -42,3 +42,30 @@ func TestClientShapeWrittenOnceForTwoWindows(t *testing.T) {
|
||||
t.Fatalf("a new Codex version's User-Agent was not kept: %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
// /api/providers asks the shape of every relay it lists: the file is
|
||||
// parsed once until it changes, and what a caller does to its copy is
|
||||
// not what the next one gets.
|
||||
func TestClientShapeParsedOnceUntilWritten(t *testing.T) {
|
||||
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
|
||||
clientShapes.Lock()
|
||||
clientShapes.written = nil
|
||||
clientShapes.Unlock()
|
||||
SawClient(ClientClaudeCode, http.Header{"User-Agent": {"claude-cli/2.1.0 (external, cli)"}})
|
||||
clientShape(ClientClaudeCode)
|
||||
parses := shapeParses.Load()
|
||||
for range 30 {
|
||||
h := clientShape(ClientClaudeCode)
|
||||
if h.Get("User-Agent") != "claude-cli/2.1.0 (external, cli)" {
|
||||
t.Fatalf("shape read back as %v", h)
|
||||
}
|
||||
h.Set("User-Agent", "changed")
|
||||
}
|
||||
if n := shapeParses.Load() - parses; n != 0 {
|
||||
t.Fatalf("30 asks parsed the file %d times, want 0", n)
|
||||
}
|
||||
SawClient(ClientClaudeCode, http.Header{"User-Agent": {"claude-cli/2.2.0 (external, cli)"}})
|
||||
if got := clientShape(ClientClaudeCode).Get("User-Agent"); got != "claude-cli/2.2.0 (external, cli)" {
|
||||
t.Fatalf("after a write: %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -32,6 +32,10 @@ var held struct {
|
||||
fgen uint64
|
||||
// roots is the providers' and the settings' files as last looked at
|
||||
roots [2]rootStamp
|
||||
// stamp is StampNow's files as a request holding the catalog last
|
||||
// looked at them, at stampAt (stampNowFiles)
|
||||
stamp [3]rootStamp
|
||||
stampAt time.Time
|
||||
}
|
||||
|
||||
// rootStamp is a file's time and size, or that it wasn't there.
|
||||
@@ -119,6 +123,8 @@ func Hold() (release func()) {
|
||||
held.built, held.env = nil, env
|
||||
}
|
||||
heldFreshLocked(true)
|
||||
// a request's first StampNow looks at the files again
|
||||
held.stampAt = time.Time{}
|
||||
}
|
||||
held.holds++
|
||||
held.Unlock()
|
||||
@@ -175,8 +181,34 @@ func StampNow() Stamp {
|
||||
held.Lock()
|
||||
gen := held.gen
|
||||
held.Unlock()
|
||||
return Stamp{gen: gen, fgen: filememo.Gen(), env: environSum(),
|
||||
roots: [3]rootStamp{stampOf(Path()), stampOf(settings.Path()), stampOf(catalog.CachePath())}}
|
||||
return Stamp{gen: gen, fgen: filememo.Gen(), env: environSum(), roots: stampNowFiles()}
|
||||
}
|
||||
|
||||
// stampLooks counts StampNow's looks at its files, for a test.
|
||||
var stampLooks atomic.Int64
|
||||
|
||||
// stampNowFiles is the files' part of StampNow: looked at once by a
|
||||
// request holding the catalog and its overlapping ones, for heldFor at
|
||||
// most, as what is held is. KeptListing takes a stamp for every
|
||||
// provider, and its three stats a provider were most of what a
|
||||
// Providers page poll spent (~600 of them a poll with 200 providers).
|
||||
// Another process's write is seen by the next request, as Hold's look
|
||||
// sees it.
|
||||
func stampNowFiles() [3]rootStamp {
|
||||
held.Lock()
|
||||
roots, fresh := held.stamp, held.holds > 0 && !held.stampAt.IsZero() && time.Since(held.stampAt) < heldFor
|
||||
held.Unlock()
|
||||
if fresh {
|
||||
return roots
|
||||
}
|
||||
stampLooks.Add(1)
|
||||
roots = [3]rootStamp{stampOf(Path()), stampOf(settings.Path()), stampOf(catalog.CachePath())}
|
||||
held.Lock()
|
||||
if held.holds > 0 {
|
||||
held.stamp, held.stampAt = roots, time.Now()
|
||||
}
|
||||
held.Unlock()
|
||||
return roots
|
||||
}
|
||||
|
||||
// Held is what build gives, built once while a request holds it (Hold),
|
||||
|
||||
@@ -946,8 +946,19 @@ func (p Provider) SignedOut() bool {
|
||||
}
|
||||
|
||||
// Logins lists the remembered accounts of an agent ("" for every one),
|
||||
// the active one flagged.
|
||||
// the active one flagged. A request lists an agent's once: /api/providers
|
||||
// asks it of every provider, twice with its account models, and each
|
||||
// took logins.json's lock, a file opened across magpies (a seventh of
|
||||
// the list's CPU). The caller gets its own copy.
|
||||
func Logins(agent string) []Login {
|
||||
return slices.Clone(heldOf("logins\x00"+agent, func() []Login { return loginsNow(agent) }))
|
||||
}
|
||||
|
||||
// loginsRuns counts the lists Logins made (a test reads it).
|
||||
var loginsRuns atomic.Int64
|
||||
|
||||
func loginsNow(agent string) []Login {
|
||||
loginsRuns.Add(1)
|
||||
if settings.AccountDiscoveryOff() {
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
package provider
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// TestLoginsListedOnceARequest: /api/providers asks an agent's accounts
|
||||
// of every provider, and each list took logins.json's lock; a request
|
||||
// lists an agent's once, a copy each, and a write in it lists anew.
|
||||
func TestLoginsListedOnceARequest(t *testing.T) {
|
||||
signIn(t)
|
||||
loginsSeenAt.Store(0) // another test's look within 30s would skip this HOME's
|
||||
defer func(d time.Duration) { heldFor = d }(heldFor)
|
||||
heldFor = time.Hour // a loaded machine's pause isn't the bound
|
||||
release := Hold()
|
||||
defer func() { release() }()
|
||||
Logins("codex") // the first list notes the sign-in in logins.json
|
||||
first := Logins("codex")
|
||||
if len(first) != 1 || first[0].User != "me@example.com" {
|
||||
t.Fatalf("codex accounts: %+v", first)
|
||||
}
|
||||
runs := loginsRuns.Load()
|
||||
for range 20 {
|
||||
ls := Logins("codex")
|
||||
if len(ls) != 1 || ls[0].User != "me@example.com" {
|
||||
t.Fatalf("listed again as %+v", ls)
|
||||
}
|
||||
ls[0].User = "changed"
|
||||
}
|
||||
if n := loginsRuns.Load() - runs; n != 0 {
|
||||
t.Fatalf("20 lists in one request listed %d times, want 0", n)
|
||||
}
|
||||
if err := writeLogins(readLogins()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
Logins("codex")
|
||||
if n := loginsRuns.Load() - runs; n != 1 {
|
||||
t.Fatalf("after a write: listed %d times, want 1", n)
|
||||
}
|
||||
release()
|
||||
release = func() {}
|
||||
Logins("codex")
|
||||
Logins("codex")
|
||||
if n := loginsRuns.Load() - runs; n != 3 {
|
||||
t.Fatalf("outside a request: listed %d times, want 3", n)
|
||||
}
|
||||
}
|
||||
@@ -16,7 +16,7 @@ func TestAccountListsCopyNoLoginsUnchanged(t *testing.T) {
|
||||
pp := plugin.Provider{ID: "fakeco", Accounts: []plugin.Account{{Key: "k1", AccountID: "one"}}}
|
||||
sideLogins("google", "a@example.com", all) // its own sign-in: written
|
||||
pluginLogins(pp) // its account: written
|
||||
before := loginsCopied.Load()
|
||||
before, locks := loginsCopied.Load(), pluginLoginLocks.Load()
|
||||
for range 20 {
|
||||
sideLogins("google", "a@example.com", all)
|
||||
if got := pluginLogins(pp); len(got) != 1 || got[0].User != "one" {
|
||||
@@ -26,6 +26,11 @@ func TestAccountListsCopyNoLoginsUnchanged(t *testing.T) {
|
||||
if n := loginsCopied.Load() - before; n != 0 {
|
||||
t.Fatalf("20 lists with nothing to change copied the accounts %d times", n)
|
||||
}
|
||||
// nor took logins.json's lock, a file opened across magpies
|
||||
if n := pluginLoginLocks.Load() - locks; n != 0 {
|
||||
t.Fatalf("20 plugin lists with nothing to change took the lock %d times", n)
|
||||
}
|
||||
locks = pluginLoginLocks.Load()
|
||||
|
||||
pp.Accounts = append(pp.Accounts, plugin.Account{Key: "k2", AccountID: "two"})
|
||||
if got := pluginLogins(pp); len(got) != 2 {
|
||||
@@ -35,6 +40,9 @@ func TestAccountListsCopyNoLoginsUnchanged(t *testing.T) {
|
||||
if got := pluginLogins(pp); len(got) != 1 || got[0].User != "two" {
|
||||
t.Fatalf("a signed-out account is still listed: %+v", got)
|
||||
}
|
||||
if n := pluginLoginLocks.Load() - locks; n != 2 {
|
||||
t.Fatalf("two changes took the lock %d times, want 2", n)
|
||||
}
|
||||
n := 0
|
||||
for _, l := range readLogins() {
|
||||
if l.Agent == "plugin:fakeco" {
|
||||
|
||||
@@ -136,7 +136,13 @@ func (p Provider) Fetched() (time.Time, bool) {
|
||||
// for a built-in, listed by its plugin for a plugin's.
|
||||
func (p Provider) Listed() (time.Time, bool) {
|
||||
if p.IsPlugin() {
|
||||
return plugin.ListedAt()
|
||||
// one look at the plugins' list a request, not one a provider
|
||||
type listed struct {
|
||||
at time.Time
|
||||
ok bool
|
||||
}
|
||||
l := heldOf("plugin-listed", func() listed { at, ok := plugin.ListedAt(); return listed{at, ok} })
|
||||
return l.at, l.ok
|
||||
}
|
||||
return p.Fetched()
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"net/http"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/plugin"
|
||||
@@ -202,6 +203,10 @@ var pluginOwnUser = func(id string) string {
|
||||
return ""
|
||||
}
|
||||
|
||||
// pluginLoginLocks counts the times pluginLogins took loginsMu (a test
|
||||
// reads it).
|
||||
var pluginLoginLocks atomic.Int64
|
||||
|
||||
// pluginLogins are the provider's accounts, the first in use first. What
|
||||
// plugin-auth.json keeps is the truth: logins.json follows it. The agent's
|
||||
// own account is named as the agent is signed in now; removed in magpie,
|
||||
@@ -224,53 +229,61 @@ func pluginLogins(pp plugin.Provider) []pluginLogin {
|
||||
mark = ownMark(pp.ID)
|
||||
}
|
||||
labels := pluginLabels(pp, named)
|
||||
loginsMu.Lock()
|
||||
// looked at as kept, and copied only at the first change: nearly
|
||||
// every list changes nothing, and a page's state lists each plugin's
|
||||
ls := sharedLogins()
|
||||
changed := false
|
||||
have := map[string]bool{}
|
||||
var keep []savedLogin
|
||||
for i, l := range ls {
|
||||
drop, edit := false, false
|
||||
if l.Agent == agent {
|
||||
if _, ok := byKey[l.Home]; !ok || have[l.Home] {
|
||||
drop = true // signed out, or listed twice
|
||||
} else {
|
||||
have[l.Home] = true
|
||||
renamed := l.User != labels[l.Home]
|
||||
if renamed {
|
||||
l.User, edit = labels[l.Home], true
|
||||
}
|
||||
// the agent's own, hidden, shows again once the agent signs
|
||||
// in anew: told by its sign-in's mark, else by another account
|
||||
if l.Hidden != "" && own[l.Home] && (mark != "" && mark != l.Hidden || mark == "" && l.Hidden == hiddenNoMark && renamed) {
|
||||
l.Hidden, edit = "", true
|
||||
settle := func(ls []savedLogin) ([]savedLogin, bool) {
|
||||
changed := false
|
||||
have := map[string]bool{}
|
||||
var keep []savedLogin
|
||||
for i, l := range ls {
|
||||
drop, edit := false, false
|
||||
if l.Agent == agent {
|
||||
if _, ok := byKey[l.Home]; !ok || have[l.Home] {
|
||||
drop = true // signed out, or listed twice
|
||||
} else {
|
||||
have[l.Home] = true
|
||||
renamed := l.User != labels[l.Home]
|
||||
if renamed {
|
||||
l.User, edit = labels[l.Home], true
|
||||
}
|
||||
// the agent's own, hidden, shows again once the agent signs
|
||||
// in anew: told by its sign-in's mark, else by another account
|
||||
if l.Hidden != "" && own[l.Home] && (mark != "" && mark != l.Hidden || mark == "" && l.Hidden == hiddenNoMark && renamed) {
|
||||
l.Hidden, edit = "", true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (drop || edit) && !changed {
|
||||
keep, changed = slices.Clone(ls[:i:i]), true
|
||||
}
|
||||
if changed && !drop {
|
||||
keep = append(keep, l)
|
||||
}
|
||||
}
|
||||
if changed {
|
||||
ls = keep
|
||||
}
|
||||
for _, a := range pp.Accounts {
|
||||
if !have[a.Key] {
|
||||
if !changed {
|
||||
ls, changed = slices.Clone(ls), true
|
||||
if (drop || edit) && !changed {
|
||||
keep, changed = slices.Clone(ls[:i:i]), true
|
||||
}
|
||||
if changed && !drop {
|
||||
keep = append(keep, l)
|
||||
}
|
||||
ls = append(ls, savedLogin{Agent: agent, User: labels[a.Key], Home: a.Key, On: true, Seen: time.Now().UTC().Truncate(time.Second)})
|
||||
}
|
||||
if changed {
|
||||
ls = keep
|
||||
}
|
||||
for _, a := range pp.Accounts {
|
||||
if !have[a.Key] {
|
||||
if !changed {
|
||||
ls, changed = slices.Clone(ls), true
|
||||
}
|
||||
ls = append(ls, savedLogin{Agent: agent, User: labels[a.Key], Home: a.Key, On: true, Seen: time.Now().UTC().Truncate(time.Second)})
|
||||
}
|
||||
}
|
||||
return ls, changed
|
||||
}
|
||||
if changed {
|
||||
_ = writeLogins(ls)
|
||||
// what nothing changes takes no lock: taken, it opens logins.json's
|
||||
// lock file, across magpies, and /api/providers lists every plugin
|
||||
// (a fifth of its CPU). A change is made from a read under it.
|
||||
if _, changed := settle(sharedLogins()); changed {
|
||||
pluginLoginLocks.Add(1)
|
||||
loginsMu.Lock()
|
||||
if ls, changed := settle(sharedLogins()); changed {
|
||||
_ = writeLogins(ls)
|
||||
}
|
||||
loginsMu.Unlock()
|
||||
}
|
||||
loginsMu.Unlock()
|
||||
var out []pluginLogin
|
||||
for _, l := range sideLogins(agent, "", func(l savedLogin) bool { _, ok := byKey[l.Home]; return ok && l.Hidden == "" }) {
|
||||
l.Lapsed = l.saved.Lapsed // a refused sign-in shows on the account
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
package provider
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// TestStampLooksOnceARequest: a request holding the catalog looks at
|
||||
// StampNow's files once, not once for each provider it lists, and the
|
||||
// next request sees a file another process wrote between them.
|
||||
func TestStampLooksOnceARequest(t *testing.T) {
|
||||
isolate(t)
|
||||
home := t.TempDir()
|
||||
t.Setenv("HOME", home)
|
||||
t.Setenv("USERPROFILE", home)
|
||||
t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config"))
|
||||
t.Setenv("XDG_CACHE_HOME", filepath.Join(home, ".cache"))
|
||||
defer func(d time.Duration) { heldFor = d }(heldFor)
|
||||
heldFor = time.Hour // a loaded machine's pause isn't the bound
|
||||
if err := Save(Provider{ID: "relay", Name: "Relay", Key: "k", Chat: "http://127.0.0.1:1/v1", Models: []string{"m1"}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
release := Hold()
|
||||
looks := stampLooks.Load()
|
||||
first := StampNow()
|
||||
for range 50 {
|
||||
if StampNow() != first {
|
||||
t.Fatal("the stamp moved within a request")
|
||||
}
|
||||
}
|
||||
if n := stampLooks.Load() - looks; n != 1 {
|
||||
t.Fatalf("51 stamps in one request looked %d times, want 1", n)
|
||||
}
|
||||
release()
|
||||
|
||||
// another process rewrites the providers' file: a size of its own
|
||||
b, err := os.ReadFile(Path())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(Path(), append(b, '\n', '\n'), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer Hold()()
|
||||
if StampNow() == first {
|
||||
t.Fatal("the next request's stamp missed another process's write")
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,9 @@ import (
|
||||
"slices"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
|
||||
"github.com/yetone/magpie/internal/filememo"
|
||||
)
|
||||
|
||||
// A relay can serve only the agents its plan is sold for, and tell them by
|
||||
@@ -180,12 +183,25 @@ func equalHeaders(a, b http.Header) bool {
|
||||
return a != nil && maps.EqualFunc(map[string][]string(a), map[string][]string(b), slices.Equal[[]string])
|
||||
}
|
||||
|
||||
// shapeParses counts client-shapes.json's parses (a test reads it).
|
||||
var shapeParses atomic.Int64
|
||||
|
||||
// clientShape is the headers last seen from client, nil when it hasn't
|
||||
// come through.
|
||||
// come through. The file is parsed once until it changes: /api/providers
|
||||
// asks it of every relay a list shows, and read anew each time it was a
|
||||
// sixth of the list's CPU. A copy goes out, as a request's headers take
|
||||
// it.
|
||||
func clientShape(client string) http.Header {
|
||||
clientShapes.Lock()
|
||||
defer clientShapes.Unlock()
|
||||
return readClientShapes(clientShapesPath())[client]
|
||||
m, err := filememo.Read("client-shapes", clientShapesPath(), func(b []byte) (map[string]http.Header, error) {
|
||||
shapeParses.Add(1)
|
||||
m := map[string]http.Header{}
|
||||
json.Unmarshal(b, &m)
|
||||
return m, nil
|
||||
})
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
return m[client].Clone()
|
||||
}
|
||||
|
||||
// clientHeaders puts client's headers on a test request: those last seen
|
||||
|
||||
Reference in New Issue
Block a user