:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(devex): stop hogli repacks from deleting commits in blobless clones (#99035)
Julian Bezb77566d1b730
diff --git a/docs/published/handbook/engineering/developing-locally.md b/docs/published/handbook/engineering/developing-locally.mdindex 234189fc20ed..e638dfe4257f 100644--- a/docs/published/handbook/engineering/developing-locally.md+++ b/docs/published/handbook/engineering/developing-locally.md@@ -111,6 +111,7 @@ You still get full git history for commands like `git log` and `git diff`. Blobs`hogli start` keeps a blobless clone healthy, because git does not consolidate the pack files these on-demand fetches create.It repacks in the background when they build up. Run `hogli doctor:git` to do it yourself.+If `git fetch` fails with `Could not read <sha>`, the clone is missing commits. Run `hogli doctor:git --fix` to download them again.> The `feature-flags` container relies on the presence of the GeoLite cities> database in the `/share` directory. If you haven't run `hogli start` this database may not exist.diff --git a/tools/hogli-commands/hogli_commands/doctor.py b/tools/hogli-commands/hogli_commands/doctor.pyindex 8e6fc542b28d..66927f9a697d 100644--- a/tools/hogli-commands/hogli_commands/doctor.py+++ b/tools/hogli-commands/hogli_commands/doctor.py@@ -258,15 +258,15 @@ def doctor_disk(title="🧹 Git repository (.git)",description=["Prunes stale remote branches, expires reflogs, and repacks objects.",- "Combines: git remote prune + reflog expire + gc --aggressive.",+ "Combines: git remote prune + reflog expire + repack (gc --aggressive on a full clone).","Can reclaim 25-40% of .git size (1-1.5GB in large repos).",],estimate=_estimate_git,cleanup=_cleanup_git,- confirmation_prompt="Run Git cleanup (prune + gc)?",+ confirmation_prompt="Run Git cleanup (prune + repack)?",include_in_total=False,skip_if_empty=False,- dry_run_message="Would run: git remote prune + reflog expire (30 days) + gc --aggressive",+ dry_run_message="Would run: git remote prune + reflog expire (30 days) + repack (gc --aggressive on a full clone)",),]@@ -573,6 +573,38 @@ def _estimate_pnpm_store(repo_root: Path) -> CleanupEstimate:return CleanupEstimate(total_size=0.0, items=[], details=details)+# `git repack -a -d` can delete commits in a partial clone. It walks refs with+# --exclude-promisor-objects, and that walk stops at each commit in a promisor pack.+# The repack then deletes the commits behind that point that are in an ordinary pack.+# Git expects to fetch them again, but `git fetch` does not, so it fails with+# "Could not read <sha>". Git's incremental-repack maintenance task moves fetched+# commits into ordinary packs. --keep-unreachable writes those commits into the new+# pack instead of deleting them.+_GIT_REPACK_ARGS = ["repack", "-a", "-d", "-l", "--keep-unreachable", "--threads=0"]+++def _promisor_remote(repo_root: Path) -> str | None:+ """The remote a partial clone fetches missing objects from, or None for a full clone.++ Git defines a partial clone by this remote. The `.promisor` scan in `_git_health`+ stops at its pack cap, so it can miss the marker.+ """+ config = _run_output(+ ["git", "-C", str(repo_root), "config", "--get-regexp", r"^remote\..*\.promisor$|^extensions\.partialclone$"]+ )+ for line in (config or "").splitlines():+ key, _, value = line.partition(" ")+ if key == "extensions.partialclone":+ return value+ if value != "false":+ return key.removeprefix("remote.").removesuffix(".promisor")+ return None+++def _is_partial_clone(repo_root: Path) -> bool:+ return _promisor_remote(repo_root) is not None++def _estimate_git(repo_root: Path) -> CleanupEstimate:"""Check .git directory size and estimate reclaimable space."""@@ -606,11 +638,12 @@ def _estimate_git(repo_root: Path) -> CleanupEstimate:len(list((git_dir / "objects" / "pack").glob("*.pack"))) if (git_dir / "objects" / "pack").exists() else 0)+ repack = "repack" if _is_partial_clone(repo_root) else "gc --aggressive"details = [f" Current .git size: {_format_size(git_size)}",f" Pack files: {pack_count}"," Estimated reclaimable: ~30% (25-40% typical)",- " Operations: remote prune + reflog expire + gc --aggressive",+ f" Operations: remote prune + reflog expire + {repack}",]return CleanupEstimate(total_size=0.0, items=[], details=details)@@ -650,7 +683,7 @@ def _cleanup_items(estimate: CleanupEstimate, _: Path) -> CleanupStats:def _cleanup_git(_: CleanupEstimate, repo_root: Path) -> CleanupStats:- """Execute git cleanup: prune remotes, expire reflogs, and run gc."""+ """Execute git cleanup: prune remotes, expire reflogs, and repack."""click.echo()success = True@@ -667,11 +700,16 @@ def _cleanup_git(_: CleanupEstimate, repo_root: Path) -> CleanupStats:if result.returncode != 0:success = False- # Step 3: Run gc --aggressive (this can take 1-2 minutes)- # Git will show its own progress output- # Note: omit --prune=now to use git's safe 2-week default- click.echo(" Running git gc --aggressive (may take 1-2 minutes)...")- result = subprocess.run(["git", "gc", "--aggressive"], cwd=repo_root, check=False)+ # Step 3: Repack+ if _is_partial_clone(repo_root):+ # Some git versions, 2.50 among them, make `git gc` delete the same commits as+ # `repack -a -d` when their pack is older than two weeks. See _GIT_REPACK_ARGS.+ click.echo(" Running git repack (may take a few minutes)...")+ result = subprocess.run(["git", *_GIT_REPACK_ARGS], cwd=repo_root, check=False)+ else:+ # Note: omit --prune=now to use git's safe 2-week default+ click.echo(" Running git gc --aggressive (may take 1-2 minutes)...")+ result = subprocess.run(["git", "gc", "--aggressive"], cwd=repo_root, check=False)if result.returncode != 0:success = False@@ -2262,7 +2300,8 @@ def _check_zombies(repo_root: Path) -> CheckResult:# A blob:none clone writes a new promisor pack on each on-demand blob fetch.# Nothing consolidates them, because `gc.autoPackLimit` does not count promisor-# packs and the `incremental-repack` maintenance task does not merge them.+# packs and a partial clone runs without the `incremental-repack` maintenance task+# (see `_incremental_repack_enabled`).# Pack lookup cost grows with the pack count, which makes `git fetch` and# `git status` slow.#@@ -2667,14 +2706,26 @@ def _git_maintenance_registered(main_worktree: Path) -> bool:return str(main_worktree) in registered or str(main_worktree.resolve()) in registered+_INCREMENTAL_REPACK_KEY = "maintenance.incremental-repack.enabled"+++def _incremental_repack_enabled(main_worktree: Path) -> bool:+ """Whether git maintenance can run the task that moves fetched commits out of promisor packs.++ `_GIT_REPACK_ARGS` explains how that loses commits.+ """+ cmd = ["git", "-C", str(main_worktree), "config", "--type=bool", "--get", _INCREMENTAL_REPACK_KEY]+ return _run_output(cmd) != "false"++def _spawn_background_repack(main_worktree: Path, common_dir: Path) -> None:- """Start `git repack -ad` detached, at background priority.+ """Start the repack detached, at background priority.A repack takes minutes, and `hogli start` must not wait for it. Git never doesthis itself on a partial clone, for the reason given at`_GIT_PACK_WARNING_THRESHOLD`."""- cmd = ["git", "-C", str(main_worktree), "repack", "-adl", "--threads=0"]+ cmd = ["git", "-C", str(main_worktree), *_GIT_REPACK_ARGS]# taskpolicy -b puts the repack in the background QoS band, which throttles its# IO as well as its CPU. Without it the repack competes with the dev stack.if shutil.which("taskpolicy"):@@ -2698,14 +2749,16 @@ def _run_git(main_worktree: Path, args: list[str], label: str) -> bool:def _write_commit_graph(main_worktree: Path) -> bool:- """Backfill unreadable commits, then write the graph.+ """Fetch missing commits again, then write the graph.`commit-graph write --reachable` stops at the first commit it cannot read, and apartial clone does not lazy-fetch during that walk, so one absent commit leavesthe repo with no commit-graph at all."""+ # An existing commit-graph can still list a deleted commit, and rev-list then+ # reads the commit from the graph and does not report it.missing = subprocess.run(- ["git", "-C", str(main_worktree), "rev-list", "--all", "--missing=print"],+ ["git", "-C", str(main_worktree), "-c", "core.commitGraph=false", "rev-list", "--all", "--missing=print"],capture_output=True,text=True,env={**os.environ, "GIT_NO_LAZY_FETCH": "1"},@@ -2714,8 +2767,23 @@ def _write_commit_graph(main_worktree: Path) -> bool:oids = [line[1:] for line in missing.stdout.splitlines() if line.startswith("?")]if oids:click.echo(f" fetching {len(oids)} missing commits...")- for oid in oids:- subprocess.run(["git", "-C", str(main_worktree), "cat-file", "-e", oid], check=False, capture_output=True)+ # A normal fetch does not send an ancestor of a commit the repo already has.+ # A lazy fetch can refuse a commit that the commit-graph lists, and a full clone+ # has no lazy fetch. --refetch skips negotiation and gets all of them in one pack.+ # After --refetch, git forces an auto gc and incremental-repack, which are the+ # repacks that lose commits.+ refetch = [+ "-c",+ "core.commitGraph=false",+ "fetch",+ "--refetch",+ "--no-auto-maintenance",+ "--no-write-fetch-head",+ _promisor_remote(main_worktree) or "origin",+ *oids,+ ]+ if not _run_git(main_worktree, refetch, "refetch of missing commits"):+ return Falseclick.echo(" writing commit-graph...")return _run_git(main_worktree, ["commit-graph", "write", "--reachable", "--split", "--no-progress"], "commit-graph write"@@ -2771,6 +2839,17 @@ def doctor_git(fix: bool) -> None:else:click.echo("Could not register scheduled git maintenance. Run `git maintenance start` yourself.")+ if _is_partial_clone(main_worktree) and _incremental_repack_enabled(main_worktree):+ if _run_ok(["git", "-C", str(main_worktree), "config", _INCREMENTAL_REPACK_KEY, "false"]):+ click.secho("Turned off git's incremental-repack maintenance task.", fg="yellow")+ click.echo("On a partial clone it can lead to lost commits and a failing `git fetch`.")+ else:+ click.echo(+ "Could not turn off git's incremental-repack maintenance task. "+ f"Run `git config {_INCREMENTAL_REPACK_KEY} false` yourself."+ )+ acted = True+count = f"{health.pack_count}+" if health.packs_capped else str(health.pack_count)if fix:@@ -2780,7 +2859,7 @@ def doctor_git(fix: bool) -> None:ok = Trueif packs_high:click.echo(f"{count} pack files. Repacking in the foreground, which takes minutes.")- ok = _run_git(main_worktree, ["repack", "-adl", "--threads=0"], "repack")+ ok = _run_git(main_worktree, _GIT_REPACK_ARGS, "repack")ok = ok and _write_commit_graph(main_worktree)if ok and health.pack_count:ok = _run_git(main_worktree, ["multi-pack-index", "write", "--no-progress"], "multi-pack-index write")diff --git a/tools/hogli-commands/hogli_commands/tests/test_doctor.py b/tools/hogli-commands/hogli_commands/tests/test_doctor.pyindex feefa7ba343f..b57c54d9978c 100644--- a/tools/hogli-commands/hogli_commands/tests/test_doctor.py+++ b/tools/hogli-commands/hogli_commands/tests/test_doctor.py@@ -17,8 +17,11 @@ from hogli_commands.doctor import (_GIT_HOUSEKEEPING_PGREP_PATTERN,FLOX_LOG_MAX_AGE_DAYS,FLOX_LOG_MAX_TOTAL_BYTES,+ CleanupEstimate,+ GitHealth,_binary_arches,_check_git_health,+ _cleanup_git,_collect_import_targets,_config_procs,_confirm_stack_teardown,@@ -1299,7 +1302,10 @@ def test_doctor_git_spawns_the_repack_detached_instead_of_blocking()ran: list[list[str]] = []spawned: list[list[str]] = []- monkeypatch.setattr("hogli_commands.doctor.subprocess.run", lambda cmd, **kw: ran.append(cmd))+ monkeypatch.setattr(+ "hogli_commands.doctor.subprocess.run",+ lambda cmd, **kw: ran.append(cmd) or SimpleNamespace(returncode=0, stdout="", stderr=""),+ )monkeypatch.setattr("hogli_commands.doctor.subprocess.Popen",lambda cmd, **kw: spawned.append(cmd) or SimpleNamespace(pid=1),@@ -1442,6 +1448,172 @@ def test_doctor_git_fix_reports_a_failed_step_instead_of_success(assert "Done." not in result.output+def _git(cwd: Path, *args: str) -> str:+ return subprocess.run(["git", *args], cwd=cwd, check=True, capture_output=True, text=True).stdout.strip()+++def _commit_is_readable(repo: Path, oid: str) -> bool:+ # Without GIT_NO_LAZY_FETCH, git fetches a missing commit back during the check.+ result = subprocess.run(+ ["git", "cat-file", "-e", oid], cwd=repo, env={**os.environ, "GIT_NO_LAZY_FETCH": "1"}, check=False+ )+ return result.returncode == 0+++def _push_commit(seed: Path, name: str) -> str:+ (seed / name).write_text(name)+ _git(seed, "add", name)+ _git(seed, "commit", "-qm", name)+ _git(seed, "push", "-q", "origin", "HEAD:main")+ return _git(seed, "rev-parse", "HEAD")+++def isolated_git_config(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ global_config = tmp_path / "gitconfig"+ global_config.write_text("[user]\n\tname = test\n\temail = [email protected]\n")+ monkeypatch.setenv("GIT_CONFIG_GLOBAL", str(global_config))+ monkeypatch.setenv("GIT_CONFIG_NOSYSTEM", "1")+++def git_origin(tmp_path: Path, isolated_git_config: None) -> tuple[Path, Path]:+ remote = tmp_path / "origin.git"+ _git(tmp_path, "init", "-q", "--bare", "-b", "main", str(remote))+ _git(remote, "config", "uploadpack.allowFilter", "true")+ _git(remote, "config", "uploadpack.allowAnySHA1InWant", "true")+ seed = tmp_path / "seed"+ _git(tmp_path, "init", "-q", "-b", "main", str(seed))+ _git(seed, "remote", "add", "origin", remote.as_uri())+ return remote, seed+++def _clone_with_commits_behind_a_promisor_commit(tmp_path: Path, remote: Path, seed: Path) -> tuple[Path, list[str]]:+ older = [_push_commit(seed, name) for name in ("a", "b", "c")]+ clone = tmp_path / "clone"+ _git(tmp_path, "clone", "-q", "--filter=blob:none", remote.as_uri(), str(clone))+ pack_dir = clone / ".git" / "objects" / "pack"+ packs_before_child = list(pack_dir.glob("*.pack"))+ _push_commit(seed, "d")+ _git(clone, "fetch", "-q", "origin")+ # incremental-repack moves older fetched objects into a pack without a .promisor+ # file and leaves the newest fetch as a promisor pack. Removing the marker from+ # the older packs gives the same state.+ for pack in packs_before_child:+ pack.with_suffix(".promisor").unlink(missing_ok=True)+ _git(clone, "multi-pack-index", "write")+ # Only the promisor commit at origin/main reaches the older commits now.+ _git(clone, "checkout", "-q", "--detach", "origin/main")+ _git(clone, "branch", "-q", "-D", "main")+ _git(clone, "reflog", "expire", "--expire=now", "--all")+ return clone, older+++def _mock_git_health(monkeypatch: pytest.MonkeyPatch, clone: Path, *, packs_high: bool, has_promisor: bool) -> None:+ monkeypatch.setattr("hogli_commands.doctor.REPO_ROOT", clone)+ monkeypatch.setattr("hogli_commands.doctor._git_housekeeping_running", lambda *a: False)+ monkeypatch.setattr("hogli_commands.doctor._git_maintenance_registered", lambda _: True)+ monkeypatch.setattr(+ "hogli_commands.doctor._git_health",+ lambda common, pack_cap: GitHealth(+ pack_count=pack_cap + 1 if packs_high else 0,+ packs_capped=False,+ has_promisor=has_promisor,+ stale_lock=None,+ missing_commit_graph=False,+ ),+ )+++def test_doctor_git_fix_keeps_fetched_commits_that_lost_promisor_status(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path, git_origin: tuple[Path, Path]+) -> None:+ # `repack -a -d` deleted these commits, and `git fetch` then failed with+ # "Could not read <sha>".+ remote, seed = git_origin+ clone, older = _clone_with_commits_behind_a_promisor_commit(tmp_path, remote, seed)+ _mock_git_health(monkeypatch, clone, packs_high=True, has_promisor=True)+ # --fix fetches missing commits back. An unreachable origin stops that, so the+ # result shows what the repack alone did.+ _git(clone, "remote", "set-url", "origin", str(tmp_path / "unreachable.git"))++ result = CliRunner().invoke(doctor_git, ["--fix"])++ _git(clone, "remote", "set-url", "origin", remote.as_uri())+ assert result.exit_code == 0, result.output+ assert [oid for oid in older if not _commit_is_readable(clone, oid)] == []+ _push_commit(seed, "e")+ _git(clone, "fetch", "-q", "origin")+++def test_cleanup_git_does_not_run_gc_on_a_partial_clone(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:+ # On git 2.50, `git gc` deletes fetched commits that lost promisor status when their+ # pack is older than two weeks. Git's behavior needs a real repo and an old pack, so+ # the doctor:git test above covers the repack itself.+ ran: list[list[str]] = []++ def fake_run(cmd, **kwargs):+ ran.append(cmd)+ stdout = "remote.origin.promisor true\n" if "--get-regexp" in cmd else ""+ return SimpleNamespace(returncode=0, stdout=stdout, stderr="")++ monkeypatch.setattr("hogli_commands.doctor.subprocess.run", fake_run)++ _cleanup_git(CleanupEstimate(total_size=0.0), tmp_path)++ assert not any("gc" in cmd for cmd in ran)+ assert any("--keep-unreachable" in cmd for cmd in ran)+++ "clone_args",+ [[], ["--filter=blob:none", "--origin", "upstream"]],+ ids=["full-clone", "blobless-clone-with-renamed-remote"],+)+def test_doctor_git_fix_fetches_commits_that_the_commit_graph_still_lists(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path, git_origin: tuple[Path, Path], clone_args: list[str]+) -> None:+ # The stale graph hid the deleted commit from the missing-commit walk, and the+ # per-commit lazy fetch that followed does not exist in a full clone.+ remote, seed = git_origin+ lost = _push_commit(seed, "a")+ _push_commit(seed, "b")+ clone = tmp_path / "clone"+ _git(tmp_path, "clone", "-q", *clone_args, remote.as_uri(), str(clone))+ _git(clone, "commit-graph", "write", "--reachable")+ # Unpack every object into a loose file, so that one commit can be deleted.+ pack_dir = clone / ".git" / "objects" / "pack"+ for pack in list(pack_dir.glob("*.pack")):+ objects = pack.read_bytes()+ for path in pack_dir.glob(f"{pack.stem}.*"):+ path.unlink()+ subprocess.run(["git", "unpack-objects", "-q"], cwd=clone, input=objects, check=True)+ (clone / ".git" / "objects" / lost[:2] / lost[2:]).unlink()+ _mock_git_health(monkeypatch, clone, packs_high=False, has_promisor=False)++ result = CliRunner().invoke(doctor_git, ["--fix"])++ assert result.exit_code == 0, result.output+ assert _commit_is_readable(clone, lost)+++def test_doctor_git_turns_off_incremental_repack_on_a_partial_clone(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path, isolated_git_config: None+) -> None:+ # incremental-repack moves fetched commits out of promisor packs, and a later gc or+ # repack can then delete them. The capped pack scan can miss every .promisor file,+ # so the promisor remote in the config must decide, whatever the remote's name.+ repo = tmp_path / "repo"+ _git(tmp_path, "init", "-q", str(repo))+ _git(repo, "config", "remote.upstream.promisor", "true")+ _mock_git_health(monkeypatch, repo, packs_high=False, has_promisor=False)++ result = CliRunner().invoke(doctor_git, [])++ assert result.exit_code == 0, result.output+ assert _git(repo, "config", "--type=bool", "maintenance.incremental-repack.enabled") == "false"++@pytest.mark.parametrize("stale_lock, packs_over, missing_graph, expected",[