Skip to content

Git designed for AI agents.

land: decide from exact ranges when committer dates are skewed

Federico Eliaa7786547e143
diff --git a/internal/gitaly/service/operations/land_attempt.go b/internal/gitaly/service/operations/land_attempt.go
index ff0a179..d8d68ab 100644
--- a/internal/gitaly/service/operations/land_attempt.go
+++ b/internal/gitaly/service/operations/land_attempt.go
@@ -253,17 +253,12 @@ func (a *landingAttempt) peel(ctx context.Context, commitID git.ObjectID) (git.O
return info.Oid, nil
}
-// plan decides how commitID lands onto tip from one listing of the commits it adds to tip (see
-// rebase.PlanLanding).
+// plan decides how commitID lands onto tip (see rebase.Plan): from one listing of the commits it
+// adds to tip, made exact when the change diverges.
func (a *landingAttempt) plan(ctx context.Context, tip, commitID git.ObjectID) (rebase.LandPlan, error) {
defer a.observe(landBatchPhasePlan, time.Now())
- rng, err := a.ancestry.Range(ctx, tip, commitID)
- if err != nil {
- return rebase.LandPlan{}, structerr.NewInternal("listing the commits of the change: %w", err)
- }
-
- plan, err := rebase.PlanLanding(tip, commitID, rng)
+ plan, err := rebase.Plan(ctx, a.ancestry, tip, commitID)
if err != nil {
return rebase.LandPlan{}, structerr.NewInternal("planning the landing: %w", err)
}
diff --git a/internal/gitaly/service/operations/land_batch_executor_spec_test.go b/internal/gitaly/service/operations/land_batch_executor_spec_test.go
index dcb64e8..b753aa9 100644
--- a/internal/gitaly/service/operations/land_batch_executor_spec_test.go
+++ b/internal/gitaly/service/operations/land_batch_executor_spec_test.go
@@ -8,6 +8,7 @@ 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/feder-cr/git-ai/internal/git/revrange"
"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/graft/landlane"
@@ -86,13 +87,13 @@ func TestSpecAncestryNewEnabledAgreesWithGit(t *testing.T) {
checker := ancestry.New(ctx, true, repo, nil, nil, testhelper.NewLogger(t))
require.NotNil(t, checker)
- // Phase 4b: the checker answers one question, the range of a change (PLAN8).
+ // Phase 4b: the checker answers the range of a change (PLAN8), exact through revrange.
pairs := [][2]git.ObjectID{{base, merge}, {merge, base}, {left, right}, {right, left}, {base, base}}
for _, p := range pairs {
- want, wantErr := reference.Range(ctx, p[0], p[1])
- got, gotErr := checker.Range(ctx, p[0], p[1])
+ want, wantErr := revrange.Exact(ctx, reference, p[0], p[1])
+ got, gotErr := revrange.Exact(ctx, checker, p[0], p[1])
require.Equal(t, wantErr != nil, gotErr != nil)
- require.ElementsMatch(t, want, got, "Range(%s, %s)", p[0], p[1])
+ require.ElementsMatch(t, want, got, "range %s..%s", p[0], p[1])
}
}
diff --git a/internal/gitaly/service/operations/land_batch_pack_test.go b/internal/gitaly/service/operations/land_batch_pack_test.go
index 87fcaad..65a4be4 100644
--- a/internal/gitaly/service/operations/land_batch_pack_test.go
+++ b/internal/gitaly/service/operations/land_batch_pack_test.go
@@ -260,10 +260,11 @@ func commandCount(ctx context.Context) 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) {
+// TestLandBatchStepperProcessesPerMember drives one batch attempt: every request is decided from one
+// range listing, made exact with one more check when the request diverges, 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 TestLandBatchStepperProcessesPerMember(t *testing.T) {
t.Parallel()
ctx := log.InitContextCustomFields(featureflag.ContextWithFeatureFlag(testhelper.Context(t), featureflag.GPGSigning, false))
@@ -309,14 +310,18 @@ func TestLandBatchStepperLandsWithOneProcessPerMember(t *testing.T) {
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 process: the range listing (git rev-list). The command factory
- // reads the object format for attr.tree from the repository's files, without a process.
+ // A request already landed and a fast-forward of the starting tip each run one short git
+ // process: the range listing (git rev-list), from which both facts are exact. A rebase onto the
+ // running tip runs one more, the check of the one bottom of its listing (git merge-base
+ // --is-ancestor), which makes the range it replays exact under skewed committer dates (see
+ // revrange). The command factory reads the object format for attr.tree from the repository's
+ // files, without a process.
const rangeListingProcesses = 1
+ const exactRangeProcesses = rangeListingProcesses + 1
second, processes := landWithProcesses(first.tip, f.diverged2)
require.True(t, second.rewritten)
- require.Equal(t, rangeListingProcesses, processes, "rebase")
+ require.Equal(t, exactRangeProcesses, processes, "rebase")
landed, processes := landWithProcesses(second.tip, f.base)
require.True(t, landed.alreadyLanded)
diff --git a/internal/gitaly/service/operations/land_skew_test.go b/internal/gitaly/service/operations/land_skew_test.go
new file mode 100644
index 0000000..66a2592
--- /dev/null
+++ b/internal/gitaly/service/operations/land_skew_test.go
@@ -0,0 +1,145 @@
+package operations
+
+import (
+ "context"
+ "fmt"
+ "strings"
+ "testing"
+ "time"
+
+ "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/gitaly/config"
+ "github.com/feder-cr/git-ai/internal/testhelper"
+ "github.com/feder-cr/git-ai/proto/go/gitalypb"
+ "github.com/stretchr/testify/require"
+ "google.golang.org/grpc/codes"
+)
+
+// skewedReviewHistory writes the history that the review of phase 4b reported, on the default
+// branch: a root R dated 2026-01, A on it dated 2026-02, and ten commits on A dated 2025-06, the
+// last of which is the tip. git rev-list tip..A lists A and R although the tip reaches both. It
+// also writes C on A, dated after A, which no branch has. Each commit adds a file of its own.
+func skewedReviewHistory(t *testing.T, cfg config.Cfg, repoPath string) (a, c, tip git.ObjectID) {
+ t.Helper()
+
+ var entries []gittest.TreeEntry
+ write := func(name string, date time.Time, parents ...git.ObjectID) git.ObjectID {
+ entries = append(entries, gittest.TreeEntry{Mode: "100644", Path: name, Content: name + "\n"})
+ return gittest.WriteCommit(t, cfg, repoPath,
+ gittest.WithParents(parents...),
+ gittest.WithTreeEntries(entries...),
+ gittest.WithMessage(name),
+ gittest.WithAuthorDate(date),
+ gittest.WithCommitterDate(date),
+ )
+ }
+
+ root := write("r", time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC))
+ a = write("a", time.Date(2026, 2, 1, 0, 0, 0, 0, time.UTC), root)
+ tip = a
+ for i := 0; i < 10; i++ {
+ tip = write(fmt.Sprintf("x%d", i), time.Date(2025, 6, 1, 0, 0, i, 0, time.UTC), tip)
+ }
+ gittest.Exec(t, cfg, "-C", repoPath, "update-ref", "refs/heads/"+git.DefaultBranch, tip.String())
+
+ // C is written on a copy of A's tree, not on the tip's.
+ entries = entries[:2]
+ c = write("c", time.Date(2026, 2, 1, 0, 1, 0, 0, time.UTC), a)
+
+ listed := strings.Fields(string(gittest.Exec(t, cfg, "-C", repoPath, "rev-list", tip.String()+".."+a.String())))
+ require.ElementsMatch(t, []string{a.String(), root.String()}, listed, "git rev-list no longer shows the skew this test is about")
+
+ return a, c, tip
+}
+
+// TestUserLand_skewedCommitterDates lands on the history of the review, with every strategy:
+// landing A again (a retry) reports it as already landed and leaves the branch alone, and C, which
+// diverges from the tip and shares A with it, lands as the strategy says, instead of failing as
+// unrelated or merging a commit that is already on the branch.
+func TestUserLand_skewedCommitterDates(t *testing.T) {
+ t.Parallel()
+
+ runLandBatchTest(t, testUserLandSkewedCommitterDates)
+}
+
+func testUserLandSkewedCommitterDates(t *testing.T, ctx context.Context) {
+ ctx, cfg, client := setupOperationsService(t, ctx)
+
+ for _, strategy := range []gitalypb.UserLandRequest_Strategy{
+ gitalypb.UserLandRequest_STRATEGY_REBASE_UNSPECIFIED,
+ gitalypb.UserLandRequest_STRATEGY_MERGE,
+ gitalypb.UserLandRequest_STRATEGY_FF_ONLY,
+ } {
+ t.Run(strategy.String(), func(t *testing.T) {
+ repoProto, repoPath := gittest.CreateRepository(t, ctx, cfg)
+ repo := localrepo.NewTestRepo(t, cfg, repoProto)
+ a, c, tip := skewedReviewHistory(t, cfg, repoPath)
+
+ request := landRequest(repoProto, git.DefaultBranch, a)
+ request.Strategy = strategy
+ resp, err := client.UserLand(ctx, request)
+ require.NoError(t, err)
+ require.True(t, resp.GetAlreadyLanded())
+ require.Equal(t, tip.String(), resp.GetLandedCommitId())
+ requireBranchAt(t, cfg, repoPath, git.DefaultBranch, tip)
+
+ request = landRequest(repoProto, git.DefaultBranch, c)
+ request.Strategy = strategy
+ resp, err = client.UserLand(ctx, request)
+
+ switch strategy {
+ case gitalypb.UserLandRequest_STRATEGY_FF_ONLY:
+ testhelper.RequireGrpcCode(t, err, codes.FailedPrecondition)
+ require.NotNil(t, landErrorDetail(t, err).GetNotAncestor())
+ requireBranchAt(t, cfg, repoPath, git.DefaultBranch, tip)
+ return
+ case gitalypb.UserLandRequest_STRATEGY_MERGE:
+ require.NoError(t, err)
+ landed, err := repo.ReadCommit(ctx, git.Revision(resp.GetLandedCommitId()))
+ require.NoError(t, err)
+ require.Equal(t, []string{tip.String(), c.String()}, landed.GetParentIds())
+ default:
+ require.NoError(t, err)
+ require.True(t, resp.GetRewritten())
+ landed, err := repo.ReadCommit(ctx, git.Revision(resp.GetLandedCommitId()))
+ require.NoError(t, err)
+ // C alone is replayed onto the tip.
+ require.Equal(t, []string{tip.String()}, landed.GetParentIds())
+ require.Equal(t, []byte("c"), landed.GetSubject())
+ }
+
+ requireBranchAt(t, cfg, repoPath, git.DefaultBranch, git.ObjectID(resp.GetLandedCommitId()))
+ content := gittest.Exec(t, cfg, "-C", repoPath, "show", resp.GetLandedCommitId()+":c")
+ require.Equal(t, "c\n", string(content))
+ })
+ }
+}
+
+// TestUserLand_skewedCommitterDatesInABatch lands A again and C in one batch on the history of the
+// review: A is already landed and C is rebased onto the tip.
+func TestUserLand_skewedCommitterDatesInABatch(t *testing.T) {
+ t.Parallel()
+
+ runLandBatchTest(t, func(t *testing.T, ctx context.Context) {
+ ctx, cfg, client := setupLandBatchService(t, ctx, batchingGraft())
+ repoProto, repoPath := gittest.CreateRepository(t, ctx, cfg)
+ repo := localrepo.NewTestRepo(t, cfg, repoProto)
+ a, c, tip := skewedReviewHistory(t, cfg, repoPath)
+
+ responses, errs := landAll(ctx, client, repoProto, []git.ObjectID{a, c})
+ require.NoError(t, errs[0])
+ require.NoError(t, errs[1])
+
+ require.True(t, responses[0].GetAlreadyLanded())
+ require.False(t, responses[1].GetAlreadyLanded())
+ require.True(t, responses[1].GetRewritten())
+
+ head := gittest.ResolveRevision(t, cfg, repoPath, "refs/heads/"+git.DefaultBranch)
+ landed, err := repo.ReadCommit(ctx, head.Revision())
+ require.NoError(t, err)
+ require.Equal(t, []string{tip.String()}, landed.GetParentIds())
+ require.Equal(t, []byte("c"), landed.GetSubject())
+ })
+}
diff --git a/internal/graft/ancestry/ancestry.go b/internal/graft/ancestry/ancestry.go
index c958899..8837916 100644
--- a/internal/graft/ancestry/ancestry.go
+++ b/internal/graft/ancestry/ancestry.go
@@ -1,24 +1,26 @@
-// Package ancestry answers the history question of a landing: which commits a change adds to a
-// branch (Checker.Range), from which the land decision follows (rebase.PlanLanding). Git answers it
-// by running git rev-list, and the graph checker from the stored graph index (see
-// internal/graft/derived/graph). Both return the same commits, so a landing gives the same outcome
-// with either.
+// Package ancestry answers the history questions of a landing (revrange.Walker): which commits a
+// change adds to a branch, whether a commit is reachable from another and the merge bases of two
+// commits. The git checker runs git for each question, and the graph checker answers from the
+// stored graph index (see internal/graft/derived/graph). The listing of the git checker may hold
+// commits outside of the range when committer dates are skewed; revrange.Exact, which
+// rebase.Plan uses, makes it exact. The listing of the graph checker is exact. A landing gives the
+// same outcome with either.
package ancestry
import (
"bytes"
+ "container/heap"
"context"
"errors"
"fmt"
"io/fs"
"os"
"path/filepath"
- "strings"
"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/gitcmd"
"github.com/feder-cr/git-ai/internal/git/localrepo"
+ "github.com/feder-cr/git-ai/internal/git/revrange"
"github.com/feder-cr/git-ai/internal/graft/derived"
"github.com/feder-cr/git-ai/internal/graft/derived/graph"
"github.com/feder-cr/git-ai/internal/log"
@@ -31,26 +33,19 @@ const (
graphKindVersion = graph.KindVersion
)
-// Checker answers the history question of one landing attempt. A Checker is used by one goroutine
-// at a time.
-type Checker interface {
- // Range returns the commits reachable from head and not from base, as git rev-list
- // base..head lists them, each with all of its parents, in no particular order. It is empty
- // when head is reachable from base.
- Range(ctx context.Context, base, head git.ObjectID) ([]RangeCommit, error)
-}
+// Checker answers the history questions of one landing attempt. A Checker is used by one goroutine
+// at a time. Its List is a listing that only revrange.Exact or revrange.Refine (through
+// rebase.Plan) make exact: no caller may take it for the exact range.
+type Checker = revrange.Walker
// RangeCommit is a commit of a range with all of its parents in order, as git rev-list --parents
// prints it.
-type RangeCommit struct {
- ID git.ObjectID
- Parents []git.ObjectID
-}
+type RangeCommit = revrange.Commit
// Git returns a Checker that runs git for each question. It is the behaviour without the graph
// index.
func Git(repo *localrepo.Repo) Checker {
- return gitChecker{repo: repo}
+ return revrange.Git(repo)
}
// Graph returns a Checker that answers from the graph index of repo. The index reads the parents
@@ -135,92 +130,146 @@ func requireAbsent(path string) error {
}
}
-// gitChecker answers with git.
-type gitChecker struct {
- repo *localrepo.Repo
+// graphChecker answers with the graph index.
+type graphChecker struct {
+ index *graph.Index
+ // source reads the parents of the commits of a range.
+ source graph.Source
}
-// Range lists the range with one git rev-list --parents process.
-func (c gitChecker) Range(ctx context.Context, base, head git.ObjectID) ([]RangeCommit, error) {
- objectHash, err := c.repo.ObjectHash(ctx)
- if err != nil {
- return nil, fmt.Errorf("detecting object hash: %w", err)
- }
+// The flags of the walk of List.
+const (
+ // fromHead marks the commits reachable from head.
+ fromHead uint8 = 1 << iota
+ // fromExcluded marks the commits reachable from a commit of exclude.
+ fromExcluded
+)
+
+// List returns exactly the commits reachable from head and from none of exclude. It walks down from
+// all of them at once in the order of their generation numbers, highest first. Every descendant of
+// a commit has a higher generation, so when the walk takes a commit, all of its descendants that the
+// walk reaches were taken already and its flags are final: it is in the range when head reaches it
+// and no excluded commit does. The walk ends when no commit that only head reaches is left to take,
+// as the ancestors of the others are not in the range.
+func (c graphChecker) List(ctx context.Context, head git.ObjectID, exclude []git.ObjectID) ([]RangeCommit, error) {
+ w := graphWalk{checker: c, flags: map[git.ObjectID]uint8{}}
- var stdout, stderr bytes.Buffer
- if err := c.repo.ExecAndWait(ctx,
- gitcmd.Command{
- Name: "rev-list",
- Flags: []gitcmd.Option{gitcmd.Flag{Name: "--parents"}},
- Args: []string{base.String() + ".." + head.String()},
- },
- gitcmd.WithStdout(&stdout),
- gitcmd.WithStderr(&stderr),
- ); err != nil {
- return nil, fmt.Errorf("rev-list: %w, stderr: %q", err, stderr.String())
+ if err := w.add(ctx, head, fromHead); err != nil {
+ return nil, err
+ }
+ for _, id := range exclude {
+ if err := w.add(ctx, id, fromExcluded); err != nil {
+ return nil, err
+ }
}
var commits []RangeCommit
- for _, line := range strings.Split(stdout.String(), "\n") {
- fields := strings.Fields(line)
- if len(fields) == 0 {
- continue
+ for w.headOnly > 0 {
+ next := heap.Pop(&w.queue).(generationItem)
+ flags := w.flags[next.id]
+ if flags == fromHead {
+ w.headOnly--
+ }
+
+ parents, err := c.source.Parents(ctx, next.id)
+ if err != nil {
+ return nil, err
}
- ids := make([]git.ObjectID, 0, len(fields))
- for _, field := range fields {
- id, err := objectHash.FromHex(field)
- if err != nil {
- return nil, fmt.Errorf("parsing rev-list output %q: %w", line, err)
+ // A commit that an excluded commit reaches passes only that on: its ancestors are not in
+ // the range, whether head reaches them or not.
+ propagate := fromExcluded
+ if flags == fromHead {
+ commits = append(commits, RangeCommit{ID: next.id, Parents: parents})
+ propagate = fromHead
+ }
+
+ for _, parent := range parents {
+ if err := w.add(ctx, parent, propagate); err != nil {
+ return nil, err
}
- ids = append(ids, id)
}
- commits = append(commits, RangeCommit{ID: ids[0], Parents: ids[1:]})
}
return commits, nil
}
-// graphChecker answers with the graph index.
-type graphChecker struct {
- index *graph.Index
- // source reads the parents of the commits of a range.
- source graph.Source
+// IsAncestor answers from the graph index.
+func (c graphChecker) IsAncestor(ctx context.Context, ancestor, descendant git.ObjectID) (bool, error) {
+ return c.index.IsAncestor(ctx, ancestor, descendant)
}
-// Range walks down from head through the parents of the commits that the index does not find
-// reachable from base. The ancestors of a commit reachable from base are all reachable from base, so
-// the walk stops there without missing a commit of the range.
-func (c graphChecker) Range(ctx context.Context, base, head git.ObjectID) ([]RangeCommit, error) {
- var commits []RangeCommit
- seen := map[git.ObjectID]bool{head: true}
- pending := []git.ObjectID{head}
+// MergeBases answers from the graph index.
+func (c graphChecker) MergeBases(ctx context.Context, a, b git.ObjectID) ([]git.ObjectID, error) {
+ return c.index.MergeBases(ctx, a, b)
+}
- for len(pending) > 0 {
- id := pending[len(pending)-1]
- pending = pending[:len(pending)-1]
+// graphWalk is the state of one List of the graph checker.
+type graphWalk struct {
+ checker graphChecker
+ // flags holds the flags of every commit the walk reached.
+ flags map[git.ObjectID]uint8
+ // queue holds the commits that the walk reached and did not take yet.
+ queue generationQueue
+ // queued holds the commits of queue.
+ queued map[git.ObjectID]bool
+ // headOnly counts the commits of queue whose flags are fromHead alone.
+ headOnly int
+}
- reachable, err := c.index.IsAncestor(ctx, id, base)
- if err != nil {
- return nil, err
- }
- if reachable {
- continue
+// add gives id the flags, and queues it when the walk did not reach it before.
+func (w *graphWalk) add(ctx context.Context, id git.ObjectID, flags uint8) error {
+ old, reached := w.flags[id]
+ if reached {
+ if !w.queued[id] {
+ // A commit is taken after all of its descendants, so a commit that was taken gets no
+ // flags from a descendant afterwards.
+ if old|flags != old {
+ return fmt.Errorf("graph walk reached commit %s again after taking it", id)
+ }
+ return nil
}
- parents, err := c.source.Parents(ctx, id)
- if err != nil {
- return nil, err
+ if old == fromHead && old|flags != fromHead {
+ w.headOnly--
}
- commits = append(commits, RangeCommit{ID: id, Parents: parents})
+ w.flags[id] = old | flags
+ return nil
+ }
- for _, parent := range parents {
- if !seen[parent] {
- seen[parent] = true
- pending = append(pending, parent)
- }
- }
+ generation, err := w.checker.index.Generation(ctx, id)
+ if err != nil {
+ return err
}
- return commits, nil
+ if w.queued == nil {
+ w.queued = map[git.ObjectID]bool{}
+ }
+ w.flags[id] = flags
+ w.queued[id] = true
+ if flags == fromHead {
+ w.headOnly++
+ }
+ heap.Push(&w.queue, generationItem{id: id, generation: generation})
+ return nil
+}
+
+// generationItem is a commit of the queue of a graph walk.
+type generationItem struct {
+ id git.ObjectID
+ generation uint32
+}
+
+// generationQueue is a heap of commits, highest generation first.
+type generationQueue []generationItem
+
+func (q generationQueue) Len() int { return len(q) }
+func (q generationQueue) Less(i, j int) bool { return q[i].generation > q[j].generation }
+func (q generationQueue) Swap(i, j int) { q[i], q[j] = q[j], q[i] }
+func (q *generationQueue) Push(x any) { *q = append(*q, x.(generationItem)) }
+func (q *generationQueue) Pop() any {
+ old := *q
+ item := old[len(old)-1]
+ *q = old[:len(old)-1]
+ return item
}
diff --git a/internal/graft/ancestry/ancestry_spec_test.go b/internal/graft/ancestry/ancestry_spec_test.go
index 173205a..d4dfc81 100644
--- a/internal/graft/ancestry/ancestry_spec_test.go
+++ b/internal/graft/ancestry/ancestry_spec_test.go
@@ -8,8 +8,9 @@ package ancestry
// - gittest.TreeEntry{Mode, Path, Content} is the tree-entry type for WithTreeEntries.
// - testhelper.NewLogger(t) returns a log.Logger.
//
-// Phase 4b (PLAN8): the checker answers one question, Range; IsAncestor and MergeBase were removed
-// with the land decision that used them. These tests check Range with the same fixtures.
+// Phase 4b (PLAN8) and the fix of committer-date skew: the checker is a revrange.Walker whose
+// listing only revrange.Exact makes exact. These tests check the exact range of each checker with
+// the same fixtures.
// - objectReader and derivedStore are placeholders for the catfile reader and the
// derived store of the test repo; they fail the test until wired.
@@ -24,6 +25,7 @@ import (
"github.com/feder-cr/git-ai/internal/git/catfile"
"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/revrange"
"github.com/feder-cr/git-ai/internal/gitaly/config"
"github.com/feder-cr/git-ai/internal/graft/derived"
"github.com/feder-cr/git-ai/internal/log"
@@ -96,8 +98,8 @@ func testLogger(t *testing.T) log.Logger {
func assertSameAnswers(t *testing.T, fx *specFixture, want, got Checker, x, y git.ObjectID) {
t.Helper()
- wRange, wErr := want.Range(fx.ctx, x, y)
- gRange, gErr := got.Range(fx.ctx, x, y)
+ wRange, wErr := revrange.Exact(fx.ctx, want, x, y)
+ gRange, gErr := revrange.Exact(fx.ctx, got, x, y)
if wErr != nil || gErr != nil {
t.Fatalf("Range(%s, %s): want err %v, got err %v", x, y, wErr, gErr)
}
@@ -106,11 +108,11 @@ func assertSameAnswers(t *testing.T, fx *specFixture, want, got Checker, x, y gi
}
}
-// mustRange returns the range base..head of chk as a set.
+// mustRange returns the exact range base..head of chk as a set.
func mustRange(t *testing.T, fx *specFixture, chk Checker, base, head git.ObjectID) map[git.ObjectID][]git.ObjectID {
t.Helper()
- rng, err := chk.Range(fx.ctx, base, head)
+ rng, err := revrange.Exact(fx.ctx, chk, base, head)
if err != nil {
t.Fatalf("Range(%s, %s): %v", base, head, err)
}
diff --git a/internal/graft/ancestry/ancestry_test.go b/internal/graft/ancestry/ancestry_test.go
index 6995ac5..5f568aa 100644
--- a/internal/graft/ancestry/ancestry_test.go
+++ b/internal/graft/ancestry/ancestry_test.go
@@ -14,6 +14,7 @@ import (
"github.com/feder-cr/git-ai/internal/git/catfile"
"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/revrange"
"github.com/feder-cr/git-ai/internal/gitaly/config"
"github.com/feder-cr/git-ai/internal/graft/derived"
"github.com/feder-cr/git-ai/internal/testhelper"
@@ -120,60 +121,241 @@ func newAncestryEnv(t *testing.T) (config.Cfg, string, *localrepo.Repo, catfile.
return cfg, repoPath, repo, reader
}
-func TestGraphMatchesGitOnRandomDAG(t *testing.T) {
- t.Parallel()
+// writeDatedHistory is writeHistory with the committer date dates[i] for commit i.
+func writeDatedHistory(t *testing.T, cfg config.Cfg, repoPath string, parents [][]int, dates []int64) []git.ObjectID {
+ t.Helper()
- for _, seed := range []int64{1, 2} {
- t.Run(fmt.Sprintf("seed %d", seed), func(t *testing.T) {
- t.Parallel()
+ var stream bytes.Buffer
+ for i, list := range parents {
+ name := fmt.Sprintf("c%d", i)
+ fmt.Fprintf(&stream, "commit refs/heads/%s\n", name)
+ fmt.Fprintf(&stream, "mark :%d\n", i+1)
+ fmt.Fprintf(&stream, "committer Tester <[email protected]> %d +0000\n", dates[i])
+ fmt.Fprintf(&stream, "data %d\n%s\n", len(name), name)
+ for j, parent := range list {
+ if j == 0 {
+ fmt.Fprintf(&stream, "from :%d\n", parent+1)
+ } else {
+ fmt.Fprintf(&stream, "merge :%d\n", parent+1)
+ }
+ }
+ stream.WriteString("\n")
+ }
- ctx := testhelper.Context(t)
- cfg, repoPath, repo, reader := newAncestryEnv(t)
- rnd := rand.New(rand.NewSource(seed))
+ gittest.ExecOpts(t, cfg, gittest.ExecConfig{Stdin: &stream}, "-C", repoPath, "fast-import", "--quiet")
- ids := writeHistory(t, cfg, repoPath, crissCrossHistory(rnd, 220))
- require.Len(t, gitMergeBases(t, cfg, repoPath, ids[3], ids[4]), 2, "commits 3 and 4 must form a criss-cross")
+ ids := make([]git.ObjectID, 0, len(parents))
+ for i := range parents {
+ ids = append(ids, gittest.ResolveRevision(t, cfg, repoPath, fmt.Sprintf("refs/heads/c%d", i)))
+ }
+ return ids
+}
- store := derived.NewStore(repoPath)
- graphChecker, err := Graph(ctx, repo, reader, store)
- require.NoError(t, err)
- gitChecker := Git(repo)
-
- // Pairs: the criss-cross, self pairs, the root against every commit, and random pairs.
- type pair struct{ a, b git.ObjectID }
- var pairs []pair
- pairs = append(pairs, pair{ids[3], ids[4]}, pair{ids[4], ids[3]}, pair{ids[3], ids[3]})
- for _, id := range ids[1:] {
- pairs = append(pairs, pair{ids[0], id}, pair{id, ids[0]})
- }
- for range 150 {
- pairs = append(pairs, pair{ids[rnd.Intn(len(ids))], ids[rnd.Intn(len(ids))]})
+// skewedDates returns dates that grow with the index of the commit, except for random runs of
+// commits that are dated a year before the first commit.
+func skewedDates(rnd *rand.Rand, n int) []int64 {
+ dates := make([]int64, n)
+ for i := range dates {
+ dates[i] = 1600000000 + int64(i)
+ }
+ for run := 0; run < n/16; run++ {
+ start := rnd.Intn(n)
+ for k := 0; k < 6+rnd.Intn(12) && start+k < n; k++ {
+ dates[start+k] = 1568000000 + int64(k)
+ }
+ }
+ return dates
+}
+
+// ancestorsOf returns the indexes of the commits reachable from commit x, x included.
+func ancestorsOf(parents [][]int, x int) map[int]bool {
+ seen := map[int]bool{x: true}
+ stack := []int{x}
+ for len(stack) > 0 {
+ c := stack[len(stack)-1]
+ stack = stack[:len(stack)-1]
+ for _, p := range parents[c] {
+ if !seen[p] {
+ seen[p] = true
+ stack = append(stack, p)
}
+ }
+ }
+ return seen
+}
+
+// exactRangeOf returns the range base..head computed from the history itself, as rangeSet returns
+// a range.
+func exactRangeOf(parents [][]int, ids []git.ObjectID, base, head int) map[git.ObjectID][]git.ObjectID {
+ baseAncestors := ancestorsOf(parents, base)
+ set := map[git.ObjectID][]git.ObjectID{}
+ for x := range ancestorsOf(parents, head) {
+ if baseAncestors[x] {
+ continue
+ }
+ var ps []git.ObjectID
+ for _, p := range parents[x] {
+ ps = append(ps, ids[p])
+ }
+ set[ids[x]] = ps
+ }
+ return set
+}
+
+// TestRangesMatchTheHistory checks, on seeded random histories with criss-crosses and an unrelated
+// tree, with committer dates that grow along the history and with skewed ones, the ranges against
+// the ones computed from the history itself: the listing of the graph checker and the exact
+// ranges of both checkers equal them, and the listing of the git checker holds them and otherwise
+// only commits that the base reaches.
+func TestRangesMatchTheHistory(t *testing.T) {
+ t.Parallel()
- requireAgree := func(checker Checker, label string, pairs []pair) {
- t.Helper()
+ for _, skewed := range []bool{false, true} {
+ for _, seed := range []int64{1, 2} {
+ t.Run(fmt.Sprintf("skewed %v seed %d", skewed, seed), func(t *testing.T) {
+ t.Parallel()
+
+ ctx := testhelper.Context(t)
+ cfg, repoPath, repo, reader := newAncestryEnv(t)
+ rnd := rand.New(rand.NewSource(seed))
+
+ parents := crissCrossHistory(rnd, 220)
+ for i := 0; i < 40; i++ {
+ if i == 0 {
+ parents = append(parents, nil)
+ continue
+ }
+ parents = append(parents, []int{len(parents) - 1})
+ }
+
+ dates := make([]int64, len(parents))
+ for i := range dates {
+ dates[i] = 1600000000 + int64(i)
+ }
+ if skewed {
+ dates = skewedDates(rnd, len(parents))
+ }
+ ids := writeDatedHistory(t, cfg, repoPath, parents, dates)
+ require.Len(t, gitMergeBases(t, cfg, repoPath, ids[3], ids[4]), 2, "commits 3 and 4 must form a criss-cross")
+ index := make(map[git.ObjectID]int, len(ids))
+ for i, id := range ids {
+ index[id] = i
+ }
+
+ store := derived.NewStore(repoPath)
+ graphChecker, err := Graph(ctx, repo, reader, store)
+ require.NoError(t, err)
+ gitChecker := Git(repo)
+
+ type pair struct{ base, head int }
+ pairs := []pair{{3, 4}, {4, 3}, {3, 3}, {0, 219}, {219, len(ids) - 1}}
+ for _, i := range []int{1, 50, 100, 150, 219} {
+ pairs = append(pairs, pair{0, i}, pair{i, 0})
+ }
+ for range 150 {
+ pairs = append(pairs, pair{rnd.Intn(len(ids)), rnd.Intn(len(ids))})
+ }
+ overListed, nonEmpty := 0, 0
for _, p := range pairs {
- want, err := gitChecker.Range(ctx, p.a, p.b)
+ base, head := ids[p.base], ids[p.head]
+ want := exactRangeOf(parents, ids, p.base, p.head)
+ if len(want) > 0 {
+ nonEmpty++
+ }
+
+ listed, err := graphChecker.List(ctx, head, []git.ObjectID{base})
require.NoError(t, err)
- got, err := checker.Range(ctx, p.a, p.b)
+ require.Equal(t, want, rangeSet(listed), "graph listing of %d..%d", p.base, p.head)
+
+ listed, err = gitChecker.List(ctx, head, []git.ObjectID{base})
require.NoError(t, err)
- require.Equal(t, rangeSet(want), rangeSet(got), "%s: Range(%s, %s)", label, p.a, p.b)
+ baseAncestors := ancestorsOf(parents, p.base)
+ extra := false
+ for id, ps := range rangeSet(listed) {
+ if wantParents, ok := want[id]; ok {
+ require.Equal(t, wantParents, ps)
+ continue
+ }
+ require.True(t, baseAncestors[index[id]], "git listing of %d..%d holds c%d, which base does not reach", p.base, p.head, index[id])
+ extra = true
+ }
+ for id := range want {
+ require.Contains(t, rangeSet(listed), id, "git listing of %d..%d misses c%d", p.base, p.head, index[id])
+ }
+ if extra {
+ overListed++
+ }
+
+ for name, checker := range map[string]Checker{"git": gitChecker, "graph": graphChecker} {
+ rng, err := revrange.Exact(ctx, checker, base, head)
+ require.NoError(t, err)
+ require.Equal(t, want, rangeSet(rng), "%s: exact range %d..%d", name, p.base, p.head)
+ }
+ }
+ require.Positive(t, nonEmpty)
+
+ // Skewed dates must produce listings that git rev-list gets wrong, which the test
+ // is about; growing dates must not.
+ if skewed {
+ require.Positive(t, overListed)
+ } else {
+ require.Zero(t, overListed)
}
- }
- requireAgree(graphChecker, "graph", pairs)
+ // The entries computed above are stored, so a checker that starts with an empty
+ // in-memory cache gives the same answers from the store.
+ _, stored, err := store.Kind(graphKindName, graphKindVersion).Get(ids[3])
+ require.NoError(t, err)
+ require.True(t, stored, "the graph entry of commit 3 is stored")
- // The entries computed above are stored, so a checker that starts with an empty
- // in-memory cache gives the same answers from the store.
- _, stored, err := store.Kind(graphKindName, graphKindVersion).Get(ids[3])
- require.NoError(t, err)
- require.True(t, stored, "the graph entry of commit 3 is stored")
+ fresh, err := Graph(ctx, repo, reader, store)
+ require.NoError(t, err)
+ for _, p := range pairs[:60] {
+ listed, err := fresh.List(ctx, ids[p.head], []git.ObjectID{ids[p.base]})
+ require.NoError(t, err)
+ require.Equal(t, exactRangeOf(parents, ids, p.base, p.head), rangeSet(listed))
+ }
+ })
+ }
+ }
+}
- fresh, err := Graph(ctx, repo, reader, store)
- require.NoError(t, err)
- requireAgree(fresh, "graph from store", pairs[:60])
- })
+// TestSkewedChainOfTheReview is the history that the review of phase 4b reported: a root R dated
+// 2026-01, A on it dated 2026-02, and ten commits on A dated 2025-06. git rev-list tip..A lists A
+// and R although tip reaches both. A is already on the branch, so its exact range is empty, and a
+// commit C on A has the exact range {C}.
+func TestSkewedChainOfTheReview(t *testing.T) {
+ t.Parallel()
+
+ ctx := testhelper.Context(t)
+ cfg, repoPath, repo, reader := newAncestryEnv(t)
+
+ parents := [][]int{nil, {0}}
+ dates := []int64{1767225600, 1769904000} // 2026-01-01, 2026-02-01
+ for i := 0; i < 10; i++ {
+ parents = append(parents, []int{len(parents) - 1})
+ dates = append(dates, 1748736000+int64(i)) // 2025-06-01
+ }
+ parents = append(parents, []int{1}) // C on A
+ dates = append(dates, 1769904100)
+ ids := writeDatedHistory(t, cfg, repoPath, parents, dates)
+ root, a, tip, c := ids[0], ids[1], ids[11], ids[12]
+
+ listed := strings.Fields(string(gittest.Exec(t, cfg, "-C", repoPath, "rev-list", tip.String()+".."+a.String())))
+ require.ElementsMatch(t, []string{a.String(), root.String()}, listed, "git rev-list no longer shows the skew this test is about")
+
+ graphChecker, err := Graph(ctx, repo, reader, derived.NewStore(repoPath))
+ require.NoError(t, err)
+
+ for name, checker := range map[string]Checker{"git": Git(repo), "graph": graphChecker} {
+ rng, err := revrange.Exact(ctx, checker, tip, a)
+ require.NoError(t, err)
+ require.Empty(t, rng, "%s: A is reachable from tip", name)
+
+ rng, err = revrange.Exact(ctx, checker, tip, c)
+ require.NoError(t, err)
+ require.Equal(t, map[git.ObjectID][]git.ObjectID{c: {a}}, rangeSet(rng), "%s: range of C", name)
}
}
@@ -193,9 +375,13 @@ func TestRangeWithoutCommonAncestor(t *testing.T) {
for name, checker := range map[string]Checker{"git": Git(repo), "graph": graphChecker} {
t.Run(name, func(t *testing.T) {
// Nothing of b's history is reachable from a, so the range is b down to its root.
- rng, err := checker.Range(ctx, a, b)
+ rng, err := revrange.Exact(ctx, checker, a, b)
require.NoError(t, err)
require.Equal(t, map[git.ObjectID][]git.ObjectID{b: nil}, rangeSet(rng))
+
+ bases, err := checker.MergeBases(ctx, a, b)
+ require.NoError(t, err)
+ require.Empty(t, bases)
})
}
}
@@ -206,26 +392,28 @@ func TestNewChoosesCheckerAndFallsBack(t *testing.T) {
ctx := testhelper.Context(t)
logger := testhelper.NewLogger(t)
+ isGraph := func(checker Checker) bool {
+ _, ok := checker.(graphChecker)
+ return ok
+ }
+
t.Run("disabled uses git", func(t *testing.T) {
_, repoPath, repo, reader := newAncestryEnv(t)
- _, isGit := New(ctx, false, repo, reader, derived.NewStore(repoPath), logger).(gitChecker)
- require.True(t, isGit)
+ require.False(t, isGraph(New(ctx, false, repo, reader, derived.NewStore(repoPath), logger)))
})
t.Run("enabled uses graph", func(t *testing.T) {
_, repoPath, repo, reader := newAncestryEnv(t)
- _, isGraph := New(ctx, true, repo, reader, derived.NewStore(repoPath), logger).(graphChecker)
- require.True(t, isGraph)
+ require.True(t, isGraph(New(ctx, true, repo, reader, derived.NewStore(repoPath), logger)))
})
t.Run("shallow repository falls back to git", func(t *testing.T) {
_, repoPath, repo, reader := newAncestryEnv(t)
require.NoError(t, os.WriteFile(filepath.Join(repoPath, "shallow"), nil, 0o600))
- _, isGit := New(ctx, true, repo, reader, derived.NewStore(repoPath), logger).(gitChecker)
- require.True(t, isGit)
+ require.False(t, isGraph(New(ctx, true, repo, reader, derived.NewStore(repoPath), logger)))
})
t.Run("replace refs fall back to git", func(t *testing.T) {
@@ -237,8 +425,7 @@ func TestNewChoosesCheckerAndFallsBack(t *testing.T) {
_, err := Graph(ctx, repo, reader, derived.NewStore(repoPath))
require.Error(t, err)
- _, isGit := New(ctx, true, repo, reader, derived.NewStore(repoPath), logger).(gitChecker)
- require.True(t, isGit)
+ require.False(t, isGraph(New(ctx, true, repo, reader, derived.NewStore(repoPath), logger)))
})
t.Run("missing repository or reader is an error", func(t *testing.T) {
@@ -260,59 +447,3 @@ func rangeSet(commits []RangeCommit) map[git.ObjectID][]git.ObjectID {
}
return set
}
-
-func TestRangeGraphMatchesGit(t *testing.T) {
- t.Parallel()
-
- for _, seed := range []int64{1, 2} {
- t.Run(fmt.Sprintf("seed %d", seed), func(t *testing.T) {
- t.Parallel()
-
- ctx := testhelper.Context(t)
- cfg, repoPath, repo, reader := newAncestryEnv(t)
- rnd := rand.New(rand.NewSource(seed))
-
- // A criss-cross history with a second, unrelated tree on top of it.
- parents := crissCrossHistory(rnd, 160)
- for i := 0; i < 40; i++ {
- if i == 0 {
- parents = append(parents, nil)
- continue
- }
- parents = append(parents, []int{len(parents) - 1})
- }
- ids := writeHistory(t, cfg, repoPath, parents)
-
- graphChecker, err := Graph(ctx, repo, reader, derived.NewStore(repoPath))
- require.NoError(t, err)
- gitChecker := Git(repo)
-
- type pair struct{ base, head git.ObjectID }
- pairs := []pair{{ids[3], ids[4]}, {ids[4], ids[3]}, {ids[3], ids[3]}, {ids[0], ids[159]}, {ids[159], ids[len(ids)-1]}}
- for range 150 {
- pairs = append(pairs, pair{ids[rnd.Intn(len(ids))], ids[rnd.Intn(len(ids))]})
- }
-
- nonEmpty := 0
- for _, p := range pairs {
- want, err := gitChecker.Range(ctx, p.base, p.head)
- require.NoError(t, err)
- got, err := graphChecker.Range(ctx, p.base, p.head)
- require.NoError(t, err)
- require.Equal(t, rangeSet(want), rangeSet(got), "Range(%s, %s)", p.base, p.head)
-
- // The git checker lists what git rev-list lists.
- listed := strings.Fields(string(gittest.Exec(t, cfg, "-C", repoPath, "rev-list", p.base.String()+".."+p.head.String())))
- require.Len(t, want, len(listed))
-
- // A range is empty exactly when head is reachable from base.
- reachable := gittest.NewCommand(t, cfg, "-C", repoPath, "merge-base", "--is-ancestor", p.head.String(), p.base.String()).Run() == nil
- require.Equal(t, reachable, len(want) == 0)
- if len(want) > 0 {
- nonEmpty++
- }
- }
- require.Positive(t, nonEmpty)
- })
- }
-}
diff --git a/internal/graft/rebase/engine.go b/internal/graft/rebase/engine.go
index be44d5b..9da4b33 100644
--- a/internal/graft/rebase/engine.go
+++ b/internal/graft/rebase/engine.go
@@ -1,6 +1,6 @@
-// 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
+// Package rebase decides how a change lands onto a branch and replays its commits. Plan makes the
+// decision from one listing of the range the change adds, made exact when the change diverges (see
+// revrange), 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 rebase
diff --git a/internal/graft/rebase/engine_test.go b/internal/graft/rebase/engine_test.go
index 2a8ada8..7f01755 100644
--- a/internal/graft/rebase/engine_test.go
+++ b/internal/graft/rebase/engine_test.go
@@ -121,16 +121,11 @@ func buildHistories(f *fixture, rng *rand.Rand) (upstream, branch git.ObjectID)
return upTip, brTip
}
-// 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
+// landRebase rebases branch onto upstream the way landing does: 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)
+ plan, err := Plan(ctx, ancestry.Git(repo), upstream, branch)
if err != nil {
return "", err
}
diff --git a/internal/graft/rebase/plan.go b/internal/graft/rebase/plan.go
index 94cc96b..fc17893 100644
--- a/internal/graft/rebase/plan.go
+++ b/internal/graft/rebase/plan.go
@@ -1,10 +1,12 @@
package rebase
import (
+ "context"
"errors"
"fmt"
"github.com/feder-cr/git-ai/internal/git"
+ "github.com/feder-cr/git-ai/internal/git/revrange"
"github.com/feder-cr/git-ai/internal/graft/ancestry"
)
@@ -43,8 +45,42 @@ type LandPlan struct {
parents map[git.ObjectID][]git.ObjectID
}
-// PlanLanding decides how commit lands onto tip from rng, the range tip..commit as
-// ancestry.Checker.Range lists it:
+// Plan decides how commit lands onto tip, with the answers of checker.
+//
+// The listing of the commits that commit adds to tip (checker.List) may hold commits that tip
+// reaches when committer dates are skewed, never fewer than the range (see revrange). Two facts
+// are exact from such a listing, so they cost nothing more:
+//
+// - The listing is empty exactly when the range is: commit is already landed.
+// - tip is a parent of a listed commit exactly when tip is reachable from commit. A listed commit
+// is reachable from commit, so tip is then reachable from commit; and on a path from commit down
+// to tip, the commit right above tip is in the range, so it is listed. That is a fast-forward.
+//
+// Whether the change has merge commits, whether it shares history with tip and which commits a
+// rebase replays need the exact range, so a diverged change has its listing made exact by
+// revrange.Refine first, which checks the bottoms of the listing once without skew.
+func Plan(ctx context.Context, checker ancestry.Checker, tip, commit git.ObjectID) (LandPlan, error) {
+ listed, err := checker.List(ctx, commit, []git.ObjectID{tip})
+ if err != nil {
+ return LandPlan{}, fmt.Errorf("listing the commits of the change: %w", err)
+ }
+
+ plan, err := planLanding(tip, commit, listed)
+ if err != nil || plan.Kind() != LandDiverged {
+ return plan, err
+ }
+
+ rng, err := revrange.Refine(ctx, checker, tip, commit, listed)
+ if err != nil {
+ return LandPlan{}, fmt.Errorf("making the range of the change exact: %w", err)
+ }
+
+ // The exact range is empty when every listed commit was reachable from tip: the commit is
+ // already landed. It cannot be a fast-forward, which the listing would have shown.
+ return planLanding(tip, commit, rng)
+}
+
+// planLanding decides how commit lands onto tip from rng, the exact range tip..commit:
//
// - The range is empty exactly when commit is reachable from tip: LandAlreadyLanded.
// - tip is a parent of a commit of the range exactly when tip is reachable from commit: on a path
@@ -53,8 +89,9 @@ type LandPlan struct {
// - Otherwise LandDiverged.
//
// A non-empty range must contain commit and list every commit once; anything else is an error,
-// because the range does not come from tip..commit.
-func PlanLanding(tip, commit git.ObjectID, rng []ancestry.RangeCommit) (LandPlan, error) {
+// because the range does not come from tip..commit. Only Plan calls it, with a listing for the two
+// facts that a listing gives exactly and with the exact range otherwise.
+func planLanding(tip, commit git.ObjectID, rng []ancestry.RangeCommit) (LandPlan, error) {
if len(rng) == 0 {
return LandPlan{kind: LandAlreadyLanded, commit: commit}, nil
}
diff --git a/internal/graft/rebase/plan_skew_test.go b/internal/graft/rebase/plan_skew_test.go
new file mode 100644
index 0000000..69ce368
--- /dev/null
+++ b/internal/graft/rebase/plan_skew_test.go
@@ -0,0 +1,150 @@
+package rebase
+
+import (
+ "bytes"
+ "context"
+ "fmt"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/feder-cr/git-ai/internal/git"
+ "github.com/feder-cr/git-ai/internal/git/gittest"
+ "github.com/feder-cr/git-ai/internal/graft/ancestry"
+ "github.com/stretchr/testify/require"
+)
+
+// countingChecker counts the questions that a plan asks, each a git process for the git checker.
+type countingChecker struct {
+ ancestry.Checker
+ lists, isAncestors, mergeBases int
+}
+
+func (c *countingChecker) List(ctx context.Context, head git.ObjectID, exclude []git.ObjectID) ([]ancestry.RangeCommit, error) {
+ c.lists++
+ return c.Checker.List(ctx, head, exclude)
+}
+
+func (c *countingChecker) IsAncestor(ctx context.Context, ancestor, descendant git.ObjectID) (bool, error) {
+ c.isAncestors++
+ return c.Checker.IsAncestor(ctx, ancestor, descendant)
+}
+
+func (c *countingChecker) MergeBases(ctx context.Context, a, b git.ObjectID) ([]git.ObjectID, error) {
+ c.mergeBases++
+ return c.Checker.MergeBases(ctx, a, b)
+}
+
+// writeChain writes commits with fast-import: commit i has the parent parents[i] (-1 for a root),
+// the committer date dates[i] and a file of its own, and is reachable as refs/heads/c<i>.
+func writeChain(t *testing.T, f *fixture, parents []int, dates []int64) []git.ObjectID {
+ t.Helper()
+
+ var stream bytes.Buffer
+ for i := range parents {
+ name := fmt.Sprintf("c%d", i)
+ fmt.Fprintf(&stream, "commit refs/heads/%s\nmark :%d\n", name, i+1)
+ fmt.Fprintf(&stream, "committer Tester <[email protected]> %d +0000\n", dates[i])
+ fmt.Fprintf(&stream, "data %d\n%s\n", len(name), name)
+ if parents[i] >= 0 {
+ fmt.Fprintf(&stream, "from :%d\n", parents[i]+1)
+ }
+ fmt.Fprintf(&stream, "M 100644 inline %s\ndata %d\n%s\n\n", name, len(name)+1, name+"\n")
+ }
+ gittest.ExecOpts(t, f.cfg, gittest.ExecConfig{Stdin: &stream}, "-C", f.repoPath, "fast-import", "--quiet")
+
+ ids := make([]git.ObjectID, len(parents))
+ for i := range ids {
+ ids[i] = gittest.ResolveRevision(t, f.cfg, f.repoPath, fmt.Sprintf("refs/heads/c%d", i))
+ }
+ return ids
+}
+
+// TestPlanOfTheReviewChain is the history that the review of phase 4b reported: a root R dated
+// 2026-01, A on it dated 2026-02, and ten commits on A dated 2025-06 that make the tip. git rev-list
+// tip..A lists A and R. Landing A again must find it already landed, and a commit C on A must be
+// rebased alone.
+func TestPlanOfTheReviewChain(t *testing.T) {
+ t.Parallel()
+
+ f := newFixture(t)
+ parents := []int{-1, 0}
+ dates := []int64{1767225600, 1769904000}
+ for i := 0; i < 10; i++ {
+ parents = append(parents, len(parents)-1)
+ dates = append(dates, 1748736000+int64(i))
+ }
+ parents = append(parents, 1)
+ dates = append(dates, 1769904100)
+ ids := writeChain(t, f, parents, dates)
+ root, a, tip, c := ids[0], ids[1], ids[11], ids[12]
+
+ listed := strings.Fields(string(gittest.Exec(t, f.cfg, "-C", f.repoPath, "rev-list", tip.String()+".."+a.String())))
+ require.ElementsMatch(t, []string{a.String(), root.String()}, listed, "git rev-list no longer shows the skew this test is about")
+
+ plan, err := Plan(f.ctx, ancestry.Git(f.repo), tip, a)
+ require.NoError(t, err)
+ require.Equal(t, LandAlreadyLanded, plan.Kind())
+
+ plan, err = Plan(f.ctx, ancestry.Git(f.repo), tip, c)
+ require.NoError(t, err)
+ require.Equal(t, LandDiverged, plan.Kind())
+ todo, err := plan.Replay()
+ require.NoError(t, err)
+ require.Equal(t, []git.ObjectID{c}, todo)
+}
+
+// TestPlanOnALongSkewedHistory measures what a skewed listing costs on a long history: a main line
+// of 2000 commits, the commit A of a change on it, and a tip of ten commits on A dated a year
+// before the main line. git rev-list tip..A then lists A and the whole main line. The plan asks
+// one listing, one check of its only bottom, the merge bases and one listing below them, and
+// nothing that grows with the history.
+func TestPlanOnALongSkewedHistory(t *testing.T) {
+ t.Parallel()
+
+ f := newFixture(t)
+ const mainLine = 2000
+ parents := make([]int, 0, mainLine+13)
+ dates := make([]int64, 0, mainLine+13)
+ for i := 0; i < mainLine; i++ {
+ parents = append(parents, i-1)
+ dates = append(dates, 1767225600+int64(i)*60)
+ }
+ a := len(parents)
+ parents = append(parents, a-1)
+ dates = append(dates, 1767225600+int64(mainLine)*60)
+ for i := 0; i < 10; i++ {
+ parents = append(parents, len(parents)-1)
+ dates = append(dates, 1735689600+int64(i))
+ }
+ tipIndex := len(parents) - 1
+ parents = append(parents, a)
+ dates = append(dates, 1767225600+int64(mainLine+1)*60)
+ ids := writeChain(t, f, parents, dates)
+ tip, change, onA := ids[tipIndex], ids[a], ids[len(ids)-1]
+
+ listed := strings.Fields(string(gittest.Exec(t, f.cfg, "-C", f.repoPath, "rev-list", tip.String()+".."+change.String())))
+ require.Greater(t, len(listed), mainLine, "git rev-list must list the main line for this test to measure anything")
+
+ for _, tc := range []struct {
+ desc string
+ commit git.ObjectID
+ wantKind LandKind
+ }{
+ {desc: "already landed", commit: change, wantKind: LandAlreadyLanded},
+ {desc: "diverged", commit: onA, wantKind: LandDiverged},
+ } {
+ checker := &countingChecker{Checker: ancestry.Git(f.repo)}
+ start := time.Now()
+ plan, err := Plan(f.ctx, checker, tip, tc.commit)
+ elapsed := time.Since(start)
+ require.NoError(t, err)
+ require.Equal(t, tc.wantKind, plan.Kind(), tc.desc)
+
+ require.Equal(t, 2, checker.lists, tc.desc)
+ require.Equal(t, 1, checker.mergeBases, tc.desc)
+ require.LessOrEqual(t, checker.isAncestors, 2, tc.desc)
+ t.Logf("%s: %d listed by git rev-list, %d listings, %d ancestry checks, %d merge-base, %v",
+ tc.desc, len(listed), checker.lists, checker.isAncestors, checker.mergeBases, elapsed)
+ }
+}
diff --git a/internal/graft/rebase/plan_test.go b/internal/graft/rebase/plan_test.go
index 502b662..f8d7f9c 100644
--- a/internal/graft/rebase/plan_test.go
+++ b/internal/graft/rebase/plan_test.go
@@ -2,9 +2,9 @@ package rebase
import (
"bytes"
+ "context"
"fmt"
"math/rand"
- "strings"
"testing"
"github.com/feder-cr/git-ai/internal/git"
@@ -96,7 +96,7 @@ func TestPlanLanding(t *testing.T) {
t.Run(tc.desc, func(t *testing.T) {
t.Parallel()
- plan, err := PlanLanding(tip, commit, tc.rng)
+ plan, err := planLanding(tip, commit, tc.rng)
if tc.wantErr != "" {
require.ErrorContains(t, err, tc.wantErr)
return
@@ -125,7 +125,7 @@ func TestPlanLandingRejectsRangesThatAreNotHistories(t *testing.T) {
t.Parallel()
commit := git.ObjectID("commit")
- plan, err := PlanLanding("tip", commit, []ancestry.RangeCommit{
+ plan, err := planLanding("tip", commit, []ancestry.RangeCommit{
{ID: commit, Parents: []git.ObjectID{"a"}},
{ID: "a", Parents: []git.ObjectID{commit}},
})
@@ -134,7 +134,7 @@ func TestPlanLandingRejectsRangesThatAreNotHistories(t *testing.T) {
_, err = plan.Replay()
require.ErrorContains(t, err, "cycle")
- plan, err = PlanLanding("tip", commit, []ancestry.RangeCommit{
+ plan, err = planLanding("tip", commit, []ancestry.RangeCommit{
{ID: commit, Parents: []git.ObjectID{"base"}},
{ID: "stray", Parents: []git.ObjectID{"base"}},
})
@@ -177,9 +177,33 @@ func forestHistory(rnd *rand.Rand, n int) [][]int {
return parents
}
-// writeForest creates the commits with git fast-import. Commit i has the parents parents[i] and is
-// reachable as refs/heads/c<i>.
-func writeForest(t *testing.T, cfg config.Cfg, repoPath string, parents [][]int) []git.ObjectID {
+// increasingDates returns committer dates that grow with the index of the commit, so that every
+// commit is younger than its parents.
+func increasingDates(n int) []int64 {
+ dates := make([]int64, n)
+ for i := range dates {
+ dates[i] = 1600000000 + int64(i)
+ }
+ return dates
+}
+
+// skewedDates returns increasing dates in which random runs of commits are dated a year before
+// the first commit, as commits written by a client whose clock is behind or whose dates were set
+// explicitly. git rev-list a..b then lists commits that a reaches.
+func skewedDates(rnd *rand.Rand, n int) []int64 {
+ dates := increasingDates(n)
+ for run := 0; run < n/16; run++ {
+ start := rnd.Intn(n)
+ for k := 0; k < 6+rnd.Intn(12) && start+k < n; k++ {
+ dates[start+k] = 1568000000 + int64(k)
+ }
+ }
+ return dates
+}
+
+// writeForest creates the commits with git fast-import. Commit i has the parents parents[i] and the
+// committer date dates[i], and is reachable as refs/heads/c<i>.
+func writeForest(t *testing.T, cfg config.Cfg, repoPath string, parents [][]int, dates []int64) []git.ObjectID {
t.Helper()
var stream bytes.Buffer
@@ -187,7 +211,7 @@ func writeForest(t *testing.T, cfg config.Cfg, repoPath string, parents [][]int)
name := fmt.Sprintf("c%d", i)
fmt.Fprintf(&stream, "commit refs/heads/%s\n", name)
fmt.Fprintf(&stream, "mark :%d\n", i+1)
- fmt.Fprintf(&stream, "committer Tester <[email protected]> %d +0000\n", 1600000000+i)
+ fmt.Fprintf(&stream, "committer Tester <[email protected]> %d +0000\n", dates[i])
fmt.Fprintf(&stream, "data %d\n%s\n", len(name), name)
for j, parent := range list {
if j == 0 {
@@ -208,119 +232,260 @@ func writeForest(t *testing.T, cfg config.Cfg, repoPath string, parents [][]int)
return ids
}
-// phase4aDecision is how landing decided before the plan, one git command per question, in the
-// order of the batch stepper and the engine: already landed, fast-forward, merges in the range,
-// common ancestor, and the todo list of the rebase.
-type phase4aDecision struct {
+// exactDecision is how a commit lands onto a tip, computed from the history itself: the ancestors of
+// both commits, from the parents that the history was written with.
+type exactDecision struct {
kind LandKind
replayErr error
todo []git.ObjectID
}
-func decideAsPhase4a(t *testing.T, cfg config.Cfg, repoPath string, tip, commit git.ObjectID) phase4aDecision {
- t.Helper()
-
- exitCode := func(args ...string) int {
- cmd := gittest.NewCommand(t, cfg, append([]string{"-C", repoPath}, args...)...)
- if err := cmd.Run(); err != nil {
- return cmd.ProcessState.ExitCode()
+// ancestorsOf returns the indexes of the commits reachable from commit x, x included.
+func ancestorsOf(parents [][]int, x int) map[int]bool {
+ seen := map[int]bool{x: true}
+ stack := []int{x}
+ for len(stack) > 0 {
+ c := stack[len(stack)-1]
+ stack = stack[:len(stack)-1]
+ for _, p := range parents[c] {
+ if !seen[p] {
+ seen[p] = true
+ stack = append(stack, p)
+ }
}
- return 0
}
+ return seen
+}
- if exitCode("merge-base", "--is-ancestor", commit.String(), tip.String()) == 0 {
- return phase4aDecision{kind: LandAlreadyLanded}
- }
- if exitCode("merge-base", "--is-ancestor", tip.String(), commit.String()) == 0 {
- return phase4aDecision{kind: LandFastForward}
+func decideExactly(parents [][]int, ids []git.ObjectID, tip, commit int) exactDecision {
+ tipAncestors, commitAncestors := ancestorsOf(parents, tip), ancestorsOf(parents, commit)
+ switch {
+ case tipAncestors[commit]:
+ return exactDecision{kind: LandAlreadyLanded}
+ case commitAncestors[tip]:
+ return exactDecision{kind: LandFastForward}
}
- if out := strings.TrimSpace(string(gittest.Exec(t, cfg, "-C", repoPath, "rev-list", "--merges", tip.String()+".."+commit.String()))); out != "" {
- return phase4aDecision{kind: LandDiverged, replayErr: ErrMergesInRange}
+ inRange := map[int]bool{}
+ shared := false
+ for x := range commitAncestors {
+ if tipAncestors[x] {
+ shared = true
+ } else {
+ inRange[x] = true
+ }
}
-
- switch code := exitCode("merge-base", "--all", tip.String(), commit.String()); code {
- case 0:
- case 1:
- return phase4aDecision{kind: LandDiverged, replayErr: ErrUnrelated}
- default:
- t.Fatalf("merge-base --all exited with %d", code)
+ for x := range inRange {
+ if len(parents[x]) > 1 {
+ return exactDecision{kind: LandDiverged, replayErr: ErrMergesInRange}
+ }
+ }
+ if !shared {
+ return exactDecision{kind: LandDiverged, replayErr: ErrUnrelated}
}
+ // Without merge commits the range is the chain from commit down to the history of tip.
var todo []git.ObjectID
- for _, line := range strings.Fields(string(gittest.Exec(t, cfg, "-C", repoPath,
- "rev-list", "--right-only", "--no-merges", "--topo-order", "--reverse", tip.String()+"..."+commit.String()))) {
- todo = append(todo, git.ObjectID(line))
+ for x := commit; inRange[x]; x = parents[x][0] {
+ todo = append([]git.ObjectID{ids[x]}, todo...)
}
-
- return phase4aDecision{kind: LandDiverged, todo: todo}
+ return exactDecision{kind: LandDiverged, todo: todo}
}
-// TestPlanLandingMatchesPhase4aDecisions compares, on seeded random forests, the plan made from one
-// range listing with the decisions landing made before it with one git command per question, for
-// the git and the graph checker.
-func TestPlanLandingMatchesPhase4aDecisions(t *testing.T) {
+// TestPlanMatchesTheExactHistory compares, on seeded random forests, the plan with the decision
+// computed from the history itself, for the git and the graph checker, with committer dates that
+// grow along the history and with skewed ones. The kinds are also checked against git merge-base
+// --is-ancestor, so that the history the test computes from is the one git sees.
+func TestPlanMatchesTheExactHistory(t *testing.T) {
t.Parallel()
- for _, seed := range []int64{1, 2, 3} {
- t.Run(fmt.Sprintf("seed %d", seed), func(t *testing.T) {
- t.Parallel()
-
- f := newFixture(t)
- rnd := rand.New(rand.NewSource(seed))
- ids := writeForest(t, f.cfg, f.repoPath, forestHistory(rnd, 160))
+ for _, skewed := range []bool{false, true} {
+ for _, seed := range []int64{1, 2, 3} {
+ t.Run(fmt.Sprintf("skewed %v seed %d", skewed, seed), func(t *testing.T) {
+ t.Parallel()
+
+ f := newFixture(t)
+ rnd := rand.New(rand.NewSource(seed))
+ parents := forestHistory(rnd, 160)
+ dates := increasingDates(len(parents))
+ if skewed {
+ dates = skewedDates(rnd, len(parents))
+ }
+ ids := writeForest(t, f.cfg, f.repoPath, parents, dates)
+ index := make(map[git.ObjectID]int, len(ids))
+ for i, id := range ids {
+ index[id] = i
+ }
- catfileCache := catfile.NewCache(f.cfg)
- t.Cleanup(catfileCache.Stop)
- reader, cancel, err := catfileCache.ObjectReader(f.ctx, f.repo)
- require.NoError(t, err)
- t.Cleanup(cancel)
+ catfileCache := catfile.NewCache(f.cfg)
+ t.Cleanup(catfileCache.Stop)
+ reader, cancel, err := catfileCache.ObjectReader(f.ctx, f.repo)
+ require.NoError(t, err)
+ t.Cleanup(cancel)
- graphChecker, err := ancestry.Graph(f.ctx, f.repo, reader, derived.NewStore(f.repoPath))
- require.NoError(t, err)
+ graphChecker, err := ancestry.Graph(f.ctx, f.repo, reader, derived.NewStore(f.repoPath))
+ require.NoError(t, err)
- checkers := map[string]ancestry.Checker{"git": ancestry.Git(f.repo), "graph": graphChecker}
+ checkers := map[string]ancestry.Checker{"git": ancestry.Git(f.repo), "graph": graphChecker}
- type pair struct{ tip, commit git.ObjectID }
- pairs := []pair{{ids[3], ids[4]}, {ids[4], ids[3]}, {ids[3], ids[3]}, {ids[0], ids[len(ids)-1]}}
- for range 200 {
- pairs = append(pairs, pair{ids[rnd.Intn(len(ids))], ids[rnd.Intn(len(ids))]})
- }
+ isAncestor := func(a, b git.ObjectID) bool {
+ cmd := gittest.NewCommand(t, f.cfg, "-C", f.repoPath, "merge-base", "--is-ancestor", a.String(), b.String())
+ if err := cmd.Run(); err != nil {
+ require.Equal(t, 1, cmd.ProcessState.ExitCode())
+ return false
+ }
+ return true
+ }
- seen := map[string]int{}
- for _, p := range pairs {
- want := decideAsPhase4a(t, f.cfg, f.repoPath, p.tip, p.commit)
+ type pair struct{ tip, commit int }
+ pairs := []pair{{3, 4}, {4, 3}, {3, 3}, {0, len(ids) - 1}}
+ for range 200 {
+ pairs = append(pairs, pair{rnd.Intn(len(ids)), rnd.Intn(len(ids))})
+ }
- for name, checker := range checkers {
- rng, err := checker.Range(f.ctx, p.tip, p.commit)
- require.NoError(t, err)
+ seen := map[string]int{}
+ overListed := 0
+ for _, p := range pairs {
+ tip, commit := ids[p.tip], ids[p.commit]
+ want := decideExactly(parents, ids, p.tip, p.commit)
+ require.Equal(t, want.kind == LandAlreadyLanded, isAncestor(commit, tip))
+ require.Equal(t, want.kind == LandFastForward, !isAncestor(commit, tip) && isAncestor(tip, commit))
- plan, err := PlanLanding(p.tip, p.commit, rng)
+ listed, err := checkers["git"].List(f.ctx, commit, []git.ObjectID{tip})
require.NoError(t, err)
- require.Equal(t, want.kind, plan.Kind(), "%s: kind of %s onto %s", name, p.commit, p.tip)
+ tipAncestors := ancestorsOf(parents, p.tip)
+ for _, c := range listed {
+ if tipAncestors[index[c.ID]] {
+ overListed++
+ break
+ }
+ }
- if want.kind != LandDiverged {
- continue
+ for name, checker := range checkers {
+ plan, err := Plan(f.ctx, checker, tip, commit)
+ require.NoError(t, err)
+ require.Equal(t, want.kind, plan.Kind(), "%s: kind of c%d onto c%d", name, p.commit, p.tip)
+
+ if want.kind != LandDiverged {
+ continue
+ }
+
+ todo, err := plan.Replay()
+ if want.replayErr != nil {
+ require.ErrorIs(t, err, want.replayErr, "%s: replay of c%d onto c%d", name, p.commit, p.tip)
+ continue
+ }
+ require.NoError(t, err)
+ require.Equal(t, want.todo, todo, "%s: todo of c%d onto c%d", name, p.commit, p.tip)
}
- todo, err := plan.Replay()
+ label := fmt.Sprint(want.kind)
if want.replayErr != nil {
- require.ErrorIs(t, err, want.replayErr, "%s: replay of %s onto %s", name, p.commit, p.tip)
- continue
+ label += want.replayErr.Error()
}
- require.NoError(t, err)
- require.Equal(t, want.todo, todo, "%s: todo of %s onto %s", name, p.commit, p.tip)
+ seen[label]++
}
+ // The forests must exercise every decision, and the skewed ones listings that git
+ // rev-list gets wrong.
+ require.Len(t, seen, 5, "decisions seen: %v", seen)
+ if skewed {
+ require.NotZero(t, overListed, "no listing of git rev-list held a commit outside of its range")
+ } else {
+ require.Zero(t, overListed)
+ }
+ })
+ }
+ }
+}
+
+// overListingChecker answers from a history held in memory. Its List adds to the exact range
+// every commit that an excluded commit reaches and head reaches too, the most that git rev-list can
+// list under committer-date skew.
+type overListingChecker struct {
+ parents [][]int
+ ids []git.ObjectID
+ index map[git.ObjectID]int
+}
+
+func (c overListingChecker) List(_ context.Context, head git.ObjectID, _ []git.ObjectID) ([]ancestry.RangeCommit, error) {
+ var commits []ancestry.RangeCommit
+ for x := range ancestorsOf(c.parents, c.index[head]) {
+ var parents []git.ObjectID
+ for _, p := range c.parents[x] {
+ parents = append(parents, c.ids[p])
+ }
+ commits = append(commits, ancestry.RangeCommit{ID: c.ids[x], Parents: parents})
+ }
+ return commits, nil
+}
+
+func (c overListingChecker) IsAncestor(_ context.Context, ancestor, descendant git.ObjectID) (bool, error) {
+ return ancestorsOf(c.parents, c.index[descendant])[c.index[ancestor]], nil
+}
+
+func (c overListingChecker) MergeBases(_ context.Context, a, b git.ObjectID) ([]git.ObjectID, error) {
+ aAncestors, bAncestors := ancestorsOf(c.parents, c.index[a]), ancestorsOf(c.parents, c.index[b])
+ var bases []git.ObjectID
+ for x := range aAncestors {
+ if !bAncestors[x] {
+ continue
+ }
+ best := true
+ for y := range aAncestors {
+ if y != x && bAncestors[y] && ancestorsOf(c.parents, y)[x] {
+ best = false
+ break
+ }
+ }
+ if best {
+ bases = append(bases, c.ids[x])
+ }
+ }
+ return bases, nil
+}
+
+// TestPlanWithAListingOfTheWholeHistory plans every pair of random forests with a checker whose
+// listing holds the whole history of the commit, the shared part included: the plan must still
+// match the exact decision.
+func TestPlanWithAListingOfTheWholeHistory(t *testing.T) {
+ t.Parallel()
+
+ ctx := context.Background()
+ seen := map[string]int{}
+ for _, seed := range []int64{1, 2, 3} {
+ rnd := rand.New(rand.NewSource(seed))
+ parents := forestHistory(rnd, 80)
+ ids := make([]git.ObjectID, len(parents))
+ index := make(map[git.ObjectID]int, len(parents))
+ for i := range ids {
+ ids[i] = git.ObjectID(fmt.Sprintf("c%02d", i))
+ index[ids[i]] = i
+ }
+ checker := overListingChecker{parents: parents, ids: ids, index: index}
+
+ for tip := range ids {
+ for commit := range ids {
+ want := decideExactly(parents, ids, tip, commit)
+
+ plan, err := Plan(ctx, checker, ids[tip], ids[commit])
+ require.NoError(t, err)
+ require.Equal(t, want.kind, plan.Kind(), "seed %d: kind of c%d onto c%d", seed, commit, tip)
+
label := fmt.Sprint(want.kind)
- if want.replayErr != nil {
- label += want.replayErr.Error()
+ if want.kind == LandDiverged {
+ todo, err := plan.Replay()
+ if want.replayErr != nil {
+ require.ErrorIs(t, err, want.replayErr, "seed %d: replay of c%d onto c%d", seed, commit, tip)
+ label += want.replayErr.Error()
+ } else {
+ require.NoError(t, err)
+ require.Equal(t, want.todo, todo, "seed %d: todo of c%d onto c%d", seed, commit, tip)
+ }
}
seen[label]++
}
-
- // The forests must exercise every decision.
- require.Len(t, seen, 5, "decisions seen: %v", seen)
- })
+ }
}
+ require.Len(t, seen, 5, "decisions seen: %v", seen)
}
diff --git a/internal/graft/rebase/rebase_spec_test.go b/internal/graft/rebase/rebase_spec_test.go
index 314693c..4524c10 100644
--- a/internal/graft/rebase/rebase_spec_test.go
+++ b/internal/graft/rebase/rebase_spec_test.go
@@ -140,8 +140,9 @@ func TestSpecRebaseConflictReturnsRebaseConflictError(t *testing.T) {
// TestSpecRebaseSkipsCherryPickedCommits: a branch commit whose change is
// 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.)
+// result is upstream itself. (Landing reapplies cherry-picks, see computeTip in
+// internal/gitaly/service/operations/land_attempt.go; the commit is dropped as empty, not by
+// patch ID.)
func TestSpecRebaseSkipsCherryPickedCommits(t *testing.T) {
ctx, cfg, repoPath, repo := specSetup(t)
diff --git a/internal/graft/rebase/zz_plan_spec_test.go b/internal/graft/rebase/zz_plan_spec_test.go
index bbd2110..471fe09 100644
--- a/internal/graft/rebase/zz_plan_spec_test.go
+++ b/internal/graft/rebase/zz_plan_spec_test.go
@@ -15,11 +15,11 @@ func TestSpecEmptyRangeIsAlreadyLanded(t *testing.T) {
tip, commit := git.ObjectID("tip"), git.ObjectID("commit")
- plan, err := PlanLanding(tip, commit, nil)
+ plan, err := planLanding(tip, commit, nil)
require.NoError(t, err)
require.Equal(t, LandAlreadyLanded, plan.Kind())
- plan, err = PlanLanding(tip, commit, []ancestry.RangeCommit{})
+ plan, err = planLanding(tip, commit, []ancestry.RangeCommit{})
require.NoError(t, err)
require.Equal(t, LandAlreadyLanded, plan.Kind())
}
@@ -33,7 +33,7 @@ func TestSpecTipAsParentIsFastForward(t *testing.T) {
{ID: commit, Parents: []git.ObjectID{"tip"}},
}
- plan, err := PlanLanding(tip, commit, rng)
+ plan, err := planLanding(tip, commit, rng)
require.NoError(t, err)
require.Equal(t, LandFastForward, plan.Kind())
}
@@ -49,7 +49,7 @@ func TestSpecMergeWithTipParentIsFastForward(t *testing.T) {
{ID: "c2", Parents: []git.ObjectID{"tip"}},
}
- plan, err := PlanLanding(tip, commit, rng)
+ plan, err := planLanding(tip, commit, rng)
require.NoError(t, err)
require.Equal(t, LandFastForward, plan.Kind())
}
@@ -64,7 +64,7 @@ func TestSpecUnmergedRangeIsDiverged(t *testing.T) {
{ID: "c1", Parents: []git.ObjectID{"base"}},
}
- plan, err := PlanLanding(tip, commit, rng)
+ plan, err := planLanding(tip, commit, rng)
require.NoError(t, err)
require.Equal(t, LandDiverged, plan.Kind())
}
@@ -81,7 +81,7 @@ func TestSpecMergeInDivergedRangeFails(t *testing.T) {
{ID: "c1", Parents: []git.ObjectID{"base"}},
{ID: "c2", Parents: []git.ObjectID{"base"}},
}
- plan, err := PlanLanding(tip, commit, mergeOnly)
+ plan, err := planLanding(tip, commit, mergeOnly)
require.NoError(t, err)
require.Equal(t, LandDiverged, plan.Kind())
_, err = plan.Replay()
@@ -92,7 +92,7 @@ func TestSpecMergeInDivergedRangeFails(t *testing.T) {
{ID: "c1", Parents: []git.ObjectID{"base"}},
{ID: "c2"},
}
- plan, err = PlanLanding(tip, commit, mergeAndRoot)
+ plan, err = planLanding(tip, commit, mergeAndRoot)
require.NoError(t, err)
_, err = plan.Replay()
require.ErrorIs(t, err, ErrMergesInRange)
@@ -108,7 +108,7 @@ func TestSpecRootInDivergedRangeIsUnrelated(t *testing.T) {
{ID: "c1"},
}
- plan, err := PlanLanding(tip, commit, rng)
+ plan, err := planLanding(tip, commit, rng)
require.NoError(t, err)
require.Equal(t, LandDiverged, plan.Kind())
_, err = plan.Replay()
@@ -134,7 +134,7 @@ func TestSpecReplayOrderIndependentOldestFirst(t *testing.T) {
}
for _, rng := range [][]ancestry.RangeCommit{inOrder, shuffled} {
- plan, err := PlanLanding(tip, commit, rng)
+ plan, err := planLanding(tip, commit, rng)
require.NoError(t, err)
todo, err := plan.Replay()
require.NoError(t, err)
@@ -148,7 +148,7 @@ func TestSpecReplayRejectsNonDivergedPlan(t *testing.T) {
tip, commit := git.ObjectID("tip"), git.ObjectID("commit")
- landed, err := PlanLanding(tip, commit, nil)
+ landed, err := planLanding(tip, commit, nil)
require.NoError(t, err)
_, err = landed.Replay()
require.Error(t, err)
@@ -156,7 +156,7 @@ func TestSpecReplayRejectsNonDivergedPlan(t *testing.T) {
fastForward := []ancestry.RangeCommit{
{ID: commit, Parents: []git.ObjectID{"tip"}},
}
- ff, err := PlanLanding(tip, commit, fastForward)
+ ff, err := planLanding(tip, commit, fastForward)
require.NoError(t, err)
require.Equal(t, LandFastForward, ff.Kind())
_, err = ff.Replay()
@@ -172,14 +172,14 @@ func TestSpecPlanLandingRejectsBadRange(t *testing.T) {
missingCommit := []ancestry.RangeCommit{
{ID: "c1", Parents: []git.ObjectID{"base"}},
}
- _, err := PlanLanding(tip, commit, missingCommit)
+ _, err := planLanding(tip, commit, missingCommit)
require.Error(t, err)
duplicated := []ancestry.RangeCommit{
{ID: commit, Parents: []git.ObjectID{"base"}},
{ID: commit, Parents: []git.ObjectID{"base"}},
}
- _, err = PlanLanding(tip, commit, duplicated)
+ _, err = planLanding(tip, commit, duplicated)
require.Error(t, err)
}
@@ -192,7 +192,7 @@ func TestSpecSingleCommitReplaysItself(t *testing.T) {
{ID: commit, Parents: []git.ObjectID{"base"}},
}
- plan, err := PlanLanding(tip, commit, rng)
+ plan, err := planLanding(tip, commit, rng)
require.NoError(t, err)
require.Equal(t, LandDiverged, plan.Kind())
todo, err := plan.Replay()