fix(dataloss): make hub GC safe against cross-share refcount undercount 🩸🗑️

Snapshots are content-addressed with a GLOBAL id, so two shares with identical
content collide on one snapshots row and the idempotent push skips the refcount
bump — a chunk two share heads both need ends up refcount=1. The old GC then
pruned the 'old' snapshot for one share and freed chunks/manifests the OTHER
share's live head still pointed at. Permanent cross-share data loss.

Rework runGC as mark-and-sweep from every share's live snapshots as roots:
nothing reachable from a kept snapshot is ever deleted, whatever the refcounts
say. Never prune a snapshot that is any share's head. Plus hardening:
- DeleteSnapshot floors refcount at 0 and only decrements if the row existed
  (no negative counts from a double-delete).
- DeleteChunkRow is now conditional (WHERE refcount<=0) and reports if it
  deleted, so a push that re-references a chunk mid-GC isn't corrupted.
Cross-share repro test + existing single-share GC test both green.

Deferred to v2 (documented): proper per-(share,id) refcount accounting — needs
a schema migration of the live hub; the ground-truth GC makes it safe meanwhile.
This commit is contained in:
shoemoney 2026-06-23 02:35:43 -05:00
parent 57ebed35b5
commit 9ad2a9da74
4 changed files with 237 additions and 29 deletions

View file

@ -0,0 +1,97 @@
package main
import (
"crypto/ed25519"
"crypto/rand"
"net/http/httptest"
"testing"
"time"
"git.shoemoney.ai/shoemoney/devbox/internal/hub"
"git.shoemoney.ai/shoemoney/devbox/internal/hub/blobstore"
"git.shoemoney.ai/shoemoney/devbox/internal/hub/meta"
"git.shoemoney.ai/shoemoney/devbox/internal/secret"
"git.shoemoney.ai/shoemoney/devbox/internal/syncer"
"git.shoemoney.ai/shoemoney/devbox/internal/transport"
)
// Two shares with byte-identical content collide on the same content-addressed
// snapshot id (the idempotent push skips the refcount bump). Advancing one share
// makes that id "deletable" for it — but it's still the OTHER share's live head.
// GC must NOT delete the chunks/manifest that head needs. Regression for the
// critical cross-share refcount/GC data-loss finding.
func TestGCKeepsChunksSharedAcrossShares(t *testing.T) {
db, err := meta.Open(":memory:")
if err != nil {
t.Fatal(err)
}
defer db.Close()
store, err := blobstore.NewDisk(t.TempDir())
if err != nil {
t.Fatal(err)
}
srv := httptest.NewServer(hub.NewServer(db, store).Handler())
defer srv.Close()
if err := db.CreateToken(hub.HashToken("tok"), time.Now().Unix()+3600); err != nil {
t.Fatal(err)
}
c := transport.New(srv.URL)
pub, _, _ := ed25519.GenerateKey(rand.Reader)
if _, err := c.Join("tok", "dev", pub); err != nil {
t.Fatal(err)
}
if err := c.Publish("a"); err != nil {
t.Fatal(err)
}
if err := c.Publish("b"); err != nil {
t.Fatal(err)
}
guard, _ := secret.New(nil)
// Push byte-identical content to BOTH shares -> same snapshot id S.
rootA, rootB := t.TempDir(), t.TempDir()
igA, _ := syncer.LoadIgnore(rootA)
igB, _ := syncer.LoadIgnore(rootB)
writeFile(t, rootA, "f.txt", "identical bytes\n")
writeFile(t, rootB, "f.txt", "identical bytes\n")
sa, err := syncer.Push(c, rootA, "a", "", igA, guard, "", nil)
if err != nil {
t.Fatalf("push a: %v", err)
}
sb, err := syncer.Push(c, rootB, "b", "", igB, guard, "", nil)
if err != nil {
t.Fatalf("push b: %v", err)
}
if sa.Snapshot != sb.Snapshot {
t.Fatalf("identical content should collide: a=%s b=%s", sa.Snapshot, sb.Snapshot)
}
shared := manifestChunksOrFail(t, store, sb.Snapshot) // b's head chunks
if len(shared) == 0 {
t.Fatal("expected at least one chunk")
}
// Advance share a so S becomes deletable FOR A (b's head stays S).
writeFile(t, rootA, "f.txt", "changed on a\n")
if _, err := syncer.Push(c, rootA, "a", "", igA, guard, sa.Head, nil); err != nil {
t.Fatalf("advance a: %v", err)
}
// GC keeping only each share's head.
if _, _, err := runGC(db, store, 1); err != nil {
t.Fatalf("gc: %v", err)
}
// b's head, its manifest blob, and its chunks must ALL survive.
if head, _, _ := db.ShareHead("b"); head != sb.Snapshot {
t.Fatalf("share b head = %q after gc, want %q (clobbered!)", head, sb.Snapshot)
}
if has, _ := store.Has(sb.Snapshot); !has {
t.Fatal("b's head manifest blob was deleted by gc (cross-share data loss)")
}
for _, h := range shared {
if has, _ := store.Has(h); !has {
t.Fatalf("chunk %s referenced by b's live head was deleted by gc (data loss)", h)
}
}
}

