diff --git a/.gitignore b/.gitignore index d4b825d..68844ea 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,7 @@ .devbox/ +.claude/ blobs/ +*.pre-v2.bak *.db *.db-wal *.db-shm diff --git a/cmd/devbox-hub/main.go b/cmd/devbox-hub/main.go index f0ac34e..cae1bef 100644 --- a/cmd/devbox-hub/main.go +++ b/cmd/devbox-hub/main.go @@ -217,11 +217,14 @@ func runGC(db *meta.DB, store blobstore.Store, keep int) (snaps, chunks int, err headSet[h] = true } - // Partition snapshots into kept vs prunable. A snapshot is prunable only if - // it's deletable for its share AND not the head of ANY share (a shared content - // id may be one share's stale snapshot but another's live head — never prune). + // Partition snapshots into kept vs prunable. Snapshots are now per-(share, id), + // so a prunable entry is a (share, id) pair: it's deletable for its share AND + // not the head of ANY share (a shared content id may be one share's stale + // snapshot but another's live head — never prune). keptSnaps tracks ids kept by + // any share, for reachability and to protect a shared manifest blob. keptSnaps := map[string]bool{} - var prunable []string + type snapRef struct{ share, id string } + var prunable []snapRef for _, share := range shares { del, err := db.DeletableSnapshots(share, keep) if err != nil { @@ -237,7 +240,7 @@ func runGC(db *meta.DB, store blobstore.Store, keep int) (snaps, chunks int, err } for _, id := range ids { if delSet[id] && !headSet[id] { - prunable = append(prunable, id) + prunable = append(prunable, snapRef{share, id}) } else { keptSnaps[id] = true } @@ -261,22 +264,26 @@ func runGC(db *meta.DB, store blobstore.Store, keep int) (snaps, chunks int, err } } - // Prune snapshots (skip any also kept by another share, and dedupe shared ids). - pruned := map[string]bool{} - for _, id := range prunable { - if keptSnaps[id] || pruned[id] { - continue + // Prune each (share, id): delete that share's row and decrement its chunks. The + // same content id in another share keeps its own row and counts. Delete the + // shared manifest blob at most once, and only when it's unreachable from any + // kept snapshot (reachable already includes every kept id, so this also won't + // remove a manifest blob that doubles as a live chunk). + blobDeleted := map[string]bool{} + for _, p := range prunable { + if keptSnaps[p.id] { + continue // a live/kept snapshot in another share still needs this content } - pruned[id] = true - hashes, err := manifestChunks(store, id) + hashes, err := manifestChunks(store, p.id) if err != nil && err != blobstore.ErrNotFound { return 0, 0, err } - if err := db.DeleteSnapshot(id, hashes); err != nil { + if err := db.DeleteSnapshot(p.share, p.id, hashes); err != nil { return 0, 0, err } - if !reachable[id] { // don't delete a manifest blob that doubles as a live chunk - if err := store.Delete(id); err != nil && err != blobstore.ErrNotFound { + if !reachable[p.id] && !blobDeleted[p.id] { + blobDeleted[p.id] = true + if err := store.Delete(p.id); err != nil && err != blobstore.ErrNotFound { return 0, 0, err } } diff --git a/internal/hub/meta/meta.go b/internal/hub/meta/meta.go index 40c5c75..d65051f 100644 --- a/internal/hub/meta/meta.go +++ b/internal/hub/meta/meta.go @@ -8,14 +8,26 @@ package meta import ( "database/sql" "errors" + "fmt" + "os" + "strings" _ "modernc.org/sqlite" ) -const schema = ` +// connPragmas are per-connection settings re-applied on every Open (foreign_keys +// is per-connection; journal_mode=WAL is persistent but harmless to re-assert). +const connPragmas = ` PRAGMA journal_mode=WAL; PRAGMA busy_timeout=5000; PRAGMA foreign_keys=ON; +` + +// baselineSchema is the v1 (schema version 0) shape. It is CREATE ... IF NOT +// EXISTS so it is a no-op on any existing database and just seeds a fresh one; +// the migrations below then transform it. Never change a column here — that's +// what migrations are for; this only has to create v1 tables for new hubs. +const baselineSchema = ` CREATE TABLE IF NOT EXISTS devices ( id TEXT PRIMARY KEY, name TEXT NOT NULL, @@ -56,23 +68,126 @@ CREATE TABLE IF NOT EXISTS chunks ( ); ` +// migrations are ordered, append-only schema transforms. migrations[i] upgrades +// the database from PRAGMA user_version i to i+1, each in its own transaction +// with the user_version bump as the LAST statement — so a crash mid-migration +// rolls the whole step back (the version only advances once the step committed). +// v1 is version 0 (baselineSchema, no migration); the first v2 step takes it to 1. +// NEVER edit or reorder a shipped entry — only append. A database whose version +// exceeds len(migrations) is refused (a newer devbox wrote it). +var migrations = []string{ + // 1 (v2): re-key snapshots from a GLOBAL `id` PK to per-`(share, id)`. v1's + // global id meant identical content pushed to two shares collided on the same + // snapshot row, so the second share's chunk refcounts were never counted + // (undercount). Per-share rows let each share account its own chunks. The wire + // `id`/Head value stays the manifest hash, so the client contract is unchanged. + ` +CREATE TABLE snapshots_v2 ( + share TEXT NOT NULL, + id TEXT NOT NULL, + parent_id TEXT, + device_id TEXT NOT NULL, + created_at INTEGER NOT NULL, + manifest_hash TEXT NOT NULL, + PRIMARY KEY (share, id) +); +INSERT INTO snapshots_v2 (share, id, parent_id, device_id, created_at, manifest_hash) + SELECT share, id, parent_id, device_id, created_at, manifest_hash FROM snapshots; +DROP TABLE snapshots; +ALTER TABLE snapshots_v2 RENAME TO snapshots; +-- Re-establish the per-share invariant the v1 idempotent push violated: every +-- non-empty share head must have its OWN snapshot row. The old global PK recorded +-- shared content under just the first share, so a share that reverted/re-pushed +-- another share's content has a head with no local row. Copy one from wherever the +-- id was recorded (parent/device/time are informational for log/restore). +INSERT OR IGNORE INTO snapshots (share, id, parent_id, device_id, created_at, manifest_hash) + SELECT s.name, s.head_snapshot, src.parent_id, src.device_id, src.created_at, src.manifest_hash + FROM shares s + JOIN snapshots src ON src.id = s.head_snapshot + WHERE s.head_snapshot IS NOT NULL AND s.head_snapshot != '' + AND NOT EXISTS (SELECT 1 FROM snapshots o WHERE o.share = s.name AND o.id = s.head_snapshot); +`, +} + // DB is the hub metadata store. type DB struct{ sql *sql.DB } // Open opens (and migrates) the SQLite database at path. Use ":memory:" in tests. +// An existing on-disk database is backed up to ".pre-v2.bak" before any +// pending migration runs, and a database written by a newer devbox is refused. func Open(path string) (*DB, error) { + // Note whether a real database already exists, so we only spend a backup on + // upgrades that have data to protect (a fresh hub has nothing to lose). + preexisting := false + if path != "" && path != ":memory:" { + if fi, err := os.Stat(path); err == nil && fi.Size() > 0 { + preexisting = true + } + } db, err := sql.Open("sqlite", path) if err != nil { return nil, err } db.SetMaxOpenConns(1) // ponytail: single-writer; SQLite serializes anyway - if _, err := db.Exec(schema); err != nil { + if _, err := db.Exec(connPragmas); err != nil { + db.Close() + return nil, err + } + if _, err := db.Exec(baselineSchema); err != nil { + db.Close() + return nil, err + } + if err := migrate(db, path, preexisting); err != nil { db.Close() return nil, err } return &DB{sql: db}, nil } +// migrate applies every pending migration in order, each in its own transaction +// ending with the user_version bump (so a crash rolls a half-applied step back). +// It refuses a database whose version is beyond what this build knows about. +func migrate(db *sql.DB, path string, preexisting bool) error { + var cur int + if err := db.QueryRow(`PRAGMA user_version`).Scan(&cur); err != nil { + return err + } + if cur > len(migrations) { + return fmt.Errorf("hub database is schema version %d but this devbox supports up to %d — upgrade devbox", cur, len(migrations)) + } + if cur == len(migrations) { + return nil // already current + } + if preexisting { + bak := path + ".pre-v2.bak" + _ = os.Remove(bak) + // VACUUM INTO writes a consistent snapshot of the live DB; it cannot run in + // a transaction and won't take a bound parameter, so quote the path inline. + if _, err := db.Exec(`VACUUM INTO '` + strings.ReplaceAll(bak, "'", "''") + `'`); err != nil { + return fmt.Errorf("pre-migration backup to %s: %w", bak, err) + } + } + for i := cur; i < len(migrations); i++ { + tx, err := db.Begin() + if err != nil { + return err + } + if _, err := tx.Exec(migrations[i]); err != nil { + tx.Rollback() + return fmt.Errorf("migration to version %d: %w", i+1, err) + } + // user_version can't be parameterized; i+1 is an internal int, never input. + if _, err := tx.Exec(fmt.Sprintf(`PRAGMA user_version = %d`, i+1)); err != nil { + tx.Rollback() + return fmt.Errorf("set user_version %d: %w", i+1, err) + } + if err := tx.Commit(); err != nil { + return fmt.Errorf("commit migration %d: %w", i+1, err) + } + } + return nil +} + // Close closes the database. func (d *DB) Close() error { return d.sql.Close() } @@ -235,10 +350,12 @@ func (d *DB) AddSnapshot(s Snapshot, chunks []ChunkRef) error { defer tx.Rollback() // Snapshots are content-addressed, so re-pushing an unchanged tree (or - // reverting to a prior state) replays an existing id. That's idempotent: - // advance the head to it, but never re-insert or double-count chunk refs. + // 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 + // refs. Keyed by (share, id): the same content in another share is a distinct + // snapshot that must record its own row and count its own chunks. var one int - switch err := tx.QueryRow(`SELECT 1 FROM snapshots WHERE id=?`, s.ID).Scan(&one); { + switch err := tx.QueryRow(`SELECT 1 FROM snapshots WHERE share=? AND id=?`, s.Share, s.ID).Scan(&one); { case err == nil: if _, err := tx.Exec(`UPDATE shares SET head_snapshot=? WHERE name=?`, s.ID, s.Share); err != nil { return err @@ -360,16 +477,18 @@ func (d *DB) DeletableSnapshots(share string, keep int) ([]string, error) { return del, rows.Err() } -// DeleteSnapshot removes a snapshot row and decrements the refcount of each -// distinct chunk hash it referenced, all in one transaction. The caller derives -// chunkHashes from the snapshot's manifest (distinct, as AddSnapshot counted them). -func (d *DB) DeleteSnapshot(id string, chunkHashes []string) error { +// DeleteSnapshot removes one share's snapshot row and decrements the refcount of +// 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. +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 id=?`, id) + res, err := tx.Exec(`DELETE FROM snapshots WHERE share=? AND 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 346f8df..a53a70d 100644 --- a/internal/hub/meta/meta_test.go +++ b/internal/hub/meta/meta_test.go @@ -1,6 +1,11 @@ package meta -import "testing" +import ( + "database/sql" + "os" + "path/filepath" + "testing" +) func open(t *testing.T) *DB { t.Helper() @@ -220,7 +225,7 @@ func TestDeleteSnapshotDecrementsRefcounts(t *testing.T) { } // Delete s1, which referenced h1 and h2. - if err := db.DeleteSnapshot("s1", []string{"h1", "h2"}); err != nil { + if err := db.DeleteSnapshot("proj", "s1", []string{"h1", "h2"}); err != nil { t.Fatal(err) } if rc, _ := db.ChunkRefcount("h1"); rc != 2 { @@ -244,7 +249,7 @@ func TestUnreferencedChunks(t *testing.T) { } // Drop s1: h2 falls to 0 and becomes collectable; h1 still has s2,s3. - if err := db.DeleteSnapshot("s1", []string{"h1", "h2"}); err != nil { + if err := db.DeleteSnapshot("proj", "s1", []string{"h1", "h2"}); err != nil { t.Fatal(err) } un, err := db.UnreferencedChunks() @@ -265,3 +270,173 @@ func TestUnreferencedChunks(t *testing.T) { t.Fatalf("after row delete, unreferenced = %v, want []", got) } } + +// TestCrossShareRefcount is the v2 (M8) data-model fix: identical content pushed +// to two shares must count its chunks once PER SHARE. Under v1's global snapshot +// PK the second push hit the idempotent branch and never bumped the refcount +// (undercount) and recorded no row for the second share. With per-(share, id) +// snapshots each share accounts independently. +func TestCrossShareRefcount(t *testing.T) { + db := open(t) + for _, s := range []string{"a", "b"} { + if err := db.CreateShare(s, "dev1", 1); err != nil { + t.Fatal(err) + } + } + // Same content id "shared" referencing chunk c1, pushed to both shares. + snap := func(share string) Snapshot { + return Snapshot{ID: "shared", Share: share, DeviceID: "dev1", ManifestHash: "shared", CreatedAt: 10} + } + if err := db.AddSnapshot(snap("a"), []ChunkRef{{"c1", 5}}); err != nil { + t.Fatal(err) + } + if err := db.AddSnapshot(snap("b"), []ChunkRef{{"c1", 5}}); err != nil { + t.Fatal(err) + } + if rc, _ := db.ChunkRefcount("c1"); rc != 2 { + t.Fatalf("c1 refcount = %d, want 2 (each share counts independently)", rc) + } + // Each share sees the snapshot in its own log + ids. + for _, s := range []string{"a", "b"} { + if log, _ := db.SnapshotLog(s, 10); len(log) != 1 || log[0].ID != "shared" { + t.Fatalf("share %s log = %+v, want one 'shared' row", s, log) + } + if ids, _ := db.SnapshotIDs(s); len(ids) != 1 { + t.Fatalf("share %s ids = %v, want [shared]", s, ids) + } + } + // 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) + } + if rc, _ := db.ChunkRefcount("c1"); rc != 1 { + t.Fatalf("c1 refcount after pruning share a = %d, want 1 (share b still references it)", rc) + } + if ids, _ := db.SnapshotIDs("b"); len(ids) != 1 { + t.Fatalf("share b still has its snapshot after share a pruned, ids = %v", ids) + } +} + +// TestMigrationRunner checks the PRAGMA user_version runner: a fresh DB lands at +// the latest version, reopening is idempotent, and a DB written by a newer build +// is refused. Uses an on-disk DB so version + the pre-migration backup persist. +func TestMigrationRunner(t *testing.T) { + dir := t.TempDir() + path := filepath.Join(dir, "hub.db") + + db, err := Open(path) + if err != nil { + t.Fatalf("first Open: %v", err) + } + if v := userVersion(t, db.sql); v != len(migrations) { + t.Fatalf("fresh DB user_version = %d, want %d", v, len(migrations)) + } + // Exercise the v2 schema end-to-end (composite PK) to prove the migration took. + if err := db.CreateShare("s", "dev1", 1); err != nil { + t.Fatal(err) + } + if err := db.AddSnapshot(Snapshot{ID: "x", Share: "s", DeviceID: "dev1", ManifestHash: "x", CreatedAt: 1}, []ChunkRef{{"c", 1}}); err != nil { + t.Fatalf("AddSnapshot on migrated schema: %v", err) + } + db.Close() + + // Reopen: no pending migrations, must be a clean no-op. + db2, err := Open(path) + if err != nil { + t.Fatalf("reopen: %v", err) + } + if v := userVersion(t, db2.sql); v != len(migrations) { + t.Fatalf("reopened DB user_version = %d, want %d", v, len(migrations)) + } + if ids, _ := db2.SnapshotIDs("s"); len(ids) != 1 { + t.Fatalf("data lost across reopen: ids = %v", ids) + } + db2.Close() + + // A DB from a newer devbox (version beyond what we know) must be refused, not + // silently downgraded or corrupted. + raw, err := sql.Open("sqlite", path) + if err != nil { + t.Fatal(err) + } + if _, err := raw.Exec("PRAGMA user_version = 999"); err != nil { + t.Fatal(err) + } + raw.Close() + if _, err := Open(path); err == nil { + t.Fatal("Open must refuse a database newer than this build") + } +} + +func userVersion(t *testing.T, db *sql.DB) int { + t.Helper() + var v int + if err := db.QueryRow("PRAGMA user_version").Scan(&v); err != nil { + t.Fatal(err) + } + return v +} + +// TestMigrationFromV1WithData is the realistic upgrade path: a populated v1 +// database (user_version 0, global snapshot PK) is migrated in place. Data must +// survive, a backup must be written, and the v1 idempotent-push legacy — a share +// whose head has no snapshot row of its own — must be repaired so every head has a +// row under the new per-(share, id) model. +func TestMigrationFromV1WithData(t *testing.T) { + dir := t.TempDir() + path := filepath.Join(dir, "hub.db") + + // Hand-build a v1 database: baseline tables, user_version left at 0. + raw, err := sql.Open("sqlite", path) + if err != nil { + t.Fatal(err) + } + if _, err := raw.Exec(baselineSchema); err != nil { + t.Fatal(err) + } + // Share s owns content snapX (has its row). Share t's head is the SAME content + // (the v1 idempotent push advanced t's head but recorded no (t, snapX) row). + stmts := []string{ + `INSERT INTO shares(name, head_snapshot, created_by, created_at) VALUES('s','snapX','dev1',1)`, + `INSERT INTO shares(name, head_snapshot, created_by, created_at) VALUES('t','snapX','dev1',1)`, + `INSERT INTO snapshots(id,share,parent_id,device_id,created_at,manifest_hash) VALUES('snapX','s',NULL,'dev1',1,'snapX')`, + `INSERT INTO chunks(hash,size,refcount) VALUES('c1',5,1)`, + } + for _, s := range stmts { + if _, err := raw.Exec(s); err != nil { + t.Fatalf("seed v1 data %q: %v", s, err) + } + } + raw.Close() + + db, err := Open(path) // triggers the v1 -> v2 migration + if err != nil { + t.Fatalf("migrating a populated v1 DB: %v", err) + } + defer db.Close() + + if v := userVersion(t, db.sql); v != len(migrations) { + t.Fatalf("post-migration user_version = %d, want %d", v, len(migrations)) + } + if _, err := os.Stat(path + ".pre-v2.bak"); err != nil { + t.Fatalf("pre-migration backup missing: %v", err) + } + // Share s keeps its row. + if ids, _ := db.SnapshotIDs("s"); len(ids) != 1 || ids[0] != "snapX" { + t.Fatalf("share s ids = %v, want [snapX]", ids) + } + // Share t's head row was backfilled (the v1 legacy is repaired). + if ids, _ := db.SnapshotIDs("t"); len(ids) != 1 || ids[0] != "snapX" { + t.Fatalf("share t ids = %v, want [snapX] (head backfill)", ids) + } + if head, ok, _ := db.ShareHead("t"); !ok || head != "snapX" { + t.Fatalf("share t head = %q ok=%v, want snapX", head, ok) + } + // The composite-PK schema is live: a new push to t records its own row. + if err := db.AddSnapshot(Snapshot{ID: "snapY", Share: "t", ParentID: "snapX", DeviceID: "dev1", ManifestHash: "snapY", CreatedAt: 2}, []ChunkRef{{"c2", 6}}); err != nil { + t.Fatalf("post-migration AddSnapshot: %v", err) + } + if ids, _ := db.SnapshotIDs("t"); len(ids) != 2 { + t.Fatalf("share t ids after new push = %v, want 2", ids) + } +}