Files
magpie/internal/agent/keptaway_lock_test.go
T
yetone 7cad9a6185 agent: magpie's own files written during a sync with ~/.config a link are left alone, and the window's size saved after a resize no longer hangs the app for good (ylorn on Discord)
ylorn (v0.1.1250, macOS arm64, ~/.config a symlink): ~10s after every
start the GUI froze, beachball, CPU ~0, SIGTERM ignored. Their SIGQUIT
stack: the window's resize timer -> settings.Save (fileMu write lock) ->
edit.WriteAtomic -> the sync's filter keptAway -> gateway.URL ->
settings.Load -> fileMu.RLock, the same lock, forever.

Cause: edit.Filtered's filter sees every file written through edit while
a sync runs, from any goroutine, under whatever lock the writer holds.
keptAway read the settings (gateway.URL, and access.LANSecret through
ourToken) inside it, and skipped magpie's own files by a prefix check on
the unresolved ~/.config/magpie while WriteAtomic hands it the path
edit.Target resolved, so with a linked ~/.config settings.json fell
through to the settings read.

Fix (the class): what the filter needs of this magpie, the gateway's
address and the LAN key, is read before it is on (keeping(), kept.away,
kept.ours), so the filter takes no settings or access lock. magpieFile
compares magpie's folder as named and as EvalSymlinks resolves it, with
the written file's folder resolved too (for a file not there yet).

Siblings found: wslSaveLocked writes wsl.json under wsl's mutex, and the
filter's wslHost takes that mutex: with a linked config folder the same
self-deadlock on Windows (now skipped as magpie's own; the test covers
it). access.save writes keys.json under access.mu, which LANSecret took
inside the filter (now read before). No other prefix check against
provider.Path()/appdir gets a Target-resolved path; the filter is
edit.Target's only consumer of that kind. edit.Filtered's doc now says
the filter waits on nothing.

Run at this head (macOS arm64, go1.26.8, -tags nogui, -p 1):
- TestOwnWritesDuringASyncWithALinkedConfig (new; sandbox HOME with
  .config a symlink): on origin/main 35aa50cfb it fails with the
  reporter's stack (settings.go:972 <- keptaway.go:92 <- settings.go:1324).
- go test ./internal/agent (whole package, 810s): ok
- go test ./internal/edit: ok
- -race TestOwnWrites...|TestKeptAwayOnlyWhatIsSure -count=2: ok
- gofmt -l clean; GOOS=darwin/linux/windows go vet ./internal/agent
  ./internal/edit: ok

Broken by hand:
- magpieFile comparing the unresolved folder only (settings read kept
  out of the filter): red, wsl.json deadlocks in wslHost.
- the settings read put back inside the filter, own check fixed: green
  (settings.json is skipped as magpie's own before it); with the old
  check as well: red with the reporter's stack. The hoist is guarded only
  together with the own check.

Not tried: the real GUI with a linked ~/.config; the Windows box.

Full suite: SUITE_LINE
2026-10-15 23:08:02 +08:00

100 lines
3.0 KiB
Go

package agent
import (
"encoding/json"
"fmt"
"os"
"path/filepath"
"runtime"
"strings"
"testing"
"time"
"github.com/yetone/magpie/internal/settings"
)
// magpie's own files written while a sync's filter is on, with ~/.config a
// link into another folder (a dotfiles repo; ylorn on Discord): the window's
// size saved after a resize (settings.Save, under the settings' lock) and
// wsl.json (under wsl's) are written, the filter leaves them as they are,
// and nothing waits on the lock its own writer holds. The GUI hung for
// good ~10s after every start, with SIGTERM ignored.
func TestOwnWritesDuringASyncWithALinkedConfig(t *testing.T) {
home := syncHome(t)
t.Setenv("MAGPIE_ADDR", "")
cfg := filepath.Join(home, ".config")
if err := os.RemoveAll(cfg); err != nil {
t.Fatal(err)
}
if err := os.Symlink(t.TempDir(), cfg); err != nil {
t.Skip(err)
}
s := settings.Load()
s.Port = 3593
// an address on another machine and keys in settings.json: what the
// filter would weigh, with the LAN key, were it not magpie's own
s.UpdateMirror = "https://mirror.example/"
if err := settings.Save(s); err != nil {
t.Fatal(err)
}
within(t, "settings.Save", func() error {
return synced(func() error {
s := settings.Load()
s.Window = []int{1200, 800}
return settings.Save(s)
})
})
if got := settings.Load(); len(got.Window) != 2 || got.Window[0] != 1200 || got.UpdateMirror != "https://mirror.example/" {
t.Errorf("settings as written: window %v, mirror %q", got.Window, got.UpdateMirror)
}
// wsl.json, written under the lock wslHost takes, holding an address
// the filter would ask wslHost about
wsl.Lock()
was := wsl.seen
wsl.Unlock()
t.Cleanup(func() {
wsl.Lock()
wsl.seen, wsl.dirty = was, false
wsl.Unlock()
})
seen := map[string]*distro{"Ubuntu": {Name: "Ubuntu", Gateway: "172.30.0.1", Values: map[string]string{"base": "http://192.168.1.20:3425/v1"}}}
b, _ := json.Marshal(seen)
if err := os.WriteFile(wslStatePath(), b, 0o644); err != nil {
t.Fatal(err)
}
seen["Ubuntu"].Values["base"] = "http://127.0.0.1:3593/v1"
within(t, "wsl.json", func() error {
return synced(func() error {
wsl.Lock()
defer wsl.Unlock()
wsl.seen, wsl.dirty = seen, true
wslSaveLocked()
return nil
})
})
if b, _ := os.ReadFile(wslStatePath()); !json.Valid(b) || !strings.Contains(string(b), "127.0.0.1:3593") {
t.Errorf("wsl.json as written: %s", b)
}
}
// within runs fn and fails the run when it hasn't returned in 10s: a
// goroutine stuck on a lock it holds can't be ended, so the binary is.
func within(t *testing.T, what string, fn func() error) {
t.Helper()
done := make(chan error, 1)
go func() { done <- fn() }()
select {
case err := <-done:
if err != nil {
t.Fatalf("%s: %v", what, err)
}
case <-time.After(10 * time.Second):
// not a panic: its cleanups would wait on the lock too
buf := make([]byte, 1<<20)
buf = buf[:runtime.Stack(buf, true)]
fmt.Fprintf(os.Stderr, "--- FAIL: %s: %s deadlocked under a sync's filter:\n%s\n", t.Name(), what, buf)
os.Exit(1)
}
}