Git designed for AI agents.
storage: review roots are keep-around references (PLAN7 WP74b)
Federico Elia510668cc16b7
diff --git a/internal/gitaly/service/review/review.go b/internal/gitaly/service/review/review.goindex a436fe3..7d82505 100644--- a/internal/gitaly/service/review/review.go+++ b/internal/gitaly/service/review/review.go@@ -81,8 +81,8 @@ func (s *server) CreateReview(ctx context.Context, req *gitalypb.CreateReviewReq}var stored *gitalypb.Review- err = s.writeRoots(ctx, req.GetRepository(), repo, st, func(st store.ReviewStore, check rootsCheck) error {- if err := check(head, base); err != nil {+ err = s.writeRoots(ctx, repo, st, func(st store.ReviewStore, protect rootsProtect) error {+ if err := protect(head, base); err != nil {return err}@@ -200,10 +200,10 @@ func (s *server) UpdateReview(ctx context.Context, req *gitalypb.UpdateReviewReq}var updated *gitalypb.Review- err = s.writeRoots(ctx, req.GetRepository(), repo, st, func(st store.ReviewStore, check rootsCheck) error {+ err = s.writeRoots(ctx, repo, st, func(st store.ReviewStore, protect rootsProtect) error {var err errorupdated, err = st.Update(req.GetId(), func(r *gitalypb.Review) error {- return moveHead(ctx, repo, req, r, head, check)+ return moveHead(ctx, repo, req, r, head, protect)})return err})@@ -214,10 +214,11 @@ func (s *server) UpdateReview(ctx context.Context, req *gitalypb.UpdateReviewReqreturn &gitalypb.UpdateReviewResponse{Review: s.withRequirements(updated)}, nil}-// moveHead moves the review r to head, for UpdateReview. check verifies the-// new head as a root of the storage core (REVIEW ROOTS R1); a head that does-// not move is not checked.-func moveHead(ctx context.Context, repo *localrepo.Repo, req *gitalypb.UpdateReviewRequest, r *gitalypb.Review, head git.ObjectID, check rootsCheck) error {+// moveHead moves the review r to head, for UpdateReview. protect writes the+// keep-around references of the head and base the review is stored with (the+// REVIEW ROOTS RULE), also when the head does not move: the review store of+// authoritative mode requires them for every review it writes here.+func moveHead(ctx context.Context, repo *localrepo.Repo, req *gitalypb.UpdateReviewRequest, r *gitalypb.Review, head git.ObjectID, protect rootsProtect) error {if err := checkAuthor(ctx, r, "update"); err != nil {return err}@@ -227,14 +228,12 @@ func moveHead(ctx context.Context, repo *localrepo.Repo, req *gitalypb.UpdateRevif expected := req.GetExpectedHeadCommitId(); expected != "" && expected != r.GetHeadCommitId() {return structerr.NewFailedPrecondition("review head is %s, expected %s", r.GetHeadCommitId(), expected)}++ base := git.ObjectID(r.GetBaseCommitId())if head.String() == r.GetHeadCommitId() {- return nil- }- if err := check(head); err != nil {- return err+ return protect(reviewCommits(head, base)...)}- base := git.ObjectID(r.GetBaseCommitId())descends, err := repo.IsAncestor(ctx, base.Revision(), head.Revision())if err != nil {if !errors.As(err, new(localrepo.InvalidCommitError)) {@@ -269,11 +268,24 @@ func moveHead(ctx context.Context, repo *localrepo.Repo, req *gitalypb.UpdateRevv.Current = survives}+ if err := protect(reviewCommits(head, base)...); err != nil {+ return err+ }+r.Files = filesr.HeadCommitId = head.String()return nil}+// reviewCommits returns the head and base of a review, leaving out an unset+// base (reviews imported from the files of an older version may have none).+func reviewCommits(head, base git.ObjectID) []git.ObjectID {+ if base == "" {+ return []git.ObjectID{head}+ }+ return []git.ObjectID{head, base}+}+// onlyCommentOrDocs reports whether every file changed between from and to is// a comment-only or docs change. An empty change qualifies. A from commit that// is no longer in the object database (for example, pruned after a force push)@@ -432,7 +444,7 @@ func (s *server) CloseReview(ctx context.Context, req *gitalypb.CloseReviewRequereturn nil, structerr.NewInvalidArgument("review id is required")}- _, st, err := s.openRepo(ctx, req.GetRepository())+ repo, st, err := s.openRepo(ctx, req.GetRepository())if err != nil {return nil, err}@@ -455,6 +467,9 @@ func (s *server) CloseReview(ctx context.Context, req *gitalypb.CloseReviewRequereturn nil, toStatus(err)}+ // A closed review is not a root any more (REVIEW ROOTS RULE).+ s.releaseRoots(ctx, repo, st, reviewCommits(git.ObjectID(updated.GetHeadCommitId()), git.ObjectID(updated.GetBaseCommitId())))+return &gitalypb.CloseReviewResponse{Review: s.withRequirements(updated)}, nil}diff --git a/internal/gitaly/service/review/review_authoritative_test.go b/internal/gitaly/service/review/review_authoritative_test.goindex 5aa9fa9..c345525 100644--- a/internal/gitaly/service/review/review_authoritative_test.go+++ b/internal/gitaly/service/review/review_authoritative_test.go@@ -11,6 +11,7 @@ import ("github.com/feder-cr/git-ai/internal/git/localrepo""github.com/feder-cr/git-ai/internal/gitaly/config""github.com/feder-cr/git-ai/internal/gitaly/service"+ hookservice "github.com/feder-cr/git-ai/internal/gitaly/service/hook""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/grpc/client"@@ -25,17 +26,26 @@ import ()// setupWithStorageCore runs a ReviewService whose storage core is in the given-// mode, on the SQLite database of the test.-func setupWithStorageCore(t *testing.T, mode corestore.Mode) (context.Context, config.Cfg, *corestore.Core, gitalypb.ReviewServiceClient) {+// mode, on the SQLite database of the test. configure, when given, adjusts the+// server before it serves.+func setupWithStorageCore(t *testing.T, mode corestore.Mode, configure ...func(*server)) (context.Context, config.Cfg, *corestore.Core, gitalypb.ReviewServiceClient) {t.Helper()ctx := testhelper.Context(t)cfg := testcfg.Build(t)cfg.Graft.Standalone = true+ // The service writes keep-around references through the+ // reference-transaction hook.+ testcfg.BuildGitalyHooks(t, cfg)core := coretest.Open(t, coretest.Options{Mode: mode})cfg.SocketPath = testserver.RunGitalyServer(t, cfg, func(srv *grpc.Server, deps *service.Dependencies) {- gitalypb.RegisterReviewServiceServer(srv, newServer(deps))+ s := newServer(deps)+ for _, c := range configure {+ c(s)+ }+ gitalypb.RegisterReviewServiceServer(srv, s)+ gitalypb.RegisterHookServiceServer(srv, hookservice.NewServer(deps))}, testserver.WithGraftStorage(core))conn, err := client.New(ctx, cfg.SocketPath)diff --git a/internal/gitaly/service/review/roots.go b/internal/gitaly/service/review/roots.goindex fb0b885..9e9bcca 100644--- a/internal/gitaly/service/review/roots.go+++ b/internal/gitaly/service/review/roots.go@@ -7,125 +7,70 @@ import ("github.com/feder-cr/git-ai/internal/git""github.com/feder-cr/git-ai/internal/git/localrepo""github.com/feder-cr/git-ai/internal/graft/corestore"- "github.com/feder-cr/git-ai/internal/graft/corestore/gitops"+ "github.com/feder-cr/git-ai/internal/graft/corestore/reviewroots""github.com/feder-cr/git-ai/internal/graft/review/store""github.com/feder-cr/git-ai/internal/structerr"- "github.com/feder-cr/git-ai/proto/go/gitalypb")-// maxRootsAttempts bounds the compare-and-swap of REVIEW ROOTS R1: a conflict-// means a checkpoint was recorded between the check and the write, and-// checkpoints are minutes apart at the least.+// maxRootsAttempts bounds the review writes that lose a keep-around reference+// to a concurrent sweep between writing it and recording the review.const maxRootsAttempts = 3-// rootsStore is the review store of authoritative mode (dbreview.Store), where-// a review's commits are roots of the storage core's object graph.-type rootsStore interface {- // Refs returns the references in the storage core and the sequence of the- // snapshot.- Refs() (map[string]corestore.Target, uint64, error)- // WithRootsAt returns the store whose writes require that no checkpoint- // newer than rootsAt was recorded.- WithRootsAt(rootsAt uint64) store.ReviewStore+// requiredRootsStore is the review store of authoritative mode+// (dbreview.Store), which can require a review's roots in the database.+type requiredRootsStore interface {+ WithRequiredRoots() store.ReviewStore}-// rootsCheck checks that commits a write is about to record as a review's-// head or base are reachable from the references of the snapshot the write-// carries.-type rootsCheck func(commits ...git.ObjectID) error+// rootsProtect writes the keep-around references of commits that a review+// write is about to record.+type rootsProtect func(commits ...git.ObjectID) error// writeRoots runs write, a review write that may record new head or base-// commits, under REVIEW ROOTS R1 (doc/graft/PLAN7.md). write calls check for-// the commits it records before it records them. In authoritative mode check-// verifies them against the references of a snapshot (refs, S) of the storage-// core, and write's store refuses the write with ErrReviewRootsStale when a-// checkpoint after S was recorded in between: then a new snapshot is taken and-// write runs again, at most maxRootsAttempts times in all, after which the-// request is Aborted. With the files store (the storage core is off or in-// shadow mode) the commits are not roots of the storage core and check-// accepts them.-func (s *server) writeRoots(ctx context.Context, repoProto *gitalypb.Repository, repo *localrepo.Repo, st store.ReviewStore, write func(store.ReviewStore, rootsCheck) error) error {- rs, ok := st.(rootsStore)- if !ok {- return write(st, func(...git.ObjectID) error { return nil })- }-- for attempt := 0; attempt < maxRootsAttempts; attempt++ {- refs, seq, err := rs.Refs()- switch {- case errors.Is(err, corestore.ErrRepositoryNotFound):- return structerr.NewFailedPrecondition("repository is not imported into the storage core")- case err != nil:- return structerr.NewUnavailable("storage core: %w", err)+// commits, under the REVIEW ROOTS RULE (doc/graft/PLAN7.md). write calls+// protect with the commits it records before it records them, which writes+// their keep-around references through the reference-transaction hook, in+// every mode: local housekeeping keeps what references reach, and in shadow and+// authoritative mode the voter records them and uploads the objects the+// storage core does not have. In authoritative mode the store of write requires+// the references in the database; a sweep that deleted one between the two+// steps makes it fail with ErrReviewRootsMissing, and write runs again (which+// writes the reference again), at most maxRootsAttempts times in all, after+// which the request is Aborted.+func (s *server) writeRoots(ctx context.Context, repo *localrepo.Repo, st store.ReviewStore, write func(store.ReviewStore, rootsProtect) error) error {+ protect := func(commits ...git.ObjectID) error {+ if err := reviewroots.Protect(ctx, repo, commits); err != nil {+ return structerr.NewInternal("protect the commits of the review: %w", err)}-- snapshot := &rootsSnapshot{ctx: ctx, fresh: s.deps.GetGraftStorageSyncer(), repoProto: repoProto, repo: repo, refs: refs}- err = write(rs.WithRootsAt(seq), snapshot.check)- if !errors.Is(err, corestore.ErrReviewRootsStale) {- return err+ if s.rootsProtected != nil {+ s.rootsProtected(ctx, repo, st)}+ return nil}- return structerr.NewAborted("the commits of the review could not be checked against a stable snapshot: checkpoints were recorded concurrently")-}--// rootsSnapshot checks commits against the references of one snapshot, in the-// local repository.-type rootsSnapshot struct {- ctx context.Context- fresh corestore.Freshener- repoProto *gitalypb.Repository- repo *localrepo.Repo- refs map[string]corestore.Target-- // tips are the object IDs the references point to, set once the local- // repository is known to hold them (a write may check more than once: the- // review store calls the write's function again on a version conflict).- tips []git.ObjectID-}--func (r *rootsSnapshot) check(commits ...git.ObjectID) error {- if r.tips == nil {- tips, err := r.localTips()- if err != nil {- return err- }- r.tips = tips+ rs, ok := st.(requiredRootsStore)+ if !ok {+ return write(st, protect)}- for _, commit := range commits {- reachable, err := gitops.IsReachable(r.ctx, r.repo, commit, r.tips)- if err != nil {- return structerr.NewInternal("check the review commit %s: %w", commit, err)- }- if !reachable {- return structerr.NewFailedPrecondition("commit %s of the review is not reachable from the references of the repository in the storage core", commit)+ required := rs.WithRequiredRoots()+ for attempt := 0; attempt < maxRootsAttempts; attempt++ {+ err := write(required, protect)+ if !errors.Is(err, corestore.ErrReviewRootsMissing) {+ return err}}- return nil+ return structerr.NewAborted("the keep-around references of the review's commits were deleted concurrently %d times", maxRootsAttempts)}-// localTips returns the object IDs the snapshot's references point to, after-// making sure the local repository holds them. The gate caught the repository-// up before the request, but a changeset committed since (on another node) can-// be in the snapshot: the repository is then caught up again, to a head read-// after this call, so at least the snapshot's.-func (r *rootsSnapshot) localTips() ([]git.ObjectID, error) {- tips := make([]git.ObjectID, 0, len(r.refs))- for _, target := range r.refs {- if !target.IsSymbolic() {- tips = append(tips, git.ObjectID(target))- }- }-- missing, err := gitops.MissingObjects(r.ctx, r.repo, tips)- if err != nil {- return nil, structerr.NewInternal("look up the references' objects: %w", err)- }- if len(missing) > 0 {- if err := r.fresh.EnsureFresh(r.ctx, r.repoProto); err != nil {- return nil, err- }+// releaseRoots deletes the keep-around references of the commits of a review+// that was just closed, unless another open review uses them. The close is+// already recorded: a reference that cannot be deleted now only keeps its+// objects alive longer, until the next close of a review of the same commit or+// the maintenance sweep of the storage core.+func (s *server) releaseRoots(ctx context.Context, repo *localrepo.Repo, st store.ReviewStore, commits []git.ObjectID) {+ if _, err := reviewroots.Sweep(ctx, repo, st, commits); err != nil {+ s.deps.GetLogger().WithError(err).WithField("commits", commits).WarnContext(ctx,+ "review: the keep-around references of a closed review were not deleted; they keep their objects until a later sweep")}- return tips, nil}diff --git a/internal/gitaly/service/review/roots_test.go b/internal/gitaly/service/review/roots_test.goindex 93b2fd4..23c4e6b 100644--- a/internal/gitaly/service/review/roots_test.go+++ b/internal/gitaly/service/review/roots_test.go@@ -2,10 +2,11 @@ package reviewimport ("context"- "errors""fmt""strings"+ "sync""testing"+ "time""github.com/stretchr/testify/require""google.golang.org/grpc/codes"@@ -13,205 +14,255 @@ import ("github.com/feder-cr/git-ai/internal/git""github.com/feder-cr/git-ai/internal/git/gittest"+ "github.com/feder-cr/git-ai/internal/git/housekeeping"+ housekeepingcfg "github.com/feder-cr/git-ai/internal/git/housekeeping/config""github.com/feder-cr/git-ai/internal/git/localrepo"+ "github.com/feder-cr/git-ai/internal/gitaly/config""github.com/feder-cr/git-ai/internal/gitaly/service"- "github.com/feder-cr/git-ai/internal/gitaly/storage""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/reviewroots""github.com/feder-cr/git-ai/internal/graft/review/store""github.com/feder-cr/git-ai/internal/testhelper"- "github.com/feder-cr/git-ai/internal/testhelper/testcfg""github.com/feder-cr/git-ai/proto/go/gitalypb")-// staleStore is a rootsStore whose first stale writes are refused with-// ErrReviewRootsStale, as when a checkpoint is recorded between the check and-// each of those writes.-type staleStore struct {+// sweptStore is a store that requires the review roots, whose first swept+// writes fail with ErrReviewRootsMissing, as when a sweep deletes the+// keep-around references between their write and the review write.+type sweptStore struct {store.ReviewStore- stale int- // snapshots counts the Refs calls; snapshot n has sequence 10*n.- snapshots int- // rootsAt are the sequences the writes carried, in order.- rootsAt []uint64+ swept, writes int}-func (f *staleStore) Refs() (map[string]corestore.Target, uint64, error) {- f.snapshots++- return map[string]corestore.Target{}, uint64(10 * f.snapshots), nil-}--func (f *staleStore) WithRootsAt(rootsAt uint64) store.ReviewStore {- return &staleWriter{f: f, rootsAt: rootsAt}-}+func (f *sweptStore) WithRequiredRoots() store.ReviewStore { return &sweptWriter{f: f} }-type staleWriter struct {+type sweptWriter struct {store.ReviewStore- f *staleStore- rootsAt uint64+ f *sweptStore}-func (w *staleWriter) Create(r *gitalypb.Review) (*gitalypb.Review, error) {- w.f.rootsAt = append(w.f.rootsAt, w.rootsAt)- if len(w.f.rootsAt) <= w.f.stale {- return nil, fmt.Errorf("insert review: %w", corestore.ErrReviewRootsStale)+func (w *sweptWriter) Create(r *gitalypb.Review) (*gitalypb.Review, error) {+ w.f.writes+++ if w.f.writes <= w.f.swept {+ return nil, fmt.Errorf("insert review: %w", corestore.ErrReviewRootsMissing)}return r, nil}-func TestWriteRootsTakesANewSnapshotAfterAConflict(t *testing.T) {+func TestWriteRootsRetriesAfterASweep(t *testing.T) {ctx := testhelper.Context(t)s := newServer(&service.Dependencies{})for _, tc := range []struct {- desc string- stale int- rootsAt []uint64- code codes.Code+ swept int+ writes int+ code codes.Code}{- {desc: "no conflict", stale: 0, rootsAt: []uint64{10}, code: codes.OK},- {desc: "exactly one conflict", stale: 1, rootsAt: []uint64{10, 20}, code: codes.OK},- {desc: "two conflicts", stale: 2, rootsAt: []uint64{10, 20, 30}, code: codes.OK},- {desc: "attempts exhausted", stale: 3, rootsAt: []uint64{10, 20, 30}, code: codes.Aborted},+ {swept: 0, writes: 1, code: codes.OK},+ {swept: 1, writes: 2, code: codes.OK},+ {swept: 2, writes: 3, code: codes.OK},+ {swept: 3, writes: 3, code: codes.Aborted},} {- t.Run(tc.desc, func(t *testing.T) {- st := &staleStore{stale: tc.stale}- checks := 0- err := s.writeRoots(ctx, nil, nil, st, func(st store.ReviewStore, _ rootsCheck) error {- checks+++ t.Run(fmt.Sprintf("swept %d", tc.swept), func(t *testing.T) {+ st := &sweptStore{swept: tc.swept}+ err := s.writeRoots(ctx, nil, st, func(st store.ReviewStore, _ rootsProtect) error {_, err := st.Create(&gitalypb.Review{})return err})require.Equal(t, tc.code, status.Code(err), "%v", err)- require.Equal(t, tc.rootsAt, st.rootsAt, "every attempt writes with its own snapshot")- require.Equal(t, len(tc.rootsAt), st.snapshots)- require.Equal(t, len(tc.rootsAt), checks, "every attempt checks again")+ require.Equal(t, tc.writes, st.writes, "every attempt writes again")})}- t.Run("other errors end the write", func(t *testing.T) {- st := &staleStore{}- broken := errors.New("database is down")- err := s.writeRoots(ctx, nil, nil, st, func(store.ReviewStore, rootsCheck) error { return broken })- require.ErrorIs(t, err, broken)- require.Equal(t, 1, st.snapshots)- })-- // The files store holds no storage core roots: nothing is checked.- t.Run("files store", func(t *testing.T) {- files := store.Open(t.TempDir())- err := s.writeRoots(ctx, nil, nil, files, func(st store.ReviewStore, check rootsCheck) error {- require.Same(t, files, st)- return check(git.ObjectID("not even an object ID"))- })- require.NoError(t, err)- })+ // The files store does not require the roots in a database.+ files := store.Open(t.TempDir())+ require.NoError(t, s.writeRoots(ctx, nil, files, func(st store.ReviewStore, _ rootsProtect) error {+ require.Same(t, files, st)+ return nil+ }))}-// countingFreshener counts EnsureFresh calls.-type countingFreshener struct {- corestore.NopFreshener- calls int-}+// housekeep runs the object housekeeping of Gitaly on the repository with an+// expiry of now: a full repack that drops unreachable objects into an expired+// cruft pack, then a prune of the unreachable loose objects. Production+// housekeeping does the same with a grace period of two weeks.+func housekeep(t *testing.T, cfg config.Cfg, repo *gitalypb.Repository) {+ t.Helper()-func (f *countingFreshener) EnsureFresh(context.Context, storage.Repository) error {- f.calls++- return nil+ ctx := testhelper.Context(t)+ local := localrepo.NewTestRepo(t, cfg, repo)+ now := time.Now()+ require.NoError(t, housekeeping.RepackObjects(ctx, local, housekeepingcfg.RepackObjectsConfig{+ Strategy: housekeepingcfg.RepackObjectsStrategyFullWithCruft,+ CruftExpireBefore: now,+ }))+ require.NoError(t, housekeeping.PruneObjects(ctx, local, housekeeping.PruneObjectsConfig{ExpireBefore: now}))}-func TestRootsCheckReachability(t *testing.T) {- ctx := testhelper.Context(t)- cfg := testcfg.Build(t)- repoProto, repoPath := gittest.CreateRepository(t, ctx, cfg, gittest.CreateRepositoryConfig{SkipCreationViaService: true})- repo := localrepo.NewTestRepo(t, cfg, repoProto)+func hasObject(t *testing.T, cfg config.Cfg, repoPath string, oid git.ObjectID) bool {+ t.Helper()+ return gittest.NewCommand(t, cfg, "-C", repoPath, "cat-file", "-e", oid.String()).Run() == nil+}- base := gittest.WriteCommit(t, cfg, repoPath, gittest.WithMessage("base"))- head := gittest.WriteCommit(t, cfg, repoPath, gittest.WithMessage("head"), gittest.WithParents(base))- unreachable := gittest.WriteCommit(t, cfg, repoPath, gittest.WithMessage("unreachable"), gittest.WithParents(base))- unrelated := gittest.WriteCommit(t, cfg, repoPath, gittest.WithMessage("unrelated"))+// keepArounds returns the keep-around references of the repository in the+// database.+func keepArounds(t *testing.T, ctx context.Context, core *corestore.Core, repoID int64) map[string]corestore.Target {+ t.Helper()- snapshot := func(fresh corestore.Freshener, refs map[string]corestore.Target) *rootsSnapshot {- return &rootsSnapshot{ctx: ctx, fresh: fresh, repoProto: repoProto, repo: repo, refs: refs}- }- refs := map[string]corestore.Target{- "HEAD": corestore.SymbolicTarget("refs/heads/main"),- "refs/heads/main": corestore.Target(head),+ refs, _, err := core.Meta.Refs(ctx, repoID)+ require.NoError(t, err)+ kept := map[string]corestore.Target{}+ for name, target := range refs {+ if strings.HasPrefix(name, corestore.KeepAroundPrefix) {+ kept[name] = target+ }}+ return kept+}- fresh := &countingFreshener{}- s := snapshot(fresh, refs)- require.NoError(t, s.check(head, base))- for _, commit := range []git.ObjectID{unreachable, unrelated} {- err := s.check(head, commit)- require.Equal(t, codes.FailedPrecondition, status.Code(err), "%v", err)- require.ErrorContains(t, err, commit.String())+func keepAroundOf(commits ...git.ObjectID) map[string]corestore.Target {+ kept := map[string]corestore.Target{}+ for _, c := range commits {+ kept[corestore.KeepAroundRef(c.String())] = corestore.Target(c)}- require.Zero(t, fresh.calls, "every tip is local: no catch-up")-- // No reference reaches anything.- err := snapshot(fresh, map[string]corestore.Target{"HEAD": corestore.SymbolicTarget("refs/heads/main")}).check(base)- require.Equal(t, codes.FailedPrecondition, status.Code(err), "%v", err)-- // A tip the local repository does not have yet (committed on another node- // after the gate caught it up): the repository is caught up before the- // check. The counting Freshener does not bring the object, so the check- // then fails as Internal: a Freshener that returns nil must have brought- // every object of the snapshot.- absent := git.ObjectID(strings.Repeat("a", gittest.DefaultObjectHash.EncodedLen()))- err = snapshot(fresh, map[string]corestore.Target{"refs/heads/other": corestore.Target(absent)}).check(base)- require.Equal(t, 1, fresh.calls)- require.Equal(t, codes.Internal, status.Code(err), "%v", err)+ return kept}-// TestAuthoritativeReviewCommitsMustBeReachable is REVIEW ROOTS R1 end to end:-// a review cannot be created on, or moved to, a commit that the references in-// the storage core do not reach, even when the local repository has it.-func TestAuthoritativeReviewCommitsMustBeReachable(t *testing.T) {+// TestAuthoritativeReviewRootsAreReferences: in authoritative mode a review+// write records keep-around references of its commits in the storage core,+// also for a commit that only the serving node had, and a close deletes those+// that no other open review uses (doc/graft/PLAN7.md, REVIEW ROOTS RULE).+func TestAuthoritativeReviewRootsAreReferences(t *testing.T) {ctx, cfg, core, client := setupAuthoritative(t)repo, repoPath := createLocalRepository(t, ctx, cfg)base := gittest.WriteCommit(t, cfg, repoPath, gittest.WithMessage("base"), gittest.WithBranch("main"))- head := gittest.WriteCommit(t, cfg, repoPath, gittest.WithMessage("head"), gittest.WithParents(base), gittest.WithBranch("feature"))tracked := importRepository(t, cfg, core, repo, repoPath, coretest.ImportOptions{})// The first request lets the gate replace the imported copy by a cache built- // from the storage core; a commit written into that cache afterwards is only- // in the local repository, never recorded in the storage core.+ // from the storage core; commits written into that cache afterwards are only+ // on this node.require.Empty(t, listStoredReviews(t, ctx, client, repo, true))- local := gittest.WriteCommit(t, cfg, repoPath, gittest.WithMessage("local only"), gittest.WithParents(base))- _, err := client.CreateReview(ctx, &gitalypb.CreateReviewRequest{- Repository: repo,- TargetBranch: []byte("main"),- HeadCommitId: local.String(),- })- require.Equal(t, codes.FailedPrecondition, status.Code(err), "%v", err)- reviews, err := core.Meta.ListReviews(ctx, tracked.ID, "", true, 0)+ head := gittest.WriteCommit(t, cfg, repoPath, gittest.WithMessage("head"), gittest.WithParents(base))+ next := gittest.WriteCommit(t, cfg, repoPath, gittest.WithMessage("next"), gittest.WithParents(head))++ first, err := client.CreateReview(ctx, &gitalypb.CreateReviewRequest{Repository: repo, TargetBranch: []byte("main"), HeadCommitId: head.String()})+ require.NoError(t, err)+ require.Equal(t, keepAroundOf(head, base), keepArounds(t, ctx, core, tracked.ID))+ second, err := client.CreateReview(ctx, &gitalypb.CreateReviewRequest{Repository: repo, TargetBranch: []byte("main"), HeadCommitId: head.String()})require.NoError(t, err)- require.Empty(t, reviews)- created, err := client.CreateReview(ctx, &gitalypb.CreateReviewRequest{- Repository: repo,- TargetBranch: []byte("main"),- HeadCommitId: head.String(),- })+ // A head move references the new head; the old one is still the second+ // review's.+ _, err = client.UpdateReview(ctx, &gitalypb.UpdateReviewRequest{Repository: repo, Id: first.GetReview().GetId(), HeadCommitId: next.String()})require.NoError(t, err)- id := created.GetReview().GetId()+ require.Equal(t, keepAroundOf(head, next, base), keepArounds(t, ctx, core, tracked.ID))- _, err = client.UpdateReview(ctx, &gitalypb.UpdateReviewRequest{- Repository: repo,- Id: id,- HeadCommitId: local.String(),- })- require.Equal(t, codes.FailedPrecondition, status.Code(err), "%v", err)- stored, _, err := core.Meta.GetReview(ctx, tracked.ID, id)+ // Closing the first review releases only what no open review uses.+ _, err = client.CloseReview(ctx, &gitalypb.CloseReviewRequest{Repository: repo, Id: first.GetReview().GetId()})require.NoError(t, err)- require.Equal(t, head.String(), stored.GetHeadCommitId(), "the head did not move")+ require.Equal(t, keepAroundOf(head, base), keepArounds(t, ctx, core, tracked.ID))+ _, err = client.CloseReview(ctx, &gitalypb.CloseReviewRequest{Repository: repo, Id: second.GetReview().GetId(), Landed: true})+ require.NoError(t, err)+ require.Empty(t, keepArounds(t, ctx, core, tracked.ID))+}++// TestAuthoritativeReviewWriteSurvivesASweep: a maintenance sweep that deletes+// the keep-around references between their write and the review write makes+// the write fail in the database (ErrReviewRootsMissing), and the service+// writes them again; after maxRootsAttempts such sweeps the request is+// Aborted and nothing is recorded.+func TestAuthoritativeReviewWriteSurvivesASweep(t *testing.T) {+ for _, tc := range []struct {+ desc string+ sweeps int+ code codes.Code+ }{+ {desc: "one sweep", sweeps: 1, code: codes.OK},+ {desc: "every attempt swept", sweeps: maxRootsAttempts, code: codes.Aborted},+ } {+ t.Run(tc.desc, func(t *testing.T) {+ var (+ mu sync.Mutex+ protects int+ deleted int+ sweepErr error+ )+ ctx, cfg, core, client := setupWithStorageCore(t, corestore.ModeAuthoritative, func(s *server) {+ s.rootsProtected = func(ctx context.Context, repo *localrepo.Repo, st store.ReviewStore) {+ mu.Lock()+ defer mu.Unlock()+ protects+++ if protects > tc.sweeps {+ return+ }+ report, err := reviewroots.Sweep(ctx, repo, st, nil)+ deleted += report.Deleted+ if err != nil && sweepErr == nil {+ sweepErr = err+ }+ }+ })++ repo, repoPath := createLocalRepository(t, ctx, cfg)+ base := gittest.WriteCommit(t, cfg, repoPath, gittest.WithMessage("base"), gittest.WithBranch("main"))+ head := gittest.WriteCommit(t, cfg, repoPath, gittest.WithMessage("head"), gittest.WithParents(base), gittest.WithBranch("feature"))+ tracked := importRepository(t, cfg, core, repo, repoPath, coretest.ImportOptions{})++ _, err := client.CreateReview(ctx, &gitalypb.CreateReviewRequest{Repository: repo, TargetBranch: []byte("main"), HeadCommitId: head.String()})+ require.Equal(t, tc.code, status.Code(err), "%v", err)++ mu.Lock()+ defer mu.Unlock()+ require.NoError(t, sweepErr)+ require.Equal(t, 2*tc.sweeps, deleted, "every sweep deleted the head's and the base's reference")- // An update that keeps the head moves no commit and is not checked.- _, err = client.UpdateReview(ctx, &gitalypb.UpdateReviewRequest{- Repository: repo,- Id: id,- HeadCommitId: head.String(),+ reviews, err := core.Meta.ListReviews(ctx, tracked.ID, "", true, 0)+ require.NoError(t, err)+ if tc.code == codes.OK {+ require.Equal(t, tc.sweeps+1, protects)+ require.Len(t, reviews, 1)+ require.Equal(t, keepAroundOf(head, base), keepArounds(t, ctx, core, tracked.ID))+ } else {+ require.Equal(t, maxRootsAttempts, protects)+ require.Empty(t, reviews, "nothing is recorded")+ }+ })+ }+}++// TestReviewRootsOutsideAuthoritativeMode: with the storage core off or in+// shadow mode the reviews are files, and the service still writes the+// keep-around references: housekeeping keeps an open review's commit after its+// branch is deleted. In shadow mode the voter records the references in the+// database, which does not require them (the files are the source of truth).+func TestReviewRootsOutsideAuthoritativeMode(t *testing.T) {+ t.Run("off", func(t *testing.T) {+ h := setupHarness(t)+ base, head := h.fixture(codeV2)+ gittest.WriteRef(t, h.cfg, h.repoPath, "refs/heads/feature", head)+ h.create(head)+ gittest.Exec(t, h.cfg, "-C", h.repoPath, "update-ref", "-d", "refs/heads/feature")++ housekeep(t, h.cfg, h.repo)+ require.True(t, hasObject(t, h.cfg, h.repoPath, head))+ require.True(t, hasObject(t, h.cfg, h.repoPath, base))+ })++ t.Run("shadow", func(t *testing.T) {+ ctx, cfg, core, client := setupWithStorageCore(t, corestore.ModeShadow)+ repo, repoPath := createLocalRepository(t, ctx, cfg)+ base := gittest.WriteCommit(t, cfg, repoPath, gittest.WithMessage("base"), gittest.WithBranch("main"))+ head := gittest.WriteCommit(t, cfg, repoPath, gittest.WithMessage("head"), gittest.WithParents(base), gittest.WithBranch("feature"))+ tracked := importRepository(t, cfg, core, repo, repoPath, coretest.ImportOptions{})++ _, err := client.CreateReview(ctx, &gitalypb.CreateReviewRequest{Repository: repo, TargetBranch: []byte("main"), HeadCommitId: head.String()})+ require.NoError(t, err)+ require.Equal(t, keepAroundOf(head, base), keepArounds(t, ctx, core, tracked.ID), "the voter records the references")+ gittest.Exec(t, cfg, "-C", repoPath, "update-ref", "-d", "refs/heads/feature")++ housekeep(t, cfg, repo)+ require.True(t, hasObject(t, cfg, repoPath, head))})- require.NoError(t, err)}diff --git a/internal/gitaly/service/review/server.go b/internal/gitaly/service/review/server.goindex f5cedcf..13cae1a 100644--- a/internal/gitaly/service/review/server.go+++ b/internal/gitaly/service/review/server.go@@ -34,6 +34,11 @@ const (type server struct {gitalypb.UnimplementedReviewServiceServerdeps *service.Dependencies++ // rootsProtected, when set by a test, is called after the keep-around+ // references of a review write were written and before the review is+ // recorded. Nil in production.+ rootsProtected func(ctx context.Context, repo *localrepo.Repo, st store.ReviewStore)}// NewServer creates a new instance of the ReviewService server.diff --git a/internal/graft/corestore/checkpoint/checkpoint.go b/internal/graft/corestore/checkpoint/checkpoint.goindex d08adc5..4388836 100644--- a/internal/graft/corestore/checkpoint/checkpoint.go+++ b/internal/graft/corestore/checkpoint/checkpoint.go@@ -1,9 +1,10 @@// Package checkpoint consolidates the history of a repository in the storage// core: a checkpoint at sequence N is one self-contained pack of every object-// reachable from the references at N and from the open reviews' commits, with-// the reference snapshot at N, so that hydration starts from it instead of-// changeset 1 and garbage collection can delete the packs it covers-// (doc/graft/PLAN7.md, "Checkpoint creation", binding).+// reachable from the references at N, with the reference snapshot at N, so that+// hydration starts from it instead of changeset 1 and garbage collection can+// delete the packs it covers (doc/graft/PLAN7.md, "Checkpoint creation",+// binding). The open reviews' commits are references too (their keep-around+// references, REVIEW ROOTS RULE), so the references are the whole closure.//// The build reads the database, catches the local repository up (EnsureFresh)// and packs from it; it holds no reference lock and never blocks or fails a@@ -20,8 +21,6 @@ import ("slices""time"- "github.com/prometheus/client_golang/prometheus"-"github.com/feder-cr/git-ai/internal/git""github.com/feder-cr/git-ai/internal/git/localrepo""github.com/feder-cr/git-ai/internal/gitaly/storage"@@ -34,10 +33,6 @@ import (// Fault points of a build, for crash injection in tests.const (- // PointAfterSnapshot is reached when the reference snapshot is read and the- // open reviews are not yet: a review written here has a snapshot greater- // than the checkpoint's sequence.- PointAfterSnapshot = "after_snapshot"// PointAfterUpload is reached when the pack is uploaded and no row// references it yet.PointAfterUpload = "after_upload"@@ -56,12 +51,8 @@ type Checkpointer struct {// faultHook, when set by a test, is called at the fault points; an error it// returns ends the build there, as a crash would. Nil in production.faultHook func(point string) error-- reviewObjectsMissing prometheus.Counter}-var _ prometheus.Collector = (*Checkpointer)(nil)-// New returns the checkpointer of core. fresh catches the local repositories// up before a build.func New(core *corestore.Core, logger log.Logger, locator storage.Locator, repoFactory localrepo.Factory, fresh corestore.Freshener) *Checkpointer {@@ -71,32 +62,16 @@ func New(core *corestore.Core, logger log.Logger, locator storage.Locator, repoFlocator: locator,repoFactory: repoFactory,fresh: fresh,- reviewObjectsMissing: prometheus.NewCounter(prometheus.CounterOpts{- Name: "graft_storage_checkpoint_review_objects_missing_total",- Help: "Number of checkpoint builds refused because a commit of an open review is missing from the local repository.",- }),}}-// Describe implements prometheus.Collector.-func (c *Checkpointer) Describe(descs chan<- *prometheus.Desc) {- c.reviewObjectsMissing.Describe(descs)-}--// Collect implements prometheus.Collector.-func (c *Checkpointer) Collect(metrics chan<- prometheus.Metric) {- c.reviewObjectsMissing.Collect(metrics)-}-// Create builds a checkpoint of repo at the current database head and records// it. created is false, with the existing checkpoint, when a checkpoint at the// head exists already, and false with a zero Checkpoint when the repository has-// no object to consolidate (every reference is symbolic and no review is-// open). The errors carry gRPC codes: FailedPrecondition outside authoritative-// mode, for an incomplete import, for an open review whose commits are missing-// locally (metadata review_id) and for reviews that changed during the build;-// NotFound for an untracked repository; Unavailable for the database and the-// bucket; Internal for a broken invariant.+// no object to consolidate (every reference is symbolic). The errors carry gRPC+// codes: FailedPrecondition outside authoritative mode and for an incomplete+// import; NotFound for an untracked repository; Unavailable for the database+// and the bucket; Internal for a broken invariant.func (c *Checkpointer) Create(ctx context.Context, repo *gitalypb.Repository) (corestore.Checkpoint, bool, error) {if !c.core.Authoritative() {return corestore.Checkpoint{}, false, structerr.NewFailedPrecondition("checkpoints are created in authoritative mode only")@@ -128,36 +103,23 @@ func (c *Checkpointer) Create(ctx context.Context, repo *gitalypb.Repository) (cif ok && newest.Seq == seq {return newest, false, nil}- if err := c.fault(PointAfterSnapshot); err != nil {- return corestore.Checkpoint{}, false, err- }- // The local repository may not exist before step 3 (EnsureFresh hydrates+ // The local repository may not exist before step 2 (EnsureFresh hydrates// it in the format of the record).hash, err := git.ObjectHashByFormat(record.ObjectFormat)if err != nil {return corestore.Checkpoint{}, false, structerr.NewInternal("object format of the repository in the storage core: %w", err)}-- // Step 2: the open reviews' commits (the roots), read after the snapshot,- // then the head H. Every review read was written after its own check at a- // snapshot S <= H (REVIEW ROOTS R1), so after step 3 the local repository- // holds its commits, even those that changesets after N brought in.- roots, err := c.reviewRoots(ctx, record.ID, hash)+ tips, err := objectTips(refs, hash)if err != nil {return corestore.Checkpoint{}, false, err}- current, err := c.core.Meta.GetRepository(ctx, key)- if err != nil {- return corestore.Checkpoint{}, false, errRepository(err)- }- if current.ID != record.ID {- return corestore.Checkpoint{}, false, errRemoved()+ if len(tips) == 0 {+ return corestore.Checkpoint{}, false, nil}- head := current.HeadSeq- // Step 3 (change D): catch the local repository up to a head read after- // the call, so at least H.+ // Step 2 (change D): catch the local repository up to a head read after+ // the call, so at least N.if err := c.fresh.EnsureFresh(ctx, repo); err != nil {return corestore.Checkpoint{}, false, err}@@ -165,32 +127,16 @@ func (c *Checkpointer) Create(ctx context.Context, repo *gitalypb.Repository) (cif err != nil {return corestore.Checkpoint{}, false, structerr.NewInternal("read the local watermark: %w", err)}- if !ok || wm.RepoID != record.ID || wm.Seq < head {+ if !ok || wm.RepoID != record.ID || wm.Seq < seq {// EnsureFresh succeeded, so the local repository is at a head read after// this call arrived: anything else breaks the Freshener contract.- return corestore.Checkpoint{}, false, structerr.NewInternal("the local repository is not caught up after EnsureFresh: watermark %+v (present %t), repository %d at head %d",- wm, ok, record.ID, head)+ return corestore.Checkpoint{}, false, structerr.NewInternal("the local repository is not caught up after EnsureFresh: watermark %+v (present %t), repository %d at changeset %d",+ wm, ok, record.ID, seq)}- // Step 4: every object is present, or a precise error and nothing built.+ // Step 3. After EnsureFresh the local repository holds every object of the+ // snapshot; a missing one fails the build (never a partial pack).local := c.repoFactory.Build(repo)- refTips, err := objectTips(refs, hash)- if err != nil {- return corestore.Checkpoint{}, false, err- }- tips := append(slices.Clone(refTips), roots.commits()...)- missing, err := gitops.MissingObjects(ctx, local, tips)- if err != nil {- return corestore.Checkpoint{}, false, structerr.NewInternal("look up the objects: %w", err)- }- if err := c.checkMissing(ctx, logger, refTips, roots, missing); err != nil {- return corestore.Checkpoint{}, false, err- }-- // Step 5.- if len(tips) == 0 {- return corestore.Checkpoint{}, false, nil- }tmpDir, err := c.tempDir(repo.GetStorageName())if err != nil {return corestore.Checkpoint{}, false, structerr.NewInternal("temporary directory: %w", err)@@ -205,10 +151,10 @@ func (c *Checkpointer) Create(ctx context.Context, repo *gitalypb.Repository) (c}}()- // Step 6: the write deadline starts at a read of the record taken right+ // Step 4: the write deadline starts at a read of the record taken right// before the upload (PACK OWNERSHIP RULE 4).readAt := time.Now()- current, err = c.core.Meta.GetRepository(ctx, key)+ current, err := c.core.Meta.GetRepository(ctx, key)if err != nil {return corestore.Checkpoint{}, false, errRepository(err)}@@ -230,7 +176,7 @@ func (c *Checkpointer) Create(ctx context.Context, repo *gitalypb.Repository) (creturn corestore.Checkpoint{}, false, err}- // Step 7.+ // Step 5.commitCtx, cancel, err := upload.CommitContext(ctx)if err != nil {return corestore.Checkpoint{}, false, structerr.NewUnavailable("%w", err)@@ -242,12 +188,8 @@ func (c *Checkpointer) Create(ctx context.Context, repo *gitalypb.Repository) (cRefs: refs,PackKey: upload.Key,PackBytes: upload.Bytes,- Roots: roots.strings(),})- switch {- case errors.Is(err, corestore.ErrCheckpointRootsChanged):- return corestore.Checkpoint{}, false, structerr.NewFailedPrecondition("the reviews changed during the checkpoint build, run it again: %w", err)- case err != nil:+ if err != nil {return corestore.Checkpoint{}, false, errRepository(err)}if err := c.fault(PointAfterCommit); err != nil {@@ -264,96 +206,6 @@ func (c *Checkpointer) Create(ctx context.Context, repo *gitalypb.Repository) (creturn cp, created, nil}-// root is a commit of an open review.-type root struct {- reviewID string- commit git.ObjectID-}--// rootSet is the root set of a build: the head and base commits of the open-// reviews, in the order read.-type rootSet []root--func (s rootSet) commits() []git.ObjectID {- commits := make([]git.ObjectID, 0, len(s))- for _, r := range s {- commits = append(commits, r.commit)- }- return commits-}--func (s rootSet) strings() []string {- commits := make([]string, 0, len(s))- for _, r := range s {- commits = append(commits, r.commit.String())- }- return commits-}--// reviewRoots reads the open reviews of the repository and returns their head-// and base commits; empty values are skipped. A commit that is not an object-// ID of the repository's hash cannot be packed, so the build is refused like-// one that is missing.-func (c *Checkpointer) reviewRoots(ctx context.Context, repoID int64, hash git.ObjectHash) (rootSet, error) {- reviews, err := c.core.Meta.ListReviews(ctx, repoID, "", false, 0)- if err != nil {- return nil, errRepository(err)- }-- var roots rootSet- var invalid []string- for _, review := range reviews {- for _, commit := range []string{review.GetHeadCommitId(), review.GetBaseCommitId()} {- if commit == "" {- continue- }- if err := hash.ValidateHex(commit); err != nil {- invalid = append(invalid, review.GetId())- continue- }- roots = append(roots, root{reviewID: review.GetId(), commit: git.ObjectID(commit)})- }- }- if len(invalid) > 0 {- c.reviewObjectsMissing.Inc()- return nil, structerr.NewFailedPrecondition("open reviews %v have a commit that is not an object ID of the repository; close them to create a checkpoint", invalid).- WithMetadata("review_id", invalid)- }- return roots, nil-}--// checkMissing turns the objects missing from the local repository into the-// error of the build. A missing reference tip is impossible after EnsureFresh-// (Internal). A missing review commit belongs to a review written without the-// R1 check (created before phase 7, or imported from the shadow-mode files):-// FailedPrecondition naming the reviews.-func (c *Checkpointer) checkMissing(ctx context.Context, logger log.Logger, refTips []git.ObjectID, roots rootSet, missing []git.ObjectID) error {- if len(missing) == 0 {- return nil- }-- absent := make(map[git.ObjectID]struct{}, len(missing))- for _, oid := range missing {- absent[oid] = struct{}{}- }- for _, tip := range refTips {- if _, ok := absent[tip]; ok {- return structerr.NewInternal("object %s of a reference is missing from the local repository after EnsureFresh", tip)- }- }-- var reviewIDs []string- for _, r := range roots {- if _, ok := absent[r.commit]; ok && !slices.Contains(reviewIDs, r.reviewID) {- reviewIDs = append(reviewIDs, r.reviewID)- }- }- c.reviewObjectsMissing.Inc()- logger.WithField("review_id", reviewIDs).WarnContext(ctx, "storage core: a checkpoint is refused: commits of open reviews are missing")- return structerr.NewFailedPrecondition("commits of open reviews %v are missing from the repository; close them to create a checkpoint", reviewIDs).- WithMetadata("review_id", reviewIDs)-}-// objectTips returns the object IDs the references point to (symbolic// references are skipped), each validated against the repository's hash.func objectTips(refs map[string]corestore.Target, hash git.ObjectHash) ([]git.ObjectID, error) {diff --git a/internal/graft/corestore/checkpoint/checkpoint_test.go b/internal/graft/corestore/checkpoint/checkpoint_test.goindex a85dae8..42bc9a0 100644--- a/internal/graft/corestore/checkpoint/checkpoint_test.go+++ b/internal/graft/corestore/checkpoint/checkpoint_test.go@@ -9,7 +9,6 @@ import ("testing""time"- "github.com/prometheus/client_golang/prometheus""github.com/stretchr/testify/require""google.golang.org/grpc/codes""google.golang.org/grpc/status"@@ -27,7 +26,6 @@ import ("github.com/feder-cr/git-ai/internal/graft/corestore/sqlstore""github.com/feder-cr/git-ai/internal/graft/corestore/syncer""github.com/feder-cr/git-ai/internal/log"- "github.com/feder-cr/git-ai/internal/structerr""github.com/feder-cr/git-ai/internal/testhelper""github.com/feder-cr/git-ai/internal/testhelper/testcfg""github.com/feder-cr/git-ai/proto/go/gitalypb"@@ -211,23 +209,6 @@ func (e *env) setRef(t *testing.T, id int64, src source, name string, old, new g}, tips...).Seq}-// review records a review of head on base, open unless state says otherwise.-func (e *env) review(t *testing.T, id int64, head, base git.ObjectID, state gitalypb.Review_State) *gitalypb.Review {- t.Helper()-- r, err := e.core.Meta.InsertReview(e.ctx, id, func(reviewID string) (*gitalypb.Review, error) {- return &gitalypb.Review{- Id: reviewID,- TargetBranch: []byte("main"),- HeadCommitId: head.String(),- BaseCommitId: base.String(),- State: state,- }, nil- }, 0)- require.NoError(t, err)- return r-}-func (e *env) head(t *testing.T) uint64 {t.Helper()@@ -318,21 +299,6 @@ func hasObject(t *testing.T, cfg config.Cfg, path string, oid git.ObjectID) boolreturn gittest.NewCommand(t, cfg, "-C", path, "cat-file", "-e", oid.String()).Run() == nil}-func missingCount(t *testing.T, c *checkpoint.Checkpointer) float64 {- t.Helper()-- reg := prometheus.NewPedanticRegistry()- require.NoError(t, reg.Register(c))- families, err := reg.Gather()- require.NoError(t, err)- for _, family := range families {- if family.GetName() == "graft_storage_checkpoint_review_objects_missing_total" {- return family.GetMetric()[0].GetCounter().GetValue()- }- }- return 0-}-func TestCreate(t *testing.T) {forEachDialect(t, func(t *testing.T, dialect sqlstore.Dialect) {e := newEnv(t, envOptions{dialect: dialect})@@ -387,31 +353,30 @@ func TestCreate(t *testing.T) {})}-func TestCreateKeepsOpenReviewCommits(t *testing.T) {+// TestCreateKeepsKeepAroundCommits: the commits of open reviews are kept by+// their keep-around references (REVIEW ROOTS RULE), which the checkpoint+// closure covers like every reference; a commit whose reference was swept is+// not kept.+func TestCreateKeepsKeepAroundCommits(t *testing.T) {forEachDialect(t, func(t *testing.T, dialect sqlstore.Dialect) {e := newEnv(t, envOptions{dialect: dialect})src := e.newSource(t)c1 := e.commit(t, src, "c1")repo := e.register(t, src, c1)- open := e.commit(t, src, "open review", c1)- e.setRef(t, repo.ID, src, "refs/heads/open", "", open)- e.review(t, repo.ID, open, c1, gitalypb.Review_STATE_OPEN_UNSPECIFIED)- closed := e.commit(t, src, "closed review", c1)- e.setRef(t, repo.ID, src, "refs/heads/closed", "", closed)- e.review(t, repo.ID, closed, c1, gitalypb.Review_STATE_CLOSED)-- // Neither commit is reachable from a reference any more.- e.setRef(t, repo.ID, src, "refs/heads/open", open, "")- e.setRef(t, repo.ID, src, "refs/heads/closed", closed, "")+ kept := e.commit(t, src, "open review", c1)+ e.setRef(t, repo.ID, src, corestore.KeepAroundRef(kept.String()), "", kept)+ swept := e.commit(t, src, "closed review", c1)+ e.setRef(t, repo.ID, src, corestore.KeepAroundRef(swept.String()), "", swept)+ e.setRef(t, repo.ID, src, corestore.KeepAroundRef(swept.String()), swept, "")cp, created, err := e.cp.Create(e.ctx, e.pbRepo())require.NoError(t, err)require.True(t, created)path := e.restore(t, cp)- require.True(t, hasObject(t, e.cfg, path, open), "an open review's commit is a root of the checkpoint")- require.False(t, hasObject(t, e.cfg, path, closed), "a closed review's commit is not (documented limit)")+ require.True(t, hasObject(t, e.cfg, path, kept))+ require.False(t, hasObject(t, e.cfg, path, swept))})}@@ -443,115 +408,11 @@ func TestCreateOnALaggingCopy(t *testing.T) {})}-// TestCreateIncludesAReviewWrittenAfterTheSnapshot is the third review's case:-// a review written after the reference snapshot N, at S > N, on a commit that-// only the changesets after N bring and that no reference reaches any more. The-// building node is below S; the build catches it up to the head and packs the-// commit.-func TestCreateIncludesAReviewWrittenAfterTheSnapshot(t *testing.T) {- forEachDialect(t, func(t *testing.T, dialect sqlstore.Dialect) {- a := newEnv(t, envOptions{dialect: dialect})- b := a.secondNode(t, dialect)- src := a.newSource(t)- c1 := a.commit(t, src, "c1")- repo := a.register(t, src, c1)- require.NoError(t, b.sy.EnsureFresh(b.ctx, b.pbRepo()))-- feature := a.commit(t, src, "feature", c1)- checkpoint.SetFaultHook(b.cp, func(point string) error {- if point == checkpoint.PointAfterSnapshot {- a.setRef(t, repo.ID, src, "refs/heads/feature", "", feature)- a.review(t, repo.ID, feature, c1, gitalypb.Review_STATE_OPEN_UNSPECIFIED)- a.setRef(t, repo.ID, src, "refs/heads/feature", feature, "")- }- return nil- })-- cp, created, err := b.cp.Create(b.ctx, b.pbRepo())- require.NoError(t, err)- require.True(t, created)- require.Equal(t, uint64(1), cp.Seq, "the snapshot was read before the review")- require.Equal(t, corestore.Watermark{RepoID: repo.ID, Seq: 3}, b.watermark(t))-- path := b.restore(t, cp)- require.True(t, hasObject(t, b.cfg, path, feature))- })-}--func TestCreateRefusesMissingReviewCommits(t *testing.T) {- forEachDialect(t, func(t *testing.T, dialect sqlstore.Dialect) {- e := newEnv(t, envOptions{dialect: dialect})- src := e.newSource(t)- c1 := e.commit(t, src, "c1")- repo := e.register(t, src, c1)-- // A review written without the R1 check, on a commit the storage core- // never received.- pruned := e.commit(t, src, "never pushed", c1)- r := e.review(t, repo.ID, pruned, c1, gitalypb.Review_STATE_OPEN_UNSPECIFIED)- before := e.packKeys(t, repo.ID)-- _, _, err := e.cp.Create(e.ctx, e.pbRepo())- require.Equal(t, codes.FailedPrecondition, status.Code(err), "%v", err)- require.Equal(t, []string{r.GetId()}, structerr.ExtractMetadata(err)["review_id"])- require.Equal(t, float64(1), missingCount(t, e.cp))- require.Equal(t, before, e.packKeys(t, repo.ID), "nothing is uploaded")- _, ok, err := e.core.Meta.NewestCheckpoint(e.ctx, repo.ID)- require.NoError(t, err)- require.False(t, ok)-- // Closing the review resolves it.- stored, version, err := e.core.Meta.GetReview(e.ctx, repo.ID, r.GetId())- require.NoError(t, err)- stored.State = gitalypb.Review_STATE_CLOSED- require.NoError(t, e.core.Meta.UpdateReview(e.ctx, repo.ID, r.GetId(), version, stored, 0))- _, created, err := e.cp.Create(e.ctx, e.pbRepo())- require.NoError(t, err)- require.True(t, created)- })-}--// TestCreateRefusesReviewsChangedDuringTheBuild is REVIEW ROOTS R2.-func TestCreateRefusesReviewsChangedDuringTheBuild(t *testing.T) {- forEachDialect(t, func(t *testing.T, dialect sqlstore.Dialect) {- e := newEnv(t, envOptions{dialect: dialect})- src := e.newSource(t)- c1 := e.commit(t, src, "c1")- repo := e.register(t, src, c1)- c2 := e.commit(t, src, "c2", c1)- e.setRef(t, repo.ID, src, "refs/heads/main", c1, c2)- before := e.packKeys(t, repo.ID)-- checkpoint.SetFaultHook(e.cp, func(point string) error {- if point == checkpoint.PointAfterUpload {- e.review(t, repo.ID, c2, c1, gitalypb.Review_STATE_OPEN_UNSPECIFIED)- }- return nil- })- _, _, err := e.cp.Create(e.ctx, e.pbRepo())- require.Equal(t, codes.FailedPrecondition, status.Code(err), "%v", err)- require.ErrorIs(t, err, corestore.ErrCheckpointRootsChanged)-- _, ok, err := e.core.Meta.NewestCheckpoint(e.ctx, repo.ID)- require.NoError(t, err)- require.False(t, ok)- orphans := newKeys(before, e.packKeys(t, repo.ID))- require.Len(t, orphans, 1, "the uploaded pack is left for garbage collection")- require.False(t, e.referenced(t, repo.ID, orphans[0]))-- // The next build includes the review.- checkpoint.SetFaultHook(e.cp, nil)- _, created, err := e.cp.Create(e.ctx, e.pbRepo())- require.NoError(t, err)- require.True(t, created)- })-}-func TestCreateCrashPoints(t *testing.T) {errCrash := errors.New("crash")forEachDialect(t, func(t *testing.T, dialect sqlstore.Dialect) {- for _, point := range []string{checkpoint.PointAfterSnapshot, checkpoint.PointAfterUpload, checkpoint.PointAfterCommit} {+ for _, point := range []string{checkpoint.PointAfterUpload, checkpoint.PointAfterCommit} {t.Run(point, func(t *testing.T) {e := newEnv(t, envOptions{dialect: dialect})src := e.newSource(t)@@ -572,9 +433,6 @@ func TestCreateCrashPoints(t *testing.T) {require.NoError(t, err)switch point {- case checkpoint.PointAfterSnapshot:- require.Empty(t, uploaded)- require.False(t, recorded)case checkpoint.PointAfterUpload:require.Len(t, uploaded, 1)require.False(t, e.referenced(t, repo.ID, uploaded[0]), "an orphan")diff --git a/internal/graft/corestore/dbreview/dbreview.go b/internal/graft/corestore/dbreview/dbreview.goindex f9bd2a4..bd3786c 100644--- a/internal/graft/corestore/dbreview/dbreview.go+++ b/internal/graft/corestore/dbreview/dbreview.go@@ -37,10 +37,9 @@ type Store struct {ctx context.Contextmeta corestore.MetaStorerepoID int64- // rootsAt is the sequence of the reference snapshot that the commits written- // by Create and Update were checked against, 0 when they move no commit- // (doc/graft/PLAN7.md, REVIEW ROOTS RULE R1).- rootsAt uint64+ // requireRoots makes Create and Update require the keep-around references of+ // the review's commits (doc/graft/PLAN7.md, REVIEW ROOTS RULE).+ requireRoots bool}var _ store.ReviewStore = (*Store)(nil)@@ -51,21 +50,14 @@ func New(ctx context.Context, meta corestore.MetaStore, repoID int64) store.Revireturn &Store{ctx: ctx, meta: meta, repoID: repoID}}-// Refs returns the references of the repository in the storage core and the-// sequence of that snapshot, which the commits of a review are checked-// against.-func (s *Store) Refs() (map[string]corestore.Target, uint64, error) {- return s.meta.Refs(s.ctx, s.repoID)-}--// WithRootsAt returns a store whose Create and Update write only while no-// checkpoint newer than rootsAt exists, else they fail with-// corestore.ErrReviewRootsStale and write nothing. rootsAt is the sequence-// returned by the Refs call the review's new commits were checked against.-func (s *Store) WithRootsAt(rootsAt uint64) store.ReviewStore {- at := *s- at.rootsAt = rootsAt- return &at+// WithRequiredRoots returns a store whose Create and Update write a review only+// when the keep-around references of its head and base commits exist in the+// database, else they fail with corestore.ErrReviewRootsMissing and write+// nothing. It is the store of the writes that may record new commits.+func (s *Store) WithRequiredRoots() store.ReviewStore {+ required := *s+ required.requireRoots = true+ return &required}// Create stores a new review. It assigns the id, created_at and updated_at.@@ -80,7 +72,7 @@ func (s *Store) Create(r *gitalypb.Review) (*gitalypb.Review, error) {review.Requirements = nilreview.Approved = falsereturn review, nil- }, s.rootsAt)+ }, s.requireRoots)if err != nil {return nil, mapErr(err)}@@ -132,7 +124,7 @@ func (s *Store) Update(id string, fn func(*gitalypb.Review) error) (*gitalypb.Restored.Requirements = nilstored.Approved = false- err = s.meta.UpdateReview(s.ctx, s.repoID, id, version, stored, s.rootsAt)+ err = s.meta.UpdateReview(s.ctx, s.repoID, id, version, stored, s.requireRoots)if err == nil {return proto.Clone(r).(*gitalypb.Review), nil}diff --git a/internal/graft/corestore/dbreview/dbreview_test.go b/internal/graft/corestore/dbreview/dbreview_test.goindex fe17a41..c42bb9e 100644--- a/internal/graft/corestore/dbreview/dbreview_test.go+++ b/internal/graft/corestore/dbreview/dbreview_test.go@@ -207,8 +207,8 @@ type conflictingMeta struct {corestore.MetaStoregets, updates intupdateErr error- // rootsAt are the rootsAt arguments of the writes, in order.- rootsAt []uint64+ // requireRoots are the requireRoots arguments of the writes, in order.+ requireRoots []bool}func (m *conflictingMeta) GetReview(context.Context, int64, string) (*gitalypb.Review, int64, error) {@@ -216,21 +216,22 @@ func (m *conflictingMeta) GetReview(context.Context, int64, string) (*gitalypb.Rreturn &gitalypb.Review{Id: "1", TargetBranch: []byte("main")}, int64(m.gets), nil}-func (m *conflictingMeta) UpdateReview(_ context.Context, _ int64, _ string, _ int64, _ *gitalypb.Review, rootsAt uint64) error {+func (m *conflictingMeta) UpdateReview(_ context.Context, _ int64, _ string, _ int64, _ *gitalypb.Review, requireRoots bool) error {m.updates++- m.rootsAt = append(m.rootsAt, rootsAt)+ m.requireRoots = append(m.requireRoots, requireRoots)return m.updateErr}-func (m *conflictingMeta) InsertReview(_ context.Context, _ int64, build func(string) (*gitalypb.Review, error), rootsAt uint64) (*gitalypb.Review, error) {- m.rootsAt = append(m.rootsAt, rootsAt)+func (m *conflictingMeta) InsertReview(_ context.Context, _ int64, build func(string) (*gitalypb.Review, error), requireRoots bool) (*gitalypb.Review, error) {+ m.requireRoots = append(m.requireRoots, requireRoots)return build("1")}-// TestRootsAtReachesTheDatabase: the snapshot sequence of WithRootsAt is the-// rootsAt of every write; New's store moves no commit (0). A stale snapshot is-// returned at once, never retried with the same snapshot.-func TestRootsAtReachesTheDatabase(t *testing.T) {+// TestRequiredRootsReachTheDatabase: the writes of WithRequiredRoots require+// the review's roots, those of New's store do not. A missing root is returned+// at once: retrying the same write without writing the reference again could+// not succeed.+func TestRequiredRootsReachTheDatabase(t *testing.T) {ctx := testhelper.Context(t)meta := &conflictingMeta{}plain := dbreview.New(ctx, meta, 1)@@ -240,17 +241,17 @@ func TestRootsAtReachesTheDatabase(t *testing.T) {_, err = plain.Update("1", func(*gitalypb.Review) error { return nil })require.NoError(t, err)- at := plain.(*dbreview.Store).WithRootsAt(7)- _, err = at.Create(&gitalypb.Review{})+ required := plain.(*dbreview.Store).WithRequiredRoots()+ _, err = required.Create(&gitalypb.Review{})require.NoError(t, err)- _, err = at.Update("1", func(*gitalypb.Review) error { return nil })+ _, err = required.Update("1", func(*gitalypb.Review) error { return nil })require.NoError(t, err)- require.Equal(t, []uint64{0, 0, 7, 7}, meta.rootsAt)+ require.Equal(t, []bool{false, false, true, true}, meta.requireRoots)- meta.updateErr = corestore.ErrReviewRootsStale+ meta.updateErr = corestore.ErrReviewRootsMissingmeta.updates = 0- _, err = at.Update("1", func(*gitalypb.Review) error { return nil })- require.ErrorIs(t, err, corestore.ErrReviewRootsStale)+ _, err = required.Update("1", func(*gitalypb.Review) error { return nil })+ require.ErrorIs(t, err, corestore.ErrReviewRootsMissing)require.Equal(t, 1, meta.updates)}diff --git a/internal/graft/corestore/gate/gate_proof_test.go b/internal/graft/corestore/gate/gate_proof_test.goindex 801b9f3..b0aaaa7 100644--- a/internal/graft/corestore/gate/gate_proof_test.go+++ b/internal/graft/corestore/gate/gate_proof_test.go@@ -136,18 +136,8 @@ func (n node) ffBranch(t *testing.T, repo *gitalypb.Repository, name string, oidrequire.NoError(t, err)}-// publish puts commit on a branch of its own, so that the storage core holds-// it: a review's commits must be reachable from its references (REVIEW ROOTS-// R1, doc/graft/PLAN7.md).-func (n node) publish(t *testing.T, s seed, commit git.ObjectID) {- t.Helper()- n.createBranch(t, s.repo, "review/"+commit.String(), commit)-}--// createReview publishes head and opens a review of it against main.func (n node) createReview(t *testing.T, s seed, head git.ObjectID) *gitalypb.Review {t.Helper()- n.publish(t, s, head)resp, err := gitalypb.NewReviewServiceClient(n.conn).CreateReview(n.ctx, &gitalypb.CreateReviewRequest{Repository: s.repo,TargetBranch: []byte("main"),@@ -659,7 +649,6 @@ func proofCases() map[string]func(t *testing.T, n node, s seed) {child := n.commit(t, s, s.base, "change", gittest.TreeEntry{Path: "a", Mode: "100644", Content: "change\n"})next := n.commit(t, s, child, "change 2", gittest.TreeEntry{Path: "a", Mode: "100644", Content: "change 2\n"})review := n.createReview(t, s, child)- n.publish(t, s, next)_, err := gitalypb.NewReviewServiceClient(n.conn).UpdateReview(n.ctx, &gitalypb.UpdateReviewRequest{Repository: s.repo,Id: review.GetId(),diff --git a/internal/graft/corestore/gate/gate_reviewroots_test.go b/internal/graft/corestore/gate/gate_reviewroots_test.gonew file mode 100644index 0000000..627dc8f--- /dev/null+++ b/internal/graft/corestore/gate/gate_reviewroots_test.go@@ -0,0 +1,168 @@+package gate_test++import (+ "testing"+ "time"++ "github.com/stretchr/testify/require"++ "github.com/feder-cr/git-ai/internal/git"+ "github.com/feder-cr/git-ai/internal/git/gittest"+ "github.com/feder-cr/git-ai/internal/git/housekeeping"+ housekeepingcfg "github.com/feder-cr/git-ai/internal/git/housekeeping/config"+ "github.com/feder-cr/git-ai/internal/git/localrepo"+ "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/testhelper"+ "github.com/feder-cr/git-ai/proto/go/gitalypb"+)++// housekeep runs the object housekeeping of Gitaly on the node's local copy+// of repo with an expiry of now: a full repack that drops unreachable objects+// into an expired cruft pack, then a prune of the unreachable loose objects.+// Production housekeeping does the same with a grace period of two weeks.+func housekeep(t *testing.T, n node, repo *gitalypb.Repository) {+ t.Helper()++ ctx := testhelper.Context(t)+ local := localrepo.NewTestRepo(t, n.cfg, repo)+ now := time.Now()+ require.NoError(t, housekeeping.RepackObjects(ctx, local, housekeepingcfg.RepackObjectsConfig{+ Strategy: housekeepingcfg.RepackObjectsStrategyFullWithCruft,+ CruftExpireBefore: now,+ }))+ require.NoError(t, housekeeping.PruneObjects(ctx, local, housekeeping.PruneObjectsConfig{ExpireBefore: now}))+}++// hasObject reports whether the node's local copy of repo has the object.+func hasObject(t *testing.T, n node, repo *gitalypb.Repository, oid git.ObjectID) bool {+ t.Helper()+ path := n.cfg.Storages[0].Path + "/" + repo.GetRelativePath()+ return gittest.NewCommand(t, n.cfg, "-C", path, "cat-file", "-e", oid.String()).Run() == nil+}++func (n node) deleteBranch(t *testing.T, repo *gitalypb.Repository, name string) {+ t.Helper()+ _, err := gitalypb.NewOperationServiceClient(n.conn).UserDeleteBranch(n.ctx, &gitalypb.UserDeleteBranchRequest{+ Repository: repo,+ BranchName: []byte(name),+ User: gittest.TestUser,+ })+ require.NoError(t, err)+}++// TestKeepAroundReferencesOfOpenReviewsAreGuarded: in authoritative mode no+// write path can delete or move the keep-around reference of an open review's+// commit: DeleteRefs, WriteRef and UpdateReferences (git update-ref through+// the reference-transaction hook) are refused by the database and change+// nothing, locally or in the database. A keep-around reference that no open+// review uses can be deleted.+func TestKeepAroundReferencesOfOpenReviewsAreGuarded(t *testing.T) {+ t.Parallel()++ for _, dialect := range coretest.Dialects() {+ t.Run(string(dialect), func(t *testing.T) {+ t.Parallel()++ n := startNode(t, coretest.Open(t, coretest.Options{Dialect: dialect}))+ s := n.newSeed(t)+ feature := n.commit(t, s, s.base, "feature", gittest.TreeEntry{Path: "a", Mode: "100644", Content: "feature\n"})+ _, err := gitalypb.NewReviewServiceClient(n.conn).CreateReview(n.ctx, &gitalypb.CreateReviewRequest{+ Repository: s.repo,+ TargetBranch: []byte("main"),+ HeadCommitId: feature.String(),+ })+ require.NoError(t, err)++ ref := corestore.KeepAroundRef(feature.String())+ require.Equal(t, corestore.Target(feature.String()), n.dbRefs(t, s.repo)[ref])+ before := n.dbRefs(t, s.repo)++ refs := gitalypb.NewRefServiceClient(n.conn)+ _, err = refs.DeleteRefs(n.ctx, &gitalypb.DeleteRefsRequest{Repository: s.repo, Refs: [][]byte{[]byte(ref)}})+ require.Error(t, err, "DeleteRefs")+ require.Equal(t, before, n.dbRefs(t, s.repo))++ _, err = gitalypb.NewRepositoryServiceClient(n.conn).WriteRef(n.ctx, &gitalypb.WriteRefRequest{+ Repository: s.repo,+ Ref: []byte(ref),+ Revision: []byte(s.base.String()),+ })+ require.Error(t, err, "WriteRef")+ require.Equal(t, before, n.dbRefs(t, s.repo))++ stream, err := refs.UpdateReferences(n.ctx)+ require.NoError(t, err)+ require.NoError(t, stream.Send(&gitalypb.UpdateReferencesRequest{+ Repository: s.repo,+ Updates: []*gitalypb.UpdateReferencesRequest_Update{{+ Reference: []byte(ref),+ OldObjectId: []byte(feature.String()),+ NewObjectId: []byte(gittest.DefaultObjectHash.ZeroOID.String()),+ }},+ }))+ _, err = stream.CloseAndRecv()+ require.Error(t, err, "UpdateReferences")+ require.Equal(t, before, n.dbRefs(t, s.repo))++ n.requireSameRefs(t, s.repo)+ require.True(t, hasObject(t, n, s.repo, feature))++ // A keep-around reference that no open review uses is not guarded.+ other := n.commit(t, s, s.base, "other", gittest.TreeEntry{Path: "a", Mode: "100644", Content: "other\n"})+ loose := corestore.KeepAroundRef(other.String())+ _, err = gitalypb.NewRepositoryServiceClient(n.conn).WriteRef(n.ctx, &gitalypb.WriteRefRequest{+ Repository: s.repo,+ Ref: []byte(loose),+ Revision: []byte(other.String()),+ })+ require.NoError(t, err)+ require.Contains(t, n.dbRefs(t, s.repo), loose)+ _, err = refs.DeleteRefs(n.ctx, &gitalypb.DeleteRefsRequest{Repository: s.repo, Refs: [][]byte{[]byte(loose)}})+ require.NoError(t, err)+ require.NotContains(t, n.dbRefs(t, s.repo), loose)+ })+ }+}++// TestOpenReviewCommitsSurviveHousekeeping: an open review's commit whose+// branch was deleted survives the object housekeeping of every node, also of+// a node that hydrated the repository after the review was created+// (doc/graft/PLAN7.md, REVIEW ROOTS amendment).+func TestOpenReviewCommitsSurviveHousekeeping(t *testing.T) {+ t.Parallel()++ for _, dialect := range coretest.Dialects() {+ t.Run(string(dialect), func(t *testing.T) {+ t.Parallel()++ databaseURL := coretest.DatabaseURL(t, dialect)+ bucketURL := coretest.BucketURL(t, false)+ a := startNode(t, coretest.Open(t, coretest.Options{Dialect: dialect, DatabaseURL: databaseURL, BucketURL: bucketURL, NodeID: "node-a"}))++ s := a.newSeed(t)+ feature := a.commit(t, s, s.base, "feature", gittest.TreeEntry{Path: "a", Mode: "100644", Content: "feature\n"})+ a.createBranch(t, s.repo, "feature", feature)+ created, err := gitalypb.NewReviewServiceClient(a.conn).CreateReview(a.ctx, &gitalypb.CreateReviewRequest{+ Repository: s.repo,+ TargetBranch: []byte("main"),+ HeadCommitId: feature.String(),+ })+ require.NoError(t, err)+ a.deleteBranch(t, s.repo, "feature")++ housekeep(t, a, s.repo)+ require.True(t, hasObject(t, a, s.repo, feature), "node A keeps the commit of the open review")++ // Node B hydrates after the review was created.+ b := startNode(t, coretest.Open(t, coretest.Options{Dialect: dialect, DatabaseURL: databaseURL, BucketURL: bucketURL, NodeID: "node-b"}))+ repoB := &gitalypb.Repository{StorageName: b.cfg.Storages[0].Name, RelativePath: s.repo.GetRelativePath()}+ got, err := gitalypb.NewReviewServiceClient(b.conn).GetReview(b.ctx, &gitalypb.GetReviewRequest{Repository: repoB, Id: created.GetReview().GetId()})+ require.NoError(t, err)+ require.Equal(t, feature.String(), got.GetReview().GetHeadCommitId())++ housekeep(t, b, repoB)+ require.True(t, hasObject(t, b, repoB, feature), "node B keeps the commit of the open review")+ })+ }+}diff --git a/internal/graft/corestore/gitops/gitops.go b/internal/graft/corestore/gitops/gitops.goindex 1feb079..b20386e 100644--- a/internal/graft/corestore/gitops/gitops.go+++ b/internal/graft/corestore/gitops/gitops.go@@ -121,8 +121,7 @@ func BuildPack(ctx context.Context, repo *localrepo.Repo, tips []git.ObjectID, t// `git rev-list --objects --stdin`, piped into `git pack-objects --stdout` and// written to a new file in tmpDir while hashing. Zero tips are ignored; without// any tip the result is an empty Pack and no file. A tip that is not in the-// repository is an error: callers check the tips with MissingObjects first, so-// that a missing object is reported precisely and never yields a partial pack.+// repository is an error, never a partial pack.func BuildPackFrom(ctx context.Context, repo *localrepo.Repo, tips []git.ObjectID, tmpDir string) (Pack, error) {stdin, positive, err := tipsInput(ctx, repo, tips)if err != nil {@@ -220,54 +219,6 @@ func MissingObjects(ctx context.Context, repo *localrepo.Repo, oids []git.Objectreturn missing, nil}-// IsReachable reports whether commit is reachable from at least one of tips-// (the object IDs that the references of a repository point to): `git-// rev-list --stdin` from commit with every tip negated prints nothing exactly-// when every commit it would walk is reachable from a tip, which holds exactly-// when commit is. commit must be in the repository; zero tips are ignored, and-// no tip at all reaches nothing.-func IsReachable(ctx context.Context, repo *localrepo.Repo, commit git.ObjectID, tips []git.ObjectID) (bool, error) {- hash, err := repo.ObjectHash(ctx)- if err != nil {- return false, fmt.Errorf("object hash: %w", err)- }- if err := hash.ValidateHex(commit.String()); err != nil {- return false, fmt.Errorf("commit: %w", err)- }-- var stdin bytes.Buffer- stdin.WriteString(commit.String())- stdin.WriteByte('\n')- for _, tip := range tips {- if hash.IsZeroOID(tip) {- continue- }- if err := hash.ValidateHex(tip.String()); err != nil {- return false, fmt.Errorf("tip: %w", err)- }- stdin.WriteString("^" + tip.String())- stdin.WriteByte('\n')- }-- var stdout, stderr bytes.Buffer- if err := repo.ExecAndWait(ctx,- gitcmd.Command{- Name: "rev-list",- Flags: []gitcmd.Option{- gitcmd.Flag{Name: "--stdin"},- gitcmd.Flag{Name: "--max-count=1"},- },- },- gitcmd.WithStdin(&stdin),- gitcmd.WithStdout(&stdout),- gitcmd.WithStderr(&stderr),- ); err != nil {- return false, structerr.New("rev-list: %w", err).WithMetadata("stderr", stderr.String())- }-- return stdout.Len() == 0, nil-}-// BuildFullPack writes a pack of every object reachable from any reference// (including HEAD), for the import of a repository.func BuildFullPack(ctx context.Context, repo *localrepo.Repo, tmpDir string) (Pack, error) {diff --git a/internal/graft/corestore/gitops/gitops_checkpoint_test.go b/internal/graft/corestore/gitops/gitops_checkpoint_test.goindex e2aab8a..2576f04 100644--- a/internal/graft/corestore/gitops/gitops_checkpoint_test.go+++ b/internal/graft/corestore/gitops/gitops_checkpoint_test.go@@ -12,17 +12,6 @@ import ("github.com/stretchr/testify/require")-// tagObject writes an annotated tag object of target, not referenced.-func (f fixture) tagObject(t *testing.T, target git.ObjectID) git.ObjectID {- t.Helper()-- mktag := gittest.NewCommand(t, f.cfg, "-C", f.path, "mktag")- mktag.Stdin = strings.NewReader("object " + target.String() + "\ntype commit\ntag v1\ntagger T <[email protected]> 1700000000 +0000\n\nv1\n")- out, err := mktag.Output()- require.NoError(t, err)- return git.ObjectID(strings.TrimSpace(string(out)))-}-func TestBuildPackFromIsSelfContained(t *testing.T) {t.Parallel()@@ -106,43 +95,3 @@ func TestMissingObjects(t *testing.T) {})}}--func TestIsReachable(t *testing.T) {- t.Parallel()-- for _, format := range objectFormats {- t.Run(format, func(t *testing.T) {- t.Parallel()-- f := newFixture(t, format)- c1 := f.commit(t, nil, "base")- c2 := f.commit(t, []git.ObjectID{c1}, "tip")- unrelated := f.commit(t, nil, "unrelated")- tag := f.tagObject(t, c2)- blob := gittest.WriteBlob(t, f.cfg, f.path, []byte("a reference may point to a blob"))-- for _, tc := range []struct {- desc string- commit git.ObjectID- tips []git.ObjectID- want bool- }{- {desc: "ancestor of a tip", commit: c1, tips: []git.ObjectID{c2}, want: true},- {desc: "the tip itself", commit: c2, tips: []git.ObjectID{c2}, want: true},- {desc: "through an annotated tag", commit: c1, tips: []git.ObjectID{tag}, want: true},- {desc: "next to a tip that is a blob", commit: c1, tips: []git.ObjectID{blob, c2}, want: true},- {desc: "unrelated history", commit: unrelated, tips: []git.ObjectID{c2, tag, blob}, want: false},- {desc: "a descendant is not reachable from its ancestor", commit: c2, tips: []git.ObjectID{c1}, want: false},- {desc: "no tips", commit: c1, tips: nil, want: false},- {desc: "zero tips are ignored", commit: c1, tips: []git.ObjectID{f.hash.ZeroOID}, want: false},- } {- got, err := gitops.IsReachable(f.ctx, f.repo, tc.commit, tc.tips)- require.NoError(t, err, tc.desc)- require.Equal(t, tc.want, got, tc.desc)- }-- _, err := gitops.IsReachable(f.ctx, f.repo, "--all", []git.ObjectID{c2})- require.Error(t, err, "the commit must be an object ID")- })- }-}diff --git a/internal/graft/corestore/metastore.go b/internal/graft/corestore/metastore.goindex 63a8dd0..bd8955b 100644--- a/internal/graft/corestore/metastore.go+++ b/internal/graft/corestore/metastore.go@@ -80,9 +80,6 @@ type CheckpointInput struct {// pack, PackBytes its size.PackKey stringPackBytes int64- // Roots are the head and base commits of the open reviews that the pack- // includes (doc/graft/PLAN7.md, REVIEW ROOTS RULE R2).- Roots []string}var (@@ -116,7 +113,11 @@ type MetaStore interface {// records the changeset, the reference changes and the changelog entries// in one transaction (see the CAS table of doc/graft/PLAN6.md). It returns// *ErrRefConflict, writing nothing, when an expectation fails and Force is- // not set, and ErrRepositoryNotFound for an unknown repository.+ // not set, and ErrRepositoryNotFound for an unknown repository. Unless Force+ // is set, a changeset that deletes or moves the keep-around reference of a+ // commit that an open review uses as its head or base is refused with+ // ErrReviewRootInUse (doc/graft/PLAN7.md, REVIEW ROOTS RULE); shadow mode,+ // whose changesets are forced, does not enforce it.CommitChangeset(ctx context.Context, in ChangesetInput) (CommitResult, error)// ListChangesets returns the changesets with after < seq <= upTo in// ascending order, with their updates.@@ -148,13 +149,13 @@ type MetaStore interface {// with it and stores the returned review (version 1), atomically. build runs// inside the write transaction and must not call the MetaStore.//- // rootsAt is the sequence of the reference snapshot the review's head and- // base commits were checked against (doc/graft/PLAN7.md, REVIEW ROOTS RULE- // R1). When it is not 0 the transaction, under the repository row lock,- // requires the newest checkpoint's sequence to be at most rootsAt, else- // ErrReviewRootsStale and nothing is written. Writes that do not check- // commits (imports) pass 0.- InsertReview(ctx context.Context, repoID int64, build func(id string) (*gitalypb.Review, error), rootsAt uint64) (*gitalypb.Review, error)+ // With requireRoots the transaction locks the repository row first and+ // requires the keep-around reference (KeepAroundRef) of the review's head and+ // base commits to exist with that value, else ErrReviewRootsMissing and+ // nothing is written (doc/graft/PLAN7.md, REVIEW ROOTS RULE). Together with+ // CommitChangeset's refusal to delete such a reference, every open review+ // written so has its commits referenced.+ InsertReview(ctx context.Context, repoID int64, build func(id string) (*gitalypb.Review, error), requireRoots bool) (*gitalypb.Review, error)// GetReview returns the review and its version, ErrReviewNotFound if unknown.GetReview(ctx context.Context, repoID int64, id string) (*gitalypb.Review, int64, error)// ListReviews returns the reviews of the repository newest first@@ -166,13 +167,11 @@ type MetaStore interface {// UpdateReview stores r if the review is still at version, which becomes// version+1. It returns ErrReviewVersionConflict otherwise.//- // rootsAt is as for InsertReview: an update that moves the review's head- // passes the sequence of the snapshot the new head was checked against, and- // the transaction then takes the repository row lock first and requires the- // newest checkpoint's sequence to be at most rootsAt, else- // ErrReviewRootsStale. Updates that move no commit (comments, verdicts,- // closes) pass 0 and do not lock the repository row (LOCK ORDER).- UpdateReview(ctx context.Context, repoID int64, id string, version int64, r *gitalypb.Review, rootsAt uint64) error+ // requireRoots is as for InsertReview, for the head and base of r: an update+ // that may move the head requires them. Updates that move no commit+ // (comments, verdicts, closes) do not, and do not lock the repository row+ // (LOCK ORDER).+ UpdateReview(ctx context.Context, repoID int64, id string, version int64, r *gitalypb.Review, requireRoots bool) error// CreateCheckpoint records a checkpoint and its reference snapshot in one// transaction, with the database time as its creation time. Its first@@ -181,9 +180,7 @@ type MetaStore interface {// an owned pack key of the repository and a valid snapshot, else an error and// nothing is written. A checkpoint at Seq that exists already is returned// unchanged with created false (its pack is kept; the caller's becomes an- // orphan). It requires every open review's head and base commit to be in- // Roots, else ErrCheckpointRootsChanged and nothing is written.- // ErrRepositoryNotFound for an unknown repository.+ // orphan). ErrRepositoryNotFound for an unknown repository.CreateCheckpoint(ctx context.Context, repoID int64, in CheckpointInput) (cp Checkpoint, created bool, err error)// NewestCheckpoint returns the checkpoint with the greatest sequence; ok is// false when the repository has none.diff --git a/internal/graft/corestore/reviewroots/reviewroots.go b/internal/graft/corestore/reviewroots/reviewroots.gonew file mode 100644index 0000000..d0519a1--- /dev/null+++ b/internal/graft/corestore/reviewroots/reviewroots.go@@ -0,0 +1,316 @@+// Package reviewroots writes and removes the keep-around references that keep+// the head and base commits of open reviews alive (doc/graft/PLAN7.md, REVIEW+// ROOTS RULE). An open review is a root of the object graph: its commits must+// survive the deletion of their branch, on every node (local housekeeping+// keeps what references reach) and in the storage core (checkpoints and garbage+// collection keep what references reach). Making the roots references gives+// them all the same rule.+//+// The references are written and deleted like any other, through the+// reference-transaction hook, so in shadow and authoritative mode the voter+// records them and uploads the objects the storage core does not have yet. In+// authoritative mode the database keeps the invariant "every open review+// written with its roots required has the keep-around references of its+// commits": MetaStore.InsertReview and UpdateReview require them and+// CommitChangeset refuses to delete one that an open review uses.+package reviewroots++import (+ "context"+ "fmt"+ "sort"+ "strings"++ "github.com/feder-cr/git-ai/internal/git"+ "github.com/feder-cr/git-ai/internal/git/localrepo"+ "github.com/feder-cr/git-ai/internal/git/updateref"+ "github.com/feder-cr/git-ai/internal/graft/corestore"+ "github.com/feder-cr/git-ai/internal/graft/corestore/gitops"+ "github.com/feder-cr/git-ai/internal/graft/review/store"+)++// Protect writes the keep-around reference of every commit that does not have+// it, in one reference transaction. The commits must be in the repository. A+// commit whose reference exists with its value is left alone, so Protect of+// protected commits writes nothing.+func Protect(ctx context.Context, repo *localrepo.Repo, commits []git.ObjectID) error {+ names := make([]string, 0, len(commits))+ byName := make(map[string]git.ObjectID, len(commits))+ for _, commit := range commits {+ name := corestore.KeepAroundRef(commit.String())+ if _, dup := byName[name]; !dup {+ names = append(names, name)+ byName[name] = commit+ }+ }+ if len(names) == 0 {+ return nil+ }+ sort.Strings(names)++ current, err := gitops.ReadRefValues(ctx, repo, names)+ if err != nil {+ return fmt.Errorf("read keep-around references: %w", err)+ }++ var missing []string+ for _, name := range names {+ if current[name] != corestore.Target(byName[name]) {+ missing = append(missing, name)+ }+ }+ if len(missing) == 0 {+ return nil+ }++ updater, err := updateref.New(ctx, repo)+ if err != nil {+ return fmt.Errorf("start the keep-around update: %w", err)+ }+ defer func() { _ = updater.Close() }()++ if err := updater.Start(); err != nil {+ return fmt.Errorf("start the keep-around update: %w", err)+ }+ for _, name := range missing {+ ref := git.ReferenceName(name)+ old := current[name]+ switch {+ case old.Absent():+ err = updater.Create(ref, byName[name])+ case old.IsSymbolic():+ return fmt.Errorf("keep-around reference %s is symbolic", name)+ default:+ err = updater.Update(ref, byName[name], git.ObjectID(old))+ }+ if err != nil {+ return fmt.Errorf("write %s: %w", name, err)+ }+ }+ if err := updater.Commit(); err != nil {+ // A concurrent Protect of the same commit (two reviews of one commit)+ // may have written the reference first: what counts is its value.+ after, readErr := gitops.ReadRefValues(ctx, repo, missing)+ if readErr != nil {+ return fmt.Errorf("write keep-around references: %w (and read them again: %w)", err, readErr)+ }+ for _, name := range missing {+ if after[name] != corestore.Target(byName[name]) {+ return fmt.Errorf("write keep-around references: %w", err)+ }+ }+ }+ return nil+}++// SweepReport counts what a sweep did.+type SweepReport struct {+ // Deleted is the number of keep-around references deleted.+ Deleted int+ // Kept is the number of keep-around references kept because an open review+ // uses their commit.+ Kept int+}++// Sweep deletes the keep-around references whose commit no open review of+// reviews uses: those of the candidate commits, or every keep-around reference+// of the repository when candidates is nil. Each deletion is its own+// reference transaction that expects the value read, so one refused deletion+// does not hold up the others. A review written after the open reviews were+// read may use a reference the sweep is deleting: authoritative mode refuses+// that deletion (the review store requires the reference, CommitChangeset+// refuses to delete it), and the sweep then keeps the reference; a review+// write that lost its reference to the sweep writes it again.+func Sweep(ctx context.Context, repo *localrepo.Repo, reviews store.ReviewStore, candidates []git.ObjectID) (SweepReport, error) {+ used, err := openRoots(reviews)+ if err != nil {+ return SweepReport{}, err+ }++ var refs map[string]corestore.Target+ if candidates == nil {+ all, err := gitops.ReadRefs(ctx, repo)+ if err != nil {+ return SweepReport{}, fmt.Errorf("read references: %w", err)+ }+ refs = map[string]corestore.Target{}+ for name, target := range all {+ if strings.HasPrefix(name, corestore.KeepAroundPrefix) {+ refs[name] = target+ }+ }+ } else {+ names := make([]string, 0, len(candidates))+ for _, commit := range candidates {+ names = append(names, corestore.KeepAroundRef(commit.String()))+ }+ if refs, err = gitops.ReadRefValues(ctx, repo, names); err != nil {+ return SweepReport{}, fmt.Errorf("read keep-around references: %w", err)+ }+ }++ hash, err := repo.ObjectHash(ctx)+ if err != nil {+ return SweepReport{}, fmt.Errorf("object hash: %w", err)+ }++ names := make([]string, 0, len(refs))+ for name := range refs {+ names = append(names, name)+ }+ sort.Strings(names)++ var report SweepReport+ for _, name := range names {+ target := refs[name]+ if target.IsSymbolic() {+ // Not a reference this package writes.+ continue+ }+ if _, ok := used[string(target)]; ok {+ report.Kept+++ continue+ }++ if err := deleteRef(ctx, repo, name, git.ObjectID(target), hash); err != nil {+ // The deletion is refused when a review written since the read uses+ // the commit: read the open reviews again to tell that from a failure.+ used, uerr := openRoots(reviews)+ if uerr != nil {+ return report, uerr+ }+ if _, ok := used[string(target)]; ok {+ report.Kept+++ continue+ }+ return report, fmt.Errorf("delete %s: %w", name, err)+ }+ report.Deleted+++ }+ return report, nil+}++// deleteRef deletes the reference if it still has the value old.+func deleteRef(ctx context.Context, repo *localrepo.Repo, name string, old git.ObjectID, hash git.ObjectHash) error {+ updater, err := updateref.New(ctx, repo)+ if err != nil {+ return err+ }+ defer func() { _ = updater.Close() }()++ if err := updater.Start(); err != nil {+ return err+ }+ if err := updater.Update(git.ReferenceName(name), hash.ZeroOID, old); err != nil {+ return err+ }+ return updater.Commit()+}++// BackfillReport counts what a backfill did.+type BackfillReport struct {+ // Protected is the number of commits whose keep-around reference was+ // written.+ Protected int+ // Missing are the IDs of the open reviews with a commit that is not in the+ // repository (or not an object ID): it cannot be protected any more.+ Missing []string+}++// Backfill writes the keep-around references of the open reviews that do not+// have them: reviews written before the REVIEW ROOTS RULE, or imported from the+// files of shadow mode. A commit that the repository does not have cannot be+// protected; its review is reported and nothing else is held up.+func Backfill(ctx context.Context, repo *localrepo.Repo, reviews store.ReviewStore) (BackfillReport, error) {+ open, err := reviews.List("", false, 0)+ if err != nil {+ return BackfillReport{}, fmt.Errorf("list open reviews: %w", err)+ }+ hash, err := repo.ObjectHash(ctx)+ if err != nil {+ return BackfillReport{}, fmt.Errorf("object hash: %w", err)+ }++ var report BackfillReport+ byCommit := map[git.ObjectID][]string{}+ var names []string+ for _, r := range open {+ for _, commit := range []string{r.GetHeadCommitId(), r.GetBaseCommitId()} {+ if commit == "" {+ continue+ }+ if hash.ValidateHex(commit) != nil {+ report.Missing = appendOnce(report.Missing, r.GetId())+ continue+ }+ oid := git.ObjectID(commit)+ if _, seen := byCommit[oid]; !seen {+ names = append(names, corestore.KeepAroundRef(commit))+ }+ byCommit[oid] = append(byCommit[oid], r.GetId())+ }+ }++ current, err := gitops.ReadRefValues(ctx, repo, names)+ if err != nil {+ return report, fmt.Errorf("read keep-around references: %w", err)+ }+ var unprotected []git.ObjectID+ for oid := range byCommit {+ if current[corestore.KeepAroundRef(oid.String())] != corestore.Target(oid) {+ unprotected = append(unprotected, oid)+ }+ }+ sort.Slice(unprotected, func(i, j int) bool { return unprotected[i] < unprotected[j] })++ missing, err := gitops.MissingObjects(ctx, repo, unprotected)+ if err != nil {+ return report, fmt.Errorf("look up review commits: %w", err)+ }+ absent := make(map[git.ObjectID]struct{}, len(missing))+ for _, oid := range missing {+ absent[oid] = struct{}{}+ for _, id := range byCommit[oid] {+ report.Missing = appendOnce(report.Missing, id)+ }+ }++ var present []git.ObjectID+ for _, oid := range unprotected {+ if _, ok := absent[oid]; !ok {+ present = append(present, oid)+ }+ }+ if err := Protect(ctx, repo, present); err != nil {+ return report, err+ }+ report.Protected = len(present)+ sort.Strings(report.Missing)+ return report, nil+}++// openRoots returns the head and base commits of the open reviews.+func openRoots(reviews store.ReviewStore) (map[string]struct{}, error) {+ open, err := reviews.List("", false, 0)+ if err != nil {+ return nil, fmt.Errorf("list open reviews: %w", err)+ }+ used := map[string]struct{}{}+ for _, r := range open {+ for _, commit := range []string{r.GetHeadCommitId(), r.GetBaseCommitId()} {+ if commit != "" {+ used[commit] = struct{}{}+ }+ }+ }+ return used, nil+}++func appendOnce(ids []string, id string) []string {+ for _, existing := range ids {+ if existing == id {+ return ids+ }+ }+ return append(ids, id)+}diff --git a/internal/graft/corestore/reviewroots/reviewroots_test.go b/internal/graft/corestore/reviewroots/reviewroots_test.gonew file mode 100644index 0000000..4dd6a97--- /dev/null+++ b/internal/graft/corestore/reviewroots/reviewroots_test.go@@ -0,0 +1,173 @@+package reviewroots_test++import (+ "context"+ "strings"+ "testing"++ "github.com/stretchr/testify/require"++ "github.com/feder-cr/git-ai/internal/git"+ "github.com/feder-cr/git-ai/internal/git/gittest"+ "github.com/feder-cr/git-ai/internal/git/localrepo"+ "github.com/feder-cr/git-ai/internal/graft/corestore"+ "github.com/feder-cr/git-ai/internal/graft/corestore/gitops"+ "github.com/feder-cr/git-ai/internal/graft/corestore/reviewroots"+ "github.com/feder-cr/git-ai/internal/graft/review/store"+ "github.com/feder-cr/git-ai/internal/testhelper"+ "github.com/feder-cr/git-ai/internal/testhelper/testcfg"+ "github.com/feder-cr/git-ai/proto/go/gitalypb"+)++func TestMain(m *testing.M) {+ testhelper.Run(m)+}++type fixture struct {+ ctx context.Context+ t *testing.T+ repo *localrepo.Repo+ path string+ reviews store.ReviewStore+ write func(message string, parents ...git.ObjectID) git.ObjectID+}++func newFixture(t *testing.T) fixture {+ t.Helper()++ ctx := testhelper.Context(t)+ cfg := testcfg.Build(t)+ pb, path := gittest.CreateRepository(t, ctx, cfg, gittest.CreateRepositoryConfig{SkipCreationViaService: true})+ return fixture{+ ctx: ctx,+ t: t,+ repo: localrepo.NewTestRepo(t, cfg, pb),+ path: path,+ reviews: store.Open(path),+ write: func(message string, parents ...git.ObjectID) git.ObjectID {+ return gittest.WriteCommit(t, cfg, path, gittest.WithMessage(message), gittest.WithParents(parents...))+ },+ }+}++// keepArounds returns the keep-around references of the repository.+func (f fixture) keepArounds() map[string]corestore.Target {+ f.t.Helper()++ refs, err := gitops.ReadRefs(f.ctx, f.repo)+ require.NoError(f.t, err)+ kept := map[string]corestore.Target{}+ for name, target := range refs {+ if strings.HasPrefix(name, corestore.KeepAroundPrefix) {+ kept[name] = target+ }+ }+ return kept+}++func (f fixture) review(head, base string, state gitalypb.Review_State) *gitalypb.Review {+ f.t.Helper()++ r, err := f.reviews.Create(&gitalypb.Review{TargetBranch: []byte("main"), HeadCommitId: head, BaseCommitId: base})+ require.NoError(f.t, err)+ if state != gitalypb.Review_STATE_OPEN_UNSPECIFIED {+ r, err = f.reviews.Update(r.GetId(), func(r *gitalypb.Review) error {+ r.State = state+ return nil+ })+ require.NoError(f.t, err)+ }+ return r+}++func keepAroundOf(commits ...git.ObjectID) map[string]corestore.Target {+ kept := map[string]corestore.Target{}+ for _, c := range commits {+ kept[corestore.KeepAroundRef(c.String())] = corestore.Target(c)+ }+ return kept+}++func TestProtect(t *testing.T) {+ t.Parallel()++ f := newFixture(t)+ c1 := f.write("c1")+ c2 := f.write("c2", c1)++ require.NoError(t, reviewroots.Protect(f.ctx, f.repo, []git.ObjectID{c1, c2, c1}))+ require.Equal(t, keepAroundOf(c1, c2), f.keepArounds())++ // Protected commits: nothing to write.+ require.NoError(t, reviewroots.Protect(f.ctx, f.repo, []git.ObjectID{c2}))+ require.NoError(t, reviewroots.Protect(f.ctx, f.repo, nil))+ require.Equal(t, keepAroundOf(c1, c2), f.keepArounds())++ // A keep-around reference with another value is set to its commit.+ c3 := f.write("c3", c2)+ gittest.WriteRef(t, testcfg.Build(t), f.path, git.ReferenceName(corestore.KeepAroundRef(c3.String())), c1)+ require.NoError(t, reviewroots.Protect(f.ctx, f.repo, []git.ObjectID{c3}))+ require.Equal(t, keepAroundOf(c1, c2, c3), f.keepArounds())++ // A commit that is not in the repository cannot be protected.+ absent := git.ObjectID(strings.Repeat("a", gittest.DefaultObjectHash.EncodedLen()))+ require.Error(t, reviewroots.Protect(f.ctx, f.repo, []git.ObjectID{absent}))+ require.Equal(t, keepAroundOf(c1, c2, c3), f.keepArounds())+}++func TestSweep(t *testing.T) {+ t.Parallel()++ f := newFixture(t)+ c0 := f.write("c0")+ c1 := f.write("c1", c0)+ c2 := f.write("c2", c0)+ c3 := f.write("c3", c0)+ f.review(c1.String(), c0.String(), gitalypb.Review_STATE_OPEN_UNSPECIFIED)+ f.review(c2.String(), c0.String(), gitalypb.Review_STATE_CLOSED)+ require.NoError(t, reviewroots.Protect(f.ctx, f.repo, []git.ObjectID{c0, c1, c2, c3}))++ // Candidates only: the open review's head is kept, the closed review's goes.+ report, err := reviewroots.Sweep(f.ctx, f.repo, f.reviews, []git.ObjectID{c1, c2})+ require.NoError(t, err)+ require.Equal(t, reviewroots.SweepReport{Deleted: 1, Kept: 1}, report)+ require.Equal(t, keepAroundOf(c0, c1, c3), f.keepArounds())++ // Every keep-around reference: the one no review uses goes.+ report, err = reviewroots.Sweep(f.ctx, f.repo, f.reviews, nil)+ require.NoError(t, err)+ require.Equal(t, reviewroots.SweepReport{Deleted: 1, Kept: 2}, report)+ require.Equal(t, keepAroundOf(c0, c1), f.keepArounds())++ // A sweep of what is gone does nothing.+ report, err = reviewroots.Sweep(f.ctx, f.repo, f.reviews, []git.ObjectID{c2, c3})+ require.NoError(t, err)+ require.Equal(t, reviewroots.SweepReport{}, report)+}++func TestBackfill(t *testing.T) {+ t.Parallel()++ f := newFixture(t)+ c0 := f.write("c0")+ c1 := f.write("c1", c0)+ c4 := f.write("c4", c0)+ require.NoError(t, reviewroots.Protect(f.ctx, f.repo, []git.ObjectID{c0}))++ absent := strings.Repeat("b", gittest.DefaultObjectHash.EncodedLen())+ f.review(c1.String(), c0.String(), gitalypb.Review_STATE_OPEN_UNSPECIFIED)+ lost := f.review(absent, c0.String(), gitalypb.Review_STATE_OPEN_UNSPECIFIED)+ garbled := f.review("not an object ID", "", gitalypb.Review_STATE_OPEN_UNSPECIFIED)+ f.review(c4.String(), c0.String(), gitalypb.Review_STATE_LANDED)++ report, err := reviewroots.Backfill(f.ctx, f.repo, f.reviews)+ require.NoError(t, err)+ require.Equal(t, 1, report.Protected, "the open review's head; its base had its reference")+ require.Equal(t, []string{lost.GetId(), garbled.GetId()}, report.Missing)+ require.Equal(t, keepAroundOf(c0, c1), f.keepArounds(), "closed reviews are not backfilled")++ // A second backfill has nothing left to protect.+ report, err = reviewroots.Backfill(f.ctx, f.repo, f.reviews)+ require.NoError(t, err)+ require.Zero(t, report.Protected)+}diff --git a/internal/graft/corestore/sqlstore/changeset.go b/internal/graft/corestore/sqlstore/changeset.goindex 73d9595..85b955c 100644--- a/internal/graft/corestore/sqlstore/changeset.go+++ b/internal/graft/corestore/sqlstore/changeset.go@@ -110,6 +110,11 @@ func (s *Store) commitChangeset(ctx context.Context, tx *sql.Tx, repo *repoStateif len(conflicts) > 0 && !in.Force {return corestore.CommitResult{}, &corestore.ErrRefConflict{Conflicts: conflicts}}+ if !in.Force {+ if err := s.refuseReleasedRoots(ctx, tx, repo.id, effective); err != nil {+ return corestore.CommitResult{}, err+ }+ }if len(effective) == 0 {return corestore.CommitResult{NoOp: true, Conflicts: conflicts}, nildiff --git a/internal/graft/corestore/sqlstore/checkpoint.go b/internal/graft/corestore/sqlstore/checkpoint.goindex abc3d44..edee86c 100644--- a/internal/graft/corestore/sqlstore/checkpoint.go+++ b/internal/graft/corestore/sqlstore/checkpoint.go@@ -25,9 +25,8 @@ func (s *Store) CreateCheckpoint(ctx context.Context, repoID int64, in corestoreerr := s.withTx(ctx, nil, func(tx *sql.Tx) error {cp, created = corestore.Checkpoint{}, false- // LOCK ORDER (doc/graft/PLAN7.md): the repository row first. It serializes- // the checkpoint with changesets and with the review writes that move a- // review's commits, which the roots check below relies on.+ // LOCK ORDER (doc/graft/PLAN7.md): the repository row first, which+ // serializes the checkpoint with changesets.repo, err := s.selectRepository(ctx, tx, "repo_id = ?", []any{repoID}, true)if err != nil {return err@@ -53,10 +52,6 @@ func (s *Store) CreateCheckpoint(ctx context.Context, repoID int64, in corestorereturn fmt.Errorf("storage core: checkpoint at changeset %d is older than the newest checkpoint at %d of repository %d", in.Seq, newest.Seq, repoID)}- if err := s.checkReviewRoots(ctx, tx, repoID, in.Roots); err != nil {- return err- }-now, err := s.wallTime(ctx, tx)if err != nil {return err@@ -128,71 +123,9 @@ func validateCheckpoint(repoID int64, in corestore.CheckpointInput) error {}}- for _, root := range in.Roots {- if root == "" || !storableText(root) {- return fmt.Errorf("storage core: invalid checkpoint root %q", root)- }- }-- return nil-}--// checkRootsAt refuses a review write whose commits were checked against the-// reference snapshot at rootsAt when a newer checkpoint was recorded since-// (doc/graft/PLAN7.md, REVIEW ROOTS RULE R1): that checkpoint may not include-// them. The caller holds the repository row, which CreateCheckpoint takes-// first too, so the two are serialized.-func (s *Store) checkRootsAt(ctx context.Context, tx *sql.Tx, repoID int64, rootsAt uint64) error {- newest, ok, err := s.newestCheckpoint(ctx, tx, repoID)- if err != nil {- return err- }- if ok && newest.Seq > rootsAt {- return fmt.Errorf("checkpoint at changeset %d, review commits checked at %d: %w", newest.Seq, rootsAt, corestore.ErrReviewRootsStale)- }return nil}-// checkReviewRoots refuses the checkpoint when an open review has a head or-// base commit that is not one of the roots the checkpoint's pack includes: the-// review was created, or moved its head, during the build (doc/graft/PLAN7.md,-// REVIEW ROOTS RULE R2). The caller holds the repository row, which every-// review write that moves a review's commits takes first, so the reviews read-// here are the ones the checkpoint commits with.-func (s *Store) checkReviewRoots(ctx context.Context, tx *sql.Tx, repoID int64, roots []string) error {- included := make(map[string]struct{}, len(roots))- for _, root := range roots {- included[root] = struct{}{}- }-- rows, err := tx.QueryContext(ctx, s.bind("SELECT body FROM graft_reviews WHERE repo_id = ? AND closed = ?"), repoID, false)- if err != nil {- return fmt.Errorf("read open reviews: %w", err)- }- defer rows.Close()-- for rows.Next() {- var body string- if err := rows.Scan(&body); err != nil {- return fmt.Errorf("scan review: %w", err)- }- review, err := unmarshalReview(body)- if err != nil {- return err- }- for _, commit := range []string{review.GetHeadCommitId(), review.GetBaseCommitId()} {- if commit == "" {- continue- }- if _, ok := included[commit]; !ok {- return fmt.Errorf("review %s commit %s: %w", review.GetId(), commit, corestore.ErrCheckpointRootsChanged)- }- }- }-- return rows.Err()-}-// checkpointColumns are the columns read by scanCheckpoint, in order.const checkpointColumns = "seq, pack_key, pack_bytes, created_at"diff --git a/internal/graft/corestore/sqlstore/gc_test.go b/internal/graft/corestore/sqlstore/gc_test.goindex 6eabe17..f1ef5c1 100644--- a/internal/graft/corestore/sqlstore/gc_test.go+++ b/internal/graft/corestore/sqlstore/gc_test.go@@ -207,7 +207,6 @@ func TestCheckpointLifecycle(t *testing.T) {"no references": {Seq: 3, PackKey: ownedKey(repo.ID, "x")},"absent target": {Seq: 3, Refs: map[string]corestore.Target{"refs/heads/main": ""}, PackKey: ownedKey(repo.ID, "x")},"empty name": {Seq: 3, Refs: map[string]corestore.Target{"": oid(1)}, PackKey: ownedKey(repo.ID, "x")},- "empty root": {Seq: 3, Refs: refs, PackKey: ownedKey(repo.ID, "x"), Roots: []string{""}},} {_, _, err := s.CreateCheckpoint(ctx, repo.ID, bad)require.Error(t, err, name)@@ -243,98 +242,6 @@ func TestCheckpointLifecycle(t *testing.T) {})}-func TestCheckpointRequiresOpenReviewRoots(t *testing.T) {- forEachDialect(t, func(t *testing.T, ctx context.Context, s *sqlstore.Store) {- repo, _ := headRepo(t, ctx, s, "roots", 1)-- head, base := string(oid(10)), string(oid(11))- insert := func(r *gitalypb.Review) {- _, err := s.InsertReview(ctx, repo.ID, func(string) (*gitalypb.Review, error) { return r, nil }, 0)- require.NoError(t, err)- }- insert(&gitalypb.Review{TargetBranch: []byte("main"), HeadCommitId: head, BaseCommitId: base})- insert(&gitalypb.Review{TargetBranch: []byte("main"), HeadCommitId: string(oid(12)), State: gitalypb.Review_STATE_CLOSED})- insert(&gitalypb.Review{TargetBranch: []byte("main"), HeadCommitId: string(oid(13)), State: gitalypb.Review_STATE_LANDED})-- input := func(roots ...string) corestore.CheckpointInput {- return corestore.CheckpointInput{- Seq: 1, Refs: map[string]corestore.Target{"refs/heads/main": oid(1)}, PackKey: ownedKey(repo.ID, "roots"), Roots: roots,- }- }-- for _, roots := range [][]string{nil, {head}, {base}} {- _, _, err := s.CreateCheckpoint(ctx, repo.ID, input(roots...))- require.ErrorIs(t, err, corestore.ErrCheckpointRootsChanged, "roots %v", roots)-- _, ok, err := s.NewestCheckpoint(ctx, repo.ID)- require.NoError(t, err)- require.False(t, ok, "nothing recorded with roots %v", roots)- }-- // Closed and landed reviews are not roots.- _, created, err := s.CreateCheckpoint(ctx, repo.ID, input(head, base))- require.NoError(t, err)- require.True(t, created)- })-}--// TestReviewWritesRequireFreshRoots is REVIEW ROOTS R1 in the store: a review-// write whose commits were checked at a snapshot older than the newest-// checkpoint is refused and writes nothing; rootsAt 0 is unconditioned.-func TestReviewWritesRequireFreshRoots(t *testing.T) {- forEachDialect(t, func(t *testing.T, ctx context.Context, s *sqlstore.Store) {- repo, _ := headRepo(t, ctx, s, "fresh-roots", 3)- build := func(head string) func(string) (*gitalypb.Review, error) {- return func(string) (*gitalypb.Review, error) {- return &gitalypb.Review{TargetBranch: []byte("main"), HeadCommitId: head}, nil- }- }-- // Without a checkpoint any snapshot is fresh.- _, err := s.InsertReview(ctx, repo.ID, build(string(oid(10))), 1)- require.NoError(t, err)-- _, _, err = s.CreateCheckpoint(ctx, repo.ID, corestore.CheckpointInput{- Seq: 2, Refs: map[string]corestore.Target{"refs/heads/main": oid(2)}, PackKey: ownedKey(repo.ID, "fresh-roots"),- Roots: []string{string(oid(10))},- })- require.NoError(t, err)-- _, err = s.InsertReview(ctx, repo.ID, build(string(oid(11))), 1)- require.ErrorIs(t, err, corestore.ErrReviewRootsStale)- reviews, err := s.ListReviews(ctx, repo.ID, "", true, 0)- require.NoError(t, err)- require.Len(t, reviews, 1, "the refused creation wrote nothing")-- for _, rootsAt := range []uint64{2, 3, 0} {- _, err = s.InsertReview(ctx, repo.ID, build(string(oid(12))), rootsAt)- require.NoError(t, err, "rootsAt %d", rootsAt)- }-- r, version, err := s.GetReview(ctx, repo.ID, "1")- require.NoError(t, err)- r.HeadCommitId = string(oid(13))- require.ErrorIs(t, s.UpdateReview(ctx, repo.ID, "1", version, r, 1), corestore.ErrReviewRootsStale)- unchanged, unchangedVersion, err := s.GetReview(ctx, repo.ID, "1")- require.NoError(t, err)- require.Equal(t, version, unchangedVersion, "the refused update wrote nothing")- require.Equal(t, string(oid(10)), unchanged.GetHeadCommitId())-- require.NoError(t, s.UpdateReview(ctx, repo.ID, "1", version, r, 2))- r.Title = []byte("a comment moves no commit")- require.NoError(t, s.UpdateReview(ctx, repo.ID, "1", version+1, r, 0))-- // A head move of a removed repository finds no repository row.- gone, _ := headRepo(t, ctx, s, "fresh-roots-gone", 1)- _, err = s.InsertReview(ctx, gone.ID, build(string(oid(14))), 1)- require.NoError(t, err)- removed, err := s.DeleteRepository(ctx, gone.Key)- require.NoError(t, err)- require.True(t, removed)- require.ErrorIs(t, s.UpdateReview(ctx, gone.ID, "1", 1, r, 1), corestore.ErrRepositoryNotFound)- })-}-func TestSyncBoundaryUsesTheDatabaseClock(t *testing.T) {forEachDialect(t, func(t *testing.T, ctx context.Context, s *sqlstore.Store) {repo, _ := headRepo(t, ctx, s, "boundary", 3)@@ -599,7 +506,7 @@ func TestLockOrderConcurrentWriters(t *testing.T) {_, err := a.InsertReview(ctx, repo.ID, func(string) (*gitalypb.Review, error) {return &gitalypb.Review{TargetBranch: []byte("main"), HeadCommitId: string(oid(500))}, nil- }, 0)+ }, false)require.NoError(t, err)const (@@ -612,52 +519,79 @@ func TestLockOrderConcurrentWriters(t *testing.T) {var (mu sync.MutexcreatedSeqs []uint64- rootsRefused int- rootsStale int+ rootsMissing int+ swept, inUse int+ committed atomic.Int32unexpected []errorrecordUnexpected = func(err error) { mu.Lock(); unexpected = append(unexpected, err); mu.Unlock() }nodes = []*sqlstore.Store{a, b}g errgroup.Group)- // writeRoots runs a review write that moves commits as the review service- // does (REVIEW ROOTS R1): with the sequence of a fresh snapshot, again- // after ErrReviewRootsStale. Its own bound is generous: the test counts- // the conflicts instead of failing on the service's third one.- writeRoots := func(s *sqlstore.Store, write func(rootsAt uint64) error) error {+ // protect writes the keep-around reference of the commit, as the review+ // service does through the voter; a reference that exists is a conflict+ // and left as it is.+ protect := func(s *sqlstore.Store, root string) error {+ _, err := commit(ctx, s, repo.ID, create(corestore.KeepAroundRef(root), corestore.Target(root)))+ var conflict *corestore.ErrRefConflict+ switch {+ case err == nil:+ committed.Add(1)+ return nil+ case errors.As(err, &conflict):+ return nil+ default:+ return err+ }+ }++ // writeRoots runs a review write that records commit as the review+ // service does (REVIEW ROOTS RULE): its reference first, then the write+ // that requires it, again after ErrReviewRootsMissing (the sweeper below+ // deleted the reference in between). Its own bound is generous: the test+ // counts the retries instead of failing on the service's third attempt.+ writeRoots := func(s *sqlstore.Store, root string, write func() error) error {for range 20 {- _, rootsAt, err := s.Refs(ctx, repo.ID)- if err != nil {+ if err := protect(s, root); err != nil {return err}- err = write(rootsAt)- if !errors.Is(err, corestore.ErrReviewRootsStale) {+ err := write()+ if !errors.Is(err, corestore.ErrReviewRootsMissing) {return err}mu.Lock()- rootsStale+++ rootsMissing++mu.Unlock()}- return errors.New("the review write kept conflicting with checkpoints")+ return errors.New("the review write kept losing its keep-around reference")}+ // The review writers below; the sweeper runs until they are done, so that+ // it races with every one of them.+ var writers sync.WaitGroup+ writersDone := make(chan struct{})+for n, s := range nodes {g.Go(func() error {for i := range landsPerNode {ref := fmt.Sprintf("refs/heads/node-%d-%d", n, i)if _, err := commitPack(ctx, s, repo.ID, create(ref, oid(1000+i)), ownedKey(repo.ID, ref)); err != nil {recordUnexpected(fmt.Errorf("land %s: %w", ref, err))+ continue}+ committed.Add(1)}return nil})+ writers.Add(1)g.Go(func() error {+ defer writers.Done()for i := range reviewsPerNode {head := string(oid(2000 + 100*n + i))- if err := writeRoots(s, func(rootsAt uint64) error {+ if err := writeRoots(s, head, func() error {_, err := s.InsertReview(ctx, repo.ID, func(string) (*gitalypb.Review, error) {return &gitalypb.Review{TargetBranch: []byte("main"), HeadCommitId: head}, nil- }, rootsAt)+ }, true)return err}); err != nil {recordUnexpected(fmt.Errorf("insert review: %w", err))@@ -667,17 +601,59 @@ func TestLockOrderConcurrentWriters(t *testing.T) {})}+ // The sweeper deletes every keep-around reference it finds; the database+ // refuses those that an open review uses.+ g.Go(func() error {+ for {+ select {+ case <-writersDone:+ return nil+ default:+ }++ refs, _, err := b.Refs(ctx, repo.ID)+ if err != nil {+ recordUnexpected(err)+ return nil+ }+ for name, target := range refs {+ if !strings.HasPrefix(name, corestore.KeepAroundPrefix) {+ continue+ }+ _, err := commit(ctx, b, repo.ID, update(name, target, ""))+ var conflict *corestore.ErrRefConflict+ switch {+ case err == nil:+ committed.Add(1)+ mu.Lock()+ swept+++ mu.Unlock()+ case errors.Is(err, corestore.ErrReviewRootInUse):+ mu.Lock()+ inUse+++ mu.Unlock()+ case errors.As(err, &conflict):+ default:+ recordUnexpected(fmt.Errorf("sweep %s: %w", name, err))+ }+ }+ }+ })+// Head moves of review 1: the repository row first, then the version// compare-and-swap of the review row.+ writers.Add(1)g.Go(func() error {+ defer writers.Done()for done := 0; done < updates; {- err := writeRoots(a, func(rootsAt uint64) error {+ head := string(oid(3000 + done))+ err := writeRoots(a, head, func() error {r, version, err := a.GetReview(ctx, repo.ID, "1")if err != nil {return err}- r.HeadCommitId = string(oid(3000 + done))- return a.UpdateReview(ctx, repo.ID, "1", version, r, rootsAt)+ r.HeadCommitId = head+ return a.UpdateReview(ctx, repo.ID, "1", version, r, true)})switch {case err == nil:@@ -690,6 +666,10 @@ func TestLockOrderConcurrentWriters(t *testing.T) {}return nil})+ go func() {+ writers.Wait()+ close(writersDone)+ }()// Updates of one review that do not move its commits (a comment): a// version compare-and-swap on the review row only.@@ -701,7 +681,7 @@ func TestLockOrderConcurrentWriters(t *testing.T) {return nil}r.Title = []byte(fmt.Sprintf("comment %d", done))- switch err := b.UpdateReview(ctx, repo.ID, "1", version, r, 0); {+ switch err := b.UpdateReview(ctx, repo.ID, "1", version, r, false); {case err == nil:done++case errors.Is(err, corestore.ErrReviewVersionConflict):@@ -713,20 +693,7 @@ func TestLockOrderConcurrentWriters(t *testing.T) {return nil})- // Checkpoints at the head. Their roots include every head the review- // writers above will record (R2 requires a superset of the open- // reviews' commits), so that checkpoints commit while the R1 writes run- // instead of being refused by them; R2's refusal is tested- // deterministically in TestCheckpointRequiresOpenReviewRoots.- roots := []string{string(oid(500))}- for n := range nodes {- for i := range reviewsPerNode {- roots = append(roots, string(oid(2000+100*n+i)))- }- }- for done := range updates {- roots = append(roots, string(oid(3000+done)))- }+ // Checkpoints at the head.g.Go(func() error {for range checkpoints {refs, head, err := a.Refs(ctx, repo.ID)@@ -736,7 +703,7 @@ func TestLockOrderConcurrentWriters(t *testing.T) {}cp, created, err := a.CreateCheckpoint(ctx, repo.ID, corestore.CheckpointInput{- Seq: head, Refs: refs, PackKey: ownedKey(repo.ID, fmt.Sprint("checkpoint ", head)), Roots: roots,+ Seq: head, Refs: refs, PackKey: ownedKey(repo.ID, fmt.Sprint("checkpoint ", head)),})switch {case err == nil && created:@@ -744,10 +711,6 @@ func TestLockOrderConcurrentWriters(t *testing.T) {createdSeqs = append(createdSeqs, cp.Seq)mu.Unlock()case err == nil:- case errors.Is(err, corestore.ErrCheckpointRootsChanged):- mu.Lock()- rootsRefused++- mu.Unlock()default:recordUnexpected(fmt.Errorf("checkpoint at %d: %w", head, err))}@@ -772,10 +735,11 @@ func TestLockOrderConcurrentWriters(t *testing.T) {require.Empty(t, unexpected)require.Zero(t, deadlocks.Load(), "a transaction deadlocked")- // Dense changesets: the first one plus every land.+ // Dense changesets: the first one plus every land, keep-around write and+ // sweep that committed.final, err := a.GetRepository(ctx, testKey("lock-order"))require.NoError(t, err)- require.Equal(t, uint64(1+2*landsPerNode), final.HeadSeq)+ require.Equal(t, uint64(1+committed.Load()), final.HeadSeq)changesets, err := a.ListChangesets(ctx, repo.ID, 0, final.HeadSeq)require.NoError(t, err)require.Len(t, changesets, int(final.HeadSeq))@@ -798,11 +762,21 @@ func TestLockOrderConcurrentWriters(t *testing.T) {recorded = append(recorded, cp.Seq)}require.Equal(t, createdSeqs, recorded)- require.Zero(t, rootsRefused, "the roots include every review commit")- t.Logf("checkpoints created %d; review writes refused after a newer checkpoint %d", len(createdSeqs), rootsStale)+ t.Logf("checkpoints created %d; keep-around references swept %d, kept for an open review %d; review writes retried after a sweep %d",+ len(createdSeqs), swept, inUse, rootsMissing)r, _, err := a.GetReview(ctx, repo.ID, "1")require.NoError(t, err)require.Equal(t, string(oid(3000+updates-1)), r.GetHeadCommitId(), "every head move applied")++ // The REVIEW ROOTS invariant: every open review written with its roots+ // required has the keep-around reference of its head. Review 1 was+ // inserted without, but every head move required its new head.+ refs, _, err := a.Refs(ctx, repo.ID)+ require.NoError(t, err)+ for _, review := range reviews {+ head := review.GetHeadCommitId()+ require.Equal(t, corestore.Target(head), refs[corestore.KeepAroundRef(head)], "review %s", review.GetId())+ }})}diff --git a/internal/graft/corestore/sqlstore/history_test.go b/internal/graft/corestore/sqlstore/history_test.goindex c3739d0..2fb57f5 100644--- a/internal/graft/corestore/sqlstore/history_test.go+++ b/internal/graft/corestore/sqlstore/history_test.go@@ -85,7 +85,7 @@ func TestImportHistory(t *testing.T) {inserted, err := s.InsertReview(ctx, repo.ID, func(id string) (*gitalypb.Review, error) {return newReview("next", "main", gitalypb.Review_STATE_OPEN_UNSPECIFIED), nil- }, 0)+ }, false)require.NoError(t, err)require.Equal(t, "8", inserted.GetId(), "the next review ID follows the largest imported one")@@ -140,7 +140,7 @@ func TestImportHistoryReplacesReviewsChangedInShadowMode(t *testing.T) {// Review 2 was changed in the database after the file (authoritative mode).dbChanged := review("2", "changed in the database", 0, 2*time.Hour)- require.NoError(t, s.UpdateReview(ctx, repo.ID, "2", 1, dbChanged, 0))+ require.NoError(t, s.UpdateReview(ctx, repo.ID, "2", 1, dbChanged, false))closed := review("1", "closed in shadow mode", 0, time.Hour)closed.State = gitalypb.Review_STATE_CLOSED@@ -183,7 +183,7 @@ func TestImportHistoryReplacesReviewsChangedInShadowMode(t *testing.T) {require.Equal(t, []string{"5", "4", "3", "2"}, openIDs)// An update based on the version before the import re-reads the review.- require.ErrorIs(t, s.UpdateReview(ctx, repo.ID, "1", 1, review("1", "stale", 0, 4*time.Hour), 0), corestore.ErrReviewVersionConflict)+ require.ErrorIs(t, s.UpdateReview(ctx, repo.ID, "1", 1, review("1", "stale", 0, 4*time.Hour), false), corestore.ErrReviewVersionConflict)// Idempotent: the same file reviews write nothing new._, reviews, err = s.ImportHistory(ctx, repo.ID, nil, []*gitalypb.Review{closed, review("5", "created in shadow mode", 3*time.Hour, 3*time.Hour)})diff --git a/internal/graft/corestore/sqlstore/review.go b/internal/graft/corestore/sqlstore/review.goindex 7c1ef9d..d31842c 100644--- a/internal/graft/corestore/sqlstore/review.go+++ b/internal/graft/corestore/sqlstore/review.go@@ -41,7 +41,7 @@ func unmarshalReview(body string) (*gitalypb.Review, error) {}// InsertReview implements corestore.MetaStore.-func (s *Store) InsertReview(ctx context.Context, repoID int64, build func(id string) (*gitalypb.Review, error), rootsAt uint64) (*gitalypb.Review, error) {+func (s *Store) InsertReview(ctx context.Context, repoID int64, build func(id string) (*gitalypb.Review, error), requireRoots bool) (*gitalypb.Review, error) {var stored *gitalypb.Reviewerr := s.withTx(ctx, nil, func(tx *sql.Tx) error {@@ -52,11 +52,6 @@ func (s *Store) InsertReview(ctx context.Context, repoID int64, build func(id stif err != nil {return err}- if rootsAt != 0 {- if err := s.checkRootsAt(ctx, tx, repoID, rootsAt); err != nil {- return err- }- }id := repo.nextReviewIDbuilt, err := build(fmt.Sprintf("%d", id))@@ -68,6 +63,11 @@ func (s *Store) InsertReview(ctx context.Context, repoID int64, build func(id st}r := prepareReview(built, fmt.Sprintf("%d", id))+ if requireRoots {+ if err := s.requireReviewRoots(ctx, tx, repoID, r); err != nil {+ return err+ }+ }body, err := marshalReview(r)if err != nil {return err@@ -170,21 +170,22 @@ func (s *Store) ListReviews(ctx context.Context, repoID int64, targetBranch stri}// UpdateReview implements corestore.MetaStore.-func (s *Store) UpdateReview(ctx context.Context, repoID int64, id string, version int64, r *gitalypb.Review, rootsAt uint64) error {+func (s *Store) UpdateReview(ctx context.Context, repoID int64, id string, version int64, r *gitalypb.Review, requireRoots bool) error {reviewID, ok := parseReviewID(id)if !ok {return corestore.ErrReviewNotFound}return s.withTx(ctx, nil, func(tx *sql.Tx) error {- // An update that moves the review's head serializes with checkpoint- // commits: LOCK ORDER, the repository row first. The others touch only- // the review row and never lock the repository row.- if rootsAt != 0 {+ // An update that may move the review's head serializes with the+ // changesets that could delete its keep-around references: LOCK ORDER,+ // the repository row first. The others touch only the review row and+ // never lock the repository row.+ if requireRoots {if _, err := s.selectRepository(ctx, tx, "repo_id = ?", []any{repoID}, true); err != nil {return err}- if err := s.checkRootsAt(ctx, tx, repoID, rootsAt); err != nil {+ if err := s.requireReviewRoots(ctx, tx, repoID, r); err != nil {return err}}diff --git a/internal/graft/corestore/sqlstore/review_test.go b/internal/graft/corestore/sqlstore/review_test.goindex 417e55b..07c1744 100644--- a/internal/graft/corestore/sqlstore/review_test.go+++ b/internal/graft/corestore/sqlstore/review_test.go@@ -19,7 +19,7 @@ func insertReview(t *testing.T, ctx context.Context, s *sqlstore.Store, repoID iinserted, err := s.InsertReview(ctx, repoID, func(id string) (*gitalypb.Review, error) {return r, nil- }, 0)+ }, false)require.NoError(t, err)return inserted}@@ -49,17 +49,17 @@ func TestReviewsCRUD(t *testing.T) {// Updates succeed on the current version only.updated := newReview("two, edited", "release", gitalypb.Review_STATE_OPEN_UNSPECIFIED)- require.NoError(t, s.UpdateReview(ctx, repo.ID, "2", 1, updated, 0))+ require.NoError(t, s.UpdateReview(ctx, repo.ID, "2", 1, updated, false))_, version, err = s.GetReview(ctx, repo.ID, "2")require.NoError(t, err)require.Equal(t, int64(2), version)- err = s.UpdateReview(ctx, repo.ID, "2", 1, updated, 0)+ err = s.UpdateReview(ctx, repo.ID, "2", 1, updated, false)require.ErrorIs(t, err, corestore.ErrReviewVersionConflict)- err = s.UpdateReview(ctx, repo.ID, "99", 1, updated, 0)+ err = s.UpdateReview(ctx, repo.ID, "99", 1, updated, false)require.ErrorIs(t, err, corestore.ErrReviewNotFound)- err = s.UpdateReview(ctx, repo.ID, "abc", 1, updated, 0)+ err = s.UpdateReview(ctx, repo.ID, "abc", 1, updated, false)require.ErrorIs(t, err, corestore.ErrReviewNotFound)// Listing is newest first, filtered by target and by state.@@ -113,7 +113,7 @@ func TestReviewsConcurrentUpdatesLoseNothing(t *testing.T) {next := fmt.Sprintf("%d", i)current.Title = []byte(next)- err = store.UpdateReview(ctx, repo.ID, "1", version, current, 0)+ err = store.UpdateReview(ctx, repo.ID, "1", version, current, false)if errors.Is(err, corestore.ErrReviewVersionConflict) {continue}diff --git a/internal/graft/corestore/sqlstore/reviewroots.go b/internal/graft/corestore/sqlstore/reviewroots.gonew file mode 100644index 0000000..493f028--- /dev/null+++ b/internal/graft/corestore/sqlstore/reviewroots.go@@ -0,0 +1,92 @@+package sqlstore++import (+ "context"+ "database/sql"+ "fmt"+ "strings"++ "github.com/feder-cr/git-ai/internal/graft/corestore"+ "github.com/feder-cr/git-ai/proto/go/gitalypb"+)++// The REVIEW ROOTS RULE (doc/graft/PLAN7.md) keeps the invariant "every open+// review written with requireRoots has the keep-around reference of its head+// and base commits" with two checks. Both run under the repository row lock,+// which review writes with requireRoots and every changeset take first (LOCK+// ORDER), so a review write and a deletion of one of its references are+// serialized: either the deletion is refused, or the review write finds the+// reference gone and fails.++// requireReviewRoots refuses a review write whose head or base commit has no+// keep-around reference with that commit as its value.+func (s *Store) requireReviewRoots(ctx context.Context, tx *sql.Tx, repoID int64, r *gitalypb.Review) error {+ commits := reviewCommits(r)+ if len(commits) == 0 {+ return nil+ }++ names := make([]string, 0, len(commits))+ for _, commit := range commits {+ names = append(names, corestore.KeepAroundRef(commit))+ }+ current, err := s.currentTargets(ctx, tx, repoID, names)+ if err != nil {+ return err+ }++ for _, commit := range commits {+ if current[corestore.KeepAroundRef(commit)] != corestore.Target(commit) {+ return fmt.Errorf("review commit %s: %w", commit, corestore.ErrReviewRootsMissing)+ }+ }+ return nil+}++// refuseReleasedRoots refuses a changeset that deletes or moves a keep-around+// reference whose value is the head or base commit of an open review.+func (s *Store) refuseReleasedRoots(ctx context.Context, tx *sql.Tx, repoID int64, updates []corestore.AppliedUpdate) error {+ released := map[string]string{}+ for _, u := range updates {+ if strings.HasPrefix(u.Name, corestore.KeepAroundPrefix) && !u.Old.Absent() && !u.Old.IsSymbolic() && u.Old != u.New {+ released[string(u.Old)] = u.Name+ }+ }+ if len(released) == 0 {+ return nil+ }++ rows, err := tx.QueryContext(ctx, s.bind("SELECT body FROM graft_reviews WHERE repo_id = ? AND closed = ?"), repoID, false)+ if err != nil {+ return fmt.Errorf("read open reviews: %w", err)+ }+ defer rows.Close()++ for rows.Next() {+ var body string+ if err := rows.Scan(&body); err != nil {+ return fmt.Errorf("scan review: %w", err)+ }+ review, err := unmarshalReview(body)+ if err != nil {+ return err+ }+ for _, commit := range reviewCommits(review) {+ if name, ok := released[commit]; ok {+ return fmt.Errorf("reference %q, review %s: %w", name, review.GetId(), corestore.ErrReviewRootInUse)+ }+ }+ }+ return rows.Err()+}++// reviewCommits returns the head and base commits of the review that are set.+func reviewCommits(r *gitalypb.Review) []string {+ var commits []string+ for _, commit := range []string{r.GetHeadCommitId(), r.GetBaseCommitId()} {+ if commit != "" {+ commits = append(commits, commit)+ }+ }+ return commits+}diff --git a/internal/graft/corestore/sqlstore/reviewroots_test.go b/internal/graft/corestore/sqlstore/reviewroots_test.gonew file mode 100644index 0000000..fcc590e--- /dev/null+++ b/internal/graft/corestore/sqlstore/reviewroots_test.go@@ -0,0 +1,151 @@+package sqlstore_test++import (+ "context"+ "testing"++ "github.com/stretchr/testify/require"++ "github.com/feder-cr/git-ai/internal/graft/corestore"+ "github.com/feder-cr/git-ai/internal/graft/corestore/sqlstore"+ "github.com/feder-cr/git-ai/proto/go/gitalypb"+)++// keepAround commits the keep-around reference of root.+func keepAround(t *testing.T, ctx context.Context, s *sqlstore.Store, repoID int64, root corestore.Target) {+ t.Helper()+ _, err := commit(ctx, s, repoID, create(corestore.KeepAroundRef(string(root)), root))+ require.NoError(t, err)+}++// TestReviewWritesRequireRootReferences: a review write that requires its+// roots is refused, writing nothing, while its head or base commit has no+// keep-around reference with that value (doc/graft/PLAN7.md, REVIEW ROOTS+// RULE).+func TestReviewWritesRequireRootReferences(t *testing.T) {+ forEachDialect(t, func(t *testing.T, ctx context.Context, s *sqlstore.Store) {+ repo, _ := headRepo(t, ctx, s, "root-refs", 1)+ head, base := oid(10), oid(11)+ build := func(head, base corestore.Target) func(string) (*gitalypb.Review, error) {+ return func(string) (*gitalypb.Review, error) {+ return &gitalypb.Review{TargetBranch: []byte("main"), HeadCommitId: string(head), BaseCommitId: string(base)}, nil+ }+ }+ requireReviews := func(n int) {+ t.Helper()+ reviews, err := s.ListReviews(ctx, repo.ID, "", true, 0)+ require.NoError(t, err)+ require.Len(t, reviews, n)+ }++ _, err := s.InsertReview(ctx, repo.ID, build(head, base), true)+ require.ErrorIs(t, err, corestore.ErrReviewRootsMissing, "no reference at all")+ keepAround(t, ctx, s, repo.ID, head)+ _, err = s.InsertReview(ctx, repo.ID, build(head, base), true)+ require.ErrorIs(t, err, corestore.ErrReviewRootsMissing, "the base has none")+ requireReviews(0)++ // A keep-around reference with another value does not protect the commit.+ _, err = commit(ctx, s, repo.ID, create(corestore.KeepAroundRef(string(base)), oid(12)))+ require.NoError(t, err)+ _, err = s.InsertReview(ctx, repo.ID, build(head, base), true)+ require.ErrorIs(t, err, corestore.ErrReviewRootsMissing)+ _, err = commit(ctx, s, repo.ID, update(corestore.KeepAroundRef(string(base)), oid(12), base))+ require.NoError(t, err)++ created, err := s.InsertReview(ctx, repo.ID, build(head, base), true)+ require.NoError(t, err)+ requireReviews(1)++ // A head move to an unprotected commit is refused and writes nothing.+ r, version, err := s.GetReview(ctx, repo.ID, created.GetId())+ require.NoError(t, err)+ r.HeadCommitId = string(oid(13))+ require.ErrorIs(t, s.UpdateReview(ctx, repo.ID, created.GetId(), version, r, true), corestore.ErrReviewRootsMissing)+ unchanged, unchangedVersion, err := s.GetReview(ctx, repo.ID, created.GetId())+ require.NoError(t, err)+ require.Equal(t, version, unchangedVersion)+ require.Equal(t, string(head), unchanged.GetHeadCommitId())++ keepAround(t, ctx, s, repo.ID, oid(13))+ require.NoError(t, s.UpdateReview(ctx, repo.ID, created.GetId(), version, r, true))++ // Writes that do not require the roots are not conditioned: imports and+ // comments.+ _, err = s.InsertReview(ctx, repo.ID, build(oid(14), ""), false)+ require.NoError(t, err)+ r.Title = []byte("a comment")+ require.NoError(t, s.UpdateReview(ctx, repo.ID, created.GetId(), version+1, r, false))++ // A required write of a removed repository finds no repository row.+ gone, _ := headRepo(t, ctx, s, "root-refs-gone", 1)+ _, err = s.InsertReview(ctx, gone.ID, build(oid(15), ""), false)+ require.NoError(t, err)+ removed, err := s.DeleteRepository(ctx, gone.Key)+ require.NoError(t, err)+ require.True(t, removed)+ require.ErrorIs(t, s.UpdateReview(ctx, gone.ID, "1", 1, r, true), corestore.ErrRepositoryNotFound)+ })+}++// TestOpenReviewRootsCannotBeReleased: a changeset that deletes or moves the+// keep-around reference of an open review's head or base is refused, writing+// nothing; forced changesets (shadow mode) are not, and closed reviews keep+// nothing.+func TestOpenReviewRootsCannotBeReleased(t *testing.T) {+ forEachDialect(t, func(t *testing.T, ctx context.Context, s *sqlstore.Store) {+ repo, _ := headRepo(t, ctx, s, "release-roots", 1)+ head, base, closed := oid(10), oid(11), oid(12)+ for _, c := range []corestore.Target{head, base, closed} {+ keepAround(t, ctx, s, repo.ID, c)+ }+ open, err := s.InsertReview(ctx, repo.ID, func(string) (*gitalypb.Review, error) {+ return &gitalypb.Review{TargetBranch: []byte("main"), HeadCommitId: string(head), BaseCommitId: string(base)}, nil+ }, true)+ require.NoError(t, err)+ _, err = s.InsertReview(ctx, repo.ID, func(string) (*gitalypb.Review, error) {+ return &gitalypb.Review{TargetBranch: []byte("main"), HeadCommitId: string(closed), State: gitalypb.Review_STATE_CLOSED}, nil+ }, true)+ require.NoError(t, err)++ before, seq, err := s.Refs(ctx, repo.ID)+ require.NoError(t, err)+ for desc, updates := range map[string][]corestore.RefUpdate{+ "delete the head's": {update(corestore.KeepAroundRef(string(head)), head, "")},+ "delete the base's": {update(corestore.KeepAroundRef(string(base)), base, "")},+ "move the head's": {update(corestore.KeepAroundRef(string(head)), head, oid(99))},+ "force-delete the head's": {force(corestore.KeepAroundRef(string(head)), "")},+ "with an unrelated deletion": {update(corestore.KeepAroundRef(string(closed)), closed, ""), update(corestore.KeepAroundRef(string(base)), base, "")},+ } {+ _, err := commit(ctx, s, repo.ID, updates...)+ require.ErrorIs(t, err, corestore.ErrReviewRootInUse, desc)+ after, afterSeq, err := s.Refs(ctx, repo.ID)+ require.NoError(t, err)+ require.Equal(t, before, after, "%s: nothing written", desc)+ require.Equal(t, seq, afterSeq)+ }++ // A closed review's commit is not a root.+ _, err = commit(ctx, s, repo.ID, update(corestore.KeepAroundRef(string(closed)), closed, ""))+ require.NoError(t, err)++ // Shadow mode records what git did: forced changesets are not refused.+ _, err = s.CommitChangeset(ctx, corestore.ChangesetInput{+ RepoID: repo.ID,+ Updates: []corestore.RefUpdate{update(corestore.KeepAroundRef(string(base)), base, "")},+ Operation: "test",+ Actor: "tester",+ NodeID: "node-a",+ Force: true,+ })+ require.NoError(t, err)++ // Once the review is closed its commits are released.+ r, version, err := s.GetReview(ctx, repo.ID, open.GetId())+ require.NoError(t, err)+ r.State = gitalypb.Review_STATE_CLOSED+ require.NoError(t, s.UpdateReview(ctx, repo.ID, open.GetId(), version, r, false))+ _, err = commit(ctx, s, repo.ID, update(corestore.KeepAroundRef(string(head)), head, ""))+ require.NoError(t, err)+ })+}diff --git a/internal/graft/corestore/sqlstore/robustness_test.go b/internal/graft/corestore/sqlstore/robustness_test.goindex a43033c..9a110c5 100644--- a/internal/graft/corestore/sqlstore/robustness_test.go+++ b/internal/graft/corestore/sqlstore/robustness_test.go@@ -79,7 +79,7 @@ func TestWritesHonourDeadlineWhileLocked(t *testing.T) {call: func(ctx context.Context) error {_, err := s.InsertReview(ctx, repo.ID, func(string) (*gitalypb.Review, error) {return newReview("t", "refs/heads/main", gitalypb.Review_STATE_OPEN_UNSPECIFIED), nil- }, 0)+ }, false)return err},},diff --git a/internal/graft/corestore/sqlstore/store_test.go b/internal/graft/corestore/sqlstore/store_test.goindex decd5c1..8531aab 100644--- a/internal/graft/corestore/sqlstore/store_test.go+++ b/internal/graft/corestore/sqlstore/store_test.go@@ -454,7 +454,7 @@ func TestRegisterWithHistory(t *testing.T) {inserted, err := s.InsertReview(ctx, repo.ID, func(id string) (*gitalypb.Review, error) {require.Equal(t, "4", id)return newReview("new", "main", gitalypb.Review_STATE_OPEN_UNSPECIFIED), nil- }, 0)+ }, false)require.NoError(t, err)require.Equal(t, "4", inserted.GetId())@@ -491,7 +491,7 @@ func TestDeleteCascadesAndReRegisterGetsNewID(t *testing.T) {require.NoError(t, err)_, err = s.InsertReview(ctx, first.ID, func(id string) (*gitalypb.Review, error) {return newReview("doomed", "main", gitalypb.Review_STATE_OPEN_UNSPECIFIED), nil- }, 0)+ }, false)require.NoError(t, err)deleted, err := s.DeleteRepository(ctx, key)diff --git a/internal/graft/corestore/types.go b/internal/graft/corestore/types.goindex a15f789..8951076 100644--- a/internal/graft/corestore/types.go+++ b/internal/graft/corestore/types.go@@ -153,9 +153,9 @@ type Changeset struct {}// Checkpoint is a consolidated state of a repository at a changeset sequence:-// one pack with every object reachable from the references at Seq and from the-// roots of the reviews open when it was built, plus the reference snapshot at-// Seq (MetaStore.CheckpointRefs). Hydration starts from the newest checkpoint+// one pack with every object reachable from the references at Seq (among them+// the keep-around references of the open reviews), plus the reference snapshot+// at Seq (MetaStore.CheckpointRefs). Hydration starts from the newest checkpoint// and replays only the changesets after it (doc/graft/PLAN7.md).type Checkpoint struct {RepoID int64@@ -227,16 +227,15 @@ var (// ErrCheckpointNotFound is returned for a checkpoint sequence the// repository has no checkpoint at.ErrCheckpointNotFound = errors.New("storage core: checkpoint not found")- // ErrCheckpointRootsChanged is returned by MetaStore.CreateCheckpoint when an- // open review has a head or base commit that the checkpoint's pack does not- // include: the review was created or moved during the build- // (doc/graft/PLAN7.md, REVIEW ROOTS RULE R2).- ErrCheckpointRootsChanged = errors.New("storage core: the open reviews changed during the checkpoint build")- // ErrReviewRootsStale is returned by MetaStore.InsertReview and UpdateReview- // when a checkpoint newer than the snapshot the review's commits were checked- // at was recorded in between: the caller checks the commits again against a- // new snapshot (doc/graft/PLAN7.md, REVIEW ROOTS RULE R1).- ErrReviewRootsStale = errors.New("storage core: a checkpoint was recorded after the review's commits were checked")+ // ErrReviewRootsMissing is returned by MetaStore.InsertReview and+ // UpdateReview, when they require the review's roots, for a head or base+ // commit that has no keep-around reference (KeepAroundRef): the caller writes+ // the reference again and retries (doc/graft/PLAN7.md, REVIEW ROOTS RULE).+ ErrReviewRootsMissing = errors.New("storage core: a commit of the review has no keep-around reference")+ // ErrReviewRootInUse is returned by MetaStore.CommitChangeset for a changeset+ // that deletes or moves the keep-around reference of a commit that an open+ // review uses; nothing is written (doc/graft/PLAN7.md, REVIEW ROOTS RULE).+ ErrReviewRootInUse = errors.New("storage core: the keep-around reference is the root of an open review")// ErrPackDeadline is returned when a pack upload, or the commit of the row// that references it, would end after the write deadline: garbage collection// may then already treat the pack as an orphan (doc/graft/PLAN7.md, PACK@@ -328,6 +327,16 @@ func parsePackKey(key string) (repoID int64, sum [32]byte, owned, ok bool) {return id, sum, owned, true}+// KeepAroundPrefix is the prefix of the references that keep the commits of+// open reviews alive: Gitaly hides it from clients (it is neither advertised+// nor writable over the git protocols), housekeeping and garbage collection+// respect it like every reference (doc/graft/PLAN7.md, REVIEW ROOTS RULE).+const KeepAroundPrefix = "refs/keep-around/"++// KeepAroundRef returns the keep-around reference of a commit; its target is+// the commit itself.+func KeepAroundRef(oid string) string { return KeepAroundPrefix + oid }+// IsChangelogRef reports whether updates of the reference are recorded in the// Graft changelog: branches and tags, as changelog.ParseUpdates does.func IsChangelogRef(name string) bool {diff --git a/internal/graft/corestore/voter/voter.go b/internal/graft/corestore/voter/voter.goindex 4b1e3f9..9a382ec 100644--- a/internal/graft/corestore/voter/voter.go+++ b/internal/graft/corestore/voter/voter.go@@ -410,6 +410,11 @@ func (v *Voter) prepare(ctx context.Context, payload gitcmd.HooksPayload, change}return structerr.NewFailedPrecondition("storage core: repository is not imported into the storage core")}+ if errors.Is(err, corestore.ErrReviewRootInUse) {+ // Only non-forced (authoritative) changesets are refused.+ result = resultConflict+ return structerr.NewFailedPrecondition("%w", err)+ }if err != nil {return v.unavailable(err)}