From 5e4933ddea45b7b32c361f5407574a6016ebd0c6 Mon Sep 17 00:00:00 2001 From: shoemoney Date: Sat, 28 Nov 2026 00:04:27 -0600 Subject: [PATCH] fix: atomically accept snapshot pushes against current head --- internal/hub/atomic_push_test.go | 108 ++++++++++++++++++++++++++ internal/hub/meta/atomic_push_test.go | 100 ++++++++++++++++++++++++ internal/hub/meta/meta.go | 57 +++++++++++++- internal/hub/meta/meta_test.go | 5 ++ internal/hub/server.go | 16 +++- 5 files changed, 278 insertions(+), 8 deletions(-) create mode 100644 internal/hub/atomic_push_test.go create mode 100644 internal/hub/meta/atomic_push_test.go diff --git a/internal/hub/atomic_push_test.go b/internal/hub/atomic_push_test.go new file mode 100644 index 0000000..6e547af --- /dev/null +++ b/internal/hub/atomic_push_test.go @@ -0,0 +1,108 @@ +package hub + +import ( + "bytes" + "encoding/json" + "net/http" + "net/http/httptest" + "testing" + + "github.com/shoemoney/devbox/internal/chunk" + "github.com/shoemoney/devbox/internal/hub/blobstore" + "github.com/shoemoney/devbox/internal/hub/meta" + "github.com/shoemoney/devbox/internal/manifest" + "github.com/shoemoney/devbox/pkg/proto" +) + +// Pause each manifest read after the handler's preliminary head check. Channels +// let both requests observe the same parent, then commit A before releasing B. +// There is no scheduler timing or repeated-attempt assumption in this proof. +type pushBarrierStore struct { + blobstore.Store + gates map[string]chan struct{} + arrived chan string +} + +func (s *pushBarrierStore) Get(hash string) ([]byte, error) { + if gate, ok := s.gates[hash]; ok { + s.arrived <- hash + <-gate + } + return s.Store.Get(hash) +} + +func TestConcurrentPushRejectsStaleParent(t *testing.T) { + db, err := meta.Open(":memory:") + if err != nil { + t.Fatal(err) + } + defer db.Close() + if err := db.AddDevice("device", "test", []byte("pub"), 1); err != nil { + t.Fatal(err) + } + if err := db.CreateShare("proj", "device", 1); err != nil { + t.Fatal(err) + } + disk, err := blobstore.NewDisk(t.TempDir()) + if err != nil { + t.Fatal(err) + } + store := &pushBarrierStore{Store: disk, gates: make(map[string]chan struct{}), arrived: make(chan string, 2)} + var hashes, chunks [2]string + for i, name := range []string{"a", "b"} { + data := []byte(name) + chunks[i] = chunk.Hash(data) + if err := disk.Put(chunks[i], data); err != nil { + t.Fatal(err) + } + mf := manifest.Manifest{Entries: []manifest.Entry{{Path: name, Mode: 0644, Size: 1, Chunks: []string{chunks[i]}}}} + body, err := mf.Marshal() + if err != nil { + t.Fatal(err) + } + hashes[i] = chunk.Hash(body) + if err := disk.Put(hashes[i], body); err != nil { + t.Fatal(err) + } + store.gates[hashes[i]] = make(chan struct{}) + } + srv := NewServer(db, store) + done := [2]chan *httptest.ResponseRecorder{make(chan *httptest.ResponseRecorder, 1), make(chan *httptest.ResponseRecorder, 1)} + for i := range hashes { + body := mustJSON(t, proto.PushRequest{Share: "proj", ManifestHash: hashes[i]}) + go func(i int) { + w := httptest.NewRecorder() + srv.handlePush(w, httptest.NewRequest("POST", proto.PathPush, bytes.NewReader(body)), "device") + done[i] <- w + }(i) + } + <-store.arrived + <-store.arrived + close(store.gates[hashes[0]]) + first := <-done[0] + close(store.gates[hashes[1]]) + second := <-done[1] + for i, w := range []*httptest.ResponseRecorder{first, second} { + var got proto.PushResponse + if w.Code != http.StatusOK || json.Unmarshal(w.Body.Bytes(), &got) != nil { + t.Fatalf("push %d: %d %s", i, w.Code, w.Body) + } + if got.Conflict != (i == 1) || got.Head != hashes[0] { + t.Errorf("push %d: %+v, want conflict=%v head=%s", i, got, i == 1, hashes[0]) + } + } + head, _, err := db.ShareHead("proj") + if err != nil || head != hashes[0] { + t.Errorf("head=%s err=%v, want %s", head, err, hashes[0]) + } + snaps, err := db.SnapshotIDs("proj") + if err != nil || len(snaps) != 1 || snaps[0] != hashes[0] { + t.Errorf("snapshots=%v err=%v, want only winner", snaps, err) + } + for i, hash := range chunks { + want := 1 - i + if rc, err := db.ChunkRefcount(hash); err != nil || rc != want { + t.Errorf("chunk %d refcount=%d err=%v, want %d", i, rc, err, want) + } + } +} diff --git a/internal/hub/meta/atomic_push_test.go b/internal/hub/meta/atomic_push_test.go new file mode 100644 index 0000000..64d903d --- /dev/null +++ b/internal/hub/meta/atomic_push_test.go @@ -0,0 +1,100 @@ +package meta + +import ( + "path/filepath" + "testing" +) + +func TestAcceptSnapshotReplayRevertAndGC(t *testing.T) { + db := open(t) + if err := db.CreateShare("proj", "device", 1); err != nil { + t.Fatal(err) + } + accept := func(id, parent string, conflict, advanced bool, head string) { + t.Helper() + got, err := db.AcceptSnapshot(Snapshot{ID: id, ManifestHash: id, Share: "proj", ParentID: parent}, []ChunkRef{{Hash: id}, {Hash: id}}) + if err != nil || got != (SnapshotAcceptance{Head: head, Conflict: conflict, Advanced: advanced}) { + t.Fatalf("accept(%s,%s)=%+v, %v", id, parent, got, err) + } + } + accept("a", "", false, true, "a") + accept("a", "old-parent", false, false, "a") // replay is independent of its original parent + accept("b", "a", false, true, "b") + candidates, err := db.DeletableSnapshots("proj", 0) + if err != nil || len(candidates) != 1 || candidates[0] != "a" { + t.Fatalf("GC candidates=%v, %v", candidates, err) + } + accept("a", "", true, false, "b") // existing snapshot cannot bypass the parent check + accept("a", "b", false, true, "a") // valid revert preserves original row and refs + // GC's previously selected candidate is now head; deletion must recheck. + if err := db.DeleteSnapshot("proj", "a", []string{"a"}); err != nil { + t.Fatal(err) + } + for _, hash := range []string{"a", "b"} { + if rc, err := db.ChunkRefcount(hash); err != nil || rc != 1 { + t.Fatalf("%s refcount=%d, %v; want 1", hash, rc, err) + } + } + snaps, err := db.SnapshotIDs("proj") + if err != nil || len(snaps) != 2 { + t.Fatalf("snapshots=%v, %v", snaps, err) + } + // If GC prunes an old snapshot before a revert, accepting it must restore refs. + if err := db.DeleteSnapshot("proj", "b", []string{"b"}); err != nil { + t.Fatal(err) + } + accept("b", "a", false, true, "b") + if rc, err := db.ChunkRefcount("b"); err != nil || rc != 1 { + t.Fatalf("restored b refcount=%d, %v", rc, err) + } +} + +func TestAcceptSnapshotAcrossConnections(t *testing.T) { + path := filepath.Join(t.TempDir(), "meta.db") + a, err := Open(path) + if err != nil { + t.Fatal(err) + } + defer a.Close() + b, err := Open(path) + if err != nil { + t.Fatal(err) + } + defer b.Close() + if err := a.CreateShare("proj", "device", 1); err != nil { + t.Fatal(err) + } + type outcome struct { + id string + result SnapshotAcceptance + err error + } + start := make(chan struct{}) + done := make(chan outcome, 2) + for i, db := range []*DB{a, b} { + id := []string{"a", "b"}[i] + go func() { + <-start + got, err := db.AcceptSnapshot(Snapshot{ID: id, Share: "proj"}, []ChunkRef{{Hash: id}}) + done <- outcome{id, got, err} + }() + } + close(start) + first, second := <-done, <-done + if first.err != nil || second.err != nil { + t.Fatalf("errors: %v, %v", first.err, second.err) + } + if first.result.Conflict { + first, second = second, first + } + if first.result.Conflict || !first.result.Advanced || !second.result.Conflict || second.result.Advanced || second.result.Head != first.id { + t.Fatalf("outcomes: %+v, %+v", first, second) + } + ids, err := a.SnapshotIDs("proj") + if err != nil || len(ids) != 1 || ids[0] != first.id { + t.Fatalf("snapshots=%v, %v", ids, err) + } + if rc, err := a.ChunkRefcount(second.id); err != nil || rc != 0 { + t.Fatalf("loser refcount=%d, %v", rc, err) + } +} diff --git a/internal/hub/meta/meta.go b/internal/hub/meta/meta.go index f0d1bc6..54dde6d 100644 --- a/internal/hub/meta/meta.go +++ b/internal/hub/meta/meta.go @@ -660,6 +660,53 @@ func (d *DB) AddSnapshot(s Snapshot, chunks []ChunkRef) error { } defer tx.Rollback() + if err := recordSnapshot(tx, s, chunks); err != nil { + return err + } + return tx.Commit() +} + +// SnapshotAcceptance is the result at the transaction's head check. A conflict +// records nothing; Advanced distinguishes a replay from a genuine head change. +type SnapshotAcceptance struct { + Head string + Conflict bool + Advanced bool +} + +// AcceptSnapshot accepts only a push extending the current head, or a replay of +// that head. The check, snapshot/refcount writes and head advance share one +// transaction. Acquire SQLite's write lock BEFORE reading so independent DB +// handles cannot both read an old head or fail upgrading a stale read transaction. +func (d *DB) AcceptSnapshot(s Snapshot, chunks []ChunkRef) (SnapshotAcceptance, error) { + var result SnapshotAcceptance + tx, err := d.sql.Begin() + if err != nil { + return result, err + } + defer tx.Rollback() + if _, err := tx.Exec(`UPDATE shares SET head_snapshot=head_snapshot WHERE name=?`, s.Share); err != nil { + return result, err + } + if err := tx.QueryRow(`SELECT COALESCE(head_snapshot,'') FROM shares WHERE name=?`, s.Share).Scan(&result.Head); err != nil { + return result, err + } + if s.ID != result.Head && s.ParentID != result.Head { + result.Conflict = true + return result, nil + } + result.Advanced = s.ID != result.Head + if err := recordSnapshot(tx, s, chunks); err != nil { + return SnapshotAcceptance{}, err + } + if err := tx.Commit(); err != nil { + return SnapshotAcceptance{}, err + } + result.Head = s.ID + return result, nil +} + +func recordSnapshot(tx *sql.Tx, s Snapshot, chunks []ChunkRef) error { // Snapshots are content-addressed, so re-pushing an unchanged tree (or // reverting to a prior state) replays an existing id within THIS share. That's // idempotent: advance the head to it, but never re-insert or double-count chunk @@ -671,7 +718,7 @@ func (d *DB) AddSnapshot(s Snapshot, chunks []ChunkRef) error { if _, err := tx.Exec(`UPDATE shares SET head_snapshot=? WHERE name=?`, s.ID, s.Share); err != nil { return err } - return tx.Commit() + return nil case !errors.Is(err, sql.ErrNoRows): return err } @@ -698,7 +745,7 @@ func (d *DB) AddSnapshot(s Snapshot, chunks []ChunkRef) error { if _, err := tx.Exec(`UPDATE shares SET head_snapshot=? WHERE name=?`, s.ID, s.Share); err != nil { return err } - return tx.Commit() + return nil } // ChunkRefcount returns a chunk's refcount (0 if unknown). Used by tests and GC. @@ -792,14 +839,16 @@ func (d *DB) DeletableSnapshots(share string, keep int) ([]string, error) { // each distinct chunk hash it referenced, all in one transaction. The caller // derives chunkHashes from the snapshot's manifest (distinct, as AddSnapshot // counted them). Keyed by (share, id): pruning one share's copy of shared content -// leaves another share's snapshot (and its refcounts) intact. +// leaves another share's snapshot (and its refcounts) intact. Recheck the live +// head in the DELETE: a GC candidate can become head after selection via revert. func (d *DB) DeleteSnapshot(share, id string, chunkHashes []string) error { tx, err := d.sql.Begin() if err != nil { return err } defer tx.Rollback() - res, err := tx.Exec(`DELETE FROM snapshots WHERE share=? AND id=?`, share, id) + res, err := tx.Exec(`DELETE FROM snapshots WHERE share=? AND id=? + AND NOT EXISTS (SELECT 1 FROM shares WHERE name=? AND head_snapshot=?)`, share, id, share, id) if err != nil { return err } diff --git a/internal/hub/meta/meta_test.go b/internal/hub/meta/meta_test.go index 5c62cf6..ceb48ed 100644 --- a/internal/hub/meta/meta_test.go +++ b/internal/hub/meta/meta_test.go @@ -306,6 +306,11 @@ func TestCrossShareRefcount(t *testing.T) { t.Fatalf("share %s ids = %v, want [shared]", s, ids) } } + // Advance share a so its shared snapshot is eligible for pruning; live heads + // are protected even if a caller passes one to DeleteSnapshot. + if err := db.AddSnapshot(Snapshot{ID: "new-a", Share: "a", ParentID: "shared"}, nil); err != nil { + t.Fatal(err) + } // Pruning one share's copy leaves the other's refcount intact (rc 2 -> 1). if err := db.DeleteSnapshot("a", "shared", []string{"c1"}); err != nil { t.Fatal(err) diff --git a/internal/hub/server.go b/internal/hub/server.go index 2915480..a015bf7 100644 --- a/internal/hub/server.go +++ b/internal/hub/server.go @@ -3,8 +3,8 @@ package hub import ( - "context" "compress/gzip" + "context" "crypto/ed25519" "crypto/rand" "crypto/sha256" @@ -505,7 +505,8 @@ func (s *Server) handlePush(w http.ResponseWriter, r *http.Request, deviceID str return } - // Conflict detection: a push must extend the current head (or replay it). + // Preliminary conflict check: a push must extend the current head (or replay + // it). AcceptSnapshot repeats this check atomically with the writes below. // Re-pushing the existing head is idempotent; a push whose parent IS the // current head fast-forwards; anything else means the device is behind and // must pull + reconcile (M3) before pushing again — we never clobber head. @@ -580,14 +581,21 @@ func (s *Server) handlePush(w http.ResponseWriter, r *http.Request, deviceID str ManifestHash: req.ManifestHash, CreatedAt: time.Now().Unix(), } - if err := s.db.AddSnapshot(snap, chunks); err != nil { + accepted, err := s.db.AcceptSnapshot(snap, chunks) + if err != nil { writeErr(w, http.StatusInternalServerError, err.Error()) return } + if accepted.Conflict { + s.conflicts.Add(1) + s.dash.Emit(dashboard.Event{Type: "conflict", Device: deviceID, Share: req.Share}) + writeJSON(w, http.StatusOK, proto.PushResponse{Head: accepted.Head, Conflict: true}) + return + } // Only announce a genuine head advance. An idempotent re-push (manifest == // current head) must NOT broadcast, or daemons would storm: pull -> re-push // the same state -> broadcast -> pull -> ... forever. - advanced := req.ManifestHash != head + advanced := accepted.Advanced if advanced { s.broker.publish(proto.Event{Share: req.Share, Snapshot: snapshotID}) }