Git designed for AI agents.
land batch: one range query per member, objects durable once as a pack
Federico Elia3171cb0e45c8
diff --git a/internal/git/localrepo/rebase_options_export.go b/internal/git/localrepo/rebase_options_export.godeleted file mode 100644index 5733062..0000000--- a/internal/git/localrepo/rebase_options_export.go+++ /dev/null@@ -1,27 +0,0 @@-package localrepo--import "github.com/feder-cr/git-ai/internal/git"--// RebaseSettings is the resolved form of a set of RebaseOptions. It lets packages that implement-// a rebase on top of the localrepo primitives honor the same options as (*Repo).Rebase.-type RebaseSettings struct {- // Committer is the signature to use as committer of the rebased commits. Nil means that each- // commit keeps the committer of the commit it replays.- Committer *git.Signature- // ReapplyCherryPicks is set when patch-equivalent commits must be picked, see- // RebaseWithReappliedCherryPicks.- ReapplyCherryPicks bool-}--// ResolveRebaseOptions applies options and returns the resulting settings.-func ResolveRebaseOptions(options ...RebaseOption) RebaseSettings {- var config rebaseConfig- for _, option := range options {- option(&config)- }-- return RebaseSettings{- Committer: config.committer,- ReapplyCherryPicks: config.reapplyCherryPicks,- }-}diff --git a/internal/gitaly/service/operations/land_batch_metrics.go b/internal/gitaly/service/operations/land_batch_metrics.goindex b545f1c..03c30af 100644--- a/internal/gitaly/service/operations/land_batch_metrics.go+++ b/internal/gitaly/service/operations/land_batch_metrics.go@@ -19,6 +19,13 @@ const (// landBatchPhaseLandMember is the landing of one request onto the running tip. It is observed// once per request of an attempt.landBatchPhaseLandMember = "land_member"+ // landBatchPhasePlan is the decision of how one request lands, from one listing of the commits it+ // adds to the running tip. It is observed once per request that reaches it.+ landBatchPhasePlan = "plan"+ // landBatchPhaseReplay is the replay of the commits of one rebased request.+ landBatchPhaseReplay = "replay"+ // landBatchPhasePack is the packing of the objects of an attempt before its compare-and-swap.+ landBatchPhasePack = "pack"// landBatchPhaseUpdate is the compare-and-swap that publishes a batch, with the hooks.landBatchPhaseUpdate = "update"// landBatchPhaseTotal is the whole execution of a batch, from its start to its outcomes.@@ -44,10 +51,16 @@ var (landBatchPhaseSeconds = promauto.NewHistogramVec(prometheus.HistogramOpts{Name: "graft_land_batch_phase_seconds",Help: "Time spent in each phase of a land batch: quarantine, tip, land_member (one observation per " +- "request of a batch attempt), update (the compare-and-swap with the hooks) and total.",+ "request of a batch attempt), plan and replay (parts of land_member), pack (the objects of an " ++ "attempt before its update), update (the compare-and-swap with the hooks) and total.",Buckets: prometheus.DefBuckets,}, []string{"phase"})+ landBatchPackedObjectsTotal = promauto.NewCounter(prometheus.CounterOpts{+ Name: "graft_land_batch_packed_objects_total",+ Help: "Objects that batch attempts packed before their update.",+ })+landBatchMembersTotal = promauto.NewCounterVec(prometheus.CounterOpts{Name: "graft_land_batch_members_total",Help: "Land requests executed by batches, by outcome: landed, already_landed, conflict, denied or error.",diff --git a/internal/gitaly/service/operations/land_batch_pack.go b/internal/gitaly/service/operations/land_batch_pack.gonew file mode 100644index 0000000..458146b--- /dev/null+++ b/internal/gitaly/service/operations/land_batch_pack.go@@ -0,0 +1,134 @@+package operations++import (+ "bytes"+ "context"+ "errors"+ "fmt"+ "io/fs"+ "os"+ "path/filepath"+ "strings"+ "syscall"++ "github.com/feder-cr/git-ai/internal/git/gitcmd"+ "github.com/feder-cr/git-ai/internal/git/localrepo"+ "github.com/feder-cr/git-ai/internal/gitaly/storage/mode"+)++// packBatchObjects packs the objects of a batch attempt before its publish. It is+// packAttemptObjects, and a variable so that tests can make it fail.+var packBatchObjects = packAttemptObjects++// packAttemptObjects packs every loose object of objectDir, the object directory of the quarantine of+// a batch attempt, into one pack in that directory, and then removes the loose files and the fan-out+// directories they leave empty. It returns the number of packed objects; 0 means that the quarantine+// holds no loose object, and nothing is done.+//+// This is how a batch makes its objects durable once (doc/graft/PLAN8.md, section 3.2): the rebaser+// writes them without fsync, git pack-objects writes and fsyncs the pack and its index with the+// fsync configuration of the server, and the quarantine migration of the update then moves only the+// pack files, fsyncing them again, before the reference is updated. The loose files are removed only+// after git pack-objects succeeded; on any error they are left as they are, and the attempt, whose+// quarantine is discarded, publishes nothing. A file that is not a loose object, such as a pack that+// a helper wrote, is left for the migration, which fsyncs it.+//+// objectDir must be a quarantine object directory that only the attempt writes to: the files are+// listed once, so an object written while the pack is built would stay loose.+func packAttemptObjects(ctx context.Context, repo *localrepo.Repo, objectDir string) (int, error) {+ objectHash, err := repo.ObjectHash(ctx)+ if err != nil {+ return 0, fmt.Errorf("detecting object hash: %w", err)+ }++ entries, err := os.ReadDir(objectDir)+ if err != nil {+ return 0, fmt.Errorf("reading the object directory: %w", err)+ }++ var objectIDs, files, fanouts []string+ for _, entry := range entries {+ if !entry.IsDir() || !isFanoutName(entry.Name()) {+ continue+ }++ fanout := filepath.Join(objectDir, entry.Name())+ objects, err := os.ReadDir(fanout)+ if err != nil {+ return 0, fmt.Errorf("reading fan-out directory: %w", err)+ }++ for _, object := range objects {+ if object.IsDir() {+ continue+ }++ // A loose object is named by the rest of its hex object ID. Anything else, such as the+ // temporary file of a writer that died, is not an object and stays for the migration.+ id, err := objectHash.FromHex(entry.Name() + object.Name())+ if err != nil {+ continue+ }++ objectIDs = append(objectIDs, id.String())+ files = append(files, filepath.Join(fanout, object.Name()))+ }+ fanouts = append(fanouts, fanout)+ }++ if len(objectIDs) == 0 {+ return 0, nil+ }++ packDir := filepath.Join(objectDir, "pack")+ if err := os.MkdirAll(packDir, mode.Directory); err != nil {+ return 0, fmt.Errorf("creating the pack directory: %w", err)+ }++ var stdout, stderr bytes.Buffer+ if err := repo.ExecAndWait(ctx,+ gitcmd.Command{+ Name: "pack-objects",+ Flags: []gitcmd.Option{gitcmd.Flag{Name: "-q"}},+ Args: []string{filepath.Join(packDir, "pack")},+ },+ gitcmd.WithStdin(strings.NewReader(strings.Join(objectIDs, "\n")+"\n")),+ gitcmd.WithStdout(&stdout),+ gitcmd.WithStderr(&stderr),+ ); err != nil {+ return 0, fmt.Errorf("pack-objects: %w, stderr: %q", err, stderr.String())+ }++ for _, file := range files {+ if err := os.Remove(file); err != nil {+ return 0, fmt.Errorf("removing packed loose object: %w", err)+ }+ }++ // A fan-out directory left in the quarantine would make the migration create it in the+ // repository, where housekeeping may remove it while the migration still uses it. One that+ // still holds a file that is not an object stays.+ for _, fanout := range fanouts {+ if err := os.Remove(fanout); err != nil && !errors.Is(err, syscall.ENOTEMPTY) && !errors.Is(err, fs.ErrExist) {+ return 0, fmt.Errorf("removing emptied fan-out directory: %w", err)+ }+ }++ return len(objectIDs), nil+}++// isFanoutName reports whether name is the name of a loose-object fan-out directory: two lower-case+// hex digits.+func isFanoutName(name string) bool {+ if len(name) != 2 {+ return false+ }++ for _, c := range name {+ if !('0' <= c && c <= '9' || 'a' <= c && c <= 'f') {+ return false+ }+ }++ return true+}diff --git a/internal/gitaly/service/operations/land_batch_pack_test.go b/internal/gitaly/service/operations/land_batch_pack_test.gonew file mode 100644index 0000000..81d677c--- /dev/null+++ b/internal/gitaly/service/operations/land_batch_pack_test.go@@ -0,0 +1,422 @@+package operations++import (+ "context"+ "errors"+ "os"+ "path/filepath"+ "slices"+ "strings"+ "testing"++ "github.com/feder-cr/git-ai/internal/featureflag"+ "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/git/quarantine"+ "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/service/hook"+ "github.com/feder-cr/git-ai/internal/gitaly/service/repository"+ "github.com/feder-cr/git-ai/internal/graft/changelog"+ "github.com/feder-cr/git-ai/internal/log"+ "github.com/feder-cr/git-ai/internal/testhelper"+ "github.com/feder-cr/git-ai/internal/testhelper/testcfg"+ "github.com/feder-cr/git-ai/internal/testhelper/testserver"+ "github.com/feder-cr/git-ai/proto/go/gitalypb"+ "github.com/stretchr/testify/require"+ "google.golang.org/grpc"+ "google.golang.org/grpc/codes"+)++// looseObjects returns the loose objects of objectDir, as fan-out directory plus file name.+func looseObjects(t *testing.T, objectDir string) []string {+ t.Helper()++ var objects []string+ entries, err := os.ReadDir(objectDir)+ require.NoError(t, err)+ for _, entry := range entries {+ if !entry.IsDir() || !isFanoutName(entry.Name()) {+ continue+ }+ files, err := os.ReadDir(filepath.Join(objectDir, entry.Name()))+ require.NoError(t, err)+ for _, file := range files {+ objects = append(objects, entry.Name()+file.Name())+ }+ }+ slices.Sort(objects)+ return objects+}++// packIndexes returns the pack index files of objectDir.+func packIndexes(t *testing.T, objectDir string) []string {+ t.Helper()++ indexes, err := filepath.Glob(filepath.Join(objectDir, "pack", "*.idx"))+ require.NoError(t, err)+ return indexes+}++// packedObjects returns the sorted object IDs of the pack index idx.+func packedObjects(t *testing.T, cfg config.Cfg, repoPath, idx string) []string {+ t.Helper()++ var objects []string+ for _, line := range strings.Split(strings.TrimSpace(string(gittest.Exec(t, cfg, "-C", repoPath, "verify-pack", "-v", idx))), "\n") {+ fields := strings.Fields(line)+ if len(fields) >= 3 && (fields[1] == "commit" || fields[1] == "tree" || fields[1] == "blob" || fields[1] == "tag") {+ objects = append(objects, fields[0])+ }+ }+ slices.Sort(objects)+ return objects+}++// newQuarantine returns a quarantine of the repository, a local repository on it and its object+// directory.+func newQuarantine(t *testing.T, ctx context.Context, cfg config.Cfg, repoProto *gitalypb.Repository, repoPath string) (*quarantine.Dir, *localrepo.Repo, string) {+ t.Helper()++ locator := config.NewLocator(cfg)+ dir, cleanup, err := quarantine.New(ctx, repoProto, testhelper.SharedLogger(t), locator)+ require.NoError(t, err)+ t.Cleanup(cleanup)++ objectDir := dir.QuarantinedRepo().GetGitObjectDirectory()+ if !filepath.IsAbs(objectDir) {+ objectDir = filepath.Join(repoPath, objectDir)+ }++ return dir, localrepo.NewTestRepo(t, cfg, dir.QuarantinedRepo()), objectDir+}++func TestPackAttemptObjects(t *testing.T) {+ t.Parallel()++ ctx := testhelper.Context(t)+ cfg := testcfg.Build(t)+ repoProto, repoPath := gittest.CreateRepository(t, ctx, cfg, gittest.CreateRepositoryConfig{SkipCreationViaService: true})++ t.Run("packs every loose object and leaves no fan-out directory", func(t *testing.T) {+ t.Parallel()++ dir, repo, objectDir := newQuarantine(t, ctx, cfg, repoProto, repoPath)++ var written []string+ for _, content := range []string{"one\n", "two\n", "three\n"} {+ id, err := repo.WriteBlob(ctx, strings.NewReader(content), localrepo.WriteBlobConfig{})+ require.NoError(t, err)+ written = append(written, id.String())+ }+ slices.Sort(written)+ require.Equal(t, written, looseObjects(t, objectDir))++ packed, err := packAttemptObjects(ctx, repo, objectDir)+ require.NoError(t, err)+ require.Equal(t, len(written), packed)++ require.Empty(t, looseObjects(t, objectDir), "no loose object is left")+ entries, err := os.ReadDir(objectDir)+ require.NoError(t, err)+ for _, entry := range entries {+ require.False(t, isFanoutName(entry.Name()), "fan-out directory %s is left", entry.Name())+ }++ indexes := packIndexes(t, objectDir)+ require.Len(t, indexes, 1)+ require.Equal(t, written, packedObjects(t, cfg, repoPath, indexes[0]))++ for _, id := range written {+ _, err := repo.ReadObject(ctx, git.ObjectID(id))+ require.NoError(t, err, "object %s is readable from the pack", id)+ }++ // The migration moves the pack, and the repository then has the objects.+ require.NoError(t, dir.Migrate(ctx))+ for _, id := range written {+ gittest.Exec(t, cfg, "-C", repoPath, "cat-file", "-e", id)+ }+ })++ t.Run("nothing to pack", func(t *testing.T) {+ t.Parallel()++ _, repo, objectDir := newQuarantine(t, ctx, cfg, repoProto, repoPath)++ packed, err := packAttemptObjects(ctx, repo, objectDir)+ require.NoError(t, err)+ require.Zero(t, packed)+ require.Empty(t, packIndexes(t, objectDir))+ })++ t.Run("a file that is not an object stays", func(t *testing.T) {+ t.Parallel()++ _, repo, objectDir := newQuarantine(t, ctx, cfg, repoProto, repoPath)++ id, err := repo.WriteBlob(ctx, strings.NewReader("object\n"), localrepo.WriteBlobConfig{})+ require.NoError(t, err)+ stray := filepath.Join(objectDir, id.String()[:2], "tmp_obj_stray")+ require.NoError(t, os.WriteFile(stray, []byte("partial"), 0o600))++ packed, err := packAttemptObjects(ctx, repo, objectDir)+ require.NoError(t, err)+ require.Equal(t, 1, packed)+ require.FileExists(t, stray)+ require.NoFileExists(t, filepath.Join(objectDir, id.String()[:2], id.String()[2:]))+ })++ t.Run("a failed pack leaves the loose objects", func(t *testing.T) {+ t.Parallel()++ _, repo, objectDir := newQuarantine(t, ctx, cfg, repoProto, repoPath)++ id, err := repo.WriteBlob(ctx, strings.NewReader("kept\n"), localrepo.WriteBlobConfig{})+ require.NoError(t, err)++ // pack-objects cannot write into a read-only pack directory.+ packDir := filepath.Join(objectDir, "pack")+ require.NoError(t, os.MkdirAll(packDir, 0o700))+ require.NoError(t, os.Chmod(packDir, 0o500))+ t.Cleanup(func() { require.NoError(t, os.Chmod(packDir, 0o700)) })++ _, err = packAttemptObjects(ctx, repo, objectDir)+ require.ErrorContains(t, err, "pack-objects")+ require.Equal(t, []string{id.String()}, looseObjects(t, objectDir))+ })+}++// runLandBatchStepperServer starts an operations service and returns its Server, so that a test can+// drive the batch stepper directly.+func runLandBatchStepperServer(t *testing.T, cfg config.Cfg) (*Server, config.Cfg) {+ t.Helper()++ testcfg.BuildGitalyHooks(t, cfg)++ var srv *Server+ cfg.SocketPath = testserver.RunGitalyServer(t, cfg, func(g *grpc.Server, deps *service.Dependencies) {+ s := NewServer(deps)+ if srv == nil {+ srv = s+ }+ gitalypb.RegisterOperationServiceServer(g, s)+ gitalypb.RegisterHookServiceServer(g, hook.NewServer(deps))+ gitalypb.RegisterRepositoryServiceServer(g, repository.NewServer(deps))+ })+ require.NotNil(t, srv)++ return srv, cfg+}++// stepperFixture is a repository whose main branch is at base, with changes to land onto it.+type stepperFixture struct {+ cfg config.Cfg+ repoProto *gitalypb.Repository+ repoPath string+ base git.ObjectID+ // forward fast-forwards base, diverged1 and diverged2 change other files from base.+ forward, diverged1, diverged2 git.ObjectID+}++func newStepperFixture(t *testing.T, ctx context.Context, cfg config.Cfg) stepperFixture {+ t.Helper()++ repoProto, repoPath := gittest.CreateRepository(t, ctx, cfg)+ rootEntry := gittest.TreeEntry{Mode: "100644", Path: "root", Content: "root"}+ root := gittest.WriteCommit(t, cfg, repoPath, gittest.WithTreeEntries(rootEntry))+ baseEntries := []gittest.TreeEntry{rootEntry, {Mode: "100644", Path: "base", Content: "base"}}+ base := gittest.WriteCommit(t, cfg, repoPath, gittest.WithBranch(git.DefaultBranch), gittest.WithParents(root),+ gittest.WithTreeEntries(baseEntries...))++ // The diverged changes are based on root, the parent of the tip, so they are rebased.+ change := func(parent git.ObjectID, entries []gittest.TreeEntry, path string) git.ObjectID {+ return gittest.WriteCommit(t, cfg, repoPath, gittest.WithParents(parent), gittest.WithMessage(path),+ gittest.WithTreeEntries(append(slices.Clone(entries), gittest.TreeEntry{Mode: "100644", Path: path, Content: path})...))+ }++ return stepperFixture{+ cfg: cfg, repoProto: repoProto, repoPath: repoPath, base: base,+ forward: change(base, baseEntries, "forward"),+ diverged1: change(root, []gittest.TreeEntry{rootEntry}, "one"),+ diverged2: change(root, []gittest.TreeEntry{rootEntry}, "two"),+ }+}++func (f stepperFixture) request(t *testing.T, ctx context.Context, commit git.ObjectID) *landBatchRequest {+ t.Helper()++ in := landRequest(f.repoProto, git.DefaultBranch, commit)+ committer, err := git.SignatureFromRequest(in)+ require.NoError(t, err)++ return &landBatchRequest{ctx: ctx, in: in, committer: committer, actor: landBatchActor(ctx, in)}+}++// commandCount returns how many commands of ctx have completed.+func commandCount(ctx context.Context) int {+ count, _ := log.CustomFieldsFromContext(ctx).Fields()["command.count"].(int)+ return count+}++// TestLandBatchStepperLandsWithOneProcessPerMember drives one batch attempt: every request is decided+// from one range listing, the long-lived processes of the attempt serve the rest, and the publish+// makes the objects of the attempt durable as one pack before the reference moves.+func TestLandBatchStepperLandsWithOneProcessPerMember(t *testing.T) {+ t.Parallel()++ ctx := log.InitContextCustomFields(featureflag.ContextWithFeatureFlag(testhelper.Context(t), featureflag.GPGSigning, false))+ cfg := testcfg.Build(t)+ srv, cfg := runLandBatchStepperServer(t, cfg)+ f := newStepperFixture(t, ctx, cfg)++ reference := git.NewReferenceNameFromBranchName(git.DefaultBranch)++ // A first attempt lands every kind of request once, so that what a server does once per git+ // binary (detecting its version) is done before the processes are counted.+ warmUp, cleanupWarmUp, err := srv.newLandBatchStepper(ctx, f.repoProto)+ require.NoError(t, err)+ warmTip := f.base+ for _, commit := range []git.ObjectID{f.diverged1, f.diverged2, f.base, f.forward} {+ step, err := warmUp.Land(ctx, warmTip, f.request(t, ctx, commit))+ require.NoError(t, err)+ if commit != f.forward {+ warmTip = step.tip+ }+ }+ cleanupWarmUp()++ st, cleanup, err := srv.newLandBatchStepper(ctx, f.repoProto)+ require.NoError(t, err)+ defer cleanup()++ tip, err := st.Tip(ctx, reference)+ require.NoError(t, err)+ require.Equal(t, f.base, tip)++ // The first rebase starts the long-lived processes of the attempt.+ first, err := st.Land(ctx, tip, f.request(t, ctx, f.diverged1))+ require.NoError(t, err)+ require.True(t, first.rewritten)++ landWithProcesses := func(tip, commit git.ObjectID) (landStep, int) {+ t.Helper()++ before := commandCount(ctx)+ step, err := st.Land(ctx, tip, f.request(t, ctx, commit))+ require.NoError(t, err)+ return step, commandCount(ctx) - before+ }++ // A rebase onto the running tip, a request already landed, and a fast-forward of the starting+ // tip each run one short git command: the range listing (git rev-list). The command factory+ // starts a second process for it: for a command outside its attr.tree list it runs git+ // rev-parse --show-object-format first (gitcmd AttrTreeConfig).+ const rangeListingProcesses = 2++ second, processes := landWithProcesses(first.tip, f.diverged2)+ require.True(t, second.rewritten)+ require.Equal(t, rangeListingProcesses, processes, "rebase")++ landed, processes := landWithProcesses(second.tip, f.base)+ require.True(t, landed.alreadyLanded)+ require.Equal(t, rangeListingProcesses, processes, "already landed")++ forward, processes := landWithProcesses(tip, f.forward)+ require.Equal(t, f.forward, forward.tip)+ require.Equal(t, rangeListingProcesses, processes, "fast-forward")++ // The publish packs the objects of the attempt and the migration moves the pack.+ objectsBefore := packIndexes(t, filepath.Join(f.repoPath, "objects"))+ kind, err := st.Update(ctx, reference, []changelog.Member{memberOf(f.request(t, ctx, f.diverged1), first), memberOf(f.request(t, ctx, f.diverged2), second)}, true, tip, second.tip)+ require.NoError(t, err)+ require.Equal(t, landUpdated, kind)+ requireBranchAt(t, cfg, f.repoPath, git.DefaultBranch, second.tip)++ newPacks := packIndexes(t, filepath.Join(f.repoPath, "objects"))+ require.Len(t, newPacks, len(objectsBefore)+1, "the attempt publishes one pack")+ for _, commit := range []git.ObjectID{first.tip, second.tip} {+ require.NoFileExists(t, filepath.Join(f.repoPath, "objects", commit.String()[:2], commit.String()[2:]),+ "the rebased commit %s is not a loose object of the repository", commit)+ }+ gittest.Exec(t, cfg, "-C", f.repoPath, "fsck", "--connectivity-only", "--no-dangling")+}++// TestLandBatchStepperPackFailureFailsTheUpdate is not parallel: it replaces packBatchObjects.+func TestLandBatchStepperPackFailureFailsTheUpdate(t *testing.T) {+ ctx := featureflag.ContextWithFeatureFlag(testhelper.Context(t), featureflag.GPGSigning, false)+ cfg := testcfg.Build(t)+ srv, cfg := runLandBatchStepperServer(t, cfg)+ f := newStepperFixture(t, ctx, cfg)++ errPack := errors.New("injected pack failure")+ original := packBatchObjects+ packBatchObjects = func(context.Context, *localrepo.Repo, string) (int, error) { return 0, errPack }+ t.Cleanup(func() { packBatchObjects = original })++ st, cleanup, err := srv.newLandBatchStepper(ctx, f.repoProto)+ require.NoError(t, err)+ defer cleanup()++ reference := git.NewReferenceNameFromBranchName(git.DefaultBranch)+ req := f.request(t, ctx, f.diverged1)+ step, err := st.Land(ctx, f.base, req)+ require.NoError(t, err)++ kind, err := st.UpdateSolo(ctx, req, memberOf(req, step), reference, true, f.base, step.tip)+ require.ErrorIs(t, err, errPack)+ testhelper.RequireGrpcCode(t, err, codes.Internal)+ require.Equal(t, landUpdateFailed, kind)+ requireBranchAt(t, cfg, f.repoPath, git.DefaultBranch, f.base)+}++// TestLandBatchStepperFaultsAroundTheMigration stops the publish of an attempt right after the pack+// (a pre-receive hook, which runs before the migration) and right after the migration (an update+// hook, which runs before update-ref). Neither moves the reference, and the repository stays+// connected; the second leaves the migrated pack in the repository, unreferenced.+func TestLandBatchStepperFaultsAroundTheMigration(t *testing.T) {+ t.Parallel()++ for _, tc := range []struct {+ hook string+ wantMigrated bool+ }{+ {hook: "pre-receive", wantMigrated: false},+ {hook: "update", wantMigrated: true},+ } {+ t.Run(tc.hook, func(t *testing.T) {+ t.Parallel()++ ctx := featureflag.ContextWithFeatureFlag(testhelper.Context(t), featureflag.GPGSigning, false)+ cfg := testcfg.Build(t)+ srv, cfg := runLandBatchStepperServer(t, cfg)+ f := newStepperFixture(t, ctx, cfg)+ gittest.WriteCustomHook(t, f.repoPath, tc.hook, []byte("#!/bin/sh\necho fault injected >&2\nexit 1\n"))++ st, cleanup, err := srv.newLandBatchStepper(ctx, f.repoProto)+ require.NoError(t, err)+ defer cleanup()++ reference := git.NewReferenceNameFromBranchName(git.DefaultBranch)+ req := f.request(t, ctx, f.diverged1)+ step, err := st.Land(ctx, f.base, req)+ require.NoError(t, err)++ packsBefore := len(packIndexes(t, filepath.Join(f.repoPath, "objects")))+ kind, err := st.Update(ctx, reference, []changelog.Member{memberOf(req, step)}, true, f.base, step.tip)+ require.Error(t, err)+ require.Equal(t, landUpdateRejected, kind)+ requireBranchAt(t, cfg, f.repoPath, git.DefaultBranch, f.base)++ packsAfter := len(packIndexes(t, filepath.Join(f.repoPath, "objects")))+ if tc.wantMigrated {+ require.Equal(t, packsBefore+1, packsAfter, "the migrated pack stays, unreferenced")+ gittest.Exec(t, cfg, "-C", f.repoPath, "cat-file", "-e", step.tip.String())+ } else {+ require.Equal(t, packsBefore, packsAfter, "nothing was migrated")+ }+ gittest.Exec(t, cfg, "-C", f.repoPath, "fsck", "--connectivity-only")+ })+ }+}diff --git a/internal/gitaly/service/operations/land_batch_phase4_test.go b/internal/gitaly/service/operations/land_batch_phase4_test.goindex b453468..ff18083 100644--- a/internal/gitaly/service/operations/land_batch_phase4_test.go+++ b/internal/gitaly/service/operations/land_batch_phase4_test.go@@ -403,15 +403,15 @@ func TestLandBatchExecutorInvalidAfterMemberIsEarlyOnlyWhenTipIndependent(t *tes}}-// countingRebaser counts the rebases of the batch attempts.+// countingRebaser counts the replays of the batch attempts.type countingRebaser struct {batchRebaserrebases *atomic.Int64}-func (r countingRebaser) Rebase(ctx context.Context, upstream, branch git.ObjectID, opts ...localrepo.RebaseOption) (git.ObjectID, error) {+func (r countingRebaser) Replay(ctx context.Context, upstream git.ObjectID, todo []git.ObjectID, committer *git.Signature) (git.ObjectID, error) {r.rebases.Add(1)- return r.batchRebaser.Rebase(ctx, upstream, branch, opts...)+ return r.batchRebaser.Replay(ctx, upstream, todo, committer)}// TestLandBatch_rebaseGoesThroughRebaser is not parallel: it replaces newBatchRebaser, which the paralleldiff --git a/internal/gitaly/service/operations/land_batch_server.go b/internal/gitaly/service/operations/land_batch_server.goindex 26a8762..9e57484 100644--- a/internal/gitaly/service/operations/land_batch_server.go+++ b/internal/gitaly/service/operations/land_batch_server.go@@ -3,9 +3,11 @@ package operationsimport ("context""errors"+ "path/filepath""time""github.com/feder-cr/git-ai/internal/git"+ "github.com/feder-cr/git-ai/internal/git/catfile""github.com/feder-cr/git-ai/internal/git/localrepo""github.com/feder-cr/git-ai/internal/git/mvcc""github.com/feder-cr/git-ai/internal/git/quarantine"@@ -138,43 +140,11 @@ func (s *Server) executeLandBatch(ctx context.Context, _ landlane.Key, reqs []*lexecutor := landBatchExecutor{maxRebuilds: landBatchMaxRebuilds,newStepper: func(ctx context.Context) (landBatchStepper, func(), error) {- defer observeLandBatchPhase(landBatchPhaseQuarantine, time.Now())-- quarantineDir, quarantineRepo, cleanup, err := s.quarantinedRepo(ctx, repository)- if err != nil {- return nil, nil, err- }-- objectHash, err := quarantineRepo.ObjectHash(ctx)- if err != nil {- cleanup()- return nil, nil, structerr.NewInternal("detecting object hash: %w", err)- }-- checker, releaseChecker, err := s.landAncestry(ctx, quarantineRepo)+ stepper, cleanup, err := s.newLandBatchStepper(ctx, repository)if err != nil {- cleanup()return nil, nil, err}-- // One rebase engine serves the whole attempt, and the attempt ends with it.- rebaser := newBatchRebaser(quarantineRepo)-- return &serverLandBatchStepper{- server: s,- repository: repository,- quarantineDir: quarantineDir,- repo: quarantineRepo,- objectHash: objectHash,- rebaser: rebaser,- ancestry: checker,- }, func() {- releaseChecker()- if err := rebaser.Close(); err != nil {- s.logger.WithError(err).Error("graft: closing the rebaser of a land batch")- }- cleanup()- }, nil+ return stepper, cleanup, nil},fallback: func(req *landBatchRequest) (*gitalypb.UserLandResponse, error) {return s.landWithRetries(req.ctx, req.in, req.committer)@@ -212,6 +182,60 @@ func (s *Server) executeLandBatch(ctx context.Context, _ landlane.Key, reqs []*lreturn results, nil}+// newLandBatchStepper starts a batch attempt on repository: it opens the quarantine of the attempt+// and the processes that serve it. The returned function ends the attempt.+func (s *Server) newLandBatchStepper(ctx context.Context, repository *gitalypb.Repository) (*serverLandBatchStepper, func(), error) {+ defer observeLandBatchPhase(landBatchPhaseQuarantine, time.Now())++ quarantineDir, quarantineRepo, cleanup, err := s.quarantinedRepo(ctx, repository)+ if err != nil {+ return nil, nil, err+ }++ objectHash, err := quarantineRepo.ObjectHash(ctx)+ if err != nil {+ cleanup()+ return nil, nil, structerr.NewInternal("detecting object hash: %w", err)+ }++ checker, releaseChecker, err := s.landAncestry(ctx, quarantineRepo)+ if err != nil {+ cleanup()+ return nil, nil, err+ }++ // The commit IDs of the requests are peeled by the object info process of the+ // quarantine, which the attempt starts once.+ info, releaseInfo, err := s.catfileCache.ObjectInfoReader(ctx, quarantineRepo)+ if err != nil {+ releaseChecker()+ cleanup()+ return nil, nil, structerr.NewInternal("reading object info: %w", err)+ }++ // One rebase engine serves the whole attempt, and the attempt ends with it. Its objects+ // are made durable by the publish of the attempt, as one pack (see publish).+ rebaser := newBatchRebaser(quarantineRepo)++ return &serverLandBatchStepper{+ server: s,+ repository: repository,+ quarantineDir: quarantineDir,+ repo: quarantineRepo,+ objectHash: objectHash,+ info: info,+ rebaser: rebaser,+ ancestry: checker,+ }, func() {+ releaseInfo()+ releaseChecker()+ if err := rebaser.Close(); err != nil {+ s.logger.WithError(err).Error("graft: closing the rebaser of a land batch")+ }+ cleanup()+ }, nil+}+// landBatchResult builds the result of a request of a batch.func landBatchResult(outcome landBatchOutcome) landlane.Result[*gitalypb.UserLandResponse] {if outcome.Err != nil {@@ -248,17 +272,18 @@ func landBatchGiveUp(req *landBatchRequest, cause error, attempts int) error {return landKeptMovingError(req.in, conflict, attempts)}-// batchRebaser rebases the commits of a batch attempt. It has the semantics of localrepo.Rebase, and-// is rebase.Engine.+// batchRebaser replays the commits of the members of a batch attempt. It is rebase.Engine.type batchRebaser interface {- Rebase(ctx context.Context, upstream, branch git.ObjectID, opts ...localrepo.RebaseOption) (git.ObjectID, error)+ Replay(ctx context.Context, upstream git.ObjectID, todo []git.ObjectID, committer *git.Signature) (git.ObjectID, error)Close() error}-// newBatchRebaser starts the rebaser of a batch attempt on the quarantine of the attempt. It is a-// variable so that tests can observe the rebases.+// newBatchRebaser starts the rebaser of a batch attempt on the quarantine of the attempt. The objects+// it writes are not fsynced one by one: the publish of the attempt packs them into one fsynced pack+// before the reference points to them (see publish). It is a variable so that tests can observe the+// replays.var newBatchRebaser = func(repo *localrepo.Repo) batchRebaser {- return rebase.New(repo)+ return rebase.New(repo, rebase.WithDeferredDurability())}// serverLandBatchStepper implements landBatchStepper on the quarantine of one batch attempt.@@ -268,9 +293,12 @@ type serverLandBatchStepper struct {quarantineDir *quarantine.Dirrepo *localrepo.RepoobjectHash git.ObjectHash- // rebaser rebases the members of the attempt. It serves the whole attempt.+ // info peels the commit IDs of the requests. It serves the whole attempt.+ info catfile.ObjectInfoReader+ // rebaser replays the members of the attempt. It serves the whole attempt.rebaser batchRebaser- // ancestry answers the ancestry questions of the attempt, with the graph index when it is enabled.+ // ancestry lists the commits that each request adds to the running tip, with the graph index+ // when it is enabled.ancestry ancestry.Checker}@@ -310,10 +338,14 @@ func (st *serverLandBatchStepper) Land(ctx context.Context, tip git.ObjectID, reWithMetadata("commit_id", in.GetCommitId())}- commitID, err = st.repo.ResolveRevision(ctx, git.Revision(commitID.String()+"^{commit}"))+ commitID, err = st.peel(ctx, commitID)if err != nil {- return landStep{tipIndependent: true}, structerr.NewInvalidArgument("cannot resolve commit ID: %w", err).- WithMetadata("commit_id", in.GetCommitId())+ if errors.As(err, new(catfile.NotFoundError)) {+ return landStep{tipIndependent: true}, structerr.NewInvalidArgument("cannot resolve commit ID: %w", err).+ WithMetadata("commit_id", in.GetCommitId())+ }++ return landStep{}, structerr.NewInternal("peeling commit ID: %w", err)}if tip == "" {@@ -328,19 +360,16 @@ func (st *serverLandBatchStepper) Land(ctx context.Context, tip git.ObjectID, rereturn landStep{commit: commitID, tip: commitID, created: true}, nil}- landed, err := st.ancestry.IsAncestor(ctx, commitID, tip)+ plan, err := st.plan(ctx, tip, commitID)if err != nil {- return landStep{}, structerr.NewInternal("checking whether commit is already landed: %w", err)+ return landStep{}, err}- if landed {++ switch plan.Kind() {+ case rebase.LandAlreadyLanded:return landStep{commit: commitID, tip: tip, alreadyLanded: true}, nil- }- fastForward, err := st.ancestry.IsAncestor(ctx, tip, commitID)- if err != nil {- return landStep{}, structerr.NewInternal("checking for ancestry: %w", err)- }- if fastForward {+ case rebase.LandFastForward:if err := st.admit(req, reference, tip, commitID); err != nil {return landStep{}, err}@@ -348,7 +377,7 @@ func (st *serverLandBatchStepper) Land(ctx context.Context, tip git.ObjectID, rereturn landStep{commit: commitID, tip: commitID}, nil}- newTip, err := st.computeTip(ctx, in, tip, commitID, req.committer)+ newTip, err := st.computeTip(ctx, in, plan, tip, commitID, req.committer)var resolution *landResolutionif err != nil {if !in.GetResolveConflicts() || !isLandMergeConflict(err) {@@ -379,36 +408,60 @@ func (st *serverLandBatchStepper) Land(ctx context.Context, tip git.ObjectID, rereturn landStep{commit: commitID, tip: newTip, rewritten: true, resolution: resolution}, nil}-// computeTip computes the new tip of the attempt for a commit that is neither reachable from the tip-// nor a fast-forward of it. It is computeLandedTip, except that the rebase strategy rebases with the-// rebaser of the attempt and checks the common ancestor with the ancestry checker of the attempt.-// The rebase has the semantics and the errors of the rebase of computeLandedTip.-//-// The single-land path keeps its own computeLandedTip (land.go is not changed by the batch executor), so-// the rebase branch below mirrors it.-func (st *serverLandBatchStepper) computeTip(ctx context.Context, in *gitalypb.UserLandRequest, tip, commitID git.ObjectID, committer git.Signature) (git.ObjectID, error) {- if in.GetStrategy() != gitalypb.UserLandRequest_STRATEGY_REBASE_UNSPECIFIED {- return st.server.computeLandedTip(ctx, in, st.repo, tip, commitID, committer)+// peel returns the commit that commitID is or peels to, through the object info process of the+// attempt. commitID is a full object ID, so nothing is abbreviated or ambiguous. An object that does+// not exist or does not peel to a commit is a catfile.NotFoundError.+func (st *serverLandBatchStepper) peel(ctx context.Context, commitID git.ObjectID) (git.ObjectID, error) {+ info, err := st.info.Info(ctx, git.Revision(commitID.String()+"^{commit}"))+ if err != nil {+ return "", err}- if err := rejectMergeCommitsInRange(ctx, st.repo, tip, commitID); err != nil {- return "", err+ return info.Oid, nil+}++// plan decides how commitID lands onto tip from one listing of the commits it adds to tip (see+// rebase.PlanLanding).+func (st *serverLandBatchStepper) plan(ctx context.Context, tip, commitID git.ObjectID) (rebase.LandPlan, error) {+ defer observeLandBatchPhase(landBatchPhasePlan, time.Now())++ rng, err := st.ancestry.Range(ctx, tip, commitID)+ if err != nil {+ return rebase.LandPlan{}, structerr.NewInternal("listing the commits of the change: %w", err)}- // Rebasing needs a merge base. Unrelated histories can only be landed with STRATEGY_MERGE.- _, related, err := st.ancestry.MergeBase(ctx, tip, commitID)+ plan, err := rebase.PlanLanding(tip, commitID, rng)if err != nil {- return "", structerr.NewInternal("checking for a common ancestor: %w", err)+ return rebase.LandPlan{}, structerr.NewInternal("planning the landing: %w", err)+ }++ return plan, nil+}++// computeTip computes the new tip of the attempt for a commit whose plan is diverged: it is neither+// reachable from the tip nor a fast-forward of it. The merge and fast-forward-only strategies are+// computeLandedTip. The rebase strategy replays the commits of the plan with the rebaser of the+// attempt, with the errors of computeLandedTip: a range with merge commits or without a common+// ancestor is InvalidArgument, a conflict is a merge conflict.+func (st *serverLandBatchStepper) computeTip(ctx context.Context, in *gitalypb.UserLandRequest, plan rebase.LandPlan, tip, commitID git.ObjectID, committer git.Signature) (git.ObjectID, error) {+ if in.GetStrategy() != gitalypb.UserLandRequest_STRATEGY_REBASE_UNSPECIFIED {+ return st.server.computeLandedTip(ctx, in, st.repo, tip, commitID, committer)}- if !related {++ todo, err := plan.Replay()+ switch {+ case errors.Is(err, rebase.ErrMergesInRange):+ return "", structerr.NewInvalidArgument("commit range contains merge commits, which cannot be rebased: use STRATEGY_MERGE")+ case errors.Is(err, rebase.ErrUnrelated):+ // Rebasing needs a merge base. Unrelated histories can only be landed with STRATEGY_MERGE.return "", structerr.NewInvalidArgument("commit shares no history with branch %q: use STRATEGY_MERGE to land unrelated history", string(in.GetBranch()))+ case err != nil:+ return "", structerr.NewInternal("planning the rebase: %w", err)}- // Reapplied cherry-picks as in computeLandedTip: see the comment there.- rebasedCommitID, err := st.rebaser.Rebase(ctx, tip, commitID,- localrepo.RebaseWithCommitter(committer),- localrepo.RebaseWithReappliedCherryPicks(),- )+ // The commits are reapplied as computeLandedTip reapplies cherry-picks: see the comment there.+ defer observeLandBatchPhase(landBatchPhaseReplay, time.Now())+ rebasedCommitID, err := st.rebaser.Replay(ctx, tip, todo, &committer)if err != nil {// The conflict error is passed as the cause itself, see computeLandedTip.var conflictErr *localrepo.RebaseConflictError@@ -450,6 +503,9 @@ func (st *serverLandBatchStepper) admit(req *landBatchRequest, reference git.Ref// Update publishes the batch with one compare-and-swap. The hooks run once for the combined update,// as the synthetic graft-batch user, and the changelog records the members of the batch.func (st *serverLandBatchStepper) Update(ctx context.Context, reference git.ReferenceName, members []changelog.Member, rewritten bool, old, newTip git.ObjectID) (landUpdateKind, error) {+ if err := st.publish(ctx); err != nil {+ return landUpdateFailed, err+ }defer observeLandBatchPhase(landBatchPhaseUpdate, time.Now())oldOID := old@@ -474,6 +530,9 @@ func (st *serverLandBatchStepper) Update(ctx context.Context, reference git.Refe// original commit of the member maps to the commit it landed as. The compare-and-swap and its outcomes// are those of Update.func (st *serverLandBatchStepper) UpdateSolo(ctx context.Context, req *landBatchRequest, member changelog.Member, reference git.ReferenceName, rewritten bool, old, newTip git.ObjectID) (landUpdateKind, error) {+ if err := st.publish(ctx); err != nil {+ return landUpdateFailed, err+ }defer observeLandBatchPhase(landBatchPhaseUpdate, time.Now())oldOID := old@@ -487,6 +546,32 @@ func (st *serverLandBatchStepper) UpdateSolo(ctx context.Context, req *landBatchreturn st.updateKind(st.server.updateLandedReference(ctx, req.in, st.quarantineDir, st.repo, reference, oldOID, newTip, rewritten))}+// publish makes the objects that the attempt wrote durable before its compare-and-swap: it packs+// every loose object of the quarantine into one fsynced pack (see packAttemptObjects), which the+// quarantine migration of the update then moves into the repository. A failure fails the update+// of the attempt, as a failed compare-and-swap that a rebuild does not fix: nothing is published.+func (st *serverLandBatchStepper) publish(ctx context.Context) error {+ defer observeLandBatchPhase(landBatchPhasePack, time.Now())++ repoPath, err := st.repo.Path(ctx)+ if err != nil {+ return structerr.NewInternal("getting quarantine path: %w", err)+ }++ objectDir := st.quarantineDir.QuarantinedRepo().GetGitObjectDirectory()+ if !filepath.IsAbs(objectDir) {+ objectDir = filepath.Join(repoPath, objectDir)+ }++ packed, err := packBatchObjects(ctx, st.repo, objectDir)+ if err != nil {+ return structerr.NewInternal("packing the objects of the batch: %w", err)+ }+ landBatchPackedObjectsTotal.Add(float64(packed))++ return nil+}+// changelogOperationLand is the operation of an unbatched land in the changelog. The lanes run outside// of the gRPC method of the requests, so the operation is set for the update of a batch of one.const changelogOperationLand = "land"diff --git a/internal/graft/rebase/engine.go b/internal/graft/rebase/engine.goindex b7c6905..554d949 100644--- a/internal/graft/rebase/engine.go+++ b/internal/graft/rebase/engine.go@@ -1,21 +1,19 @@-// Package rebase implements the rebase used by graft batch landing with long-lived git helper-// processes. It produces the same results as (*localrepo.Repo).Rebase, without starting several-// git processes per rebased commit.+// Package rebase decides how a change lands onto a branch and replays its commits. PlanLanding+// makes the decision from one listing of the range the change adds (see ancestry.Checker.Range),+// and an Engine replays the commits of a rebase through long-lived git helper processes. Together+// they produce the same commits as (*localrepo.Repo).Rebase with reapplied cherry-picks, without+// starting several git processes per commit.package rebaseimport (- "bufio""bytes""context""errors""fmt"- "strings""time""github.com/feder-cr/git-ai/internal/git"- "github.com/feder-cr/git-ai/internal/git/gitcmd""github.com/feder-cr/git-ai/internal/git/localrepo"- "github.com/feder-cr/git-ai/internal/helper/text""github.com/feder-cr/git-ai/internal/structerr""github.com/feder-cr/git-ai/proto/go/gitalypb")@@ -42,14 +40,14 @@ type backends struct {newCommitWriter func(ctx context.Context) (commitWriter, error)}-// Engine rebases commits within one batch attempt using one merge-tree stream and one commit+// Engine replays commits within one batch attempt using one merge-tree stream and one commit// writer, started lazily and closed by Close. An Engine is not safe for concurrent use.//// The helper processes are started with the context of the call that needs them and die with// it. A helper whose context is done is replaced by a new one on the next use, so a canceled-// context of one Rebase does not fail the later Rebase calls of the Engine. A helper that+// context of one Replay does not fail the later Replay calls of the Engine. A helper that// fails with an error other than a merge conflict is replaced in the same way, so that one-// failed rebase does not fail the rebases that follow it.+// failed replay does not fail the replays that follow it.type Engine struct {repo *localrepo.Repobackends backends@@ -63,18 +61,40 @@ type Engine struct {writerDone <-chan struct{}}+// Option configures an Engine.+type Option func(*engineConfig)++type engineConfig struct {+ helperOpts []localrepo.HelperOption+}++// WithDeferredDurability starts the helper processes without fsync of the loose objects they write.+// The caller makes those objects durable before any reference points to them. The batch stepper of+// UserLand does: it publishes the objects of its quarantine as one fsynced pack (doc/graft/PLAN8.md,+// section 3.2).+func WithDeferredDurability() Option {+ return func(cfg *engineConfig) {+ cfg.helperOpts = append(cfg.helperOpts, localrepo.WithoutObjectFsync())+ }+}+// New returns an Engine for repo.-func New(repo *localrepo.Repo) *Engine {+func New(repo *localrepo.Repo, opts ...Option) *Engine {+ var cfg engineConfig+ for _, opt := range opts {+ opt(&cfg)+ }+return newEngine(repo, backends{newMergeStream: func(ctx context.Context) (mergeStream, error) {- stream, err := repo.NewMergeTreeStream(ctx)+ stream, err := repo.NewMergeTreeStream(ctx, cfg.helperOpts...)if err != nil {return nil, err}return stream, nil},newCommitWriter: func(ctx context.Context) (commitWriter, error) {- writer, err := repo.NewCommitWriter(ctx)+ writer, err := repo.NewCommitWriter(ctx, cfg.helperOpts...)if err != nil {return nil, err}@@ -87,103 +107,26 @@ func newEngine(repo *localrepo.Repo, b backends) *Engine {return &Engine{repo: repo, backends: b}}-// Rebase has the semantics and errors of (*localrepo.Repo).Rebase(ctx, upstream, branch, opts...).-func (e *Engine) Rebase(ctx context.Context, upstream, branch git.ObjectID, opts ...localrepo.RebaseOption) (git.ObjectID, error) {- settings := localrepo.ResolveRebaseOptions(opts...)-- upstreamOID, err := e.repo.ResolveRevision(ctx, git.Revision(upstream.String()+"^{commit}"))- if err != nil {- return "", structerr.NewInvalidArgument("resolving upstream commit: %w", err).WithMetadata("revision", upstream.String())- }-- branchOID, err := e.repo.ResolveRevision(ctx, git.Revision(branch.String()+"^{commit}"))- if err != nil {- return "", structerr.NewInvalidArgument("resolving branch commit: %w", err).WithMetadata("revision", branch.String())- }-- var stdout bytes.Buffer- if err := e.repo.ExecAndWait(ctx,- gitcmd.Command{- Name: "merge-base",- Args: []string{upstreamOID.String(), branchOID.String()},- },- gitcmd.WithStdout(&stdout),- ); err != nil {- return "", structerr.NewInternal("get merge-base: %w", err)- }-- // fast-forward if possible- mergeBase := text.ChompBytes(stdout.Bytes())- if mergeBase == upstreamOID.String() {- return branchOID, nil- }- if mergeBase == branchOID.String() {- return upstreamOID, nil- }-- newOID, err := e.rebaseCommits(ctx, settings, upstreamOID, branchOID)- if err != nil {- return "", structerr.NewInternal("rebase using merge-tree: %w", err)- }-- return newOID, nil-}--// Close ends the helper processes started by the Engine. It is safe to call more than once. A-// helper that was already ended by the cancellation of its context is not an error.-func (e *Engine) Close() error {- var errs []error- if e.stream != nil {- errs = append(errs, closeHelper(e.streamDone, e.stream.Close))- e.stream, e.streamDone = nil, nil- }- if e.writer != nil {- errs = append(errs, closeHelper(e.writerDone, e.writer.Close))- e.writer, e.writerDone = nil, nil- }- return errors.Join(errs...)-}--// closeHelper closes a helper process. The error of a helper whose context is done is dropped,-// because the process was killed by the cancellation.-func closeHelper(done <-chan struct{}, closeFn func() error) error {- err := closeFn()- if isDone(done) {- return nil- }- return err-}--// isDone reports whether the channel is closed. A nil channel, the Done channel of a context that-// can never be canceled, is never done.-func isDone(done <-chan struct{}) bool {- select {- case <-done:- return true- default:- return false- }-}--func (e *Engine) rebaseCommits(ctx context.Context, settings localrepo.RebaseSettings, upstreamOID, branchOID git.ObjectID) (git.ObjectID, error) {+// Replay replays the commits of todo, oldest first, onto upstream and returns the last commit+// written, or upstream when every commit became empty and was dropped. It is the replay of+// (*localrepo.Repo).Rebase: a commit whose merge onto the running tip changes nothing is dropped+// unless it is itself empty, each commit keeps its author and message, and its committer is+// committer, or its own committer when committer is nil. A commit that does not apply cleanly+// returns *localrepo.RebaseConflictError. The todo list comes from LandPlan.Replay.+func (e *Engine) Replay(ctx context.Context, upstream git.ObjectID, todo []git.ObjectID, committer *git.Signature) (git.ObjectID, error) {objectHash, err := e.repo.ObjectHash(ctx)if err != nil {return "", structerr.NewInternal("getting object hash %w", err)}- todoList, err := e.todoList(ctx, settings, upstreamOID, branchOID)- if err != nil {- return "", err- }-- upstreamCommit, err := e.repo.ReadCommit(ctx, git.Revision(upstreamOID))+ upstreamCommit, err := e.repo.ReadCommit(ctx, git.Revision(upstream))if err != nil {return "", fmt.Errorf("reading upstream commit: %w", err)}- oursCommitOID := upstreamOID+ oursCommitOID := upstreamoursTreeOID := git.ObjectID(upstreamCommit.GetTreeId())- for _, todoItem := range todoList {+ for _, todoItem := range todo {theirsCommit, err := e.repo.ReadCommit(ctx, git.Revision(todoItem))if err != nil {return "", fmt.Errorf("reading todo list commit: %w", err)@@ -198,7 +141,7 @@ func (e *Engine) rebaseCommits(ctx context.Context, settings localrepo.RebaseSetif err != nil {var conflictErr *localrepo.MergeTreeConflictErrorif errors.As(err, &conflictErr) {- return newTreeOID, &localrepo.RebaseConflictError{+ return "", &localrepo.RebaseConflictError{Commit: theirsCommit.GetId(),ConflictError: conflictErr,}@@ -226,9 +169,9 @@ func (e *Engine) rebaseCommits(ctx context.Context, settings localrepo.RebaseSet}author := signatureFromCommitAuthor(theirsCommit.GetAuthor())- committer := settings.Committer- if committer == nil {- committer = signatureFromCommitAuthor(theirsCommit.GetCommitter())+ commitCommitter := committer+ if commitCommitter == nil {+ commitCommitter = signatureFromCommitAuthor(theirsCommit.GetCommitter())}message, err := e.fullCommitMessage(ctx, theirsCommit)@@ -241,9 +184,9 @@ func (e *Engine) rebaseCommits(ctx context.Context, settings localrepo.RebaseSetAuthorName: author.Name,AuthorEmail: author.Email,AuthorDate: author.When,- CommitterName: committer.Name,- CommitterEmail: committer.Email,- CommitterDate: committer.When,+ CommitterName: commitCommitter.Name,+ CommitterEmail: commitCommitter.Email,+ CommitterDate: commitCommitter.When,Message: string(message),TreeID: newTreeOID,})@@ -257,46 +200,40 @@ func (e *Engine) rebaseCommits(ctx context.Context, settings localrepo.RebaseSetreturn oursCommitOID, nil}-// todoList returns the commits of branch that are not in upstream, oldest first, without the-// clean cherry-picks of upstream unless they are reapplied. It is the list that-// (*localrepo.Repo).Rebase replays.-func (e *Engine) todoList(ctx context.Context, settings localrepo.RebaseSettings, upstreamOID, branchOID git.ObjectID) ([]string, error) {- // Flags of git-rev-list to get the pick-only todo_list for a rebase, see- // (*localrepo.Repo).Rebase for their origin.- var flags []gitcmd.Option- if !settings.ReapplyCherryPicks {- flags = append(flags, gitcmd.Flag{Name: "--cherry-pick"})+// Close ends the helper processes started by the Engine. It is safe to call more than once. A+// helper that was already ended by the cancellation of its context is not an error.+func (e *Engine) Close() error {+ var errs []error+ if e.stream != nil {+ errs = append(errs, closeHelper(e.streamDone, e.stream.Close))+ e.stream, e.streamDone = nil, nil}- flags = append(flags,- gitcmd.Flag{Name: "--right-only"},- gitcmd.Flag{Name: "--no-merges"},- gitcmd.Flag{Name: "--topo-order"},- gitcmd.Flag{Name: "--reverse"},- )-- var stderr bytes.Buffer- cmd, err := e.repo.Exec(ctx, gitcmd.Command{- Name: "rev-list",- Flags: flags,- Args: []string{fmt.Sprintf("%s...%s", upstreamOID, branchOID)},- }, gitcmd.WithStderr(&stderr), gitcmd.WithSetupStdout())- if err != nil {- return nil, structerr.NewInternal("start git rev-list: %w", err)+ if e.writer != nil {+ errs = append(errs, closeHelper(e.writerDone, e.writer.Close))+ e.writer, e.writerDone = nil, nil}+ return errors.Join(errs...)+}- var todoList []string- scanner := bufio.NewScanner(cmd)- for scanner.Scan() {- todoList = append(todoList, strings.TrimSpace(scanner.Text()))- }- if err := scanner.Err(); err != nil {- return nil, fmt.Errorf("scanning rev-list output: %w", err)- }- if err := cmd.Wait(); err != nil {- return nil, structerr.NewInternal("git rev-list: %w", err).WithMetadata("stderr", stderr.String())+// closeHelper closes a helper process. The error of a helper whose context is done is dropped,+// because the process was killed by the cancellation.+func closeHelper(done <-chan struct{}, closeFn func() error) error {+ err := closeFn()+ if isDone(done) {+ return nil}+ return err+}- return todoList, nil+// isDone reports whether the channel is closed. A nil channel, the Done channel of a context that+// can never be canceled, is never done.+func isDone(done <-chan struct{}) bool {+ select {+ case <-done:+ return true+ default:+ return false+ }}// merge merges theirs into ours with base as the merge base. base is empty for a root commit.diff --git a/internal/graft/rebase/engine_recover_test.go b/internal/graft/rebase/engine_recover_test.goindex 7012ab7..a6917ef 100644--- a/internal/graft/rebase/engine_recover_test.go+++ b/internal/graft/rebase/engine_recover_test.go@@ -8,7 +8,6 @@ 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/localrepo""github.com/stretchr/testify/require")@@ -37,13 +36,13 @@ func TestEngineRecoversFromBrokenMergeTreeStream(t *testing.T) {engine := newEngine(f.repo, fb.backends())t.Cleanup(func() { require.NoError(t, engine.Close()) })- _, err := engine.Rebase(f.ctx, upstream, bad, localrepo.RebaseWithReappliedCherryPicks())+ _, err := landRebase(f.ctx, f.repo, engine, upstream, bad, nil)require.Error(t, err)require.Equal(t, 1, fb.streamStarts)require.Equal(t, 1, fb.streamClosed, "the broken stream is closed")// The next rebase starts a new stream and gives the result of localrepo.- require.NoError(t, requireSameRebase(t, f, engine, upstream, good, localrepo.RebaseWithCommitter(testCommitter)))+ require.NoError(t, requireSameRebase(t, f, engine, upstream, good, &testCommitter))require.Equal(t, 2, fb.streamStarts)}@@ -60,11 +59,11 @@ func TestEngineRecoversAfterMergeError(t *testing.T) {engine := newEngine(f.repo, failFirst.backends())t.Cleanup(func() { require.NoError(t, engine.Close()) })- _, err := engine.Rebase(f.ctx, upstream, branch, localrepo.RebaseWithCommitter(testCommitter))+ _, err := landRebase(f.ctx, f.repo, engine, upstream, branch, &testCommitter)require.ErrorIs(t, err, errInjected)require.Equal(t, 1, fb.streamClosed, "the stream that failed is closed")- require.NoError(t, requireSameRebase(t, f, engine, upstream, branch, localrepo.RebaseWithCommitter(testCommitter)))+ require.NoError(t, requireSameRebase(t, f, engine, upstream, branch, &testCommitter))require.Equal(t, 2, fb.streamStarts, "the next rebase starts a new stream")}@@ -80,14 +79,14 @@ func TestEngineReplacesHelpersOfCanceledContext(t *testing.T) {engine := newEngine(f.repo, fb.backends())ctx, cancel := context.WithCancel(f.ctx)- want, err := engine.Rebase(ctx, upstream, branch, localrepo.RebaseWithCommitter(testCommitter))+ want, err := landRebase(ctx, f.repo, engine, upstream, branch, &testCommitter)require.NoError(t, err)require.Equal(t, 1, fb.streamStarts)require.Equal(t, 1, fb.writerStarts)cancel()- got, err := engine.Rebase(f.ctx, upstream, branch, localrepo.RebaseWithCommitter(testCommitter))+ got, err := landRebase(f.ctx, f.repo, engine, upstream, branch, &testCommitter)require.NoError(t, err)require.Equal(t, want, got)require.Equal(t, 2, fb.streamStarts)diff --git a/internal/graft/rebase/engine_test.go b/internal/graft/rebase/engine_test.goindex 98a0289..2a8ada8 100644--- a/internal/graft/rebase/engine_test.go+++ b/internal/graft/rebase/engine_test.go@@ -15,6 +15,7 @@ import ("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/gitaly/config"+ "github.com/feder-cr/git-ai/internal/graft/ancestry""github.com/feder-cr/git-ai/internal/testhelper""github.com/feder-cr/git-ai/internal/testhelper/testcfg""github.com/stretchr/testify/require"@@ -120,22 +121,67 @@ func buildHistories(f *fixture, rng *rand.Rand) (upstream, branch git.ObjectID)return upTip, brTip}-// requireSameRebase rebases with the engine and with localrepo and requires the same outcome: the-// same object ID, or the same error with the same code, message and conflict contents. It returns-// the error of the localrepo rebase.-func requireSameRebase(t *testing.T, f *fixture, engine *Engine, upstream, branch git.ObjectID, opts ...localrepo.RebaseOption) error {+// landRebase rebases branch onto upstream the way landing does: one range listing, the plan, and+// the replay of the engine. Like (*localrepo.Repo).Rebase it returns branch when upstream is+// reachable from it and upstream when branch is reachable from upstream.+func landRebase(ctx context.Context, repo *localrepo.Repo, engine *Engine, upstream, branch git.ObjectID, committer *git.Signature) (git.ObjectID, error) {+ rng, err := ancestry.Git(repo).Range(ctx, upstream, branch)+ if err != nil {+ return "", err+ }++ plan, err := PlanLanding(upstream, branch, rng)+ if err != nil {+ return "", err+ }++ switch plan.Kind() {+ case LandAlreadyLanded:+ return upstream, nil+ case LandFastForward:+ return branch, nil+ }++ todo, err := plan.Replay()+ if err != nil {+ return "", err+ }++ return engine.Replay(ctx, upstream, todo, committer)+}++// rebaseOptions returns the options of (*localrepo.Repo).Rebase that landing uses: reapplied+// cherry-picks, and the committer when it is set.+func rebaseOptions(committer *git.Signature) []localrepo.RebaseOption {+ opts := []localrepo.RebaseOption{localrepo.RebaseWithReappliedCherryPicks()}+ if committer != nil {+ opts = append(opts, localrepo.RebaseWithCommitter(*committer))+ }+ return opts+}++// hasMergesInRange reports whether git rev-list --merges upstream..branch lists a commit, which is+// how landing found merge commits before the plan.+func hasMergesInRange(t *testing.T, f *fixture, upstream, branch git.ObjectID) bool {+ t.Helper()+ return strings.TrimSpace(string(gittest.Exec(t, f.cfg, "-C", f.repoPath, "rev-list", "--merges", upstream.String()+".."+branch.String()))) != ""+}++// requireSameRebase rebases with landRebase and with localrepo and requires the same outcome: the+// same object ID, or an error from both, with the same conflicting commit and conflict contents for+// a conflict. It returns the error of the localrepo rebase.+func requireSameRebase(t *testing.T, f *fixture, engine *Engine, upstream, branch git.ObjectID, committer *git.Signature) error {t.Helper()- wantOID, wantErr := f.repo.Rebase(f.ctx, upstream.String(), branch.String(), opts...)- gotOID, gotErr := engine.Rebase(f.ctx, upstream, branch, opts...)+ wantOID, wantErr := f.repo.Rebase(f.ctx, upstream.String(), branch.String(), rebaseOptions(committer)...)+ gotOID, gotErr := landRebase(f.ctx, f.repo, engine, upstream, branch, committer)require.Equal(t, wantOID, gotOID)if wantErr == nil {require.NoError(t, gotErr)return nil}-- testhelper.RequireGrpcError(t, wantErr, gotErr)+ require.Error(t, gotErr)var wantConflict, gotConflict *localrepo.RebaseConflictErrorif errors.As(wantErr, &wantConflict) {@@ -147,11 +193,14 @@ func requireSameRebase(t *testing.T, f *fixture, engine *Engine, upstream, brancreturn wantErr}-func TestEngineRebaseMatchesLocalrepo(t *testing.T) {+// TestEngineReplayMatchesLocalrepo rebases random histories the way landing does and with+// localrepo. A range with merge commits is refused by the plan, as landing refused it before with+// git rev-list --merges; every other range gives the commits of localrepo, or its conflict.+func TestEngineReplayMatchesLocalrepo(t *testing.T) {t.Parallel()- var conflicts, successes int- for seed := int64(1); seed <= 25; seed++ {+ var conflicts, successes, merges int+ for seed := int64(1); seed <= 40; seed++ {f := newFixture(t)rng := rand.New(rand.NewSource(seed))upstream, branch := buildHistories(f, rng)@@ -159,16 +208,20 @@ func TestEngineRebaseMatchesLocalrepo(t *testing.T) {engine := New(f.repo)t.Cleanup(func() { require.NoError(t, engine.Close()) })- var opts []localrepo.RebaseOption+ var committer *git.Signatureif seed%2 == 1 {- opts = append(opts, localrepo.RebaseWithCommitter(testCommitter))- }- if seed%5 == 0 {- opts = append(opts, localrepo.RebaseWithReappliedCherryPicks())+ committer = &testCommitter}t.Run(fmt.Sprintf("seed %d", seed), func(t *testing.T) {- err := requireSameRebase(t, f, engine, upstream, branch, opts...)+ if hasMergesInRange(t, f, upstream, branch) {+ merges+++ _, err := landRebase(f.ctx, f.repo, engine, upstream, branch, committer)+ require.ErrorIs(t, err, ErrMergesInRange)+ return+ }++ err := requireSameRebase(t, f, engine, upstream, branch, committer)var conflictErr *localrepo.RebaseConflictErrorswitch {@@ -182,6 +235,7 @@ func TestEngineRebaseMatchesLocalrepo(t *testing.T) {require.Positive(t, conflicts, "the seeds must cover conflicts")require.Positive(t, successes, "the seeds must cover successful rebases")+ require.Positive(t, merges, "the seeds must cover ranges with merge commits")}func TestEngineRebaseUnrelatedHistories(t *testing.T) {@@ -194,8 +248,10 @@ func TestEngineRebaseUnrelatedHistories(t *testing.T) {engine := New(f.repo)t.Cleanup(func() { require.NoError(t, engine.Close()) })- // Without a merge base the merge-base lookup fails the same way in both implementations.- require.Error(t, requireSameRebase(t, f, engine, upstream, branch, localrepo.RebaseWithCommitter(testCommitter)))+ // Without a merge base localrepo fails in its merge-base lookup, and the plan refuses the range.+ require.Error(t, requireSameRebase(t, f, engine, upstream, branch, &testCommitter))+ _, err := landRebase(f.ctx, f.repo, engine, upstream, branch, &testCommitter)+ require.ErrorIs(t, err, ErrUnrelated)}func TestEngineRebaseLongCommitMessage(t *testing.T) {@@ -210,7 +266,7 @@ func TestEngineRebaseLongCommitMessage(t *testing.T) {engine := New(f.repo)t.Cleanup(func() { require.NoError(t, engine.Close()) })- require.NoError(t, requireSameRebase(t, f, engine, upstream, branch))+ require.NoError(t, requireSameRebase(t, f, engine, upstream, branch, nil))}// fakeBackends counts the helper processes started and the operations done through them. Merges@@ -312,14 +368,14 @@ func TestEngineStartsHelpersLazily(t *testing.T) {engine := newEngine(f.repo, fb.backends())// A fast-forward, as the base is an ancestor of the branch, needs no helper process.- oid, err := engine.Rebase(f.ctx, base, branch)+ oid, err := landRebase(f.ctx, f.repo, engine, base, branch, nil)require.NoError(t, err)require.Equal(t, branch, oid)require.Zero(t, fb.streamStarts)require.Zero(t, fb.writerStarts)// A real rebase starts one helper of each kind, once.- oid, err = engine.Rebase(f.ctx, upstream, branch, localrepo.RebaseWithCommitter(testCommitter))+ oid, err = landRebase(f.ctx, f.repo, engine, upstream, branch, &testCommitter)require.NoError(t, err)require.NotEmpty(t, oid)require.Equal(t, 1, fb.streamStarts)@@ -358,7 +414,7 @@ func TestEngineFallsBackToWriteCommitWhenUnsupported(t *testing.T) {engine := newEngine(f.repo, fb.backends())t.Cleanup(func() { require.NoError(t, engine.Close()) })- require.NoError(t, requireSameRebase(t, f, engine, upstream, branch, localrepo.RebaseWithCommitter(testCommitter)))+ require.NoError(t, requireSameRebase(t, f, engine, upstream, branch, &testCommitter))require.Equal(t, 3, fb.writes, "every commit is offered to the writer first")}@@ -373,15 +429,15 @@ func TestEngineReportsHelperStartFailure(t *testing.T) {engine := newEngine(f.repo, fb.backends())t.Cleanup(func() { require.NoError(t, engine.Close()) })- _, err := engine.Rebase(f.ctx, upstream, branch)+ _, err := landRebase(f.ctx, f.repo, engine, upstream, branch, nil)require.ErrorIs(t, err, startErr)require.Zero(t, fb.writes)}func BenchmarkRebaseEngine(b *testing.B) {benchmarkRebase(b, func(f *fixture, upstream, branch git.ObjectID) {- // The fake backends count the helper processes the engine starts. The git commands run- // for the merge-base, the todo list and the object reads are not counted.+ // The fake backends count the helper processes the engine starts. The git command that lists+ // the range and the object reads are not counted.fb := &fakeBackends{repo: f.repo}engine := newEngine(f.repo, fb.backends())defer func() { require.NoError(b, engine.Close()) }()@@ -389,7 +445,7 @@ func BenchmarkRebaseEngine(b *testing.B) {var iterations intfor b.Loop() {iterations++- if _, err := engine.Rebase(f.ctx, upstream, branch, localrepo.RebaseWithCommitter(testCommitter)); err != nil {+ if _, err := landRebase(f.ctx, f.repo, engine, upstream, branch, &testCommitter); err != nil {b.Fatal(err)}}@@ -401,7 +457,7 @@ func BenchmarkRebaseEngine(b *testing.B) {func BenchmarkLocalrepoRebase(b *testing.B) {benchmarkRebase(b, func(f *fixture, upstream, branch git.ObjectID) {for b.Loop() {- if _, err := f.repo.Rebase(f.ctx, upstream.String(), branch.String(), localrepo.RebaseWithCommitter(testCommitter)); err != nil {+ if _, err := f.repo.Rebase(f.ctx, upstream.String(), branch.String(), rebaseOptions(&testCommitter)...); err != nil {b.Fatal(err)}}diff --git a/internal/graft/rebase/rebase_spec_test.go b/internal/graft/rebase/rebase_spec_test.goindex ec4adb8..314693c 100644--- a/internal/graft/rebase/rebase_spec_test.go+++ b/internal/graft/rebase/rebase_spec_test.go@@ -56,7 +56,7 @@ func specParents(t *testing.T, cfg config.Cfg, repoPath string, commit git.Objec}// TestSpecRebaseFastForward: when upstream is already an ancestor of the-// branch, Rebase returns the branch unchanged.+// branch, landing returns the branch unchanged.func TestSpecRebaseFastForward(t *testing.T) {ctx, cfg, repoPath, repo := specSetup(t)@@ -67,7 +67,7 @@ func TestSpecRebaseFastForward(t *testing.T) {engine := New(repo)t.Cleanup(func() { _ = engine.Close() })- got, err := engine.Rebase(ctx, upstream, branch)+ got, err := landRebase(ctx, repo, engine, upstream, branch, nil)if err != nil {t.Fatalf("Rebase: %v", err)}@@ -89,7 +89,7 @@ func TestSpecRebaseReplaysBranchOntoUpstream(t *testing.T) {engine := New(repo)t.Cleanup(func() { _ = engine.Close() })- got, err := engine.Rebase(ctx, upstream, c2)+ got, err := landRebase(ctx, repo, engine, upstream, c2, nil)if err != nil {t.Fatalf("Rebase: %v", err)}@@ -131,7 +131,7 @@ func TestSpecRebaseConflictReturnsRebaseConflictError(t *testing.T) {engine := New(repo)t.Cleanup(func() { _ = engine.Close() })- _, err := engine.Rebase(ctx, upstream, branch)+ _, err := landRebase(ctx, repo, engine, upstream, branch, nil)var conflict *localrepo.RebaseConflictErrorif !errors.As(err, &conflict) {t.Fatalf("got error %v (%T), want *localrepo.RebaseConflictError", err, err)@@ -139,7 +139,9 @@ func TestSpecRebaseConflictReturnsRebaseConflictError(t *testing.T) {}// TestSpecRebaseSkipsCherryPickedCommits: a branch commit whose change is-// already in upstream is not replayed, so the result is upstream itself.+// already in upstream becomes empty when it is replayed and is dropped, so the+// result is upstream itself. (Landing reapplies cherry-picks, see+// computeLandedTip; the commit is dropped as empty, not by patch ID.)func TestSpecRebaseSkipsCherryPickedCommits(t *testing.T) {ctx, cfg, repoPath, repo := specSetup(t)@@ -150,7 +152,7 @@ func TestSpecRebaseSkipsCherryPickedCommits(t *testing.T) {engine := New(repo)t.Cleanup(func() { _ = engine.Close() })- got, err := engine.Rebase(ctx, upstream, branch)+ got, err := landRebase(ctx, repo, engine, upstream, branch, nil)if err != nil {t.Fatalf("Rebase: %v", err)}@@ -159,10 +161,10 @@ func TestSpecRebaseSkipsCherryPickedCommits(t *testing.T) {}}-// TestSpecRebaseIgnoresMergesInRange: merge commits in upstream...branch are-// not replayed (--no-merges); the result is linear and keeps the changes of-// both merged sides.-func TestSpecRebaseIgnoresMergesInRange(t *testing.T) {+// TestSpecPlanRefusesMergesInRange: a range with a merge commit cannot be+// rebased. Landing refuses it (InvalidArgument, use STRATEGY_MERGE), so the plan+// returns ErrMergesInRange instead of a todo list.+func TestSpecPlanRefusesMergesInRange(t *testing.T) {ctx, cfg, repoPath, repo := specSetup(t)base := specCommit(t, cfg, repoPath, nil, map[string]string{"base": "base\n"})@@ -174,27 +176,13 @@ func TestSpecRebaseIgnoresMergesInRange(t *testing.T) {engine := New(repo)t.Cleanup(func() { _ = engine.Close() })- got, err := engine.Rebase(ctx, upstream, merge)- if err != nil {- t.Fatalf("Rebase: %v", err)- }- if n := len(specParents(t, cfg, repoPath, got)); n > 1 {- t.Fatalf("rebased tip is a merge with %d parents, want linear history", n)- }- merges := specGit(t, cfg, repoPath, "rev-list", "--merges", got.String(), "^"+upstream.String())- if merges != "" {- t.Fatalf("rebased history contains merge commits: %q", merges)- }- files := specFiles(t, cfg, repoPath, got)- for _, want := range []string{"base", "u", "b", "s"} {- if !specContains(files, want) {- t.Fatalf("rebased tree %v is missing %q", files, want)- }+ if _, err := landRebase(ctx, repo, engine, upstream, merge, nil); !errors.Is(err, ErrMergesInRange) {+ t.Fatalf("got error %v, want ErrMergesInRange", err)}}-// TestSpecEngineMatchesLocalrepoRebase: for the same inputs, Engine.Rebase and-// (*localrepo.Repo).Rebase produce the same tree, parents and messages on a+// TestSpecEngineMatchesLocalrepoRebase: for the same inputs, landing (plan and+// replay) and (*localrepo.Repo).Rebase with reapplied cherry-picks produce the same tree, parents and messages on a// clean replay, and the same error type on a conflict.func TestSpecEngineMatchesLocalrepoRebase(t *testing.T) {ctx, cfg, repoPath, repo := specSetup(t)@@ -209,8 +197,8 @@ func TestSpecEngineMatchesLocalrepoRebase(t *testing.T) {engine := New(repo)t.Cleanup(func() { _ = engine.Close() })- engineOID, engineErr := engine.Rebase(ctx, upstream, c2)- localOID, localErr := repo.Rebase(ctx, upstream.String(), c2.String())+ engineOID, engineErr := landRebase(ctx, repo, engine, upstream, c2, nil)+ localOID, localErr := repo.Rebase(ctx, upstream.String(), c2.String(), rebaseOptions(nil)...)if engineErr != nil || localErr != nil {t.Fatalf("clean replay errors: engine=%v localrepo=%v", engineErr, localErr)}@@ -224,8 +212,8 @@ func TestSpecEngineMatchesLocalrepoRebase(t *testing.T) {t.Fatalf("message mismatch: engine %q, localrepo %q", got, want)}- _, engineErr = engine.Rebase(ctx, conflictUpstream, conflictBranch)- _, localErr = repo.Rebase(ctx, conflictUpstream.String(), conflictBranch.String())+ _, engineErr = landRebase(ctx, repo, engine, conflictUpstream, conflictBranch, nil)+ _, localErr = repo.Rebase(ctx, conflictUpstream.String(), conflictBranch.String(), rebaseOptions(nil)...)var engineConflict, localConflict *localrepo.RebaseConflictErrorif !errors.As(engineErr, &engineConflict) || !errors.As(localErr, &localConflict) {t.Fatalf("conflict errors: engine %v (%T), localrepo %v (%T)", engineErr, engineErr, localErr, localErr)@@ -244,7 +232,7 @@ func TestSpecEngineReuseAndClose(t *testing.T) {engine := New(repo)for _, branch := range []git.ObjectID{c1, c2} {- if _, err := engine.Rebase(ctx, upstream, branch); err != nil {+ if _, err := landRebase(ctx, repo, engine, upstream, branch, nil); err != nil {t.Fatalf("Rebase %s: %v", branch, err)}}