From 082820cbd43d3ddc2b88003e6df084759683cc78 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=A7=D1=83=D0=BA=D0=B0=D0=BB=D0=B8=D0=BD=20=D0=92=D0=B0?= =?UTF-8?q?=D0=BB=D0=B5=D1=80=D0=B8=D0=B9?= Date: Fri, 16 Oct 2026 09:42:31 +0300 Subject: [PATCH 01/35] refs: parse packed-refs once while the file is unchanged --- internal/gitcore/refs/bench_test.go | 32 +++ internal/gitcore/refs/packed.go | 65 +++++- internal/gitcore/refs/packedcache_test.go | 243 ++++++++++++++++++++++ internal/gitcore/refs/store.go | 1 + 4 files changed, 340 insertions(+), 1 deletion(-) create mode 100644 internal/gitcore/refs/packedcache_test.go diff --git a/internal/gitcore/refs/bench_test.go b/internal/gitcore/refs/bench_test.go index 2250d38b..e88979b8 100644 --- a/internal/gitcore/refs/bench_test.go +++ b/internal/gitcore/refs/bench_test.go @@ -2,8 +2,11 @@ package refs import ( "fmt" + "os" + "path/filepath" "strings" "testing" + "time" ) func benchmarkPackedRefs(count int) []byte { @@ -55,3 +58,32 @@ func BenchmarkAll(b *testing.B) { } } } + +func BenchmarkLookupOfAPackedRef(b *testing.B) { + dir := b.TempDir() + if err := os.WriteFile(filepath.Join(dir, "HEAD"), []byte("ref: refs/heads/main\n"), 0o666); err != nil { + b.Fatalf("WriteFile returned error %v", err) + } + if err := os.MkdirAll(filepath.Join(dir, "refs"), 0o777); err != nil { + b.Fatalf("MkdirAll returned error %v", err) + } + packed := filepath.Join(dir, packedRefsFile) + if err := os.WriteFile(packed, benchmarkPackedRefs(1000), 0o666); err != nil { + b.Fatalf("WriteFile returned error %v", err) + } + settled := time.Now().Add(-time.Hour) + if err := os.Chtimes(packed, settled, settled); err != nil { + b.Fatalf("Chtimes returned error %v", err) + } + store, err := Open(Options{GitDir: dir}) + if err != nil { + b.Fatalf("Open returned error %v", err) + } + defer func() { _ = store.Close() }() + name := RemoteBranchName("origin", "branch-0500") + for b.Loop() { + if _, err := store.Lookup(name); err != nil { + b.Fatalf("Lookup returned error %v", err) + } + } +} diff --git a/internal/gitcore/refs/packed.go b/internal/gitcore/refs/packed.go index 5ee2aacd..761ab9c9 100644 --- a/internal/gitcore/refs/packed.go +++ b/internal/gitcore/refs/packed.go @@ -6,6 +6,8 @@ import ( "fmt" "slices" "strings" + "sync" + "time" "github.com/oops1/gogit/internal/gitcore/hash" ) @@ -46,15 +48,76 @@ func (p *packedSnapshot) hasPrefix(prefix string) bool { return false } +const packedCacheSettle = 2 * time.Second + +var ( + parsePackedSnapshot = parsePackedRefs + packedClock = time.Now +) + +type packedStamp struct { + size int64 + modTime time.Time +} + +type packedCache struct { + mu sync.Mutex + stamp packedStamp + snapshot *packedSnapshot +} + +func (c *packedCache) lookup(stamp packedStamp) *packedSnapshot { + c.mu.Lock() + defer c.mu.Unlock() + if c.snapshot != nil && c.stamp.size == stamp.size && c.stamp.modTime.Equal(stamp.modTime) { + return c.snapshot + } + return nil +} + +func (c *packedCache) remember(stamp packedStamp, snapshot *packedSnapshot) { + c.mu.Lock() + defer c.mu.Unlock() + c.stamp, c.snapshot = stamp, snapshot +} + +func (c *packedCache) forget() { + c.remember(packedStamp{}, nil) +} + +func (s *Store) packedStamp() (packedStamp, bool) { + info, err := fsLstat(s.common.root, packedRefsFile) + if err != nil || info.IsDir() { + return packedStamp{}, false + } + return packedStamp{size: info.Size(), modTime: info.ModTime()}, true +} + func (s *Store) loadPacked() (*packedSnapshot, error) { + stamp, present := s.packedStamp() + if !present { + s.packed.forget() + return &packedSnapshot{}, nil + } + if cached := s.packed.lookup(stamp); cached != nil { + return cached, nil + } data, err := s.common.read(packedRefsFile) if errors.Is(err, ErrNotFound) { + s.packed.forget() return &packedSnapshot{}, nil } if err != nil { return nil, err } - return parsePackedRefs(data) + snapshot, err := parsePackedSnapshot(data) + if err != nil { + return nil, err + } + if packedClock().Sub(stamp.modTime) >= packedCacheSettle { + s.packed.remember(stamp, snapshot) + } + return snapshot, nil } func parsePackedRefs(data []byte) (*packedSnapshot, error) { diff --git a/internal/gitcore/refs/packedcache_test.go b/internal/gitcore/refs/packedcache_test.go new file mode 100644 index 00000000..9dbab235 --- /dev/null +++ b/internal/gitcore/refs/packedcache_test.go @@ -0,0 +1,243 @@ +package refs + +import ( + "errors" + "io/fs" + "os" + "path/filepath" + "testing" + "time" + + "github.com/oops1/gogit/internal/gitcore/hash" +) + +const packedCacheFile = packedHeaderPlain + + "1111111111111111111111111111111111111111 refs/heads/main\n" + + "2222222222222222222222222222222222222222 refs/heads/feature\n" + +func countPackedParses(t *testing.T) *int { + t.Helper() + parses := new(int) + previous := parsePackedSnapshot + parsePackedSnapshot = func(data []byte) (*packedSnapshot, error) { + *parses++ + return previous(data) + } + t.Cleanup(func() { parsePackedSnapshot = previous }) + return parses +} + +func agePackedFile(t *testing.T, dir string, age time.Duration) { + t.Helper() + when := time.Now().Add(-age) + if err := os.Chtimes(filepath.Join(dir, packedRefsFile), when, when); err != nil { + t.Fatalf("Chtimes returned error %v", err) + } +} + +func TestLookupParsesAnUnchangedPackedRefsFileOnce(t *testing.T) { + dir := newGitDir(t) + writeAt(t, dir, packedRefsFile, packedCacheFile) + agePackedFile(t, dir, time.Hour) + store := openStore(t, dir) + parses := countPackedParses(t) + + for range 100 { + if _, err := store.Lookup(BranchName("main")); err != nil { + t.Fatalf("Lookup returned error %v", err) + } + if _, err := store.Lookup(BranchName("missing")); !errors.Is(err, ErrNotFound) { + t.Fatalf("Lookup of a missing reference returned %v", err) + } + } + + if *parses != 1 { + t.Fatalf("packed-refs was parsed %d times, want once", *parses) + } +} + +func TestLookupReadsAChangedPackedRefsFileAgain(t *testing.T) { + dir := newGitDir(t) + writeAt(t, dir, packedRefsFile, packedCacheFile) + agePackedFile(t, dir, time.Hour) + store := openStore(t, dir) + parses := countPackedParses(t) + if _, err := store.Lookup(BranchName("main")); err != nil { + t.Fatalf("Lookup returned error %v", err) + } + + writeAt(t, dir, packedRefsFile, packedCacheFile+"3333333333333333333333333333333333333333 refs/heads/extra\n") + agePackedFile(t, dir, time.Hour) + ref, err := store.Lookup(BranchName("extra")) + + if err != nil || ref.Target != oidFrom(t, "3333333333333333333333333333333333333333") { + t.Fatalf("Lookup of a reference added to packed-refs returned %v, %v", ref, err) + } + if *parses != 2 { + t.Fatalf("packed-refs was parsed %d times, want twice", *parses) + } +} + +func TestLookupReadsAChangedPackedRefsFileOfTheSameSizeAgain(t *testing.T) { + dir := newGitDir(t) + writeAt(t, dir, packedRefsFile, packedCacheFile) + agePackedFile(t, dir, time.Hour) + store := openStore(t, dir) + if _, err := store.Lookup(BranchName("main")); err != nil { + t.Fatalf("Lookup returned error %v", err) + } + + writeAt(t, dir, packedRefsFile, packedHeaderPlain+ + "4444444444444444444444444444444444444444 refs/heads/main\n"+ + "2222222222222222222222222222222222222222 refs/heads/feature\n") + agePackedFile(t, dir, 30*time.Minute) + ref, err := store.Lookup(BranchName("main")) + + if err != nil || ref.Target != oidFrom(t, "4444444444444444444444444444444444444444") { + t.Fatalf("Lookup after a same-size rewrite returned %v, %v", ref, err) + } +} + +func TestLookupDoesNotTrustAPackedRefsFileWrittenJustNow(t *testing.T) { + dir := newGitDir(t) + writeAt(t, dir, packedRefsFile, packedCacheFile) + store := openStore(t, dir) + parses := countPackedParses(t) + + for range 3 { + if _, err := store.Lookup(BranchName("main")); err != nil { + t.Fatalf("Lookup returned error %v", err) + } + } + + if *parses != 3 { + t.Fatalf("packed-refs was parsed %d times, want every time while the file is fresh", *parses) + } +} + +func TestLookupTrustsAPackedRefsFileOnceItHasSettled(t *testing.T) { + dir := newGitDir(t) + writeAt(t, dir, packedRefsFile, packedCacheFile) + store := openStore(t, dir) + parses := countPackedParses(t) + info, err := os.Lstat(filepath.Join(dir, packedRefsFile)) + if err != nil { + t.Fatalf("Lstat returned error %v", err) + } + previous := packedClock + packedClock = func() time.Time { return info.ModTime().Add(packedCacheSettle) } + t.Cleanup(func() { packedClock = previous }) + + for range 3 { + if _, err := store.Lookup(BranchName("main")); err != nil { + t.Fatalf("Lookup returned error %v", err) + } + } + + if *parses != 1 { + t.Fatalf("packed-refs was parsed %d times, want once after it settled", *parses) + } +} + +func TestLookupForgetsAPackedRefsFileThatWasRemoved(t *testing.T) { + dir := newGitDir(t) + writeAt(t, dir, packedRefsFile, packedCacheFile) + agePackedFile(t, dir, time.Hour) + store := openStore(t, dir) + if _, err := store.Lookup(BranchName("main")); err != nil { + t.Fatalf("Lookup returned error %v", err) + } + + if err := os.Remove(filepath.Join(dir, packedRefsFile)); err != nil { + t.Fatalf("Remove returned error %v", err) + } + + if _, err := store.Lookup(BranchName("main")); !errors.Is(err, ErrNotFound) { + t.Fatalf("Lookup after removing packed-refs returned %v, want ErrNotFound", err) + } +} + +func TestLookupForgetsAPackedRefsFileThatVanishesBeforeItIsRead(t *testing.T) { + dir := newGitDir(t) + writeAt(t, dir, packedRefsFile, packedCacheFile) + agePackedFile(t, dir, time.Hour) + store := openStore(t, dir) + if _, err := store.Lookup(BranchName("main")); err != nil { + t.Fatalf("Lookup returned error %v", err) + } + writeAt(t, dir, packedRefsFile, packedCacheFile+"3333333333333333333333333333333333333333 refs/heads/extra\n") + statCalls := 0 + previous := fsLstat + fsLstat = func(root *os.Root, name string) (fs.FileInfo, error) { + if filepath.ToSlash(name) == packedRefsFile { + statCalls++ + if statCalls > 1 { + return nil, os.ErrNotExist + } + } + return previous(root, name) + } + t.Cleanup(func() { fsLstat = previous }) + + snapshot, err := store.loadPacked() + + if err != nil || len(snapshot.refs) != 0 { + t.Fatalf("loadPacked of a file that vanished returned %v, %v", snapshot, err) + } + if store.packed.lookup(packedStamp{}) != nil { + t.Fatal("the cache kept a snapshot of a file that vanished") + } +} + +func TestLookupReportsAMalformedPackedRefsFileWithoutCachingIt(t *testing.T) { + dir := newGitDir(t) + writeAt(t, dir, packedRefsFile, "not a packed-refs file\n") + agePackedFile(t, dir, time.Hour) + store := openStore(t, dir) + parses := countPackedParses(t) + + for range 2 { + if _, err := store.Lookup(BranchName("main")); !errors.Is(err, ErrMalformedPacked) { + t.Fatalf("Lookup returned %v, want ErrMalformedPacked", err) + } + } + + if *parses != 2 { + t.Fatalf("a malformed file was parsed %d times, want every time", *parses) + } +} + +func TestLookupTreatsAPackedRefsDirectoryAsAbsent(t *testing.T) { + dir := newGitDir(t) + mkdirAt(t, dir, packedRefsFile) + store := openStore(t, dir) + + if _, err := store.Lookup(BranchName("main")); !errors.Is(err, ErrNotFound) { + t.Fatalf("Lookup returned %v, want ErrNotFound", err) + } +} + +func TestTransactionSeesPackedRefsWrittenByAnEarlierTransaction(t *testing.T) { + dir := newGitDir(t) + writeAt(t, dir, packedRefsFile, packedCacheFile) + agePackedFile(t, dir, time.Hour) + store := openStore(t, dir) + if _, err := store.Lookup(BranchName("feature")); err != nil { + t.Fatalf("Lookup returned error %v", err) + } + + tx := store.Begin() + if err := tx.Delete(BranchName("feature"), hash.Zero); err != nil { + t.Fatalf("Delete returned error %v", err) + } + if err := tx.Commit(); err != nil { + t.Fatalf("Commit returned error %v", err) + } + + if _, err := store.Lookup(BranchName("feature")); !errors.Is(err, ErrNotFound) { + t.Fatalf("Lookup of a deleted packed reference returned %v, want ErrNotFound", err) + } + if _, err := store.Lookup(BranchName("main")); err != nil { + t.Fatalf("Lookup of a surviving packed reference returned %v", err) + } +} diff --git a/internal/gitcore/refs/store.go b/internal/gitcore/refs/store.go index 0e772301..7f6df4da 100644 --- a/internal/gitcore/refs/store.go +++ b/internal/gitcore/refs/store.go @@ -60,6 +60,7 @@ type Store struct { git tree common tree opts Options + packed packedCache } type Ref struct { From fddc7f666173eac3e5642f8676550d2ac01a18a9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=A7=D1=83=D0=BA=D0=B0=D0=BB=D0=B8=D0=BD=20=D0=92=D0=B0?= =?UTF-8?q?=D0=BB=D0=B5=D1=80=D0=B8=D0=B9?= Date: Fri, 16 Oct 2026 09:44:20 +0300 Subject: [PATCH 02/35] pack: skip rescanning a pack directory that has not changed --- internal/gitcore/pack/store.go | 41 ++++++- internal/gitcore/pack/storescan_test.go | 138 ++++++++++++++++++++++++ 2 files changed, 177 insertions(+), 2 deletions(-) create mode 100644 internal/gitcore/pack/storescan_test.go diff --git a/internal/gitcore/pack/store.go b/internal/gitcore/pack/store.go index 6adb43b6..5b34b541 100644 --- a/internal/gitcore/pack/store.go +++ b/internal/gitcore/pack/store.go @@ -16,7 +16,18 @@ import ( "github.com/oops1/gogit/internal/gitcore/object" ) -var statPath = os.Stat +const directorySettle = 2 * time.Second + +var ( + statPath = os.Stat + readDirPath = os.ReadDir + scanClock = time.Now +) + +type directoryStamp struct { + modTime time.Time + settled bool +} type PackFile struct { Name string @@ -60,6 +71,7 @@ type Store struct { settings settings mu sync.RWMutex files []*PackFile + scanned directoryStamp } type candidate struct { @@ -173,13 +185,38 @@ func (s *Store) Verify() error { return nil } +func (s *Store) directoryUnchanged() bool { + s.mu.RLock() + scanned := s.scanned + s.mu.RUnlock() + if !scanned.settled { + return false + } + info, err := statPath(s.dir) + return err == nil && info.ModTime().Equal(scanned.modTime) +} + +func (s *Store) directoryStamp() directoryStamp { + now := scanClock() + info, err := statPath(s.dir) + if err != nil { + return directoryStamp{} + } + return directoryStamp{modTime: info.ModTime(), settled: now.Sub(info.ModTime()) >= directorySettle} +} + func (s *Store) Reload() (bool, error) { + if s.directoryUnchanged() { + return false, nil + } + before := s.directoryStamp() found, err := s.scan() if err != nil { return false, err } s.mu.Lock() defer s.mu.Unlock() + s.scanned = before kept := make(map[string]*PackFile, len(s.files)) for _, file := range s.files { kept[file.Name] = file @@ -285,7 +322,7 @@ func (s *Store) openPair(wanted candidate) (*PackFile, error) { } func (s *Store) scan() ([]candidate, error) { - entries, err := os.ReadDir(s.dir) + entries, err := readDirPath(s.dir) if err != nil { return nil, fmt.Errorf("pack: read %s: %w", s.dir, err) } diff --git a/internal/gitcore/pack/storescan_test.go b/internal/gitcore/pack/storescan_test.go new file mode 100644 index 00000000..df465bb9 --- /dev/null +++ b/internal/gitcore/pack/storescan_test.go @@ -0,0 +1,138 @@ +package pack + +import ( + "io/fs" + "os" + "path/filepath" + "testing" + "time" +) + +func countDirectoryScans(t *testing.T) *int { + t.Helper() + scans := new(int) + previous := readDirPath + readDirPath = func(name string) ([]fs.DirEntry, error) { + *scans++ + return previous(name) + } + t.Cleanup(func() { readDirPath = previous }) + return scans +} + +func ageDirectory(t *testing.T, dir string, age time.Duration) { + t.Helper() + when := time.Now().Add(-age) + if err := os.Chtimes(dir, when, when); err != nil { + t.Fatalf("Chtimes returned error %v", err) + } +} + +func addFixturePack(t *testing.T, dir, name string) { + t.Helper() + for _, suffix := range []string{packSuffix, indexSuffix} { + writeTemp(t, filepath.Join(dir, name+suffix), readFixture(t, filepath.Join(packsDir, name+suffix))) + } +} + +func TestStoreReloadDoesNotScanAnUnchangedSettledDirectoryAgain(t *testing.T) { + names := fixtureNames(t) + dir := copyFixtureDir(t, names[0]) + ageDirectory(t, dir, time.Hour) + scans := countDirectoryScans(t) + store := openStore(t, dir) + + for range 100 { + if changed, err := store.Reload(); changed || err != nil { + t.Fatalf("Reload returned (%v, %v), want (false, nil)", changed, err) + } + } + + if *scans != 1 { + t.Fatalf("the directory was scanned %d times, want once", *scans) + } +} + +func TestStoreReloadScansAgainOnceTheDirectoryChanges(t *testing.T) { + names := fixtureNames(t) + dir := copyFixtureDir(t, names[0]) + ageDirectory(t, dir, time.Hour) + store := openStore(t, dir) + if changed, err := store.Reload(); changed || err != nil { + t.Fatalf("Reload returned (%v, %v), want (false, nil)", changed, err) + } + scans := countDirectoryScans(t) + + addFixturePack(t, dir, names[1]) + + if changed, err := store.Reload(); !changed || err != nil { + t.Fatalf("Reload returned (%v, %v), want (true, nil)", changed, err) + } + if *scans != 1 || len(store.Files()) != 2 { + t.Fatalf("scans = %d, packfiles = %d, want one scan and two packfiles", *scans, len(store.Files())) + } +} + +func TestStoreReloadDoesNotTrustADirectoryThatChangedJustNow(t *testing.T) { + dir := copyFixtureDir(t, fixtureNames(t)[0]) + store := openStore(t, dir) + scans := countDirectoryScans(t) + + for range 3 { + if _, err := store.Reload(); err != nil { + t.Fatalf("Reload returned error %v", err) + } + } + + if *scans != 3 { + t.Fatalf("the directory was scanned %d times, want every time while it is fresh", *scans) + } +} + +func TestStoreReloadScansWhenTheDirectoryCannotBeInspected(t *testing.T) { + dir := copyFixtureDir(t, fixtureNames(t)[0]) + ageDirectory(t, dir, time.Hour) + store := openStore(t, dir) + scans := countDirectoryScans(t) + previous := statPath + statPath = func(name string) (os.FileInfo, error) { + if name == dir { + return nil, os.ErrPermission + } + return previous(name) + } + t.Cleanup(func() { statPath = previous }) + + for range 2 { + if _, err := store.Reload(); err != nil { + t.Fatalf("Reload returned error %v", err) + } + } + + if *scans != 2 { + t.Fatalf("the directory was scanned %d times, want every time without a stamp", *scans) + } +} + +func TestStoreReloadTreatsADirectoryAsSettledOnceItsStampIsOldEnough(t *testing.T) { + dir := copyFixtureDir(t, fixtureNames(t)[0]) + info, err := os.Stat(dir) + if err != nil { + t.Fatalf("Stat returned error %v", err) + } + previous := scanClock + scanClock = func() time.Time { return info.ModTime().Add(directorySettle) } + t.Cleanup(func() { scanClock = previous }) + scans := countDirectoryScans(t) + store := openStore(t, dir) + + for range 3 { + if _, err := store.Reload(); err != nil { + t.Fatalf("Reload returned error %v", err) + } + } + + if *scans != 1 { + t.Fatalf("the directory was scanned %d times, want once", *scans) + } +} From f5e55246692afc5452fe3de179411eb6747cae4c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=A7=D1=83=D0=BA=D0=B0=D0=BB=D0=B8=D0=BD=20=D0=92=D0=B0?= =?UTF-8?q?=D0=BB=D0=B5=D1=80=D0=B8=D0=B9?= Date: Fri, 16 Oct 2026 09:53:51 +0300 Subject: [PATCH 03/35] app: count branch divergence once per pair of tips on the open repository and cache its commit graph --- internal/app/autofetch.go | 2 +- internal/app/branchdivergence.go | 38 +++--- internal/app/branchdivergence_test.go | 38 +++++- internal/app/divergencememo.go | 72 ++++++++++++ internal/app/divergencememo_test.go | 143 +++++++++++++++++++++++ internal/app/flowlog.go | 4 +- internal/app/graphcache.go | 63 ++++++++++ internal/app/graphcache_test.go | 160 ++++++++++++++++++++++++++ internal/app/journal.go | 4 +- internal/app/opened.go | 8 ++ internal/repo/divergence.go | 13 ++- internal/repo/divergence_test.go | 31 +++++ 12 files changed, 548 insertions(+), 28 deletions(-) create mode 100644 internal/app/divergencememo.go create mode 100644 internal/app/divergencememo_test.go create mode 100644 internal/app/graphcache.go create mode 100644 internal/app/graphcache_test.go diff --git a/internal/app/autofetch.go b/internal/app/autofetch.go index 513c3eb7..adf1624c 100644 --- a/internal/app/autofetch.go +++ b/internal/app/autofetch.go @@ -47,7 +47,7 @@ func divergenceStatusSuffix(d divergenceState) string { } func (a *App) computeDivergence(o *openedRepository) (repo.Divergence, bool) { - div, hasUpstream, err := repo.AheadBehind(o.repo) + div, hasUpstream, err := repo.AheadBehindWith(o.repo, o.store, a.statusDivergenceLoader().counter(o)) if err != nil { a.log.Warn("compute ahead/behind failed", "path", o.path, "error", err) return repo.Divergence{}, false diff --git a/internal/app/branchdivergence.go b/internal/app/branchdivergence.go index 3f97b1dd..46e6281e 100644 --- a/internal/app/branchdivergence.go +++ b/internal/app/branchdivergence.go @@ -4,19 +4,26 @@ import ( "log/slog" "github.com/oops1/gogit/internal/gitcore/refs" - gitrepo "github.com/oops1/gogit/internal/gitcore/repo" + "github.com/oops1/gogit/internal/gitcore/revision" "github.com/oops1/gogit/internal/repo" "github.com/oops1/gogit/internal/ui/branches" ) -var manyAheadBehind = repo.ManyAheadBehind +var manyAheadBehind = repo.ManyAheadBehindIn type branchDivergenceLoader struct { - open func(string, gitrepo.OpenOptions) (*gitrepo.Repository, error) - many func(*gitrepo.Repository, []repo.BranchPair) (map[refs.Name]repo.Divergence, error) + many func(revision.Context, []repo.BranchPair) (map[refs.Name]repo.Divergence, error) log *slog.Logger } +func (a *App) divergenceLoader() branchDivergenceLoader { + return branchDivergenceLoader{many: manyAheadBehind, log: a.log} +} + +func (a *App) statusDivergenceLoader() branchDivergenceLoader { + return branchDivergenceLoader{many: repo.ManyAheadBehindIn, log: a.log} +} + func (a *App) clearBranchDivergence() { a.branchDivergenceGen.Add(1) a.branchesView.SetDivergence(nil) @@ -29,9 +36,9 @@ func (a *App) refreshBranchDivergence(o *openedRepository, snap branches.Snapsho a.branchesView.SetDivergence(nil) return } - loader := branchDivergenceLoader{open: openGitRepository, many: manyAheadBehind, log: a.log} + loader := a.divergenceLoader() a.branchDivergenceWG.Go(func() { - result := loader.load(o.path, pairs) + result := loader.load(o, pairs) a.Post(func() { if a.branchDivergenceGen.Load() == gen && a.opened() == o { a.branchesView.SetDivergence(result) @@ -40,17 +47,20 @@ func (a *App) refreshBranchDivergence(o *openedRepository, snap branches.Snapsho }) } -func (l branchDivergenceLoader) load(path string, pairs []repo.BranchPair) map[refs.Name]repo.Divergence { - r, err := l.open(path, gitrepo.OpenOptions{}) - if err != nil { - l.log.Warn("open repository for branch divergence failed", "path", path, "error", err) - return nil +func (l branchDivergenceLoader) counter(o *openedRepository) repo.Counter { + return func(pairs []repo.BranchPair) (map[refs.Name]repo.Divergence, error) { + return o.divergence.count(pairs, func(missing []repo.BranchPair) (map[refs.Name]repo.Divergence, error) { + return l.many(o.revisionContext(), missing) + }) } - defer func() { _ = r.Close() }() - result, err := l.many(r, pairs) +} + +func (l branchDivergenceLoader) load(o *openedRepository, pairs []repo.BranchPair) map[refs.Name]repo.Divergence { + result, err := l.counter(o)(pairs) if err != nil { - l.log.Warn("compute branch divergence failed", "path", path, "error", err) + l.log.Warn("compute branch divergence failed", "path", o.path, "error", err) return nil } + o.divergence.keepOnly(pairs) return result } diff --git a/internal/app/branchdivergence_test.go b/internal/app/branchdivergence_test.go index b99edabb..54a2ded4 100644 --- a/internal/app/branchdivergence_test.go +++ b/internal/app/branchdivergence_test.go @@ -1,6 +1,7 @@ package app import ( + "errors" "path/filepath" "testing" "time" @@ -8,6 +9,7 @@ import ( "github.com/oops1/gogit/internal/gitcore/ops" "github.com/oops1/gogit/internal/gitcore/refs" gitrepo "github.com/oops1/gogit/internal/gitcore/repo" + "github.com/oops1/gogit/internal/gitcore/revision" "github.com/oops1/gogit/internal/repo" ) @@ -109,19 +111,26 @@ func TestBranchesPaneShowsNoSuffixForABranchWithoutUpstream(t *testing.T) { } func TestBranchDivergenceComputationRunsInTheBackgroundWithoutBlockingRefresh(t *testing.T) { - a, server, _ := cloneForDivergence(t) - addRemoteServerCommit(t, server, "main", "second.txt", "second\n") + a, _, local := cloneForDivergence(t) + addLocalCommitWithMessage(t, local, "main", "second.txt", "second\n", "second") + o := a.opened() + o.divergence.keepOnly(nil) + snap, err := loadBranchSnapshot(o.store) + if err != nil { + t.Fatal(err) + } + a.enrichBranchSnapshot(o, &snap) release := make(chan struct{}) entered := make(chan struct{}, 1) prev := manyAheadBehind - manyAheadBehind = func(r *gitrepo.Repository, pairs []repo.BranchPair) (map[refs.Name]repo.Divergence, error) { + manyAheadBehind = func(source revision.Context, pairs []repo.BranchPair) (map[refs.Name]repo.Divergence, error) { select { case entered <- struct{}{}: default: } <-release - return prev(r, pairs) + return prev(source, pairs) } t.Cleanup(func() { manyAheadBehind = prev @@ -130,14 +139,14 @@ func TestBranchDivergenceComputationRunsInTheBackgroundWithoutBlockingRefresh(t done := make(chan struct{}) go func() { - a.RefreshRepository() + a.refreshBranchDivergence(o, snap) close(done) }() select { case <-done: case <-time.After(testTimeout): - t.Fatal("RefreshRepository did not return; it must not wait for the divergence computation") + t.Fatal("refreshBranchDivergence did not return; it must not wait for the divergence computation") } select { @@ -146,3 +155,20 @@ func TestBranchDivergenceComputationRunsInTheBackgroundWithoutBlockingRefresh(t t.Fatal("the background computation was never started") } } + +func TestBranchDivergenceLoaderReturnsNothingWhenCountingFails(t *testing.T) { + a, _, _ := cloneForDivergence(t) + o := a.opened() + o.divergence.keepOnly(nil) + loader := branchDivergenceLoader{ + many: func(revision.Context, []repo.BranchPair) (map[refs.Name]repo.Divergence, error) { + return nil, errors.New("boom") + }, + log: a.log, + } + pair := memoPair(t, "main", "11", "22") + + if got := loader.load(o, []repo.BranchPair{pair}); got != nil { + t.Fatalf("load returned %v, want nothing after a failed count", got) + } +} diff --git a/internal/app/divergencememo.go b/internal/app/divergencememo.go new file mode 100644 index 00000000..90537d89 --- /dev/null +++ b/internal/app/divergencememo.go @@ -0,0 +1,72 @@ +package app + +import ( + "sync" + + "github.com/oops1/gogit/internal/gitcore/hash" + "github.com/oops1/gogit/internal/gitcore/refs" + "github.com/oops1/gogit/internal/repo" +) + +type divergenceKey struct { + local hash.ObjectID + remote hash.ObjectID +} + +func keyOf(pair repo.BranchPair) divergenceKey { + return divergenceKey{local: pair.Local, remote: pair.Remote} +} + +type divergenceMemo struct { + mu sync.Mutex + known map[divergenceKey]repo.Divergence +} + +func (m *divergenceMemo) count(pairs []repo.BranchPair, compute repo.Counter) (map[refs.Name]repo.Divergence, error) { + result := make(map[refs.Name]repo.Divergence, len(pairs)) + var missing []repo.BranchPair + m.mu.Lock() + for _, pair := range pairs { + counted, ok := m.known[keyOf(pair)] + if !ok { + missing = append(missing, pair) + continue + } + if counted != (repo.Divergence{}) { + result[pair.Name] = counted + } + } + m.mu.Unlock() + if len(missing) == 0 { + return result, nil + } + computed, err := compute(missing) + if err != nil { + return nil, err + } + m.mu.Lock() + defer m.mu.Unlock() + if m.known == nil { + m.known = make(map[divergenceKey]repo.Divergence, len(missing)) + } + for _, pair := range missing { + counted := computed[pair.Name] + m.known[keyOf(pair)] = counted + if counted != (repo.Divergence{}) { + result[pair.Name] = counted + } + } + return result, nil +} + +func (m *divergenceMemo) keepOnly(pairs []repo.BranchPair) { + m.mu.Lock() + defer m.mu.Unlock() + kept := make(map[divergenceKey]repo.Divergence, len(pairs)) + for _, pair := range pairs { + if counted, ok := m.known[keyOf(pair)]; ok { + kept[keyOf(pair)] = counted + } + } + m.known = kept +} diff --git a/internal/app/divergencememo_test.go b/internal/app/divergencememo_test.go new file mode 100644 index 00000000..8de571e6 --- /dev/null +++ b/internal/app/divergencememo_test.go @@ -0,0 +1,143 @@ +package app + +import ( + "errors" + "testing" + + "github.com/oops1/gogit/internal/gitcore/hash" + "github.com/oops1/gogit/internal/gitcore/refs" + "github.com/oops1/gogit/internal/repo" +) + +func memoPair(t *testing.T, name, local, remote string) repo.BranchPair { + t.Helper() + return repo.BranchPair{ + Name: refs.BranchName(name), + Local: memoID(t, local), + Remote: memoID(t, remote), + } +} + +func memoID(t *testing.T, seed string) hash.ObjectID { + t.Helper() + id, err := hash.Parse(seed + "0000000000000000000000000000000000000000"[:hash.HexSize-len(seed)]) + if err != nil { + t.Fatalf("Parse returned error %v", err) + } + return id +} + +type countingCounter struct { + asked [][]repo.BranchPair + answer map[refs.Name]repo.Divergence + err error +} + +func (c *countingCounter) count(pairs []repo.BranchPair) (map[refs.Name]repo.Divergence, error) { + c.asked = append(c.asked, pairs) + return c.answer, c.err +} + +func TestDivergenceMemoComputesEachPairOnce(t *testing.T) { + var memo divergenceMemo + pair := memoPair(t, "main", "11", "22") + counter := &countingCounter{answer: map[refs.Name]repo.Divergence{pair.Name: {Ahead: 2, Behind: 1}}} + + for range 3 { + got, err := memo.count([]repo.BranchPair{pair}, counter.count) + if err != nil || got[pair.Name] != (repo.Divergence{Ahead: 2, Behind: 1}) { + t.Fatalf("count returned %v, %v", got, err) + } + } + + if len(counter.asked) != 1 { + t.Fatalf("the counter was asked %d times, want once", len(counter.asked)) + } +} + +func TestDivergenceMemoRemembersPairsThatDoNotDiverge(t *testing.T) { + var memo divergenceMemo + pair := memoPair(t, "main", "11", "11") + counter := &countingCounter{answer: map[refs.Name]repo.Divergence{}} + + for range 2 { + got, err := memo.count([]repo.BranchPair{pair}, counter.count) + if err != nil || len(got) != 0 { + t.Fatalf("count returned %v, %v, want nothing", got, err) + } + } + + if len(counter.asked) != 1 { + t.Fatalf("the counter was asked %d times, want once", len(counter.asked)) + } +} + +func TestDivergenceMemoAsksOnlyForPairsWhoseTipsChanged(t *testing.T) { + var memo divergenceMemo + main := memoPair(t, "main", "11", "22") + feature := memoPair(t, "feature", "33", "22") + counter := &countingCounter{answer: map[refs.Name]repo.Divergence{main.Name: {Ahead: 1}, feature.Name: {Behind: 4}}} + if _, err := memo.count([]repo.BranchPair{main, feature}, counter.count); err != nil { + t.Fatalf("count returned error %v", err) + } + + moved := memoPair(t, "main", "44", "22") + counter.answer = map[refs.Name]repo.Divergence{moved.Name: {Ahead: 2}} + got, err := memo.count([]repo.BranchPair{moved, feature}, counter.count) + + if err != nil { + t.Fatalf("count returned error %v", err) + } + if len(counter.asked) != 2 || len(counter.asked[1]) != 1 || counter.asked[1][0] != moved { + t.Fatalf("the second question was %v, want only the moved branch", counter.asked) + } + if got[moved.Name] != (repo.Divergence{Ahead: 2}) || got[feature.Name] != (repo.Divergence{Behind: 4}) { + t.Fatalf("count returned %v", got) + } +} + +func TestDivergenceMemoDoesNotRememberAFailedCount(t *testing.T) { + var memo divergenceMemo + pair := memoPair(t, "main", "11", "22") + boom := errors.New("boom") + counter := &countingCounter{err: boom} + if _, err := memo.count([]repo.BranchPair{pair}, counter.count); !errors.Is(err, boom) { + t.Fatalf("count returned %v, want %v", err, boom) + } + + counter.err = nil + counter.answer = map[refs.Name]repo.Divergence{pair.Name: {Ahead: 1}} + got, err := memo.count([]repo.BranchPair{pair}, counter.count) + + if err != nil || got[pair.Name] != (repo.Divergence{Ahead: 1}) || len(counter.asked) != 2 { + t.Fatalf("count returned %v, %v after %d questions", got, err, len(counter.asked)) + } +} + +func TestDivergenceMemoForgetsPairsThatLeftTheBranchList(t *testing.T) { + var memo divergenceMemo + main := memoPair(t, "main", "11", "22") + gone := memoPair(t, "gone", "33", "22") + counter := &countingCounter{answer: map[refs.Name]repo.Divergence{}} + if _, err := memo.count([]repo.BranchPair{main, gone}, counter.count); err != nil { + t.Fatalf("count returned error %v", err) + } + + memo.keepOnly([]repo.BranchPair{main}) + if _, err := memo.count([]repo.BranchPair{main, gone}, counter.count); err != nil { + t.Fatalf("count returned error %v", err) + } + + if len(counter.asked) != 2 || len(counter.asked[1]) != 1 || counter.asked[1][0] != gone { + t.Fatalf("the questions were %v, want the forgotten pair asked again", counter.asked) + } +} + +func TestDivergenceMemoKeepsOnlyPairsItHasCounted(t *testing.T) { + var memo divergenceMemo + memo.keepOnly([]repo.BranchPair{memoPair(t, "main", "11", "22")}) + + if len(memo.known) != 0 { + t.Fatalf("the memo holds %d pairs it never counted", len(memo.known)) + } +} diff --git a/internal/app/flowlog.go b/internal/app/flowlog.go index 8dd65d6d..4dacfa2b 100644 --- a/internal/app/flowlog.go +++ b/internal/app/flowlog.go @@ -5,7 +5,6 @@ import ( "errors" "github.com/oops1/gogit/internal/gitcore/hash" - "github.com/oops1/gogit/internal/gitcore/ops" "github.com/oops1/gogit/internal/gitcore/refs" gitrepo "github.com/oops1/gogit/internal/gitcore/repo" "github.com/oops1/gogit/internal/gitcore/revision" @@ -60,8 +59,7 @@ func flowLogCommits(ctx context.Context, o *openedRepository, max int) ([]flow.L if err != nil { return nil, err } - graph, _ := ops.OpenCommitGraph(o.repo, o.db) - source := revision.Context{Objects: o.db, Refs: o.store, Shallow: o.shallow, Graph: graph} + source := o.revisionContext() walk := revision.Options{ Context: source, Include: []hash.ObjectID{head.Target}, diff --git a/internal/app/graphcache.go b/internal/app/graphcache.go new file mode 100644 index 00000000..8c1f7829 --- /dev/null +++ b/internal/app/graphcache.go @@ -0,0 +1,63 @@ +package app + +import ( + "os" + "path/filepath" + "strconv" + "strings" + "time" + + "github.com/oops1/gogit/internal/gitcore/commitgraph" + "github.com/oops1/gogit/internal/gitcore/ops" + "github.com/oops1/gogit/internal/gitcore/revision" +) + +const graphSettle = 2 * time.Second + +var ( + openCommitGraph = ops.OpenCommitGraph + statGraphFile = os.Stat + graphClock = time.Now +) + +func graphFilePaths(objectDirs []string) []string { + paths := make([]string, 0, 2*len(objectDirs)) + for _, dir := range objectDirs { + info := filepath.Join(dir, "info") + paths = append(paths, filepath.Join(info, "commit-graph"), filepath.Join(info, "commit-graphs", "commit-graph-chain")) + } + return paths +} + +func graphFilesKey(objectDirs []string) (string, bool) { + var key strings.Builder + settled := true + now := graphClock() + for _, path := range graphFilePaths(objectDirs) { + info, err := statGraphFile(path) + if err != nil { + continue + } + key.WriteString(path + "|" + strconv.FormatInt(info.Size(), 10) + "|" + strconv.FormatInt(info.ModTime().UnixNano(), 10) + ";") + if now.Sub(info.ModTime()) < graphSettle { + settled = false + } + } + return key.String(), settled +} + +func (o *openedRepository) commitGraph() *commitgraph.Graph { + key, settled := graphFilesKey(o.db.Dirs()) + o.graphMu.Lock() + defer o.graphMu.Unlock() + if o.graphReady && settled && key == o.graphKey { + return o.graph + } + graph, _ := openCommitGraph(o.repo, o.db) + o.graph, o.graphKey, o.graphReady = graph, key, settled + return graph +} + +func (o *openedRepository) revisionContext() revision.Context { + return revision.Context{Objects: o.db, Refs: o.store, Shallow: o.shallow, Graph: o.commitGraph()} +} diff --git a/internal/app/graphcache_test.go b/internal/app/graphcache_test.go new file mode 100644 index 00000000..2e6fb4ae --- /dev/null +++ b/internal/app/graphcache_test.go @@ -0,0 +1,160 @@ +package app + +import ( + "os" + "path/filepath" + "testing" + "time" + + "github.com/oops1/gogit/internal/gitcore/commitgraph" + "github.com/oops1/gogit/internal/gitcore/odb" + "github.com/oops1/gogit/internal/gitcore/refs" + gitrepo "github.com/oops1/gogit/internal/gitcore/repo" + "github.com/oops1/gogit/internal/gitcore/revision" + "github.com/oops1/gogit/internal/repo" +) + +func countGraphOpens(t *testing.T) *int { + t.Helper() + opens := new(int) + previous := openCommitGraph + openCommitGraph = func(*gitrepo.Repository, *odb.DB) (*commitgraph.Graph, error) { + *opens++ + return nil, nil + } + t.Cleanup(func() { openCommitGraph = previous }) + return opens +} + +func writeGraphFile(t *testing.T, o *openedRepository, rel, content string, age time.Duration) { + t.Helper() + path := filepath.Join(o.repo.ObjectsDir(), "info", filepath.FromSlash(rel)) + if err := os.MkdirAll(filepath.Dir(path), 0o777); err != nil { + t.Fatalf("MkdirAll returned error %v", err) + } + if err := os.WriteFile(path, []byte(content), 0o666); err != nil { + t.Fatalf("WriteFile returned error %v", err) + } + when := time.Now().Add(-age) + if err := os.Chtimes(path, when, when); err != nil { + t.Fatalf("Chtimes returned error %v", err) + } +} + +func TestCommitGraphIsOpenedOnceWhileItsFilesAreUnchanged(t *testing.T) { + a, _, _ := cloneForDivergence(t) + o := a.opened() + opens := countGraphOpens(t) + writeGraphFile(t, o, "commit-graph", "graph", time.Hour) + + for range 5 { + o.commitGraph() + } + + if *opens != 1 { + t.Fatalf("the commit graph was opened %d times, want once", *opens) + } +} + +func TestCommitGraphIsOpenedAgainWhenItsFileChanges(t *testing.T) { + a, _, _ := cloneForDivergence(t) + o := a.opened() + opens := countGraphOpens(t) + writeGraphFile(t, o, "commit-graph", "graph", time.Hour) + o.commitGraph() + + writeGraphFile(t, o, "commit-graph", "a longer graph", time.Hour) + writeGraphFile(t, o, "commit-graphs/commit-graph-chain", "chain", time.Hour) + o.commitGraph() + o.commitGraph() + + if *opens != 2 { + t.Fatalf("the commit graph was opened %d times, want twice", *opens) + } +} + +func TestCommitGraphIsNotTrustedWhileItsFileIsFresh(t *testing.T) { + a, _, _ := cloneForDivergence(t) + o := a.opened() + opens := countGraphOpens(t) + writeGraphFile(t, o, "commit-graph", "graph", 0) + + for range 3 { + o.commitGraph() + } + + if *opens != 3 { + t.Fatalf("the commit graph was opened %d times, want every time while the file is fresh", *opens) + } +} + +func TestCommitGraphIsTrustedOnceItsFileHasSettled(t *testing.T) { + a, _, _ := cloneForDivergence(t) + o := a.opened() + opens := countGraphOpens(t) + writeGraphFile(t, o, "commit-graph", "graph", 0) + previous := graphClock + graphClock = func() time.Time { return time.Now().Add(graphSettle) } + t.Cleanup(func() { graphClock = previous }) + + for range 3 { + o.commitGraph() + } + + if *opens != 1 { + t.Fatalf("the commit graph was opened %d times, want once after the file settled", *opens) + } +} + +func TestCommitGraphIsNotOpenedAgainWhenTheRepositoryHasNone(t *testing.T) { + a, _, _ := cloneForDivergence(t) + o := a.opened() + opens := countGraphOpens(t) + + for range 4 { + o.commitGraph() + } + + if *opens != 0 { + t.Fatalf("the commit graph was opened %d times, want none: the absence is cached too", *opens) + } +} + +func TestRevisionContextCarriesTheOpenRepositoryAndItsCachedGraph(t *testing.T) { + a, _, _ := cloneForDivergence(t) + o := a.opened() + + source := o.revisionContext() + + want := revision.Context{Objects: o.db, Refs: o.store, Shallow: o.shallow, Graph: o.commitGraph()} + if source.Objects != want.Objects || source.Refs != want.Refs || source.Graph != want.Graph || len(source.Shallow) != len(want.Shallow) { + t.Fatalf("revisionContext returned %+v, want %+v", source, want) + } +} + +func TestRefreshDoesNotCountDivergenceAgainWhileBranchTipsAreUnchanged(t *testing.T) { + a, _, local := cloneForDivergence(t) + calls := 0 + previous := manyAheadBehind + manyAheadBehind = func(source revision.Context, pairs []repo.BranchPair) (map[refs.Name]repo.Divergence, error) { + calls++ + return previous(source, pairs) + } + t.Cleanup(func() { manyAheadBehind = previous }) + + a.RefreshRepository() + a.branchDivergenceWG.Wait() + a.RefreshRepository() + a.branchDivergenceWG.Wait() + if calls != 0 { + t.Fatalf("divergence was counted %d times while no branch moved, want none", calls) + } + + addLocalCommitWithMessage(t, local, "main", "second.txt", "second\n", "second") + a.RefreshRepository() + a.branchDivergenceWG.Wait() + + if calls != 1 { + t.Fatalf("divergence was counted %d times after one branch moved, want once", calls) + } +} diff --git a/internal/app/journal.go b/internal/app/journal.go index 5953cc3a..8a9a0505 100644 --- a/internal/app/journal.go +++ b/internal/app/journal.go @@ -6,7 +6,6 @@ import ( "slices" "github.com/oops1/gogit/internal/gitcore/hash" - "github.com/oops1/gogit/internal/gitcore/ops" "github.com/oops1/gogit/internal/gitcore/revision" "github.com/oops1/gogit/internal/i18n" "github.com/oops1/gogit/internal/ui/journal" @@ -33,8 +32,7 @@ func (a *App) startJournal() { if o == nil { return } - graph, _ := ops.OpenCommitGraph(o.repo, o.db) - source := revision.Context{Objects: o.db, Refs: o.store, Shallow: o.shallow, Graph: graph} + source := o.revisionContext() filter := a.journalFilter() opts, err := filter.Apply(journal.WalkOptions(a.cfg.Git.LogMaxCount, a.State().HasRemotes)) if err != nil { diff --git a/internal/app/opened.go b/internal/app/opened.go index 37f714c0..1dfbfb5e 100644 --- a/internal/app/opened.go +++ b/internal/app/opened.go @@ -4,6 +4,7 @@ import ( "errors" "sync" + "github.com/oops1/gogit/internal/gitcore/commitgraph" "github.com/oops1/gogit/internal/gitcore/hash" "github.com/oops1/gogit/internal/gitcore/odb" "github.com/oops1/gogit/internal/gitcore/refs" @@ -24,6 +25,13 @@ type openedRepository struct { wtMu sync.RWMutex worktree *worktree.Worktree + + divergence divergenceMemo + + graphMu sync.Mutex + graphKey string + graphReady bool + graph *commitgraph.Graph } func (o *openedRepository) currentWorktree() *worktree.Worktree { diff --git a/internal/repo/divergence.go b/internal/repo/divergence.go index 5adaee10..a95a06dd 100644 --- a/internal/repo/divergence.go +++ b/internal/repo/divergence.go @@ -27,13 +27,20 @@ var openDivergenceObjects = odb.Open var openDivergenceRefs = refs.Open +type Counter func(pairs []BranchPair) (map[refs.Name]Divergence, error) + func AheadBehind(r *gitrepo.Repository) (Divergence, bool, error) { store, err := openDivergenceRefs(refs.Options{GitDir: r.GitDir(), CommonDir: r.CommonDir(), Bare: r.IsBare()}) if err != nil { return Divergence{}, false, err } defer func() { _ = store.Close() }() + return AheadBehindWith(r, store, func(pairs []BranchPair) (map[refs.Name]Divergence, error) { + return ManyAheadBehind(r, pairs) + }) +} +func AheadBehindWith(r *gitrepo.Repository, store *refs.Store, count Counter) (Divergence, bool, error) { head, err := store.Lookup(refs.HEAD) if err != nil { return Divergence{}, false, err @@ -61,7 +68,7 @@ func AheadBehind(r *gitrepo.Repository) (Divergence, bool, error) { return Divergence{}, false, err } - result, err := ManyAheadBehind(r, []BranchPair{{Name: head.SymbolicTarget, Local: localCommit, Remote: remoteCommit}}) + result, err := count([]BranchPair{{Name: head.SymbolicTarget, Local: localCommit, Remote: remoteCommit}}) if err != nil { return Divergence{}, false, err } @@ -93,7 +100,11 @@ func ManyAheadBehind(r *gitrepo.Repository, pairs []BranchPair) (map[refs.Name]D if settings.Enabled { revCtx.Graph, _ = commitgraph.Open(db.Dirs(), settings.Open) } + return ManyAheadBehindIn(revCtx, pairs) +} +func ManyAheadBehindIn(revCtx revision.Context, pairs []BranchPair) (map[refs.Name]Divergence, error) { + result := make(map[refs.Name]Divergence, len(pairs)) for _, pair := range pairs { ahead, err := countDivergenceCommits(revCtx, pair.Local, pair.Remote) if err != nil { diff --git a/internal/repo/divergence_test.go b/internal/repo/divergence_test.go index f749b846..77cb65d1 100644 --- a/internal/repo/divergence_test.go +++ b/internal/repo/divergence_test.go @@ -14,6 +14,7 @@ import ( "github.com/oops1/gogit/internal/gitcore/odb" "github.com/oops1/gogit/internal/gitcore/refs" gitrepo "github.com/oops1/gogit/internal/gitcore/repo" + "github.com/oops1/gogit/internal/gitcore/revision" ) var errDivergenceInjected = errors.New("divergence: injected failure") @@ -451,3 +452,33 @@ func TestAheadBehindReportsAllRemoteCommitsAsBehindForAnUnbornBranch(t *testing. t.Fatalf("divergence = %+v, want {0 1}", div) } } + +type unreadableObjects struct{} + +func (unreadableObjects) Get(hash.ObjectID) (object.Type, []byte, error) { + return 0, nil, errDivergenceInjected +} + +func TestManyAheadBehindInReportsAnUnreadableRemoteCommitOfAnUnbornBranch(t *testing.T) { + pair := BranchPair{Name: refs.BranchName("main"), Remote: divergenceFakeObjectID(t, "22")} + + _, err := ManyAheadBehindIn(revision.Context{Objects: unreadableObjects{}}, []BranchPair{pair}) + + if !errors.Is(err, errDivergenceInjected) { + t.Fatalf("ManyAheadBehindIn returned %v, want the injected failure", err) + } +} + +func TestManyAheadBehindInCountsPairsOnTheContextItIsGiven(t *testing.T) { + db, _ := openDivergenceWriters(t, newDivergenceRepoDir(t, "main")) + base := putDivergenceCommit(t, db, "base") + local := putDivergenceCommit(t, db, "local", base) + remote := putDivergenceCommit(t, db, "remote", base) + pair := BranchPair{Name: refs.BranchName("main"), Local: local, Remote: remote} + + got, err := ManyAheadBehindIn(revision.Context{Objects: db}, []BranchPair{pair}) + + if err != nil || got[pair.Name] != (Divergence{Ahead: 1, Behind: 1}) { + t.Fatalf("ManyAheadBehindIn returned %v, %v, want one ahead and one behind", got, err) + } +} From 6e9027b3e771c4d0704009c3e9b6ec60c93049ef Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=A7=D1=83=D0=BA=D0=B0=D0=BB=D0=B8=D0=BD=20=D0=92=D0=B0?= =?UTF-8?q?=D0=BB=D0=B5=D1=80=D0=B8=D0=B9?= Date: Fri, 16 Oct 2026 09:59:17 +0300 Subject: [PATCH 04/35] ops: write a commit graph from the refs alone when a repository has none --- internal/gitcore/ops/commitgraphensure.go | 119 ++++++++++ .../gitcore/ops/commitgraphensure_test.go | 224 ++++++++++++++++++ 2 files changed, 343 insertions(+) create mode 100644 internal/gitcore/ops/commitgraphensure.go create mode 100644 internal/gitcore/ops/commitgraphensure_test.go diff --git a/internal/gitcore/ops/commitgraphensure.go b/internal/gitcore/ops/commitgraphensure.go new file mode 100644 index 00000000..68986433 --- /dev/null +++ b/internal/gitcore/ops/commitgraphensure.go @@ -0,0 +1,119 @@ +package ops + +import ( + "context" + "errors" + "os" + "path/filepath" + + "github.com/oops1/gogit/internal/gitcore/commitgraph" + "github.com/oops1/gogit/internal/gitcore/hash" + "github.com/oops1/gogit/internal/gitcore/object" + "github.com/oops1/gogit/internal/gitcore/odb" + "github.com/oops1/gogit/internal/gitcore/refs" + "github.com/oops1/gogit/internal/gitcore/repo" +) + +var commitGraphStat = os.Stat + +func EnsureCommitGraph(ctx context.Context, r *repo.Repository) (int, error) { + settings, err := r.CommitGraphSettings() + if err != nil || !settings.Enabled { + return 0, err + } + wanted, err := gcWritesCommitGraph(r) + if err != nil || !wanted { + return 0, err + } + db, err := odbOpen(r.ObjectsDir(), odbOptions(r)) + if err != nil { + return 0, err + } + defer func() { _ = db.Close() }() + if commitGraphPresent(db) { + return 0, nil + } + commits, err := reachableCommits(ctx, r, db) + if err != nil { + return 0, err + } + return writeCommitGraph(ctx, r, db, commits) +} + +func commitGraphPresent(db *odb.DB) bool { + for _, dir := range db.Dirs() { + info := filepath.Join(dir, commitgraph.InfoDir) + for _, path := range []string{ + filepath.Join(info, commitgraph.FileName), + filepath.Join(info, commitgraph.GraphsDir, commitgraph.ChainFileName), + } { + if _, err := commitGraphStat(path); err == nil { + return true + } + } + } + return false +} + +func reachableCommits(ctx context.Context, r *repo.Repository, db *odb.DB) ([]commitgraph.Commit, error) { + store, err := refsOpen(refs.Options{GitDir: r.GitDir(), CommonDir: r.CommonDir(), Bare: r.IsBare(), Peeler: db}) + if err != nil { + return nil, err + } + defer func() { _ = store.Close() }() + pending, err := commitGraphRoots(store) + if err != nil { + return nil, err + } + seen := make(map[hash.ObjectID]struct{}, len(pending)) + var commits []commitgraph.Commit + for len(pending) > 0 { + if err := ctx.Err(); err != nil { + return nil, err + } + id := pending[len(pending)-1] + pending = pending[:len(pending)-1] + if _, done := seen[id]; done || id.IsZero() { + continue + } + seen[id] = struct{}{} + kind, target, err := db.Peel(id) + if err != nil { + return nil, err + } + if kind != object.TypeCommit { + continue + } + if target != id { + if _, done := seen[target]; done { + continue + } + seen[target] = struct{}{} + } + commit, err := db.Commit(target) + if err != nil { + return nil, err + } + commits = append(commits, commitgraph.Commit{ID: target, Tree: commit.Tree, Parents: commit.Parents, Time: commit.Committer.When.Unix()}) + pending = append(pending, commit.Parents...) + } + return commits, nil +} + +func commitGraphRoots(store *refs.Store) ([]hash.ObjectID, error) { + var roots []hash.ObjectID + for ref, err := range store.All() { + if err != nil { + return nil, err + } + roots = append(roots, ref.Target) + } + head, err := store.Resolve(refs.HEAD) + if errors.Is(err, refs.ErrNotFound) { + return roots, nil + } + if err != nil { + return nil, err + } + return append(roots, head.Target), nil +} diff --git a/internal/gitcore/ops/commitgraphensure_test.go b/internal/gitcore/ops/commitgraphensure_test.go new file mode 100644 index 00000000..8a49a708 --- /dev/null +++ b/internal/gitcore/ops/commitgraphensure_test.go @@ -0,0 +1,224 @@ +package ops + +import ( + "context" + "errors" + "io/fs" + "os" + "path/filepath" + "testing" + + "github.com/oops1/gogit/internal/gitcore/commitgraph" + "github.com/oops1/gogit/internal/gitcore/hash" + "github.com/oops1/gogit/internal/gitcore/object" + "github.com/oops1/gogit/internal/gitcore/odb" + "github.com/oops1/gogit/internal/gitcore/refs" +) + +func TestEnsuringTheCommitGraphWritesOneWhenTheRepositoryHasNone(t *testing.T) { + r := newTestRepo(t) + buildMaintHistory(t, r) + + written, err := EnsureCommitGraph(t.Context(), r.repo) + + if err != nil || written != 2 { + t.Fatalf("EnsureCommitGraph returned %d, %v, want both commits", written, err) + } + graph, err := commitgraph.Open([]string{r.repo.ObjectsDir()}, commitgraph.OpenOptions{}) + if err != nil || graph == nil || graph.Len() != 2 { + t.Fatalf("the written graph is %v, %v, want two commits", graph, err) + } +} + +func TestEnsuringTheCommitGraphLeavesAnExistingGraphAlone(t *testing.T) { + r := newTestRepo(t) + buildMaintHistory(t, r) + if _, err := EnsureCommitGraph(t.Context(), r.repo); err != nil { + t.Fatal(err) + } + before, err := os.Stat(commitGraphPath(r)) + if err != nil { + t.Fatal(err) + } + + written, err := EnsureCommitGraph(t.Context(), r.repo) + + if err != nil || written != 0 { + t.Fatalf("EnsureCommitGraph returned %d, %v, want nothing written", written, err) + } + after, err := os.Stat(commitGraphPath(r)) + if err != nil || !after.ModTime().Equal(before.ModTime()) { + t.Fatalf("the graph was rewritten: %v, %v", after, err) + } +} + +func TestEnsuringTheCommitGraphRecognisesAGraphChain(t *testing.T) { + r := newTestRepo(t) + buildMaintHistory(t, r) + chain := filepath.Join(r.repo.ObjectsDir(), commitgraph.InfoDir, commitgraph.GraphsDir, commitgraph.ChainFileName) + if err := os.MkdirAll(filepath.Dir(chain), 0o777); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(chain, []byte("chain\n"), 0o666); err != nil { + t.Fatal(err) + } + + written, err := EnsureCommitGraph(t.Context(), r.repo) + + if err != nil || written != 0 { + t.Fatalf("EnsureCommitGraph returned %d, %v, want nothing written next to a chain", written, err) + } +} + +func TestEnsuringTheCommitGraphHonoursTheSettingsAndTheRepositoryKind(t *testing.T) { + for _, tt := range []struct { + name string + setup func(t *testing.T, r *testRepo) + }{ + {"an empty repository", func(*testing.T, *testRepo) {}}, + {"a shallow repository", func(t *testing.T, r *testRepo) { + h := buildMaintHistory(t, r) + writeGitFile(t, r.repo.CommonDir(), "shallow", h.second.String()+"\n") + }}, + {"core.commitGraph switched off", func(t *testing.T, r *testRepo) { + buildMaintHistory(t, r) + r.appendConfig("[core]\n\tcommitGraph = false\n") + r.repo = r.reopen() + }}, + {"gc.writeCommitGraph switched off", func(t *testing.T, r *testRepo) { + buildMaintHistory(t, r) + r.appendConfig("[gc]\n\twriteCommitGraph = false\n") + r.repo = r.reopen() + }}, + } { + t.Run(tt.name, func(t *testing.T) { + r := newTestRepo(t) + tt.setup(t, r) + + written, err := EnsureCommitGraph(t.Context(), r.repo) + + if err != nil || written != 0 { + t.Fatalf("EnsureCommitGraph returned %d, %v, want nothing", written, err) + } + if _, err := os.Stat(commitGraphPath(r)); !errors.Is(err, fs.ErrNotExist) { + t.Fatalf("a graph was written: %v", err) + } + }) + } +} + +func TestEnsuringTheCommitGraphCountsEachCommitOnceEvenWhenAnnotatedTagsPointAtIt(t *testing.T) { + r := newTestRepo(t) + h := buildMaintHistory(t, r) + second, err := r.db().PutObject(&object.Tag{Object: h.second, ObjectType: object.TypeCommit, Name: "v2", Message: "v2\n"}) + if err != nil { + t.Fatal(err) + } + setMaintRef(t, r, refs.TagName("v2"), second) + setMaintRef(t, r, refs.TagName("v2-again"), second) + setMaintRef(t, r, refs.TagName("v2-plain"), h.second) + lonely := putMaintCommit(t, r, h.tree1) + lonelyTag, err := r.db().PutObject(&object.Tag{Object: lonely, ObjectType: object.TypeCommit, Name: "lonely", Message: "lonely\n"}) + if err != nil { + t.Fatal(err) + } + setMaintRef(t, r, refs.TagName("lonely"), lonelyTag) + treeRef := putTree(t, r, object.TreeEntry{Mode: object.ModeBlob, Name: "a.txt", ID: h.blobA}) + setMaintRef(t, r, refs.Name("refs/odd/tree"), treeRef) + + written, err := EnsureCommitGraph(t.Context(), r.repo) + + if err != nil || written != 3 { + t.Fatalf("EnsureCommitGraph returned %d, %v, want three commits", written, err) + } +} + +func TestEnsuringTheCommitGraphStartsFromADetachedHead(t *testing.T) { + r := newTestRepo(t) + h := buildMaintHistory(t, r) + if err := os.WriteFile(filepath.Join(r.repo.GitDir(), "HEAD"), []byte(h.first.String()+"\n"), 0o666); err != nil { + t.Fatal(err) + } + setMaintRef(t, r, refs.BranchName("main"), h.first) + if err := os.Remove(filepath.Join(r.repo.CommonDir(), "refs", "tags", "v1")); err != nil && !errors.Is(err, fs.ErrNotExist) { + t.Fatal(err) + } + + written, err := EnsureCommitGraph(t.Context(), r.repo) + + if err != nil || written < 1 { + t.Fatalf("EnsureCommitGraph returned %d, %v, want the commits behind a detached HEAD", written, err) + } +} + +func TestEnsuringTheCommitGraphStopsWhenTheCallerGivesUp(t *testing.T) { + r := newTestRepo(t) + buildMaintHistory(t, r) + ctx, cancel := context.WithCancel(t.Context()) + cancel() + + if _, err := EnsureCommitGraph(ctx, r.repo); !errors.Is(err, context.Canceled) { + t.Fatalf("EnsureCommitGraph returned %v, want context.Canceled", err) + } +} + +func TestEnsuringTheCommitGraphReportsEveryFailure(t *testing.T) { + boom := errors.New("boom") + for _, tt := range []struct { + name string + setup func(t *testing.T, r *testRepo) + }{ + {"reading the graph settings", func(t *testing.T, r *testRepo) { + r.appendConfig("[core]\n\tcommitGraph = maybe\n") + r.repo = r.reopen() + }}, + {"reading gc.writeCommitGraph", func(t *testing.T, r *testRepo) { + r.appendConfig("[gc]\n\twriteCommitGraph = maybe\n") + r.repo = r.reopen() + }}, + {"reading the shallow file", func(t *testing.T, r *testRepo) { + if err := os.MkdirAll(filepath.Join(r.repo.CommonDir(), "shallow"), 0o777); err != nil { + t.Fatal(err) + } + }}, + {"opening the database", func(t *testing.T, r *testRepo) { + swapMaint(t, &odbOpen, func(string, odb.Options) (*odb.DB, error) { return nil, boom }) + }}, + {"opening the references", func(t *testing.T, r *testRepo) { + swapMaint(t, &refsOpen, func(refs.Options) (*refs.Store, error) { return nil, boom }) + }}, + {"listing the references", func(t *testing.T, r *testRepo) { + if err := os.WriteFile(filepath.Join(r.repo.CommonDir(), "packed-refs"), []byte("garbage\n"), 0o666); err != nil { + t.Fatal(err) + } + }}, + {"resolving HEAD", func(t *testing.T, r *testRepo) { + if err := os.WriteFile(filepath.Join(r.repo.GitDir(), "HEAD"), []byte("garbage\n"), 0o666); err != nil { + t.Fatal(err) + } + }}, + {"reading a commit that does not parse", func(t *testing.T, r *testRepo) { + broken, err := r.db().Put(object.TypeCommit, []byte("not a commit")) + if err != nil { + t.Fatal(err) + } + setMaintRef(t, r, refs.BranchName("broken"), broken) + }}, + {"reading a commit", func(t *testing.T, r *testRepo) { + setMaintRef(t, r, refs.BranchName("lost"), bogusObjectID(t, hash.SHA1)) + }}, + {"writing the file", func(t *testing.T, r *testRepo) { + swapMaint(t, &writeCommitGraphFile, func(string, hash.Format, []commitgraph.Commit, commitgraph.EncodeOptions) error { return boom }) + }}, + } { + t.Run(tt.name, func(t *testing.T) { + r := newTestRepo(t) + buildMaintHistory(t, r) + tt.setup(t, r) + + if _, err := EnsureCommitGraph(t.Context(), r.repo); err == nil { + t.Fatal("the failure was not reported") + } + }) + } +} From cbcd87b43448cd1c0eb7262428c8bf409233d4e6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=A7=D1=83=D0=BA=D0=B0=D0=BB=D0=B8=D0=BD=20=D0=92=D0=B0?= =?UTF-8?q?=D0=BB=D0=B5=D1=80=D0=B8=D0=B9?= Date: Fri, 16 Oct 2026 09:59:18 +0300 Subject: [PATCH 05/35] app: write the commit graph in the background when the opened repository has none --- internal/app/app.go | 4 ++ internal/app/graphwrite.go | 45 +++++++++++++ internal/app/graphwrite_test.go | 108 ++++++++++++++++++++++++++++++++ 3 files changed, 157 insertions(+) create mode 100644 internal/app/graphwrite.go create mode 100644 internal/app/graphwrite_test.go diff --git a/internal/app/app.go b/internal/app/app.go index 2ea66282..62e26ae6 100644 --- a/internal/app/app.go +++ b/internal/app/app.go @@ -149,6 +149,8 @@ type App struct { journalWG sync.WaitGroup journalPageSize int + graphWrite graphWriter + filesItems *datagrid.ObservableCollection readMu sync.Mutex @@ -728,6 +730,7 @@ func (a *App) ActivateRepository(id string) { a.startJournal() a.startWorking() a.startAutoFetch() + a.startGraphWrite(opened) } func (a *App) opened() *openedRepository { @@ -791,6 +794,7 @@ func (a *App) closeOpenRepository() { a.filesMu.Lock() a.mutedDirs = nil a.filesMu.Unlock() + a.stopGraphWrite() o := a.opened() if o == nil { return diff --git a/internal/app/graphwrite.go b/internal/app/graphwrite.go new file mode 100644 index 00000000..af6517fe --- /dev/null +++ b/internal/app/graphwrite.go @@ -0,0 +1,45 @@ +package app + +import ( + "context" + "errors" + "sync" + + "github.com/oops1/gogit/internal/gitcore/ops" +) + +var ensureCommitGraph = ops.EnsureCommitGraph + +type graphWriter struct { + mu sync.Mutex + cancel context.CancelFunc + wg sync.WaitGroup +} + +func (a *App) startGraphWrite(o *openedRepository) { + ctx, cancel := context.WithCancel(context.Background()) + a.graphWrite.mu.Lock() + a.graphWrite.cancel = cancel + a.graphWrite.mu.Unlock() + a.graphWrite.wg.Go(func() { + written, err := ensureCommitGraph(ctx, o.repo) + switch { + case errors.Is(err, context.Canceled): + case err != nil: + a.log.Warn("write commit graph failed", "path", o.path, "error", err) + case written > 0: + a.log.Info("commit graph written", "path", o.path, "commits", written) + } + }) +} + +func (a *App) stopGraphWrite() { + a.graphWrite.mu.Lock() + cancel := a.graphWrite.cancel + a.graphWrite.cancel = nil + a.graphWrite.mu.Unlock() + if cancel != nil { + cancel() + } + a.graphWrite.wg.Wait() +} diff --git a/internal/app/graphwrite_test.go b/internal/app/graphwrite_test.go new file mode 100644 index 00000000..b128b83d --- /dev/null +++ b/internal/app/graphwrite_test.go @@ -0,0 +1,108 @@ +package app + +import ( + "bytes" + "context" + "errors" + "log/slog" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/oops1/gogit/internal/config" + gitrepo "github.com/oops1/gogit/internal/gitcore/repo" +) + +func newLoggedGraphApp(t *testing.T, level slog.Level) (*App, *bytes.Buffer) { + t.Helper() + target := filepath.Join(t.TempDir(), "main") + initTestRepo(t, target) + cfg := config.Default() + cfg.Repositories = []config.Repository{{ID: "r1", Name: "Main", Path: target}} + var buf bytes.Buffer + logger := slog.New(slog.NewTextHandler(&buf, &slog.HandlerOptions{Level: level})) + a, err := New(cfg, config.Paths{Dir: t.TempDir()}, logger) + if err != nil { + t.Fatal(err) + } + t.Cleanup(a.Close) + return a, &buf +} + +func TestOpeningARepositoryWritesItsCommitGraphInTheBackground(t *testing.T) { + a, _, local := cloneForDivergence(t) + a.graphWrite.wg.Wait() + + if _, err := os.Stat(filepath.Join(local, ".git", "objects", "info", "commit-graph")); err != nil { + t.Fatalf("the commit graph was not written: %v", err) + } +} + +func TestTheCommitGraphWriteIsLoggedWhenItProducesOne(t *testing.T) { + a, buf := newLoggedGraphApp(t, slog.LevelInfo) + previous := ensureCommitGraph + ensureCommitGraph = func(context.Context, *gitrepo.Repository) (int, error) { return 7, nil } + t.Cleanup(func() { ensureCommitGraph = previous }) + + a.ActivateRepository("r1") + a.graphWrite.wg.Wait() + + if !strings.Contains(buf.String(), "commit graph written") || !strings.Contains(buf.String(), "commits=7") { + t.Fatalf("the write was not logged: %s", buf.String()) + } +} + +func TestTheCommitGraphWriteIsSilentWhenThereIsNothingToWrite(t *testing.T) { + a, buf := newLoggedGraphApp(t, slog.LevelDebug) + previous := ensureCommitGraph + ensureCommitGraph = func(context.Context, *gitrepo.Repository) (int, error) { return 0, nil } + t.Cleanup(func() { ensureCommitGraph = previous }) + + a.ActivateRepository("r1") + a.graphWrite.wg.Wait() + + if strings.Contains(buf.String(), "commit graph") { + t.Fatalf("an empty write was logged: %s", buf.String()) + } +} + +func TestAFailedCommitGraphWriteIsLoggedAsAWarning(t *testing.T) { + a, buf := newLoggedGraphApp(t, slog.LevelWarn) + previous := ensureCommitGraph + ensureCommitGraph = func(context.Context, *gitrepo.Repository) (int, error) { return 0, errors.New("disk full") } + t.Cleanup(func() { ensureCommitGraph = previous }) + + a.ActivateRepository("r1") + a.graphWrite.wg.Wait() + + if !strings.Contains(buf.String(), "write commit graph failed") || !strings.Contains(buf.String(), "disk full") { + t.Fatalf("the failure was not logged: %s", buf.String()) + } +} + +func TestClosingTheRepositoryCancelsARunningCommitGraphWriteWithoutLoggingIt(t *testing.T) { + a, buf := newLoggedGraphApp(t, slog.LevelDebug) + started := make(chan struct{}) + previous := ensureCommitGraph + ensureCommitGraph = func(ctx context.Context, _ *gitrepo.Repository) (int, error) { + close(started) + <-ctx.Done() + return 0, ctx.Err() + } + t.Cleanup(func() { ensureCommitGraph = previous }) + a.ActivateRepository("r1") + <-started + + a.CloseRepository() + + if strings.Contains(buf.String(), "write commit graph failed") { + t.Fatalf("a cancelled write was logged as a failure: %s", buf.String()) + } +} + +func TestStoppingACommitGraphWriteThatNeverStartedDoesNothing(t *testing.T) { + a, _ := newLoggedGraphApp(t, slog.LevelWarn) + + a.stopGraphWrite() +} From 33039f005c11b98e7419b03e80eb0511b3b46124 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=A7=D1=83=D0=BA=D0=B0=D0=BB=D0=B8=D0=BD=20=D0=92=D0=B0?= =?UTF-8?q?=D0=BB=D0=B5=D1=80=D0=B8=D0=B9?= Date: Fri, 16 Oct 2026 10:00:07 +0300 Subject: [PATCH 06/35] changes: sort the working status once and build the rows from the sorted entries --- internal/app/working.go | 2 +- internal/ui/changes/files.go | 5 ++++- internal/ui/changes/files_test.go | 36 +++++++++++++++++++++++++++++++ 3 files changed, 41 insertions(+), 2 deletions(-) diff --git a/internal/app/working.go b/internal/app/working.go index 021dfd59..3219443b 100644 --- a/internal/app/working.go +++ b/internal/app/working.go @@ -109,8 +109,8 @@ func (a *App) runWorking(ctx context.Context, wt *worktree.Worktree) { } return } - rows := changes.WorkingRows(status) entries := changes.SortEntries(status.Entries) + rows := changes.WorkingRowsOfSorted(entries) if len(entries) > changes.MaxFiles { entries = entries[:changes.MaxFiles] } diff --git a/internal/ui/changes/files.go b/internal/ui/changes/files.go index 1917e48f..a76e64a8 100644 --- a/internal/ui/changes/files.go +++ b/internal/ui/changes/files.go @@ -113,7 +113,10 @@ func workingRank(e worktree.Entry) int { } func WorkingRows(s worktree.Status) []Row { - sorted := SortEntries(s.Entries) + return WorkingRowsOfSorted(SortEntries(s.Entries)) +} + +func WorkingRowsOfSorted(sorted []worktree.Entry) []Row { limit := len(sorted) truncated := limit > MaxFiles if truncated { diff --git a/internal/ui/changes/files_test.go b/internal/ui/changes/files_test.go index 596869db..50919c83 100644 --- a/internal/ui/changes/files_test.go +++ b/internal/ui/changes/files_test.go @@ -400,3 +400,39 @@ func TestSizeStringIsEmptyForZeroOrNegativeSizes(t *testing.T) { t.Fatalf("sizeString(5) = %q, want 5", got) } } + +func TestWorkingRowsOfSortedKeepsTheOrderItIsGiven(t *testing.T) { + registerStateStrings(t) + entries := []worktree.Entry{ + {Path: "z.txt", Staged: worktree.StatusUnmodified, Unstaged: worktree.StatusModified}, + {Path: "a.txt", Staged: worktree.StatusUnmodified, Unstaged: worktree.StatusModified}, + } + + rows := WorkingRowsOfSorted(entries) + + if len(rows) != 2 || rows[0].RelPath != "z.txt" || rows[1].RelPath != "a.txt" { + t.Fatalf("rows = %+v, want the given order z.txt then a.txt", rows) + } +} + +func TestWorkingRowsAreTheRowsOfTheSortedEntries(t *testing.T) { + registerStateStrings(t) + status := worktree.Status{Entries: []worktree.Entry{ + {Path: "untracked.txt", Staged: worktree.StatusUnmodified, Unstaged: worktree.StatusUntracked}, + {Path: "staged.txt", Staged: worktree.StatusAdded, Unstaged: worktree.StatusUnmodified}, + {Path: "b.txt", Staged: worktree.StatusUnmodified, Unstaged: worktree.StatusModified}, + {Path: "a.txt", Staged: worktree.StatusUnmodified, Unstaged: worktree.StatusModified}, + }} + + got := WorkingRows(status) + want := WorkingRowsOfSorted(SortEntries(status.Entries)) + + if len(got) != len(want) { + t.Fatalf("rows = %d, want %d", len(got), len(want)) + } + for i := range want { + if got[i] != want[i] { + t.Fatalf("rows[%d] = %+v, want %+v", i, got[i], want[i]) + } + } +} From 8122a7dd31863f2ba73f8d51830adca171e896cf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=A7=D1=83=D0=BA=D0=B0=D0=BB=D0=B8=D0=BD=20=D0=92=D0=B0?= =?UTF-8?q?=D0=BB=D0=B5=D1=80=D0=B8=D0=B9?= Date: Fri, 16 Oct 2026 10:07:14 +0300 Subject: [PATCH 07/35] app: restart the journal on refresh only when what it is built from has changed --- internal/app/app.go | 15 +++- internal/app/journalkey.go | 53 ++++++++++++ internal/app/journalkey_test.go | 148 ++++++++++++++++++++++++++++++++ internal/app/opened.go | 3 +- internal/app/refresh_test.go | 2 +- 5 files changed, 217 insertions(+), 4 deletions(-) create mode 100644 internal/app/journalkey.go create mode 100644 internal/app/journalkey_test.go diff --git a/internal/app/app.go b/internal/app/app.go index 62e26ae6..284b09a2 100644 --- a/internal/app/app.go +++ b/internal/app/app.go @@ -499,7 +499,7 @@ func NewFromXAML(cfg *config.Config, paths config.Paths, xaml []byte, log *slog. a.handlers[CmdSearch] = a.openSearch a.handlers[CmdCompareFiles] = a.openCompare a.handlers[CmdResetLayout] = func() { _ = a.ResetLayout() } - a.handlers[CmdRefresh] = a.RefreshRepository + a.handlers[CmdRefresh] = a.reloadRepository a.handlers[CmdBlame] = a.blameSelectedFile a.handlers[CmdInvestigate] = a.investigateSelectedFile a.handlers[CmdRepoSettings] = a.openActiveRepoSettings @@ -728,6 +728,7 @@ func (a *App) ActivateRepository(id string) { a.reposView.Render(a.registry, a.repoTreeState()) a.startWatcher(opened.repo.Layout()) a.startJournal() + opened.journalKeeper.remember(a.currentJournalKey(snap)) a.startWorking() a.startAutoFetch() a.startGraphWrite(opened) @@ -806,6 +807,14 @@ func (a *App) closeOpenRepository() { } func (a *App) RefreshRepository() { + a.refreshRepository(false) +} + +func (a *App) reloadRepository() { + a.refreshRepository(true) +} + +func (a *App) refreshRepository(force bool) { o := a.opened() if o == nil { return @@ -828,7 +837,9 @@ func (a *App) RefreshRepository() { a.refreshRemoteState() a.refreshFlowState(o, snap.Current) a.reposView.Render(a.registry, a.repoTreeState()) - a.startJournal() + if force || o.journalKeeper.changed(a.currentJournalKey(snap)) { + a.startJournal() + } if a.commitIsSelected() { return } diff --git a/internal/app/journalkey.go b/internal/app/journalkey.go new file mode 100644 index 00000000..42556163 --- /dev/null +++ b/internal/app/journalkey.go @@ -0,0 +1,53 @@ +package app + +import ( + "crypto/sha256" + "fmt" + "strings" + "sync" + + "github.com/oops1/gogit/internal/ui/branches" +) + +type journalKeeper struct { + mu sync.Mutex + key string +} + +func (k *journalKeeper) changed(key string) bool { + k.mu.Lock() + defer k.mu.Unlock() + if k.key == key { + return false + } + k.key = key + return true +} + +func (k *journalKeeper) remember(key string) { + k.mu.Lock() + defer k.mu.Unlock() + k.key = key +} + +func journalKeyOf(snap branches.Snapshot, hasRemotes bool, logMaxCount int) string { + var text strings.Builder + fmt.Fprintf(&text, "%s|%t|%s|%t|%d\n", snap.Current, snap.Detached, snap.HeadID, hasRemotes, logMaxCount) + for _, branch := range snap.Local { + fmt.Fprintf(&text, "L|%s|%s|%s\n", branch.Name, branch.Target, branch.SymbolicTarget) + } + for _, remote := range snap.Remotes { + fmt.Fprintf(&text, "R|%s|%s\n", remote.Name, remote.Head) + for _, branch := range remote.Branches { + fmt.Fprintf(&text, "B|%s|%s\n", branch.Name, branch.Target) + } + } + for _, tag := range snap.Tags { + fmt.Fprintf(&text, "T|%s|%s|%s\n", tag.Name, tag.Target, tag.Peeled) + } + return fmt.Sprintf("%x", sha256.Sum256([]byte(text.String()))) +} + +func (a *App) currentJournalKey(snap branches.Snapshot) string { + return journalKeyOf(snap, a.State().HasRemotes, a.cfg.Git.LogMaxCount) +} diff --git a/internal/app/journalkey_test.go b/internal/app/journalkey_test.go new file mode 100644 index 00000000..dfa890ae --- /dev/null +++ b/internal/app/journalkey_test.go @@ -0,0 +1,148 @@ +package app + +import ( + "context" + "testing" + + "github.com/oops1/gogit/internal/gitcore/hash" + "github.com/oops1/gogit/internal/gitcore/refs" + "github.com/oops1/gogit/internal/gitcore/revision" + "github.com/oops1/gogit/internal/ui/branches" + "github.com/oops1/gogit/internal/ui/journal" +) + +func keySnapshot(t *testing.T) branches.Snapshot { + t.Helper() + return branches.Snapshot{ + Current: "main", + HeadID: memoID(t, "11"), + Local: []branches.Branch{ + {Name: refs.BranchName("main"), Target: memoID(t, "11"), Upstream: refs.RemoteBranchName("origin", "main")}, + }, + Remotes: []branches.Remote{{ + Name: "origin", + Head: refs.RemoteBranchName("origin", "main"), + Branches: []branches.Branch{{Name: refs.RemoteBranchName("origin", "main"), Target: memoID(t, "22")}}, + }}, + Tags: []branches.Tag{{Name: refs.TagName("v1"), Target: memoID(t, "33"), Peeled: memoID(t, "44")}}, + } +} + +func TestTheJournalKeyFollowsEverythingTheJournalIsBuiltFrom(t *testing.T) { + base := journalKeyOf(keySnapshot(t), true, 500) + tests := []struct { + name string + change func(s *branches.Snapshot) (hasRemotes bool, logMax int) + }{ + {"the current branch", func(s *branches.Snapshot) (bool, int) { s.Current = "dev"; return true, 500 }}, + {"a detached head", func(s *branches.Snapshot) (bool, int) { s.Detached = true; return true, 500 }}, + {"the head commit", func(s *branches.Snapshot) (bool, int) { s.HeadID = memoID(t, "99"); return true, 500 }}, + {"a local branch tip", func(s *branches.Snapshot) (bool, int) { s.Local[0].Target = memoID(t, "99"); return true, 500 }}, + {"a symbolic branch", func(s *branches.Snapshot) (bool, int) { + s.Local[0].SymbolicTarget = refs.BranchName("x") + return true, 500 + }}, + {"a new local branch", func(s *branches.Snapshot) (bool, int) { + s.Local = append(s.Local, branches.Branch{Name: refs.BranchName("new"), Target: memoID(t, "55")}) + return true, 500 + }}, + {"a remote head", func(s *branches.Snapshot) (bool, int) { + s.Remotes[0].Head = refs.RemoteBranchName("origin", "dev") + return true, 500 + }}, + {"a remote branch tip", func(s *branches.Snapshot) (bool, int) { + s.Remotes[0].Branches[0].Target = memoID(t, "99") + return true, 500 + }}, + {"a new remote", func(s *branches.Snapshot) (bool, int) { + s.Remotes = append(s.Remotes, branches.Remote{Name: "fork"}) + return true, 500 + }}, + {"a tag target", func(s *branches.Snapshot) (bool, int) { s.Tags[0].Target = memoID(t, "99"); return true, 500 }}, + {"a peeled tag", func(s *branches.Snapshot) (bool, int) { s.Tags[0].Peeled = memoID(t, "99"); return true, 500 }}, + {"the presence of remotes", func(s *branches.Snapshot) (bool, int) { return false, 500 }}, + {"the log length", func(s *branches.Snapshot) (bool, int) { return true, 1000 }}, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + snap := keySnapshot(t) + hasRemotes, logMax := tc.change(&snap) + + if journalKeyOf(snap, hasRemotes, logMax) == base { + t.Fatalf("the key did not change with %s", tc.name) + } + }) + } +} + +func TestTheJournalKeyIgnoresWhatTheJournalIsNotBuiltFrom(t *testing.T) { + base := journalKeyOf(keySnapshot(t), true, 500) + snap := keySnapshot(t) + snap.Local[0].Upstream = refs.RemoteBranchName("origin", "other") + snap.Stashes = []branches.Stash{{Index: 0, Commit: hash.ObjectID{1}, Message: "wip"}} + + if journalKeyOf(snap, true, 500) != base { + t.Fatal("the key changed with an upstream name or a stash") + } +} + +func TestTheJournalKeeperReportsOnlyChanges(t *testing.T) { + var keeper journalKeeper + + if !keeper.changed("a") || keeper.changed("a") || !keeper.changed("b") { + t.Fatal("the keeper did not report exactly the changes") + } + keeper.remember("c") + if keeper.changed("c") { + t.Fatal("a remembered key was reported as a change") + } +} + +func countJournalRestarts(t *testing.T) *int { + t.Helper() + restarts := new(int) + previous := newJournalPager + newJournalPager = func(ctx context.Context, source revision.Context, opts journal.Options) journalPager { + *restarts++ + return previous(ctx, source, opts) + } + t.Cleanup(func() { newJournalPager = previous }) + return restarts +} + +func TestARefreshWithUnchangedRefsDoesNotRestartTheJournal(t *testing.T) { + a, _, _ := cloneForDivergence(t) + restarts := countJournalRestarts(t) + + a.RefreshRepository() + a.RefreshRepository() + a.refreshAtOnce() + + if *restarts != 0 { + t.Fatalf("the journal was restarted %d times while no ref moved, want none", *restarts) + } +} + +func TestARefreshAfterABranchMovedRestartsTheJournalOnce(t *testing.T) { + a, _, local := cloneForDivergence(t) + restarts := countJournalRestarts(t) + addLocalCommitWithMessage(t, local, "main", "second.txt", "second\n", "second") + + a.RefreshRepository() + a.RefreshRepository() + + if *restarts != 1 { + t.Fatalf("the journal was restarted %d times after one ref moved, want once", *restarts) + } +} + +func TestTheRefreshCommandAlwaysReloadsTheJournal(t *testing.T) { + a, _, _ := cloneForDivergence(t) + restarts := countJournalRestarts(t) + + a.Dispatch(CmdRefresh) + + if *restarts != 1 { + t.Fatalf("the journal was restarted %d times by the refresh command, want once", *restarts) + } +} diff --git a/internal/app/opened.go b/internal/app/opened.go index 1dfbfb5e..13f95ee3 100644 --- a/internal/app/opened.go +++ b/internal/app/opened.go @@ -26,7 +26,8 @@ type openedRepository struct { wtMu sync.RWMutex worktree *worktree.Worktree - divergence divergenceMemo + divergence divergenceMemo + journalKeeper journalKeeper graphMu sync.Mutex graphKey string diff --git a/internal/app/refresh_test.go b/internal/app/refresh_test.go index 22a1cd21..24118a56 100644 --- a/internal/app/refresh_test.go +++ b/internal/app/refresh_test.go @@ -103,7 +103,7 @@ func TestARefreshPutsTheJournalSelectionBackOnTheShownCommitWithoutReloadingIt(t waitForDetails(t, a, row.ID) runOnDispatcher(t, a, func() { a.journalGrid().Grid.SetSelectedIndexQuiet(0) }) - runOnDispatcher(t, a, a.RefreshRepository) + runOnDispatcher(t, a, a.reloadRepository) waitOnDispatcher(t, a, func() bool { return a.journalView.Count() >= 2 }) waitOnDispatcher(t, a, func() bool { From a47590ccaa4a06aba9631c3f179f0dec67ceb79b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=A7=D1=83=D0=BA=D0=B0=D0=BB=D0=B8=D0=BD=20=D0=92=D0=B0?= =?UTF-8?q?=D0=BB=D0=B5=D1=80=D0=B8=D0=B9?= Date: Fri, 16 Oct 2026 11:57:51 +0300 Subject: [PATCH 08/35] pack: keep the index name table in memory so a lookup stops reading the file for every probe --- internal/gitcore/odb/db_test.go | 9 ++ internal/gitcore/odb/freshen_test.go | 5 +- internal/gitcore/odb/write_test.go | 10 +- internal/gitcore/pack/index.go | 25 ++++ internal/gitcore/pack/prefix_test.go | 1 + internal/gitcore/pack/residentnames_test.go | 158 ++++++++++++++++++++ internal/gitcore/pack/reuse_test.go | 2 + internal/gitcore/pack/stream_test.go | 2 + 8 files changed, 200 insertions(+), 12 deletions(-) create mode 100644 internal/gitcore/pack/residentnames_test.go diff --git a/internal/gitcore/odb/db_test.go b/internal/gitcore/odb/db_test.go index f66c775f..f18cbec5 100644 --- a/internal/gitcore/odb/db_test.go +++ b/internal/gitcore/odb/db_test.go @@ -21,6 +21,15 @@ func newFixtureDB(t testing.TB) *DB { return openDB(t, objects, Options{}) } +func packedPayload(t testing.TB) (object.Type, []byte) { + t.Helper() + kind, data, err := newFixtureDB(t).Get(packFixtureObjects(t)[0].id) + if err != nil { + t.Fatalf("Get returned error %v", err) + } + return kind, data +} + func TestOpenReadsEveryPackedObject(t *testing.T) { db := newFixtureDB(t) for _, want := range packFixtureObjects(t) { diff --git a/internal/gitcore/odb/freshen_test.go b/internal/gitcore/odb/freshen_test.go index 7ae34223..1d1c7893 100644 --- a/internal/gitcore/odb/freshen_test.go +++ b/internal/gitcore/odb/freshen_test.go @@ -172,10 +172,7 @@ func TestPutReportsAPackLookupFailureInAnAlternate(t *testing.T) { copyFixturePacks(t, shared) writeAlternates(t, main, shared) db := openDB(t, main, Options{}) - kind, data, err := db.Get(packFixtureObjects(t)[0].id) - if err != nil { - t.Fatalf("Get returned error %v", err) - } + kind, data := packedPayload(t) closePackIndexes(t, db.Alternates()[0]) if _, err := db.Put(kind, data); err == nil { diff --git a/internal/gitcore/odb/write_test.go b/internal/gitcore/odb/write_test.go index d613f730..9ccf2085 100644 --- a/internal/gitcore/odb/write_test.go +++ b/internal/gitcore/odb/write_test.go @@ -116,10 +116,7 @@ func TestPutRejectsUnknownTypes(t *testing.T) { func TestPutReportsLookupFailures(t *testing.T) { db := newFixtureDB(t) - kind, data, err := db.Get(packFixtureObjects(t)[0].id) - if err != nil { - t.Fatalf("Get returned error %v", err) - } + kind, data := packedPayload(t) closePackIndexes(t, db) if _, err := db.Put(kind, data); err == nil { t.Fatal("Put ignored a pack index it could not read") @@ -300,10 +297,7 @@ func TestWriterReportsStreamFailures(t *testing.T) { func TestWriterReportsLookupFailures(t *testing.T) { db := newFixtureDB(t) - kind, data, err := db.Get(packFixtureObjects(t)[0].id) - if err != nil { - t.Fatalf("Get returned error %v", err) - } + kind, data := packedPayload(t) writer, err := db.Writer(kind, int64(len(data))) if err != nil { t.Fatalf("Writer returned error %v", err) diff --git a/internal/gitcore/pack/index.go b/internal/gitcore/pack/index.go index 6af1500e..1fcc26e3 100644 --- a/internal/gitcore/pack/index.go +++ b/internal/gitcore/pack/index.go @@ -8,6 +8,7 @@ import ( "io" "iter" "os" + "sync" "github.com/oops1/gogit/internal/gitcore/hash" ) @@ -28,6 +29,8 @@ const ( namesChunk = 512 ) +var residentNamesLimit = int64(32 << 20) + var indexMagic = []byte{0xff, 0x74, 0x4f, 0x63} type Entry struct { @@ -54,6 +57,9 @@ type Index struct { largeCount int64 pack hash.ObjectID self hash.ObjectID + + namesOnce sync.Once + resident []byte } func OpenIndex(path string) (*Index, error) { @@ -379,8 +385,27 @@ func (x *Index) verifyOrder() error { return nil } +func (x *Index) residentNames() []byte { + x.namesOnce.Do(func() { + span := int64(x.count-1)*x.nameStride + hash.Size + if x.count == 0 || span > residentNamesLimit { + return + } + table := make([]byte, span) + if readFull(x.source, table, x.names) == nil { + x.resident = table + } + }) + return x.resident +} + func (x *Index) idAt(position int) (hash.ObjectID, error) { var id hash.ObjectID + if table := x.residentNames(); table != nil && position >= 0 && position < x.count { + at := int64(position) * x.nameStride + copy(id[:], table[at:at+hash.Size]) + return id, nil + } if err := readFull(x.source, id[:], x.names+int64(position)*x.nameStride); err != nil { return hash.Zero, err } diff --git a/internal/gitcore/pack/prefix_test.go b/internal/gitcore/pack/prefix_test.go index 55674e44..400b9e42 100644 --- a/internal/gitcore/pack/prefix_test.go +++ b/internal/gitcore/pack/prefix_test.go @@ -109,6 +109,7 @@ func TestPrefixStopsWhenLowerBoundFails(t *testing.T) { } func TestPrefixStopsWhenIterationFails(t *testing.T) { + withoutResidentNames(t) ids := make([]hash.ObjectID, 8) for i := range ids { ids[i] = idBytes(byte((i + 1) * 0x10)) diff --git a/internal/gitcore/pack/residentnames_test.go b/internal/gitcore/pack/residentnames_test.go new file mode 100644 index 00000000..07675dae --- /dev/null +++ b/internal/gitcore/pack/residentnames_test.go @@ -0,0 +1,158 @@ +package pack + +import ( + "bytes" + "errors" + "io" + "testing" + + "github.com/oops1/gogit/internal/gitcore/hash" +) + +var errNameTableRead = errors.New("pack: injected name table failure") + +type countingSource struct { + data *bytes.Reader + reads int + failBelow int + failOnce bool +} + +func (c *countingSource) ReadAt(p []byte, offset int64) (int, error) { + c.reads++ + if c.failOnce && len(p) > c.failBelow { + c.failOnce = false + return 0, errNameTableRead + } + return c.data.ReadAt(p, offset) +} + +func withoutResidentNames(t *testing.T) { + t.Helper() + previous := residentNamesLimit + residentNamesLimit = 0 + t.Cleanup(func() { residentNamesLimit = previous }) +} + +func indexOverCountingSource(t *testing.T, raw []byte) (*Index, *countingSource) { + t.Helper() + source := &countingSource{data: bytes.NewReader(raw)} + index, err := NewIndex(source, int64(len(raw))) + if err != nil { + t.Fatalf("NewIndex returned error %v", err) + } + source.reads = 0 + return index, source +} + +func residentFixture(t *testing.T) ([]byte, []Entry, *Index) { + t.Helper() + entries, modern := fixtureEntries(t, fixtureName(t, offsetPack)) + raw, err := io.ReadAll(io.NewSectionReader(modern.source, 0, modern.size)) + if err != nil { + t.Fatalf("ReadAll returned error %v", err) + } + return raw, entries, modern +} + +func TestFindReadsTheNameTableOnceAndThenSearchesInMemory(t *testing.T) { + raw, entries, _ := residentFixture(t) + index, source := indexOverCountingSource(t, raw) + + for range 50 { + for _, entry := range entries { + position, ok, err := index.Position(entry.ID) + if err != nil || !ok { + t.Fatalf("Position(%s) = %d, %v, %v", entry.ID, position, ok, err) + } + } + if _, ok, err := index.Position(hash.ObjectID{0xee}); ok || err != nil { + t.Fatalf("Position of an unknown object = %v, %v", ok, err) + } + } + + if source.reads != 1 { + t.Fatalf("the index source was read %d times, want only the one that loads the name table", source.reads) + } +} + +func TestResidentNamesGiveTheSameAnswersAsReadingEachName(t *testing.T) { + raw, entries, _ := residentFixture(t) + resident, _ := indexOverCountingSource(t, raw) + withoutResidentNames(t) + reading, _ := indexOverCountingSource(t, raw) + probes := []hash.ObjectID{{0x00}, {0xff}, {0xee}} + for _, entry := range entries { + probes = append(probes, entry.ID) + } + + for _, probe := range probes { + wantPosition, wantOK, wantErr := reading.Position(probe) + position, ok, err := resident.Position(probe) + if position != wantPosition || ok != wantOK || !errors.Is(err, wantErr) { + t.Fatalf("Position(%s) = %d, %v, %v; reading each name gives %d, %v, %v", probe, position, ok, err, wantPosition, wantOK, wantErr) + } + } +} + +func TestVersionOneIndexKeepsItsNamesResidentToo(t *testing.T) { + entries, modern := fixtureEntries(t, fixtureName(t, offsetPack)) + raw := encodeIndexVersionOne(entries, modern.PackHash()) + index, source := indexOverCountingSource(t, raw) + + for _, entry := range entries { + if position, ok, err := index.Position(entry.ID); err != nil || !ok { + t.Fatalf("Position(%s) = %d, %v, %v", entry.ID, position, ok, err) + } + } + + if source.reads != 1 { + t.Fatalf("the version 1 index was read %d times, want only the one that loads the names", source.reads) + } +} + +func TestIndexFallsBackToReadingEachNameWhenTheTableCannotBeLoaded(t *testing.T) { + raw, entries, _ := residentFixture(t) + index, source := indexOverCountingSource(t, raw) + source.failOnce = true + source.failBelow = hash.Size + + for _, entry := range entries { + if _, ok, err := index.Position(entry.ID); err != nil || !ok { + t.Fatalf("Position(%s) = %v, %v after the table failed to load", entry.ID, ok, err) + } + } + + if source.reads <= len(entries) { + t.Fatalf("the index was read %d times, want a read per probe once the table could not be loaded", source.reads) + } +} + +func TestIndexTooLargeToKeepResidentIsReadNameByName(t *testing.T) { + raw, entries, _ := residentFixture(t) + previous := residentNamesLimit + residentNamesLimit = hash.Size + t.Cleanup(func() { residentNamesLimit = previous }) + index, source := indexOverCountingSource(t, raw) + + for _, entry := range entries { + if _, ok, err := index.Position(entry.ID); err != nil || !ok { + t.Fatalf("Position(%s) = %v, %v", entry.ID, ok, err) + } + } + + if source.reads <= len(entries) { + t.Fatalf("the index was read %d times, want a read per probe above the resident limit", source.reads) + } +} + +func TestAnIndexWithoutObjectsHasNoNamesToKeepResident(t *testing.T) { + index := indexOf(t, buildIndex(nil, hash.ObjectID{1})) + + if _, ok, err := index.Position(hash.ObjectID{0x01}); ok || err != nil { + t.Fatalf("Position in an empty index = %v, %v", ok, err) + } + if index.residentNames() != nil { + t.Fatal("an empty index kept a name table") + } +} diff --git a/internal/gitcore/pack/reuse_test.go b/internal/gitcore/pack/reuse_test.go index 1d052137..c454a771 100644 --- a/internal/gitcore/pack/reuse_test.go +++ b/internal/gitcore/pack/reuse_test.go @@ -385,6 +385,7 @@ func TestReuseFindLocatesAStoredDeltaAndItsBase(t *testing.T) { } func TestReuseFindReportsWhatItCannotRead(t *testing.T) { + withoutResidentNames(t) fixture := newFindFixture(t) for _, tt := range []struct { name string @@ -521,6 +522,7 @@ func TestWritePackCopiesALargeStoredObjectWholesale(t *testing.T) { } func TestWritePackReportsFailuresAroundReusedAndSearchedDeltas(t *testing.T) { + withoutResidentNames(t) plain := newFakeSource() big, small := deltaPair(plain) opts := WriteOptions{Window: 10, Depth: 50} diff --git a/internal/gitcore/pack/stream_test.go b/internal/gitcore/pack/stream_test.go index 25bc9df4..cf0f7790 100644 --- a/internal/gitcore/pack/stream_test.go +++ b/internal/gitcore/pack/stream_test.go @@ -59,6 +59,7 @@ func TestPackInfoAtDescribesDeltasWithoutResolvingThem(t *testing.T) { } func TestPackInfoAtReportsBrokenDeltas(t *testing.T) { + withoutResidentNames(t) content := bytes.Repeat([]byte("broken info\n"), 30) builder := newPackBuilder() base := builder.addObject(t, KindBlob, content) @@ -246,6 +247,7 @@ func TestStoreStreamHoldsThePackUntilTheReaderCloses(t *testing.T) { } func TestStoreStreamReportsBrokenIndexesAndObjects(t *testing.T) { + withoutResidentNames(t) raw, offsets, _ := streamFixture(t) ids := []hash.ObjectID{{1}, {2}, {3}, {4}, {5}, {6}, {7}} entries := make([]Entry, len(ids)) From c058e8bff780c218500a26f3abdadb414b02850b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=A7=D1=83=D0=BA=D0=B0=D0=BB=D0=B8=D0=BD=20=D0=92=D0=B0?= =?UTF-8?q?=D0=BB=D0=B5=D1=80=D0=B8=D0=B9?= Date: Fri, 16 Oct 2026 12:00:17 +0300 Subject: [PATCH 09/35] pack: search the packfile that answered last before the others --- internal/gitcore/pack/store.go | 20 ++++- internal/gitcore/pack/storehot_test.go | 103 +++++++++++++++++++++++++ 2 files changed, 122 insertions(+), 1 deletion(-) create mode 100644 internal/gitcore/pack/storehot_test.go diff --git a/internal/gitcore/pack/store.go b/internal/gitcore/pack/store.go index 5b34b541..aecf95ec 100644 --- a/internal/gitcore/pack/store.go +++ b/internal/gitcore/pack/store.go @@ -72,6 +72,7 @@ type Store struct { mu sync.RWMutex files []*PackFile scanned directoryStamp + hot atomic.Pointer[PackFile] } type candidate struct { @@ -101,8 +102,9 @@ func (s *Store) Acquire() iter.Seq[*PackFile] { return func(yield func(*PackFile) bool) { files := s.acquire() defer release(files) - for _, file := range files { + for _, file := range s.preferHot(files) { if !yield(file) { + s.hot.Store(file) return } } @@ -246,6 +248,7 @@ func (s *Store) Reload() (bool, error) { changed = true } s.files = files + s.hot.Store(nil) return changed, nil } @@ -287,6 +290,21 @@ func (s *Store) acquire() []*PackFile { return s.files } +func (s *Store) preferHot(files []*PackFile) []*PackFile { + hot := s.hot.Load() + if hot == nil || len(files) < 2 || files[0] == hot { + return files + } + at := slices.Index(files, hot) + if at < 0 { + return files + } + ordered := make([]*PackFile, 0, len(files)) + ordered = append(ordered, hot) + ordered = append(ordered, files[:at]...) + return append(ordered, files[at+1:]...) +} + func release(files []*PackFile) { for _, file := range files { file.release() diff --git a/internal/gitcore/pack/storehot_test.go b/internal/gitcore/pack/storehot_test.go new file mode 100644 index 00000000..3a42dcc3 --- /dev/null +++ b/internal/gitcore/pack/storehot_test.go @@ -0,0 +1,103 @@ +package pack + +import ( + "testing" + + "github.com/oops1/gogit/internal/gitcore/hash" +) + +func twoPackStore(t *testing.T) (*Store, *PackFile, *PackFile) { + t.Helper() + names := fixtureNames(t) + store := openStore(t, copyFixtureDir(t, names...)) + files := store.Files() + if len(files) != 2 { + t.Fatalf("the store lists %d packfiles, want two", len(files)) + } + return store, files[0], files[1] +} + +func sharedObject(t *testing.T, first, second *PackFile) hash.ObjectID { + t.Helper() + entry, err := second.Index.EntryAt(0) + if err != nil { + t.Fatalf("EntryAt returned error %v", err) + } + for _, file := range []*PackFile{first, second} { + if _, found, err := file.Index.Lookup(entry.ID); !found || err != nil { + t.Fatalf("%s does not hold %s (%v, %v)", file.Name, entry.ID, found, err) + } + } + return entry.ID +} + +func TestStoreSearchesTheMostRecentlyUsedPackfileFirst(t *testing.T) { + store, newest, oldest := twoPackStore(t) + id := sharedObject(t, newest, oldest) + if holder, _, _ := store.Holder(id); holder != newest.Name { + t.Fatalf("before any hit the holder is %s, want the newest %s", holder, newest.Name) + } + + for file := range store.Acquire() { + if file == oldest { + break + } + } + + if holder, found, err := store.Holder(id); err != nil || !found || holder != oldest.Name { + t.Fatalf("after a hit in %s the holder is %q (%v, %v)", oldest.Name, holder, found, err) + } + if files := store.Files(); files[0] != newest || files[1] != oldest { + t.Fatalf("Files lists %s then %s, want the listing to stay newest first", files[0].Name, files[1].Name) + } +} + +func TestStoreKeepsTheOrderWhenNothingIsHotOrTheHotPackIsAlreadyFirst(t *testing.T) { + store, newest, oldest := twoPackStore(t) + files := store.Files() + + if got := store.preferHot(files); got[0] != newest || got[1] != oldest { + t.Fatalf("an order without a hot packfile changed to %s, %s", got[0].Name, got[1].Name) + } + store.hot.Store(newest) + if got := store.preferHot(files); got[0] != newest || got[1] != oldest { + t.Fatalf("an order that already starts with the hot packfile changed to %s, %s", got[0].Name, got[1].Name) + } + store.hot.Store(&PackFile{Name: "gone"}) + if got := store.preferHot(files); got[0] != newest || got[1] != oldest { + t.Fatalf("a hot packfile that is no longer listed changed the order to %s, %s", got[0].Name, got[1].Name) + } +} + +func TestStoreMovesTheHotPackfileToTheFrontWithoutLosingTheOthers(t *testing.T) { + store, newest, oldest := twoPackStore(t) + store.hot.Store(oldest) + + got := store.preferHot(store.Files()) + + if len(got) != 2 || got[0] != oldest || got[1] != newest { + t.Fatalf("the search order is %v, want the hot packfile first and the other after it", got) + } +} + +func TestStoreForgetsTheHotPackfileWhenItReloads(t *testing.T) { + store, _, oldest := twoPackStore(t) + store.hot.Store(oldest) + + if _, err := store.Reload(); err != nil { + t.Fatalf("Reload returned error %v", err) + } + + if store.hot.Load() != nil { + t.Fatal("the store kept pointing at a packfile after it reloaded") + } +} + +func TestStoreStillReportsAnUnknownObjectWhenAPackfileIsHot(t *testing.T) { + store, _, oldest := twoPackStore(t) + store.hot.Store(oldest) + + if _, found, err := store.Holder(hash.ObjectID{0xee}); found || err != nil { + t.Fatalf("Holder of an unknown object = %v, %v", found, err) + } +} From d73f543804b17fcf378d18e77006e9b48a3d8b37 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=A7=D1=83=D0=BA=D0=B0=D0=BB=D0=B8=D0=BD=20=D0=92=D0=B0?= =?UTF-8?q?=D0=BB=D0=B5=D1=80=D0=B8=D0=B9?= Date: Fri, 16 Oct 2026 12:06:51 +0300 Subject: [PATCH 10/35] worktree: add a fifty thousand file status benchmark with a fixture that builds in seconds --- internal/gitcore/worktree/bench_test.go | 52 +++++++++++++++++++++++++ 1 file changed, 52 insertions(+) diff --git a/internal/gitcore/worktree/bench_test.go b/internal/gitcore/worktree/bench_test.go index e6e08b26..0090fc9f 100644 --- a/internal/gitcore/worktree/bench_test.go +++ b/internal/gitcore/worktree/bench_test.go @@ -2,7 +2,12 @@ package worktree import ( "fmt" + "os" "testing" + + "github.com/oops1/gogit/internal/gitcore/hash" + "github.com/oops1/gogit/internal/gitcore/index" + "github.com/oops1/gogit/internal/gitcore/object" ) func newBenchRepo(b *testing.B, fileCount int) *testRepo { @@ -31,3 +36,50 @@ func BenchmarkStatusOfFiveThousandFiles(b *testing.B) { } } } + +func (r *testRepo) stageUnstored(rel, content string) { + r.t.Helper() + r.writeFile(rel, content) + fi, err := os.Lstat(r.path(rel)) + if err != nil { + r.t.Fatalf("Lstat returned error %v", err) + } + id, err := hash.Sum(hash.SHA1, "blob", []byte(content)) + if err != nil { + r.t.Fatalf("Sum returned error %v", err) + } + r.idx.Add(index.Entry{ + Path: rel, + Mode: object.ModeBlob, + ID: id, + Stat: index.Stat{MTime: fi.ModTime(), CTime: fi.ModTime(), Size: uint32(fi.Size())}, + }) +} + +func newLargeBenchRepo(b *testing.B, fileCount int) *testRepo { + b.Helper() + tr := newTestRepo(b) + for i := range fileCount { + rel := fmt.Sprintf("src/module%03d/pkg%02d/file%05d.go", i%64, i%16, i) + tr.stageUnstored(rel, fmt.Sprintf("package p\n\nconst N = %d\n", i)) + } + tr.commit("initial") + for i := range fileCount / 100 { + rel := fmt.Sprintf("src/module%03d/pkg%02d/file%05d.go", i%64, i%16, i) + tr.writeFile(rel, fmt.Sprintf("package p\n\nconst N = %d\n\nconst Changed = true\n", i)) + } + return tr +} + +func BenchmarkStatusOfFiftyThousandFiles(b *testing.B) { + tr := newLargeBenchRepo(b, 50000) + w := tr.open() + ctx := b.Context() + b.ReportAllocs() + b.ResetTimer() + for b.Loop() { + if _, err := w.Status(ctx); err != nil { + b.Fatalf("Status returned error %v", err) + } + } +} From 53a0229ac5af7438ef91b734b456b5067aa428aa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=A7=D1=83=D0=BA=D0=B0=D0=BB=D0=B8=D0=BD=20=D0=92=D0=B0?= =?UTF-8?q?=D0=BB=D0=B5=D1=80=D0=B8=D0=B9?= Date: Fri, 16 Oct 2026 12:06:51 +0300 Subject: [PATCH 11/35] worktree: list a directory once to state its tracked files and keep the stat for the result --- internal/gitcore/worktree/gitlinkstatus.go | 27 ++- internal/gitcore/worktree/statbatch_test.go | 220 ++++++++++++++++++++ internal/gitcore/worktree/status.go | 5 +- internal/gitcore/worktree/workingtree.go | 158 +++++++++++--- 4 files changed, 365 insertions(+), 45 deletions(-) create mode 100644 internal/gitcore/worktree/statbatch_test.go diff --git a/internal/gitcore/worktree/gitlinkstatus.go b/internal/gitcore/worktree/gitlinkstatus.go index 1e6c03e0..d70aa9f8 100644 --- a/internal/gitcore/worktree/gitlinkstatus.go +++ b/internal/gitcore/worktree/gitlinkstatus.go @@ -20,6 +20,8 @@ var ( type unstagedChange struct { code StatusCode submodule SubmoduleChange + stat workingStat + statted bool } type ignoreFlags struct { @@ -85,25 +87,32 @@ func (r gitlinkRules) flagsFor(path string) (ignoreFlags, error) { return ignoreFlagsOf(mode), nil } -func (w *Worktree) unstagedChangeOf(ctx context.Context, entry *index.Entry, rules gitlinkRules) (unstagedChange, error) { - code, err := w.compareToWorktree(entry) +func (w *Worktree) unstagedChangeOf(ctx context.Context, entry *index.Entry, rules gitlinkRules, listing directoryListing) (unstagedChange, error) { + code, info, err := w.compareToWorktree(entry, listing) + change := unstagedChange{code: code} + if info != nil { + change.stat, change.statted = workingStat{size: info.Size(), modTime: info.ModTime()}, true + } if err != nil || entry.SkipWorktree || !entry.Mode.IsSubmodule() { - return unstagedChange{code: code}, err + return change, err } flags, err := rules.flagsFor(entry.Path) switch { case err != nil: return unstagedChange{}, fmt.Errorf("%w: %s: %w", ErrReadSubmodule, entry.Path, err) case flags.all: - return unstagedChange{code: StatusUnmodified}, nil + change.code = StatusUnmodified + return change, nil case code != StatusUnmodified: - return unstagedChange{code: code}, nil + return change, nil } - change, err := w.gitlinkChange(ctx, entry, flags) - if err != nil || change == (SubmoduleChange{}) { - return unstagedChange{code: StatusUnmodified}, err + nested, err := w.gitlinkChange(ctx, entry, flags) + if err != nil || nested == (SubmoduleChange{}) { + change.code = StatusUnmodified + return change, err } - return unstagedChange{code: StatusModified, submodule: change}, nil + change.code, change.submodule = StatusModified, nested + return change, nil } func (w *Worktree) gitlinkChange(ctx context.Context, entry *index.Entry, flags ignoreFlags) (SubmoduleChange, error) { diff --git a/internal/gitcore/worktree/statbatch_test.go b/internal/gitcore/worktree/statbatch_test.go new file mode 100644 index 00000000..609d2a8e --- /dev/null +++ b/internal/gitcore/worktree/statbatch_test.go @@ -0,0 +1,220 @@ +package worktree + +import ( + "context" + "errors" + "fmt" + "io/fs" + "os" + "path/filepath" + "strings" + "sync/atomic" + "testing" + + "github.com/oops1/gogit/internal/gitcore/index" +) + +const batchedDirectory = "batched" + +func newBatchedRepo(t *testing.T, files int) *testRepo { + t.Helper() + tr := newTestRepo(t) + for i := range files { + tr.stage(fmt.Sprintf("%s/file%02d.txt", batchedDirectory, i), fmt.Sprintf("content %d\n", i)) + } + tr.stage("small/a.txt", "a\n") + tr.stage("small/b.txt", "b\n") + tr.commit("initial") + return tr +} + +func countLstatCalls(t *testing.T, prefix string) *atomic.Int64 { + t.Helper() + calls := new(atomic.Int64) + previous := fsLstatFile + fsLstatFile = func(root *os.Root, name string) (fs.FileInfo, error) { + if strings.HasPrefix(filepath.ToSlash(name), prefix) { + calls.Add(1) + } + return previous(root, name) + } + t.Cleanup(func() { fsLstatFile = previous }) + return calls +} + +func TestStatusReadsABigDirectoryOnceInsteadOfStatingEachFileInIt(t *testing.T) { + tr := newBatchedRepo(t, batchedStatMinimum+4) + w := tr.openWith(Options{IncludeUnmodified: true}) + inBatched := countLstatCalls(t, batchedDirectory+"/") + + status, err := w.Status(t.Context()) + + if err != nil { + t.Fatalf("Status returned error %v", err) + } + if calls := inBatched.Load(); calls != 0 { + t.Fatalf("Status stated %d files of a directory it had already listed, want none", calls) + } + var seen int + for _, entry := range status.Entries { + if strings.HasPrefix(entry.Path, batchedDirectory+"/") { + seen++ + if entry.Size == 0 || entry.ModTime.IsZero() { + t.Fatalf("%s has no size or time although the scan had them", entry.Path) + } + } + } + if seen != batchedStatMinimum+4 { + t.Fatalf("Status listed %d files of the directory, want %d", seen, batchedStatMinimum+4) + } +} + +func TestStatusStatesFilesOfSmallDirectoriesOneByOne(t *testing.T) { + tr := newBatchedRepo(t, batchedStatMinimum) + w := tr.open() + inSmall := countLstatCalls(t, "small/") + + if _, err := w.Status(t.Context()); err != nil { + t.Fatalf("Status returned error %v", err) + } + + if calls := inSmall.Load(); calls != 2 { + t.Fatalf("Status stated %d files of a two-file directory, want one each", calls) + } +} + +func TestStatusReportsAFileDeletedFromABatchedDirectory(t *testing.T) { + tr := newBatchedRepo(t, batchedStatMinimum+2) + tr.remove(batchedDirectory + "/file03.txt") + tr.writeFile(batchedDirectory+"/file04.txt", "changed in the working tree\n") + w := tr.open() + + status, err := w.Status(t.Context()) + + if err != nil { + t.Fatalf("Status returned error %v", err) + } + got := map[string]StatusCode{} + for _, entry := range status.Entries { + got[entry.Path] = entry.Unstaged + } + if got[batchedDirectory+"/file03.txt"] != StatusDeleted || got[batchedDirectory+"/file04.txt"] != StatusModified || len(got) != 2 { + t.Fatalf("Status reported %v, want one deleted and one modified file", got) + } +} + +func TestStatusStatesAFileTheDirectoryListingLacks(t *testing.T) { + tr := newBatchedRepo(t, 1) + w := tr.open() + entry, ok := w.currentIndex().Get(batchedDirectory+"/file00.txt", index.StageMerged) + if !ok { + t.Fatal("the file is not in the index") + } + + code, info, err := w.compareToWorktree(entry, directoryListing{}) + + if err != nil || code != StatusUnmodified || info == nil { + t.Fatalf("compareToWorktree = %v, %v, %v, want the file found by stating it", code, info, err) + } +} + +func TestStatusFallsBackToStatingWhenADirectoryCannotBeListed(t *testing.T) { + tr := newBatchedRepo(t, batchedStatMinimum) + w := tr.open() + previous := fsOpenDir + refused := false + fsOpenDir = func(root *os.Root, name string) (*os.File, error) { + if name == batchedDirectory && !refused { + refused = true + return nil, errors.New("listing refused") + } + return previous(root, name) + } + t.Cleanup(func() { fsOpenDir = previous }) + statted := countLstatCalls(t, batchedDirectory+"/") + + status, err := w.Status(t.Context()) + + if err != nil || len(status.Entries) != 0 { + t.Fatalf("Status = %v, %v, want a clean tree", status.Entries, err) + } + if calls := statted.Load(); calls != batchedStatMinimum { + t.Fatalf("Status stated %d files, want %d one by one", calls, batchedStatMinimum) + } +} + +type brokenDirEntry struct{ name string } + +func (e brokenDirEntry) Name() string { return e.name } +func (e brokenDirEntry) IsDir() bool { return false } +func (e brokenDirEntry) Type() fs.FileMode { return 0 } +func (e brokenDirEntry) Info() (fs.FileInfo, error) { return nil, errors.New("gone") } + +func TestDirectoryListingIgnoresAnEntryItCannotDescribe(t *testing.T) { + listing := directoryListing{"x": brokenDirEntry{name: "x"}} + + if info, ok := listing.info("x"); ok || info != nil { + t.Fatalf("info = %v, %v, want nothing for an entry whose Info fails", info, ok) + } + if _, ok := listing.info("absent"); ok { + t.Fatal("info found a name that is not listed") + } + if _, ok := directoryListing(nil).info("x"); ok { + t.Fatal("info found a name in a missing listing") + } +} + +func TestGroupingByDirectoryKeepsEachDirectoryTogether(t *testing.T) { + entries := []*index.Entry{ + {Path: "a.txt"}, {Path: "dir/one.txt"}, {Path: "dir/two.txt"}, {Path: "dir/sub/three.txt"}, {Path: "b.txt"}, + } + + groups := groupByDirectory(entries) + + sizes := map[int]int{} + for _, group := range groups { + sizes[len(group)]++ + dir := "" + for _, at := range group { + current := entries[at].Path[:strings.LastIndex(entries[at].Path, "/")+1] + if dir != "" && current != dir { + t.Fatalf("a group mixes %q and %q", dir, current) + } + dir = current + } + } + if len(groups) != 3 || sizes[2] != 2 || sizes[1] != 1 { + t.Fatalf("groups = %v, want the root pair, the dir pair and the nested single", groups) + } +} + +func TestStatusStopsWhenTheCallerGivesUpInTheMiddleOfAGroup(t *testing.T) { + tr := newBatchedRepo(t, batchedStatMinimum) + w := tr.open() + entries := make([]*index.Entry, 0, batchedStatMinimum) + for entry := range w.currentIndex().Entries() { + if strings.HasPrefix(entry.Path, batchedDirectory+"/") { + entries = append(entries, entry) + } + } + group := make([]int, len(entries)) + for at := range group { + group[at] = at + } + + err := w.scanGroup(newStepContext(0), entries, group, gitlinkRules{}, make([]unstagedChange, len(entries))) + + if !errors.Is(err, context.Canceled) { + t.Fatalf("scanGroup returned %v, want the cancellation", err) + } +} + +func TestStatusReportsACancelledContextAfterTheScan(t *testing.T) { + w := newBatchedRepo(t, 3).open() + ctx, cancel := context.WithCancel(t.Context()) + cancel() + + if _, err := w.unstagedStatuses(ctx, nil, gitlinkRules{}); !errors.Is(err, context.Canceled) { + t.Fatalf("unstagedStatuses returned %v, want the cancellation", err) + } +} diff --git a/internal/gitcore/worktree/status.go b/internal/gitcore/worktree/status.go index 86ef1b6b..70a8520b 100644 --- a/internal/gitcore/worktree/status.go +++ b/internal/gitcore/worktree/status.go @@ -108,10 +108,11 @@ func (w *Worktree) Status(ctx context.Context) (Status, error) { if err != nil { return Status{}, err } - unstaged, err := w.unstagedStatuses(ctx, mergedEntries, rules) + scan, err := w.unstagedStatuses(ctx, mergedEntries, rules) if err != nil { return Status{}, err } + unstaged := scan.changes var untracked []Entry if !w.hideUntracked { untracked, err = w.untrackedEntries(ctx, trackedDirs, trackedFiles) @@ -157,7 +158,7 @@ func (w *Worktree) Status(ctx context.Context) (Status, error) { result := Status{HeadBranch: branch, Detached: detached, Entries: make([]Entry, 0, len(combined))} for _, entry := range combined { - w.fillWorkingInfo(entry) + w.fillWorkingInfo(entry, scan.stats) entry.FilterUnsupported = !entry.IsDir && w.policy(entry.Path).FilterUnsupported() result.Entries = append(result.Entries, *entry) } diff --git a/internal/gitcore/worktree/workingtree.go b/internal/gitcore/worktree/workingtree.go index e676e204..3d06127a 100644 --- a/internal/gitcore/worktree/workingtree.go +++ b/internal/gitcore/worktree/workingtree.go @@ -6,88 +6,174 @@ import ( "fmt" "io/fs" "os" + "path" "path/filepath" "sync" + "time" "github.com/oops1/gogit/internal/gitcore/hash" "github.com/oops1/gogit/internal/gitcore/index" "github.com/oops1/gogit/internal/gitcore/object" ) +const batchedStatMinimum = 16 + var ( fsLstatFile = (*os.Root).Lstat fsReadlinkFile = (*os.Root).Readlink fsReadFileFile = (*os.Root).ReadFile ) -func (w *Worktree) unstagedStatuses(ctx context.Context, entries []*index.Entry, rules gitlinkRules) (map[string]unstagedChange, error) { - results := make(map[string]unstagedChange, len(entries)) +type workingStat struct { + size int64 + modTime time.Time +} + +type workingScan struct { + changes map[string]unstagedChange + stats map[string]workingStat +} + +type directoryListing map[string]fs.DirEntry + +func (l directoryListing) info(name string) (fs.FileInfo, bool) { + item, ok := l[name] + if !ok { + return nil, false + } + info, err := item.Info() + return info, err == nil +} + +func (w *Worktree) listDirectory(rel string) directoryListing { + items, err := w.readDir(rel) + if err != nil { + return nil + } + listing := make(directoryListing, len(items)) + for _, item := range items { + listing[item.Name()] = item + } + return listing +} + +func groupByDirectory(entries []*index.Entry) [][]int { + byDirectory := make(map[string][]int) + for at, entry := range entries { + dir := path.Dir(entry.Path) + byDirectory[dir] = append(byDirectory[dir], at) + } + groups := make([][]int, 0, len(byDirectory)) + for _, group := range byDirectory { + groups = append(groups, group) + } + return groups +} + +func (w *Worktree) unstagedStatuses(ctx context.Context, entries []*index.Entry, rules gitlinkRules) (workingScan, error) { + groups := groupByDirectory(entries) + queue := make(chan []int, len(groups)) + for _, group := range groups { + queue <- group + } + close(queue) + scanned := make([]unstagedChange, len(entries)) var ( - mu sync.Mutex wg sync.WaitGroup once sync.Once failure error ) fail := func(err error) { once.Do(func() { failure = err }) } - sem := make(chan struct{}, w.workers) - for _, entry := range entries { - if ctx.Err() != nil { - break - } - sem <- struct{}{} + for range min(w.workers, len(groups)) { wg.Go(func() { - defer func() { <-sem }() - change, err := w.unstagedChangeOf(ctx, entry, rules) - if err != nil { - fail(err) - return + for group := range queue { + if err := w.scanGroup(ctx, entries, group, rules, scanned); err != nil { + fail(err) + return + } } - if change.code == StatusUnmodified { - return - } - mu.Lock() - results[entry.Path] = change - mu.Unlock() }) } wg.Wait() if failure != nil { - return nil, failure + return workingScan{}, failure } if err := ctx.Err(); err != nil { - return nil, err + return workingScan{}, err + } + scan := workingScan{ + changes: make(map[string]unstagedChange), + stats: make(map[string]workingStat, len(entries)), } - return results, nil + for at, change := range scanned { + if change.code != StatusUnmodified { + scan.changes[entries[at].Path] = change + } + if change.statted { + scan.stats[entries[at].Path] = change.stat + } + } + return scan, nil } -func (w *Worktree) compareToWorktree(entry *index.Entry) (StatusCode, error) { +func (w *Worktree) scanGroup(ctx context.Context, entries []*index.Entry, group []int, rules gitlinkRules, scanned []unstagedChange) error { + var listing directoryListing + if len(group) >= batchedStatMinimum { + listing = w.listDirectory(path.Dir(entries[group[0]].Path)) + } + for _, at := range group { + if err := ctx.Err(); err != nil { + return err + } + change, err := w.unstagedChangeOf(ctx, entries[at], rules, listing) + if err != nil { + return err + } + scanned[at] = change + } + return nil +} + +func (w *Worktree) statEntry(rel, name string, listing directoryListing) (fs.FileInfo, error) { + if info, ok := listing.info(path.Base(rel)); ok { + return info, nil + } + return fsLstatFile(w.root, name) +} + +func (w *Worktree) compareToWorktree(entry *index.Entry, listing directoryListing) (StatusCode, fs.FileInfo, error) { if entry.SkipWorktree { - return StatusUnmodified, nil + return StatusUnmodified, nil, nil } name := filepath.FromSlash(entry.Path) - fi, err := fsLstatFile(w.root, name) + fi, err := w.statEntry(entry.Path, name, listing) if errors.Is(err, fs.ErrNotExist) { - return StatusDeleted, nil + return StatusDeleted, nil, nil } if err != nil { - return 0, fmt.Errorf("%w: %s: %w", ErrReadWorkingTree, entry.Path, err) + return 0, nil, fmt.Errorf("%w: %s: %w", ErrReadWorkingTree, entry.Path, err) } if fi.IsDir() && !entry.Mode.IsSubmodule() { - return StatusDeleted, nil + return StatusDeleted, fi, nil } wantKind, actualKind := kindOfMode(entry.Mode), kindOfInfo(fi) if wantKind != actualKind && !w.holdsPlainSymlink(wantKind, fi) { - return StatusTypeChanged, nil + return StatusTypeChanged, fi, nil } if w.currentIndex().MatchesFile(entry, fi, w.symlinks) { if w.modeChanged(entry, fi) { - return StatusModified, nil + return StatusModified, fi, nil } - return StatusUnmodified, nil + return StatusUnmodified, fi, nil } if sizeChangedWithoutReading(entry, fi) { - return StatusModified, nil + return StatusModified, fi, nil } + code, err := w.compareContent(entry, name, fi, actualKind) + return code, fi, err +} + +func (w *Worktree) compareContent(entry *index.Entry, name string, fi fs.FileInfo, actualKind entryKind) (StatusCode, error) { switch actualKind { case kindSymlink: target, err := fsReadlinkFile(w.root, name) @@ -132,10 +218,14 @@ func (w *Worktree) holdsPlainSymlink(wantKind entryKind, fi os.FileInfo) bool { return !w.symlinks && wantKind == kindSymlink && fi.Mode().IsRegular() } -func (w *Worktree) fillWorkingInfo(e *Entry) { +func (w *Worktree) fillWorkingInfo(e *Entry, known map[string]workingStat) { if e.IsDir { return } + if stat, ok := known[e.Path]; ok { + e.Size, e.ModTime = stat.size, stat.modTime + return + } fi, err := fsLstatFile(w.root, filepath.FromSlash(e.Path)) if err != nil { return From fd63affe7bccaa2b0c13a577aefcd20ea3558c09 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=A7=D1=83=D0=BA=D0=B0=D0=BB=D0=B8=D0=BD=20=D0=92=D0=B0?= =?UTF-8?q?=D0=BB=D0=B5=D1=80=D0=B8=D0=B9?= Date: Fri, 16 Oct 2026 12:10:18 +0300 Subject: [PATCH 12/35] object: parse commit headers and signatures from one string and reuse fixed time zones --- internal/gitcore/object/commit.go | 2 +- internal/gitcore/object/headers.go | 16 ++- internal/gitcore/object/signature.go | 93 ++++++++++-- internal/gitcore/object/signaturefast_test.go | 134 ++++++++++++++++++ 4 files changed, 222 insertions(+), 23 deletions(-) create mode 100644 internal/gitcore/object/signaturefast_test.go diff --git a/internal/gitcore/object/commit.go b/internal/gitcore/object/commit.go index 6549bb0a..3de1eb07 100644 --- a/internal/gitcore/object/commit.go +++ b/internal/gitcore/object/commit.go @@ -118,7 +118,7 @@ func parseHeaderID(header ExtraHeader) (hash.ObjectID, error) { } func parseHeaderSignature(header ExtraHeader) (Signature, error) { - signature, err := ParseSignature([]byte(header.Value)) + signature, err := parseSignature(header.Value) if err != nil { return Signature{}, fmt.Errorf("header %s: %w", header.Key, err) } diff --git a/internal/gitcore/object/headers.go b/internal/gitcore/object/headers.go index aaf85aa3..f7779096 100644 --- a/internal/gitcore/object/headers.go +++ b/internal/gitcore/object/headers.go @@ -6,6 +6,8 @@ import ( "strings" ) +const expectedHeaders = 6 + type ExtraHeader struct { Key string Value string @@ -16,24 +18,24 @@ func splitHeaders(data []byte) ([]ExtraHeader, string, error) { if separator < 0 { return nil, "", fmt.Errorf("%w: no blank line between headers and message", ErrMalformed) } - block := data[:separator+1] + block := string(data[:separator+1]) message := string(data[separator+2:]) - var headers []ExtraHeader + headers := make([]ExtraHeader, 0, expectedHeaders) for len(block) > 0 { - var line []byte - line, block, _ = bytes.Cut(block, []byte("\n")) + var line string + line, block, _ = strings.Cut(block, "\n") if len(line) > 0 && line[0] == ' ' { if len(headers) == 0 { return nil, "", fmt.Errorf("%w: continuation line before any header", ErrMalformed) } - headers[len(headers)-1].Value += "\n" + string(line[1:]) + headers[len(headers)-1].Value += "\n" + line[1:] continue } - key, value, found := bytes.Cut(line, []byte(" ")) + key, value, found := strings.Cut(line, " ") if !found { return nil, "", fmt.Errorf("%w: header line %q has no value", ErrMalformed, line) } - headers = append(headers, ExtraHeader{Key: string(key), Value: string(value)}) + headers = append(headers, ExtraHeader{Key: key, Value: value}) } return headers, message, nil } diff --git a/internal/gitcore/object/signature.go b/internal/gitcore/object/signature.go index cd01ef0f..9e6b2cf5 100644 --- a/internal/gitcore/object/signature.go +++ b/internal/gitcore/object/signature.go @@ -1,10 +1,11 @@ package object import ( - "bytes" "fmt" + "math" "strconv" "strings" + "sync" "time" ) @@ -18,11 +19,15 @@ type Signature struct { } func ParseSignature(line []byte) (Signature, error) { - open := bytes.LastIndexByte(line, '<') + return parseSignature(string(line)) +} + +func parseSignature(line string) (Signature, error) { + open := strings.LastIndexByte(line, '<') if open < 1 || line[open-1] != ' ' { return Signature{}, fmt.Errorf("%w: no name before email in %q", ErrInvalidSignature, line) } - closing := bytes.IndexByte(line[open:], '>') + closing := strings.IndexByte(line[open:], '>') if closing < 0 { return Signature{}, fmt.Errorf("%w: email is not closed in %q", ErrInvalidSignature, line) } @@ -31,17 +36,14 @@ func ParseSignature(line []byte) (Signature, error) { if len(rest) == 0 || rest[0] != ' ' { return Signature{}, fmt.Errorf("%w: no timestamp in %q", ErrInvalidSignature, line) } - stamp, zone, hasZone := bytes.Cut(rest[1:], []byte(" ")) - seconds, err := strconv.ParseInt(string(stamp), 10, 64) - if err != nil { - return Signature{}, fmt.Errorf("%w: %w", ErrInvalidSignature, err) - } - if strconv.FormatInt(seconds, 10) != string(stamp) { - return Signature{}, fmt.Errorf("%w: timestamp %q is not canonical", ErrInvalidSignature, stamp) + stamp, zone, hasZone := strings.Cut(rest[1:], " ") + seconds, ok := parseCanonicalSeconds(stamp) + if !ok { + return Signature{}, invalidTimestamp(stamp) } signature := Signature{ - Name: string(line[:open-1]), - Email: string(line[open+1 : closing]), + Name: line[:open-1], + Email: line[open+1 : closing], OmitZone: !hasZone, } if !hasZone { @@ -52,10 +54,71 @@ func ParseSignature(line []byte) (Signature, error) { if err != nil { return Signature{}, err } - signature.When = time.Unix(seconds, 0).In(time.FixedZone(string(zone), offset)) + signature.When = time.Unix(seconds, 0).In(zoneLocation(zone, offset)) return signature, nil } +func parseCanonicalSeconds(stamp string) (int64, bool) { + digits, negative := stamp, false + if strings.HasPrefix(stamp, "-") { + digits, negative = stamp[1:], true + } + if len(digits) == 0 || len(digits) > maxTimestampDigits || (digits[0] == '0' && (len(digits) > 1 || negative)) { + return 0, false + } + var magnitude uint64 + for index := range len(digits) { + if digits[index] < '0' || digits[index] > '9' { + return 0, false + } + magnitude = magnitude*10 + uint64(digits[index]-'0') + } + if negative { + if magnitude > 1<<63 { + return 0, false + } + return -int64(magnitude), true + } + if magnitude > math.MaxInt64 { + return 0, false + } + return int64(magnitude), true +} + +func invalidTimestamp(stamp string) error { + if _, err := strconv.ParseInt(stamp, 10, 64); err != nil { + return fmt.Errorf("%w: %w", ErrInvalidSignature, err) + } + return fmt.Errorf("%w: timestamp %q is not canonical", ErrInvalidSignature, stamp) +} + +const ( + maxTimestampDigits = 19 + zoneCacheLimit = 4096 +) + +var zoneCache = struct { + sync.RWMutex + locations map[string]*time.Location +}{locations: make(map[string]*time.Location)} + +func zoneLocation(token string, offset int) *time.Location { + zoneCache.RLock() + location, cached := zoneCache.locations[token] + zoneCache.RUnlock() + if cached { + return location + } + name := strings.Clone(token) + location = time.FixedZone(name, offset) + zoneCache.Lock() + defer zoneCache.Unlock() + if len(zoneCache.locations) < zoneCacheLimit { + zoneCache.locations[name] = location + } + return location +} + func (s Signature) String() string { var text strings.Builder text.WriteString(s.Name) @@ -71,8 +134,8 @@ func (s Signature) String() string { return text.String() } -func parseZone(zone []byte) (int, error) { - if !isZoneToken(string(zone)) { +func parseZone(zone string) (int, error) { + if !isZoneToken(zone) { return 0, fmt.Errorf("%w: bad timezone %q", ErrInvalidSignature, zone) } offset := (int(zone[1]-'0')*10+int(zone[2]-'0'))*3600 + (int(zone[3]-'0')*10+int(zone[4]-'0'))*60 diff --git a/internal/gitcore/object/signaturefast_test.go b/internal/gitcore/object/signaturefast_test.go new file mode 100644 index 00000000..c4b9db8e --- /dev/null +++ b/internal/gitcore/object/signaturefast_test.go @@ -0,0 +1,134 @@ +package object + +import ( + "errors" + "fmt" + "strconv" + "strings" + "sync" + "testing" +) + +func referenceSeconds(stamp string) (int64, bool) { + seconds, err := strconv.ParseInt(stamp, 10, 64) + if err != nil || strconv.FormatInt(seconds, 10) != stamp { + return 0, false + } + return seconds, true +} + +func TestCanonicalSecondsAgreeWithParsingAndFormattingAnInteger(t *testing.T) { + stamps := []string{ + "", "0", "-0", "+1", "01", "-", "--1", "-01", "1", "-1", "1700000000", "-1700000000", + "9223372036854775807", "9223372036854775808", "-9223372036854775808", "-9223372036854775809", + "99999999999999999999", "12a", "1_0", " 1", "1 ", "0x10", "1e3", "٣", + } + for _, stamp := range stamps { + wantSeconds, wantOK := referenceSeconds(stamp) + gotSeconds, gotOK := parseCanonicalSeconds(stamp) + if gotOK != wantOK || (gotOK && gotSeconds != wantSeconds) { + t.Errorf("parseCanonicalSeconds(%q) = %d, %v; parsing and formatting gives %d, %v", stamp, gotSeconds, gotOK, wantSeconds, wantOK) + } + } +} + +func TestInvalidTimestampsKeepTheirFailureMessages(t *testing.T) { + tests := []struct { + stamp string + want string + }{ + {"12a", "invalid syntax"}, + {"99999999999999999999", "value out of range"}, + {"01", "is not canonical"}, + {"+1", "is not canonical"}, + {"-0", "is not canonical"}, + } + for _, tc := range tests { + err := invalidTimestamp(tc.stamp) + if !errors.Is(err, ErrInvalidSignature) || !strings.Contains(err.Error(), tc.want) { + t.Errorf("invalidTimestamp(%q) = %v, want %q", tc.stamp, err, tc.want) + } + } +} + +func TestParsingASignatureRejectsATimestampThatIsNotCanonical(t *testing.T) { + _, err := ParseSignature([]byte("Ann 0100 +0300")) + + if !errors.Is(err, ErrInvalidSignature) { + t.Fatalf("ParseSignature returned %v, want ErrInvalidSignature", err) + } +} + +func TestSignaturesInTheSameZoneShareOneLocation(t *testing.T) { + first, err := ParseSignature([]byte("Ann 1700000000 +0530")) + if err != nil { + t.Fatal(err) + } + second, err := ParseSignature([]byte("Bob 1700000100 +0530")) + if err != nil { + t.Fatal(err) + } + + if first.When.Location() != second.When.Location() { + t.Fatal("two signatures in +0530 got different location objects") + } + if name := first.When.Location().String(); name != "+0530" { + t.Fatalf("the location is named %q, want +0530", name) + } + if _, offset := first.When.Zone(); offset != 5*3600+30*60 { + t.Fatalf("the offset is %d, want +0530", offset) + } +} + +func TestTheZoneCacheStopsGrowingAtItsLimit(t *testing.T) { + var wg sync.WaitGroup + for worker := range 4 { + wg.Go(func() { + for index := range zoneCacheLimit + 500 { + token := fmt.Sprintf("+%04d", (index*4+worker)%10000) + offset, err := parseZone(token) + if err != nil { + t.Errorf("parseZone(%q) returned error %v", token, err) + return + } + location := zoneLocation(token, offset) + if location.String() != token { + t.Errorf("zoneLocation(%q) is named %q", token, location.String()) + return + } + } + }) + } + wg.Wait() + + zoneCache.RLock() + size := len(zoneCache.locations) + zoneCache.RUnlock() + if size > zoneCacheLimit { + t.Fatalf("the zone cache holds %d locations, want at most %d", size, zoneCacheLimit) + } + beyond, err := parseZone("-9999") + if err != nil { + t.Fatal(err) + } + if fresh := zoneLocation("-9999", beyond); fresh == nil || fresh.String() != "-9999" { + t.Fatalf("a zone beyond the limit returned %v", fresh) + } +} + +func TestParsingACommitAllocatesLittle(t *testing.T) { + data := []byte("tree 4b825dc642cb6eb9a060e54bf8d69288fbee4904\n" + + "parent 1111111111111111111111111111111111111111\n" + + "author Ann 1700000000 +0300\n" + + "committer Bob 1700000100 +0300\n\nmessage\n") + + allocations := testing.AllocsPerRun(100, func() { + if _, err := ParseCommit(data); err != nil { + t.Fatal(err) + } + }) + + if allocations > 10 { + t.Fatalf("ParseCommit allocates %v times, want at most 10", allocations) + } +} From 5de230e321025abd1b64bf7fba19ed8a2eff6495 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=A7=D1=83=D0=BA=D0=B0=D0=BB=D0=B8=D0=BD=20=D0=92=D0=B0?= =?UTF-8?q?=D0=BB=D0=B5=D1=80=D0=B8=D0=B9?= Date: Fri, 16 Oct 2026 12:18:56 +0300 Subject: [PATCH 13/35] app: make the divergence and journal restart tests independent of the file watcher --- internal/app/branchdivergence_test.go | 1 + internal/app/graphcache_test.go | 37 +++++++++++++++++++-------- internal/app/journalkey_test.go | 3 +++ 3 files changed, 31 insertions(+), 10 deletions(-) diff --git a/internal/app/branchdivergence_test.go b/internal/app/branchdivergence_test.go index 54a2ded4..7512a27a 100644 --- a/internal/app/branchdivergence_test.go +++ b/internal/app/branchdivergence_test.go @@ -112,6 +112,7 @@ func TestBranchesPaneShowsNoSuffixForABranchWithoutUpstream(t *testing.T) { func TestBranchDivergenceComputationRunsInTheBackgroundWithoutBlockingRefresh(t *testing.T) { a, _, local := cloneForDivergence(t) + a.stopWatcher() addLocalCommitWithMessage(t, local, "main", "second.txt", "second\n", "second") o := a.opened() o.divergence.keepOnly(nil) diff --git a/internal/app/graphcache_test.go b/internal/app/graphcache_test.go index 2e6fb4ae..ed3bfbd7 100644 --- a/internal/app/graphcache_test.go +++ b/internal/app/graphcache_test.go @@ -3,6 +3,7 @@ package app import ( "os" "path/filepath" + "sync/atomic" "testing" "time" @@ -12,6 +13,7 @@ import ( gitrepo "github.com/oops1/gogit/internal/gitcore/repo" "github.com/oops1/gogit/internal/gitcore/revision" "github.com/oops1/gogit/internal/repo" + "github.com/oops1/gogit/internal/ui/branches" ) func countGraphOpens(t *testing.T) *int { @@ -132,29 +134,44 @@ func TestRevisionContextCarriesTheOpenRepositoryAndItsCachedGraph(t *testing.T) } } -func TestRefreshDoesNotCountDivergenceAgainWhileBranchTipsAreUnchanged(t *testing.T) { +func enrichedSnapshot(t *testing.T, a *App, o *openedRepository) branches.Snapshot { + t.Helper() + snap, err := loadBranchSnapshot(o.store) + if err != nil { + t.Fatal(err) + } + a.enrichBranchSnapshot(o, &snap) + return snap +} + +func TestBranchDivergenceIsNotCountedAgainWhileBranchTipsAreUnchanged(t *testing.T) { a, _, local := cloneForDivergence(t) - calls := 0 + a.stopWatcher() + o := a.opened() + var calls atomic.Int32 previous := manyAheadBehind manyAheadBehind = func(source revision.Context, pairs []repo.BranchPair) (map[refs.Name]repo.Divergence, error) { - calls++ + calls.Add(1) return previous(source, pairs) } t.Cleanup(func() { manyAheadBehind = previous }) - a.RefreshRepository() + a.refreshBranchDivergence(o, enrichedSnapshot(t, a, o)) a.branchDivergenceWG.Wait() - a.RefreshRepository() + a.refreshBranchDivergence(o, enrichedSnapshot(t, a, o)) a.branchDivergenceWG.Wait() - if calls != 0 { - t.Fatalf("divergence was counted %d times while no branch moved, want none", calls) + if got := calls.Load(); got != 0 { + t.Fatalf("divergence was counted %d times while no branch moved, want none", got) } addLocalCommitWithMessage(t, local, "main", "second.txt", "second\n", "second") - a.RefreshRepository() + moved := enrichedSnapshot(t, a, o) + a.refreshBranchDivergence(o, moved) + a.branchDivergenceWG.Wait() + a.refreshBranchDivergence(o, moved) a.branchDivergenceWG.Wait() - if calls != 1 { - t.Fatalf("divergence was counted %d times after one branch moved, want once", calls) + if got := calls.Load(); got != 1 { + t.Fatalf("divergence was counted %d times after one branch moved, want once", got) } } diff --git a/internal/app/journalkey_test.go b/internal/app/journalkey_test.go index dfa890ae..43b311c7 100644 --- a/internal/app/journalkey_test.go +++ b/internal/app/journalkey_test.go @@ -112,6 +112,7 @@ func countJournalRestarts(t *testing.T) *int { func TestARefreshWithUnchangedRefsDoesNotRestartTheJournal(t *testing.T) { a, _, _ := cloneForDivergence(t) + a.stopWatcher() restarts := countJournalRestarts(t) a.RefreshRepository() @@ -125,6 +126,7 @@ func TestARefreshWithUnchangedRefsDoesNotRestartTheJournal(t *testing.T) { func TestARefreshAfterABranchMovedRestartsTheJournalOnce(t *testing.T) { a, _, local := cloneForDivergence(t) + a.stopWatcher() restarts := countJournalRestarts(t) addLocalCommitWithMessage(t, local, "main", "second.txt", "second\n", "second") @@ -138,6 +140,7 @@ func TestARefreshAfterABranchMovedRestartsTheJournalOnce(t *testing.T) { func TestTheRefreshCommandAlwaysReloadsTheJournal(t *testing.T) { a, _, _ := cloneForDivergence(t) + a.stopWatcher() restarts := countJournalRestarts(t) a.Dispatch(CmdRefresh) From 822d559e793f8308761edb8b1bfe1bd9abc5a92a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=A7=D1=83=D0=BA=D0=B0=D0=BB=D0=B8=D0=BD=20=D0=92=D0=B0?= =?UTF-8?q?=D0=BB=D0=B5=D1=80=D0=B8=D0=B9?= Date: Fri, 16 Oct 2026 14:38:08 +0300 Subject: [PATCH 14/35] worktree: compare the index with HEAD through the cache tree and read only the trees that differ --- internal/gitcore/worktree/coverage_test.go | 10 +- internal/gitcore/worktree/errors_test.go | 6 +- internal/gitcore/worktree/gitlinkstatus.go | 9 +- internal/gitcore/worktree/headdiff.go | 221 ++++++++++ internal/gitcore/worktree/headdiff_test.go | 394 ++++++++++++++++++ .../gitcore/worktree/headreference_test.go | 116 ++++++ internal/gitcore/worktree/headtree.go | 109 ----- internal/gitcore/worktree/status.go | 13 +- 8 files changed, 753 insertions(+), 125 deletions(-) create mode 100644 internal/gitcore/worktree/headdiff.go create mode 100644 internal/gitcore/worktree/headdiff_test.go create mode 100644 internal/gitcore/worktree/headreference_test.go diff --git a/internal/gitcore/worktree/coverage_test.go b/internal/gitcore/worktree/coverage_test.go index 63eba7a9..94b59d75 100644 --- a/internal/gitcore/worktree/coverage_test.go +++ b/internal/gitcore/worktree/coverage_test.go @@ -14,15 +14,15 @@ import ( "github.com/oops1/gogit/internal/gitcore/repo" ) -func TestCollectHeadTreeReturnsAnEmptyMapForAZeroID(t *testing.T) { +func TestStagedStatusAgainstAnUnbornHeadOfAnEmptyIndexIsEmpty(t *testing.T) { tr := newTestRepo(t) w := tr.open() - tree, err := w.collectHeadTree(t.Context(), hash.Zero) + staged, err := w.stagedStatus(t.Context(), hash.Zero) if err != nil { - t.Fatalf("collectHeadTree returned error %v", err) + t.Fatalf("stagedStatus returned error %v", err) } - if len(tree) != 0 { - t.Fatalf("collectHeadTree(zero) = %#v, want empty", tree) + if len(staged) != 0 { + t.Fatalf("stagedStatus(zero) = %#v, want empty", staged) } } diff --git a/internal/gitcore/worktree/errors_test.go b/internal/gitcore/worktree/errors_test.go index 2293f7d7..187b1cf6 100644 --- a/internal/gitcore/worktree/errors_test.go +++ b/internal/gitcore/worktree/errors_test.go @@ -167,7 +167,7 @@ func TestStatusFailsWhenTheHeadTreeObjectIsMissing(t *testing.T) { } } -func TestCollectHeadTreeStopsWhenContextIsCanceled(t *testing.T) { +func TestStagedStatusStopsWhenContextIsCanceled(t *testing.T) { tr := newTestRepo(t) tr.stage("a.txt", "hi\n") tr.stage("dir/b.txt", "hi\n") @@ -177,8 +177,8 @@ func TestCollectHeadTreeStopsWhenContextIsCanceled(t *testing.T) { if err != nil { t.Fatalf("Commit returned error %v", err) } - if _, err := w.collectHeadTree(newStepContext(0), commit.Tree); err == nil { - t.Fatalf("collectHeadTree returned no error for a canceled context") + if _, err := w.stagedStatus(newStepContext(0), commit.Tree); err == nil { + t.Fatalf("stagedStatus returned no error for a canceled context") } } diff --git a/internal/gitcore/worktree/gitlinkstatus.go b/internal/gitcore/worktree/gitlinkstatus.go index d70aa9f8..3bc43db7 100644 --- a/internal/gitcore/worktree/gitlinkstatus.go +++ b/internal/gitcore/worktree/gitlinkstatus.go @@ -6,6 +6,7 @@ import ( "path/filepath" "github.com/oops1/gogit/internal/gitcore/gitlink" + "github.com/oops1/gogit/internal/gitcore/hash" "github.com/oops1/gogit/internal/gitcore/index" "github.com/oops1/gogit/internal/gitcore/odb" "github.com/oops1/gogit/internal/gitcore/repo" @@ -49,7 +50,7 @@ func hasGitlink(entries []*index.Entry) bool { return false } -func (w *Worktree) gitlinkRulesFor(entries []*index.Entry, headTree map[string]headEntry) (gitlinkRules, error) { +func (w *Worktree) gitlinkRulesFor(entries []*index.Entry, headTree hash.ObjectID) (gitlinkRules, error) { rules := gitlinkRules{cfg: w.repo.Config(), modules: &submodule.Modules{}, base: ignoreFlags{untracked: w.hideUntracked}} if !hasGitlink(entries) || w.ignoreNoSubmodule { return rules, nil @@ -62,11 +63,15 @@ func (w *Worktree) gitlinkRulesFor(entries []*index.Entry, headTree map[string]h rules.base = ignoreFlagsOf(mode) rules.base.untracked = rules.base.untracked || w.hideUntracked } + headBlob, err := w.headGitmodules(headTree) + if err != nil { + return gitlinkRules{}, err + } modules, err := submodule.Load(submodule.Source{ WorkTree: w.repo.WorkTree(), Index: w.currentIndex(), Objects: w.db, - HeadBlob: headTree[submodule.GitmodulesFile].ID, + HeadBlob: headBlob, }) if err != nil { return gitlinkRules{}, err diff --git a/internal/gitcore/worktree/headdiff.go b/internal/gitcore/worktree/headdiff.go new file mode 100644 index 00000000..54831e5f --- /dev/null +++ b/internal/gitcore/worktree/headdiff.go @@ -0,0 +1,221 @@ +package worktree + +import ( + "context" + "fmt" + "slices" + "strings" + + "github.com/oops1/gogit/internal/gitcore/hash" + "github.com/oops1/gogit/internal/gitcore/index" + "github.com/oops1/gogit/internal/gitcore/object" + "github.com/oops1/gogit/internal/gitcore/odb" + "github.com/oops1/gogit/internal/gitcore/submodule" +) + +var loadTree = (*odb.DB).Tree + +type stagedAddition struct { + path string + entry *index.Entry +} + +type stagedRemoval struct { + path string + mode object.Mode + id hash.ObjectID +} + +type headDifference struct { + changed map[string]Entry + added []stagedAddition + removed []stagedRemoval +} + +type indexRun struct { + name string + isDir bool + first int + end int +} + +func (r indexRun) key() string { + if r.isDir { + return r.name + "/" + } + return r.name +} + +func treeEntryKey(entry object.TreeEntry) string { + if entry.Mode.IsTree() { + return entry.Name + "/" + } + return entry.Name +} + +func (w *Worktree) stagedStatus(ctx context.Context, headTree hash.ObjectID) (map[string]Entry, error) { + idx := w.currentIndex() + difference := &headDifference{changed: map[string]Entry{}} + if err := w.compareDirectory(ctx, difference, headTree, "", idx.CacheTree, 0, idx.Len()); err != nil { + return nil, err + } + return difference.entries(), nil +} + +func (w *Worktree) compareDirectory(ctx context.Context, difference *headDifference, treeID hash.ObjectID, prefix string, cache *index.CacheTree, first, end int) error { + if err := ctx.Err(); err != nil { + return err + } + if cache != nil && cache.Valid() && !treeID.IsZero() && cache.ID == treeID { + return nil + } + var tree *object.Tree + if !treeID.IsZero() { + loaded, err := loadTree(w.db, treeID) + if err != nil { + return fmt.Errorf("%w: %w", ErrReadHeadTree, err) + } + tree = loaded + } + runs := w.indexRuns(prefix, first, end) + var entries []object.TreeEntry + if tree != nil { + entries = tree.Entries + } + for len(entries) > 0 || len(runs) > 0 { + switch { + case len(runs) == 0 || (len(entries) > 0 && treeEntryKey(entries[0]) < runs[0].key()): + if err := w.removeTreeEntry(ctx, difference, entries[0], prefix); err != nil { + return err + } + entries = entries[1:] + case len(entries) == 0 || runs[0].key() < treeEntryKey(entries[0]): + w.addRun(difference, prefix, runs[0]) + runs = runs[1:] + default: + if err := w.compareEntry(ctx, difference, entries[0], runs[0], prefix, cache); err != nil { + return err + } + entries, runs = entries[1:], runs[1:] + } + } + return nil +} + +func (w *Worktree) indexRuns(prefix string, first, end int) []indexRun { + idx := w.currentIndex() + var runs []indexRun + for position := first; position < end; position++ { + entry := idx.At(position) + if entry.Stage != index.StageMerged { + continue + } + name, _, nested := strings.Cut(entry.Path[len(prefix):], "/") + if last := len(runs) - 1; last >= 0 && runs[last].name == name && runs[last].isDir == nested { + runs[last].end = position + 1 + continue + } + runs = append(runs, indexRun{name: name, isDir: nested, first: position, end: position + 1}) + } + return runs +} + +func (w *Worktree) compareEntry(ctx context.Context, difference *headDifference, entry object.TreeEntry, run indexRun, prefix string, cache *index.CacheTree) error { + if entry.Mode.IsTree() { + var sub *index.CacheTree + if cache != nil { + sub = cache.Find(entry.Name) + } + return w.compareDirectory(ctx, difference, entry.ID, prefix+entry.Name+"/", sub, run.first, run.end) + } + staged := w.currentIndex().At(run.first) + if staged.Mode == entry.Mode && staged.ID == entry.ID { + return nil + } + code := StatusModified + if kindOfMode(staged.Mode) != kindOfMode(entry.Mode) { + code = StatusTypeChanged + } + difference.changed[staged.Path] = Entry{Path: staged.Path, Staged: code, Unstaged: StatusUnmodified} + return nil +} + +func (w *Worktree) addRun(difference *headDifference, prefix string, run indexRun) { + idx := w.currentIndex() + for position := run.first; position < run.end; position++ { + if entry := idx.At(position); entry.Stage == index.StageMerged { + difference.added = append(difference.added, stagedAddition{path: entry.Path, entry: entry}) + } + } +} + +func (w *Worktree) removeTreeEntry(ctx context.Context, difference *headDifference, entry object.TreeEntry, prefix string) error { + if !entry.Mode.IsTree() { + difference.removed = append(difference.removed, stagedRemoval{path: prefix + entry.Name, mode: entry.Mode, id: entry.ID}) + return nil + } + return w.removeTree(ctx, difference, entry.ID, prefix+entry.Name+"/") +} + +func (w *Worktree) removeTree(ctx context.Context, difference *headDifference, treeID hash.ObjectID, prefix string) error { + if err := ctx.Err(); err != nil { + return err + } + tree, err := loadTree(w.db, treeID) + if err != nil { + return fmt.Errorf("%w: %w", ErrReadHeadTree, err) + } + for _, entry := range tree.Entries { + if err := w.removeTreeEntry(ctx, difference, entry, prefix); err != nil { + return err + } + } + return nil +} + +func (d *headDifference) entries() map[string]Entry { + slices.SortFunc(d.added, func(a, b stagedAddition) int { return strings.Compare(a.path, b.path) }) + slices.SortFunc(d.removed, func(a, b stagedRemoval) int { return strings.Compare(a.path, b.path) }) + byID := map[hash.ObjectID][]stagedRemoval{} + for _, removed := range d.removed { + byID[removed.id] = append(byID[removed.id], removed) + } + used := map[string]bool{} + for _, added := range d.added { + matched := "" + for _, candidate := range byID[added.entry.ID] { + if used[candidate.path] || candidate.mode.ObjectType() != added.entry.Mode.ObjectType() { + continue + } + matched = candidate.path + break + } + if matched != "" { + used[matched] = true + d.changed[added.path] = Entry{Path: added.path, OrigPath: matched, Staged: StatusRenamed, Unstaged: StatusUnmodified} + continue + } + d.changed[added.path] = Entry{Path: added.path, Staged: StatusAdded, Unstaged: StatusUnmodified} + } + for _, removed := range d.removed { + if !used[removed.path] { + d.changed[removed.path] = Entry{Path: removed.path, Staged: StatusDeleted, Unstaged: StatusUnmodified} + } + } + return d.changed +} + +func (w *Worktree) headGitmodules(headTree hash.ObjectID) (hash.ObjectID, error) { + if headTree.IsZero() { + return hash.Zero, nil + } + tree, err := loadTree(w.db, headTree) + if err != nil { + return hash.Zero, fmt.Errorf("%w: %w", ErrReadHeadTree, err) + } + entry, found := tree.Find(submodule.GitmodulesFile) + if !found || entry.Mode.IsTree() { + return hash.Zero, nil + } + return entry.ID, nil +} diff --git a/internal/gitcore/worktree/headdiff_test.go b/internal/gitcore/worktree/headdiff_test.go new file mode 100644 index 00000000..cbd4db4a --- /dev/null +++ b/internal/gitcore/worktree/headdiff_test.go @@ -0,0 +1,394 @@ +package worktree + +import ( + "errors" + "fmt" + "reflect" + "slices" + "sync/atomic" + "testing" + + "github.com/oops1/gogit/internal/gitcore/hash" + "github.com/oops1/gogit/internal/gitcore/index" + "github.com/oops1/gogit/internal/gitcore/object" + "github.com/oops1/gogit/internal/gitcore/odb" +) + +func headTreeOf(t *testing.T, w *Worktree, tr *testRepo) hash.ObjectID { + t.Helper() + commit, err := w.db.Commit(tr.headCommit()) + if err != nil { + t.Fatalf("Commit returned error %v", err) + } + return commit.Tree +} + +func newComparisonRepo(t *testing.T) *testRepo { + t.Helper() + tr := newTestRepo(t) + for _, rel := range []string{ + "README.md", "main.go", "go.mod", "a.txt", "a.txt.bak", + "src/one.go", "src/two.go", "src/deep/three.go", "src/deep/four.go", "src/deep/er/five.go", + "docs/guide.md", "docs/api/index.md", "docs/api/types.md", + "lib/x.c", "lib/y.c", "lib.d/z.c", "z/last.txt", + } { + tr.stage(rel, "content of "+rel+"\n") + } + tr.commit("initial") + return tr +} + +type sequence struct{ state uint64 } + +func (s *sequence) Int() int { + s.state ^= s.state << 13 + s.state ^= s.state >> 7 + s.state ^= s.state << 17 + return int(s.state >> 1) +} + +func (s *sequence) IntN(limit int) int { return s.Int() % limit } + +func randomMutation(rng *sequence, idx *index.Index, step int) { + var merged []*index.Entry + for entry := range idx.Entries() { + if entry.Stage == index.StageMerged { + merged = append(merged, entry) + } + } + if len(merged) == 0 { + return + } + pick := *merged[rng.IntN(len(merged))] + freshID := func() hash.ObjectID { + id, _ := hash.Sum(hash.SHA1, "blob", fmt.Appendf(nil, "mutation %d %d", step, rng.Int())) + return id + } + switch rng.IntN(10) { + case 0: + pick.ID = freshID() + idx.Add(pick) + case 1: + idx.Add(index.Entry{Path: fmt.Sprintf("new%d/file%d.txt", rng.IntN(3), step), Mode: object.ModeBlob, ID: freshID()}) + case 2: + idx.Remove(pick.Path) + case 3: + idx.Remove(pick.Path) + idx.Add(index.Entry{Path: fmt.Sprintf("moved/%d/%s", step, pick.Path), Mode: pick.Mode, ID: pick.ID}) + case 4: + if pick.Mode == object.ModeExecutable { + pick.Mode = object.ModeBlob + } else { + pick.Mode = object.ModeExecutable + } + idx.Add(pick) + case 5: + pick.Mode = object.ModeSymlink + idx.Add(pick) + case 6: + idx.Remove(pick.Path) + idx.Add(index.Entry{Path: pick.Path + "/inner.txt", Mode: object.ModeBlob, ID: freshID()}) + case 7: + dir := pick.Path + for at := len(dir) - 1; at >= 0; at-- { + if dir[at] == '/' { + dir = dir[:at] + break + } + } + if dir == pick.Path { + return + } + for _, entry := range merged { + if len(entry.Path) > len(dir) && entry.Path[:len(dir)+1] == dir+"/" { + idx.Remove(entry.Path) + } + } + idx.Add(index.Entry{Path: dir, Mode: object.ModeBlob, ID: freshID()}) + case 8: + idx.Remove(pick.Path) + for _, stage := range []index.Stage{index.StageAncestor, index.StageOurs, index.StageTheirs} { + idx.Add(index.Entry{Path: pick.Path, Mode: object.ModeBlob, ID: freshID(), Stage: stage}) + } + default: + idx.Add(index.Entry{Path: pick.Path + ".copy", Mode: pick.Mode, ID: pick.ID}) + } +} + +func TestStagedStatusAgreesWithTheFullComparisonOnRandomChanges(t *testing.T) { + for seed := range uint64(120) { + t.Run(fmt.Sprintf("seed%03d", seed), func(t *testing.T) { + rng := &sequence{state: seed*7919 + 1} + tr := newComparisonRepo(t) + for step := range 1 + rng.IntN(6) { + randomMutation(rng, tr.idx, step) + } + if seed%3 == 0 { + tr.idx.CacheTree = nil + } + w := tr.open() + treeID := headTreeOf(t, w, tr) + + got, err := w.stagedStatus(t.Context(), treeID) + if err != nil { + t.Fatalf("stagedStatus returned error %v", err) + } + head, err := w.referenceHeadTree(t.Context(), treeID) + if err != nil { + t.Fatalf("referenceHeadTree returned error %v", err) + } + want := w.referenceStagedStatus(head) + + if !reflect.DeepEqual(got, want) { + t.Fatalf("stagedStatus = %v\nthe full comparison gives %v", sortedStaged(got), sortedStaged(want)) + } + }) + } +} + +func sortedStaged(entries map[string]Entry) []string { + lines := make([]string, 0, len(entries)) + for path, entry := range entries { + lines = append(lines, fmt.Sprintf("%s staged=%c from=%q", path, entry.Staged, entry.OrigPath)) + } + slices.Sort(lines) + return lines +} + +func TestAnIndexIdenticalToHeadReadsOnlyTheRootTree(t *testing.T) { + tr := newComparisonRepo(t) + w := tr.open() + treeID := headTreeOf(t, w, tr) + if cache := w.currentIndex().CacheTree; cache == nil || !cache.Valid() || cache.ID != treeID { + t.Fatalf("the saved index has no valid cache tree for %s", treeID) + } + reads := countTreeReads(t) + + staged, err := w.stagedStatus(t.Context(), treeID) + + if err != nil || len(staged) != 0 { + t.Fatalf("stagedStatus = %v, %v, want nothing staged", staged, err) + } + if got := reads.Load(); got != 0 { + t.Fatalf("stagedStatus read %d trees of an unchanged HEAD, want none", got) + } +} + +func TestOneChangedFileReadsOnlyTheTreesOnItsPath(t *testing.T) { + tr := newComparisonRepo(t) + tr.stage("src/deep/er/five.go", "changed\n") + w := tr.open() + treeID := headTreeOf(t, w, tr) + reads := countTreeReads(t) + + staged, err := w.stagedStatus(t.Context(), treeID) + + if err != nil || len(staged) != 1 || staged["src/deep/er/five.go"].Staged != StatusModified { + t.Fatalf("stagedStatus = %v, %v, want the one modified file", staged, err) + } + if got := reads.Load(); got != 4 { + t.Fatalf("stagedStatus read %d trees, want the four on the path root, src, deep and er", got) + } +} + +func TestStagedStatusReportsAnUnreadableTreeBelowTheRoot(t *testing.T) { + tr := newComparisonRepo(t) + tr.stage("docs/api/types.md", "changed\n") + tr.idx.CacheTree = nil + w := tr.open() + treeID := headTreeOf(t, w, tr) + root, err := w.db.Tree(treeID) + if err != nil { + t.Fatalf("Tree returned error %v", err) + } + brokenID := hash.Zero + for _, entry := range root.Entries { + if entry.Name == "lib" { + brokenID = entry.ID + } + } + failing := failTreeReads(t, brokenID) + + if _, err := w.stagedStatus(t.Context(), treeID); err == nil || failing.Load() == 0 { + t.Fatalf("stagedStatus returned %v after %d failing reads, want an error", err, failing.Load()) + } +} + +func countTreeReads(t *testing.T) *atomic.Int64 { + t.Helper() + reads := new(atomic.Int64) + previous := loadTree + loadTree = func(db *odb.DB, id hash.ObjectID) (*object.Tree, error) { + reads.Add(1) + return previous(db, id) + } + t.Cleanup(func() { loadTree = previous }) + return reads +} + +func failTreeReads(t *testing.T, broken hash.ObjectID) *atomic.Int64 { + t.Helper() + failures := new(atomic.Int64) + previous := loadTree + loadTree = func(db *odb.DB, id hash.ObjectID) (*object.Tree, error) { + if id == broken { + failures.Add(1) + return nil, errors.New("tree unreadable") + } + return previous(db, id) + } + t.Cleanup(func() { loadTree = previous }) + return failures +} + +func TestStagedStatusReportsAnUnreadableTreeOfADirectoryTheIndexLacks(t *testing.T) { + tr := newComparisonRepo(t) + tr.idx.Remove("lib/x.c") + tr.idx.Remove("lib/y.c") + w := tr.open() + treeID := headTreeOf(t, w, tr) + root, err := w.db.Tree(treeID) + if err != nil { + t.Fatalf("Tree returned error %v", err) + } + var lib hash.ObjectID + for _, entry := range root.Entries { + if entry.Name == "lib" { + lib = entry.ID + } + } + failing := failTreeReads(t, lib) + + if _, err := w.stagedStatus(t.Context(), treeID); !errors.Is(err, ErrReadHeadTree) || failing.Load() == 0 { + t.Fatalf("stagedStatus returned %v after %d failing reads, want ErrReadHeadTree", err, failing.Load()) + } +} + +func TestStagedStatusReportsEverythingUnderADirectoryRemovedFromTheIndex(t *testing.T) { + tr := newComparisonRepo(t) + for _, rel := range []string{"src/one.go", "src/two.go", "src/deep/three.go", "src/deep/four.go", "src/deep/er/five.go"} { + tr.idx.Remove(rel) + } + w := tr.open() + + staged, err := w.stagedStatus(t.Context(), headTreeOf(t, w, tr)) + + if err != nil || len(staged) != 5 { + t.Fatalf("stagedStatus = %v, %v, want five deletions", sortedStaged(staged), err) + } + for path, entry := range staged { + if entry.Staged != StatusDeleted { + t.Fatalf("%s is %c, want deleted", path, entry.Staged) + } + } +} + +func TestRemovingATreeStopsWhenTheCallerGivesUp(t *testing.T) { + tr := newComparisonRepo(t) + w := tr.open() + + err := w.removeTree(newStepContext(0), &headDifference{changed: map[string]Entry{}}, headTreeOf(t, w, tr), "") + + if err == nil { + t.Fatal("removeTree ignored a cancelled context") + } +} + +func TestTheHeadGitmodulesBlobIsFoundOnlyAsAFileOfTheRootTree(t *testing.T) { + tr := newTestRepo(t) + tr.stage(".gitmodules", "[submodule \"x\"]\n\tpath = x\n\turl = ../x\n") + tr.stage("dir/.gitmodules", "nested\n") + tr.commit("with modules") + w := tr.open() + treeID := headTreeOf(t, w, tr) + want, err := hash.Sum(hash.SHA1, "blob", []byte("[submodule \"x\"]\n\tpath = x\n\turl = ../x\n")) + if err != nil { + t.Fatal(err) + } + + got, err := w.headGitmodules(treeID) + if err != nil || got != want { + t.Fatalf("headGitmodules = %s, %v, want %s", got, err, want) + } + if got, err := w.headGitmodules(hash.Zero); err != nil || !got.IsZero() { + t.Fatalf("headGitmodules of an unborn HEAD = %s, %v, want nothing", got, err) + } +} + +func TestTheHeadGitmodulesBlobIsAbsentWhenTheNameIsADirectoryOrMissing(t *testing.T) { + tr := newTestRepo(t) + tr.stage(".gitmodules/inner.txt", "x\n") + tr.commit("a directory with that name") + w := tr.open() + + if got, err := w.headGitmodules(headTreeOf(t, w, tr)); err != nil || !got.IsZero() { + t.Fatalf("headGitmodules = %s, %v, want nothing for a directory", got, err) + } + other := newTestRepo(t) + other.stage("plain.txt", "x\n") + other.commit("no modules") + ow := other.open() + if got, err := ow.headGitmodules(headTreeOf(t, ow, other)); err != nil || !got.IsZero() { + t.Fatalf("headGitmodules = %s, %v, want nothing without the file", got, err) + } +} + +func TestTheHeadGitmodulesBlobReportsAnUnreadableRootTree(t *testing.T) { + tr := newComparisonRepo(t) + w := tr.open() + treeID := headTreeOf(t, w, tr) + failTreeReads(t, treeID) + + if _, err := w.headGitmodules(treeID); !errors.Is(err, ErrReadHeadTree) { + t.Fatalf("headGitmodules returned %v, want ErrReadHeadTree", err) + } +} + +func TestSubmoduleRulesReportAnUnreadableHeadTree(t *testing.T) { + tr := newComparisonRepo(t) + tr.idx.Add(index.Entry{Path: "vendor/sub", Mode: object.ModeSubmodule, ID: hash.ObjectID{7}}) + w := tr.open() + treeID := headTreeOf(t, w, tr) + failTreeReads(t, treeID) + var entries []*index.Entry + for entry := range w.currentIndex().Entries() { + entries = append(entries, entry) + } + + if _, err := w.gitlinkRulesFor(entries, treeID); !errors.Is(err, ErrReadHeadTree) { + t.Fatalf("gitlinkRulesFor returned %v, want ErrReadHeadTree", err) + } +} + +func TestStagedStatusReportsAnUnreadableNestedTreeOfARemovedDirectory(t *testing.T) { + tr := newComparisonRepo(t) + tr.idx.Remove("docs/guide.md") + tr.idx.Remove("docs/api/index.md") + tr.idx.Remove("docs/api/types.md") + w := tr.open() + treeID := headTreeOf(t, w, tr) + root, err := w.db.Tree(treeID) + if err != nil { + t.Fatalf("Tree returned error %v", err) + } + var docs, api hash.ObjectID + for _, entry := range root.Entries { + if entry.Name == "docs" { + docs = entry.ID + } + } + docsTree, err := w.db.Tree(docs) + if err != nil { + t.Fatalf("Tree returned error %v", err) + } + for _, entry := range docsTree.Entries { + if entry.Name == "api" { + api = entry.ID + } + } + failing := failTreeReads(t, api) + + if _, err := w.stagedStatus(t.Context(), treeID); !errors.Is(err, ErrReadHeadTree) || failing.Load() == 0 { + t.Fatalf("stagedStatus returned %v after %d failing reads, want ErrReadHeadTree", err, failing.Load()) + } +} diff --git a/internal/gitcore/worktree/headreference_test.go b/internal/gitcore/worktree/headreference_test.go new file mode 100644 index 00000000..17a22f2a --- /dev/null +++ b/internal/gitcore/worktree/headreference_test.go @@ -0,0 +1,116 @@ +package worktree + +import ( + "context" + "fmt" + "slices" + + "github.com/oops1/gogit/internal/gitcore/hash" + "github.com/oops1/gogit/internal/gitcore/index" + "github.com/oops1/gogit/internal/gitcore/object" +) + +type headEntry struct { + Mode object.Mode + ID hash.ObjectID +} + +func (w *Worktree) referenceHeadTree(ctx context.Context, id hash.ObjectID) (map[string]headEntry, error) { + out := map[string]headEntry{} + if id.IsZero() { + return out, nil + } + type frame struct { + id hash.ObjectID + prefix string + } + stack := []frame{{id: id}} + for len(stack) > 0 { + if err := ctx.Err(); err != nil { + return nil, err + } + top := stack[len(stack)-1] + stack = stack[:len(stack)-1] + tree, err := w.db.Tree(top.id) + if err != nil { + return nil, fmt.Errorf("%w: %w", ErrReadHeadTree, err) + } + for _, entry := range tree.Entries { + entryPath := top.prefix + entry.Name + if entry.Mode.IsTree() { + stack = append(stack, frame{id: entry.ID, prefix: entryPath + "/"}) + continue + } + out[entryPath] = headEntry{Mode: entry.Mode, ID: entry.ID} + } + } + return out, nil +} + +func (w *Worktree) referenceStagedStatus(headTree map[string]headEntry) map[string]Entry { + indexPaths := map[string]*index.Entry{} + for entry := range w.currentIndex().Entries() { + if entry.Stage == index.StageMerged { + indexPaths[entry.Path] = entry + } + } + + entries := map[string]Entry{} + var deletedPaths []string + for headPath, he := range headTree { + ie, ok := indexPaths[headPath] + if !ok { + deletedPaths = append(deletedPaths, headPath) + continue + } + if ie.Mode == he.Mode && ie.ID == he.ID { + continue + } + code := StatusModified + if kindOfMode(ie.Mode) != kindOfMode(he.Mode) { + code = StatusTypeChanged + } + entries[headPath] = Entry{Path: headPath, Staged: code, Unstaged: StatusUnmodified} + } + var addedPaths []string + for indexPath := range indexPaths { + if _, ok := headTree[indexPath]; !ok { + addedPaths = append(addedPaths, indexPath) + } + } + slices.Sort(addedPaths) + slices.Sort(deletedPaths) + + byID := map[hash.ObjectID][]string{} + for _, deleted := range deletedPaths { + byID[headTree[deleted].ID] = append(byID[headTree[deleted].ID], deleted) + } + used := map[string]bool{} + for _, added := range addedPaths { + ie := indexPaths[added] + matched := "" + for _, candidate := range byID[ie.ID] { + if used[candidate] { + continue + } + if headTree[candidate].Mode.ObjectType() != ie.Mode.ObjectType() { + continue + } + matched = candidate + break + } + if matched != "" { + used[matched] = true + entries[added] = Entry{Path: added, OrigPath: matched, Staged: StatusRenamed, Unstaged: StatusUnmodified} + continue + } + entries[added] = Entry{Path: added, Staged: StatusAdded, Unstaged: StatusUnmodified} + } + for _, deleted := range deletedPaths { + if used[deleted] { + continue + } + entries[deleted] = Entry{Path: deleted, Staged: StatusDeleted, Unstaged: StatusUnmodified} + } + return entries +} diff --git a/internal/gitcore/worktree/headtree.go b/internal/gitcore/worktree/headtree.go index 5912fcd7..daaf1d40 100644 --- a/internal/gitcore/worktree/headtree.go +++ b/internal/gitcore/worktree/headtree.go @@ -1,22 +1,13 @@ package worktree import ( - "context" "errors" "fmt" - "slices" "github.com/oops1/gogit/internal/gitcore/hash" - "github.com/oops1/gogit/internal/gitcore/index" - "github.com/oops1/gogit/internal/gitcore/object" "github.com/oops1/gogit/internal/gitcore/refs" ) -type headEntry struct { - Mode object.Mode - ID hash.ObjectID -} - const maxHeadHops = 5 func (w *Worktree) resolveHead() (branch string, detached bool, headCommit hash.ObjectID, err error) { @@ -42,103 +33,3 @@ func (w *Worktree) resolveHead() (branch string, detached bool, headCommit hash. } return "", false, hash.Zero, fmt.Errorf("%w: HEAD", refs.ErrTooManySymlinks) } - -func (w *Worktree) collectHeadTree(ctx context.Context, id hash.ObjectID) (map[string]headEntry, error) { - out := map[string]headEntry{} - if id.IsZero() { - return out, nil - } - type frame struct { - id hash.ObjectID - prefix string - } - stack := []frame{{id: id}} - for len(stack) > 0 { - if err := ctx.Err(); err != nil { - return nil, err - } - top := stack[len(stack)-1] - stack = stack[:len(stack)-1] - tree, err := w.db.Tree(top.id) - if err != nil { - return nil, fmt.Errorf("%w: %w", ErrReadHeadTree, err) - } - for _, entry := range tree.Entries { - entryPath := top.prefix + entry.Name - if entry.Mode.IsTree() { - stack = append(stack, frame{id: entry.ID, prefix: entryPath + "/"}) - continue - } - out[entryPath] = headEntry{Mode: entry.Mode, ID: entry.ID} - } - } - return out, nil -} - -func (w *Worktree) stagedStatus(headTree map[string]headEntry) map[string]Entry { - indexPaths := map[string]*index.Entry{} - for entry := range w.currentIndex().Entries() { - if entry.Stage == index.StageMerged { - indexPaths[entry.Path] = entry - } - } - - entries := map[string]Entry{} - var deletedPaths []string - for headPath, he := range headTree { - ie, ok := indexPaths[headPath] - if !ok { - deletedPaths = append(deletedPaths, headPath) - continue - } - if ie.Mode == he.Mode && ie.ID == he.ID { - continue - } - code := StatusModified - if kindOfMode(ie.Mode) != kindOfMode(he.Mode) { - code = StatusTypeChanged - } - entries[headPath] = Entry{Path: headPath, Staged: code, Unstaged: StatusUnmodified} - } - var addedPaths []string - for indexPath := range indexPaths { - if _, ok := headTree[indexPath]; !ok { - addedPaths = append(addedPaths, indexPath) - } - } - slices.Sort(addedPaths) - slices.Sort(deletedPaths) - - byID := map[hash.ObjectID][]string{} - for _, deleted := range deletedPaths { - byID[headTree[deleted].ID] = append(byID[headTree[deleted].ID], deleted) - } - used := map[string]bool{} - for _, added := range addedPaths { - ie := indexPaths[added] - matched := "" - for _, candidate := range byID[ie.ID] { - if used[candidate] { - continue - } - if headTree[candidate].Mode.ObjectType() != ie.Mode.ObjectType() { - continue - } - matched = candidate - break - } - if matched != "" { - used[matched] = true - entries[added] = Entry{Path: added, OrigPath: matched, Staged: StatusRenamed, Unstaged: StatusUnmodified} - continue - } - entries[added] = Entry{Path: added, Staged: StatusAdded, Unstaged: StatusUnmodified} - } - for _, deleted := range deletedPaths { - if used[deleted] { - continue - } - entries[deleted] = Entry{Path: deleted, Staged: StatusDeleted, Unstaged: StatusUnmodified} - } - return entries -} diff --git a/internal/gitcore/worktree/status.go b/internal/gitcore/worktree/status.go index 70a8520b..3922c80a 100644 --- a/internal/gitcore/worktree/status.go +++ b/internal/gitcore/worktree/status.go @@ -8,6 +8,7 @@ import ( "strings" "time" + "github.com/oops1/gogit/internal/gitcore/hash" "github.com/oops1/gogit/internal/gitcore/index" ) @@ -78,18 +79,18 @@ func (w *Worktree) Status(ctx context.Context) (Status, error) { if err != nil { return Status{}, err } - headTree := map[string]headEntry{} + headTree := hash.Zero if !headCommit.IsZero() { commit, err := w.db.Commit(headCommit) if err != nil { return Status{}, fmt.Errorf("%w: %w", ErrReadHead, err) } - headTree, err = w.collectHeadTree(ctx, commit.Tree) - if err != nil { - return Status{}, err - } + headTree = commit.Tree + } + staged, err := w.stagedStatus(ctx, headTree) + if err != nil { + return Status{}, err } - staged := w.stagedStatus(headTree) var mergedEntries []*index.Entry trackedFiles := map[string]bool{} From 6749e024f3d737ddbe50d53bf32b3b7914079d7a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=A7=D1=83=D0=BA=D0=B0=D0=BB=D0=B8=D0=BD=20=D0=92=D0=B0?= =?UTF-8?q?=D0=BB=D0=B5=D1=80=D0=B8=D0=B9?= Date: Fri, 16 Oct 2026 14:38:09 +0300 Subject: [PATCH 15/35] worktree: add status benchmarks for twenty thousand untracked and ignored files --- internal/gitcore/worktree/bench_test.go | 46 +++++++++++++++++++++++++ 1 file changed, 46 insertions(+) diff --git a/internal/gitcore/worktree/bench_test.go b/internal/gitcore/worktree/bench_test.go index 0090fc9f..3595cc38 100644 --- a/internal/gitcore/worktree/bench_test.go +++ b/internal/gitcore/worktree/bench_test.go @@ -83,3 +83,49 @@ func BenchmarkStatusOfFiftyThousandFiles(b *testing.B) { } } } + +func newUntrackedBenchRepo(b *testing.B, tracked, untracked int) *testRepo { + b.Helper() + tr := newTestRepo(b) + for i := range tracked { + tr.stageUnstored(fmt.Sprintf("src/module%03d/pkg%02d/file%05d.go", i%64, i%16, i), fmt.Sprintf("package p\n\nconst N = %d\n", i)) + } + tr.commit("initial") + for i := range untracked { + tr.writeFile(fmt.Sprintf("scratch/area%02d/sub%02d/file%05d.tmp", i%32, i%8, i), "x\n") + } + return tr +} + +func BenchmarkStatusWithTwentyThousandUntrackedFiles(b *testing.B) { + tr := newUntrackedBenchRepo(b, 5000, 20000) + w := tr.open() + ctx := b.Context() + b.ReportAllocs() + b.ResetTimer() + for b.Loop() { + if _, err := w.Status(ctx); err != nil { + b.Fatalf("Status returned error %v", err) + } + } +} + +func BenchmarkStatusWithTwentyThousandIgnoredFiles(b *testing.B) { + tr := newUntrackedBenchRepo(b, 5000, 0) + tr.writeFile(".gitignore", "build/\n*.log\n") + for i := range 20000 { + tr.writeFile(fmt.Sprintf("build/area%02d/sub%02d/file%05d.o", i%32, i%8, i), "x\n") + } + for i := range 2000 { + tr.writeFile(fmt.Sprintf("src/module%03d/pkg00/trace%04d.log", i%64, i), "x\n") + } + w := tr.open() + ctx := b.Context() + b.ReportAllocs() + b.ResetTimer() + for b.Loop() { + if _, err := w.Status(ctx); err != nil { + b.Fatalf("Status returned error %v", err) + } + } +} From c16a0e70068a8fe4805fb4d69728c3b12081a71f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=A7=D1=83=D0=BA=D0=B0=D0=BB=D0=B8=D0=BD=20=D0=92=D0=B0?= =?UTF-8?q?=D0=BB=D0=B5=D1=80=D0=B8=D0=B9?= Date: Fri, 16 Oct 2026 14:39:22 +0300 Subject: [PATCH 16/35] odb: sweep dead entries of the weak object cache lazily instead of registering a cleanup for each value --- internal/gitcore/odb/bench_test.go | 15 +++++++++ internal/gitcore/odb/cache.go | 27 ++++++++++------ internal/gitcore/odb/cache_test.go | 49 ++++++++++++++++++++---------- 3 files changed, 65 insertions(+), 26 deletions(-) diff --git a/internal/gitcore/odb/bench_test.go b/internal/gitcore/odb/bench_test.go index 4275667d..c6a1ad8a 100644 --- a/internal/gitcore/odb/bench_test.go +++ b/internal/gitcore/odb/bench_test.go @@ -63,3 +63,18 @@ func BenchmarkPutBlobOfOneMegabyte(b *testing.B) { } } } + +func BenchmarkWeakCacheOfParsedCommits(b *testing.B) { + cache := newWeakCache[object.Commit]() + var id hash.ObjectID + counter := uint64(0) + b.ReportAllocs() + for b.Loop() { + counter++ + binary.LittleEndian.PutUint64(id[:], counter) + cache.put(id, &object.Commit{Message: "m"}) + if cache.get(id) == nil { + b.Fatal("the commit just stored is gone") + } + } +} diff --git a/internal/gitcore/odb/cache.go b/internal/gitcore/odb/cache.go index 5a669b51..6e95f007 100644 --- a/internal/gitcore/odb/cache.go +++ b/internal/gitcore/odb/cache.go @@ -2,7 +2,6 @@ package odb import ( "container/list" - "runtime" "sync" "weak" @@ -89,9 +88,12 @@ func (c *rawCache) purge() { c.used = 0 } +const weakSweepFloor = 1024 + type weakCache[T any] struct { - mu sync.Mutex - items map[hash.ObjectID]weak.Pointer[T] + mu sync.Mutex + items map[hash.ObjectID]weak.Pointer[T] + sweepAt int } func newWeakCache[T any]() *weakCache[T] { @@ -114,22 +116,26 @@ func (c *weakCache[T]) get(id hash.ObjectID) *T { func (c *weakCache[T]) put(id hash.ObjectID, value *T) { c.mu.Lock() + defer c.mu.Unlock() c.items[id] = weak.Make(value) - c.mu.Unlock() - runtime.AddCleanup(value, c.drop, id) + if len(c.items) >= max(c.sweepAt, weakSweepFloor) { + c.sweepLocked() + c.sweepAt = 2 * len(c.items) + } } -func (c *weakCache[T]) drop(id hash.ObjectID) { - c.mu.Lock() - defer c.mu.Unlock() - if pointer, ok := c.items[id]; ok && pointer.Value() == nil { - delete(c.items, id) +func (c *weakCache[T]) sweepLocked() { + for id, pointer := range c.items { + if pointer.Value() == nil { + delete(c.items, id) + } } } func (c *weakCache[T]) len() int { c.mu.Lock() defer c.mu.Unlock() + c.sweepLocked() return len(c.items) } @@ -137,6 +143,7 @@ func (c *weakCache[T]) purge() { c.mu.Lock() defer c.mu.Unlock() clear(c.items) + c.sweepAt = 0 } type objectCache struct { diff --git a/internal/gitcore/odb/cache_test.go b/internal/gitcore/odb/cache_test.go index 352e274b..b1e8181b 100644 --- a/internal/gitcore/odb/cache_test.go +++ b/internal/gitcore/odb/cache_test.go @@ -1,6 +1,7 @@ package odb import ( + "encoding/binary" "runtime" "testing" "weak" @@ -9,6 +10,12 @@ import ( "github.com/oops1/gogit/internal/gitcore/object" ) +func numberedID(number uint64) hash.ObjectID { + var id hash.ObjectID + binary.LittleEndian.PutUint64(id[:], number) + return id +} + func idFrom(t testing.TB, prefix byte) hash.ObjectID { t.Helper() var id hash.ObjectID @@ -111,28 +118,38 @@ func TestWeakCacheForgetsCollectedValues(t *testing.T) { } } -func TestWeakCacheDropKeepsLiveValues(t *testing.T) { +func TestWeakCacheSweepsCollectedValuesOnceItGrowsPastItsThreshold(t *testing.T) { cache := newWeakCache[object.Blob]() - id := idFrom(t, 12) - blob := &object.Blob{Data: []byte("live")} - cache.put(id, blob) - cache.drop(idFrom(t, 13)) - cache.drop(id) - if cache.len() != 1 { - t.Fatalf("cache holds %d entries, want 1", cache.len()) + for index := range 3 * weakSweepFloor { + cache.put(numberedID(uint64(index)), &object.Blob{Data: []byte("garbage")}) + if index == weakSweepFloor { + collect() + } + } + + cache.mu.Lock() + held := len(cache.items) + cache.mu.Unlock() + if held >= 3*weakSweepFloor { + t.Fatalf("the cache still holds %d entries, want the collected ones swept", held) } - runtime.KeepAlive(blob) } -func TestWeakCacheDropRemovesCollectedValues(t *testing.T) { +func TestWeakCacheKeepsLiveValuesThroughASweep(t *testing.T) { cache := newWeakCache[object.Blob]() - id := idFrom(t, 14) - cache.put(id, &object.Blob{Data: []byte("garbage")}) - collect() - cache.drop(id) - if cache.len() != 0 { - t.Fatalf("cache holds %d entries after drop", cache.len()) + live := make([]*object.Blob, weakSweepFloor+10) + for index := range live { + live[index] = &object.Blob{Data: []byte("live")} + cache.put(numberedID(uint64(index)), live[index]) + } + + if got := cache.len(); got != len(live) { + t.Fatalf("the cache holds %d entries, want all %d live ones", got, len(live)) + } + if cache.get(numberedID(5)) != live[5] { + t.Fatal("a live value was lost in a sweep") } + runtime.KeepAlive(live) } func TestWeakCachePurgeEmptiesEverything(t *testing.T) { From 077c671955e22dad93e6614b574ae8275435ad01 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=A7=D1=83=D0=BA=D0=B0=D0=BB=D0=B8=D0=BD=20=D0=92=D0=B0?= =?UTF-8?q?=D0=BB=D0=B5=D1=80=D0=B8=D0=B9?= Date: Fri, 16 Oct 2026 14:40:07 +0300 Subject: [PATCH 17/35] attributes: let the ignore matcher and attribute lookups serve many goroutines at once --- internal/gitcore/attributes/attributes.go | 36 ++++++---- .../gitcore/attributes/concurrent_test.go | 69 +++++++++++++++++++ internal/gitcore/attributes/ignore.go | 30 ++++---- 3 files changed, 111 insertions(+), 24 deletions(-) create mode 100644 internal/gitcore/attributes/concurrent_test.go diff --git a/internal/gitcore/attributes/attributes.go b/internal/gitcore/attributes/attributes.go index b5cf3912..f97994bf 100644 --- a/internal/gitcore/attributes/attributes.go +++ b/internal/gitcore/attributes/attributes.go @@ -4,6 +4,7 @@ import ( "cmp" "maps" "strings" + "sync" "github.com/oops1/gogit/internal/gitcore/config" "github.com/oops1/gogit/internal/gitcore/hash" @@ -205,7 +206,9 @@ type Attributes struct { resolved map[string]map[string]Value globals [][]attrLine globalErr error - globalsRead bool + globalsOnce sync.Once + mu sync.Mutex + resolvedMu sync.Mutex } func New(opts AttributeOptions) *Attributes { @@ -234,13 +237,19 @@ func (a *Attributes) dirFile(dir string) string { } func (a *Attributes) node(dir string) *attrNode { + a.mu.Lock() + defer a.mu.Unlock() + return a.nodeLocked(dir) +} + +func (a *Attributes) nodeLocked(dir string) *attrNode { if n, ok := a.nodes[dir]; ok { return n } n := &attrNode{} a.nodes[dir] = n if dir != "" { - n.parent = a.node(parentDir(dir)) + n.parent = a.nodeLocked(parentDir(dir)) n.err = n.parent.err } lines, err := a.perDir.get(a.dirFile(dir)) @@ -250,15 +259,13 @@ func (a *Attributes) node(dir string) *attrNode { } func (a *Attributes) globalLists() ([][]attrLine, error) { - if a.globalsRead { - return a.globals, a.globalErr - } - a.globalsRead = true - for _, name := range []string{a.opts.InfoFile, a.opts.AttributesFile, a.opts.SystemFile} { - lines, err := a.globalFiles.get(name) - a.globalErr = cmp.Or(a.globalErr, err) - a.globals = append(a.globals, lines) - } + a.globalsOnce.Do(func() { + for _, name := range []string{a.opts.InfoFile, a.opts.AttributesFile, a.opts.SystemFile} { + lines, err := a.globalFiles.get(name) + a.globalErr = cmp.Or(a.globalErr, err) + a.globals = append(a.globals, lines) + } + }) return a.globals, a.globalErr } @@ -311,7 +318,10 @@ func (a *Attributes) Lookup(path string) (map[string]Value, error) { if isDir { key += "/" } - if cached, ok := a.resolved[key]; ok { + a.resolvedMu.Lock() + cached, ok := a.resolved[key] + a.resolvedMu.Unlock() + if ok { return cached, err } macros := determineMacros(lists) @@ -325,7 +335,9 @@ func (a *Attributes) Lookup(path string) (map[string]Value, error) { fillStates(out, line.states, macros) } } + a.resolvedMu.Lock() a.resolved[key] = out + a.resolvedMu.Unlock() return out, err } diff --git a/internal/gitcore/attributes/concurrent_test.go b/internal/gitcore/attributes/concurrent_test.go new file mode 100644 index 00000000..ed904d0c --- /dev/null +++ b/internal/gitcore/attributes/concurrent_test.go @@ -0,0 +1,69 @@ +package attributes + +import ( + "fmt" + "sync" + "testing" +) + +func concurrentFiles() map[string]string { + files := map[string]string{ + ".gitignore": "*.log\nbuild/\n!keep.log\n", + ".gitattributes": "* text=auto\n*.png binary\n", + } + for dir := range 16 { + files[fmt.Sprintf("d%02d/.gitignore", dir)] = "*.tmp\n!important.tmp\n" + files[fmt.Sprintf("d%02d/.gitattributes", dir)] = "*.go text eol=lf\n" + } + return files +} + +func TestMatcherAnswersTheSameWhenManyGoroutinesAskAtOnce(t *testing.T) { + files := concurrentFiles() + shared := testMatcher(files, IgnoreOptions{}) + var wg sync.WaitGroup + for worker := range 8 { + wg.Go(func() { + for round := range 200 { + dir := (round + worker) % 16 + for name, wantIgnored := range map[string]bool{ + fmt.Sprintf("d%02d/a.log", dir): true, + fmt.Sprintf("d%02d/keep.log", dir): false, + fmt.Sprintf("d%02d/x.tmp", dir): true, + fmt.Sprintf("d%02d/important.tmp", dir): false, + fmt.Sprintf("d%02d/build/o.txt", dir): true, + fmt.Sprintf("d%02d/src/main.go", dir): false, + } { + if got, _ := shared.Ignored(name, false); got != wantIgnored { + t.Errorf("Ignored(%q) = %v, want %v", name, got, wantIgnored) + return + } + } + } + }) + } + wg.Wait() +} + +func TestAttributesAnswerTheSameWhenManyGoroutinesAskAtOnce(t *testing.T) { + shared := New(AttributeOptions{Work: MemoryLoader(concurrentFiles())}) + var wg sync.WaitGroup + for worker := range 8 { + wg.Go(func() { + for round := range 200 { + dir := (round + worker) % 16 + path := fmt.Sprintf("d%02d/src/file%d.go", dir, round%7) + values := shared.Get(path, "text", "eol") + if !values["text"].IsSet() || values["eol"].Text() != "lf" { + t.Errorf("Get(%q) = %v, want text set and eol=lf", path, values) + return + } + if !shared.Get(fmt.Sprintf("d%02d/pic.png", dir), "binary")["binary"].IsSet() { + t.Errorf("pic.png in d%02d is not binary", dir) + return + } + } + }) + } + wg.Wait() +} diff --git a/internal/gitcore/attributes/ignore.go b/internal/gitcore/attributes/ignore.go index 6180f379..e47a4359 100644 --- a/internal/gitcore/attributes/ignore.go +++ b/internal/gitcore/attributes/ignore.go @@ -5,6 +5,7 @@ import ( "iter" "slices" "strings" + "sync" ) const DefaultIgnoreFile = ".gitignore" @@ -101,7 +102,8 @@ type Matcher struct { nodes map[string]*ignoreNode globals [][]Rule globalErr error - globalsRead bool + globalsOnce sync.Once + mu sync.Mutex } func NewMatcher(opts IgnoreOptions) *Matcher { @@ -121,17 +123,15 @@ func NewMatcher(opts IgnoreOptions) *Matcher { } func (m *Matcher) globalLists() ([][]Rule, error) { - if m.globalsRead { - return m.globals, m.globalErr - } - m.globalsRead = true - for _, name := range []string{m.opts.InfoExclude, m.opts.ExcludesFile} { - rules, err := m.globalFiles.get(name) - if err != nil && m.globalErr == nil { - m.globalErr = err + m.globalsOnce.Do(func() { + for _, name := range []string{m.opts.InfoExclude, m.opts.ExcludesFile} { + rules, err := m.globalFiles.get(name) + if err != nil && m.globalErr == nil { + m.globalErr = err + } + m.globals = append(m.globals, rules) } - m.globals = append(m.globals, rules) - } + }) return m.globals, m.globalErr } @@ -143,13 +143,19 @@ func (m *Matcher) dirFile(dir string) string { } func (m *Matcher) node(dir string) *ignoreNode { + m.mu.Lock() + defer m.mu.Unlock() + return m.nodeLocked(dir) +} + +func (m *Matcher) nodeLocked(dir string) *ignoreNode { if n, ok := m.nodes[dir]; ok { return n } n := &ignoreNode{} m.nodes[dir] = n if dir != "" { - n.parent = m.node(parentDir(dir)) + n.parent = m.nodeLocked(parentDir(dir)) n.err = n.parent.err if n.parent.blocked { n.blocked, n.rule = true, n.parent.rule From 8c93e936068dd09f0b7605f3213fc2acbe7f219b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=A7=D1=83=D0=BA=D0=B0=D0=BB=D0=B8=D0=BD=20=D0=92=D0=B0?= =?UTF-8?q?=D0=BB=D0=B5=D1=80=D0=B8=D0=B9?= Date: Fri, 16 Oct 2026 14:40:07 +0300 Subject: [PATCH 18/35] worktree: stop serialising ignore and attribute lookups behind a lock --- internal/gitcore/worktree/worktree.go | 6 ------ 1 file changed, 6 deletions(-) diff --git a/internal/gitcore/worktree/worktree.go b/internal/gitcore/worktree/worktree.go index 5c1c09f3..71d86a77 100644 --- a/internal/gitcore/worktree/worktree.go +++ b/internal/gitcore/worktree/worktree.go @@ -38,9 +38,7 @@ type Worktree struct { indexMu sync.RWMutex root *os.Root ignore *attributes.Matcher - ignoreMu sync.Mutex attrs *attributes.Attributes - attrsMu sync.Mutex env func(string) string format hash.Format fileMode bool @@ -233,15 +231,11 @@ func (w *Worktree) Close() error { } func (w *Worktree) isIgnored(path string, isDir bool) bool { - w.ignoreMu.Lock() - defer w.ignoreMu.Unlock() ignored, _ := w.ignore.Ignored(path, isDir) return ignored } func (w *Worktree) policy(path string) attributes.Policy { - w.attrsMu.Lock() - defer w.attrsMu.Unlock() return w.attrs.Policy(path) } From a9f19515a4cff784ad4234342b9c780ce2c7b018 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=A7=D1=83=D0=BA=D0=B0=D0=BB=D0=B8=D0=BD=20=D0=92=D0=B0?= =?UTF-8?q?=D0=BB=D0=B5=D1=80=D0=B8=D0=B9?= Date: Fri, 16 Oct 2026 14:40:08 +0300 Subject: [PATCH 19/35] worktree: walk untracked directories in parallel, read each once and keep their file stats --- internal/gitcore/worktree/coverage_test.go | 2 +- internal/gitcore/worktree/untracked.go | 268 +++++++++++------- .../gitcore/worktree/untrackedscan_test.go | 151 ++++++++++ internal/gitcore/worktree/workingtree.go | 2 +- 4 files changed, 312 insertions(+), 111 deletions(-) create mode 100644 internal/gitcore/worktree/untrackedscan_test.go diff --git a/internal/gitcore/worktree/coverage_test.go b/internal/gitcore/worktree/coverage_test.go index 94b59d75..be22bd84 100644 --- a/internal/gitcore/worktree/coverage_test.go +++ b/internal/gitcore/worktree/coverage_test.go @@ -179,7 +179,7 @@ func TestCompareToWorktreeDetectsExecutableBitAfterAFullContentRead(t *testing.T w.fileMode = true original := fsLstatFile fsLstatFile = func(root *os.Root, name string) (os.FileInfo, error) { - return fakeFileInfo{mode: 0o755, size: 999, modTime: time.Unix(999, 0)}, nil + return fakeFileInfo{mode: 0o755, size: int64(len("echo\n")), modTime: time.Unix(999, 0)}, nil } t.Cleanup(func() { fsLstatFile = original }) status, err := w.Status(t.Context()) diff --git a/internal/gitcore/worktree/untracked.go b/internal/gitcore/worktree/untracked.go index 925d063d..0131525f 100644 --- a/internal/gitcore/worktree/untracked.go +++ b/internal/gitcore/worktree/untracked.go @@ -3,149 +3,190 @@ package worktree import ( "context" "fmt" + "io/fs" "sync" "sync/atomic" ) +type untrackedScan struct { + w *Worktree + ctx context.Context + trackedDirs map[string]bool + trackedFiles map[string]bool + + mu sync.Mutex + out []Entry + wg sync.WaitGroup + once sync.Once + failure error + count atomic.Int64 + slots chan struct{} +} + func (w *Worktree) untrackedEntries(ctx context.Context, trackedDirs, trackedFiles map[string]bool) ([]Entry, error) { - entries, err := w.readDir("") + scan := &untrackedScan{ + w: w, + ctx: ctx, + trackedDirs: trackedDirs, + trackedFiles: trackedFiles, + slots: make(chan struct{}, w.workers), + } + items, err := w.readDirTyped("") if err != nil { return nil, err } - var ( - mu sync.Mutex - out []Entry - wg sync.WaitGroup - once sync.Once - fail error - count atomic.Int64 - ) - sem := make(chan struct{}, w.workers) - reportFail := func(err error) { once.Do(func() { fail = err }) } - if err := w.countBudget(&count, len(entries)); err != nil { + if err := scan.budget(len(items)); err != nil { + return nil, err + } + scan.visit("", withoutGitDir(items)) + scan.wg.Wait() + if scan.failure != nil { + return nil, scan.failure + } + if err := ctx.Err(); err != nil { return nil, err } + return scan.out, nil +} - var walk func(dir string, items []dirEntry) - recurse := func(rel string) { - children, err := w.readDirTyped(rel) - if err != nil { - reportFail(err) - return - } - if err := w.countBudget(&count, len(children)); err != nil { - reportFail(err) - return +func withoutGitDir(items []dirEntry) []dirEntry { + kept := make([]dirEntry, 0, len(items)) + for _, item := range items { + if item.name != gitDirName { + kept = append(kept, item) } - walk(rel, children) } - walk = func(dir string, items []dirEntry) { - for _, item := range items { - if ctx.Err() != nil { - return - } - rel := joinRel(dir, item.name) - if !item.isDir { - if trackedFiles[rel] { - continue - } - if w.isIgnored(rel, false) { - mu.Lock() - out = append(out, Entry{Path: rel, Staged: StatusUnmodified, Unstaged: StatusIgnored}) - mu.Unlock() - continue - } - mu.Lock() - out = append(out, Entry{Path: rel, Staged: StatusUnmodified, Unstaged: StatusUntracked}) - mu.Unlock() - continue - } - if trackedFiles[rel] { - continue - } - if trackedDirs[rel] { - recurse(rel) - continue - } - has, err := w.hasVisibleFile(rel) - if err != nil { - reportFail(err) - continue - } - if has { - mu.Lock() - out = append(out, Entry{Path: rel + "/", IsDir: true, Staged: StatusUnmodified, Unstaged: StatusUntracked}) - mu.Unlock() - continue - } - anyFile, err := w.hasAnyFile(rel) - if err != nil { - reportFail(err) - continue - } - if anyFile { - mu.Lock() - out = append(out, Entry{Path: rel + "/", IsDir: true, Staged: StatusUnmodified, Unstaged: StatusIgnored}) - mu.Unlock() - } - } + return kept +} + +func (s *untrackedScan) fail(err error) { + s.once.Do(func() { s.failure = err }) +} + +func (s *untrackedScan) budget(added int) error { + if s.w.maxFiles <= 0 { + return nil + } + if s.count.Add(int64(added)) > int64(s.w.maxFiles) { + return fmt.Errorf("%w: %d", ErrTooManyFiles, s.w.maxFiles) + } + return nil +} + +func (s *untrackedScan) record(entry Entry) { + s.mu.Lock() + s.out = append(s.out, entry) + s.mu.Unlock() +} + +func (s *untrackedScan) descend(rel string) { + select { + case s.slots <- struct{}{}: + s.wg.Go(func() { + defer func() { <-s.slots }() + s.enter(rel) + }) + default: + s.enter(rel) } +} + +func (s *untrackedScan) enter(rel string) { + children, err := s.w.readDirTyped(rel) + if err != nil { + s.fail(err) + return + } + if err := s.budget(len(children)); err != nil { + s.fail(err) + return + } + s.visit(rel, children) +} - for _, entry := range entries { - if entry.Name() == gitDirName { +func (s *untrackedScan) visit(dir string, items []dirEntry) { + for _, item := range items { + if s.ctx.Err() != nil { + return + } + rel := joinRel(dir, item.name) + if !item.isDir { + s.visitFile(rel, item) continue } - item := dirEntry{name: entry.Name(), isDir: entry.IsDir()} - sem <- struct{}{} - wg.Go(func() { - defer func() { <-sem }() - walk("", []dirEntry{item}) - }) + s.visitDirectory(rel) } - wg.Wait() +} - if fail != nil { - return nil, fail +func (s *untrackedScan) visitFile(rel string, item dirEntry) { + if s.trackedFiles[rel] { + return } - if err := ctx.Err(); err != nil { - return nil, err + code := StatusUntracked + if s.w.isIgnored(rel, false) { + code = StatusIgnored } - return out, nil + entry := Entry{Path: rel, Staged: StatusUnmodified, Unstaged: code} + if info, ok := item.describe(); ok { + entry.Size, entry.ModTime = info.Size(), info.ModTime() + } + s.record(entry) } -func (w *Worktree) countBudget(count *atomic.Int64, added int) error { - if w.maxFiles <= 0 { - return nil +func (s *untrackedScan) visitDirectory(rel string) { + if s.trackedFiles[rel] { + return } - if count.Add(int64(added)) > int64(w.maxFiles) { - return fmt.Errorf("%w: %d", ErrTooManyFiles, w.maxFiles) + if s.trackedDirs[rel] { + s.descend(rel) + return + } + visible, anyFile, err := s.w.directoryContents(rel) + if err != nil { + s.fail(err) + return + } + switch { + case visible: + s.record(Entry{Path: rel + "/", IsDir: true, Staged: StatusUnmodified, Unstaged: StatusUntracked}) + case anyFile: + s.record(Entry{Path: rel + "/", IsDir: true, Staged: StatusUnmodified, Unstaged: StatusIgnored}) } - return nil } -func (w *Worktree) hasVisibleFile(dir string) (bool, error) { +func (w *Worktree) directoryContents(dir string) (visible, anyFile bool, err error) { items, err := w.readDirTyped(dir) if err != nil { - return false, err + return false, false, err } for _, item := range items { rel := joinRel(dir, item.name) ignored := w.isIgnored(rel, item.isDir) - if ignored { - continue - } - if !item.isDir { - return true, nil - } - has, err := w.hasVisibleFile(rel) - if err != nil { - return false, err - } - if has { - return true, nil + switch { + case !item.isDir: + anyFile = true + if !ignored { + return true, true, nil + } + case ignored: + if anyFile { + continue + } + if anyFile, err = w.hasAnyFile(rel); err != nil { + return false, false, err + } + default: + nestedVisible, nestedAny, err := w.directoryContents(rel) + if err != nil { + return false, false, err + } + if nestedVisible { + return true, true, nil + } + anyFile = anyFile || nestedAny } } - return false, nil + return false, anyFile, nil } func (w *Worktree) hasAnyFile(dir string) (bool, error) { @@ -171,6 +212,15 @@ func (w *Worktree) hasAnyFile(dir string) (bool, error) { type dirEntry struct { name string isDir bool + entry fs.DirEntry +} + +func (e dirEntry) describe() (fs.FileInfo, bool) { + if e.entry == nil { + return nil, false + } + info, err := e.entry.Info() + return info, err == nil } func (w *Worktree) readDirTyped(rel string) ([]dirEntry, error) { @@ -180,7 +230,7 @@ func (w *Worktree) readDirTyped(rel string) ([]dirEntry, error) { } out := make([]dirEntry, len(entries)) for i, entry := range entries { - out[i] = dirEntry{name: entry.Name(), isDir: entry.IsDir()} + out[i] = dirEntry{name: entry.Name(), isDir: entry.IsDir(), entry: entry} } return out, nil } diff --git a/internal/gitcore/worktree/untrackedscan_test.go b/internal/gitcore/worktree/untrackedscan_test.go new file mode 100644 index 00000000..6ebba0c9 --- /dev/null +++ b/internal/gitcore/worktree/untrackedscan_test.go @@ -0,0 +1,151 @@ +package worktree + +import ( + "errors" + "os" + "path/filepath" + "slices" + "testing" +) + +func untrackedPaths(t *testing.T, w *Worktree) map[string]StatusCode { + t.Helper() + status, err := w.Status(t.Context()) + if err != nil { + t.Fatalf("Status returned error %v", err) + } + got := map[string]StatusCode{} + for _, entry := range status.Entries { + got[entry.Path] = entry.Unstaged + } + return got +} + +func TestUntrackedScanWorksInlineWhenEveryWorkerIsBusy(t *testing.T) { + tr := newTestRepo(t) + tr.stage("a/b/c/tracked.txt", "t\n") + tr.stage("a/b/other.txt", "o\n") + tr.commit("initial") + tr.writeFile("a/b/c/new.txt", "n\n") + tr.writeFile("a/b/new.txt", "n\n") + w := tr.openWith(Options{Workers: 1}) + + got := untrackedPaths(t, w) + + if got["a/b/c/new.txt"] != StatusUntracked || got["a/b/new.txt"] != StatusUntracked || len(got) != 2 { + t.Fatalf("Status reported %v, want both new files with one worker", got) + } +} + +func TestAnUntrackedDirectoryWithOnlyIgnoredContentIsReportedIgnored(t *testing.T) { + tr := newTestRepo(t) + tr.stage(".gitignore", "*.log\nlogs/\n") + tr.commit("initial") + tr.writeFile("cache/first.log", "x\n") + tr.writeFile("cache/logs/second.txt", "x\n") + tr.writeFile("deep/only/dirs/third.log", "x\n") + tr.mkdir("empty/nothing/here") + tr.mkdir("hollow/logs/empty") + + got := untrackedPaths(t, tr.open()) + + if got["cache/"] != StatusIgnored || got["deep/"] != StatusIgnored { + t.Fatalf("Status reported %v, want both directories ignored", got) + } + if _, listed := got["hollow/"]; listed { + t.Fatalf("Status listed a directory whose ignored part holds no files: %v", got) + } + if _, listed := got["empty/"]; listed { + t.Fatalf("Status listed a directory without files: %v", got) + } +} + +func TestAnIgnoredSubdirectoryIsSearchedForFilesOnlyWhenNothingElseWasFound(t *testing.T) { + tr := newTestRepo(t) + tr.stage(".gitignore", "logs/\n") + tr.commit("initial") + tr.mkdir("box/logs/inner") + tr.writeFile("box/logs/inner/deep.txt", "x\n") + + got := untrackedPaths(t, tr.open()) + + if got["box/"] != StatusIgnored { + t.Fatalf("Status reported %v, want box/ ignored because of the file under logs/", got) + } +} + +func TestReadingAnUntrackedTreeReportsADirectoryThatCannotBeListed(t *testing.T) { + for _, broken := range []string{"stray/inner", "lone/logs/inner"} { + t.Run(broken, func(t *testing.T) { + tr := newTestRepo(t) + tr.stage(".gitignore", "logs/\n") + tr.commit("initial") + tr.writeFile("stray/inner/y.txt", "x\n") + tr.writeFile("lone/logs/inner/x.txt", "x\n") + w := tr.open() + previous := fsOpenDir + fsOpenDir = func(root *os.Root, name string) (*os.File, error) { + if filepath.ToSlash(name) == broken { + return nil, errors.New("listing refused") + } + return previous(root, name) + } + t.Cleanup(func() { fsOpenDir = previous }) + + if _, err := w.Status(t.Context()); err == nil { + t.Fatalf("Status ignored that %s could not be listed", broken) + } + }) + } +} + +func TestAnIgnoredDirectoryIsSkippedOnceAFileWasFound(t *testing.T) { + tr := newTestRepo(t) + tr.stage(".gitignore", "logs/\n*.log\n") + tr.commit("initial") + tr.writeFile("stray/inner/y.log", "x\n") + tr.writeFile("stray/logs/inner/x.txt", "x\n") + w := tr.open() + previous := fsOpenDir + fsOpenDir = func(root *os.Root, name string) (*os.File, error) { + if filepath.ToSlash(name) == "stray/logs" { + return nil, errors.New("this directory must not be read") + } + return previous(root, name) + } + t.Cleanup(func() { fsOpenDir = previous }) + + got := untrackedPaths(t, w) + + if got["stray/"] != StatusIgnored { + t.Fatalf("Status reported %v, want stray/ ignored without reading stray/logs", got) + } +} + +func TestAnEntryWithoutDirectoryInformationHasNothingToDescribe(t *testing.T) { + if info, ok := (dirEntry{name: "x"}).describe(); ok || info != nil { + t.Fatalf("describe = %v, %v, want nothing", info, ok) + } +} + +func TestUntrackedFilesCarryTheirSizeAndTimeFromTheListing(t *testing.T) { + tr := newTestRepo(t) + tr.stage("kept.txt", "k\n") + tr.commit("initial") + tr.writeFile("fresh.txt", "twelve bytes") + w := tr.open() + stated := countLstatCalls(t, "fresh.txt") + + status, err := w.Status(t.Context()) + + if err != nil { + t.Fatalf("Status returned error %v", err) + } + at := slices.IndexFunc(status.Entries, func(e Entry) bool { return e.Path == "fresh.txt" }) + if at < 0 || status.Entries[at].Size != 12 || status.Entries[at].ModTime.IsZero() { + t.Fatalf("fresh.txt = %+v, want its size and time", status.Entries) + } + if calls := stated.Load(); calls != 0 { + t.Fatalf("an untracked file was stated %d times, want its listing reused", calls) + } +} diff --git a/internal/gitcore/worktree/workingtree.go b/internal/gitcore/worktree/workingtree.go index 3d06127a..e0aefb0d 100644 --- a/internal/gitcore/worktree/workingtree.go +++ b/internal/gitcore/worktree/workingtree.go @@ -219,7 +219,7 @@ func (w *Worktree) holdsPlainSymlink(wantKind entryKind, fi os.FileInfo) bool { } func (w *Worktree) fillWorkingInfo(e *Entry, known map[string]workingStat) { - if e.IsDir { + if e.IsDir || !e.ModTime.IsZero() { return } if stat, ok := known[e.Path]; ok { From f5c8a08e94b784215589461b7de8df5e35439d09 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=A7=D1=83=D0=BA=D0=B0=D0=BB=D0=B8=D0=BD=20=D0=92=D0=B0?= =?UTF-8?q?=D0=BB=D0=B5=D1=80=D0=B8=D0=B9?= Date: Fri, 16 Oct 2026 14:41:22 +0300 Subject: [PATCH 20/35] odb: split the raw object cache into shards so parallel readers stop sharing one lock --- internal/gitcore/odb/bench_test.go | 52 +++++++++++++++++++++++ internal/gitcore/odb/cache.go | 68 +++++++++++++++++++++++++----- internal/gitcore/odb/cache_test.go | 66 +++++++++++++++++++++++++++++ 3 files changed, 176 insertions(+), 10 deletions(-) diff --git a/internal/gitcore/odb/bench_test.go b/internal/gitcore/odb/bench_test.go index c6a1ad8a..51be4da8 100644 --- a/internal/gitcore/odb/bench_test.go +++ b/internal/gitcore/odb/bench_test.go @@ -78,3 +78,55 @@ func BenchmarkWeakCacheOfParsedCommits(b *testing.B) { } } } + +func BenchmarkGetFromPackWithAWarmCacheInParallel(b *testing.B) { + db, ids := packedBenchmarkDB(b, Options{}) + for _, id := range ids { + if _, _, err := db.Get(id); err != nil { + b.Fatalf("Get(%s) returned error %v", id, err) + } + } + b.ReportAllocs() + b.RunParallel(func(pb *testing.PB) { + at := 0 + for pb.Next() { + if _, _, err := db.Get(ids[at%len(ids)]); err != nil { + b.Errorf("Get returned error %v", err) + return + } + at++ + } + }) +} + +func benchmarkRawCacheInParallel(b *testing.B, limit int64) { + cache := newRawCache(limit) + const entries = 4096 + ids := make([]hash.ObjectID, entries) + for at := range ids { + binary.LittleEndian.PutUint64(ids[at][4:], uint64(at)*2654435761) + ids[at][0] = byte(at * 7) + cache.put(ids[at], object.TypeBlob, []byte("payload")) + } + b.ReportAllocs() + b.RunParallel(func(pb *testing.PB) { + at := 0 + for pb.Next() { + if _, _, ok := cache.get(ids[at%entries]); !ok { + b.Error("an entry is missing") + return + } + at += 7 + } + }) +} + +func BenchmarkRawCacheOfOneShardInParallel(b *testing.B) { benchmarkRawCacheInParallel(b, 1<<20) } + +func BenchmarkRawCacheOfDefaultSizeInParallel(b *testing.B) { + benchmarkRawCacheInParallel(b, DefaultCacheBytes) +} + +func BenchmarkRawCacheOfSixteenShardsInParallel(b *testing.B) { + benchmarkRawCacheInParallel(b, 16*rawShardBytes) +} diff --git a/internal/gitcore/odb/cache.go b/internal/gitcore/odb/cache.go index 6e95f007..9031048b 100644 --- a/internal/gitcore/odb/cache.go +++ b/internal/gitcore/odb/cache.go @@ -15,7 +15,12 @@ type rawEntry struct { data []byte } -type rawCache struct { +const ( + rawShardBytes = 2 << 20 + rawShardLimit = 16 +) + +type rawShard struct { mu sync.Mutex limit int64 used int64 @@ -23,15 +28,58 @@ type rawCache struct { items map[hash.ObjectID]*list.Element } +type rawCache struct { + shards []*rawShard +} + func newRawCache(limit int64) *rawCache { - return &rawCache{ - limit: limit, - order: list.New(), - items: make(map[hash.ObjectID]*list.Element), + count := int(min(rawShardLimit, max(1, limit/rawShardBytes))) + cache := &rawCache{shards: make([]*rawShard, count)} + for at := range cache.shards { + cache.shards[at] = &rawShard{ + limit: limit / int64(count), + order: list.New(), + items: make(map[hash.ObjectID]*list.Element), + } } + return cache +} + +func (c *rawCache) shardOf(id hash.ObjectID) *rawShard { + return c.shards[int(id[0])%len(c.shards)] } func (c *rawCache) get(id hash.ObjectID) (object.Type, []byte, bool) { + return c.shardOf(id).get(id) +} + +func (c *rawCache) put(id hash.ObjectID, kind object.Type, data []byte) { + c.shardOf(id).put(id, kind, data) +} + +func (c *rawCache) bytes() int64 { + var total int64 + for _, shard := range c.shards { + total += shard.bytes() + } + return total +} + +func (c *rawCache) len() int { + total := 0 + for _, shard := range c.shards { + total += shard.len() + } + return total +} + +func (c *rawCache) purge() { + for _, shard := range c.shards { + shard.purge() + } +} + +func (c *rawShard) get(id hash.ObjectID) (object.Type, []byte, bool) { c.mu.Lock() defer c.mu.Unlock() element, ok := c.items[id] @@ -43,7 +91,7 @@ func (c *rawCache) get(id hash.ObjectID) (object.Type, []byte, bool) { return entry.kind, entry.data, true } -func (c *rawCache) put(id hash.ObjectID, kind object.Type, data []byte) { +func (c *rawShard) put(id hash.ObjectID, kind object.Type, data []byte) { size := int64(len(data)) if size > c.limit { return @@ -61,26 +109,26 @@ func (c *rawCache) put(id hash.ObjectID, kind object.Type, data []byte) { } } -func (c *rawCache) evict(element *list.Element) { +func (c *rawShard) evict(element *list.Element) { entry := element.Value.(*rawEntry) c.order.Remove(element) delete(c.items, entry.id) c.used -= int64(len(entry.data)) } -func (c *rawCache) bytes() int64 { +func (c *rawShard) bytes() int64 { c.mu.Lock() defer c.mu.Unlock() return c.used } -func (c *rawCache) len() int { +func (c *rawShard) len() int { c.mu.Lock() defer c.mu.Unlock() return len(c.items) } -func (c *rawCache) purge() { +func (c *rawShard) purge() { c.mu.Lock() defer c.mu.Unlock() c.order.Init() diff --git a/internal/gitcore/odb/cache_test.go b/internal/gitcore/odb/cache_test.go index b1e8181b..999b797a 100644 --- a/internal/gitcore/odb/cache_test.go +++ b/internal/gitcore/odb/cache_test.go @@ -199,3 +199,69 @@ func TestWeakCacheForgetsCollectedValuesOnRead(t *testing.T) { t.Fatalf("cache holds %d entries after a read", cache.len()) } } + +func TestRawCacheUsesOneShardPerTwoMegabytesUpToSixteen(t *testing.T) { + tests := []struct { + limit int64 + want int + }{ + {1, 1}, {rawShardBytes - 1, 1}, {rawShardBytes, 1}, {3 * rawShardBytes, 3}, + {DefaultCacheBytes, DefaultCacheBytes / rawShardBytes}, {1 << 40, rawShardLimit}, + } + for _, tc := range tests { + if got := len(newRawCache(tc.limit).shards); got != tc.want { + t.Errorf("a limit of %d gives %d shards, want %d", tc.limit, got, tc.want) + } + } +} + +func TestRawCacheSpreadsEntriesAcrossShardsAndSumsThem(t *testing.T) { + cache := newRawCache(4 * rawShardBytes) + for prefix := range byte(40) { + cache.put(idFrom(t, prefix), object.TypeBlob, []byte("12345")) + } + + used := 0 + for _, shard := range cache.shards { + if shard.len() > 0 { + used++ + } + } + if used != len(cache.shards) || cache.len() != 40 || cache.bytes() != 200 { + t.Fatalf("%d shards hold %d entries and %d bytes, want 40 entries and 200 bytes in every shard", used, cache.len(), cache.bytes()) + } + cache.purge() + if cache.len() != 0 || cache.bytes() != 0 { + t.Fatalf("cache holds %d entries and %d bytes after purge", cache.len(), cache.bytes()) + } +} + +func TestRawCacheEvictsOnlyWithinTheShardThatIsFull(t *testing.T) { + cache := newRawCache(2 * rawShardBytes) + half := make([]byte, rawShardBytes*3/4) + first, second := idFrom(t, 2), idFrom(t, 4) + other := idFrom(t, 3) + cache.put(first, object.TypeBlob, half) + cache.put(other, object.TypeBlob, half) + cache.put(second, object.TypeBlob, half) + + if _, _, ok := cache.get(first); ok { + t.Fatal("the oldest entry of the full shard survived") + } + if _, _, ok := cache.get(second); !ok { + t.Fatal("the newest entry of the full shard was lost") + } + if _, _, ok := cache.get(other); !ok { + t.Fatal("an entry of another shard was evicted") + } +} + +func TestRawCacheRefusesAnEntryLargerThanItsShard(t *testing.T) { + cache := newRawCache(4 * rawShardBytes) + + cache.put(idFrom(t, 1), object.TypeBlob, make([]byte, rawShardBytes+1)) + + if cache.len() != 0 { + t.Fatalf("cache holds %d entries, want the oversized one refused", cache.len()) + } +} From ee34e735d0c6df5eaa2e31d4f4743ae7cfd93ef6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=A7=D1=83=D0=BA=D0=B0=D0=BB=D0=B8=D0=BD=20=D0=92=D0=B0?= =?UTF-8?q?=D0=BB=D0=B5=D1=80=D0=B8=D0=B9?= Date: Fri, 16 Oct 2026 14:42:25 +0300 Subject: [PATCH 21/35] journal: hand the grid the accumulated rows once per page instead of copying them twice --- internal/ui/journal/view.go | 9 ++++--- internal/ui/journal/view_test.go | 44 ++++++++++++++++++++++++++++++++ 2 files changed, 50 insertions(+), 3 deletions(-) diff --git a/internal/ui/journal/view.go b/internal/ui/journal/view.go index 986ad305..31329e16 100644 --- a/internal/ui/journal/view.go +++ b/internal/ui/journal/view.go @@ -2,6 +2,7 @@ package journal import ( "image/color" + "slices" "sync" "github.com/oops1/headless-gui/v3/widget" @@ -15,6 +16,7 @@ const nearEndRows = 5 type View struct { grid *widget.DataGridWidget items *datagrid.ObservableCollection + shown []any columnsMu sync.Mutex authorHeader string fullAuthorName bool @@ -83,6 +85,7 @@ func (v *View) installMessageColumn() { } func (v *View) Reset() { + v.shown = nil v.items.Clear() v.lanes.Reset() v.resizeToVisibleRows() @@ -151,12 +154,12 @@ func (v *View) ClearSelection() { } func (v *View) Append(rows []Row) { - items := v.items.Items() + v.shown = slices.Grow(v.shown, len(rows)) for _, row := range rows { row.Graph = v.lanes.Add(graph.Commit{ID: row.ID, Parents: row.Parents}) - items = append(items, row) + v.shown = append(v.shown, row) } - v.items.SetItems(items) + v.items.SetItems(v.shown) v.resizeToVisibleRows() } diff --git a/internal/ui/journal/view_test.go b/internal/ui/journal/view_test.go index 9f139b84..6b1a276c 100644 --- a/internal/ui/journal/view_test.go +++ b/internal/ui/journal/view_test.go @@ -299,3 +299,47 @@ func TestARowOfAnotherKindIsSkippedWhenTheLanesAreCounted(t *testing.T) { t.Fatal("a row that is not a commit must not widen the graph") } } + +func TestAppendAfterResetShowsOnlyTheNewRows(t *testing.T) { + v, grid := bound(t) + v.Append(sampleRows(4)) + v.Reset() + fresh := sampleRows(2) + + v.Append(fresh) + + if v.Count() != 2 || grid.Grid.ItemsSource().Count() != 2 { + t.Fatalf("Count() = %d, grid holds %d, want only the two new rows", v.Count(), grid.Grid.ItemsSource().Count()) + } + if got, _ := grid.Grid.ItemsSource().Get(0).(Row); got.ID != fresh[0].ID { + t.Fatalf("the first row is %s, want %s", got.ID, fresh[0].ID) + } +} + +func TestAppendKeepsEveryPageInOrder(t *testing.T) { + v, grid := bound(t) + var want []Row + for range 5 { + page := sampleRows(3) + want = append(want, page...) + v.Append(page) + } + + for at, row := range want { + if got, _ := grid.Grid.ItemsSource().Get(at).(Row); got.ID != row.ID { + t.Fatalf("row %d is %s, want %s", at, got.ID, row.ID) + } + } +} + +func BenchmarkAppendingTwoHundredPagesToTheJournal(b *testing.B) { + page := sampleRows(500) + b.ReportAllocs() + for b.Loop() { + v := NewView() + v.Bind(widget.NewDataGridWidget()) + for range 200 { + v.Append(page) + } + } +} From c7bc98f85225dd42edecdffca3294535c6779631 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=A7=D1=83=D0=BA=D0=B0=D0=BB=D0=B8=D0=BD=20=D0=92=D0=B0?= =?UTF-8?q?=D0=BB=D0=B5=D1=80=D0=B8=D0=B9?= Date: Fri, 16 Oct 2026 14:44:23 +0300 Subject: [PATCH 22/35] revision: let a series of walks share the commits and trees they have parsed --- internal/gitcore/revision/context.go | 25 +++++++-- internal/gitcore/revision/parsedshare_test.go | 54 +++++++++++++++++++ 2 files changed, 76 insertions(+), 3 deletions(-) create mode 100644 internal/gitcore/revision/parsedshare_test.go diff --git a/internal/gitcore/revision/context.go b/internal/gitcore/revision/context.go index 626eea9a..0cb1d4db 100644 --- a/internal/gitcore/revision/context.go +++ b/internal/gitcore/revision/context.go @@ -41,6 +41,21 @@ type Context struct { Head refs.Name Shallow map[hash.ObjectID]struct{} Graph *commitgraph.Graph + Parsed *ParsedObjects +} + +type ParsedObjects struct { + commits map[hash.ObjectID]*object.Commit + trees map[hash.ObjectID]*object.Tree + paths map[pathKey]pathValue +} + +func NewParsedObjects() *ParsedObjects { + return &ParsedObjects{ + commits: make(map[hash.ObjectID]*object.Commit), + trees: make(map[hash.ObjectID]*object.Tree), + paths: make(map[pathKey]pathValue), + } } type Rev struct { @@ -70,11 +85,15 @@ type store struct { } func newStore(ctx Context) *store { + parsed := ctx.Parsed + if parsed == nil { + parsed = NewParsedObjects() + } return &store{ objects: ctx.Objects, - commits: make(map[hash.ObjectID]*object.Commit), - trees: make(map[hash.ObjectID]*object.Tree), - paths: make(map[pathKey]pathValue), + commits: parsed.commits, + trees: parsed.trees, + paths: parsed.paths, shallow: ctx.Shallow, graph: ctx.Graph, } diff --git a/internal/gitcore/revision/parsedshare_test.go b/internal/gitcore/revision/parsedshare_test.go new file mode 100644 index 00000000..3fa3d6a5 --- /dev/null +++ b/internal/gitcore/revision/parsedshare_test.go @@ -0,0 +1,54 @@ +package revision + +import ( + "testing" + + "github.com/oops1/gogit/internal/gitcore/hash" +) + +func walkAll(t *testing.T, opts Options) int { + t.Helper() + count := 0 + for _, err := range Walk(t.Context(), opts) { + if err != nil { + t.Fatalf("Walk returned error %v", err) + } + count++ + } + return count +} + +func TestWalksSharingParsedObjectsReadEachCommitOnce(t *testing.T) { + b := newBuilder(t) + b.commit("a") + b.commit("b", "a") + b.commit("c", "b") + source := b.context() + source.Parsed = NewParsedObjects() + + first := walkAll(t, Options{Context: source, Include: []hash.ObjectID{b.id("c")}}) + reads := b.objects.gets + second := walkAll(t, Options{Context: source, Include: []hash.ObjectID{b.id("c")}}) + + if first != 3 || second != 3 { + t.Fatalf("the walks listed %d and %d commits, want three each", first, second) + } + if b.objects.gets != reads { + t.Fatalf("the second walk read %d objects, want none", b.objects.gets-reads) + } +} + +func TestWalksWithoutSharedParsedObjectsReadAgain(t *testing.T) { + b := newBuilder(t) + b.commit("a") + b.commit("b", "a") + source := b.context() + + walkAll(t, Options{Context: source, Include: []hash.ObjectID{b.id("b")}}) + reads := b.objects.gets + walkAll(t, Options{Context: source, Include: []hash.ObjectID{b.id("b")}}) + + if b.objects.gets == reads { + t.Fatal("a walk without shared parsed objects read nothing") + } +} From 3cb325bd7b9b0c24a1815cfd0d885ce6a61bfc82 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=A7=D1=83=D0=BA=D0=B0=D0=BB=D0=B8=D0=BD=20=D0=92=D0=B0?= =?UTF-8?q?=D0=BB=D0=B5=D1=80=D0=B8=D0=B9?= Date: Fri, 16 Oct 2026 14:44:23 +0300 Subject: [PATCH 23/35] repo: count the divergence of every branch pair on commits parsed once --- internal/repo/divergence.go | 3 +++ internal/repo/divergence_test.go | 42 ++++++++++++++++++++++++++++++++ 2 files changed, 45 insertions(+) diff --git a/internal/repo/divergence.go b/internal/repo/divergence.go index a95a06dd..cd167517 100644 --- a/internal/repo/divergence.go +++ b/internal/repo/divergence.go @@ -104,6 +104,9 @@ func ManyAheadBehind(r *gitrepo.Repository, pairs []BranchPair) (map[refs.Name]D } func ManyAheadBehindIn(revCtx revision.Context, pairs []BranchPair) (map[refs.Name]Divergence, error) { + if revCtx.Parsed == nil { + revCtx.Parsed = revision.NewParsedObjects() + } result := make(map[refs.Name]Divergence, len(pairs)) for _, pair := range pairs { ahead, err := countDivergenceCommits(revCtx, pair.Local, pair.Remote) diff --git a/internal/repo/divergence_test.go b/internal/repo/divergence_test.go index 77cb65d1..26674476 100644 --- a/internal/repo/divergence_test.go +++ b/internal/repo/divergence_test.go @@ -2,6 +2,7 @@ package repo import ( "errors" + "fmt" "os" "path/filepath" "strings" @@ -482,3 +483,44 @@ func TestManyAheadBehindInCountsPairsOnTheContextItIsGiven(t *testing.T) { t.Fatalf("ManyAheadBehindIn returned %v, %v, want one ahead and one behind", got, err) } } + +type countingObjects struct { + inner revision.Objects + reads map[hash.ObjectID]int +} + +func (c *countingObjects) Get(id hash.ObjectID) (object.Type, []byte, error) { + c.reads[id]++ + return c.inner.Get(id) +} + +func TestManyAheadBehindInReadsEachCommitOnceAcrossAllPairs(t *testing.T) { + db, _ := openDivergenceWriters(t, newDivergenceRepoDir(t, "main")) + tip := putDivergenceCommit(t, db, "root") + for step := range 20 { + tip = putDivergenceCommit(t, db, fmt.Sprintf("base %d", step), tip) + } + var pairs []BranchPair + for branch := range 30 { + first := putDivergenceCommit(t, db, fmt.Sprintf("branch %d first", branch), tip) + second := putDivergenceCommit(t, db, fmt.Sprintf("branch %d second", branch), first) + pairs = append(pairs, BranchPair{Name: refs.BranchName(fmt.Sprintf("b%02d", branch)), Local: second, Remote: tip}) + } + counting := &countingObjects{inner: db, reads: map[hash.ObjectID]int{}} + + got, err := ManyAheadBehindIn(revision.Context{Objects: counting}, pairs) + + if err != nil { + t.Fatalf("ManyAheadBehindIn returned error %v", err) + } + for _, pair := range pairs { + if got[pair.Name] != (Divergence{Ahead: 2}) { + t.Fatalf("%s = %+v, want two ahead", pair.Name, got[pair.Name]) + } + } + for id, reads := range counting.reads { + if reads > 1 { + t.Fatalf("commit %s was read %d times, want once for the whole computation", id, reads) + } + } +} From 06949aad6b8907a784b9a2c1499f8ca68ed5e864 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=A7=D1=83=D0=BA=D0=B0=D0=BB=D0=B8=D0=BD=20=D0=92=D0=B0?= =?UTF-8?q?=D0=BB=D0=B5=D1=80=D0=B8=D0=B9?= Date: Fri, 16 Oct 2026 14:45:51 +0300 Subject: [PATCH 24/35] pack: read packfiles and their indexes through a memory mapping when the platform allows it --- .golangci.yml | 4 + internal/gitcore/pack/index.go | 6 +- internal/gitcore/pack/mapped.go | 76 ++++++++ internal/gitcore/pack/mapped_linux.go | 15 ++ internal/gitcore/pack/mapped_linux_test.go | 19 ++ internal/gitcore/pack/mapped_other.go | 14 ++ internal/gitcore/pack/mapped_test.go | 205 +++++++++++++++++++++ internal/gitcore/pack/mapped_windows.go | 22 +++ internal/gitcore/pack/pack.go | 6 +- 9 files changed, 363 insertions(+), 4 deletions(-) create mode 100644 internal/gitcore/pack/mapped.go create mode 100644 internal/gitcore/pack/mapped_linux.go create mode 100644 internal/gitcore/pack/mapped_linux_test.go create mode 100644 internal/gitcore/pack/mapped_other.go create mode 100644 internal/gitcore/pack/mapped_test.go create mode 100644 internal/gitcore/pack/mapped_windows.go diff --git a/.golangci.yml b/.golangci.yml index 2814b995..27244dfe 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -83,6 +83,10 @@ linters: - path: internal/gitcore/transport/httpproxy_test\.go linters: - gosec + - path: internal/gitcore/pack/mapped_windows\.go + linters: + - gosec + text: "G103" - path: internal/gitcore/credential/wincredapi_windows\.go linters: - gosec diff --git a/internal/gitcore/pack/index.go b/internal/gitcore/pack/index.go index 1fcc26e3..67d7bf14 100644 --- a/internal/gitcore/pack/index.go +++ b/internal/gitcore/pack/index.go @@ -80,11 +80,13 @@ func NewIndexFile(file *os.File) (*Index, error) { if err != nil { return nil, err } - index, err := NewIndex(file, info.Size()) + source, closer := sourceOf(file, info.Size()) + index, err := NewIndex(source, info.Size()) if err != nil { + _ = closer.Close() return nil, err } - index.closer = file + index.closer = closer index.path = file.Name() return index, nil } diff --git a/internal/gitcore/pack/mapped.go b/internal/gitcore/pack/mapped.go new file mode 100644 index 00000000..d0eef867 --- /dev/null +++ b/internal/gitcore/pack/mapped.go @@ -0,0 +1,76 @@ +package pack + +import ( + "fmt" + "io" + "os" + "runtime/debug" + "sync" +) + +var mapFile = mapFileView + +type mappedFile struct { + mu sync.RWMutex + file *os.File + data []byte + release func() error +} + +func newMappedFile(file *os.File, size int64) (*mappedFile, error) { + data, release, err := mapFile(file, size) + if err != nil { + return nil, err + } + return &mappedFile{file: file, data: data, release: release}, nil +} + +func sourceOf(file *os.File, size int64) (io.ReaderAt, io.Closer) { + if mapped, err := newMappedFile(file, size); err == nil { + return mapped, mapped + } + return file, file +} + +func (m *mappedFile) ReadAt(p []byte, offset int64) (read int, err error) { + if offset < 0 { + return 0, fmt.Errorf("pack: negative offset %d", offset) + } + m.mu.RLock() + defer m.mu.RUnlock() + if m.data == nil { + return 0, os.ErrClosed + } + if offset >= int64(len(m.data)) { + if len(p) == 0 { + return 0, nil + } + return 0, io.EOF + } + previous := debug.SetPanicOnFault(true) + defer func() { + debug.SetPanicOnFault(previous) + if recovered := recover(); recovered != nil { + read, err = 0, fmt.Errorf("pack: the mapped file changed under the reader: %v", recovered) + } + }() + read = copy(p, m.data[offset:]) + if read < len(p) { + return read, io.EOF + } + return read, nil +} + +func (m *mappedFile) Close() error { + m.mu.Lock() + defer m.mu.Unlock() + if m.data == nil { + return &os.PathError{Op: "close", Path: m.file.Name(), Err: os.ErrClosed} + } + m.data = nil + unmapErr := m.release() + if err := m.file.Close(); err != nil { + return err + } + return unmapErr +} diff --git a/internal/gitcore/pack/mapped_linux.go b/internal/gitcore/pack/mapped_linux.go new file mode 100644 index 00000000..1a48f62c --- /dev/null +++ b/internal/gitcore/pack/mapped_linux.go @@ -0,0 +1,15 @@ +package pack + +import ( + "os" + + "golang.org/x/sys/unix" +) + +func mapFileView(file *os.File, size int64) ([]byte, func() error, error) { + data, err := unix.Mmap(int(file.Fd()), 0, int(size), unix.PROT_READ, unix.MAP_SHARED) + if err != nil { + return nil, nil, err + } + return data, func() error { return unix.Munmap(data) }, nil +} diff --git a/internal/gitcore/pack/mapped_linux_test.go b/internal/gitcore/pack/mapped_linux_test.go new file mode 100644 index 00000000..5e98e614 --- /dev/null +++ b/internal/gitcore/pack/mapped_linux_test.go @@ -0,0 +1,19 @@ +package pack + +import ( + "os" + "testing" +) + +func TestReadingAMappedFileThatWasTruncatedReportsAnErrorInsteadOfCrashing(t *testing.T) { + mapped, path := mappedFileWith(t, make([]byte, 3*os.Getpagesize())) + if err := os.Truncate(path, 0); err != nil { + t.Fatalf("Truncate returned error %v", err) + } + + _, err := mapped.ReadAt(make([]byte, 100), int64(2*os.Getpagesize())) + + if err == nil { + t.Fatal("ReadAt of a truncated mapping returned no error") + } +} diff --git a/internal/gitcore/pack/mapped_other.go b/internal/gitcore/pack/mapped_other.go new file mode 100644 index 00000000..f8fa9b90 --- /dev/null +++ b/internal/gitcore/pack/mapped_other.go @@ -0,0 +1,14 @@ +//go:build !linux && !windows + +package pack + +import ( + "errors" + "os" +) + +var errMappingUnsupported = errors.New("pack: memory mapping is not supported on this platform") + +func mapFileView(*os.File, int64) ([]byte, func() error, error) { + return nil, nil, errMappingUnsupported +} diff --git a/internal/gitcore/pack/mapped_test.go b/internal/gitcore/pack/mapped_test.go new file mode 100644 index 00000000..71aaba76 --- /dev/null +++ b/internal/gitcore/pack/mapped_test.go @@ -0,0 +1,205 @@ +package pack + +import ( + "bytes" + "errors" + "io" + "os" + "path/filepath" + "sync" + "testing" +) + +func mappedFileWith(t *testing.T, content []byte) (*mappedFile, string) { + t.Helper() + path := filepath.Join(t.TempDir(), "data") + if err := os.WriteFile(path, content, 0o600); err != nil { + t.Fatalf("WriteFile returned error %v", err) + } + file, err := os.Open(path) + if err != nil { + t.Fatalf("Open returned error %v", err) + } + mapped, err := newMappedFile(file, int64(len(content))) + if err != nil { + _ = file.Close() + t.Fatalf("newMappedFile returned error %v", err) + } + t.Cleanup(func() { _ = mapped.Close() }) + return mapped, path +} + +func TestMappedFileReadsLikeAFile(t *testing.T) { + mapped, _ := mappedFileWith(t, []byte("0123456789")) + + whole := make([]byte, 4) + if n, err := mapped.ReadAt(whole, 3); n != 4 || err != nil || string(whole) != "3456" { + t.Fatalf("ReadAt inside the file = %d, %v, %q", n, err, whole) + } + tail := make([]byte, 8) + if n, err := mapped.ReadAt(tail, 6); n != 4 || !errors.Is(err, io.EOF) || string(tail[:n]) != "6789" { + t.Fatalf("ReadAt across the end = %d, %v, %q", n, err, tail[:n]) + } + if n, err := mapped.ReadAt(tail, 10); n != 0 || !errors.Is(err, io.EOF) { + t.Fatalf("ReadAt at the end = %d, %v, want EOF", n, err) + } + if n, err := mapped.ReadAt(tail, 99); n != 0 || !errors.Is(err, io.EOF) { + t.Fatalf("ReadAt past the end = %d, %v, want EOF", n, err) + } + if n, err := mapped.ReadAt(nil, 10); n != 0 || err != nil { + t.Fatalf("an empty ReadAt at the end = %d, %v, want nothing", n, err) + } + if _, err := mapped.ReadAt(tail, -1); err == nil { + t.Fatal("ReadAt accepted a negative offset") + } +} + +func TestMappedFileServesManyReadersAtOnce(t *testing.T) { + content := bytes.Repeat([]byte("abcdefghij"), 1000) + mapped, _ := mappedFileWith(t, content) + var wg sync.WaitGroup + for worker := range 8 { + wg.Go(func() { + buffer := make([]byte, 100) + for round := range 200 { + offset := int64((worker*37 + round*91) % (len(content) - len(buffer))) + if n, err := mapped.ReadAt(buffer, offset); n != len(buffer) || err != nil || !bytes.Equal(buffer, content[offset:offset+100]) { + t.Errorf("ReadAt(%d) = %d, %v", offset, n, err) + return + } + } + }) + } + wg.Wait() +} + +func TestMappedFileCloseUnmapsOnceAndReportsAClosedFile(t *testing.T) { + mapped, _ := mappedFileWith(t, []byte("data")) + + if err := mapped.Close(); err != nil { + t.Fatalf("Close returned error %v", err) + } + if err := mapped.Close(); !errors.Is(err, os.ErrClosed) { + t.Fatalf("a second Close returned %v, want os.ErrClosed", err) + } + if _, err := mapped.ReadAt(make([]byte, 1), 0); !errors.Is(err, os.ErrClosed) { + t.Fatalf("ReadAt after Close returned %v, want os.ErrClosed", err) + } +} + +func TestMappedFileCloseReportsWhatTheUnmappingAndTheFileReport(t *testing.T) { + boom := errors.New("unmapping failed") + path := filepath.Join(t.TempDir(), "data") + if err := os.WriteFile(path, []byte("data"), 0o600); err != nil { + t.Fatal(err) + } + previous := mapFile + mapFile = func(file *os.File, size int64) ([]byte, func() error, error) { + data, release, err := previous(file, size) + if err != nil { + return nil, nil, err + } + return data, func() error { return errors.Join(release(), boom) }, nil + } + t.Cleanup(func() { mapFile = previous }) + file, err := os.Open(path) + if err != nil { + t.Fatal(err) + } + mapped, err := newMappedFile(file, 4) + if err != nil { + t.Fatal(err) + } + if err := mapped.Close(); !errors.Is(err, boom) { + t.Fatalf("Close returned %v, want the unmapping failure", err) + } + + other, err := os.Open(path) + if err != nil { + t.Fatal(err) + } + again, err := newMappedFile(other, 4) + if err != nil { + t.Fatal(err) + } + if err := other.Close(); err != nil { + t.Fatal(err) + } + if err := again.Close(); err == nil { + t.Fatalf("Close of a mapping whose file is already closed returned %v, want the file failure", err) + } +} + +func TestAFileThatCannotBeMappedIsReadThroughTheFile(t *testing.T) { + path := filepath.Join(t.TempDir(), "data") + if err := os.WriteFile(path, []byte("data"), 0o600); err != nil { + t.Fatal(err) + } + file, err := os.Open(path) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = file.Close() }) + previous := mapFile + mapFile = func(*os.File, int64) ([]byte, func() error, error) { return nil, nil, errors.New("no mapping here") } + t.Cleanup(func() { mapFile = previous }) + + source, closer := sourceOf(file, 4) + + if source != io.ReaderAt(file) || closer != io.Closer(file) { + t.Fatalf("sourceOf returned %T and %T, want the file itself", source, closer) + } +} + +func TestAnEmptyFileCannotBeMapped(t *testing.T) { + path := filepath.Join(t.TempDir(), "empty") + if err := os.WriteFile(path, nil, 0o600); err != nil { + t.Fatal(err) + } + file, err := os.Open(path) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = file.Close() }) + + if _, err := newMappedFile(file, 0); err == nil { + t.Fatal("an empty file was mapped") + } +} + +func TestPackfilesAndIndexesAreMappedWhenThePlatformAllows(t *testing.T) { + name := fixtureNames(t)[0] + dir := copyFixtureDir(t, name) + + packfile, err := OpenPack(filepath.Join(dir, name+packSuffix)) + if err != nil { + t.Fatalf("OpenPack returned error %v", err) + } + t.Cleanup(func() { _ = packfile.Close() }) + index, err := OpenIndex(filepath.Join(dir, name+indexSuffix)) + if err != nil { + t.Fatalf("OpenIndex returned error %v", err) + } + t.Cleanup(func() { _ = index.Close() }) + + if _, ok := packfile.source.(*mappedFile); !ok { + t.Errorf("the packfile is read through %T, want a mapping", packfile.source) + } + if _, ok := index.source.(*mappedFile); !ok { + t.Errorf("the index is read through %T, want a mapping", index.source) + } +} + +func TestPackfilesStillOpenWhenMappingFails(t *testing.T) { + name := fixtureNames(t)[0] + dir := copyFixtureDir(t, name) + previous := mapFile + mapFile = func(*os.File, int64) ([]byte, func() error, error) { return nil, nil, errors.New("no mapping here") } + t.Cleanup(func() { mapFile = previous }) + + store := openStore(t, dir) + + if _, _, ok, err := store.Get(objectTypesFirstID(t)); !ok || err != nil { + t.Fatalf("Get returned (%v, %v) from a packfile read through the file", ok, err) + } +} diff --git a/internal/gitcore/pack/mapped_windows.go b/internal/gitcore/pack/mapped_windows.go new file mode 100644 index 00000000..e43a0642 --- /dev/null +++ b/internal/gitcore/pack/mapped_windows.go @@ -0,0 +1,22 @@ +package pack + +import ( + "os" + "unsafe" + + "golang.org/x/sys/windows" +) + +func mapFileView(file *os.File, size int64) ([]byte, func() error, error) { + mapping, err := windows.CreateFileMapping(windows.Handle(file.Fd()), nil, windows.PAGE_READONLY, 0, 0, nil) + if err != nil { + return nil, nil, err + } + defer func() { _ = windows.CloseHandle(mapping) }() + address, err := windows.MapViewOfFile(mapping, windows.FILE_MAP_READ, 0, 0, 0) + if err != nil { + return nil, nil, err + } + data := unsafe.Slice((*byte)(unsafe.Pointer(address)), int(size)) + return data, func() error { return windows.UnmapViewOfFile(address) }, nil +} diff --git a/internal/gitcore/pack/pack.go b/internal/gitcore/pack/pack.go index 3fab702f..ec106704 100644 --- a/internal/gitcore/pack/pack.go +++ b/internal/gitcore/pack/pack.go @@ -40,11 +40,13 @@ func NewPackFile(file *os.File, opts ...Option) (*Pack, error) { if err != nil { return nil, err } - packfile, err := NewPack(file, info.Size(), opts...) + source, closer := sourceOf(file, info.Size()) + packfile, err := NewPack(source, info.Size(), opts...) if err != nil { + _ = closer.Close() return nil, err } - packfile.closer = file + packfile.closer = closer packfile.path = file.Name() return packfile, nil } From 25f39d780db15e42642a7162f85d30e8a1a2c2f1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=A7=D1=83=D0=BA=D0=B0=D0=BB=D0=B8=D0=BD=20=D0=92=D0=B0?= =?UTF-8?q?=D0=BB=D0=B5=D1=80=D0=B8=D0=B9?= Date: Fri, 16 Oct 2026 14:45:52 +0300 Subject: [PATCH 25/35] pack: pool a buffered reader for each inflater instead of letting zlib allocate one per object --- internal/gitcore/pack/inflate.go | 27 ++++-- internal/gitcore/pack/inflatesource_test.go | 94 +++++++++++++++++++++ 2 files changed, 115 insertions(+), 6 deletions(-) create mode 100644 internal/gitcore/pack/inflatesource_test.go diff --git a/internal/gitcore/pack/inflate.go b/internal/gitcore/pack/inflate.go index 3526c92e..16481e33 100644 --- a/internal/gitcore/pack/inflate.go +++ b/internal/gitcore/pack/inflate.go @@ -1,6 +1,7 @@ package pack import ( + "bufio" "bytes" "compress/zlib" "errors" @@ -16,22 +17,36 @@ type inflater interface { var emptyStream = []byte{0x78, 0x01, 0x03, 0x00, 0x00, 0x00, 0x00, 0x01} +const inflateBufferSize = 8 << 10 + +type pooledInflater struct { + inflater + buffer *bufio.Reader +} + var inflaters = sync.Pool{New: func() any { reader, _ := zlib.NewReader(bytes.NewReader(emptyStream)) - return reader.(inflater) + return &pooledInflater{inflater: reader.(inflater), buffer: bufio.NewReaderSize(nil, inflateBufferSize)} }} func acquireInflater(source io.Reader) (inflater, error) { - reader := inflaters.Get().(inflater) - if err := reader.Reset(source, nil); err != nil { - inflaters.Put(reader) + pooled := inflaters.Get().(*pooledInflater) + feed := source + if _, exact := source.(io.ByteReader); !exact { + pooled.buffer.Reset(source) + feed = pooled.buffer + } + if err := pooled.Reset(feed, nil); err != nil { + releaseInflater(pooled) return nil, fmt.Errorf("%w: %v", ErrDecompress, err) } - return reader, nil + return pooled, nil } func releaseInflater(reader inflater) { - inflaters.Put(reader) + pooled := reader.(*pooledInflater) + pooled.buffer.Reset(nil) + inflaters.Put(pooled) } func inflateExact(source io.Reader, into []byte) error { diff --git a/internal/gitcore/pack/inflatesource_test.go b/internal/gitcore/pack/inflatesource_test.go new file mode 100644 index 00000000..71521bf5 --- /dev/null +++ b/internal/gitcore/pack/inflatesource_test.go @@ -0,0 +1,94 @@ +package pack + +import ( + "bytes" + "compress/zlib" + "io" + "testing" +) + +type plainReader struct{ source io.Reader } + +func (r plainReader) Read(p []byte) (int, error) { return r.source.Read(p) } + +func deflated(t *testing.T, payload []byte) []byte { + t.Helper() + var out bytes.Buffer + writer := zlib.NewWriter(&out) + if _, err := writer.Write(payload); err != nil { + t.Fatalf("Write returned error %v", err) + } + if err := writer.Close(); err != nil { + t.Fatalf("Close returned error %v", err) + } + return out.Bytes() +} + +func TestInflatingFromAByteReaderConsumesExactlyTheCompressedStream(t *testing.T) { + payload := bytes.Repeat([]byte("exact consumption matters for a streamed pack\n"), 40) + compressed := deflated(t, payload) + source := bytes.NewReader(append(append([]byte(nil), compressed...), []byte("next object follows")...)) + + into := make([]byte, len(payload)) + if err := inflateExact(source, into); err != nil { + t.Fatalf("inflateExact returned error %v", err) + } + + if !bytes.Equal(into, payload) { + t.Fatal("the inflated bytes differ") + } + if consumed := len(compressed); source.Size()-int64(source.Len()) != int64(consumed) { + t.Fatalf("the source was read up to %d, want exactly %d", source.Size()-int64(source.Len()), consumed) + } +} + +func TestInflatingFromASourceWithoutByteReadingStillWorks(t *testing.T) { + payload := bytes.Repeat([]byte("a section of a packfile\n"), 200) + source := plainReader{source: bytes.NewReader(deflated(t, payload))} + into := make([]byte, len(payload)) + + if err := inflateExact(source, into); err != nil { + t.Fatalf("inflateExact returned error %v", err) + } + + if !bytes.Equal(into, payload) { + t.Fatal("the inflated bytes differ") + } +} + +func TestInflatingFromASourceWithoutByteReadingDoesNotAllocateABufferEachTime(t *testing.T) { + payload := bytes.Repeat([]byte("small object\n"), 20) + compressed := deflated(t, payload) + into := make([]byte, len(payload)) + + allocated := testing.AllocsPerRun(50, func() { + if err := inflateExact(plainReader{source: bytes.NewReader(compressed)}, into); err != nil { + t.Fatalf("inflateExact returned error %v", err) + } + }) + + if allocated > 4 { + t.Fatalf("inflating a small object allocated %v times, want the buffers pooled", allocated) + } +} + +func TestAnInflaterGoesBackToThePoolWithoutHoldingItsSource(t *testing.T) { + source := plainReader{source: bytes.NewReader(deflated(t, []byte("x")))} + reader, err := acquireInflater(source) + if err != nil { + t.Fatalf("acquireInflater returned error %v", err) + } + pooled := reader.(*pooledInflater) + + releaseInflater(reader) + + if pooled.buffer.Buffered() != 0 { + t.Fatal("a released inflater still buffers bytes of its source") + } +} + +func TestAcquireInflaterReportsAStreamThatIsNotZlibAndReturnsTheInflater(t *testing.T) { + if _, err := acquireInflater(plainReader{source: bytes.NewReader([]byte("not zlib at all"))}); err == nil { + t.Fatal("acquireInflater accepted a stream that is not zlib") + } +} From f6cc7dad7930e52f64481469f0b967a7a1062b42 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=A7=D1=83=D0=BA=D0=B0=D0=BB=D0=B8=D0=BD=20=D0=92=D0=B0?= =?UTF-8?q?=D0=BB=D0=B5=D1=80=D0=B8=D0=B9?= Date: Fri, 16 Oct 2026 14:51:29 +0300 Subject: [PATCH 26/35] pack: skip the inflater allocation budget test under the race detector --- internal/gitcore/pack/inflatesource_test.go | 3 +++ internal/gitcore/pack/race_off_test.go | 5 +++++ internal/gitcore/pack/race_on_test.go | 5 +++++ 3 files changed, 13 insertions(+) create mode 100644 internal/gitcore/pack/race_off_test.go create mode 100644 internal/gitcore/pack/race_on_test.go diff --git a/internal/gitcore/pack/inflatesource_test.go b/internal/gitcore/pack/inflatesource_test.go index 71521bf5..e4bfff66 100644 --- a/internal/gitcore/pack/inflatesource_test.go +++ b/internal/gitcore/pack/inflatesource_test.go @@ -57,6 +57,9 @@ func TestInflatingFromASourceWithoutByteReadingStillWorks(t *testing.T) { } func TestInflatingFromASourceWithoutByteReadingDoesNotAllocateABufferEachTime(t *testing.T) { + if raceEnabled { + t.Skip("the race detector makes sync.Pool drop values, so allocation counts are not stable") + } payload := bytes.Repeat([]byte("small object\n"), 20) compressed := deflated(t, payload) into := make([]byte, len(payload)) diff --git a/internal/gitcore/pack/race_off_test.go b/internal/gitcore/pack/race_off_test.go new file mode 100644 index 00000000..26c3cadc --- /dev/null +++ b/internal/gitcore/pack/race_off_test.go @@ -0,0 +1,5 @@ +//go:build !race + +package pack + +const raceEnabled = false diff --git a/internal/gitcore/pack/race_on_test.go b/internal/gitcore/pack/race_on_test.go new file mode 100644 index 00000000..9674e16f --- /dev/null +++ b/internal/gitcore/pack/race_on_test.go @@ -0,0 +1,5 @@ +//go:build race + +package pack + +const raceEnabled = true From a3c564b54546f28600d7ecb58c4205b01aec9a04 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=A7=D1=83=D0=BA=D0=B0=D0=BB=D0=B8=D0=BD=20=D0=92=D0=B0?= =?UTF-8?q?=D0=BB=D0=B5=D1=80=D0=B8=D0=B9?= Date: Fri, 16 Oct 2026 15:02:09 +0300 Subject: [PATCH 27/35] diagnostics: trace the startup steps into the log when GOGIT_TRACE_STARTUP is set --- cmd/gogit/main.go | 4 ++ internal/app/app.go | 3 ++ internal/app/journal.go | 2 + internal/app/startuptrace_test.go | 50 +++++++++++++++++++ internal/app/working.go | 2 + internal/diagnostics/startup.go | 58 ++++++++++++++++++++++ internal/diagnostics/startup_test.go | 72 ++++++++++++++++++++++++++++ 7 files changed, 191 insertions(+) create mode 100644 internal/app/startuptrace_test.go create mode 100644 internal/diagnostics/startup.go create mode 100644 internal/diagnostics/startup_test.go diff --git a/cmd/gogit/main.go b/cmd/gogit/main.go index 81f217e7..dbe2dc82 100644 --- a/cmd/gogit/main.go +++ b/cmd/gogit/main.go @@ -26,6 +26,7 @@ func main() { } func run() error { + started := startupClock() winconsole.Hide() paths, err := config.DefaultPaths() if err != nil { @@ -41,6 +42,8 @@ func run() error { logger = logx.Discard() } defer logger.Close() + diagnostics.BeginStartupTrace(logger.Slog(), started) + diagnostics.StartupStep(diagnostics.StepLoggerOpened) diagnostics.StartProfiler(logger.Slog()) diagnostics.LimitMemory(logger.Slog()) if backup != "" { @@ -52,6 +55,7 @@ func run() error { if err != nil { return err } + diagnostics.StartupStep(diagnostics.StepApplicationBuilt) return a.Run() } diff --git a/internal/app/app.go b/internal/app/app.go index 284b09a2..7f0de815 100644 --- a/internal/app/app.go +++ b/internal/app/app.go @@ -18,6 +18,7 @@ import ( "github.com/oops1/gogit/internal/assets" "github.com/oops1/gogit/internal/config" + "github.com/oops1/gogit/internal/diagnostics" "github.com/oops1/gogit/internal/gitcore/diff" "github.com/oops1/gogit/internal/gitcore/hash" "github.com/oops1/gogit/internal/gitcore/odb" @@ -732,6 +733,7 @@ func (a *App) ActivateRepository(id string) { a.startWorking() a.startAutoFetch() a.startGraphWrite(opened) + diagnostics.StartupStep(diagnostics.StepRepositoryOpened) } func (a *App) opened() *openedRepository { @@ -1174,6 +1176,7 @@ func (a *App) Run() error { if a.OnExit == nil { a.OnExit = win.Close } + diagnostics.StartupStep(diagnostics.StepWindowStarted) err := win.Run() if saveErr := a.SaveLayout(); err == nil { err = saveErr diff --git a/internal/app/journal.go b/internal/app/journal.go index 8a9a0505..9fbe8f13 100644 --- a/internal/app/journal.go +++ b/internal/app/journal.go @@ -5,6 +5,7 @@ import ( "errors" "slices" + "github.com/oops1/gogit/internal/diagnostics" "github.com/oops1/gogit/internal/gitcore/hash" "github.com/oops1/gogit/internal/gitcore/revision" "github.com/oops1/gogit/internal/i18n" @@ -64,6 +65,7 @@ func (a *App) runJournal(ctx context.Context, pager journalPager, more chan stru return } a.journalView.Append(rows) + diagnostics.StartupStep(diagnostics.StepJournalShown) a.showJournalFilterCount(a.journalView.Count(), filtered) a.reselectJournalCommit(reselect, rows) }) diff --git a/internal/app/startuptrace_test.go b/internal/app/startuptrace_test.go new file mode 100644 index 00000000..c443593a --- /dev/null +++ b/internal/app/startuptrace_test.go @@ -0,0 +1,50 @@ +package app + +import ( + "bytes" + "log/slog" + "strings" + "sync" + "testing" + "time" + + "github.com/oops1/gogit/internal/diagnostics" +) + +type lockedBuffer struct { + mu sync.Mutex + buf bytes.Buffer +} + +func (b *lockedBuffer) Write(p []byte) (int, error) { + b.mu.Lock() + defer b.mu.Unlock() + return b.buf.Write(p) +} + +func (b *lockedBuffer) String() string { + b.mu.Lock() + defer b.mu.Unlock() + return b.buf.String() +} + +func TestStartupTraceMarksTheRepositoryTheJournalAndTheStatus(t *testing.T) { + t.Setenv(diagnostics.EnvStartupTrace, "1") + var trace lockedBuffer + if !diagnostics.BeginStartupTrace(slog.New(slog.NewTextHandler(&trace, nil)), time.Now()) { + t.Fatal("the startup trace did not begin") + } + t.Cleanup(diagnostics.EndStartupTrace) + + a, _, _ := cloneForDivergence(t) + waitForJournalRows(t, a, 1) + waitForWorkingRows(t, a, 0) + drainPostQueue(t, a) + + text := trace.String() + for _, step := range []string{diagnostics.StepRepositoryOpened, diagnostics.StepJournalShown, diagnostics.StepStatusShown} { + if !strings.Contains(text, "step=\""+step+"\"") { + t.Fatalf("the trace %q lacks %q", text, step) + } + } +} diff --git a/internal/app/working.go b/internal/app/working.go index 3219443b..7a1674ee 100644 --- a/internal/app/working.go +++ b/internal/app/working.go @@ -5,6 +5,7 @@ import ( "context" "errors" + "github.com/oops1/gogit/internal/diagnostics" "github.com/oops1/gogit/internal/gitcore/attributes" "github.com/oops1/gogit/internal/gitcore/diff" "github.com/oops1/gogit/internal/gitcore/hash" @@ -133,6 +134,7 @@ func (a *App) runWorking(ctx context.Context, wt *worktree.Worktree) { return } a.setFilesRows(rows) + diagnostics.StartupStep(diagnostics.StepStatusShown) a.showSidebarWorkingCounts(len(rows), staged) a.reposView.Render(a.registry, a.repoTreeState()) a.setHasStagedChanges(staged > 0) diff --git a/internal/diagnostics/startup.go b/internal/diagnostics/startup.go new file mode 100644 index 00000000..7202a4aa --- /dev/null +++ b/internal/diagnostics/startup.go @@ -0,0 +1,58 @@ +package diagnostics + +import ( + "log/slog" + "os" + "strings" + "sync" + "time" +) + +const EnvStartupTrace = "GOGIT_TRACE_STARTUP" + +const ( + StepLoggerOpened = "logger opened" + StepApplicationBuilt = "application built" + StepRepositoryOpened = "repository opened" + StepWindowStarted = "window started" + StepJournalShown = "journal first page shown" + StepStatusShown = "working tree status shown" +) + +var ( + startupEnv = os.Getenv + startupNow = time.Now +) + +var startup struct { + sync.Mutex + log *slog.Logger + start time.Time + seen map[string]bool +} + +func BeginStartupTrace(log *slog.Logger, start time.Time) bool { + if strings.TrimSpace(startupEnv(EnvStartupTrace)) == "" { + return false + } + startup.Lock() + defer startup.Unlock() + startup.log, startup.start, startup.seen = log, start, map[string]bool{} + return true +} + +func StartupStep(step string) { + startup.Lock() + defer startup.Unlock() + if startup.log == nil || startup.seen[step] { + return + } + startup.seen[step] = true + startup.log.Info("startup step", "step", step, "elapsed_ms", startupNow().Sub(startup.start).Milliseconds()) +} + +func EndStartupTrace() { + startup.Lock() + defer startup.Unlock() + startup.log, startup.seen = nil, nil +} diff --git a/internal/diagnostics/startup_test.go b/internal/diagnostics/startup_test.go new file mode 100644 index 00000000..9491274e --- /dev/null +++ b/internal/diagnostics/startup_test.go @@ -0,0 +1,72 @@ +package diagnostics + +import ( + "bytes" + "log/slog" + "strings" + "testing" + "time" +) + +func traceInto(t *testing.T, env string) (*bytes.Buffer, bool) { + t.Helper() + previousEnv, previousNow := startupEnv, startupNow + startupEnv = func(name string) string { + if name == EnvStartupTrace { + return env + } + return "" + } + start := time.Unix(1700000000, 0) + startupNow = func() time.Time { return start.Add(250 * time.Millisecond) } + t.Cleanup(func() { + startupEnv, startupNow = previousEnv, previousNow + EndStartupTrace() + }) + var buf bytes.Buffer + began := BeginStartupTrace(slog.New(slog.NewTextHandler(&buf, nil)), start) + return &buf, began +} + +func TestStartupStepsAreLoggedOnceWithTheTimeSinceStart(t *testing.T) { + buf, began := traceInto(t, "1") + + StartupStep(StepWindowStarted) + StartupStep(StepWindowStarted) + StartupStep(StepJournalShown) + + if !began { + t.Fatal("the trace did not begin although the variable is set") + } + text := buf.String() + if strings.Count(text, "step=\"window started\"") != 1 || !strings.Contains(text, "step=\"journal first page shown\"") { + t.Fatalf("the log is %q, want each step once", text) + } + if !strings.Contains(text, "elapsed_ms=250") { + t.Fatalf("the log is %q, want the time since the process started", text) + } + if strings.Index(text, "window started") > strings.Index(text, "journal first page shown") { + t.Fatalf("the steps are out of order in %q", text) + } +} + +func TestStartupStepsAreSilentWithoutTheVariable(t *testing.T) { + buf, began := traceInto(t, " ") + + StartupStep(StepLoggerOpened) + + if began || buf.Len() != 0 { + t.Fatalf("began = %v, log = %q, want nothing without the variable", began, buf.String()) + } +} + +func TestStartupStepsStopAfterTheTraceEnds(t *testing.T) { + buf, _ := traceInto(t, "1") + EndStartupTrace() + + StartupStep(StepStatusShown) + + if buf.Len() != 0 { + t.Fatalf("the log is %q after the trace ended", buf.String()) + } +} From 32f8334fb4e557bf93fcd5c3a51d6d49027dd7e8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=A7=D1=83=D0=BA=D0=B0=D0=BB=D0=B8=D0=BD=20=D0=92=D0=B0?= =?UTF-8?q?=D0=BB=D0=B5=D1=80=D0=B8=D0=B9?= Date: Fri, 16 Oct 2026 15:02:09 +0300 Subject: [PATCH 28/35] app: select the branch tip by its id in the details test instead of assuming it is the first journal row --- internal/app/detailscmd_test.go | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/internal/app/detailscmd_test.go b/internal/app/detailscmd_test.go index e39332f0..0bf1fa3a 100644 --- a/internal/app/detailscmd_test.go +++ b/internal/app/detailscmd_test.go @@ -24,6 +24,17 @@ func waitForDetails(t *testing.T, a *App, want hash.ObjectID) { }, "the commit details") } +func journalRowIndexOf(t *testing.T, a *App, id hash.ObjectID) int { + t.Helper() + for at := range journalRowCountOnDispatcher(t, a) { + if journalRowOnDispatcher(t, a, at).ID == id { + return at + } + } + t.Fatalf("the journal does not list %s", id) + return -1 +} + func TestSelectingACommitFillsTheDetailsPanel(t *testing.T) { a, target := forkedApp(t, false) head := branchTip(t, target, "main") @@ -49,7 +60,7 @@ func TestTheJournalSelectionFillsTheDetailsPanel(t *testing.T) { waitForJournalRows(t, a, 1) head := branchTip(t, target, "main") - selectJournalRow(t, a, 0) + selectJournalRow(t, a, journalRowIndexOf(t, a, head)) waitForDetails(t, a, head) } From 9e068332144c045da8ea822159caaf98ed576c4c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=A7=D1=83=D0=BA=D0=B0=D0=BB=D0=B8=D0=BD=20=D0=92=D0=B0?= =?UTF-8?q?=D0=BB=D0=B5=D1=80=D0=B8=D0=B9?= Date: Fri, 16 Oct 2026 15:12:03 +0300 Subject: [PATCH 29/35] object: isolate the zone cache in the signature tests so their allocation budget does not depend on other tests --- internal/gitcore/object/signaturefast_test.go | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/internal/gitcore/object/signaturefast_test.go b/internal/gitcore/object/signaturefast_test.go index c4b9db8e..0e931c35 100644 --- a/internal/gitcore/object/signaturefast_test.go +++ b/internal/gitcore/object/signaturefast_test.go @@ -7,6 +7,7 @@ import ( "strings" "sync" "testing" + "time" ) func referenceSeconds(stamp string) (int64, bool) { @@ -60,6 +61,7 @@ func TestParsingASignatureRejectsATimestampThatIsNotCanonical(t *testing.T) { } func TestSignaturesInTheSameZoneShareOneLocation(t *testing.T) { + emptyZoneCache(t) first, err := ParseSignature([]byte("Ann 1700000000 +0530")) if err != nil { t.Fatal(err) @@ -81,6 +83,7 @@ func TestSignaturesInTheSameZoneShareOneLocation(t *testing.T) { } func TestTheZoneCacheStopsGrowingAtItsLimit(t *testing.T) { + emptyZoneCache(t) var wg sync.WaitGroup for worker := range 4 { wg.Go(func() { @@ -116,7 +119,21 @@ func TestTheZoneCacheStopsGrowingAtItsLimit(t *testing.T) { } } +func emptyZoneCache(t *testing.T) { + t.Helper() + zoneCache.Lock() + saved := zoneCache.locations + zoneCache.locations = make(map[string]*time.Location) + zoneCache.Unlock() + t.Cleanup(func() { + zoneCache.Lock() + zoneCache.locations = saved + zoneCache.Unlock() + }) +} + func TestParsingACommitAllocatesLittle(t *testing.T) { + emptyZoneCache(t) data := []byte("tree 4b825dc642cb6eb9a060e54bf8d69288fbee4904\n" + "parent 1111111111111111111111111111111111111111\n" + "author Ann 1700000000 +0300\n" + From a2690edaaaa9b5c7b760f5c3d1722ac448b35928 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=A7=D1=83=D0=BA=D0=B0=D0=BB=D0=B8=D0=BD=20=D0=92=D0=B0?= =?UTF-8?q?=D0=BB=D0=B5=D1=80=D0=B8=D0=B9?= Date: Fri, 16 Oct 2026 15:12:20 +0300 Subject: [PATCH 30/35] release: prepare 1.7.0 --- CHANGELOG.md | 59 ++++++++++++++++++++++++++++++ README.en.md | 2 +- README.md | 2 +- RELEASE_NOTES.md | 69 +++++++++++++++++++++++++++--------- USER_GUIDE.md | 7 ++++ cmd/gogit/winres/winres.json | 6 ++-- 6 files changed, 124 insertions(+), 21 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 007c8a31..aac556f1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,64 @@ # Изменения +## 1.7.0 — 2026-10-16 + +Релиз про скорость: статус, журнал, счётчики веток и чтение объектов на больших +репозиториях стали заметно быстрее, а commit-graph Go.Git теперь пишет сам. +Все цифры ниже измерены на Windows, 20 потоков. + +### Статус рабочей папки + +- Статус репозитория на 50 тысяч файлов — 0,12 с вместо 5,1 с. Почти всё время + уходило на проверку каждого файла по пути, который открывается по + компонентам. Теперь каталог читается один раз, файлы описываются по его + листингу, и только маленькие каталоги и файлы, которых в листинге нет, + проверяются по одному. +- Индекс сравнивается с HEAD через cache-tree: каталог, чьё дерево совпало с + HEAD, не читается вовсе. Если в индексе ничего нет, ни одно дерево ниже корня + не читается. +- Неотслеживаемые каталоги обходятся параллельно, каждый читается один раз: + 20 тысяч неотслеживаемых файлов — 23 мс вместо 46, 20 тысяч игнорируемых — + 24 мс вместо 76. Сопоставители игнорирования и атрибутов больше не ждут друг + друга за одним замком. + +### Журнал и история + +- Если в репозитории нет commit-graph, Go.Git пишет его в фоне после открытия. + С графом журнал отдаёт первую страницу потоком, а не обходит всю историю. + Настройки `core.commitGraph` и `gc.writeCommitGraph` соблюдаются, неглубокие + клоны пропускаются. +- Разбор коммита делает почти вчетверо меньше аллокаций: обход 10 тысяч коммитов — + 90 тысяч аллокаций вместо 330 тысяч и 7,5 мс вместо 12,1. +- Журнал отдаёт сетке строки один раз на страницу, а не копирует дважды: + 100 тысяч строк — 65 мс вместо 127 и 284 МБ вместо 635. +- Обновление не перезапускает журнал, если ни одна ветка, тег или удалённая + ветка не сдвинулись. + +### Счётчики расхождения веток + +- Счётчики `↑` и `↓` считаются один раз на пару вершин и запоминаются: + обновление пересчитывает только сдвинувшиеся ветки. Все обходы одного расчёта + делят разобранные коммиты, а подсчёт использует уже открытый репозиторий и + его кеш commit-graph. + +### Объекты и ссылки + +- Индексы паков держат таблицу имён в памяти; индексы и сами паки читаются + через отображение в память на Windows и Linux (с откатом на обычное чтение). + Поиск объекта в индексе пака — около 70 нс. +- `packed-refs` разбирается один раз, пока файл не менялся, а не при каждом + промахе. +- Промах по объекту не пересканирует каталог паков, если он не менялся. +- Пак, ответивший последним, проверяется первым; буферы распаковки берутся из + пула; кеш разобранных объектов чистит мёртвые записи лениво; кеш сырых + объектов разбит на шарды, чтобы параллельные читатели не делили один замок. + +### Диагностика + +- `GOGIT_TRACE_STARTUP=1` записывает в `gogit.log` шаги запуска с временем от + старта процесса: журнал открыт, приложение собрано, репозиторий открыт, окно + запущено, показаны первая страница журнала и статус рабочей папки. + ## 1.6.4 — 2026-10-14 В консоли команд появилась справка с примерами, а счётчик расхождения у ветки diff --git a/README.en.md b/README.en.md index 42a95905..e4c8ee74 100644 --- a/README.en.md +++ b/README.en.md @@ -17,7 +17,7 @@ interface. An alternative to the paid SmartGit. window; the layout is remembered. - Localization: Russian and English out of the box, any other language is a single JSON file. -## What 1.6.4 can already do +## What 1.7.0 can already do **Interface.** The menu and toolbar mirror SmartGit; the toolbar is configured in a separate window and stored in `config.toml`. Dock panels: diff --git a/README.md b/README.md index c018bfb7..d43c8a10 100644 --- a/README.md +++ b/README.md @@ -17,7 +17,7 @@ раскладка запоминается. - Локализация: русский и английский из коробки, любой другой язык — один JSON-файл. -## Что уже умеет 1.6.4 +## Что уже умеет 1.7.0 **Интерфейс.** Меню и панель инструментов повторяют SmartGit; панель настраивается в отдельном окне и хранится в `config.toml`. Док-панели: diff --git a/RELEASE_NOTES.md b/RELEASE_NOTES.md index 84c57a2c..fa153ae0 100644 --- a/RELEASE_NOTES.md +++ b/RELEASE_NOTES.md @@ -1,21 +1,58 @@ -# Go.Git 1.6.4 — Help in the console +# Go.Git 1.7.0 — Speed -The command console now has a reference with examples, and the ahead and behind -counter of a branch no longer dims its name. +Status, the journal, branch counters and object reading are noticeably faster on +big repositories, and Go.Git now writes the commit graph itself. -## Help in the command console +All numbers below were measured on Windows with a 20-thread processor. -- The `help` command prints how the console works and lists every command with - a short description; `help ` shows the options and examples of one - command (`help log`, `help push`). The new Help button in the window does the - same in one click. The texts come in Russian and English, and the reference - works even when no repository is open. A test checks every example: the - command parses, and every option in it is one the command accepts. +## Working tree status -## The branch counter +- Status of a repository with 50 thousand files takes 0.12 s instead of 5.1 s. + Almost all the time went into stating each file through a path that is opened + component by component. A directory is now read once and its files are described + from that listing; only small directories and files missing from a listing are + stated one by one. +- The index is compared with HEAD through the cache tree: if a directory has the + same tree as in HEAD, it is not read at all. With nothing staged, no tree below + the root is read. +- Untracked directories are walked in parallel, each read once. With 20 thousand + untracked files the status takes 23 ms instead of 46 ms, with 20 thousand ignored + files 24 ms instead of 76 ms. The ignore and attribute matchers no longer wait for + each other behind a lock. -- The `↑3 ↓1` counter of a branch in the Branches pane, and of the active - repository in the Repositories pane, is now drawn as a separate muted piece of - the row instead of being appended to the label. Before, the whole name of a - diverged branch was dimmed. The headless-gui engine is updated to v3.35.1 for - this; it also keeps popup menus inside the window. +## Journal and history + +- If a repository has no commit graph, Go.Git writes it in the background after the + repository is opened. With a graph the journal streams its first page instead of + walking the whole history. The settings `core.commitGraph` and + `gc.writeCommitGraph` are honoured, and shallow clones are left alone. +- Parsing a commit makes almost four times fewer allocations: a walk over 10 thousand commits goes + from 330 thousand allocations to 90 thousand and from 12.1 ms to 7.5 ms. +- The journal hands its rows to the grid once per page instead of copying them + twice: with 100 thousand rows 65 ms instead of 127 ms and 284 MB instead of 635 MB. +- A refresh no longer restarts the journal when no branch, tag or remote moved. + +## Branch counters + +- The ahead and behind counters are computed once for each pair of branch tips and + remembered, so a refresh recounts only the branches that moved. All walks of one + computation share the commits they have parsed, and the counting reuses the open + repository and its cached commit graph. + +## Objects and references + +- Pack indexes keep their name table in memory and, together with packfiles, are + read through a memory mapping on Windows and Linux (with a fallback to plain + reads). Looking an object up in a pack index takes about 70 ns. +- `packed-refs` is parsed once while the file does not change instead of on every + miss. +- A missing object no longer rescans the pack directory when it has not changed. +- The pack that answered last is searched first; the decompression buffers are + pooled; the parsed object cache sweeps dead entries lazily; the raw object cache + is split into shards so parallel readers stop sharing one lock. + +## Diagnostics + +- `GOGIT_TRACE_STARTUP=1` writes the startup steps with their time since the process + start into `gogit.log`: logger opened, application built, repository opened, + window started, first journal page and working tree status shown. diff --git a/USER_GUIDE.md b/USER_GUIDE.md index 87f40334..6717a633 100644 --- a/USER_GUIDE.md +++ b/USER_GUIDE.md @@ -402,6 +402,13 @@ git**. операцией — это помогает понять, что именно выполнялось в момент роста. Файл ротируется при достижении 5 МБ, старые копии остаются рядом как `gogit.log.1`, `gogit.log.2`, `gogit.log.3`. +- **Скорость запуска.** `GOGIT_TRACE_STARTUP=1` записывает в `gogit.log` шаги + запуска с временем от старта процесса — это помогает понять, на каком шаге + приложение медлит. +- **commit-graph.** Если в репозитории нет файла commit-graph, Go.Git пишет его + в фоне после открытия: с ним журнал быстрее. Запись отключается настройками + `gc.writeCommitGraph=false` или `core.commitGraph=false`; неглубокие клоны + пропускаются. - **Занятость окна.** Если команда не реагирует, посмотрите на строку состояния — вместо молчаливого «Занято» она называет операцию («Занято: Отправка») и предлагает её прервать. diff --git a/cmd/gogit/winres/winres.json b/cmd/gogit/winres/winres.json index cb651b95..ee0cbb56 100644 --- a/cmd/gogit/winres/winres.json +++ b/cmd/gogit/winres/winres.json @@ -11,7 +11,7 @@ "0409": { "identity": { "name": "Go.Git", - "version": "1.6.4.0" + "version": "1.7.0.0" }, "description": "Go.Git git client", "minimum-os": "win7", @@ -35,8 +35,8 @@ "#1": { "0000": { "fixed": { - "file_version": "1.6.4.0", - "product_version": "1.6.4.0" + "file_version": "1.7.0.0", + "product_version": "1.7.0.0" }, "info": { "0409": { From 20dc3633d53fee3a2e56659173e9f26ae9b5f79d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=A7=D1=83=D0=BA=D0=B0=D0=BB=D0=B8=D0=BD=20=D0=92=D0=B0?= =?UTF-8?q?=D0=BB=D0=B5=D1=80=D0=B8=D0=B9?= Date: Fri, 16 Oct 2026 15:48:00 +0300 Subject: [PATCH 31/35] transport: show every NTLM step with its connection when the proxy handshake test fails --- internal/gitcore/transport/httpauth_test.go | 10 ++++++++++ internal/gitcore/transport/httpproxyntlm_test.go | 2 +- 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/internal/gitcore/transport/httpauth_test.go b/internal/gitcore/transport/httpauth_test.go index c8507724..97f334ee 100644 --- a/internal/gitcore/transport/httpauth_test.go +++ b/internal/gitcore/transport/httpauth_test.go @@ -34,6 +34,7 @@ type ntlmTestServer struct { sawBinding []byte postBody []byte trace []string + steps []string } func (s *ntlmTestServer) record(step string) { @@ -111,6 +112,9 @@ func (s *ntlmTestServer) authorize(w http.ResponseWriter, r *http.Request) bool name, rawToken, _ := strings.Cut(auth, " ") token, err := base64.StdEncoding.DecodeString(strings.TrimSpace(rawToken)) s.record(r.Method + " " + strings.ToLower(name) + " " + ntlmStepName(token)) + s.mu.Lock() + s.steps = append(s.steps, ntlmStepName(token)+" from "+r.RemoteAddr+" "+r.Method+" "+r.Proto) + s.mu.Unlock() if err != nil { s.reject(w) return false @@ -245,6 +249,12 @@ func utf16Decode(b []byte) string { return string(runes) } +func (s *ntlmTestServer) stepsSeen() []string { + s.mu.Lock() + defer s.mu.Unlock() + return append([]string(nil), s.steps...) +} + func (s *ntlmTestServer) sameConnection() bool { s.mu.Lock() defer s.mu.Unlock() diff --git a/internal/gitcore/transport/httpproxyntlm_test.go b/internal/gitcore/transport/httpproxyntlm_test.go index 01a36595..67027f76 100644 --- a/internal/gitcore/transport/httpproxyntlm_test.go +++ b/internal/gitcore/transport/httpproxyntlm_test.go @@ -85,7 +85,7 @@ func TestHTTPAuthenticatesToAnNTLMOrNegotiateProxy(t *testing.T) { t.Fatalf("advertise through the %s proxy returned error %v", scheme, err) } if authority.authenticated == 0 || !authority.sameConnection() { - t.Fatalf("authenticated %d times, same connection %v; want a completed handshake on one connection", authority.authenticated, authority.sameConnection()) + t.Fatalf("authenticated %d times, same connection %v (steps %q); want a completed handshake on one connection", authority.authenticated, authority.sameConnection(), authority.stepsSeen()) } if len(source.asked) != 1 || source.asked[0] != proxy.server.URL { t.Fatalf("asked = %q, want one question about %s", source.asked, proxy.server.URL) From 169977e235c894c4603894add6f2c2b8c926309d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=A7=D1=83=D0=BA=D0=B0=D0=BB=D0=B8=D0=BD=20=D0=92=D0=B0?= =?UTF-8?q?=D0=BB=D0=B5=D1=80=D0=B8=D0=B9?= Date: Fri, 16 Oct 2026 16:26:02 +0300 Subject: [PATCH 32/35] transport: let the tests observe why a proxy tunnel connection was reopened --- .../gitcore/transport/httpproxyntlm_test.go | 23 ++++++++++++++++++- internal/gitcore/transport/httptunnel.go | 5 ++++ 2 files changed, 27 insertions(+), 1 deletion(-) diff --git a/internal/gitcore/transport/httpproxyntlm_test.go b/internal/gitcore/transport/httpproxyntlm_test.go index 67027f76..278e8166 100644 --- a/internal/gitcore/transport/httpproxyntlm_test.go +++ b/internal/gitcore/transport/httpproxyntlm_test.go @@ -2,6 +2,7 @@ package transport import ( "errors" + "fmt" "io" "log" "net/http" @@ -9,6 +10,7 @@ import ( "os" "slices" "strings" + "sync" "testing" ) @@ -76,6 +78,7 @@ func TestHTTPAuthenticatesToAnNTLMOrNegotiateProxy(t *testing.T) { } t.Run(name, func(t *testing.T) { authority := newNTLMProxyAuthority(t, scheme, "hunter2") + reopened := recordTunnelReopens(t) proxy := startAuthenticatingProxy(t, authority, false) target := newProxyTarget(t, secure) opts := proxyConfig(t, proxy.server.URL, target, "") @@ -85,7 +88,7 @@ func TestHTTPAuthenticatesToAnNTLMOrNegotiateProxy(t *testing.T) { t.Fatalf("advertise through the %s proxy returned error %v", scheme, err) } if authority.authenticated == 0 || !authority.sameConnection() { - t.Fatalf("authenticated %d times, same connection %v (steps %q); want a completed handshake on one connection", authority.authenticated, authority.sameConnection(), authority.stepsSeen()) + t.Fatalf("authenticated %d times, same connection %v (steps %q, reopened after %q); want a completed handshake on one connection", authority.authenticated, authority.sameConnection(), authority.stepsSeen(), reopened()) } if len(source.asked) != 1 || source.asked[0] != proxy.server.URL { t.Fatalf("asked = %q, want one question about %s", source.asked, proxy.server.URL) @@ -298,3 +301,21 @@ func TestPlainProxyForIgnoresForeignTransportsAndBadURLs(t *testing.T) { t.Fatalf("a caller-supplied client must not be proxied by the session") } } + +func recordTunnelReopens(t *testing.T) func() []string { + t.Helper() + var mu sync.Mutex + var seen []string + previous := observeTunnelReopen + observeTunnelReopen = func(resp *http.Response) { + mu.Lock() + defer mu.Unlock() + seen = append(seen, fmt.Sprintf("%s length=%d encoding=%v header=%v", resp.Status, resp.ContentLength, resp.TransferEncoding, resp.Header)) + } + t.Cleanup(func() { observeTunnelReopen = previous }) + return func() []string { + mu.Lock() + defer mu.Unlock() + return append([]string(nil), seen...) + } +} diff --git a/internal/gitcore/transport/httptunnel.go b/internal/gitcore/transport/httptunnel.go index 66e57226..ffb1d42f 100644 --- a/internal/gitcore/transport/httptunnel.go +++ b/internal/gitcore/transport/httptunnel.go @@ -55,6 +55,8 @@ func (s *httpSession) dialTLS(ctx context.Context, network, addr string) (net.Co return s.handshakeTLS(ctx, conn, host) } +var observeTunnelReopen = func(*http.Response) {} + type proxyTunnel struct { session *httpSession proxyURL *url.URL @@ -115,6 +117,9 @@ func (t *proxyTunnel) leg(ctx context.Context) func(string) (*http.Response, err return nil, err } t.reopen = resp.Close + if resp.Close { + observeTunnelReopen(resp) + } return resp, nil } } From 19823bae668b3066cf06284943830060ddb2b242 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=A7=D1=83=D0=BA=D0=B0=D0=BB=D0=B8=D0=BD=20=D0=92=D0=B0?= =?UTF-8?q?=D0=BB=D0=B5=D1=80=D0=B8=D0=B9?= Date: Fri, 16 Oct 2026 16:54:50 +0300 Subject: [PATCH 33/35] transport: let the tests tap the proxy tunnel connection to see what the proxy sends --- .../gitcore/transport/httpproxyntlm_test.go | 34 ++++++++++++++++++- internal/gitcore/transport/httptunnel.go | 3 ++ 2 files changed, 36 insertions(+), 1 deletion(-) diff --git a/internal/gitcore/transport/httpproxyntlm_test.go b/internal/gitcore/transport/httpproxyntlm_test.go index 278e8166..6e2eec91 100644 --- a/internal/gitcore/transport/httpproxyntlm_test.go +++ b/internal/gitcore/transport/httpproxyntlm_test.go @@ -5,6 +5,7 @@ import ( "fmt" "io" "log" + "net" "net/http" "net/http/httptest" "os" @@ -79,6 +80,7 @@ func TestHTTPAuthenticatesToAnNTLMOrNegotiateProxy(t *testing.T) { t.Run(name, func(t *testing.T) { authority := newNTLMProxyAuthority(t, scheme, "hunter2") reopened := recordTunnelReopens(t) + heard := recordTunnelReads(t) proxy := startAuthenticatingProxy(t, authority, false) target := newProxyTarget(t, secure) opts := proxyConfig(t, proxy.server.URL, target, "") @@ -88,7 +90,7 @@ func TestHTTPAuthenticatesToAnNTLMOrNegotiateProxy(t *testing.T) { t.Fatalf("advertise through the %s proxy returned error %v", scheme, err) } if authority.authenticated == 0 || !authority.sameConnection() { - t.Fatalf("authenticated %d times, same connection %v (steps %q, reopened after %q); want a completed handshake on one connection", authority.authenticated, authority.sameConnection(), authority.stepsSeen(), reopened()) + t.Fatalf("authenticated %d times, same connection %v (steps %q, reopened after %q, heard %q); want a completed handshake on one connection", authority.authenticated, authority.sameConnection(), authority.stepsSeen(), reopened(), heard()) } if len(source.asked) != 1 || source.asked[0] != proxy.server.URL { t.Fatalf("asked = %q, want one question about %s", source.asked, proxy.server.URL) @@ -319,3 +321,33 @@ func recordTunnelReopens(t *testing.T) func() []string { return append([]string(nil), seen...) } } + +type listeningConn struct { + net.Conn + mu *sync.Mutex + heard *[]string +} + +func (c listeningConn) Read(p []byte) (int, error) { + n, err := c.Conn.Read(p) + if n > 0 { + c.mu.Lock() + *c.heard = append(*c.heard, fmt.Sprintf("%s: %q", c.Conn.LocalAddr(), p[:min(n, 400)])) + c.mu.Unlock() + } + return n, err +} + +func recordTunnelReads(t *testing.T) func() []string { + t.Helper() + var mu sync.Mutex + var heard []string + previous := tapTunnelConn + tapTunnelConn = func(conn net.Conn) net.Conn { return listeningConn{Conn: conn, mu: &mu, heard: &heard} } + t.Cleanup(func() { tapTunnelConn = previous }) + return func() []string { + mu.Lock() + defer mu.Unlock() + return append([]string(nil), heard...) + } +} diff --git a/internal/gitcore/transport/httptunnel.go b/internal/gitcore/transport/httptunnel.go index ffb1d42f..5888d8b0 100644 --- a/internal/gitcore/transport/httptunnel.go +++ b/internal/gitcore/transport/httptunnel.go @@ -57,6 +57,8 @@ func (s *httpSession) dialTLS(ctx context.Context, network, addr string) (net.Co var observeTunnelReopen = func(*http.Response) {} +var tapTunnelConn = func(conn net.Conn) net.Conn { return conn } + type proxyTunnel struct { session *httpSession proxyURL *url.URL @@ -75,6 +77,7 @@ func (t *proxyTunnel) open(ctx context.Context) error { if err != nil { return err } + conn = tapTunnelConn(conn) if t.proxyURL.Scheme == string(SchemeHTTPS) { tc, err := t.session.handshakeTLS(ctx, conn, t.proxyURL.Hostname()) if err != nil { From 25fc9764f6120b2dd240b9d5017de81f20765085 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=A7=D1=83=D0=BA=D0=B0=D0=BB=D0=B8=D0=BD=20=D0=92=D0=B0?= =?UTF-8?q?=D0=BB=D0=B5=D1=80=D0=B8=D0=B9?= Date: Fri, 16 Oct 2026 16:55:12 +0300 Subject: [PATCH 34/35] transport: use the promoted address method in the tunnel tap --- internal/gitcore/transport/httpproxyntlm_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/internal/gitcore/transport/httpproxyntlm_test.go b/internal/gitcore/transport/httpproxyntlm_test.go index 6e2eec91..38a65d97 100644 --- a/internal/gitcore/transport/httpproxyntlm_test.go +++ b/internal/gitcore/transport/httpproxyntlm_test.go @@ -332,7 +332,7 @@ func (c listeningConn) Read(p []byte) (int, error) { n, err := c.Conn.Read(p) if n > 0 { c.mu.Lock() - *c.heard = append(*c.heard, fmt.Sprintf("%s: %q", c.Conn.LocalAddr(), p[:min(n, 400)])) + *c.heard = append(*c.heard, fmt.Sprintf("%s: %q", c.LocalAddr(), p[:min(n, 400)])) c.mu.Unlock() } return n, err From 8bbc90cd21db87e0bd30932d7d8058423ced4bdb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=A7=D1=83=D0=BA=D0=B0=D0=BB=D0=B8=D0=BD=20=D0=92=D0=B0?= =?UTF-8?q?=D0=BB=D0=B5=D1=80=D0=B8=D0=B9?= Date: Fri, 16 Oct 2026 17:27:29 +0300 Subject: [PATCH 35/35] transport: keep the test proxy's connection alive itself for CONNECT, since Go 1.26.9 closes it after every unhijacked reply --- internal/gitcore/transport/httpauth_test.go | 10 ---- internal/gitcore/transport/httpproxy_test.go | 43 +++++++++++++++ .../gitcore/transport/httpproxyntlm_test.go | 55 +------------------ internal/gitcore/transport/httptunnel.go | 8 --- 4 files changed, 44 insertions(+), 72 deletions(-) diff --git a/internal/gitcore/transport/httpauth_test.go b/internal/gitcore/transport/httpauth_test.go index 97f334ee..c8507724 100644 --- a/internal/gitcore/transport/httpauth_test.go +++ b/internal/gitcore/transport/httpauth_test.go @@ -34,7 +34,6 @@ type ntlmTestServer struct { sawBinding []byte postBody []byte trace []string - steps []string } func (s *ntlmTestServer) record(step string) { @@ -112,9 +111,6 @@ func (s *ntlmTestServer) authorize(w http.ResponseWriter, r *http.Request) bool name, rawToken, _ := strings.Cut(auth, " ") token, err := base64.StdEncoding.DecodeString(strings.TrimSpace(rawToken)) s.record(r.Method + " " + strings.ToLower(name) + " " + ntlmStepName(token)) - s.mu.Lock() - s.steps = append(s.steps, ntlmStepName(token)+" from "+r.RemoteAddr+" "+r.Method+" "+r.Proto) - s.mu.Unlock() if err != nil { s.reject(w) return false @@ -249,12 +245,6 @@ func utf16Decode(b []byte) string { return string(runes) } -func (s *ntlmTestServer) stepsSeen() []string { - s.mu.Lock() - defer s.mu.Unlock() - return append([]string(nil), s.steps...) -} - func (s *ntlmTestServer) sameConnection() bool { s.mu.Lock() defer s.mu.Unlock() diff --git a/internal/gitcore/transport/httpproxy_test.go b/internal/gitcore/transport/httpproxy_test.go index df538cca..8cca5930 100644 --- a/internal/gitcore/transport/httpproxy_test.go +++ b/internal/gitcore/transport/httpproxy_test.go @@ -50,8 +50,51 @@ func (p *forwardProxy) track(conns ...net.Conn) { p.conns = append(p.conns, conns...) } +func (p *forwardProxy) serveHandshake(w http.ResponseWriter, r *http.Request) { + client, buffered, err := http.NewResponseController(w).Hijack() + if err != nil { + return + } + p.track(client) + for { + recorder := httptest.NewRecorder() + if p.authority.authorize(recorder, r) { + p.connectThrough(client, buffered, r.Host) + return + } + if err := recorder.Result().Write(client); err != nil { + return + } + next, err := http.ReadRequest(buffered.Reader) + if err != nil { + _ = client.Close() + return + } + next.RemoteAddr = client.RemoteAddr().String() + p.requests.Add(1) + r = next + } +} + +func (p *forwardProxy) connectThrough(client net.Conn, buffered io.Reader, target string) { + upstream, err := net.Dial("tcp", target) + if err != nil { + _, _ = client.Write([]byte("HTTP/1.1 502 Bad Gateway\r\nContent-Length: 0\r\n\r\n")) + _ = client.Close() + return + } + p.track(upstream) + _, _ = client.Write([]byte("HTTP/1.1 200 Connection Established\r\n\r\n")) + go func() { _, _ = io.Copy(upstream, buffered) }() + go func() { _, _ = io.Copy(client, upstream) }() +} + func (p *forwardProxy) serve(w http.ResponseWriter, r *http.Request) { p.requests.Add(1) + if p.authority != nil && r.Method == http.MethodConnect { + p.serveHandshake(w, r) + return + } if p.authority != nil && !p.authority.authorize(w, r) { return } diff --git a/internal/gitcore/transport/httpproxyntlm_test.go b/internal/gitcore/transport/httpproxyntlm_test.go index 38a65d97..01a36595 100644 --- a/internal/gitcore/transport/httpproxyntlm_test.go +++ b/internal/gitcore/transport/httpproxyntlm_test.go @@ -2,16 +2,13 @@ package transport import ( "errors" - "fmt" "io" "log" - "net" "net/http" "net/http/httptest" "os" "slices" "strings" - "sync" "testing" ) @@ -79,8 +76,6 @@ func TestHTTPAuthenticatesToAnNTLMOrNegotiateProxy(t *testing.T) { } t.Run(name, func(t *testing.T) { authority := newNTLMProxyAuthority(t, scheme, "hunter2") - reopened := recordTunnelReopens(t) - heard := recordTunnelReads(t) proxy := startAuthenticatingProxy(t, authority, false) target := newProxyTarget(t, secure) opts := proxyConfig(t, proxy.server.URL, target, "") @@ -90,7 +85,7 @@ func TestHTTPAuthenticatesToAnNTLMOrNegotiateProxy(t *testing.T) { t.Fatalf("advertise through the %s proxy returned error %v", scheme, err) } if authority.authenticated == 0 || !authority.sameConnection() { - t.Fatalf("authenticated %d times, same connection %v (steps %q, reopened after %q, heard %q); want a completed handshake on one connection", authority.authenticated, authority.sameConnection(), authority.stepsSeen(), reopened(), heard()) + t.Fatalf("authenticated %d times, same connection %v; want a completed handshake on one connection", authority.authenticated, authority.sameConnection()) } if len(source.asked) != 1 || source.asked[0] != proxy.server.URL { t.Fatalf("asked = %q, want one question about %s", source.asked, proxy.server.URL) @@ -303,51 +298,3 @@ func TestPlainProxyForIgnoresForeignTransportsAndBadURLs(t *testing.T) { t.Fatalf("a caller-supplied client must not be proxied by the session") } } - -func recordTunnelReopens(t *testing.T) func() []string { - t.Helper() - var mu sync.Mutex - var seen []string - previous := observeTunnelReopen - observeTunnelReopen = func(resp *http.Response) { - mu.Lock() - defer mu.Unlock() - seen = append(seen, fmt.Sprintf("%s length=%d encoding=%v header=%v", resp.Status, resp.ContentLength, resp.TransferEncoding, resp.Header)) - } - t.Cleanup(func() { observeTunnelReopen = previous }) - return func() []string { - mu.Lock() - defer mu.Unlock() - return append([]string(nil), seen...) - } -} - -type listeningConn struct { - net.Conn - mu *sync.Mutex - heard *[]string -} - -func (c listeningConn) Read(p []byte) (int, error) { - n, err := c.Conn.Read(p) - if n > 0 { - c.mu.Lock() - *c.heard = append(*c.heard, fmt.Sprintf("%s: %q", c.LocalAddr(), p[:min(n, 400)])) - c.mu.Unlock() - } - return n, err -} - -func recordTunnelReads(t *testing.T) func() []string { - t.Helper() - var mu sync.Mutex - var heard []string - previous := tapTunnelConn - tapTunnelConn = func(conn net.Conn) net.Conn { return listeningConn{Conn: conn, mu: &mu, heard: &heard} } - t.Cleanup(func() { tapTunnelConn = previous }) - return func() []string { - mu.Lock() - defer mu.Unlock() - return append([]string(nil), heard...) - } -} diff --git a/internal/gitcore/transport/httptunnel.go b/internal/gitcore/transport/httptunnel.go index 5888d8b0..66e57226 100644 --- a/internal/gitcore/transport/httptunnel.go +++ b/internal/gitcore/transport/httptunnel.go @@ -55,10 +55,6 @@ func (s *httpSession) dialTLS(ctx context.Context, network, addr string) (net.Co return s.handshakeTLS(ctx, conn, host) } -var observeTunnelReopen = func(*http.Response) {} - -var tapTunnelConn = func(conn net.Conn) net.Conn { return conn } - type proxyTunnel struct { session *httpSession proxyURL *url.URL @@ -77,7 +73,6 @@ func (t *proxyTunnel) open(ctx context.Context) error { if err != nil { return err } - conn = tapTunnelConn(conn) if t.proxyURL.Scheme == string(SchemeHTTPS) { tc, err := t.session.handshakeTLS(ctx, conn, t.proxyURL.Hostname()) if err != nil { @@ -120,9 +115,6 @@ func (t *proxyTunnel) leg(ctx context.Context) func(string) (*http.Response, err return nil, err } t.reopen = resp.Close - if resp.Close { - observeTunnelReopen(resp) - } return resp, nil } }