From 8570ade39ead5194adba94c9f2dc75490621d1e8 Mon Sep 17 00:00:00 2001 From: Anders Rex Date: Tue, 1 Dec 2026 07:41:44 +0000 Subject: [PATCH 1/4] Add coarse git repo size to bundle deploy telemetry Sends git_repo_size on the bundle deploy event for bundles in a local git checkout: the tracked file count from the .git/index header and the size of .git/objects/pack, each as a coarse bucket. Co-authored-by: Isaac Signed-off-by: Anders Rex --- .../bundle/telemetry/deploy-git/output.txt | 6 +- acceptance/bundle/telemetry/deploy-git/script | 2 +- bundle/phases/telemetry.go | 80 +++++++ bundle/phases/telemetry_test.go | 51 +++++ libs/git/size.go | 162 ++++++++++++++ libs/git/size_test.go | 199 ++++++++++++++++++ libs/telemetry/protos/bundle_deploy.go | 14 ++ libs/telemetry/protos/enum.go | 32 +++ 8 files changed, 544 insertions(+), 2 deletions(-) create mode 100644 libs/git/size.go create mode 100644 libs/git/size_test.go diff --git a/acceptance/bundle/telemetry/deploy-git/output.txt b/acceptance/bundle/telemetry/deploy-git/output.txt index 259b256c782..73a8aee14a7 100644 --- a/acceptance/bundle/telemetry/deploy-git/output.txt +++ b/acceptance/bundle/telemetry/deploy-git/output.txt @@ -12,5 +12,9 @@ Resources: 0 created, 0 changed, 0 deleted, 0 unchanged "commit": "[COMMIT_SHA]" }, "from_workspace_folder": null, - "in_git_repo": true + "in_git_repo": true, + "git_repo_size": { + "tracked_file_count": "FILES_UNDER_1K", + "pack_size": "PACK_UNDER_10_MB" + } } diff --git a/acceptance/bundle/telemetry/deploy-git/script b/acceptance/bundle/telemetry/deploy-git/script index bbcb7701461..52d5a995a0c 100644 --- a/acceptance/bundle/telemetry/deploy-git/script +++ b/acceptance/bundle/telemetry/deploy-git/script @@ -3,6 +3,6 @@ git remote add origin https://github.com/databricks/cli trace $CLI bundle deploy -trace cat "$OUT_REQUESTS" | jq 'select(has("path") and .path == "/telemetry-ext") | .body.protoLogs[] | fromjson | .entry.databricks_cli_log.bundle_deploy_event | {git, from_workspace_folder, in_git_repo}' +trace cat "$OUT_REQUESTS" | jq 'select(has("path") and .path == "/telemetry-ext") | .body.protoLogs[] | fromjson | .entry.databricks_cli_log.bundle_deploy_event | {git, from_workspace_folder, in_git_repo, git_repo_size}' rm "$OUT_REQUESTS" diff --git a/bundle/phases/telemetry.go b/bundle/phases/telemetry.go index 7f4ebfff312..f269aa70b52 100644 --- a/bundle/phases/telemetry.go +++ b/bundle/phases/telemetry.go @@ -19,6 +19,7 @@ import ( "github.com/databricks/cli/libs/dbr" "github.com/databricks/cli/libs/diag" "github.com/databricks/cli/libs/dyn" + "github.com/databricks/cli/libs/git" "github.com/databricks/cli/libs/log" "github.com/databricks/cli/libs/telemetry" "github.com/databricks/cli/libs/telemetry/protos" @@ -241,6 +242,84 @@ func bundleGitInfo(b *bundle.Bundle) *protos.BundleGitInfo { } } +// Exclusive upper bounds for the tracked file count buckets. Counts at or above +// the last bound fall in the final bucket. Kept in sync with +// GitTrackedFileCountBucket in the universe proto. +var trackedFileCountBuckets = []struct { + below int64 + bucket protos.GitTrackedFileCountBucket +}{ + {1_000, protos.GitTrackedFileCountUnder1K}, + {5_000, protos.GitTrackedFileCount1KTo5K}, + {10_000, protos.GitTrackedFileCount5KTo10K}, + {20_000, protos.GitTrackedFileCount10KTo20K}, + {50_000, protos.GitTrackedFileCount20KTo50K}, + {100_000, protos.GitTrackedFileCount50KTo100K}, + {500_000, protos.GitTrackedFileCount100KTo500K}, + {1_000_000, protos.GitTrackedFileCount500KTo1M}, +} + +func trackedFileCountBucket(count int64) protos.GitTrackedFileCountBucket { + for _, b := range trackedFileCountBuckets { + if count < b.below { + return b.bucket + } + } + return protos.GitTrackedFileCountOver1M +} + +// Exclusive upper bounds in bytes for the pack size buckets. Sizes at or above +// the last bound fall in the final bucket. Kept in sync with GitPackSizeBucket +// in the universe proto. +var packSizeBuckets = []struct { + below int64 + bucket protos.GitPackSizeBucket +}{ + {10 << 20, protos.GitPackSizeUnder10MB}, + {100 << 20, protos.GitPackSize10MBTo100MB}, + {500 << 20, protos.GitPackSize100MBTo500MB}, + {1 << 30, protos.GitPackSize500MBTo1GB}, + {2 << 30, protos.GitPackSize1GBTo2GB}, + {5 << 30, protos.GitPackSize2GBTo5GB}, + {20 << 30, protos.GitPackSize5GBTo20GB}, +} + +func packSizeBucket(size int64) protos.GitPackSizeBucket { + for _, b := range packSizeBuckets { + if size < b.below { + return b.bucket + } + } + return protos.GitPackSizeOver20GB +} + +// bundleGitRepoSize reports the coarse size of the local git repository the +// bundle is in. Only buckets are sent, exact values never leave the machine. +// Nil for Databricks Git folders, whose size the workspace already knows, and +// when neither value could be read. +func bundleGitRepoSize(ctx context.Context, b *bundle.Bundle) *protos.BundleGitRepoSize { + if b.InGitRepo == nil || !*b.InGitRepo || fromWorkspaceFolder(ctx, b) { + return nil + } + // On error the values that could be read are still reported. + size, err := git.FetchRepositorySize(b.WorktreeRoot) + if err != nil { + log.Debugf(ctx, "failed to read git repository size: %s", err) + } + if size.TrackedFileCount == nil && size.PackSizeBytes == nil { + return nil + } + + out := &protos.BundleGitRepoSize{} + if size.TrackedFileCount != nil { + out.TrackedFileCount = trackedFileCountBucket(*size.TrackedFileCount) + } + if size.PackSizeBytes != nil { + out.PackSize = packSizeBucket(*size.PackSizeBytes) + } + return out +} + // fromWorkspaceFolder reports whether the bundle was deployed from a workspace // folder: the CLI running on a Databricks cluster with the bundle source under // /Workspace/, as opposed to a local checkout. Same signal as the source-linked @@ -474,6 +553,7 @@ func LogDeployTelemetry(ctx context.Context, b *bundle.Bundle, errMsg string) { Git: bundleGitInfo(b), FromWorkspaceFolder: fromWorkspaceFolder(ctx, b), InGitRepo: b.InGitRepo, + GitRepoSize: bundleGitRepoSize(ctx, b), BundleBitmap: bundleBitmap(ctx, b), Experimental: &protos.BundleDeployExperimental{ diff --git a/bundle/phases/telemetry_test.go b/bundle/phases/telemetry_test.go index 613f0f6de10..3345badfe00 100644 --- a/bundle/phases/telemetry_test.go +++ b/bundle/phases/telemetry_test.go @@ -209,3 +209,54 @@ func TestPydabsMetrics(t *testing.T) { b := &bundle.Bundle{Config: config.Root{Experimental: &config.Experimental{Python: pythonConfig}}, Metrics: metrics} assert.Equal(t, expected, pydabsMetrics(b)) } + +func TestTrackedFileCountBucket(t *testing.T) { + tests := []struct { + count int64 + want protos.GitTrackedFileCountBucket + }{ + {0, protos.GitTrackedFileCountUnder1K}, + {999, protos.GitTrackedFileCountUnder1K}, + {1_000, protos.GitTrackedFileCount1KTo5K}, + {4_999, protos.GitTrackedFileCount1KTo5K}, + {5_000, protos.GitTrackedFileCount5KTo10K}, + {10_000, protos.GitTrackedFileCount10KTo20K}, + {19_999, protos.GitTrackedFileCount10KTo20K}, + {20_000, protos.GitTrackedFileCount20KTo50K}, + {50_000, protos.GitTrackedFileCount50KTo100K}, + {99_999, protos.GitTrackedFileCount50KTo100K}, + {100_000, protos.GitTrackedFileCount100KTo500K}, + {499_999, protos.GitTrackedFileCount100KTo500K}, + {500_000, protos.GitTrackedFileCount500KTo1M}, + {1_000_000, protos.GitTrackedFileCountOver1M}, + {5_000_000, protos.GitTrackedFileCountOver1M}, + } + for _, tt := range tests { + assert.Equal(t, tt.want, trackedFileCountBucket(tt.count), "count %d", tt.count) + } +} + +func TestPackSizeBucket(t *testing.T) { + const mb = int64(1 << 20) + tests := []struct { + size int64 + want protos.GitPackSizeBucket + }{ + {0, protos.GitPackSizeUnder10MB}, + {10*mb - 1, protos.GitPackSizeUnder10MB}, + {10 * mb, protos.GitPackSize10MBTo100MB}, + {100 * mb, protos.GitPackSize100MBTo500MB}, + {500*mb - 1, protos.GitPackSize100MBTo500MB}, + {500 * mb, protos.GitPackSize500MBTo1GB}, + {1024 * mb, protos.GitPackSize1GBTo2GB}, + {2048*mb - 1, protos.GitPackSize1GBTo2GB}, + {2048 * mb, protos.GitPackSize2GBTo5GB}, + {5*1024*mb - 1, protos.GitPackSize2GBTo5GB}, + {5 * 1024 * mb, protos.GitPackSize5GBTo20GB}, + {20 * 1024 * mb, protos.GitPackSizeOver20GB}, + {100 * 1024 * mb, protos.GitPackSizeOver20GB}, + } + for _, tt := range tests { + assert.Equal(t, tt.want, packSizeBucket(tt.size), "size %d", tt.size) + } +} diff --git a/libs/git/size.go b/libs/git/size.go new file mode 100644 index 00000000000..48bbd3df8dc --- /dev/null +++ b/libs/git/size.go @@ -0,0 +1,162 @@ +package git + +import ( + "bytes" + "encoding/binary" + "errors" + "fmt" + "io" + "io/fs" + "path" + "strings" + + "github.com/databricks/cli/libs/vfs" +) + +// RepositorySize holds cheap proxies for the size of a local repository. They +// come from git metadata only, so the worktree is never walked. A field is nil +// when it is not known. +type RepositorySize struct { + // Number of entries in the index, which is the number of tracked files. + // Nil without an index, or when the index header does not hold the full + // count (split index or sparse index). + TrackedFileCount *int64 + + // Total size in bytes of the files in objects/pack. Loose objects and + // alternates are not counted. Nil without a pack directory, and for + // shallow and partial clones. + PackSizeBytes *int64 +} + +// The index starts with a 12 byte header: the "DIRC" signature, a version and +// the entry count, all big-endian. +// See https://git-scm.com/docs/index-format +var indexSignature = []byte("DIRC") + +const indexHeaderSize = 12 + +// FetchRepositorySize reads the size proxies of the repository whose worktree +// root is root. The index lives in $GIT_DIR and packs in $GIT_COMMON_DIR, so +// both are read correctly from a linked worktree. The fields are read +// independently, so on error the ones that could be read are still set. +func FetchRepositorySize(root vfs.Path) (RepositorySize, error) { + var size RepositorySize + + gitDir, gitCommonDir, err := resolveGitDirs(root) + if err != nil { + return size, err + } + + var countErr, packErr error + size.TrackedFileCount, countErr = indexEntryCount(gitDir, gitCommonDir) + size.PackSizeBytes, packErr = packSize(gitCommonDir) + return size, errors.Join(countErr, packErr) +} + +func indexEntryCount(gitDir, gitCommonDir vfs.Path) (*int64, error) { + partial, err := indexHeaderIsPartial(gitDir, gitCommonDir) + if err != nil || partial { + return nil, err + } + + f, err := gitDir.Open("index") + if errors.Is(err, fs.ErrNotExist) { + return nil, nil + } + if err != nil { + return nil, err + } + defer f.Close() + + header := make([]byte, indexHeaderSize) + if _, err := io.ReadFull(f, header); err != nil { + return nil, fmt.Errorf("failed to read git index header: %w", err) + } + if !bytes.Equal(header[:4], indexSignature) { + return nil, errors.New("git index has an invalid signature") + } + count := int64(binary.BigEndian.Uint32(header[8:12])) + return &count, nil +} + +// indexHeaderIsPartial reports whether the index header may not count every +// tracked file. A split index keeps most entries in a sharedindex. file. +// A sparse index (index.sparse) collapses directories outside the sparse cone +// into one entry. A plain sparse checkout keeps an entry per file, so its +// count is complete. Detecting either from the index itself needs a full +// parse, so this checks the files git keeps next to it. +func indexHeaderIsPartial(gitDir, gitCommonDir vfs.Path) (bool, error) { + entries, err := gitDir.ReadDir(".") + if errors.Is(err, fs.ErrNotExist) { + return false, nil + } + if err != nil { + return false, err + } + for _, entry := range entries { + if strings.HasPrefix(entry.Name(), "sharedindex.") { + return true, nil + } + } + + // `git sparse-checkout init --sparse-index` writes index.sparse to the + // worktree config when worktree config is enabled, else to the repo config. + cfg := config{variables: make(map[string]string)} + if err := cfg.loadFile(gitCommonDir, "config"); err != nil { + return false, err + } + if err := cfg.loadFile(gitDir, "config.worktree"); err != nil { + return false, err + } + return isTrue(cfg.variables["index.sparse"]), nil +} + +// isTrue parses a git boolean value. +// See https://git-scm.com/docs/git-config#Documentation/git-config.txt-boolean +func isTrue(value string) bool { + switch strings.ToLower(value) { + case "true", "yes", "on", "1": + return true + } + return false +} + +// packSize returns nil for shallow and partial clones. Their packs hold only +// part of the history, so the size would understate the repository. +func packSize(gitCommonDir vfs.Path) (*int64, error) { + // A shallow clone has a shallow file in $GIT_COMMON_DIR, also when read + // from a linked worktree. + if _, err := gitCommonDir.Stat("shallow"); err == nil { + return nil, nil + } else if !errors.Is(err, fs.ErrNotExist) { + return nil, err + } + + entries, err := gitCommonDir.ReadDir(path.Join("objects", "pack")) + if errors.Is(err, fs.ErrNotExist) { + return nil, nil + } + if err != nil { + return nil, err + } + + var total int64 + for _, entry := range entries { + // A partial clone (e.g. --filter=blob:none) marks every pack it fetched + // with a .promisor file. The config marker differs across git versions. + // See https://git-scm.com/docs/partial-clone + if strings.HasSuffix(entry.Name(), ".promisor") { + return nil, nil + } + // Skip packs that a concurrent fetch or gc is still writing. + if !entry.Type().IsRegular() || strings.HasPrefix(entry.Name(), "tmp_") { + continue + } + info, err := entry.Info() + if err != nil { + return nil, err + } + total += info.Size() + } + return &total, nil +} diff --git a/libs/git/size_test.go b/libs/git/size_test.go new file mode 100644 index 00000000000..0354aed529b --- /dev/null +++ b/libs/git/size_test.go @@ -0,0 +1,199 @@ +package git + +import ( + "encoding/binary" + "os" + "path/filepath" + "testing" + + "github.com/databricks/cli/libs/vfs" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func writeIndex(t *testing.T, gitDir string, entries uint32) { + // Bytes after the header stand in for the entries, which are never read. + content := make([]byte, indexHeaderSize+64) + copy(content, indexSignature) + binary.BigEndian.PutUint32(content[4:8], 2) + binary.BigEndian.PutUint32(content[8:12], entries) + require.NoError(t, os.MkdirAll(gitDir, 0o755)) + require.NoError(t, os.WriteFile(filepath.Join(gitDir, "index"), content, 0o644)) +} + +func writePack(t *testing.T, gitCommonDir, name string, size int) { + dir := filepath.Join(gitCommonDir, "objects", "pack") + require.NoError(t, os.MkdirAll(dir, 0o755)) + require.NoError(t, os.WriteFile(filepath.Join(dir, name), make([]byte, size), 0o644)) +} + +func TestFetchRepositorySize(t *testing.T) { + root := t.TempDir() + gitDir := filepath.Join(root, ".git") + require.NoError(t, os.MkdirAll(gitDir, 0o755)) + writeIndex(t, gitDir, 4321) + writePack(t, gitDir, "pack-1.pack", 1000) + writePack(t, gitDir, "pack-1.idx", 200) + writePack(t, gitDir, "pack-2.pack", 30) + // Directories in objects/pack are not counted. + require.NoError(t, os.MkdirAll(filepath.Join(gitDir, "objects", "pack", "tmp"), 0o755)) + + size, err := FetchRepositorySize(vfs.MustNew(root)) + require.NoError(t, err) + require.NotNil(t, size.TrackedFileCount) + require.NotNil(t, size.PackSizeBytes) + assert.Equal(t, int64(4321), *size.TrackedFileCount) + assert.Equal(t, int64(1230), *size.PackSizeBytes) +} + +func TestFetchRepositorySizeWorktree(t *testing.T) { + dir := setupWorktree(t) + writeGitDir(t, dir, "gitdir: ../.git/worktrees/my_worktree") + writeGitCommonDir(t, dir, "../..") + + // The index is per worktree, packs are shared. + writeIndex(t, filepath.Join(dir, ".git", "worktrees", "my_worktree"), 7) + writeIndex(t, filepath.Join(dir, ".git"), 99) + writePack(t, filepath.Join(dir, ".git"), "pack-1.pack", 512) + + size, err := FetchRepositorySize(vfs.MustNew(filepath.Join(dir, "my_worktree"))) + require.NoError(t, err) + require.NotNil(t, size.TrackedFileCount) + require.NotNil(t, size.PackSizeBytes) + assert.Equal(t, int64(7), *size.TrackedFileCount) + assert.Equal(t, int64(512), *size.PackSizeBytes) +} + +func TestFetchRepositorySizeEmptyRepository(t *testing.T) { + root := t.TempDir() + require.NoError(t, os.MkdirAll(filepath.Join(root, ".git"), 0o755)) + + size, err := FetchRepositorySize(vfs.MustNew(root)) + require.NoError(t, err) + assert.Nil(t, size.TrackedFileCount) + assert.Nil(t, size.PackSizeBytes) +} + +func TestFetchRepositorySizeInvalidIndexKeepsPackSize(t *testing.T) { + for name, content := range map[string]string{ + "invalid signature": "not an index", + "failed to read git index header": "DIRC", + } { + t.Run(name, func(t *testing.T) { + root := t.TempDir() + gitDir := filepath.Join(root, ".git") + require.NoError(t, os.MkdirAll(gitDir, 0o755)) + require.NoError(t, os.WriteFile(filepath.Join(gitDir, "index"), []byte(content), 0o644)) + writePack(t, gitDir, "pack-1.pack", 100) + + size, err := FetchRepositorySize(vfs.MustNew(root)) + assert.ErrorContains(t, err, name) + assert.Nil(t, size.TrackedFileCount) + require.NotNil(t, size.PackSizeBytes) + assert.Equal(t, int64(100), *size.PackSizeBytes) + }) + } +} + +func TestFetchRepositorySizePartialIndex(t *testing.T) { + for name, files := range map[string]map[string]string{ + "split index": { + "sharedindex.0123456789abcdef0123456789abcdef01234567": "", + }, + "sparse index in repo config": { + "config": "[core]\n\tsparseCheckout = true\n[index]\n\tsparse = true\n", + }, + "sparse index in worktree config": { + "config.worktree": "[index]\n\tsparse = yes\n", + }, + } { + t.Run(name, func(t *testing.T) { + root := t.TempDir() + gitDir := filepath.Join(root, ".git") + require.NoError(t, os.MkdirAll(gitDir, 0o755)) + writeIndex(t, gitDir, 12) + for file, content := range files { + require.NoError(t, os.WriteFile(filepath.Join(gitDir, file), []byte(content), 0o644)) + } + + size, err := FetchRepositorySize(vfs.MustNew(root)) + require.NoError(t, err) + assert.Nil(t, size.TrackedFileCount) + }) + } +} + +func TestFetchRepositorySizeSparseCheckoutWithoutSparseIndex(t *testing.T) { + // Without index.sparse the index keeps an entry per tracked file. + root := t.TempDir() + gitDir := filepath.Join(root, ".git") + require.NoError(t, os.MkdirAll(filepath.Join(gitDir, "info"), 0o755)) + writeIndex(t, gitDir, 250_000) + require.NoError(t, os.WriteFile(filepath.Join(gitDir, "info", "sparse-checkout"), []byte("/*\n"), 0o644)) + require.NoError(t, os.WriteFile(filepath.Join(gitDir, "config"), []byte("[core]\n\tsparseCheckout = true\n[index]\n\tsparse = false\n"), 0o644)) + + size, err := FetchRepositorySize(vfs.MustNew(root)) + require.NoError(t, err) + require.NotNil(t, size.TrackedFileCount) + assert.Equal(t, int64(250_000), *size.TrackedFileCount) +} + +func TestFetchRepositorySizeSkipsTemporaryPacks(t *testing.T) { + root := t.TempDir() + gitDir := filepath.Join(root, ".git") + writePack(t, gitDir, "pack-1.pack", 10) + writePack(t, gitDir, "tmp_pack_abc123", 1000) + + size, err := FetchRepositorySize(vfs.MustNew(root)) + require.NoError(t, err) + require.NotNil(t, size.PackSizeBytes) + assert.Equal(t, int64(10), *size.PackSizeBytes) +} + +func TestFetchRepositorySizeShallowClone(t *testing.T) { + root := t.TempDir() + gitDir := filepath.Join(root, ".git") + writeIndex(t, gitDir, 12) + writePack(t, gitDir, "pack-1.pack", 100) + require.NoError(t, os.WriteFile(filepath.Join(gitDir, "shallow"), []byte("0123456789abcdef0123456789abcdef01234567\n"), 0o644)) + + size, err := FetchRepositorySize(vfs.MustNew(root)) + require.NoError(t, err) + assert.Nil(t, size.PackSizeBytes) + // The index still lists every tracked file. + require.NotNil(t, size.TrackedFileCount) + assert.Equal(t, int64(12), *size.TrackedFileCount) +} + +func TestFetchRepositorySizeShallowCloneWorktree(t *testing.T) { + dir := setupWorktree(t) + writeGitDir(t, dir, "gitdir: ../.git/worktrees/my_worktree") + writeGitCommonDir(t, dir, "../..") + writePack(t, filepath.Join(dir, ".git"), "pack-1.pack", 100) + require.NoError(t, os.WriteFile(filepath.Join(dir, ".git", "shallow"), nil, 0o644)) + + size, err := FetchRepositorySize(vfs.MustNew(filepath.Join(dir, "my_worktree"))) + require.NoError(t, err) + assert.Nil(t, size.PackSizeBytes) +} + +func TestFetchRepositorySizePartialClone(t *testing.T) { + root := t.TempDir() + gitDir := filepath.Join(root, ".git") + writeIndex(t, gitDir, 12) + writePack(t, gitDir, "pack-1.pack", 100) + writePack(t, gitDir, "pack-1.promisor", 0) + + size, err := FetchRepositorySize(vfs.MustNew(root)) + require.NoError(t, err) + assert.Nil(t, size.PackSizeBytes) + require.NotNil(t, size.TrackedFileCount) + assert.Equal(t, int64(12), *size.TrackedFileCount) +} + +func TestFetchRepositorySizeNoRepository(t *testing.T) { + size, err := FetchRepositorySize(vfs.MustNew(t.TempDir())) + require.NoError(t, err) + assert.Nil(t, size.TrackedFileCount) + assert.Nil(t, size.PackSizeBytes) +} diff --git a/libs/telemetry/protos/bundle_deploy.go b/libs/telemetry/protos/bundle_deploy.go index 0064abb8568..4a0110b7127 100644 --- a/libs/telemetry/protos/bundle_deploy.go +++ b/libs/telemetry/protos/bundle_deploy.go @@ -67,6 +67,10 @@ type BundleDeployEvent struct { // names are recorded as "*". Omitted when the configuration did not load. BundleBitmap string `json:"bundle_bitmap,omitempty"` + // Coarse size of the local git repository the bundle was deployed from. + // Nil outside a local `.git` checkout or when it could not be read. + GitRepoSize *BundleGitRepoSize `json:"git_repo_size,omitempty"` + Experimental *BundleDeployExperimental `json:"experimental,omitempty"` } @@ -85,6 +89,16 @@ type BundleGitInfo struct { Commit string `json:"commit,omitempty"` } +// BundleGitRepoSize mirrors the universe proto. Only buckets are sent, never +// exact values. A bucket is empty when the repository does not have it yet. +type BundleGitRepoSize struct { + // Bucketed entry count from the git index header. + TrackedFileCount GitTrackedFileCountBucket `json:"tracked_file_count,omitempty"` + + // Bucketed total size of the files in `.git/objects/pack`. + PackSize GitPackSizeBucket `json:"pack_size,omitempty"` +} + // BundleDeploymentHistory measures history recording for one deployment version. type BundleDeploymentHistory struct { // Number of resource operations staged for this deployment version. diff --git a/libs/telemetry/protos/enum.go b/libs/telemetry/protos/enum.go index a0c873063fa..3d4f0e64701 100644 --- a/libs/telemetry/protos/enum.go +++ b/libs/telemetry/protos/enum.go @@ -33,3 +33,35 @@ const ( PydabsConfigSectionExperimentalPython PydabsConfigSection = "EXPERIMENTAL_PYTHON" PydabsConfigSectionBoth PydabsConfigSection = "BOTH" ) + +// GitTrackedFileCountBucket is a coarse bucket for the number of entries in a +// git index. +type GitTrackedFileCountBucket string + +const ( + GitTrackedFileCountBucketUnspecified GitTrackedFileCountBucket = "TYPE_UNSPECIFIED" + GitTrackedFileCountUnder1K GitTrackedFileCountBucket = "FILES_UNDER_1K" + GitTrackedFileCount1KTo5K GitTrackedFileCountBucket = "FILES_1K_TO_5K" + GitTrackedFileCount5KTo10K GitTrackedFileCountBucket = "FILES_5K_TO_10K" + GitTrackedFileCount10KTo20K GitTrackedFileCountBucket = "FILES_10K_TO_20K" + GitTrackedFileCount20KTo50K GitTrackedFileCountBucket = "FILES_20K_TO_50K" + GitTrackedFileCount50KTo100K GitTrackedFileCountBucket = "FILES_50K_TO_100K" + GitTrackedFileCount100KTo500K GitTrackedFileCountBucket = "FILES_100K_TO_500K" + GitTrackedFileCount500KTo1M GitTrackedFileCountBucket = "FILES_500K_TO_1M" + GitTrackedFileCountOver1M GitTrackedFileCountBucket = "FILES_OVER_1M" +) + +// GitPackSizeBucket is a coarse bucket for the on-disk size of git pack files. +type GitPackSizeBucket string + +const ( + GitPackSizeBucketUnspecified GitPackSizeBucket = "TYPE_UNSPECIFIED" + GitPackSizeUnder10MB GitPackSizeBucket = "PACK_UNDER_10_MB" + GitPackSize10MBTo100MB GitPackSizeBucket = "PACK_10_MB_TO_100_MB" + GitPackSize100MBTo500MB GitPackSizeBucket = "PACK_100_MB_TO_500_MB" + GitPackSize500MBTo1GB GitPackSizeBucket = "PACK_500_MB_TO_1_GB" + GitPackSize1GBTo2GB GitPackSizeBucket = "PACK_1_GB_TO_2_GB" + GitPackSize2GBTo5GB GitPackSizeBucket = "PACK_2_GB_TO_5_GB" + GitPackSize5GBTo20GB GitPackSizeBucket = "PACK_5_GB_TO_20_GB" + GitPackSizeOver20GB GitPackSizeBucket = "PACK_OVER_20_GB" +) From 8a4a2eea17d4490d39960995ab49bcc4f1e8b80b Mon Sep 17 00:00:00 2001 From: Anders Rex Date: Tue, 1 Dec 2026 13:01:11 +0000 Subject: [PATCH 2/4] Fix git repo size for loose objects, alternates and stale split indexes Counts loose objects in the object store size, and leaves it unset for repositories that use alternates. Treats a shared index as active only when it is as new as the index, reads index.sparse from the global config and requires core.sparseCheckout for a sparse index. Adds tests for the cases where git_repo_size is not sent. Co-authored-by: Isaac Signed-off-by: Anders Rex --- bundle/phases/telemetry.go | 2 +- bundle/phases/telemetry_git_repo_size_test.go | 96 +++++++++++ libs/git/size.go | 154 ++++++++++++------ libs/git/size_test.go | 127 +++++++++++++-- 4 files changed, 317 insertions(+), 62 deletions(-) create mode 100644 bundle/phases/telemetry_git_repo_size_test.go diff --git a/bundle/phases/telemetry.go b/bundle/phases/telemetry.go index f269aa70b52..cec56d4d12d 100644 --- a/bundle/phases/telemetry.go +++ b/bundle/phases/telemetry.go @@ -302,7 +302,7 @@ func bundleGitRepoSize(ctx context.Context, b *bundle.Bundle) *protos.BundleGitR return nil } // On error the values that could be read are still reported. - size, err := git.FetchRepositorySize(b.WorktreeRoot) + size, err := git.FetchRepositorySize(ctx, b.WorktreeRoot) if err != nil { log.Debugf(ctx, "failed to read git repository size: %s", err) } diff --git a/bundle/phases/telemetry_git_repo_size_test.go b/bundle/phases/telemetry_git_repo_size_test.go new file mode 100644 index 00000000000..2c7d92ece5f --- /dev/null +++ b/bundle/phases/telemetry_git_repo_size_test.go @@ -0,0 +1,96 @@ +package phases + +import ( + "context" + "encoding/binary" + "os" + "path/filepath" + "testing" + + "github.com/databricks/cli/bundle" + "github.com/databricks/cli/libs/dbr" + "github.com/databricks/cli/libs/env" + "github.com/databricks/cli/libs/telemetry/protos" + "github.com/databricks/cli/libs/vfs" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// gitRepoSizeContext isolates the global git config and sets whether the CLI +// runs on a Databricks cluster. +func gitRepoSizeContext(t *testing.T, onRuntime bool) context.Context { + ctx := env.WithUserHomeDir(t.Context(), t.TempDir()) + ctx = env.Set(ctx, "XDG_CONFIG_HOME", "") + return dbr.MockRuntime(ctx, dbr.Environment{IsDbr: onRuntime}) +} + +// gitRepoSizeBundle returns a bundle in a repository with 1,500 tracked files +// and a 20 MiB pack. Without withRepo the .git directory is empty. +func gitRepoSizeBundle(t *testing.T, withRepo bool) *bundle.Bundle { + root := t.TempDir() + gitDir := filepath.Join(root, ".git") + require.NoError(t, os.MkdirAll(gitDir, 0o755)) + if withRepo { + require.NoError(t, os.MkdirAll(filepath.Join(gitDir, "objects", "pack"), 0o755)) + index := make([]byte, 12) + copy(index, "DIRC") + binary.BigEndian.PutUint32(index[4:8], 2) + binary.BigEndian.PutUint32(index[8:12], 1_500) + require.NoError(t, os.WriteFile(filepath.Join(gitDir, "index"), index, 0o644)) + require.NoError(t, os.WriteFile(filepath.Join(gitDir, "objects", "pack", "pack-1.pack"), make([]byte, 20<<20), 0o644)) + } + inGitRepo := true + return &bundle.Bundle{ + WorktreeRoot: vfs.MustNew(root), + SyncRootPath: root, + InGitRepo: &inGitRepo, + } +} + +func TestBundleGitRepoSize(t *testing.T) { + got := bundleGitRepoSize(gitRepoSizeContext(t, false), gitRepoSizeBundle(t, true)) + assert.Equal(t, &protos.BundleGitRepoSize{ + TrackedFileCount: protos.GitTrackedFileCount1KTo5K, + PackSize: protos.GitPackSize10MBTo100MB, + }, got) +} + +func TestBundleGitRepoSizeSkipped(t *testing.T) { + notInRepo := false + + tests := []struct { + name string + onRuntime bool + edit func(b *bundle.Bundle) + withRepo bool + }{ + { + name: "git detection did not run", + edit: func(b *bundle.Bundle) { b.InGitRepo = nil }, + withRepo: true, + }, + { + name: "not in a git repository", + edit: func(b *bundle.Bundle) { b.InGitRepo = ¬InRepo }, + withRepo: true, + }, + { + // The workspace already knows the size of a Databricks Git folder. + name: "deployed from a workspace folder", + onRuntime: true, + edit: func(b *bundle.Bundle) { b.SyncRootPath = "/Workspace/Users/someone@example.com/repo" }, + withRepo: true, + }, + { + name: "nothing readable", + edit: func(b *bundle.Bundle) {}, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + b := gitRepoSizeBundle(t, tt.withRepo) + tt.edit(b) + assert.Nil(t, bundleGitRepoSize(gitRepoSizeContext(t, tt.onRuntime), b)) + }) + } +} diff --git a/libs/git/size.go b/libs/git/size.go index 48bbd3df8dc..5d1270100ae 100644 --- a/libs/git/size.go +++ b/libs/git/size.go @@ -2,6 +2,7 @@ package git import ( "bytes" + "context" "encoding/binary" "errors" "fmt" @@ -22,9 +23,9 @@ type RepositorySize struct { // count (split index or sparse index). TrackedFileCount *int64 - // Total size in bytes of the files in objects/pack. Loose objects and - // alternates are not counted. Nil without a pack directory, and for - // shallow and partial clones. + // Total size in bytes of the object store: the files in objects/pack plus + // loose objects. Nil without an objects directory, and for shallow clones, + // partial clones and repositories that borrow objects through alternates. PackSizeBytes *int64 } @@ -36,10 +37,10 @@ var indexSignature = []byte("DIRC") const indexHeaderSize = 12 // FetchRepositorySize reads the size proxies of the repository whose worktree -// root is root. The index lives in $GIT_DIR and packs in $GIT_COMMON_DIR, so +// root is root. The index lives in $GIT_DIR and objects in $GIT_COMMON_DIR, so // both are read correctly from a linked worktree. The fields are read // independently, so on error the ones that could be read are still set. -func FetchRepositorySize(root vfs.Path) (RepositorySize, error) { +func FetchRepositorySize(ctx context.Context, root vfs.Path) (RepositorySize, error) { var size RepositorySize gitDir, gitCommonDir, err := resolveGitDirs(root) @@ -48,17 +49,12 @@ func FetchRepositorySize(root vfs.Path) (RepositorySize, error) { } var countErr, packErr error - size.TrackedFileCount, countErr = indexEntryCount(gitDir, gitCommonDir) - size.PackSizeBytes, packErr = packSize(gitCommonDir) + size.TrackedFileCount, countErr = indexEntryCount(ctx, gitDir, gitCommonDir) + size.PackSizeBytes, packErr = objectStoreSize(gitCommonDir) return size, errors.Join(countErr, packErr) } -func indexEntryCount(gitDir, gitCommonDir vfs.Path) (*int64, error) { - partial, err := indexHeaderIsPartial(gitDir, gitCommonDir) - if err != nil || partial { - return nil, err - } - +func indexEntryCount(ctx context.Context, gitDir, gitCommonDir vfs.Path) (*int64, error) { f, err := gitDir.Open("index") if errors.Is(err, fs.ErrNotExist) { return nil, nil @@ -68,6 +64,11 @@ func indexEntryCount(gitDir, gitCommonDir vfs.Path) (*int64, error) { } defer f.Close() + partial, err := indexHeaderIsPartial(ctx, gitDir, gitCommonDir) + if err != nil || partial { + return nil, err + } + header := make([]byte, indexHeaderSize) if _, err := io.ReadFull(f, header); err != nil { return nil, fmt.Errorf("failed to read git index header: %w", err) @@ -81,34 +82,66 @@ func indexEntryCount(gitDir, gitCommonDir vfs.Path) (*int64, error) { // indexHeaderIsPartial reports whether the index header may not count every // tracked file. A split index keeps most entries in a sharedindex. file. -// A sparse index (index.sparse) collapses directories outside the sparse cone -// into one entry. A plain sparse checkout keeps an entry per file, so its -// count is complete. Detecting either from the index itself needs a full -// parse, so this checks the files git keeps next to it. -func indexHeaderIsPartial(gitDir, gitCommonDir vfs.Path) (bool, error) { - entries, err := gitDir.ReadDir(".") - if errors.Is(err, fs.ErrNotExist) { - return false, nil +// A sparse index collapses directories outside the sparse cone into one entry. +// A plain sparse checkout keeps an entry per file, so its count is complete. +// Detecting either from the index itself needs a full parse, so this checks +// the files and config git keeps next to it. +func indexHeaderIsPartial(ctx context.Context, gitDir, gitCommonDir vfs.Path) (bool, error) { + split, err := splitIndexIsActive(gitDir) + if err != nil || split { + return split, err + } + return sparseIndexIsEnabled(ctx, gitDir, gitCommonDir) +} + +// splitIndexIsActive reports whether a shared index belongs to the current +// index. Git sets the mtime of the shared index to that of the index on every +// write. After split index is turned off the old shared index files stay +// (splitIndex.sharedIndexExpire, two weeks by default) but are no longer +// touched, so they are older than the index. +func splitIndexIsActive(gitDir vfs.Path) (bool, error) { + index, err := gitDir.Stat("index") + if err != nil { + return false, err } + entries, err := gitDir.ReadDir(".") if err != nil { return false, err } for _, entry := range entries { - if strings.HasPrefix(entry.Name(), "sharedindex.") { + if !strings.HasPrefix(entry.Name(), "sharedindex.") { + continue + } + info, err := entry.Info() + if err != nil { + return false, err + } + if !info.ModTime().Before(index.ModTime()) { return true, nil } } + return false, nil +} - // `git sparse-checkout init --sparse-index` writes index.sparse to the - // worktree config when worktree config is enabled, else to the repo config. - cfg := config{variables: make(map[string]string)} - if err := cfg.loadFile(gitCommonDir, "config"); err != nil { +// sparseIndexIsEnabled reports whether git writes a sparse index, which needs +// both core.sparseCheckout and index.sparse. Settings in included config files +// are not read. +func sparseIndexIsEnabled(ctx context.Context, gitDir, gitCommonDir vfs.Path) (bool, error) { + cfg, err := globalGitConfig(ctx) + if err != nil { return false, err } - if err := cfg.loadFile(gitDir, "config.worktree"); err != nil { + if err := cfg.loadFile(gitCommonDir, "config"); err != nil { return false, err } - return isTrue(cfg.variables["index.sparse"]), nil + // `git sparse-checkout init` writes to config.worktree when worktree config + // is enabled. Git ignores that file otherwise. + if isTrue(cfg.variables["extensions.worktreeconfig"]) { + if err := cfg.loadFile(gitDir, "config.worktree"); err != nil { + return false, err + } + } + return isTrue(cfg.variables["core.sparsecheckout"]) && isTrue(cfg.variables["index.sparse"]), nil } // isTrue parses a git boolean value. @@ -121,18 +154,21 @@ func isTrue(value string) bool { return false } -// packSize returns nil for shallow and partial clones. Their packs hold only -// part of the history, so the size would understate the repository. -func packSize(gitCommonDir vfs.Path) (*int64, error) { +// objectStoreSize returns nil when the local objects hold only part of the +// history, so the size would understate the repository. +func objectStoreSize(gitCommonDir vfs.Path) (*int64, error) { // A shallow clone has a shallow file in $GIT_COMMON_DIR, also when read - // from a linked worktree. - if _, err := gitCommonDir.Stat("shallow"); err == nil { - return nil, nil - } else if !errors.Is(err, fs.ErrNotExist) { - return nil, err + // from a linked worktree. A clone made with --reference or --shared reads + // most objects from the repositories listed in objects/info/alternates. + for _, name := range []string{"shallow", path.Join("objects", "info", "alternates")} { + if _, err := gitCommonDir.Stat(name); err == nil { + return nil, nil + } else if !errors.Is(err, fs.ErrNotExist) { + return nil, err + } } - entries, err := gitCommonDir.ReadDir(path.Join("objects", "pack")) + dirs, err := gitCommonDir.ReadDir("objects") if errors.Is(err, fs.ErrNotExist) { return nil, nil } @@ -141,22 +177,44 @@ func packSize(gitCommonDir vfs.Path) (*int64, error) { } var total int64 - for _, entry := range entries { - // A partial clone (e.g. --filter=blob:none) marks every pack it fetched - // with a .promisor file. The config marker differs across git versions. - // See https://git-scm.com/docs/partial-clone - if strings.HasSuffix(entry.Name(), ".promisor") { - return nil, nil - } - // Skip packs that a concurrent fetch or gc is still writing. - if !entry.Type().IsRegular() || strings.HasPrefix(entry.Name(), "tmp_") { + for _, dir := range dirs { + // Packs live in objects/pack, loose objects in objects/<2 hex digits>. + if !dir.IsDir() || (dir.Name() != "pack" && !isLooseObjectDir(dir.Name())) { continue } - info, err := entry.Info() + entries, err := gitCommonDir.ReadDir(path.Join("objects", dir.Name())) if err != nil { return nil, err } - total += info.Size() + for _, entry := range entries { + // A partial clone (e.g. --filter=blob:none) marks every pack it + // fetched with a .promisor file. The config marker differs across + // git versions. See https://git-scm.com/docs/partial-clone + if strings.HasSuffix(entry.Name(), ".promisor") { + return nil, nil + } + // Skip files that a concurrent fetch, commit or gc is still writing. + if !entry.Type().IsRegular() || strings.HasPrefix(entry.Name(), "tmp_") { + continue + } + info, err := entry.Info() + if err != nil { + return nil, err + } + total += info.Size() + } } return &total, nil } + +func isLooseObjectDir(name string) bool { + if len(name) != 2 { + return false + } + for _, c := range name { + if !strings.ContainsRune("0123456789abcdef", c) { + return false + } + } + return true +} diff --git a/libs/git/size_test.go b/libs/git/size_test.go index 0354aed529b..bde8b40a4a9 100644 --- a/libs/git/size_test.go +++ b/libs/git/size_test.go @@ -1,16 +1,25 @@ package git import ( + "context" "encoding/binary" "os" "path/filepath" "testing" + "time" + "github.com/databricks/cli/libs/env" "github.com/databricks/cli/libs/vfs" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) +// testContext isolates the global git config in an empty home directory. +func testContext(t *testing.T) context.Context { + ctx := env.WithUserHomeDir(t.Context(), t.TempDir()) + return env.Set(ctx, "XDG_CONFIG_HOME", "") +} + func writeIndex(t *testing.T, gitDir string, entries uint32) { // Bytes after the header stand in for the entries, which are never read. content := make([]byte, indexHeaderSize+64) @@ -38,7 +47,7 @@ func TestFetchRepositorySize(t *testing.T) { // Directories in objects/pack are not counted. require.NoError(t, os.MkdirAll(filepath.Join(gitDir, "objects", "pack", "tmp"), 0o755)) - size, err := FetchRepositorySize(vfs.MustNew(root)) + size, err := FetchRepositorySize(testContext(t), vfs.MustNew(root)) require.NoError(t, err) require.NotNil(t, size.TrackedFileCount) require.NotNil(t, size.PackSizeBytes) @@ -56,7 +65,7 @@ func TestFetchRepositorySizeWorktree(t *testing.T) { writeIndex(t, filepath.Join(dir, ".git"), 99) writePack(t, filepath.Join(dir, ".git"), "pack-1.pack", 512) - size, err := FetchRepositorySize(vfs.MustNew(filepath.Join(dir, "my_worktree"))) + size, err := FetchRepositorySize(testContext(t), vfs.MustNew(filepath.Join(dir, "my_worktree"))) require.NoError(t, err) require.NotNil(t, size.TrackedFileCount) require.NotNil(t, size.PackSizeBytes) @@ -68,7 +77,7 @@ func TestFetchRepositorySizeEmptyRepository(t *testing.T) { root := t.TempDir() require.NoError(t, os.MkdirAll(filepath.Join(root, ".git"), 0o755)) - size, err := FetchRepositorySize(vfs.MustNew(root)) + size, err := FetchRepositorySize(testContext(t), vfs.MustNew(root)) require.NoError(t, err) assert.Nil(t, size.TrackedFileCount) assert.Nil(t, size.PackSizeBytes) @@ -86,7 +95,7 @@ func TestFetchRepositorySizeInvalidIndexKeepsPackSize(t *testing.T) { require.NoError(t, os.WriteFile(filepath.Join(gitDir, "index"), []byte(content), 0o644)) writePack(t, gitDir, "pack-1.pack", 100) - size, err := FetchRepositorySize(vfs.MustNew(root)) + size, err := FetchRepositorySize(testContext(t), vfs.MustNew(root)) assert.ErrorContains(t, err, name) assert.Nil(t, size.TrackedFileCount) require.NotNil(t, size.PackSizeBytes) @@ -104,25 +113,117 @@ func TestFetchRepositorySizePartialIndex(t *testing.T) { "config": "[core]\n\tsparseCheckout = true\n[index]\n\tsparse = true\n", }, "sparse index in worktree config": { - "config.worktree": "[index]\n\tsparse = yes\n", + "config": "[extensions]\n\tworktreeConfig = true\n", + "config.worktree": "[core]\n\tsparseCheckout = true\n[index]\n\tsparse = yes\n", }, } { t.Run(name, func(t *testing.T) { root := t.TempDir() gitDir := filepath.Join(root, ".git") - require.NoError(t, os.MkdirAll(gitDir, 0o755)) writeIndex(t, gitDir, 12) for file, content := range files { require.NoError(t, os.WriteFile(filepath.Join(gitDir, file), []byte(content), 0o644)) } - size, err := FetchRepositorySize(vfs.MustNew(root)) + size, err := FetchRepositorySize(testContext(t), vfs.MustNew(root)) require.NoError(t, err) assert.Nil(t, size.TrackedFileCount) }) } } +func TestFetchRepositorySizeSparseIndexInGlobalConfig(t *testing.T) { + root := t.TempDir() + gitDir := filepath.Join(root, ".git") + writeIndex(t, gitDir, 12) + require.NoError(t, os.WriteFile(filepath.Join(gitDir, "config"), []byte("[core]\n\tsparseCheckout = true\n"), 0o644)) + + home := t.TempDir() + require.NoError(t, os.WriteFile(filepath.Join(home, ".gitconfig"), []byte("[index]\n\tsparse = true\n"), 0o644)) + ctx := env.Set(env.WithUserHomeDir(t.Context(), home), "XDG_CONFIG_HOME", "") + + size, err := FetchRepositorySize(ctx, vfs.MustNew(root)) + require.NoError(t, err) + assert.Nil(t, size.TrackedFileCount) +} + +func TestFetchRepositorySizeCompleteIndex(t *testing.T) { + for name, files := range map[string]map[string]string{ + // Git writes a full index unless sparse checkout is also on. + "index.sparse without sparse checkout": { + "config": "[index]\n\tsparse = true\n", + }, + // Git reads config.worktree only with extensions.worktreeConfig. + "worktree config without the extension": { + "config.worktree": "[core]\n\tsparseCheckout = true\n[index]\n\tsparse = true\n", + }, + } { + t.Run(name, func(t *testing.T) { + root := t.TempDir() + gitDir := filepath.Join(root, ".git") + writeIndex(t, gitDir, 12) + for file, content := range files { + require.NoError(t, os.WriteFile(filepath.Join(gitDir, file), []byte(content), 0o644)) + } + + size, err := FetchRepositorySize(testContext(t), vfs.MustNew(root)) + require.NoError(t, err) + require.NotNil(t, size.TrackedFileCount) + assert.Equal(t, int64(12), *size.TrackedFileCount) + }) + } +} + +func TestFetchRepositorySizeStaleSharedIndex(t *testing.T) { + // After split index is turned off, old shared index files stay but are no + // longer touched, so they are older than the index. + root := t.TempDir() + gitDir := filepath.Join(root, ".git") + writeIndex(t, gitDir, 12) + shared := filepath.Join(gitDir, "sharedindex.0123456789abcdef0123456789abcdef01234567") + require.NoError(t, os.WriteFile(shared, nil, 0o644)) + old := time.Now().Add(-time.Hour) + require.NoError(t, os.Chtimes(shared, old, old)) + + size, err := FetchRepositorySize(testContext(t), vfs.MustNew(root)) + require.NoError(t, err) + require.NotNil(t, size.TrackedFileCount) + assert.Equal(t, int64(12), *size.TrackedFileCount) +} + +func TestFetchRepositorySizeCountsLooseObjects(t *testing.T) { + root := t.TempDir() + gitDir := filepath.Join(root, ".git") + writePack(t, gitDir, "pack-1.pack", 100) + loose := filepath.Join(gitDir, "objects", "ab") + require.NoError(t, os.MkdirAll(loose, 0o755)) + require.NoError(t, os.WriteFile(filepath.Join(loose, "cdef0123456789abcdef0123456789abcdef01"), make([]byte, 30), 0o644)) + require.NoError(t, os.WriteFile(filepath.Join(loose, "tmp_obj_abc"), make([]byte, 1000), 0o644)) + // objects/info is not an object directory. + require.NoError(t, os.MkdirAll(filepath.Join(gitDir, "objects", "info"), 0o755)) + require.NoError(t, os.WriteFile(filepath.Join(gitDir, "objects", "info", "packs"), make([]byte, 1000), 0o644)) + + size, err := FetchRepositorySize(testContext(t), vfs.MustNew(root)) + require.NoError(t, err) + require.NotNil(t, size.PackSizeBytes) + assert.Equal(t, int64(130), *size.PackSizeBytes) +} + +func TestFetchRepositorySizeAlternates(t *testing.T) { + root := t.TempDir() + gitDir := filepath.Join(root, ".git") + writeIndex(t, gitDir, 12) + writePack(t, gitDir, "pack-1.pack", 100) + require.NoError(t, os.MkdirAll(filepath.Join(gitDir, "objects", "info"), 0o755)) + require.NoError(t, os.WriteFile(filepath.Join(gitDir, "objects", "info", "alternates"), []byte("/elsewhere/.git/objects\n"), 0o644)) + + size, err := FetchRepositorySize(testContext(t), vfs.MustNew(root)) + require.NoError(t, err) + assert.Nil(t, size.PackSizeBytes) + require.NotNil(t, size.TrackedFileCount) + assert.Equal(t, int64(12), *size.TrackedFileCount) +} + func TestFetchRepositorySizeSparseCheckoutWithoutSparseIndex(t *testing.T) { // Without index.sparse the index keeps an entry per tracked file. root := t.TempDir() @@ -132,7 +233,7 @@ func TestFetchRepositorySizeSparseCheckoutWithoutSparseIndex(t *testing.T) { require.NoError(t, os.WriteFile(filepath.Join(gitDir, "info", "sparse-checkout"), []byte("/*\n"), 0o644)) require.NoError(t, os.WriteFile(filepath.Join(gitDir, "config"), []byte("[core]\n\tsparseCheckout = true\n[index]\n\tsparse = false\n"), 0o644)) - size, err := FetchRepositorySize(vfs.MustNew(root)) + size, err := FetchRepositorySize(testContext(t), vfs.MustNew(root)) require.NoError(t, err) require.NotNil(t, size.TrackedFileCount) assert.Equal(t, int64(250_000), *size.TrackedFileCount) @@ -144,7 +245,7 @@ func TestFetchRepositorySizeSkipsTemporaryPacks(t *testing.T) { writePack(t, gitDir, "pack-1.pack", 10) writePack(t, gitDir, "tmp_pack_abc123", 1000) - size, err := FetchRepositorySize(vfs.MustNew(root)) + size, err := FetchRepositorySize(testContext(t), vfs.MustNew(root)) require.NoError(t, err) require.NotNil(t, size.PackSizeBytes) assert.Equal(t, int64(10), *size.PackSizeBytes) @@ -157,7 +258,7 @@ func TestFetchRepositorySizeShallowClone(t *testing.T) { writePack(t, gitDir, "pack-1.pack", 100) require.NoError(t, os.WriteFile(filepath.Join(gitDir, "shallow"), []byte("0123456789abcdef0123456789abcdef01234567\n"), 0o644)) - size, err := FetchRepositorySize(vfs.MustNew(root)) + size, err := FetchRepositorySize(testContext(t), vfs.MustNew(root)) require.NoError(t, err) assert.Nil(t, size.PackSizeBytes) // The index still lists every tracked file. @@ -172,7 +273,7 @@ func TestFetchRepositorySizeShallowCloneWorktree(t *testing.T) { writePack(t, filepath.Join(dir, ".git"), "pack-1.pack", 100) require.NoError(t, os.WriteFile(filepath.Join(dir, ".git", "shallow"), nil, 0o644)) - size, err := FetchRepositorySize(vfs.MustNew(filepath.Join(dir, "my_worktree"))) + size, err := FetchRepositorySize(testContext(t), vfs.MustNew(filepath.Join(dir, "my_worktree"))) require.NoError(t, err) assert.Nil(t, size.PackSizeBytes) } @@ -184,7 +285,7 @@ func TestFetchRepositorySizePartialClone(t *testing.T) { writePack(t, gitDir, "pack-1.pack", 100) writePack(t, gitDir, "pack-1.promisor", 0) - size, err := FetchRepositorySize(vfs.MustNew(root)) + size, err := FetchRepositorySize(testContext(t), vfs.MustNew(root)) require.NoError(t, err) assert.Nil(t, size.PackSizeBytes) require.NotNil(t, size.TrackedFileCount) @@ -192,7 +293,7 @@ func TestFetchRepositorySizePartialClone(t *testing.T) { } func TestFetchRepositorySizeNoRepository(t *testing.T) { - size, err := FetchRepositorySize(vfs.MustNew(t.TempDir())) + size, err := FetchRepositorySize(testContext(t), vfs.MustNew(t.TempDir())) require.NoError(t, err) assert.Nil(t, size.TrackedFileCount) assert.Nil(t, size.PackSizeBytes) From d1dbceae689b26f8a33e360fcc2688c8a8269823 Mon Sep 17 00:00:00 2001 From: Anders Rex Date: Wed, 2 Dec 2026 14:43:28 +0000 Subject: [PATCH 3/4] Bound git repo size read and test it against a real repository Counts only the files the repository layout defines (pack-* files and hex named loose objects) instead of skipping a tmp_ prefix. Gives the read a 200 ms budget so a slow filesystem cannot hold up the deploy. Extends the deploy-git acceptance test with a repository of known size, as loose objects and after git gc. Co-authored-by: Isaac Signed-off-by: Anders Rex --- .../telemetry/deploy-git/databricks.yml | 5 +++ .../bundle/telemetry/deploy-git/output.txt | 16 ++++++++ acceptance/bundle/telemetry/deploy-git/script | 23 +++++++++++ .../bundle/telemetry/deploy-git/test.toml | 1 + bundle/phases/telemetry.go | 7 ++++ libs/git/size.go | 38 ++++++++++++++----- libs/git/size_test.go | 34 +++++++++++++++++ 7 files changed, 114 insertions(+), 10 deletions(-) diff --git a/acceptance/bundle/telemetry/deploy-git/databricks.yml b/acceptance/bundle/telemetry/deploy-git/databricks.yml index 576d7a9ef25..8d65b154993 100644 --- a/acceptance/bundle/telemetry/deploy-git/databricks.yml +++ b/acceptance/bundle/telemetry/deploy-git/databricks.yml @@ -1,2 +1,7 @@ bundle: name: test-bundle + +# The data directory only gives the repository a known size. +sync: + exclude: + - data diff --git a/acceptance/bundle/telemetry/deploy-git/output.txt b/acceptance/bundle/telemetry/deploy-git/output.txt index 73a8aee14a7..a2fdb14b95a 100644 --- a/acceptance/bundle/telemetry/deploy-git/output.txt +++ b/acceptance/bundle/telemetry/deploy-git/output.txt @@ -18,3 +18,19 @@ Resources: 0 created, 0 changed, 0 deleted, 0 unchanged "pack_size": "PACK_UNDER_10_MB" } } + +=== 1,202 tracked files and 12 MB of loose objects + +>>> git_repo_size +{ + "tracked_file_count": "FILES_1K_TO_5K", + "pack_size": "PACK_10_MB_TO_100_MB" +} + +=== The same repository after git gc packs the objects + +>>> git_repo_size +{ + "tracked_file_count": "FILES_1K_TO_5K", + "pack_size": "PACK_10_MB_TO_100_MB" +} diff --git a/acceptance/bundle/telemetry/deploy-git/script b/acceptance/bundle/telemetry/deploy-git/script index 52d5a995a0c..1719e01f795 100644 --- a/acceptance/bundle/telemetry/deploy-git/script +++ b/acceptance/bundle/telemetry/deploy-git/script @@ -6,3 +6,26 @@ trace $CLI bundle deploy trace cat "$OUT_REQUESTS" | jq 'select(has("path") and .path == "/telemetry-ext") | .body.protoLogs[] | fromjson | .entry.databricks_cli_log.bundle_deploy_event | {git, from_workspace_folder, in_git_repo, git_repo_size}' rm "$OUT_REQUESTS" + +# Prints git_repo_size of the last deploy. +git_repo_size() { + jq 'select(has("path") and .path == "/telemetry-ext") | .body.protoLogs[] | fromjson | .entry.databricks_cli_log.bundle_deploy_event.git_repo_size' "$OUT_REQUESTS" + rm "$OUT_REQUESTS" +} + +title "1,202 tracked files and 12 MB of loose objects" +mkdir data +for i in $(seq 1200); do echo "$i" > "data/f$i"; done +# Random bytes do not compress, so the object store grows by 12 MB. +head -c 12000000 /dev/urandom > data/blob.bin +git add data +git commit -qm 'Add data' + +$CLI bundle deploy > LOG.deploy-loose 2>&1 +trace git_repo_size + +title "The same repository after git gc packs the objects" +git gc -q > LOG.gc 2>&1 + +$CLI bundle deploy > LOG.deploy-packed 2>&1 +trace git_repo_size diff --git a/acceptance/bundle/telemetry/deploy-git/test.toml b/acceptance/bundle/telemetry/deploy-git/test.toml index 59966cb8183..0f9449d0bce 100644 --- a/acceptance/bundle/telemetry/deploy-git/test.toml +++ b/acceptance/bundle/telemetry/deploy-git/test.toml @@ -1,6 +1,7 @@ # git-repo-init creates a repo in the test directory so the deploy has git metadata. Ignore = [ '.git', + 'data', ] # The commit is different on every run. diff --git a/bundle/phases/telemetry.go b/bundle/phases/telemetry.go index cec56d4d12d..fd20649bce8 100644 --- a/bundle/phases/telemetry.go +++ b/bundle/phases/telemetry.go @@ -293,6 +293,11 @@ func packSizeBucket(size int64) protos.GitPackSizeBucket { return protos.GitPackSizeOver20GB } +// Time budget for reading the git repository size. The read takes about a +// millisecond on a local disk. The budget keeps a slow filesystem from holding +// up the deploy. +const gitRepoSizeTimeout = 200 * time.Millisecond + // bundleGitRepoSize reports the coarse size of the local git repository the // bundle is in. Only buckets are sent, exact values never leave the machine. // Nil for Databricks Git folders, whose size the workspace already knows, and @@ -301,6 +306,8 @@ func bundleGitRepoSize(ctx context.Context, b *bundle.Bundle) *protos.BundleGitR if b.InGitRepo == nil || !*b.InGitRepo || fromWorkspaceFolder(ctx, b) { return nil } + ctx, cancel := context.WithTimeout(ctx, gitRepoSizeTimeout) + defer cancel() // On error the values that could be read are still reported. size, err := git.FetchRepositorySize(ctx, b.WorktreeRoot) if err != nil { diff --git a/libs/git/size.go b/libs/git/size.go index 5d1270100ae..eb6aea6f291 100644 --- a/libs/git/size.go +++ b/libs/git/size.go @@ -29,8 +29,9 @@ type RepositorySize struct { PackSizeBytes *int64 } -// The index starts with a 12 byte header: the "DIRC" signature, a version and -// the entry count, all big-endian. +// The index starts with a 12 byte header: the "DIRC" signature, a 4 byte +// version and a 32 bit entry count. The format stores all numbers in network +// byte order, so this is the same on every platform. // See https://git-scm.com/docs/index-format var indexSignature = []byte("DIRC") @@ -40,6 +41,8 @@ const indexHeaderSize = 12 // root is root. The index lives in $GIT_DIR and objects in $GIT_COMMON_DIR, so // both are read correctly from a linked worktree. The fields are read // independently, so on error the ones that could be read are still set. +// Sizing the object store stats every loose object, so it stops when ctx is +// done. func FetchRepositorySize(ctx context.Context, root vfs.Path) (RepositorySize, error) { var size RepositorySize @@ -50,7 +53,7 @@ func FetchRepositorySize(ctx context.Context, root vfs.Path) (RepositorySize, er var countErr, packErr error size.TrackedFileCount, countErr = indexEntryCount(ctx, gitDir, gitCommonDir) - size.PackSizeBytes, packErr = objectStoreSize(gitCommonDir) + size.PackSizeBytes, packErr = objectStoreSize(ctx, gitCommonDir) return size, errors.Join(countErr, packErr) } @@ -156,7 +159,7 @@ func isTrue(value string) bool { // objectStoreSize returns nil when the local objects hold only part of the // history, so the size would understate the repository. -func objectStoreSize(gitCommonDir vfs.Path) (*int64, error) { +func objectStoreSize(ctx context.Context, gitCommonDir vfs.Path) (*int64, error) { // A shallow clone has a shallow file in $GIT_COMMON_DIR, also when read // from a linked worktree. A clone made with --reference or --shared reads // most objects from the repositories listed in objects/info/alternates. @@ -182,6 +185,9 @@ func objectStoreSize(gitCommonDir vfs.Path) (*int64, error) { if !dir.IsDir() || (dir.Name() != "pack" && !isLooseObjectDir(dir.Name())) { continue } + if err := ctx.Err(); err != nil { + return nil, err + } entries, err := gitCommonDir.ReadDir(path.Join("objects", dir.Name())) if err != nil { return nil, err @@ -193,8 +199,7 @@ func objectStoreSize(gitCommonDir vfs.Path) (*int64, error) { if strings.HasSuffix(entry.Name(), ".promisor") { return nil, nil } - // Skip files that a concurrent fetch, commit or gc is still writing. - if !entry.Type().IsRegular() || strings.HasPrefix(entry.Name(), "tmp_") { + if !entry.Type().IsRegular() || !isObjectFile(dir.Name(), entry.Name()) { continue } info, err := entry.Info() @@ -208,13 +213,26 @@ func objectStoreSize(gitCommonDir vfs.Path) (*int64, error) { } func isLooseObjectDir(name string) bool { - if len(name) != 2 { - return false + return len(name) == 2 && isHex(name) +} + +// isObjectFile reports whether name is a file that the repository layout +// defines for dir: pack-* files in objects/pack, and loose objects named by the +// rest of their hash elsewhere. Other files, such as ones a concurrent fetch or +// gc is still writing, are not counted. +// See https://git-scm.com/docs/gitrepository-layout +func isObjectFile(dir, name string) bool { + if dir == "pack" { + return strings.HasPrefix(name, "pack-") } - for _, c := range name { + return isHex(name) +} + +func isHex(s string) bool { + for _, c := range s { if !strings.ContainsRune("0123456789abcdef", c) { return false } } - return true + return s != "" } diff --git a/libs/git/size_test.go b/libs/git/size_test.go index bde8b40a4a9..1ec38016555 100644 --- a/libs/git/size_test.go +++ b/libs/git/size_test.go @@ -209,6 +209,40 @@ func TestFetchRepositorySizeCountsLooseObjects(t *testing.T) { assert.Equal(t, int64(130), *size.PackSizeBytes) } +func TestFetchRepositorySizeIgnoresUnknownFiles(t *testing.T) { + root := t.TempDir() + gitDir := filepath.Join(root, ".git") + writePack(t, gitDir, "pack-1.pack", 10) + // Only pack-* files and hex named loose objects are counted. + writePack(t, gitDir, "multi-pack-index", 1000) + writePack(t, gitDir, "notes.txt", 1000) + loose := filepath.Join(gitDir, "objects", "ab") + require.NoError(t, os.MkdirAll(loose, 0o755)) + require.NoError(t, os.WriteFile(filepath.Join(loose, "README"), make([]byte, 1000), 0o644)) + + size, err := FetchRepositorySize(testContext(t), vfs.MustNew(root)) + require.NoError(t, err) + require.NotNil(t, size.PackSizeBytes) + assert.Equal(t, int64(10), *size.PackSizeBytes) +} + +func TestFetchRepositorySizeStopsWhenContextIsDone(t *testing.T) { + root := t.TempDir() + gitDir := filepath.Join(root, ".git") + writeIndex(t, gitDir, 12) + writePack(t, gitDir, "pack-1.pack", 100) + + ctx, cancel := context.WithCancel(testContext(t)) + cancel() + + size, err := FetchRepositorySize(ctx, vfs.MustNew(root)) + require.ErrorIs(t, err, context.Canceled) + assert.Nil(t, size.PackSizeBytes) + // The index header is a single small read, so it is still reported. + require.NotNil(t, size.TrackedFileCount) + assert.Equal(t, int64(12), *size.TrackedFileCount) +} + func TestFetchRepositorySizeAlternates(t *testing.T) { root := t.TempDir() gitDir := filepath.Join(root, ".git") From 3210b35de9b201c99b2af4f91d65d7361e3f5ec4 Mon Sep 17 00:00:00 2001 From: Anders Rex Date: Thu, 3 Dec 2026 08:51:34 +0000 Subject: [PATCH 4/4] Clarify that pack_size covers the whole object store Co-authored-by: Isaac --- libs/telemetry/protos/bundle_deploy.go | 2 +- libs/telemetry/protos/enum.go | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/libs/telemetry/protos/bundle_deploy.go b/libs/telemetry/protos/bundle_deploy.go index 4a0110b7127..610675514b7 100644 --- a/libs/telemetry/protos/bundle_deploy.go +++ b/libs/telemetry/protos/bundle_deploy.go @@ -95,7 +95,7 @@ type BundleGitRepoSize struct { // Bucketed entry count from the git index header. TrackedFileCount GitTrackedFileCountBucket `json:"tracked_file_count,omitempty"` - // Bucketed total size of the files in `.git/objects/pack`. + // Bucketed total size of the git object store: pack files plus loose objects. PackSize GitPackSizeBucket `json:"pack_size,omitempty"` } diff --git a/libs/telemetry/protos/enum.go b/libs/telemetry/protos/enum.go index 3d4f0e64701..9976ab42526 100644 --- a/libs/telemetry/protos/enum.go +++ b/libs/telemetry/protos/enum.go @@ -51,7 +51,7 @@ const ( GitTrackedFileCountOver1M GitTrackedFileCountBucket = "FILES_OVER_1M" ) -// GitPackSizeBucket is a coarse bucket for the on-disk size of git pack files. +// GitPackSizeBucket is a coarse bucket for the git object store size: pack files plus loose objects. type GitPackSizeBucket string const (