Git designed for AI agents.
Review M2, m8: superseded checkpoints go with GC off; decide before the lease
Federico Elia9e0c414f1e81
diff --git a/doc/graft/PLAN7.md b/doc/graft/PLAN7.mdindex d4cc5bc..a317007 100644--- a/doc/graft/PLAN7.md+++ b/doc/graft/PLAN7.md@@ -1569,6 +1569,17 @@ shutdown.`maintenance_interval` and the lease serve both, and `Config.Checkpoints` and`Config.Collect` gate the steps. Test: `TestRunOnceDoesOnlyWhatIsOn`. The e2etest of the background checkpoints runs with the defaults.+* **Integrated review M2 and m8.**+ * M2: with checkpoints on and GC off, every checkpoint stayed forever. The+ runs now drop the superseded checkpoints even with GC off+ (`gc.CollectCheckpoints`, step 2 of `CollectRepository` on its own), under+ the same `C_gc` rule: no reader uses a checkpoint below `C_gc`, whether the+ covered changeset packs are collected or not.+ * m8: what is due is decided by reads, before the lease: `checkpointDue` and+ `C_gc` = `SyncBoundary(gc_grace)`. The runner remembers, per repository, the+ `C_gc` it dropped below. A repository with nothing due is skipped+ (`nothing_due`) without a write.+ * Test: `TestRunOnceDropsSupersededCheckpointsWithGCOff`.* **Database openers (audit).** Only `gitaly serve` opens the storage database(`corestoreopen.Open`, one `sqlstore.Store` per process). The `graft` CLI andevery other binary reach it through gRPC. Two Stores on one SQLite file existdiff --git a/doc/graft/STORAGE.md b/doc/graft/STORAGE.mdindex 4015aff..157385a 100644--- a/doc/graft/STORAGE.md+++ b/doc/graft/STORAGE.md@@ -234,6 +234,19 @@ does not:- Garbage collection deletes packs, so it is turned on deliberately(`gc = "auto"`), or run with `graft storage gc`. Until it runs, the bucketonly grows.+- Space cost with the defaults (checkpoints on, `gc` off). The bucket holds+ every changeset pack (it grows with the history), plus the checkpoints at or+ above `C_gc`: the newest checkpoint at least `gc_grace` old and the newer+ ones. The background checkpoints drop the older ones, under the same rule as+ garbage collection (a checkpoint below `C_gc` has no reader), so a repository+ keeps about one or two checkpoints, not one per `checkpoint_changesets`.+- A checkpoint is a whole copy of the repository: one pack of every object+ reachable from its references, about the size of a fresh clone.+- With `gc = "auto"` the changeset packs that a checkpoint `C_gc` covers go+ too, and the bucket holds about one or two checkpoints plus the packs of the+ changesets after `C_gc`.+- Orphan packs stay until garbage collection runs: those of failed writes, and+ of a drop interrupted between the row and the pack.The metrics are `graft_storage_maintenance_*` (runs, checkpoints, packs andbytes deleted, skipped repositories, failed steps).diff --git a/internal/graft/corestore/gc/gc.go b/internal/graft/corestore/gc/gc.goindex 68403b8..6b6315f 100644--- a/internal/graft/corestore/gc/gc.go+++ b/internal/graft/corestore/gc/gc.go@@ -93,22 +93,34 @@ 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) {+// CollectCheckpoints drops the checkpoints of one repository that the newest+// checkpoint at least gc_grace old supersedes (C_gc), and nothing else: it is+// step 2 of CollectRepository on its own. No reader uses a checkpoint below+// C_gc (GC BOUNDARY rule), whether or not the changeset packs it covers are+// collected, so the background checkpoints run it with garbage collection off:+// a repository then keeps the checkpoints at or above C_gc, not every+// checkpoint ever built. A crash between a row and its pack leaves an+// unreferenced pack, which the orphan protocol of CollectRepository reclaims.+func (c *Collector) CollectCheckpoints(ctx context.Context, repoID int64, dryRun bool) (Report, error) {if err := c.validTimes(); err != nil {return Report{}, err}+ _, report, _, _, err := c.dropSuperseded(ctx, repoID, dryRun)+ return report, err+}+// dropSuperseded reads the snapshot of the repository, computes the boundary+// C_gc and drops the checkpoints below it (steps 1 and 2 of CollectRepository).+// It returns the snapshot, the report so far, the live checkpoint packs and the+// dropped ones.+func (c *Collector) dropSuperseded(ctx context.Context, repoID int64, dryRun bool) (corestore.GCState, Report, map[string]struct{}, map[string]struct{}, error) {// Step 1: one snapshot and the boundary.+ report := Report{DryRun: dryRun}st, err := c.core.Meta.GCSnapshot(ctx, repoID)if err != nil {- return Report{}, errDatabase(err)+ return st, report, nil, nil, 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@@ -134,15 +146,33 @@ func (c *Collector) CollectRepository(ctx context.Context, repoID int64, dryRuncontinue}if _, err := c.core.Meta.DeleteCheckpoint(ctx, repoID, cp.Seq); err != nil {- return report, errDatabase(err)+ return st, report, live, dropped, errDatabase(err)}if err := c.fault(PointAfterDropRow); err != nil {- return report, err+ return st, report, live, dropped, err}if err := c.core.Blobs.Delete(ctx, cp.PackKey); err != nil {- return report, errBucket(err)+ return st, report, live, dropped, errBucket(err)}}+ return st, report, live, dropped, nil+}++// 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+ }++ // Steps 1 and 2: one snapshot, the boundary, the superseded checkpoints.+ st, report, live, dropped, err := c.dropSuperseded(ctx, repoID, dryRun)+ if err != nil {+ return report, err+ }+ cutoff := st.Now.Add(-c.core.GCGrace)// Step 3: liveness per key (change G): a key is live when its greatest// referencing sequence is above the boundary, covered otherwise.diff --git a/internal/graft/corestore/maintenance/maintenance.go b/internal/graft/corestore/maintenance/maintenance.goindex 6fc8ef5..33f6b78 100644--- a/internal/graft/corestore/maintenance/maintenance.go+++ b/internal/graft/corestore/maintenance/maintenance.go@@ -82,6 +82,10 @@ type Runner struct {// so that two processes of one node (a graceful upgrade) do not both hold a// lease.holder string+ // dropped is, per repository ID, the C_gc below which this runner dropped+ // the superseded checkpoints. Only the runs read and write it, one at a+ // time.+ dropped map[int64]uint64runs *prometheus.CounterVeccheckpoints prometheus.Counter@@ -121,6 +125,7 @@ func New(core *corestore.Core, cp *checkpoint.Checkpointer, collector *gc.Colleccfg: cfg,storages: storages,holder: LeaseHolder(core),+ dropped: map[int64]uint64{},runs: prometheus.NewCounterVec(prometheus.CounterOpts{Name: "graft_storage_maintenance_runs_total",Help: "Runs of the background maintenance of the storage core, by result (ok, error: at least one step failed).",@@ -139,7 +144,7 @@ func New(core *corestore.Core, cp *checkpoint.Checkpointer, collector *gc.Collec}),skipped: prometheus.NewCounterVec(prometheus.CounterOpts{Name: "graft_storage_maintenance_skipped_total",- Help: "Repositories the background maintenance skipped, by reason (no_local_copy, lease_held).",+ Help: "Repositories the background maintenance skipped, by reason (no_local_copy, nothing_due: no checkpoint due, no superseded checkpoint and no collection, decided without the lease; lease_held).",}, []string{"reason"}),failures: prometheus.NewCounterVec(prometheus.CounterOpts{Name: "graft_storage_maintenance_failures_total",@@ -149,7 +154,7 @@ func New(core *corestore.Core, cp *checkpoint.Checkpointer, collector *gc.Collecfor _, result := range []string{"ok", "error"} {r.runs.WithLabelValues(result)}- for _, reason := range []string{"no_local_copy", "lease_held"} {+ for _, reason := range []string{"no_local_copy", "nothing_due", "lease_held"} {r.skipped.WithLabelValues(reason)}for _, step := range []string{stepCollectRemoved, stepList, stepLease, stepCheckpoint, stepCollect} {@@ -245,6 +250,27 @@ func (r *Runner) maintain(ctx context.Context, record corestore.Repository) (strreturn "", nil}+ // What is due is decided by reads, before the lease (a row-lock write) is+ // taken: a repository with nothing due costs no write.+ due, err := r.checkpointDue(ctx, record)+ if err != nil {+ return stepCheckpoint, err+ }+ var boundary uint64+ if r.cfg.Checkpoints {+ // C_gc: the newest checkpoint at least gc_grace old on the database+ // clock. The checkpoints below it are superseded; a C_gc that this+ // runner dropped below already has none left.+ if boundary, err = r.core.Meta.SyncBoundary(ctx, record.ID, r.core.GCGrace); err != nil {+ return stepCheckpoint, err+ }+ }+ dropDue := boundary > 0 && boundary != r.dropped[record.ID]+ if !due && !dropDue && !r.cfg.Collect {+ r.skipped.WithLabelValues("nothing_due").Inc()+ return "", nil+ }+acquired, err := r.core.Meta.AcquireMaintenanceLease(ctx, record.ID, r.holder, r.cfg.LeaseTTL)if errors.Is(err, corestore.ErrRepositoryNotFound) {return "", nil@@ -262,10 +288,6 @@ func (r *Runner) maintain(ctx context.Context, record corestore.Repository) (str})defer release()- due, err := r.checkpointDue(leaseCtx, record)- if err != nil {- return stepCheckpoint, err- }if due {_, created, err := r.cp.Create(leaseCtx, repo)if err != nil {@@ -276,16 +298,23 @@ func (r *Runner) maintain(ctx context.Context, record corestore.Repository) (str}}- if !r.cfg.Collect {+ var report gc.Report+ switch {+ case r.cfg.Collect:+ // The collection drops the superseded checkpoints too.+ report, err = r.collector.CollectRepository(leaseCtx, record.ID, false)+ case dropDue:+ report, err = r.collector.CollectCheckpoints(leaseCtx, record.ID, false)+ default:return "", nil}- report, err := r.collector.CollectRepository(leaseCtx, record.ID, false)if errors.Is(err, corestore.ErrRepositoryNotFound) {return "", nil}if err != nil {return stepCollect, err}+ r.dropped[record.ID] = report.Boundaryr.count(report)return "", nil}diff --git a/internal/graft/corestore/maintenance/maintenance_test.go b/internal/graft/corestore/maintenance/maintenance_test.goindex 3f8dba9..ce15d08 100644--- a/internal/graft/corestore/maintenance/maintenance_test.go+++ b/internal/graft/corestore/maintenance/maintenance_test.go@@ -175,6 +175,63 @@ func config3(changesets uint64, packBytes int64) maintenance.Config {return maintenance.Config{Interval: time.Hour, Checkpoints: true, Collect: true, CheckpointChangesets: changesets, CheckpointPackBytes: packBytes, LeaseTTL: time.Minute}}+// TestRunOnceDropsSupersededCheckpointsWithGCOff verifies that the default+// configuration (checkpoints on, garbage collection off) does not keep every+// checkpoint ever built: once the newest checkpoint is gc_grace old (C_gc), the+// older ones go, under the same rule as the collection's. The changeset packs+// stay: they are the collection's. With nothing due, a run takes no lease.+func TestRunOnceDropsSupersededCheckpointsWithGCOff(t *testing.T) {+ t.Parallel()+ ctx := testhelper.Context(t)+ cfg := config3(1, 0)+ cfg.Collect = false+ e := newEnv(t, coretest.Options{GCGrace: 200 * time.Millisecond, GCMargin: 50 * time.Millisecond}, cfg)++ var built []corestore.Checkpoint+ for i := 0; i < 3; i++ {+ e.advance(1)+ e.fresh()+ require.NoError(t, e.runner.RunOnce(ctx))+ cp, ok := e.newestCheckpoint()+ require.True(t, ok)+ built = append(built, cp)+ }+ changesetPacks := e.bucketKeys()+ for _, cp := range built {+ delete(changesetPacks, cp.PackKey)+ }++ newest := built[len(built)-1]+ require.Eventually(t, func() bool {+ require.NoError(t, e.runner.RunOnce(ctx))+ return len(e.checkpoints()) == 1+ }, 30*time.Second, 50*time.Millisecond, "the superseded checkpoints are dropped")+ require.Equal(t, newest.Seq, e.checkpoints()[0].Seq)++ keys := e.bucketKeys()+ for _, cp := range built[:len(built)-1] {+ require.NotContains(t, keys, cp.PackKey, "the pack of a dropped checkpoint is deleted")+ }+ require.Contains(t, keys, newest.PackKey)+ for key := range changesetPacks {+ require.Contains(t, keys, key, "garbage collection is off: the changeset packs stay")+ }+ require.Len(t, keys, len(changesetPacks)+1)++ // Nothing is due any more: the run decides it without the lease.+ before := e.metric("graft_storage_maintenance_skipped_total", "nothing_due")+ require.NoError(t, e.runner.RunOnce(ctx))+ require.Equal(t, before+1, e.metric("graft_storage_maintenance_skipped_total", "nothing_due"))+}++// checkpoints returns the checkpoints of the repository.+func (e *env) checkpoints() []corestore.Checkpoint {+ e.t.Helper()+ st, err := e.core.Meta.GCSnapshot(testhelper.Context(e.t), e.repo.ID)+ require.NoError(e.t, err)+ return st.Checkpoints+}+// TestRunOnceDoesOnlyWhatIsOn verifies that the checkpoints and the garbage// collection are configured apart: checkpoints alone delete nothing, and the// collection alone creates no checkpoint.