diff --git a/pkgs/mcpx/internal/daemon/paths.go b/pkgs/mcpx/internal/daemon/paths.go index c81945ca1b..7a841b4428 100644 --- a/pkgs/mcpx/internal/daemon/paths.go +++ b/pkgs/mcpx/internal/daemon/paths.go @@ -178,10 +178,20 @@ func privateRuntimeDir() (string, error) { // places stay separate. // // "Different places" means different files, not different spellings of one. -// Each path is resolved through symlinks first: /tmp is a symlink to -// /private/tmp on macOS, and a process whose $PWD holds the unresolved form -// -- a shell, an editor, the opencode plugin -- otherwise computed a second -// key for the same file, reported no daemon running, and started another. +// Each path's *directory* is resolved through symlinks first: /tmp is a +// symlink to /private/tmp on macOS, and a process whose $PWD holds the +// unresolved form -- a shell, an editor, the opencode plugin -- otherwise +// computed a second key for the same file, reported no daemon running, and +// started another. +// +// The file's own link is deliberately NOT resolved (#368). A nix or +// home-manager config is a symlink whose target is content-addressed, so +// resolving it made the key follow the target: every content change moved +// the socket, the running daemon became unreachable, and the CLI started a +// second one, which the first then fought over the new socket name. The +// path the user names -- directory resolved, file name as given -- is the +// stable identity; content changes behind the link are the content +// fingerprint's and the watch stamp's job, not the key's. // // The *contents* used to be in the key as well, so that editing a config got // a fresh daemon rather than a stale one. That stopped being a good trade the @@ -195,13 +205,21 @@ func privateRuntimeDir() (string, error) { // // So the key is the file set, and staleness is handled where it belongs: the // daemon notices its files changed and re-reads them. +// keyPath is the identity a config path contributes to a fingerprint: its +// directory resolved through symlinks, its file name as given. See +// FingerprintConfig for why the file's own link is not resolved. +func keyPath(p string) string { + dir := filepath.Dir(p) + if real, err := filepath.EvalSymlinks(dir); err == nil { + dir = real + } + return filepath.Join(dir, filepath.Base(p)) +} + func FingerprintConfig(paths []string) string { h := sha256.New() for _, p := range paths { - if real, err := filepath.EvalSymlinks(p); err == nil { - p = real - } - h.Write([]byte(p)) + h.Write([]byte(keyPath(p))) h.Write([]byte{0}) } return hex.EncodeToString(h.Sum(nil))[:12] @@ -210,14 +228,14 @@ func FingerprintConfig(paths []string) string { // ContentFingerprint hashes what the config files currently say. // // Not the daemon key -- that is the file set -- but the thing the daemon -// compares against to notice somebody edited one behind its back. +// compares against to notice somebody edited one behind its back. The path +// hashed is the same keyPath the daemon key uses, so re-pointing a config +// symlink at identical content is not a content change, while different +// content behind the same link is. func ContentFingerprint(paths []string) string { h := sha256.New() for _, p := range paths { - if real, err := filepath.EvalSymlinks(p); err == nil { - p = real - } - h.Write([]byte(p)) + h.Write([]byte(keyPath(p))) h.Write([]byte{0}) if b, err := os.ReadFile(p); err == nil { h.Write(b) diff --git a/pkgs/mcpx/internal/daemon/paths_test.go b/pkgs/mcpx/internal/daemon/paths_test.go index 94b97acb69..92ef432a2e 100644 --- a/pkgs/mcpx/internal/daemon/paths_test.go +++ b/pkgs/mcpx/internal/daemon/paths_test.go @@ -133,6 +133,63 @@ func TestOneConfigReachedThroughASymlinkIsOneDaemon(t *testing.T) { } } +func TestAConfigBehindARepointedSymlinkKeepsItsDaemon(t *testing.T) { + // A nix/home-manager config is a symlink whose target is + // content-addressed: every content change re-points the link at a new + // store path. Resolving the file's own link made the daemon key follow + // the target (#368), so each edit moved the socket, the running daemon + // became unreachable, and a second daemon was started. + t.Setenv("MCPX_SOCKET", "") + dir := t.TempDir() + genA := filepath.Join(t.TempDir(), "config.json") + genB := filepath.Join(t.TempDir(), "config.json") + for p, body := range map[string]string{ + genA: `{"mcpServers":{}}`, + genB: `{"mcpServers":{"added":{"command":"x"}}}`, + } { + if err := os.WriteFile(p, []byte(body), 0o644); err != nil { + t.Fatal(err) + } + } + cfg := filepath.Join(dir, "config.json") + repoint := func(target string) { + t.Helper() + _ = os.Remove(cfg) + if err := os.Symlink(target, cfg); err != nil { + t.Fatal(err) + } + } + base := daemon.Paths{State: "/tmp/s"} + + repoint(genA) + before := daemon.FingerprintConfig([]string{cfg}) + beforeContent := daemon.ContentFingerprint([]string{cfg}) + repoint(genB) + after := daemon.FingerprintConfig([]string{cfg}) + if before != after { + t.Errorf("re-pointing the config symlink moved the daemon key: %s vs %s", before, after) + } + if base.ForConfig(before) != base.ForConfig(after) { + t.Errorf("re-pointing the config symlink moved the daemon socket/info paths") + } + // The content fingerprint is what notices the new content behind the + // same key, so it must still change. + if daemon.ContentFingerprint([]string{cfg}) == beforeContent { + t.Error("content fingerprint did not change when the re-pointed link's content changed") + } + + // A re-point at identical content (a rebuild that changed nothing) + // must not look like a content change either. + genC := filepath.Join(t.TempDir(), "config.json") + if err := os.WriteFile(genC, []byte(`{"mcpServers":{}}`), 0o644); err != nil { + t.Fatal(err) + } + repoint(genC) + if got := daemon.ContentFingerprint([]string{cfg}); got != beforeContent { + t.Errorf("re-pointing at identical content changed the content fingerprint: %s vs %s", got, beforeContent) + } +} + // ForConfig's key is the config file set, and both halves of that are // load-bearing (#183). Stable across an edit is why a daemon that reloads stays // reachable by the client that edited it (#56); unstable across the set is why diff --git a/pkgs/mcpx/internal/daemon/reload_test.go b/pkgs/mcpx/internal/daemon/reload_test.go index 9b174b3920..6ed9d69841 100644 --- a/pkgs/mcpx/internal/daemon/reload_test.go +++ b/pkgs/mcpx/internal/daemon/reload_test.go @@ -2,6 +2,7 @@ package daemon import ( "context" + "os" "path/filepath" "syscall" "testing" @@ -48,6 +49,43 @@ func waitGone(t *testing.T, pid int) { } } +func TestStampConfigNoticesARepointedSymlinkWithSameSizeAndMtime(t *testing.T) { + // Nix store files all carry mtime 1, so a re-pointed config link whose + // new target has the same byte length as the old one is invisible to a + // stamp built from the followed file's mtime+size alone (#368). The + // stamp must notice the link itself moved. + dir := t.TempDir() + stampTime := time.Unix(1, 0) + genA := filepath.Join(t.TempDir(), "config.json") + genB := filepath.Join(t.TempDir(), "config.json") + // Same length, different content. + for p, body := range map[string]string{genA: `{"a":1}`, genB: `{"b":2}`} { + if err := os.WriteFile(p, []byte(body), 0o444); err != nil { + t.Fatal(err) + } + if err := os.Chtimes(p, stampTime, stampTime); err != nil { + t.Fatal(err) + } + } + cfg := filepath.Join(dir, "config.json") + repoint := func(target string) { + t.Helper() + _ = os.Remove(cfg) + if err := os.Symlink(target, cfg); err != nil { + t.Fatal(err) + } + } + repoint(genA) + before := stampConfig([]string{cfg}) + if again := stampConfig([]string{cfg}); again != before { + t.Fatalf("stamp is not stable when nothing moved: %q vs %q", before, again) + } + repoint(genB) + if after := stampConfig([]string{cfg}); after == before { + t.Errorf("stamp did not notice the config link was re-pointed at a same-size, same-mtime file") + } +} + func TestReloadKeepsUnchangedChildAndReplacesChangedOne(t *testing.T) { fake := testsupport.FakeMCPBinary(t) dir := t.TempDir() diff --git a/pkgs/mcpx/internal/daemon/routes_settings.go b/pkgs/mcpx/internal/daemon/routes_settings.go index 03fb6405da..ad20ec4074 100644 --- a/pkgs/mcpx/internal/daemon/routes_settings.go +++ b/pkgs/mcpx/internal/daemon/routes_settings.go @@ -723,15 +723,30 @@ func (s *Server) watchConfig() { } // stampConfig is a cheap "did anything move" check: no file is read. +// +// A symlinked config needs both halves stamped (#368): the followed file's +// mtime+size (an in-place edit to the target) and the link itself -- its +// own mtime+size plus where it points. Nix store targets all carry mtime 1, +// so a re-pointed link whose new target happens to have the same byte +// length as the old one is invisible to the followed stat alone. func stampConfig(paths []string) string { var b strings.Builder for _, p := range paths { - st, err := os.Stat(p) + st, err := os.Lstat(p) if err != nil { b.WriteString(p + ":gone;") continue } fmt.Fprintf(&b, "%s:%d:%d;", p, st.ModTime().UnixNano(), st.Size()) + if st.Mode()&os.ModeSymlink == 0 { + continue + } + if target, err := os.Readlink(p); err == nil { + b.WriteString("->" + target + ";") + } + if tst, err := os.Stat(p); err == nil { + fmt.Fprintf(&b, "target:%d:%d;", tst.ModTime().UnixNano(), tst.Size()) + } } return b.String() }