View file

@ -186,48 +186,114 @@ func gcCmd() *cobra.Command {
return cmd
}
// runGC prunes deletable snapshots (keeping the head + `keep` newest per share),
// then deletes any chunk that lost its last reference. It returns how many
// snapshots and chunks were removed. Deleting an already-absent blob is fine —
// the metadata is the source of truth.
// runGC prunes deletable snapshots (keeping the head + `keep` newest per share)
// and sweeps unreachable chunks. It is mark-and-sweep from every share's live
// snapshots as roots: nothing reachable from a kept snapshot is ever deleted,
// regardless of refcounts. That makes GC safe even when refcounts are off — e.g.
// content-addressed snapshot ids are shared across shares, so a naive per-share
// refcount can undercount a chunk that two share heads both need.
func runGC(db *meta.DB, store blobstore.Store, keep int) (snaps, chunks int, err error) {
shares, err := db.ShareNames()
if err != nil {
return 0, 0, err
}
heads, err := db.Heads()
if err != nil {
return 0, 0, err
}
headSet := map[string]bool{}
for _, h := range heads {
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).
keptSnaps := map[string]bool{}
var prunable []string
for _, share := range shares {
ids, err := db.DeletableSnapshots(share, keep)
del, err := db.DeletableSnapshots(share, keep)
if err != nil {
return 0, 0, err
}
delSet := map[string]bool{}
for _, id := range del {
delSet[id] = true
}
ids, err := db.SnapshotIDs(share)
if err != nil {
return 0, 0, err
}
for _, id := range ids {
if delSet[id] && !headSet[id] {
prunable = append(prunable, id)
} else {
keptSnaps[id] = true
}
}
}
// Ground truth: everything reachable from a kept snapshot survives. Reach a
// missing manifest? Nothing is reachable through it — skip, don't abort.
reachable := map[string]bool{}
for id := range keptSnaps {
reachable[id] = true // the manifest blob itself is live
hashes, err := manifestChunks(store, id)
if err == blobstore.ErrNotFound {
continue
}
if err != nil {
return 0, 0, err
}
for _, h := range hashes {
reachable[h] = true
}
}
// 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
}
pruned[id] = true
hashes, err := manifestChunks(store, id)
if err != nil && err != blobstore.ErrNotFound {
return 0, 0, err
}
if err := db.DeleteSnapshot(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 {
return 0, 0, err
}
}
snaps++
}
}
// Sweep chunks: refcount==0 candidates, but only delete those NOT reachable
// from any kept snapshot. The reachability check is the safety net.
unref, err := db.UnreferencedChunks()
if err != nil {
return 0, 0, err
}
for _, h := range unref {
if reachable[h] {
continue // a live head needs it despite refcount — never delete
}
deleted, err := db.DeleteChunkRow(h) // conditional on refcount<=0
if err != nil {
return 0, 0, err
}
if deleted {
if err := store.Delete(h); err != nil && err != blobstore.ErrNotFound {
return 0, 0, err
}
if err := db.DeleteChunkRow(h); err != nil {
return 0, 0, err
chunks++
}
}
return snaps, len(unref), nil
return snaps, chunks, nil
}
// manifestChunks returns the distinct chunk hashes referenced by the snapshot

