Skip to content

Git designed for AI agents.

gc: collect covered, superseded and orphaned packs (PLAN7 WP75)

Federico Elia42168d48f80f
diff --git a/doc/graft/PLAN7.md b/doc/graft/PLAN7.md
index 439e926..9d59e22 100644
--- a/doc/graft/PLAN7.md
+++ b/doc/graft/PLAN7.md
@@ -954,11 +954,26 @@ func (c *Collector) CollectRepository(ctx context.Context, repoID int64, dryRun
// tombstones.
func (c *Collector) CollectRemoved(ctx context.Context, storage string, dryRun bool) (Report, error)
-// FaultHook is called at "after_drop_row", "after_delete", "mid_sweep" and
-// "after_prefix" (tests only).
-var FaultHook func(point string) error
```
+The fault hook is an unexported field set by tests (as for the checkpointer),
+with the points `after_drop_row` (a superseded checkpoint's row deleted, its
+pack not yet), `mid_sweep` (after the first deletion of the sweep),
+`after_delete` (the sweep's deletions done, the observations not yet updated)
+and `after_prefix` (a removed repository's objects deleted, its tombstone not
+yet). Errors carry gRPC codes: `NotFound` for an untracked repository,
+`Unavailable` for the database and the bucket, `FailedPrecondition` for
+invalid GC times.
+
+**List under concurrent deletion (found by the WP75 race test).** fileblob's
+own listing reads a directory and then stats each entry, and fails with
+`NotFound` when an entry was deleted in between, which is exactly what two
+overlapping collections do. `blobstore.List` on a file bucket therefore walks
+the directory itself: an entry that vanished is an object that is gone and is
+not listed. The `BlobStore.List` contract states that an object deleted during
+a listing is listed or not, never an error
+(`TestListWhileDeleting`, which fails with fileblob's listing).
+
`CollectRepository` (binding):
1. `st = GCSnapshot(repoID)`. `C_gc` = the greatest `Seq` among `st.Checkpoints`
diff --git a/internal/graft/corestore/gc/export_test.go b/internal/graft/corestore/gc/export_test.go
new file mode 100644
index 0000000..d233db0
--- /dev/null
+++ b/internal/graft/corestore/gc/export_test.go
@@ -0,0 +1,4 @@
+package gc
+
+// SetFaultHook sets the hook called at the fault points of c's runs.
+func SetFaultHook(c *Collector, hook func(point string) error) { c.faultHook = hook }
diff --git a/internal/graft/corestore/gc/gc.go b/internal/graft/corestore/gc/gc.go
new file mode 100644
index 0000000..68403b8
--- /dev/null
+++ b/internal/graft/corestore/gc/gc.go
@@ -0,0 +1,361 @@
+// Package gc reclaims the packs of the storage core that no reader will ever
+// need again (doc/graft/PLAN7.md, "Pack GC" and "Removed repositories",
+// binding):
+// - the changeset packs covered by a checkpoint older than gc_grace (C_gc,
+// GC BOUNDARY rule) and the packs of the checkpoints superseded by it;
+// - the objects under the repository's pack prefix that no row references,
+// once the collector itself observed them unreferenced at least gc_grace
+// earlier on the database clock (PACK OWNERSHIP RULE);
+// - every object of a removed repository, once its tombstone is gc_grace
+// old.
+//
+// Every decision of a run comes from one database snapshot (GCSnapshot) and the
+// proofs of PLAN7; the bucket's times are never read. Deleting a missing key is
+// success and observations are recorded with "do nothing on conflict", so a
+// run that crashed, or two runs that overlap, converge on the next run. The
+// database decides liveness: a pack is deleted only when no row needs it.
+package gc
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "sort"
+ "strconv"
+
+ "github.com/feder-cr/git-ai/internal/graft/corestore"
+ "github.com/feder-cr/git-ai/internal/log"
+ "github.com/feder-cr/git-ai/internal/structerr"
+)
+
+// Fault points of a collection, for crash injection in tests.
+const (
+ // PointAfterDropRow is reached when a superseded checkpoint's row is
+ // deleted and its pack is not yet.
+ PointAfterDropRow = "after_drop_row"
+ // PointMidSweep is reached after the first deletion of the sweep.
+ PointMidSweep = "mid_sweep"
+ // PointAfterDelete is reached when the sweep deleted its objects and the
+ // orphan observations are not yet updated.
+ PointAfterDelete = "after_delete"
+ // PointAfterPrefix is reached when a removed repository's objects are
+ // deleted and its tombstone is not yet.
+ PointAfterPrefix = "after_prefix"
+)
+
+// Report counts what a collection did, or would do in a dry run.
+type Report struct {
+ // Boundary is C_gc: the sequence of the newest checkpoint at least gc_grace
+ // old, 0 when there is none.
+ Boundary uint64
+ // CoveredDeleted are the changeset packs covered by the boundary.
+ CoveredDeleted int
+ // CheckpointsDropped are the checkpoints superseded by the boundary.
+ CheckpointsDropped int
+ // OrphansDeleted are the unreferenced objects observed at least gc_grace ago.
+ OrphansDeleted int
+ // OrphansObserved are the unreferenced objects seen for the first time.
+ OrphansObserved int
+ // OrphansInGrace are the unreferenced objects observed less than gc_grace ago.
+ OrphansInGrace int
+ // PacksDeleted counts every object deleted (or to delete in a dry run).
+ PacksDeleted int
+ // BytesReclaimed is the size of those objects.
+ BytesReclaimed int64
+ // RemovedRepos are the removed repositories whose objects were deleted.
+ RemovedRepos int
+ // DryRun tells that nothing was deleted or recorded.
+ DryRun bool
+}
+
+// Collector reclaims packs.
+type Collector struct {
+ core *corestore.Core
+ logger log.Logger
+
+ // faultHook, when set by a test, is called at the fault points; an error it
+ // returns ends the run there, as a crash would. Nil in production.
+ faultHook func(point string) error
+}
+
+// New returns the collector of core.
+func New(core *corestore.Core, logger log.Logger) *Collector {
+ return &Collector{core: core, logger: logger}
+}
+
+// packPrefix is the bucket prefix of the packs of a repository.
+func packPrefix(repoID int64) string {
+ return "repos/" + strconv.FormatInt(repoID, 10) + "/packs/"
+}
+
+// repoPrefix is the bucket prefix of every object of a repository.
+func repoPrefix(repoID int64) string {
+ return "repos/" + strconv.FormatInt(repoID, 10) + "/"
+}
+
+// CollectRepository reclaims the dead packs of one repository. The caller holds
+// the repository's maintenance lease, which only prevents wasted runs:
+// correctness does not depend on it. The errors carry gRPC codes: NotFound for
+// an untracked repository, Unavailable for the database and the bucket.
+func (c *Collector) CollectRepository(ctx context.Context, repoID int64, dryRun bool) (Report, error) {
+ if err := c.validTimes(); err != nil {
+ return Report{}, err
+ }
+
+ // Step 1: one snapshot and the boundary.
+ st, err := c.core.Meta.GCSnapshot(ctx, repoID)
+ if err != nil {
+ return Report{}, errDatabase(err)
+ }
+ cutoff := st.Now.Add(-c.core.GCGrace)
+ report := Report{DryRun: dryRun}
+ for _, cp := range st.Checkpoints {
+ if !cp.CreatedAt.After(cutoff) && cp.Seq > report.Boundary {
+ report.Boundary = cp.Seq
+ }
+ }
+
+ // Step 2: the checkpoints superseded by the boundary, row first. No reader
+ // uses a checkpoint below C_gc (GC BOUNDARY rule), and its pack belongs to
+ // its row only. A crash between the two leaves an unreferenced pack, which
+ // the orphan protocol reclaims.
+ live := map[string]struct{}{}
+ dropped := map[string]struct{}{}
+ for _, cp := range st.Checkpoints {
+ if cp.Seq >= report.Boundary {
+ live[cp.PackKey] = struct{}{}
+ continue
+ }
+ dropped[cp.PackKey] = struct{}{}
+ report.CheckpointsDropped++
+ report.PacksDeleted++
+ report.BytesReclaimed += cp.PackBytes
+ if dryRun {
+ continue
+ }
+ if _, err := c.core.Meta.DeleteCheckpoint(ctx, repoID, cp.Seq); err != nil {
+ return report, errDatabase(err)
+ }
+ if err := c.fault(PointAfterDropRow); err != nil {
+ return report, err
+ }
+ if err := c.core.Blobs.Delete(ctx, cp.PackKey); err != nil {
+ return report, errBucket(err)
+ }
+ }
+
+ // Step 3: liveness per key (change G): a key is live when its greatest
+ // referencing sequence is above the boundary, covered otherwise.
+ covered := map[string]struct{}{}
+ for key, seq := range st.Packs {
+ if seq > report.Boundary {
+ live[key] = struct{}{}
+ } else {
+ covered[key] = struct{}{}
+ }
+ }
+ for key := range live {
+ delete(covered, key)
+ }
+
+ // Step 4: the sweep of the bucket prefix.
+ var (
+ observe []string
+ forget []string
+ listed = map[string]struct{}{}
+ deleted bool
+ )
+ deleteObject := func(info corestore.BlobInfo) error {
+ report.PacksDeleted++
+ report.BytesReclaimed += info.Size
+ if dryRun {
+ return nil
+ }
+ if err := c.core.Blobs.Delete(ctx, info.Key); err != nil {
+ return errBucket(err)
+ }
+ if !deleted {
+ deleted = true
+ return c.fault(PointMidSweep)
+ }
+ return nil
+ }
+
+ var infos []corestore.BlobInfo
+ if err := c.core.Blobs.List(ctx, packPrefix(repoID), func(info corestore.BlobInfo) error {
+ infos = append(infos, info)
+ return nil
+ }); err != nil {
+ return report, errBucket(err)
+ }
+ sort.Slice(infos, func(i, j int) bool { return infos[i].Key < infos[j].Key })
+
+ for _, info := range infos {
+ key := info.Key
+ listed[key] = struct{}{}
+ _, observed := st.Orphans[key]
+
+ switch {
+ case isKey(live, key):
+ if observed {
+ // Committed since it was observed (PACK OWNERSHIP RULE 4): keep it.
+ forget = append(forget, key)
+ }
+ case isKey(dropped, key):
+ // Deleted in step 2 (or to be, in a dry run); a listing that raced the
+ // deletion still shows it.
+ case isKey(covered, key):
+ if err := deleteObject(info); err != nil {
+ return report, err
+ }
+ report.CoveredDeleted++
+ if observed {
+ forget = append(forget, key)
+ }
+ default:
+ firstSeen, ok := st.Orphans[key]
+ switch {
+ case !ok:
+ report.OrphansObserved++
+ observe = append(observe, key)
+ case firstSeen.After(cutoff):
+ report.OrphansInGrace++
+ default:
+ // Observed unreferenced at least gc_grace ago and still unreferenced
+ // in this snapshot: no writer can commit it any more (PACK OWNERSHIP
+ // RULE 5).
+ if err := deleteObject(info); err != nil {
+ return report, err
+ }
+ report.OrphansDeleted++
+ forget = append(forget, key)
+ }
+ }
+ }
+
+ // Observations of keys that are gone from the bucket are forgotten too.
+ for key := range st.Orphans {
+ if _, ok := listed[key]; !ok {
+ forget = append(forget, key)
+ }
+ }
+
+ if dryRun {
+ return report, nil
+ }
+ if err := c.fault(PointAfterDelete); err != nil {
+ return report, err
+ }
+ sort.Strings(observe)
+ sort.Strings(forget)
+ if err := c.core.Meta.RecordOrphans(ctx, repoID, observe); err != nil {
+ return report, errDatabase(err)
+ }
+ if err := c.core.Meta.ForgetOrphans(ctx, repoID, forget); err != nil {
+ return report, errDatabase(err)
+ }
+
+ c.logger.WithFields(log.Fields{
+ "repository_id": repoID,
+ "boundary": report.Boundary,
+ "covered_deleted": report.CoveredDeleted,
+ "checkpoints_dropped": report.CheckpointsDropped,
+ "orphans_deleted": report.OrphansDeleted,
+ "orphans_observed": report.OrphansObserved,
+ "orphans_in_grace": report.OrphansInGrace,
+ "bytes_reclaimed": report.BytesReclaimed,
+ }).InfoContext(ctx, "storage core: garbage collection")
+ return report, nil
+}
+
+// CollectRemoved reclaims the bucket prefixes of the tombstones of the storage
+// (every storage when empty) that are at least gc_grace old, then deletes the
+// tombstones (change F). A writer whose record read found a removed repository
+// did so before removed_at and uploads only until t_r + W, so no upload arrives
+// in the prefix after the sweep. A crash after a partial deletion leaves the
+// tombstone; the next run finishes it.
+func (c *Collector) CollectRemoved(ctx context.Context, storage string, dryRun bool) (Report, error) {
+ if err := c.validTimes(); err != nil {
+ return Report{}, err
+ }
+
+ removed, err := c.core.Meta.ListRemovedRepositories(ctx, storage, c.core.GCGrace)
+ if err != nil {
+ return Report{}, errDatabase(err)
+ }
+
+ report := Report{DryRun: dryRun}
+ for _, r := range removed {
+ var infos []corestore.BlobInfo
+ if err := c.core.Blobs.List(ctx, repoPrefix(r.RepoID), func(info corestore.BlobInfo) error {
+ infos = append(infos, info)
+ return nil
+ }); err != nil {
+ return report, errBucket(err)
+ }
+
+ for _, info := range infos {
+ report.PacksDeleted++
+ report.BytesReclaimed += info.Size
+ if dryRun {
+ continue
+ }
+ if err := c.core.Blobs.Delete(ctx, info.Key); err != nil {
+ return report, errBucket(err)
+ }
+ }
+ report.RemovedRepos++
+ if dryRun {
+ continue
+ }
+ if err := c.fault(PointAfterPrefix); err != nil {
+ return report, err
+ }
+ if err := c.core.Meta.DeleteRemovedRepository(ctx, r.RepoID); err != nil {
+ return report, errDatabase(err)
+ }
+ c.logger.WithFields(log.Fields{
+ "repository_id": r.RepoID,
+ "repository": r.Key.String(),
+ "objects": len(infos),
+ }).InfoContext(ctx, "storage core: the objects of a removed repository are deleted")
+ }
+ return report, nil
+}
+
+// validTimes refuses to collect with times that would break the proofs.
+func (c *Collector) validTimes() error {
+ if c.core.GCGrace <= 0 || c.core.GCMargin <= 0 || c.core.WriteDeadline() <= 0 {
+ return structerr.NewFailedPrecondition("storage core: invalid garbage collection times: gc_grace %s, gc_margin %s",
+ c.core.GCGrace, c.core.GCMargin)
+ }
+ return nil
+}
+
+func (c *Collector) fault(point string) error {
+ if c.faultHook == nil {
+ return nil
+ }
+ if err := c.faultHook(point); err != nil {
+ return fmt.Errorf("fault at %s: %w", point, err)
+ }
+ return nil
+}
+
+func isKey(set map[string]struct{}, key string) bool {
+ _, ok := set[key]
+ return ok
+}
+
+// errDatabase maps a database error of a collection.
+func errDatabase(err error) error {
+ if errors.Is(err, corestore.ErrRepositoryNotFound) {
+ return structerr.NewNotFound("the repository is not tracked by the storage core")
+ }
+ return structerr.NewUnavailable("storage core: %w", err)
+}
+
+// errBucket maps a bucket error of a collection.
+func errBucket(err error) error {
+ return structerr.NewUnavailable("storage core: bucket: %w", err)
+}
diff --git a/internal/graft/corestore/gc/gc_test.go b/internal/graft/corestore/gc/gc_test.go
new file mode 100644
index 0000000..134d3d5
--- /dev/null
+++ b/internal/graft/corestore/gc/gc_test.go
@@ -0,0 +1,489 @@
+package gc_test
+
+import (
+ "bytes"
+ "context"
+ "crypto/sha256"
+ "errors"
+ "fmt"
+ "sort"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/stretchr/testify/require"
+ "google.golang.org/grpc/codes"
+ "google.golang.org/grpc/status"
+
+ "github.com/feder-cr/git-ai/internal/graft/corestore"
+ "github.com/feder-cr/git-ai/internal/graft/corestore/coretest"
+ "github.com/feder-cr/git-ai/internal/graft/corestore/gc"
+ "github.com/feder-cr/git-ai/internal/graft/corestore/sqlstore"
+ "github.com/feder-cr/git-ai/internal/testhelper"
+)
+
+func TestMain(m *testing.M) {
+ testhelper.Run(m)
+}
+
+const grace = time.Hour
+
+func forEachDialect(t *testing.T, test func(t *testing.T, e *env)) {
+ for _, dialect := range coretest.Dialects() {
+ t.Run(string(dialect), func(t *testing.T) {
+ test(t, newEnv(t, dialect))
+ })
+ }
+}
+
+// env is a storage core with one repository, and the helpers to put rows and
+// objects in it and to age them on the database clock.
+type env struct {
+ t *testing.T
+ ctx context.Context
+ core *corestore.Core
+ store *sqlstore.Store
+ gc *gc.Collector
+ repo corestore.Repository
+ nextID int
+}
+
+func newEnv(t *testing.T, dialect sqlstore.Dialect) *env {
+ t.Helper()
+
+ core := coretest.Open(t, coretest.Options{Dialect: dialect, GCGrace: grace, GCMargin: 5 * time.Minute})
+ ctx := testhelper.Context(t)
+ e := &env{t: t, ctx: ctx, core: core, store: core.Meta.(*sqlstore.Store), gc: gc.New(core, testhelper.NewLogger(t))}
+ e.repo = e.register("repo")
+ return e
+}
+
+func (e *env) register(name string) corestore.Repository {
+ e.t.Helper()
+ repo, _, err := e.core.Meta.RegisterRepository(e.ctx, corestore.RepoKey{Storage: "default", RelativePath: name + ".git"}, "sha1", corestore.InitialState{})
+ require.NoError(e.t, err)
+ return repo
+}
+
+// upload stores a new pack object with unique content under a new owned key
+// of the repository, referenced by no row.
+func (e *env) upload(repoID int64) string {
+ e.t.Helper()
+ e.nextID++
+ return e.uploadContent(repoID, []byte(fmt.Sprintf("pack %d of %d", e.nextID, repoID)))
+}
+
+func (e *env) uploadContent(repoID int64, content []byte) string {
+ e.t.Helper()
+ key := corestore.NewPackKey(repoID, sha256.Sum256(content))
+ require.NoError(e.t, e.core.Blobs.Put(e.ctx, key, bytes.NewReader(content)))
+ return key
+}
+
+// changeset commits the next changeset of the repository, moving main, with
+// a new pack; it returns the pack key.
+func (e *env) changeset() string {
+ e.t.Helper()
+ key := e.upload(e.repo.ID)
+ e.commit(key)
+ return key
+}
+
+// commit commits the next changeset with the given pack key.
+func (e *env) commit(key string) uint64 {
+ e.t.Helper()
+ res, err := e.core.Meta.CommitChangeset(e.ctx, corestore.ChangesetInput{
+ RepoID: e.repo.ID,
+ Updates: []corestore.RefUpdate{{Name: "refs/heads/main", Expect: corestore.ExpectAny, New: corestore.Target(fmt.Sprintf("%040x", e.nextID+1000))}},
+ Operation: "test",
+ Actor: "tester",
+ NodeID: "node-a",
+ PackKey: key,
+ PackBytes: 1,
+ })
+ require.NoError(e.t, err)
+ return res.Seq
+}
+
+// checkpoint records a checkpoint at seq with a new pack; it returns the key.
+func (e *env) checkpoint(seq uint64) string {
+ e.t.Helper()
+ key := e.upload(e.repo.ID)
+ _, created, err := e.core.Meta.CreateCheckpoint(e.ctx, e.repo.ID, corestore.CheckpointInput{
+ Seq: seq,
+ Refs: map[string]corestore.Target{"refs/heads/main": corestore.Target(strings.Repeat("a", 40))},
+ PackKey: key,
+ PackBytes: 1,
+ })
+ require.NoError(e.t, err)
+ require.True(e.t, created)
+ return key
+}
+
+// exec runs a statement with ? placeholders on the database.
+func (e *env) exec(query string, args ...any) {
+ e.t.Helper()
+ if e.store.Dialect() == sqlstore.Postgres {
+ var b strings.Builder
+ n := 0
+ for _, r := range query {
+ if r == '?' {
+ n++
+ fmt.Fprintf(&b, "$%d", n)
+ continue
+ }
+ b.WriteRune(r)
+ }
+ query = b.String()
+ }
+ _, err := e.store.DB().ExecContext(e.ctx, query, args...)
+ require.NoError(e.t, err)
+}
+
+// past returns a database time value d before now.
+func (e *env) past(d time.Duration) any {
+ t := time.Now().Add(-d).UTC()
+ if e.store.Dialect() == sqlstore.SQLite {
+ return t.Format(time.RFC3339Nano)
+ }
+ return t
+}
+
+func (e *env) ageCheckpoint(seq uint64, d time.Duration) {
+ e.exec("UPDATE graft_checkpoints SET created_at = ? WHERE repo_id = ? AND seq = ?", e.past(d), e.repo.ID, int64(seq))
+}
+
+func (e *env) ageObservations(d time.Duration) {
+ e.exec("UPDATE graft_gc_orphans SET first_seen = ? WHERE repo_id = ?", e.past(d), e.repo.ID)
+}
+
+// objects lists the objects of the repository in the bucket.
+func (e *env) objects(repoID int64) []string {
+ e.t.Helper()
+ var keys []string
+ require.NoError(e.t, e.core.Blobs.List(e.ctx, fmt.Sprintf("repos/%d/", repoID), func(info corestore.BlobInfo) error {
+ keys = append(keys, info.Key)
+ return nil
+ }))
+ sort.Strings(keys)
+ return keys
+}
+
+func (e *env) observations() map[string]time.Time {
+ e.t.Helper()
+ st, err := e.core.Meta.GCSnapshot(e.ctx, e.repo.ID)
+ require.NoError(e.t, err)
+ return st.Orphans
+}
+
+func (e *env) collect(dryRun bool) gc.Report {
+ e.t.Helper()
+ report, err := e.gc.CollectRepository(e.ctx, e.repo.ID, dryRun)
+ require.NoError(e.t, err)
+ return report
+}
+
+func sorted(keys ...string) []string {
+ sort.Strings(keys)
+ return keys
+}
+
+// TestCollectOrphans is the orphan protocol: an unreferenced object is
+// observed, kept while its observation is younger than gc_grace, and deleted
+// after; a re-run is a no-op.
+func TestCollectOrphans(t *testing.T) {
+ forEachDialect(t, func(t *testing.T, e *env) {
+ p1 := e.changeset()
+ orphan := e.upload(e.repo.ID)
+
+ report := e.collect(false)
+ require.Equal(t, gc.Report{OrphansObserved: 1}, report)
+ require.Contains(t, e.observations(), orphan)
+
+ report = e.collect(false)
+ require.Equal(t, gc.Report{OrphansInGrace: 1}, report)
+ require.Equal(t, sorted(p1, orphan), e.objects(e.repo.ID))
+
+ e.ageObservations(grace + time.Minute)
+ report = e.collect(false)
+ require.Equal(t, 1, report.OrphansDeleted)
+ require.Equal(t, 1, report.PacksDeleted)
+ require.Equal(t, []string{p1}, e.objects(e.repo.ID))
+ require.Empty(t, e.observations())
+
+ require.Equal(t, gc.Report{}, e.collect(false), "a re-run is a no-op")
+ })
+}
+
+// TestCollectKeepsAPackCommittedAfterItsObservation is crash/race case 3: an
+// object observed unreferenced (an upload whose commit was still running) and
+// committed by its writer before its deadline is kept, and its observation is
+// forgotten.
+func TestCollectKeepsAPackCommittedAfterItsObservation(t *testing.T) {
+ forEachDialect(t, func(t *testing.T, e *env) {
+ late := e.upload(e.repo.ID)
+ require.Equal(t, 1, e.collect(false).OrphansObserved)
+
+ e.commit(late)
+ e.ageObservations(grace + time.Minute)
+ report := e.collect(false)
+ require.Zero(t, report.OrphansDeleted)
+ require.Equal(t, []string{late}, e.objects(e.repo.ID))
+ require.Empty(t, e.observations(), "the observation of a referenced key is forgotten")
+ })
+}
+
+// TestCollectForgetsObservationsOfGoneObjects: an observed object that left the
+// bucket (deleted by an overlapping run) loses its observation.
+func TestCollectForgetsObservationsOfGoneObjects(t *testing.T) {
+ forEachDialect(t, func(t *testing.T, e *env) {
+ gone := e.upload(e.repo.ID)
+ require.Equal(t, 1, e.collect(false).OrphansObserved)
+ require.NoError(t, e.core.Blobs.Delete(e.ctx, gone))
+
+ require.Equal(t, gc.Report{}, e.collect(false))
+ require.Empty(t, e.observations())
+ })
+}
+
+// TestCollectBoundary covers the GC BOUNDARY rule: only checkpoints at least
+// gc_grace old count; packs of changesets up to the boundary are covered, the
+// checkpoints below it are dropped, everything above it is kept.
+func TestCollectBoundary(t *testing.T) {
+ forEachDialect(t, func(t *testing.T, e *env) {
+ var packs []string
+ for range 5 {
+ packs = append(packs, e.changeset())
+ }
+ cp2 := e.checkpoint(2)
+ cp4 := e.checkpoint(4)
+
+ // No checkpoint is old enough: nothing is covered.
+ require.Equal(t, gc.Report{}, e.collect(false))
+
+ // cp2 is old enough: changesets 1 and 2 are covered.
+ e.ageCheckpoint(2, grace+time.Minute)
+ report := e.collect(false)
+ require.Equal(t, uint64(2), report.Boundary)
+ require.Equal(t, 2, report.CoveredDeleted)
+ require.Zero(t, report.CheckpointsDropped)
+ require.Equal(t, sorted(packs[2], packs[3], packs[4], cp2, cp4), e.objects(e.repo.ID))
+
+ // cp4 is old enough too: cp2 is dropped, changesets 3 and 4 covered.
+ e.ageCheckpoint(4, grace+time.Minute)
+ report = e.collect(false)
+ require.Equal(t, uint64(4), report.Boundary)
+ require.Equal(t, 2, report.CoveredDeleted)
+ require.Equal(t, 1, report.CheckpointsDropped)
+ require.Equal(t, 3, report.PacksDeleted)
+ require.Equal(t, sorted(packs[4], cp4), e.objects(e.repo.ID))
+
+ newest, ok, err := e.core.Meta.NewestCheckpoint(e.ctx, e.repo.ID)
+ require.NoError(t, err)
+ require.True(t, ok)
+ require.Equal(t, uint64(4), newest.Seq)
+ _, err = e.core.Meta.CheckpointRefs(e.ctx, e.repo.ID, 2)
+ require.ErrorIs(t, err, corestore.ErrCheckpointNotFound)
+
+ // History is never deleted: every changeset row stays.
+ changesets, err := e.core.Meta.ListChangesets(e.ctx, e.repo.ID, 0, 5)
+ require.NoError(t, err)
+ require.Len(t, changesets, 5)
+
+ require.Equal(t, gc.Report{Boundary: 4}, e.collect(false), "a re-run is a no-op")
+ })
+}
+
+// TestCollectIdenticalPacks is crash/race case 1: two writes with
+// byte-identical packs own one object each, so covering the first deletes only
+// its own object and the second write's pack stays.
+func TestCollectIdenticalPacks(t *testing.T) {
+ forEachDialect(t, func(t *testing.T, e *env) {
+ content := []byte("the same pack twice")
+ first := e.uploadContent(e.repo.ID, content)
+ e.commit(first)
+ second := e.uploadContent(e.repo.ID, content)
+ require.NotEqual(t, first, second)
+ e.checkpoint(1)
+ secondSeq := e.commit(second)
+ require.Equal(t, uint64(2), secondSeq)
+
+ e.ageCheckpoint(1, grace+time.Minute)
+ report := e.collect(false)
+ require.Equal(t, 1, report.CoveredDeleted)
+ require.Contains(t, e.objects(e.repo.ID), second)
+ require.NotContains(t, e.objects(e.repo.ID), first)
+ })
+}
+
+// TestCollectDryRun deletes and records nothing and reports what a real run
+// does.
+func TestCollectDryRun(t *testing.T) {
+ forEachDialect(t, func(t *testing.T, e *env) {
+ for range 3 {
+ e.changeset()
+ }
+ e.checkpoint(1)
+ e.checkpoint(2)
+ orphan := e.upload(e.repo.ID)
+ require.Equal(t, 1, e.collect(false).OrphansObserved)
+ e.ageObservations(grace + time.Minute)
+ e.ageCheckpoint(1, grace+time.Minute)
+ e.ageCheckpoint(2, grace+time.Minute)
+ newOrphan := e.upload(e.repo.ID)
+
+ before := e.objects(e.repo.ID)
+ observations := e.observations()
+ dry := e.collect(true)
+ require.True(t, dry.DryRun)
+ require.Equal(t, before, e.objects(e.repo.ID))
+ require.Equal(t, observations, e.observations())
+
+ real := e.collect(false)
+ dry.DryRun = false
+ require.Equal(t, real, dry)
+ require.Equal(t, gc.Report{Boundary: 2, CoveredDeleted: 2, CheckpointsDropped: 1, OrphansDeleted: 1, OrphansObserved: 1, PacksDeleted: 4, BytesReclaimed: real.BytesReclaimed}, real)
+ require.NotContains(t, e.objects(e.repo.ID), orphan)
+ require.Contains(t, e.objects(e.repo.ID), newOrphan)
+ })
+}
+
+// TestCollectCrashPoints: a run that dies at any fault point leaves a state
+// that the next runs converge from.
+func TestCollectCrashPoints(t *testing.T) {
+ errCrash := errors.New("crash")
+
+ for _, point := range []string{gc.PointAfterDropRow, gc.PointMidSweep, gc.PointAfterDelete} {
+ t.Run(point, func(t *testing.T) {
+ forEachDialect(t, func(t *testing.T, e *env) {
+ var packs []string
+ for range 4 {
+ packs = append(packs, e.changeset())
+ }
+ e.checkpoint(1)
+ cp3 := e.checkpoint(3)
+ orphan := e.upload(e.repo.ID)
+ require.Equal(t, 1, e.collect(false).OrphansObserved)
+ e.ageObservations(grace + time.Minute)
+ e.ageCheckpoint(1, grace+time.Minute)
+ e.ageCheckpoint(3, grace+time.Minute)
+
+ gc.SetFaultHook(e.gc, func(p string) error {
+ if p == point {
+ return errCrash
+ }
+ return nil
+ })
+ _, err := e.gc.CollectRepository(e.ctx, e.repo.ID, false)
+ require.ErrorIs(t, err, errCrash)
+ gc.SetFaultHook(e.gc, nil)
+
+ // The next run finishes; a checkpoint pack whose row was dropped before
+ // the crash is an orphan the protocol reclaims after gc_grace.
+ e.collect(false)
+ e.ageObservations(grace + time.Minute)
+ e.collect(false)
+ require.Equal(t, sorted(packs[3], cp3), e.objects(e.repo.ID))
+ require.NotContains(t, e.objects(e.repo.ID), orphan)
+ require.Empty(t, e.observations())
+ require.Equal(t, gc.Report{Boundary: 3}, e.collect(false))
+ })
+ })
+ }
+}
+
+// TestCollectConcurrently is crash/race case 9 for two collectors: overlapping
+// runs make only safe decisions and converge.
+func TestCollectConcurrently(t *testing.T) {
+ forEachDialect(t, func(t *testing.T, e *env) {
+ var packs []string
+ for range 6 {
+ packs = append(packs, e.changeset())
+ }
+ cp4 := e.checkpoint(4)
+ for range 5 {
+ e.upload(e.repo.ID)
+ }
+ e.collect(false)
+ e.ageObservations(grace + time.Minute)
+ e.ageCheckpoint(4, grace+time.Minute)
+
+ other := gc.New(e.core, testhelper.NewLogger(t))
+ var wg sync.WaitGroup
+ errs := make([]error, 2)
+ for i, c := range []*gc.Collector{e.gc, other} {
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ _, errs[i] = c.CollectRepository(e.ctx, e.repo.ID, false)
+ }()
+ }
+ wg.Wait()
+ require.NoError(t, errors.Join(errs...))
+
+ require.Equal(t, sorted(packs[4], packs[5], cp4), e.objects(e.repo.ID))
+ require.Empty(t, e.observations())
+ })
+}
+
+func TestCollectUntrackedRepository(t *testing.T) {
+ forEachDialect(t, func(t *testing.T, e *env) {
+ _, err := e.gc.CollectRepository(e.ctx, e.repo.ID+1000, false)
+ require.Equal(t, codes.NotFound, status.Code(err), "%v", err)
+ })
+}
+
+// TestCollectRemoved is change F: the objects of a removed repository are
+// deleted once its tombstone is gc_grace old, then the tombstone; a crash after
+// the objects, or a partial deletion, converges on the next run.
+func TestCollectRemoved(t *testing.T) {
+ forEachDialect(t, func(t *testing.T, e *env) {
+ removed := e.register("removed")
+ var keys []string
+ for range 4 {
+ keys = append(keys, e.upload(removed.ID))
+ }
+ kept := e.changeset()
+ ok, err := e.core.Meta.DeleteRepository(e.ctx, removed.Key)
+ require.NoError(t, err)
+ require.True(t, ok)
+
+ report, err := e.gc.CollectRemoved(e.ctx, "", false)
+ require.NoError(t, err)
+ require.Equal(t, gc.Report{}, report, "the tombstone is younger than gc_grace")
+ require.Len(t, e.objects(removed.ID), 4)
+
+ e.exec("UPDATE graft_gc_removed SET removed_at = ? WHERE repo_id = ?", e.past(grace+time.Minute), removed.ID)
+
+ dry, err := e.gc.CollectRemoved(e.ctx, "", true)
+ require.NoError(t, err)
+ require.Equal(t, gc.Report{RemovedRepos: 1, PacksDeleted: 4, BytesReclaimed: dry.BytesReclaimed, DryRun: true}, dry)
+ require.Len(t, e.objects(removed.ID), 4)
+
+ // A partial deletion, then a crash after the prefix.
+ require.NoError(t, e.core.Blobs.Delete(e.ctx, keys[0]))
+ gc.SetFaultHook(e.gc, func(p string) error {
+ if p == gc.PointAfterPrefix {
+ return errors.New("crash")
+ }
+ return nil
+ })
+ _, err = e.gc.CollectRemoved(e.ctx, "", false)
+ require.Error(t, err)
+ gc.SetFaultHook(e.gc, nil)
+ require.Empty(t, e.objects(removed.ID))
+ tombstones, err := e.core.Meta.ListRemovedRepositories(e.ctx, "", 0)
+ require.NoError(t, err)
+ require.Len(t, tombstones, 1, "the tombstone stays until its prefix is gone")
+
+ report, err = e.gc.CollectRemoved(e.ctx, "", false)
+ require.NoError(t, err)
+ require.Equal(t, 1, report.RemovedRepos)
+ tombstones, err = e.core.Meta.ListRemovedRepositories(e.ctx, "", 0)
+ require.NoError(t, err)
+ require.Empty(t, tombstones)
+
+ require.Equal(t, []string{kept}, e.objects(e.repo.ID), "other repositories are untouched")
+ })
+}