From 0ab6a88627c841c3d097fb40a78f371eb600bc48 Mon Sep 17 00:00:00 2001 From: shoemoney Date: Tue, 30 Jun 2026 16:24:21 -0500 Subject: [PATCH] feat(hub): fsck also detects dangling snapshots (manifest refs a missing blob) --- cmd/devbox-hub/fsck_test.go | 143 +++++++++++++++++++++++++++++++++ cmd/devbox-hub/main.go | 93 ++++++++++++++++++--- internal/hub/meta/meta.go | 22 +++++ internal/hub/meta/meta_test.go | 46 +++++++++++ 4 files changed, 295 insertions(+), 9 deletions(-) create mode 100644 cmd/devbox-hub/fsck_test.go diff --git a/cmd/devbox-hub/fsck_test.go b/cmd/devbox-hub/fsck_test.go new file mode 100644 index 0000000..7bf7f0f --- /dev/null +++ b/cmd/devbox-hub/fsck_test.go @@ -0,0 +1,143 @@ +package main + +import ( + "crypto/ed25519" + "crypto/rand" + "net/http/httptest" + "testing" + "time" + + "github.com/shoemoney/devbox/internal/hub" + "github.com/shoemoney/devbox/internal/hub/blobstore" + "github.com/shoemoney/devbox/internal/hub/meta" + "github.com/shoemoney/devbox/internal/secret" + "github.com/shoemoney/devbox/internal/syncer" + "github.com/shoemoney/devbox/internal/transport" +) + +// TestCheckDanglingHealthy asserts a clean store reports zero dangling snapshots. +func TestCheckDanglingHealthy(t *testing.T) { + db, store, _ := fsckTestSetup(t, "proj") + dangling, err := checkDangling(db, store) + if err != nil { + t.Fatal(err) + } + if len(dangling) != 0 { + t.Fatalf("healthy store: want 0 dangling, got %d: %+v", len(dangling), dangling) + } +} + +// TestCheckDanglingMissingChunk asserts that deleting a chunk blob from the +// store causes the snapshot referencing it to be reported as dangling. +func TestCheckDanglingMissingChunk(t *testing.T) { + db, store, snap := fsckTestSetup(t, "proj") + + // grab all chunk hashes this snapshot references + chunks := manifestChunksOrFail(t, store, snap) + if len(chunks) == 0 { + t.Fatal("test setup: snapshot has no chunks") + } + victim := chunks[0] + + // delete the chunk blob directly from the store + if err := store.Delete(victim); err != nil { + t.Fatalf("deleting chunk blob: %v", err) + } + + dangling, err := checkDangling(db, store) + if err != nil { + t.Fatal(err) + } + if len(dangling) != 1 { + t.Fatalf("want 1 dangling snapshot, got %d: %+v", len(dangling), dangling) + } + d := dangling[0] + if d.Share != "proj" { + t.Fatalf("dangling.Share = %q, want %q", d.Share, "proj") + } + if d.ID != snap { + t.Fatalf("dangling.ID = %q, want %q", d.ID, snap) + } + found := false + for _, m := range d.Missing { + if m == victim { + found = true + } + } + if !found { + t.Fatalf("missing list %v does not contain deleted chunk %s", d.Missing, victim) + } +} + +// TestCheckDanglingMissingManifest asserts that deleting the manifest blob +// itself causes the snapshot to be reported as dangling. +func TestCheckDanglingMissingManifest(t *testing.T) { + db, store, snap := fsckTestSetup(t, "proj") + + if err := store.Delete(snap); err != nil { + t.Fatalf("deleting manifest blob: %v", err) + } + + dangling, err := checkDangling(db, store) + if err != nil { + t.Fatal(err) + } + if len(dangling) != 1 { + t.Fatalf("want 1 dangling snapshot, got %d", len(dangling)) + } + found := false + for _, m := range dangling[0].Missing { + if m == snap { + found = true + } + } + if !found { + t.Fatalf("missing list %v does not contain manifest hash %s", dangling[0].Missing, snap) + } +} + +// fsckTestSetup spins up a hub, enrolls a device, pushes one snapshot, and +// returns the db, store, and snapshot id. Cleans up on test end. +func fsckTestSetup(t *testing.T, share string) (*meta.DB, blobstore.Store, string) { + t.Helper() + db, err := meta.Open(":memory:") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { db.Close() }) + + store, err := blobstore.NewDisk(t.TempDir()) + if err != nil { + t.Fatal(err) + } + + srv := httptest.NewServer(hub.NewServer(db, store).Handler()) + t.Cleanup(srv.Close) + + if err := db.CreateToken(hub.HashToken("tok"), time.Now().Unix()+3600); err != nil { + t.Fatal(err) + } + c := transport.New(srv.URL) + pub, priv, err := ed25519.GenerateKey(rand.Reader) + if err != nil { + t.Fatal(err) + } + if _, err := c.Join("tok", "dev", pub, priv); err != nil { + t.Fatal(err) + } + if err := c.Publish(share); err != nil { + t.Fatal(err) + } + + guard, _ := secret.New(nil) + root := t.TempDir() + ig, _ := syncer.LoadIgnore(root) + + writeFile(t, root, "file.txt", "some content for fsck test\n") + result, err := syncer.Push(c, root, share, "", ig, guard, "", nil) + if err != nil { + t.Fatalf("push: %v", err) + } + + return db, store, result.Snapshot +} diff --git a/cmd/devbox-hub/main.go b/cmd/devbox-hub/main.go index 530bb21..c344da1 100644 --- a/cmd/devbox-hub/main.go +++ b/cmd/devbox-hub/main.go @@ -703,14 +703,58 @@ func backupCmd() *cobra.Command { return cmd } -// fsckCmd re-hashes every blob on disk to detect at-rest corruption. +// danglingEntry is a snapshot that references at least one missing blob. +type danglingEntry struct { + Share string `json:"share"` + ID string `json:"id"` + Missing []string `json:"missing"` +} + +// checkDangling enumerates every snapshot in db and returns those that reference +// a blob that does not exist in store (missing manifest or missing chunk). +func checkDangling(db *meta.DB, store blobstore.Store) ([]danglingEntry, error) { + snaps, err := db.AllSnapshots() + if err != nil { + return nil, err + } + var out []danglingEntry + for _, snap := range snaps { + var missing []string + if ok, _ := store.Has(snap.ID); !ok { + missing = append(missing, snap.ID) // manifest blob itself is gone + } else { + chunks, err := manifestChunks(store, snap.ID) + if err != nil { + if errors.Is(err, blobstore.ErrNotFound) { + missing = append(missing, snap.ID) + } else { + return nil, err + } + } else { + for _, h := range chunks { + if ok, _ := store.Has(h); !ok { + missing = append(missing, h) + } + } + } + } + if len(missing) > 0 { + out = append(out, danglingEntry{snap.Share, snap.ID, missing}) + } + } + return out, nil +} + +// fsckCmd re-hashes every blob on disk to detect at-rest corruption, then +// checks every snapshot for dangling references (manifest or chunk blobs that +// no longer exist in the store). // ponytail: re-hashes every blob (full read); fine for periodic DR checks, sample/mtime-skip if it ever gets too slow on a huge store. func fsckCmd() *cobra.Command { var data string var asJSON bool cmd := &cobra.Command{ Use: "fsck", - Short: "🔍 at-rest blob integrity scan (re-hash every blob)", + Short: "🔍 at-rest blob integrity scan (re-hash every blob + dangling snapshot check)", RunE: func(cmd *cobra.Command, _ []string) error { store, err := blobstore.NewDisk(filepath.Join(data, "blobs")) if err != nil { @@ -744,23 +788,54 @@ func fsckCmd() *cobra.Command { if walkErr != nil { return walkErr } + + db, err := openDB(data) + if err != nil { + return err + } + defer db.Close() + dangling, err := checkDangling(db, store) + if err != nil { + return err + } + if !asJSON { + for _, d := range dangling { + shortID := d.ID + if len(shortID) > 12 { + shortID = shortID[:12] + } + extra := len(d.Missing) - 1 + if extra > 0 { + fmt.Fprintf(cmd.OutOrStdout(), "⚠️ DANGLING snapshot %s/%s: missing %s (+%d more)\n", d.Share, shortID, d.Missing[0], extra) + } else { + fmt.Fprintf(cmd.OutOrStdout(), "⚠️ DANGLING snapshot %s/%s: missing %s\n", d.Share, shortID, d.Missing[0]) + } + } + } + if asJSON { type result struct { - Scanned int `json:"scanned"` - Corrupt []corruptEntry `json:"corrupt"` + Scanned int `json:"scanned"` + Corrupt []corruptEntry `json:"corrupt"` + Dangling []danglingEntry `json:"dangling"` } enc := json.NewEncoder(cmd.OutOrStdout()) enc.SetIndent("", " ") - if err := enc.Encode(result{scanned, corrupt}); err != nil { + if err := enc.Encode(result{scanned, corrupt, dangling}); err != nil { return err } - } else if len(corrupt) == 0 { + } else if len(corrupt) == 0 && len(dangling) == 0 { fmt.Fprintf(cmd.OutOrStdout(), "✅ fsck: %d blobs OK\n", scanned) } else { - fmt.Fprintf(cmd.OutOrStdout(), "❌ fsck: %d/%d blobs CORRUPT\n", len(corrupt), scanned) + if len(corrupt) > 0 { + fmt.Fprintf(cmd.OutOrStdout(), "❌ fsck: %d/%d blobs CORRUPT\n", len(corrupt), scanned) + } + if len(dangling) > 0 { + fmt.Fprintf(cmd.OutOrStdout(), "❌ fsck: %d dangling snapshot(s)\n", len(dangling)) + } } - if len(corrupt) > 0 { - return fmt.Errorf("fsck: %d corrupt blob(s) found", len(corrupt)) + if len(corrupt) > 0 || len(dangling) > 0 { + return fmt.Errorf("fsck: %d corrupt blob(s), %d dangling snapshot(s)", len(corrupt), len(dangling)) } return nil }, diff --git a/internal/hub/meta/meta.go b/internal/hub/meta/meta.go index f57c808..f0d1bc6 100644 --- a/internal/hub/meta/meta.go +++ b/internal/hub/meta/meta.go @@ -839,6 +839,28 @@ func (d *DB) UnreferencedChunks() ([]string, error) { return out, rows.Err() } +// SnapshotRef is a (share, id) pair for cross-share snapshot enumeration. +type SnapshotRef struct{ Share, ID string } + +// AllSnapshots returns every snapshot row as a {Share, ID} pair. +// Used by fsck to enumerate all snapshots across all shares. +func (d *DB) AllSnapshots() ([]SnapshotRef, error) { + rows, err := d.sql.Query(`SELECT share, id FROM snapshots`) + if err != nil { + return nil, err + } + defer rows.Close() + var out []SnapshotRef + for rows.Next() { + var r SnapshotRef + if err := rows.Scan(&r.Share, &r.ID); err != nil { + return nil, err + } + out = append(out, r) + } + return out, rows.Err() +} + // DeleteChunkRow removes a chunk's metadata row, but ONLY if it is still // unreferenced at delete time (refcount<=0) — so a push that re-referenced the // chunk between GC's scan and this delete isn't silently corrupted. Returns diff --git a/internal/hub/meta/meta_test.go b/internal/hub/meta/meta_test.go index e314f9a..5c62cf6 100644 --- a/internal/hub/meta/meta_test.go +++ b/internal/hub/meta/meta_test.go @@ -644,3 +644,49 @@ func TestDeviceLsShowsDevice(t *testing.T) { t.Fatal("fresh device should not be revoked") } } + +func TestAllSnapshots(t *testing.T) { + db := open(t) + now := time.Now().Unix() + if err := db.AddDevice("d1", "dev", []byte("pub"), now); err != nil { + t.Fatal(err) + } + if err := db.CreateShare("s1", "d1", now); err != nil { + t.Fatal(err) + } + if err := db.CreateShare("s2", "d1", now); err != nil { + t.Fatal(err) + } + + // empty: no snapshots yet + refs, err := db.AllSnapshots() + if err != nil { + t.Fatal(err) + } + if len(refs) != 0 { + t.Fatalf("expected 0 snapshots, got %d", len(refs)) + } + + // add one snapshot per share + if err := db.AddSnapshot(Snapshot{ID: "snap1", Share: "s1", DeviceID: "d1", ManifestHash: "snap1", CreatedAt: now}, nil); err != nil { + t.Fatal(err) + } + if err := db.AddSnapshot(Snapshot{ID: "snap2", Share: "s2", DeviceID: "d1", ManifestHash: "snap2", CreatedAt: now}, nil); err != nil { + t.Fatal(err) + } + + refs, err = db.AllSnapshots() + if err != nil { + t.Fatal(err) + } + if len(refs) != 2 { + t.Fatalf("expected 2 snapshots, got %d", len(refs)) + } + got := map[string]string{} + for _, r := range refs { + got[r.ID] = r.Share + } + if got["snap1"] != "s1" || got["snap2"] != "s2" { + t.Fatalf("unexpected refs: %+v", got) + } +}