From c01cabc7c9cd5a1d1e12f07d03dc4ba782b04412 Mon Sep 17 00:00:00 2001 From: sdouglas Date: Wed, 25 Nov 2026 06:18:07 +0000 Subject: [PATCH] perf(git): skip bitmaps for incremental upload-pack and bundle builds When an upload-pack request's haves aren't covered by a bitmap, git first fills one in by walking their whole tree. On the cash-server mirror (bb-block staging, git 2.52.1, MIDX bitmap 9 minutes old, boundary traversal on), a v2 fetch through http-backend for a 47-commit gap took 13-15s and sent 4.3 MB with bitmaps, against under 1s and 1.1 MB without. A 2,000-commit gap took 24s and 72 MB against 8s and 42 MB. Delta bundle builds (HEAD ^base) hit the same fill-in: 14s against about 1s. serveReadyRepo already buffers the request body. A git-upload-pack request whose body (gzip-aware, same inspect window as clone counting) has "have" lines now runs http-backend with pack.useBitmaps=false through GIT_CONFIG_COUNT. The "not our ref" replay gets the same override. Clones, ls-refs and info/refs keep bitmaps, which a full object walk needs. v0 and v2 requests both take this path. Bundles are built with -c pack.useBitmaps=false. The mirror config is unchanged. Co-authored-by: Sleeper Service --- internal/strategy/git/backend.go | 8 +- internal/strategy/git/bundlecoord_test.go | 2 +- internal/strategy/git/git.go | 5 +- internal/strategy/git/repocounts.go | 26 ++-- internal/strategy/git/snapshot.go | 2 +- .../strategy/git/upload_pack_bitmaps_test.go | 132 ++++++++++++++++++ 6 files changed, 162 insertions(+), 13 deletions(-) create mode 100644 internal/strategy/git/upload_pack_bitmaps_test.go diff --git a/internal/strategy/git/backend.go b/internal/strategy/git/backend.go index 63bbc9e4..eeb63325 100644 --- a/internal/strategy/git/backend.go +++ b/internal/strategy/git/backend.go @@ -83,7 +83,7 @@ func (b *bufferedResponseWriter) commit() { // // It returns true when upload-pack rejects the request with "not our ref" and it should be retried upstream. // This typically happens when a concurrent force-push fetch orphans a previously advertised commit. -func (s *Strategy) serveFromBackend(w http.ResponseWriter, r *http.Request, repo *gitclone.Repository) bool { +func (s *Strategy) serveFromBackend(w http.ResponseWriter, r *http.Request, repo *gitclone.Repository, incremental bool) bool { ctx := r.Context() logger := logging.FromContext(ctx) @@ -146,6 +146,12 @@ func (s *Strategy) serveFromBackend(w http.ResponseWriter, r *http.Request, repo "PATH=" + os.Getenv("PATH"), }, } + // Incremental fetches skip bitmaps, whose fill-in for uncovered haves walks a whole tree, seconds on a monorepo. + // + // Clones send no haves and need bitmaps to avoid walking every object. + if incremental { + handler.Env = append(handler.Env, "GIT_CONFIG_COUNT=1", "GIT_CONFIG_KEY_0=pack.useBitmaps", "GIT_CONFIG_VALUE_0=false") + } r2 := r.Clone(r.Context()) r2.URL.Path = backendPath diff --git a/internal/strategy/git/bundlecoord_test.go b/internal/strategy/git/bundlecoord_test.go index 2c4ececa..eea33eb8 100644 --- a/internal/strategy/git/bundlecoord_test.go +++ b/internal/strategy/git/bundlecoord_test.go @@ -349,7 +349,7 @@ func TestBundleBuildCancellationReleasesFetchLock(t *testing.T) { assert.NoError(t, err) bin := t.TempDir() started := filepath.Join(bin, "started") - script := fmt.Sprintf("#!/bin/sh\nif [ \"$3\" = bundle ]; then\n sleep 2 &\n touch %q\n wait\nfi\nexec %q \"$@\"\n", started, realGit) + script := fmt.Sprintf("#!/bin/sh\ncase \" $* \" in *\" bundle create \"*)\n sleep 2 &\n touch %q\n wait\nesac\nexec %q \"$@\"\n", started, realGit) assert.NoError(t, os.WriteFile(filepath.Join(bin, "git"), []byte(script), 0o700)) t.Setenv("PATH", bin+string(os.PathListSeparator)+os.Getenv("PATH")) ctx, cancel := context.WithCancel(s.ctx) diff --git a/internal/strategy/git/git.go b/internal/strategy/git/git.go index beee574b..5efd2b46 100644 --- a/internal/strategy/git/git.go +++ b/internal/strategy/git/git.go @@ -518,7 +518,8 @@ func (s *Strategy) serveReadyRepo(w http.ResponseWriter, r *http.Request, repo * r.TransferEncoding = nil } - if !s.serveFromBackend(w, r, repo) { + incremental := strings.HasSuffix(pathValue, "/git-upload-pack") && uploadPackBodyHasHaves(r.Header, bodyBytes) + if !s.serveFromBackend(w, r, repo, incremental) { return nil } replayBody := func() { @@ -537,7 +538,7 @@ func (s *Strategy) serveReadyRepo(w http.ResponseWriter, r *http.Request, repo * "error", err) } else { replayBody() - if !s.serveFromBackend(w, r, repo) { + if !s.serveFromBackend(w, r, repo, incremental) { logger.InfoContext(ctx, "Served from mirror after fetching object missing for 'not our ref'", "path", pathValue) return nil } diff --git a/internal/strategy/git/repocounts.go b/internal/strategy/git/repocounts.go index 88c597bb..6c2977f1 100644 --- a/internal/strategy/git/repocounts.go +++ b/internal/strategy/git/repocounts.go @@ -112,15 +112,25 @@ func inspectUploadPackBody(r *http.Request) ([]byte, error) { io.Closer }{io.MultiReader(bytes.NewReader(prefix), original), original} - inspect := prefix - if strings.EqualFold(r.Header.Get("Content-Encoding"), "gzip") { - if gr, gzErr := gzip.NewReader(bytes.NewReader(prefix)); gzErr == nil { - decoded, _ := io.ReadAll(io.LimitReader(gr, uploadPackBodyInspectLimit)) //nolint:errcheck // best-effort - _ = gr.Close() //nolint:errcheck // best-effort - inspect = decoded - } + return decodeUploadPackPrefix(r.Header, prefix), nil +} + +func uploadPackBodyHasHaves(header http.Header, body []byte) bool { + inspect := decodeUploadPackPrefix(header, body[:min(len(body), uploadPackBodyInspectLimit)]) + return !isLsRefsBody(inspect) && bytes.Contains(inspect, haveNeedle) +} + +func decodeUploadPackPrefix(header http.Header, prefix []byte) []byte { + if !strings.EqualFold(header.Get("Content-Encoding"), "gzip") { + return prefix + } + gr, err := gzip.NewReader(bytes.NewReader(prefix)) + if err != nil { + return prefix } - return inspect, nil + decoded, _ := io.ReadAll(io.LimitReader(gr, uploadPackBodyInspectLimit)) //nolint:errcheck // best-effort + _ = gr.Close() //nolint:errcheck // best-effort + return decoded } func isLsRefsBody(inspect []byte) bool { diff --git a/internal/strategy/git/snapshot.go b/internal/strategy/git/snapshot.go index a1debd5d..6535276b 100644 --- a/internal/strategy/git/snapshot.go +++ b/internal/strategy/git/snapshot.go @@ -1044,7 +1044,7 @@ func createBundleFile(ctx context.Context, repo *gitclone.Repository, baseCommit return nil, errors.Wrap(err, "close bundle temp file") } - cmd := exec.CommandContext(ctx, "git", "-C", repo.Path(), "bundle", "create", //nolint:gosec // baseCommit is a SHA string from rev-parse + cmd := exec.CommandContext(ctx, "git", "-C", repo.Path(), "-c", "pack.useBitmaps=false", "bundle", "create", //nolint:gosec // baseCommit is a SHA string from rev-parse bundlePath, headRef, "^"+baseCommit) cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true} cmd.Cancel = func() error { diff --git a/internal/strategy/git/upload_pack_bitmaps_test.go b/internal/strategy/git/upload_pack_bitmaps_test.go new file mode 100644 index 00000000..3a1dfb5e --- /dev/null +++ b/internal/strategy/git/upload_pack_bitmaps_test.go @@ -0,0 +1,132 @@ +package git_test + +import ( + "bytes" + "compress/gzip" + "fmt" + "net/http" + "net/http/httptest" + "os" + "os/exec" + "path/filepath" + "strings" + "testing" + + "github.com/alecthomas/assert/v2" +) + +func recordBackendBitmaps(t *testing.T, upstream string) string { + t.Helper() + realGit, err := exec.LookPath("git") + assert.NoError(t, err) + dir := t.TempDir() + log := filepath.Join(dir, "backend.log") + script := fmt.Sprintf(`#!/bin/sh +if echo " $* " | grep -q ' ls-remote '; then + exec %[1]q ls-remote %[2]q +fi +if [ "$1" = http-backend ]; then + echo "bitmaps=$(%[1]q config --get pack.usebitmaps)" >> %[3]q +fi +exec %[1]q "$@" +`, realGit, upstream, log) + assert.NoError(t, os.WriteFile(filepath.Join(dir, "git"), []byte(script), 0o755)) + t.Setenv("PATH", dir+string(os.PathListSeparator)+os.Getenv("PATH")) + return log +} + +func TestUploadPackSkipsBitmapsOnlyForIncrementalFetches(t *testing.T) { + tests := []struct { + name string + protocol string + body func(want, have string) string + newWant bool + gzipped bool + backend []string + forwarded int32 + }{ + { + name: "v2 fetch with haves", + protocol: "version=2", + body: func(want, have string) string { + return pkt("command=fetch\n") + "0001" + pkt("want "+want+"\n") + pkt("have "+have+"\n") + pkt("done\n") + "0000" + }, + backend: []string{"bitmaps=false"}, + }, + { + name: "v0 fetch with haves", + body: func(want, have string) string { + return pkt("want "+want+"\n") + "0000" + pkt("have "+have+"\n") + pkt("done\n") + }, + backend: []string{"bitmaps=false"}, + }, + { + name: "gzipped v0 fetch with haves", + body: func(want, have string) string { + return pkt("want "+want+"\n") + "0000" + pkt("have "+have+"\n") + pkt("done\n") + }, + gzipped: true, + backend: []string{"bitmaps=false"}, + }, + { + name: "fetch replayed after not our ref", + body: func(want, have string) string { + return pkt("want "+want+"\n") + "0000" + pkt("have "+have+"\n") + pkt("done\n") + }, + newWant: true, + backend: []string{"bitmaps=false", "bitmaps=false"}, + }, + { + name: "v0 clone", + body: func(want, _ string) string { + return pkt("want "+want+"\n") + "0000" + pkt("done\n") + }, + backend: []string{"bitmaps="}, + }, + { + name: "v2 ls-refs", + protocol: "version=2", + body: func(_, _ string) string { return pkt("command=ls-refs\n") + "0000" }, + backend: []string{"bitmaps="}, + }, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + fixture := newInfoRefsFixture(t) + log := recordBackendBitmaps(t, fixture.upstreamPath) + have := runInfoRefsGit(t, "-C", fixture.mirrorPath, "rev-parse", "refs/heads/main") + want := have + if test.newWant { + want = fixture.commitUpstream(t) + } + body := []byte(test.body(want, have)) + if test.gzipped { + var compressed bytes.Buffer + gw := gzip.NewWriter(&compressed) + _, err := gw.Write(body) + assert.NoError(t, err) + assert.NoError(t, gw.Close()) + body = compressed.Bytes() + } + req := httptest.NewRequestWithContext(fixture.ctx, http.MethodPost, + "/git/example.test/org/repo/git-upload-pack", bytes.NewReader(body)) + req.Header.Set("Content-Type", "application/x-git-upload-pack-request") + if test.gzipped { + req.Header.Set("Content-Encoding", "gzip") + } + if test.protocol != "" { + req.Header.Set("Git-Protocol", test.protocol) + } + req.SetPathValue("host", "example.test") + req.SetPathValue("path", "org/repo/git-upload-pack") + w := httptest.NewRecorder() + fixture.uploadPack.ServeHTTP(w, req) + + assert.Equal(t, http.StatusOK, w.Code) + assert.Equal(t, test.forwarded, fixture.transport.hits.Load()) + recorded, err := os.ReadFile(log) + assert.NoError(t, err) + assert.Equal(t, test.backend, strings.Fields(string(recorded))) + }) + } +}