| 1 | #!/usr/bin/env python3 |
| 2 | """Report where Rust build output lives and how much of it nothing claims. |
| 3 | |
| 4 | Read-only by design. This prints an inventory and a reclaim candidate list; |
| 5 | it never deletes, moves, or writes anything. Deleting hundreds of gigabytes |
| 6 | is a human decision, and the classification below is the evidence for it. |
| 7 | |
| 8 | Why this exists: agents build far more often than people do, and each |
| 9 | worktree keeps its own build output. `scripts/dev-cache.sh` already isolates |
| 10 | per-workspace build dirs so parallel agents do not share one Cargo lock, but |
| 11 | nothing ever collects those directories when a worktree goes away. |
| 12 | |
| 13 | Three places accumulate output, and they are easy to confuse: |
| 14 | |
| 15 | * `<worktree>/target` — the ordinary Cargo target dir, one per checkout. |
| 16 | * the isolated build cache — `dev-cache.sh` mode `isolated-build-dir`, keyed |
| 17 | by Cargo's `{workspace-path-hash}`, which |
| 18 | expands to a TWO-level `XX/YYYYYYYYYYYYYY` path. |
| 19 | Counting the first level alone undercounts |
| 20 | roots and makes every name look unmatched. |
| 21 | * `<repo>/target` — the main checkout's own, usually the largest |
| 22 | single object and easily forgotten. |
| 23 | |
| 24 | Worktree classification is NOT reimplemented here: `scripts/workspace-status.sh` |
| 25 | already owns which worktrees exist, which are merged, and which are dirty. |
| 26 | Run that for the checkout side of the picture. |
| 27 | |
| 28 | scripts/measure-build-cache.py |
| 29 | scripts/measure-build-cache.py --json |
| 30 | """ |
| 31 | |
| 32 | from __future__ import annotations |
| 33 | |
| 34 | import argparse |
| 35 | import json |
| 36 | import os |
| 37 | import pathlib |
| 38 | import subprocess |
| 39 | import sys |
| 40 | |
| 41 | ROOT = pathlib.Path(__file__).resolve().parents[1] |
| 42 | |
| 43 | # The signature every Cargo target dir carries. Used to identify a build root |
| 44 | # rather than guessing from the directory name, which is a hash. |
| 45 | CACHEDIR_SIGNATURE = "Signature: 8a477f597d28d172789f06886806bc55" |
| 46 | |
| 47 | |
| 48 | def disk_usage_bytes(path: pathlib.Path) -> int: |
| 49 | """Apparent size via `du -sk`, which is what the operator sees.""" |
| 50 | try: |
| 51 | out = subprocess.run( |
| 52 | ["du", "-sk", str(path)], |
| 53 | capture_output=True, |
| 54 | text=True, |
| 55 | check=True, |
| 56 | ).stdout |
| 57 | except (subprocess.CalledProcessError, FileNotFoundError): |
| 58 | return 0 |
| 59 | try: |
| 60 | return int(out.split("\t", 1)[0]) * 1024 |
| 61 | except (ValueError, IndexError): |
| 62 | return 0 |
| 63 | |
| 64 | |
| 65 | def gib(n: int) -> float: |
| 66 | return n / (1024**3) |
| 67 | |
| 68 | |
| 69 | def cache_root() -> pathlib.Path | None: |
| 70 | """The isolated build-dir root that `dev-cache.sh` would use. |
| 71 | |
| 72 | Asked of the script itself rather than re-derived, so this cannot drift |
| 73 | from the thing that actually creates the directories. |
| 74 | """ |
| 75 | script = ROOT / "scripts" / "dev-cache.sh" |
| 76 | if not script.exists(): |
| 77 | return None |
| 78 | try: |
| 79 | out = subprocess.run( |
| 80 | ["sh", "-c", f'. "{script}" && codewhale_dev_cache_apply && ' |
| 81 | 'printf "%s" "${CARGO_BUILD_BUILD_DIR:-}"'], |
| 82 | capture_output=True, |
| 83 | text=True, |
| 84 | timeout=60, |
| 85 | ).stdout.strip() |
| 86 | except (subprocess.SubprocessError, OSError): |
| 87 | return None |
| 88 | if not out: |
| 89 | return None |
| 90 | # The value carries Cargo's `{workspace-path-hash}` placeholder; the root |
| 91 | # is everything above it. |
| 92 | marker = "{workspace-path-hash}" |
| 93 | base = out.split(marker, 1)[0] if marker in out else out |
| 94 | path = pathlib.Path(base.rstrip("/")) |
| 95 | return path if path.is_dir() else None |
| 96 | |
| 97 | |
| 98 | def build_roots(base: pathlib.Path) -> list[pathlib.Path]: |
| 99 | """Every Cargo build root under `base`, found by its CACHEDIR.TAG. |
| 100 | |
| 101 | Depth is not assumed: Cargo's hash expands two levels, and a future |
| 102 | layout change should not silently return nothing. |
| 103 | """ |
| 104 | roots: list[pathlib.Path] = [] |
| 105 | for dirpath, dirnames, filenames in os.walk(base): |
| 106 | if "CACHEDIR.TAG" in filenames: |
| 107 | tag = pathlib.Path(dirpath) / "CACHEDIR.TAG" |
| 108 | try: |
| 109 | first = tag.read_text(errors="replace").splitlines()[:1] |
| 110 | except OSError: |
| 111 | first = [] |
| 112 | if first and first[0].startswith(CACHEDIR_SIGNATURE): |
| 113 | roots.append(pathlib.Path(dirpath)) |
| 114 | dirnames.clear() # never descend into a build root |
| 115 | return roots |
| 116 | |
| 117 | |
| 118 | def live_worktrees(repo: pathlib.Path) -> list[pathlib.Path]: |
| 119 | try: |
| 120 | out = subprocess.run( |
| 121 | ["git", "-C", str(repo), "worktree", "list", "--porcelain"], |
| 122 | capture_output=True, |
| 123 | text=True, |
| 124 | check=True, |
| 125 | ).stdout |
| 126 | except (subprocess.CalledProcessError, FileNotFoundError): |
| 127 | return [] |
| 128 | return [ |
| 129 | pathlib.Path(line.split(" ", 1)[1].strip()) |
| 130 | for line in out.splitlines() |
| 131 | if line.startswith("worktree ") |
| 132 | ] |
| 133 | |
| 134 | |
| 135 | def main() -> int: |
| 136 | parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) |
| 137 | parser.add_argument("--repo", type=pathlib.Path, default=ROOT) |
| 138 | parser.add_argument("--json", action="store_true", help="machine-readable output") |
| 139 | args = parser.parse_args() |
| 140 | |
| 141 | worktrees = live_worktrees(args.repo) |
| 142 | checkout_targets = [] |
| 143 | for wt in worktrees: |
| 144 | target = wt / "target" |
| 145 | if target.is_dir(): |
| 146 | checkout_targets.append((wt, disk_usage_bytes(target))) |
| 147 | checkout_targets.sort(key=lambda row: row[1], reverse=True) |
| 148 | |
| 149 | base = cache_root() |
| 150 | roots = build_roots(base) if base else [] |
| 151 | cache_entries = sorted( |
| 152 | ((r, disk_usage_bytes(r)) for r in roots), |
| 153 | key=lambda row: row[1], |
| 154 | reverse=True, |
| 155 | ) |
| 156 | |
| 157 | checkout_total = sum(size for _, size in checkout_targets) |
| 158 | cache_total = sum(size for _, size in cache_entries) |
| 159 | |
| 160 | report = { |
| 161 | "checkout_targets": [ |
| 162 | {"path": str(p), "bytes": b} for p, b in checkout_targets |
| 163 | ], |
| 164 | "checkout_total_bytes": checkout_total, |
| 165 | "cache_root": str(base) if base else None, |
| 166 | "cache_build_roots": len(cache_entries), |
| 167 | "cache_total_bytes": cache_total, |
| 168 | "grand_total_bytes": checkout_total + cache_total, |
| 169 | "live_worktrees": len(worktrees), |
| 170 | } |
| 171 | |
| 172 | if args.json: |
| 173 | json.dump(report, sys.stdout, indent=2) |
| 174 | sys.stdout.write("\n") |
| 175 | return 0 |
| 176 | |
| 177 | print("Rust build output") |
| 178 | print("=================") |
| 179 | print() |
| 180 | print(f"Live worktrees (git): {len(worktrees)}") |
| 181 | print() |
| 182 | print(f"Per-checkout target dirs — {gib(checkout_total):.0f} GiB") |
| 183 | for path, size in checkout_targets[:12]: |
| 184 | print(f" {gib(size):8.1f} GiB {path.name}/target") |
| 185 | if len(checkout_targets) > 12: |
| 186 | print(f" … {len(checkout_targets) - 12} more") |
| 187 | print() |
| 188 | if base is None: |
| 189 | print("Isolated build cache: not configured (dev-cache.sh reported no build dir)") |
| 190 | else: |
| 191 | print(f"Isolated build cache — {gib(cache_total):.0f} GiB " |
| 192 | f"across {len(cache_entries)} build roots") |
| 193 | print(f" root: {base}") |
| 194 | for path, size in cache_entries[:12]: |
| 195 | print(f" {gib(size):8.1f} GiB {path.relative_to(base)}") |
| 196 | if len(cache_entries) > 12: |
| 197 | print(f" … {len(cache_entries) - 12} more") |
| 198 | print() |
| 199 | print(f"Total: {gib(checkout_total + cache_total):.0f} GiB") |
| 200 | print() |
| 201 | print("Nothing was deleted. A build root here is not proof of garbage: the") |
| 202 | print("cache is keyed by Cargo's workspace-path hash, and only a build run") |
| 203 | print("through scripts/dev-cargo.sh from that exact path can claim one.") |
| 204 | print("Run scripts/workspace-status.sh for which worktrees are merged or") |
| 205 | print("dirty before retiring anything.") |
| 206 | return 0 |
| 207 | |
| 208 | |
| 209 | if __name__ == "__main__": |
| 210 | raise SystemExit(main()) |
| 211 |