View file

@ -369,19 +369,29 @@ func (d *DB) DeleteSnapshot(id string, chunkHashes []string) error {
return err
}
defer tx.Rollback()
if _, err := tx.Exec(`DELETE FROM snapshots WHERE id=?`, id); err != nil {
res, err := tx.Exec(`DELETE FROM snapshots WHERE id=?`, id)
if err != nil {
return err
}
// Only decrement if this row actually existed. A double-delete (a retry, or a
// content id pruned once already) must not over-decrement and drive a chunk a
// live head still references below zero.
if n, _ := res.RowsAffected(); n == 0 {
return tx.Commit()
}
for _, h := range chunkHashes {
if _, err := tx.Exec(`UPDATE chunks SET refcount=refcount-1 WHERE hash=?`, h); err != nil {
// max(0, …) floors the refcount: even if accounting is off, it can never
// go negative and later let a live chunk read as unreferenced.
if _, err := tx.Exec(`UPDATE chunks SET refcount=max(0, refcount-1) WHERE hash=?`, h); err != nil {
return err
}
}
return tx.Commit()
}
// UnreferencedChunks lists chunk hashes whose refcount has dropped to zero (or
// below): their bytes are no longer reachable and the GC may delete them.
// UnreferencedChunks lists chunk hashes whose refcount has dropped to zero: GC
// treats these as deletion CANDIDATES, then re-verifies each against the live
// snapshot set before actually deleting (refcounts are only a hint).
func (d *DB) UnreferencedChunks() ([]string, error) {
rows, err := d.sql.Query(`SELECT hash FROM chunks WHERE refcount<=0`)
if err != nil {
@ -399,10 +409,45 @@ func (d *DB) UnreferencedChunks() ([]string, error) {
return out, rows.Err()
}
// DeleteChunkRow removes a chunk's metadata row (after its blob is gone).
func (d *DB) DeleteChunkRow(hash string) error {
_, err := d.sql.Exec(`DELETE FROM chunks WHERE hash=?`, hash)
return 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
// whether a row was removed; the caller deletes the blob only when it was.
func (d *DB) DeleteChunkRow(hash string) (bool, error) {
res, err := d.sql.Exec(`DELETE FROM chunks WHERE hash=? AND refcount<=0`, hash)
if err != nil {
return false, err
}
n, err := res.RowsAffected()
return n > 0, err
}
// Heads returns the current head snapshot id of every share that has one. GC
// uses these (plus the keep window) as the roots that must never be swept.
func (d *DB) Heads() ([]string, error) {
return d.queryStrings(`SELECT head_snapshot FROM shares WHERE head_snapshot IS NOT NULL AND head_snapshot != ''`)
}
// SnapshotIDs returns every snapshot id recorded for a share.
func (d *DB) SnapshotIDs(share string) ([]string, error) {
return d.queryStrings(`SELECT id FROM snapshots WHERE share=?`, share)
}
func (d *DB) queryStrings(query string, args ...any) ([]string, error) {
rows, err := d.sql.Query(query, args...)
if err != nil {
return nil, err
}
defer rows.Close()
var out []string
for rows.Next() {
var s string
if err := rows.Scan(&s); err != nil {
return nil, err
}
out = append(out, s)
}
return out, rows.Err()
}
func nullable(v int64) any {

View file

@ -255,8 +255,8 @@ func TestUnreferencedChunks(t *testing.T) {
t.Fatalf("unreferenced = %v, want [h2]", un)
}
if err := db.DeleteChunkRow("h2"); err != nil {
t.Fatal(err)
if deleted, err := db.DeleteChunkRow("h2"); err != nil || !deleted {
t.Fatalf("DeleteChunkRow(h2) = %v, %v; want true, nil", deleted, err)
}
if rc, _ := db.ChunkRefcount("h2"); rc != 0 {
t.Fatalf("h2 should be gone, refcount lookup = %d", rc)