provider: a forget, a TUI group edit or a failed group save no longer changes the record or groups every other reader holds (#1124)
* provider: forgetting a moved subscription's account no longer changes the record every other reader holds, so a forget whose write fails can't leave moving back an account with no key
setMigration copied only the outer map of migrations.json as filememo
had parsed it. The record handed to its callback still shared its
Accounts and Backup with that parse, which every MigrationOf reader gets
too. forgetPluginAccounts' callback deletes from both lists in place
(slices.DeleteFunc), which shifts the entries and zeroes the tail of the
shared arrays. putBack and moveBack read those lists without
migrationsMu, so that was a data race. When the write then failed, the
file was unchanged and filememo kept serving the changed parse: the same
length, the forgotten account replaced by the next and a last entry with
no key, which a move back would hand back. setMigration now gives the
callback its own copy of both lists (and of each account's Was).
Other readers of shared parses were checked (migrations, logins, credits,
quota history, settings, catalog and plugin caches): none changes what
it reads. TUI group editing changes heldOf("file")'s groups in place
while a Hold is open; that is a different cache and goes in its own
change.
Tested: TestFailedMigrationWriteLeavesItAsRead fails without the fix
(read as accounts ["zed:b" ""], backup ["b@example.com" ""]) and passes
with it. TestMigrationReadWhileForgotten fails with DATA RACE in 9 of 10
separate -race runs without the fix and passes 20 of 20 with it.
go test -race -tags nogui ./internal/provider, go vet ./..., go build,
GOOS=linux go build -tags nogui and GOOS=windows go build pass.
* provider: a group edit the TUI makes, or a save that fails, no longer changes the groups every other reader holds
While any goroutine holds provider.Hold() (SyncCatalog after every store,
the in-process gateway's /models and model routes), groupsIn hands every
caller the same providers.json, and each Group copied out of it still
shared its Members, Match, Matched, Off, Levels, Fast and Rules (with each
rule's Agents and Time) with that file; withMatches cloned Members only
for a group with patterns. The TUI's saveGroup changes the group it read
in place before saving it (slices.Delete/DeleteFunc/Insert on Rules and
Members, swaps, RenameMember), and SaveGroup itself wrote Rules[i].Use and
appended to Fast in the caller's lists. That raced with SyncCatalog's and
the gateway's group reads, and a save that failed ("every model in X is
switched off") left the held groups shifted with an empty member or rule
at the end for up to a second, where SyncCatalog could write agents'
model files from them.
groupsIn now gives each group lists of its own (Group.own), and SaveGroup
cleans its own copy, so the caller's group is as it gave it, saved or not.
RenameGroup and SetAutoGroups read through groupsIn and are covered too.
The CLI's in-place edits (groups_cli.go, groups_rules_cli.go) run with no
hold and read a fresh file; they are covered all the same.
Found by the sibling sweep for #1124.
Verified: TestHeldGroupsAreTheCallers (internal/provider) and
TestGroupTakeOutRefusedWhileHeld (internal/tui) hold the catalog, take a
model out of a group whose other one is off, as the TUI's d does, and
read the groups again. Without the change both fail: members
[b/big ""] / [b/gpt-5.5 ""] and a zeroed rule in the held groups. With
only SaveGroup's copy removed, the first fails with "SaveGroup changed the
caller's rule". go test -tags nogui -race ./internal/provider
./internal/tui, go test -tags nogui ./..., go vet ./..., go build,
GOOS=linux go build -tags nogui and GOOS=windows go build pass.
This commit is contained in:
@@ -304,7 +304,7 @@ func groupsIn(entries []Entry) []Group {
|
||||
}
|
||||
g = withoutRemoved(g, have)
|
||||
}
|
||||
out = append(out, withMatches(entries, g))
|
||||
out = append(out, withMatches(entries, g.own()))
|
||||
}
|
||||
if f.NoAutoGroups {
|
||||
return orderedGroups(out, f.GroupOrder)
|
||||
@@ -353,6 +353,30 @@ func withoutRemoved(g Group, have map[string]bool) Group {
|
||||
return g
|
||||
}
|
||||
|
||||
// own is the group with lists of its own. f.Groups is the providers.json
|
||||
// every look-up shares while a request holds the catalog (heldOf), so a
|
||||
// caller changing its group in place — the TUI deleting a rule, SaveGroup
|
||||
// cleaning one — would change it for every reader in that while, and keep
|
||||
// the change there when the save failed.
|
||||
func (g Group) own() Group {
|
||||
g.Members = slices.Clone(g.Members)
|
||||
g.Match = slices.Clone(g.Match)
|
||||
g.Matched = slices.Clone(g.Matched)
|
||||
g.Off = slices.Clone(g.Off)
|
||||
g.Levels = slices.Clone(g.Levels)
|
||||
g.Fast = slices.Clone(g.Fast)
|
||||
g.Rules = slices.Clone(g.Rules)
|
||||
for i, r := range g.Rules {
|
||||
g.Rules[i].Agents = slices.Clone(r.Agents)
|
||||
if r.Time != nil {
|
||||
w := *r.Time
|
||||
w.Days = slices.Clone(w.Days)
|
||||
g.Rules[i].Time = &w
|
||||
}
|
||||
}
|
||||
return g
|
||||
}
|
||||
|
||||
// AutoGroupsOn reports whether magpie finds groups on its own: a model
|
||||
// more than one provider serves is a group of them (autoGroups). It is on
|
||||
// until the user turns it off.
|
||||
@@ -885,6 +909,7 @@ func (e Entry) Quiet() bool {
|
||||
// SaveGroup adds or replaces a group of the user's. Changing one magpie
|
||||
// found makes it the user's.
|
||||
func SaveGroup(g Group) error {
|
||||
g = g.own() // cleaned below in place: the caller's lists stay as they were
|
||||
g.ID = strings.ToLower(strings.TrimSpace(g.ID))
|
||||
g.Name = strings.TrimSpace(g.Name)
|
||||
if g.ID == "" {
|
||||
|
||||
@@ -197,3 +197,64 @@ func TestHoldReadsMigrationsOnce(t *testing.T) {
|
||||
t.Fatalf("a move written while held: %v %v", Moved("held-sub"), Moved("other-sub"))
|
||||
}
|
||||
}
|
||||
|
||||
// A group read while a request holds the catalog is the caller's own: the
|
||||
// TUI changes its group in place before saving it, and a save that fails
|
||||
// left that change in every look-up's providers.json for the rest of the
|
||||
// hold (SyncCatalog and the gateway's routes read it meanwhile); a group
|
||||
// handed to SaveGroup isn't cleaned in the caller's lists either.
|
||||
func TestHeldGroupsAreTheCallers(t *testing.T) {
|
||||
t.Setenv("HOME", t.TempDir())
|
||||
t.Setenv("USERPROFILE", t.TempDir())
|
||||
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
|
||||
for _, id := range []string{"a", "b"} {
|
||||
if err := Save(Provider{ID: id, Name: id, Key: "k", Chat: "http://127.0.0.1:1/v1", Models: []string{"m", "big"}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
saved := Group{ID: "pair", Name: "Pair", Members: []string{"a/m", "b/big"}, Off: []string{"b/big"}, Levels: []string{"low", "high"},
|
||||
Rules: []Rule{{Use: "a/m", Tokens: 5}, {Use: "b/big", Agents: []string{"codex"}, Time: &TimeWindow{From: "09:00", To: "18:00", Days: []string{"mon"}}}}}
|
||||
if err := SaveGroup(saved); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer Hold()()
|
||||
pair := func() Group {
|
||||
t.Helper()
|
||||
for _, g := range Groups() {
|
||||
if g.ID == "pair" {
|
||||
return g
|
||||
}
|
||||
}
|
||||
t.Fatal("no group pair")
|
||||
return Group{}
|
||||
}
|
||||
same := func(why string) {
|
||||
t.Helper()
|
||||
g := pair()
|
||||
if !slices.Equal(g.Members, saved.Members) || !slices.Equal(g.Off, saved.Off) || !slices.Equal(g.Levels, saved.Levels) ||
|
||||
len(g.Rules) != 2 || g.Rules[0].Use != "a/m" || g.Rules[1].Use != "b/big" ||
|
||||
!slices.Equal(g.Rules[1].Agents, []string{"codex"}) || g.Rules[1].Time == nil || !slices.Equal(g.Rules[1].Time.Days, []string{"mon"}) {
|
||||
t.Fatalf("%s: %+v", why, g)
|
||||
}
|
||||
}
|
||||
// taking a/m out, as the TUI's d does: b/big alone is off, so it fails
|
||||
g := pair()
|
||||
g.Members = slices.DeleteFunc(g.Members, func(m string) bool { return m == "a/m" })
|
||||
g.Rules = slices.DeleteFunc(g.Rules, func(r Rule) bool { return r.Use == "a/m" })
|
||||
if err := SaveGroup(g); err == nil || !strings.Contains(err.Error(), "switched off") {
|
||||
t.Fatalf("saved: %v", err)
|
||||
}
|
||||
same("a failed save's change is in the held groups")
|
||||
g = pair()
|
||||
g.Levels[0], g.Rules[1].Agents[0], g.Rules[1].Time.Days[0] = "max", "x", "sun"
|
||||
same("a caller's change is in the held groups")
|
||||
|
||||
// the caller's group, cleaned for saving: as it gave it, saved or not
|
||||
in := Group{Name: "R", Members: []string{"a/m", "b/big"}, Rules: []Rule{{Use: " b/big ", Intent: "tests"}}}
|
||||
if err := SaveGroup(in); err == nil || !strings.Contains(err.Error(), "classifier") {
|
||||
t.Fatalf("saved: %v", err)
|
||||
}
|
||||
if in.Rules[0].Use != " b/big " {
|
||||
t.Fatalf("SaveGroup changed the caller's rule: %q", in.Rules[0].Use)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -374,7 +374,14 @@ func setMigration(id string, f func(m *Migration)) error {
|
||||
for k, v := range readMigrationsFile() {
|
||||
all[k] = v
|
||||
}
|
||||
// f changes its own copy: the lists read are shared with every reader
|
||||
// (filememo), and a write that fails leaves them as the file has them
|
||||
m := all[id]
|
||||
m.Accounts = slices.Clone(m.Accounts)
|
||||
for i := range m.Accounts {
|
||||
m.Accounts[i].Was = maps.Clone(m.Accounts[i].Was)
|
||||
}
|
||||
m.Backup = slices.Clone(m.Backup)
|
||||
f(&m)
|
||||
all[id] = m
|
||||
b, err := json.MarshalIndent(all, "", " ")
|
||||
|
||||
@@ -0,0 +1,117 @@
|
||||
package provider
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"slices"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// movedTwo records "zed" moved with two accounts, as forgetting one of
|
||||
// them finds it.
|
||||
func movedTwo(t *testing.T) {
|
||||
t.Helper()
|
||||
claudeHome(t)
|
||||
if err := setMigration("zed", func(m *Migration) {
|
||||
*m = Migration{State: MovePlugin, Package: "@magpie-community/opencode-zed-auth", At: time.Now().UTC().Truncate(time.Second),
|
||||
Accounts: []movedAccount{
|
||||
{Key: "zed:a", User: "a@example.com", Was: map[string]any{"type": "oauth", "refresh": "r-a"}},
|
||||
{Key: "zed:b", User: "b@example.com"},
|
||||
},
|
||||
Backup: []savedLogin{
|
||||
{Agent: "zed", User: "a@example.com", Auth: json.RawMessage(`{"token":"t-a"}`)},
|
||||
{Agent: "zed", User: "b@example.com", Auth: json.RawMessage(`{"token":"t-b"}`)},
|
||||
}}
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
// forgetA is what forgetPluginAccounts does to the record when a@ is
|
||||
// signed out.
|
||||
func forgetA(m *Migration) {
|
||||
m.Accounts = slices.DeleteFunc(m.Accounts, func(a movedAccount) bool { return a.User == "a@example.com" })
|
||||
m.Backup = slices.DeleteFunc(m.Backup, func(b savedLogin) bool { return b.User == "a@example.com" })
|
||||
}
|
||||
|
||||
// A forget whose write fails changed nothing: what the record is read as
|
||||
// afterwards is still what migrations.json holds. It was read as b@'s
|
||||
// account twice over, the second with no key, so moving back handed back
|
||||
// an account with no sign-in.
|
||||
func TestFailedMigrationWriteLeavesItAsRead(t *testing.T) {
|
||||
if runtime.GOOS == "windows" || os.Geteuid() == 0 {
|
||||
t.Skip("needs a folder this user can't write to")
|
||||
}
|
||||
movedTwo(t)
|
||||
before, _ := MigrationOf("zed")
|
||||
if len(before.Accounts) != 2 || len(before.Backup) != 2 {
|
||||
t.Fatalf("recorded: %+v", before)
|
||||
}
|
||||
dir := filepath.Dir(migrationsPath())
|
||||
if err := os.Chmod(dir, 0o500); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { os.Chmod(dir, 0o700) })
|
||||
if err := setMigration("zed", forgetA); err == nil {
|
||||
t.Fatal("wrote into a folder it can't write to")
|
||||
}
|
||||
m, _ := MigrationOf("zed")
|
||||
var keys, users []string
|
||||
for _, a := range m.Accounts {
|
||||
keys = append(keys, a.Key)
|
||||
}
|
||||
for _, b := range m.Backup {
|
||||
users = append(users, b.User)
|
||||
}
|
||||
if !slices.Equal(keys, []string{"zed:a", "zed:b"}) || !slices.Equal(users, []string{"a@example.com", "b@example.com"}) {
|
||||
t.Fatalf("after a forget that wasn't written, read as accounts %q, backup %q", keys, users)
|
||||
}
|
||||
if m.Accounts[0].Was["refresh"] != "r-a" {
|
||||
t.Fatalf("a@'s earlier sign-in read as %v", m.Accounts[0].Was)
|
||||
}
|
||||
}
|
||||
|
||||
// Moving back and putting back read the record without the lock a forget
|
||||
// changes it under: what they read is never changed by it (go test -race).
|
||||
func TestMigrationReadWhileForgotten(t *testing.T) {
|
||||
movedTwo(t)
|
||||
MigrationOf("zed")
|
||||
var wg sync.WaitGroup
|
||||
stop, reading := make(chan struct{}), make(chan struct{})
|
||||
read := 0
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
for i := 0; ; i++ {
|
||||
select {
|
||||
case <-stop:
|
||||
return
|
||||
default:
|
||||
}
|
||||
m, _ := MigrationOf("zed")
|
||||
if i == 0 {
|
||||
close(reading)
|
||||
}
|
||||
for _, a := range m.Accounts {
|
||||
read += len(a.Key)
|
||||
}
|
||||
for _, b := range m.Backup {
|
||||
read += len(b.User)
|
||||
}
|
||||
}
|
||||
}()
|
||||
<-reading
|
||||
err := setMigration("zed", forgetA)
|
||||
close(stop)
|
||||
wg.Wait()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if m, _ := MigrationOf("zed"); len(m.Accounts) != 1 || m.Accounts[0].Key != "zed:b" || len(m.Backup) != 1 || m.Backup[0].User != "b@example.com" {
|
||||
t.Fatalf("after forgetting a@: %+v", m)
|
||||
}
|
||||
}
|
||||
@@ -44,3 +44,23 @@ func TestGroupMemberEffortAndFast(t *testing.T) {
|
||||
m = press(t, m, "down", "F")
|
||||
wantFlash(t, m, false, "no fast mode")
|
||||
}
|
||||
|
||||
// Taking a model out of a group whose other one is off is refused; while
|
||||
// the in-process gateway holds the catalog, the group stays as it was, not
|
||||
// shifted down a model with an empty one at its end.
|
||||
func TestGroupTakeOutRefusedWhileHeld(t *testing.T) {
|
||||
home(t)
|
||||
if err := provider.SaveGroup(provider.Group{ID: "pair", Name: "Pair", Members: []string{"a/m", "b/gpt-5.5"}, Off: []string{"b/gpt-5.5"}, Rules: []provider.Rule{{Use: "a/m", Tokens: 5}}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer provider.Hold()()
|
||||
m := press(t, model{w: 120, h: 40}, "3", "enter")
|
||||
if m.mode != modeGroup || m.gsel != 0 {
|
||||
t.Fatalf("mode %d, picked %d", m.mode, m.gsel)
|
||||
}
|
||||
m = press(t, m, "d", "d")
|
||||
wantFlash(t, m, false, "switched off")
|
||||
if g := group(t, "pair"); !slices.Equal(g.Members, []string{"a/m", "b/gpt-5.5"}) || len(g.Rules) != 1 || g.Rules[0].Use != "a/m" {
|
||||
t.Fatalf("members %v rules %+v", g.Members, g.Rules)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user