From 5bfccdb297000bac45a66122af3a56e2d33987f7 Mon Sep 17 00:00:00 2001 From: shoemoney Date: Tue, 23 Jun 2026 01:37:58 -0500 Subject: [PATCH] =?UTF-8?q?fix(M7):=20review=20fixes=20=E2=80=94=20pidfile?= =?UTF-8?q?=20O=5FEXCL,=20publish=20race,=20backoff=20reset=20=F0=9F=90=9B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Code-review pass on M6.5+M7: - pidfile: claim via O_CREATE|O_EXCL and arbitrate live-vs-stale, so two `devbox start` invocations can't both win the guard and run concurrently - hub: serialize publish (publishMu) so a case-clash check + create is atomic; reject share names ending in '.' (Windows strips it → silent collision) - daemon: reset SSE backoff only after a genuinely healthy stream (2m), not the 30s ceiling, so a hub that recycles connections doesn't pin a 30s event lag - document that restore/deploy's delete pass is ignore/guard-filtered on purpose (never delete a user's gitignored runtime files or local secrets) - test: pidfile claim/refuse/stale-reclaim arbitration --- cmd/devbox/main.go | 28 +++++++++++++++++--- cmd/devbox/main_test.go | 48 ++++++++++++++++++++++++++++++++++ internal/daemon/backoff.go | 10 ++++--- internal/daemon/daemon.go | 2 +- internal/hub/server.go | 12 ++++++--- internal/hub/sharename.go | 2 ++ internal/hub/sharename_test.go | 1 + internal/syncer/pull.go | 7 ++++- 8 files changed, 98 insertions(+), 12 deletions(-) create mode 100644 cmd/devbox/main_test.go diff --git a/cmd/devbox/main.go b/cmd/devbox/main.go index 0830696..ed110f4 100644 --- a/cmd/devbox/main.go +++ b/cmd/devbox/main.go @@ -475,9 +475,6 @@ func startCmd() *cobra.Command { if len(cfg.Mounts) == 0 { return fmt.Errorf("no mounts — run: devbox mount ") } - if pid, ok := runningPid(dir); ok { - return fmt.Errorf("daemon already running (pid %d) — run: devbox stop", pid) - } if err := writePid(dir); err != nil { return err } @@ -577,11 +574,34 @@ func stopCmd() *cobra.Command { func pidPath(dir string) string { return filepath.Join(dir, "daemon.pid") } +// writePid atomically claims the pidfile via O_EXCL so two `devbox start` +// invocations can't both think they're the only daemon. If the file already +// exists it arbitrates: a live pid means refuse; a stale pid (crashed daemon) +// is removed and the claim retried. func writePid(dir string) error { if err := os.MkdirAll(dir, 0o700); err != nil { return err } - return os.WriteFile(pidPath(dir), []byte(strconv.Itoa(os.Getpid())), 0o600) + for { + f, err := os.OpenFile(pidPath(dir), os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o600) + if err == nil { + _, werr := f.WriteString(strconv.Itoa(os.Getpid())) + if cerr := f.Close(); werr == nil { + werr = cerr + } + return werr + } + if !os.IsExist(err) { + return err + } + if pid, ok := runningPid(dir); ok { + return fmt.Errorf("daemon already running (pid %d) — run: devbox stop", pid) + } + if rerr := os.Remove(pidPath(dir)); rerr != nil && !os.IsNotExist(rerr) { + return rerr + } + // Stale pidfile removed; loop retries the exclusive create. + } } func removePid(dir string) { _ = os.Remove(pidPath(dir)) } diff --git a/cmd/devbox/main_test.go b/cmd/devbox/main_test.go new file mode 100644 index 0000000..27a61df --- /dev/null +++ b/cmd/devbox/main_test.go @@ -0,0 +1,48 @@ +package main + +import ( + "os" + "strconv" + "strings" + "testing" +) + +// TestWritePidArbitration covers the O_EXCL claim, the live-daemon refusal, and +// stale-pidfile recovery. +func TestWritePidArbitration(t *testing.T) { + dir := t.TempDir() + + // First claim succeeds and records our (live) pid. + if err := writePid(dir); err != nil { + t.Fatalf("first writePid: %v", err) + } + if pid, ok := runningPid(dir); !ok || pid != os.Getpid() { + t.Fatalf("runningPid = (%d,%v), want (%d,true)", pid, ok, os.Getpid()) + } + + // A second claim must refuse: the pid in the file (us) is alive. + if err := writePid(dir); err == nil || !strings.Contains(err.Error(), "already running") { + t.Fatalf("second writePid = %v, want 'already running'", err) + } + + // A stale pidfile (a pid that isn't running) is reclaimed, not refused. + dead := 0x7fffffff // implausibly-high pid; Signal(0) returns ESRCH + if err := os.WriteFile(pidPath(dir), []byte(strconv.Itoa(dead)), 0o600); err != nil { + t.Fatal(err) + } + if _, ok := runningPid(dir); ok { + t.Fatal("runningPid reported a dead pid as alive") + } + if err := writePid(dir); err != nil { + t.Fatalf("reclaiming a stale pidfile: %v", err) + } + if pid, _ := runningPid(dir); pid != os.Getpid() { + t.Fatalf("after reclaim pid = %d, want %d", pid, os.Getpid()) + } + + // removePid clears it. + removePid(dir) + if _, ok := runningPid(dir); ok { + t.Fatal("pidfile still live after removePid") + } +} diff --git a/internal/daemon/backoff.go b/internal/daemon/backoff.go index cf5136e..1d692e3 100644 --- a/internal/daemon/backoff.go +++ b/internal/daemon/backoff.go @@ -5,10 +5,14 @@ import ( "time" ) -// Reconnect backoff bounds: start at 1s, double to a 30s ceiling. +// Reconnect backoff bounds: start at 1s, double to a 30s ceiling. A stream that +// stayed up at least healthyStream is treated as a transient drop (reset to base), +// not a hard failure — so a hub that recycles SSE connections every ~30s doesn't +// leave the daemon stuck at the ceiling with a 30s event lag. const ( - backoffBase = 1 * time.Second - backoffMax = 30 * time.Second + backoffBase = 1 * time.Second + backoffMax = 30 * time.Second + healthyStream = 2 * time.Minute ) // nextBackoff returns the next clean (un-jittered) backoff: base, then doubling diff --git a/internal/daemon/daemon.go b/internal/daemon/daemon.go index 4657e9c..9aacf86 100644 --- a/internal/daemon/daemon.go +++ b/internal/daemon/daemon.go @@ -138,7 +138,7 @@ func (d *Daemon) runMount(ctx context.Context, m config.Mount) { } // A stream that lived a while is a transient drop, not a hard failure: // reset so the retry is prompt instead of inheriting a grown delay. - if time.Since(start) > backoffMax { + if time.Since(start) > healthyStream { backoff = 0 } backoff = nextBackoff(backoff) diff --git a/internal/hub/server.go b/internal/hub/server.go index 5f84aaf..07a3fbc 100644 --- a/internal/hub/server.go +++ b/internal/hub/server.go @@ -13,6 +13,7 @@ import ( "io" "net/http" "strconv" + "sync" "time" "git.shoemoney.ai/shoemoney/devbox/internal/chunk" @@ -25,9 +26,10 @@ import ( // Server is the devbox hub: metadata in db, blob bytes in store, change events // fanned out via broker. type Server struct { - db *meta.DB - store blobstore.Store - broker *broker + db *meta.DB + store blobstore.Store + broker *broker + publishMu sync.Mutex // serializes publish so the case-clash check + create is atomic } // NewServer builds a hub server over the given metadata store and blob store. @@ -127,6 +129,10 @@ func (s *Server) handlePublish(w http.ResponseWriter, r *http.Request, deviceID if !decode(w, r, &req) { return } + // Serialize: the case-clash check below reads all names then creates one, so + // two concurrent publishes of "Foo"/"foo" must not both pass the check. + s.publishMu.Lock() + defer s.publishMu.Unlock() existing, err := s.db.ShareNames() if err != nil { writeErr(w, http.StatusInternalServerError, err.Error()) diff --git a/internal/hub/sharename.go b/internal/hub/sharename.go index 05fa1f7..7c4e217 100644 --- a/internal/hub/sharename.go +++ b/internal/hub/sharename.go @@ -32,6 +32,8 @@ func ValidateShareName(name string, existing []string) error { return fmt.Errorf("share name %q is reserved", name) case strings.HasPrefix(name, ".") || strings.HasPrefix(name, "-"): return fmt.Errorf("share name %q must not start with '.' or '-'", name) + case strings.HasSuffix(name, "."): + return fmt.Errorf("share name %q must not end with '.' (Windows strips it)", name) } for _, r := range name { switch { diff --git a/internal/hub/sharename_test.go b/internal/hub/sharename_test.go index ff0816a..aeaf348 100644 --- a/internal/hub/sharename_test.go +++ b/internal/hub/sharename_test.go @@ -18,6 +18,7 @@ func TestValidateShareName(t *testing.T) { {"a\\b", false}, // backslash {"..", false}, // traversal {".hidden", false}, // leading dot + {"trail.", false}, // trailing dot (Windows strips it) {"-flag", false}, // leading dash {"sp ace", false}, // interior space {"emoji🎉", false}, // non-ASCII diff --git a/internal/syncer/pull.go b/internal/syncer/pull.go index 5aa4315..54fee61 100644 --- a/internal/syncer/pull.go +++ b/internal/syncer/pull.go @@ -210,7 +210,12 @@ func applySnapshot(c *transport.Client, root, subpath, snapshot, onlyPath string return 0, err } } - // Delete anything present locally but absent from the snapshot. + // Delete tracked files present locally but absent from the snapshot. We diff + // against manifest.Build (ignore- + secret-guard-filtered) ON PURPOSE: a + // restore/deploy must NOT delete a user's .devignore'd runtime files (caches, + // logs) or local secrets — those were never in any snapshot, so "match the + // snapshot" leaves them untouched. Tracked extras (e.g. a file added in a newer + // snapshot) are still removed. ponytail: never lose a byte we didn't sync. local, _, err := manifest.Build(root, ig, guard) if err != nil { return 0, err