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 259b256c782..a2fdb14b95a 100644 --- a/acceptance/bundle/telemetry/deploy-git/output.txt +++ b/acceptance/bundle/telemetry/deploy-git/output.txt @@ -12,5 +12,25 @@ 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" + } +} + +=== 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 bbcb7701461..1719e01f795 100644 --- a/acceptance/bundle/telemetry/deploy-git/script +++ b/acceptance/bundle/telemetry/deploy-git/script @@ -3,6 +3,29 @@ 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" + +# 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 7f4ebfff312..fd20649bce8 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,91 @@ 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 +} + +// 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 +// 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 + } + 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 { + 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 +560,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_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/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..eb6aea6f291 --- /dev/null +++ b/libs/git/size.go @@ -0,0 +1,238 @@ +package git + +import ( + "bytes" + "context" + "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 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 +} + +// 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") + +const indexHeaderSize = 12 + +// FetchRepositorySize reads the size proxies of the repository whose worktree +// 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 + + gitDir, gitCommonDir, err := resolveGitDirs(root) + if err != nil { + return size, err + } + + var countErr, packErr error + size.TrackedFileCount, countErr = indexEntryCount(ctx, gitDir, gitCommonDir) + size.PackSizeBytes, packErr = objectStoreSize(ctx, gitCommonDir) + return size, errors.Join(countErr, packErr) +} + +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 + } + if err != nil { + return nil, err + } + 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) + } + 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 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.") { + continue + } + info, err := entry.Info() + if err != nil { + return false, err + } + if !info.ModTime().Before(index.ModTime()) { + return true, nil + } + } + return false, 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(gitCommonDir, "config"); err != nil { + return false, err + } + // `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. +// 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 +} + +// objectStoreSize returns nil when the local objects hold only part of the +// history, so the size would understate the repository. +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. + 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 + } + } + + dirs, err := gitCommonDir.ReadDir("objects") + if errors.Is(err, fs.ErrNotExist) { + return nil, nil + } + if err != nil { + return nil, err + } + + var total int64 + 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 + } + if err := ctx.Err(); err != nil { + return nil, err + } + entries, err := gitCommonDir.ReadDir(path.Join("objects", dir.Name())) + if err != nil { + return nil, err + } + 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 + } + if !entry.Type().IsRegular() || !isObjectFile(dir.Name(), entry.Name()) { + continue + } + info, err := entry.Info() + if err != nil { + return nil, err + } + total += info.Size() + } + } + return &total, nil +} + +func isLooseObjectDir(name string) bool { + 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-") + } + return isHex(name) +} + +func isHex(s string) bool { + for _, c := range s { + if !strings.ContainsRune("0123456789abcdef", c) { + return false + } + } + return s != "" +} diff --git a/libs/git/size_test.go b/libs/git/size_test.go new file mode 100644 index 00000000000..1ec38016555 --- /dev/null +++ b/libs/git/size_test.go @@ -0,0 +1,334 @@ +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) + 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(testContext(t), 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(testContext(t), 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(testContext(t), 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(testContext(t), 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": "[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") + 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) + 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 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") + 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() + 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(testContext(t), 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(testContext(t), 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(testContext(t), 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(testContext(t), 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(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 TestFetchRepositorySizeNoRepository(t *testing.T) { + size, err := FetchRepositorySize(testContext(t), 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..610675514b7 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 git object store: pack files plus loose objects. + 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..9976ab42526 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 git object store size: pack files plus loose objects. +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" +)