Commit.MergeBase rebuilds the ancestor index per call: O(N × history) when mapping many branches onto one trunk

Đang mở
#2,353 2 bình luận 0 reaction 0 người được giao Xem trên GitHub

Maintainer thường phản hồi trong vòng 3 ngày

@nexus-cw đang làm issue này rồi.

Từ ngày 5/9/2026.

Đánh giá

Độ khó
5/5
Thời gian dự kiến
Hơn một tuần
Mức phù hợp với người mới
38/100
Loại issue
Tính năng
Độ rõ ràng
Khá rõ ràng
Mức độ hoạt động
Sôi nổi
Công nghệ
git, go

Hướng nghiên cứu

Bắt đầu trong plumbing/object/merge_base.go, đặc biệt là MergeBase và ancestorsIndex, rồi so sánh chúng với cách tiếp cận tổ tiên dùng chung trong trình tái hiện main.go. Xác định một API có thể tái sử dụng hoặc API batch, bảo toàn các kết quả và hành vi merge-base hiện có. Chạy phép so sánh 1.000 branch được cung cấp và xác nhận rằng các kết quả vẫn giống hệt nhau, đồng thời lịch sử trunk dùng chung không bị xây dựng lại cho mỗi lần gọi.

Do mô hình lập chỉ mục viết ra từ nội dung của issue.

Mô tả

What happened

Commit.MergeBase rebuilds an ancestor index on every call, so computing merge bases for N branches against one trunk re-walks the trunk N times — O(N × history). There is no way to amortise the shared side.

This is not a correctness bug; the results are right. It is a missing amortisation path for a common shape: "map many branches onto one mainline", which any forge, CI, or VCS tool built on go-git ends up doing.

Measured

Fixture: bare repo, 3000-commit trunk, 1000 branches each forked at a random trunk commit with 2 commits of its own.

branches: 1000
pairwise Commit.MergeBase : 1m10.143s
shared ancestor set       : 156ms
speedup                   : 449.4x
results differing         : 0 / 1000

Both approaches return identical merge bases for all 1000 branches.

Cause

plumbing/object/merge_base.go → ancestorsIndex(older, newer) builds a full BFS index of the newer commit's history per call:

newerHistory, err := ancestorsIndex(older, newer)

When newer is a branch forked off trunk, that index contains the whole trunk below the fork point — recomputed for every branch.

Reproducer

Standalone, go-git only:

main.go
package main

import (
	"fmt"
	"os"
	"time"

	"github.com/go-git/go-git/v5"
	"github.com/go-git/go-git/v5/plumbing"
	"github.com/go-git/go-git/v5/plumbing/object"
	"github.com/go-git/go-git/v5/plumbing/storer"
)

func main() {
	r, _ := git.PlainOpen(os.Args[1])
	trunk, _ := r.Reference(plumbing.ReferenceName("refs/heads/main"), true)
	trunkC, _ := r.CommitObject(trunk.Hash())

	var heads []*object.Commit
	it, _ := r.References()
	_ = it.ForEach(func(ref *plumbing.Reference) error {
		if ref.Type() != plumbing.HashReference || ref.Name() == trunk.Name() || !ref.Name().IsBranch() {
			return nil
		}
		if c, err := r.CommitObject(ref.Hash()); err == nil {
			heads = append(heads, c)
		}
		return nil
	})

	// (a) today
	t0 := time.Now()
	a := make([]string, 0, len(heads))
	for _, h := range heads {
		bases, err := h.MergeBase(trunkC)
		if err != nil {
			panic(err)
		}
		if len(bases) > 0 {
			a = append(a, bases[0].Hash.String())
		} else {
			a = append(a, "")
		}
	}
	pairwise := time.Since(t0)

	// (b) trunk ancestry once, then a short walk per branch
	t0 = time.Now()
	set := map[plumbing.Hash]struct{}{}
	_ = object.NewCommitPreorderIter(trunkC, nil, nil).
		ForEach(func(c *object.Commit) error { set[c.Hash] = struct{}{}; return nil })
	b := make([]string, 0, len(heads))
	for _, h := range heads {
		var found string
		_ = object.NewCommitIterCTime(h, nil, nil).ForEach(func(c *object.Commit) error {
			if _, ok := set[c.Hash]; ok {
				found = c.Hash.String()
				return storer.ErrStop
			}
			return nil
		})
		b = append(b, found)
	}
	shared := time.Since(t0)

	diff := 0
	for i := range a {
		if a[i] != b[i] {
			diff++
		}
	}
	fmt.Printf("branches: %d\npairwise: %v\nshared: %v\nspeedup: %.1fx\ndiffering: %d/%d\n",
		len(heads), pairwise, shared, float64(pairwise)/float64(shared), diff, len(a))
}

The fixture is generated with git fast-import; happy to attach that script if useful.

Possible direction

A way to reuse the expensive side across calls would cover this without touching existing behaviour — for example a batch entry point:

func (c *Commit) MergeBaseMany(others []*Commit) ([][]*Commit, error)

or exporting a reusable ancestor index that MergeBase itself consumes.

Note the workaround above walks in committer-time-descending order via NewCommitIterCTime, which is the same ordering MergeBase already sorts by (sortByCommitDateDesc), so the first commit found in the set is the most recent common ancestor. It carries the same clock-skew caveat MergeBase has today, and it does not compute Independents for the multi-base case — so it is a fast path for the "one trunk, many branches" shape rather than a drop-in replacement.

This may also be adjacent to #2350 ("ObjectsWithRef walks the object graph once per want"), which is the same walk-once-per-item shape in a different place.

Environment
  • go-git v5.19.2 (current v5; main/v6-alpha carries the same algorithm, only errors.Is cosmetics)
  • Go 1.26.3, Linux amd64
Ngôn ngữ chính
Go
Star
7.9k
Fork
1.1k
Merge trung bình
4 ngày 19 giờ
Pull request đã merge (30 ngày)
34

Chuẩn bị môi trường

Bắt đầu từ đâu

  1. Đọc hết issue, rồi đọc hướng dẫn đóng góp của dự án.
  2. Bình luận trên issue rằng bạn sẽ nhận — tránh hai người làm cùng một việc.
  3. Fork repository và làm thay đổi trên một nhánh.
  4. Mở pull request có tham chiếu số hiệu của issue.

Issue khác của go-git/go-git

Tất cả issue của go-git/go-git

Issue tương tự

Thêm issue về Go

Nhận issue mới trong hộp thư của bạn

Bản tóm tắt ngắn những issue GitHub phù hợp với người mới.