Skip to content

The agent that grows with you

fix(update): fold lazy-fetch packfiles so a partial clone's .git stops growing

liuhao1024add654131ff6
diff --git a/hermes_cli/gitlock.py b/hermes_cli/gitlock.py
index 815d23cacc0..4d4fe8816a9 100644
--- a/hermes_cli/gitlock.py
+++ b/hermes_cli/gitlock.py
@@ -525,3 +525,37 @@ def fetch_with_partial_clone_recovery(runner: Callable[..., subprocess.Completed
mark_unmarked_packs_promisor(repo_root)
logger.info("pack-objects crash on a partial clone; retrying the fetch")
return runner(git_cmd, fetch_args)
+
+
+def consolidate_lazy_fetch_packs(repo_root: Path) -> int:
+ """Fold a partial clone's lazy-fetch packfiles back into one; returns how many packs went away.
+
+ Every on-demand fetch a promisor remote serves writes its own small packfile, and nothing in
+ the update workflow ever consolidates them — a ``tree:0`` installer checkout lazy-fetches
+ blob by blob, so ``.git`` grows without bound (2,475 packs / 39 GiB observed for a ~1 GiB
+ repo, #129712). ``git gc --auto`` already knows when this is worth doing: it exits in
+ milliseconds while the small-pack count sits under ``gc.autoPackLimit`` (default 50) and
+ repacks them into one pack once past it. The gc does not write a commit-graph: on git ≤2.50
+ a freshly written one makes the next lazy fetch abort with "in the commit graph file but
+ not in the object database". gc's repack merges the marked packs into a fresh one; on gits
+ that do not carry the ``.promisor`` marker over, an unmarked pack is the git 2.53+ fetch
+ crash (#124272), so the merged pack is re-marked afterwards. Best-effort like every helper
+ here: never raises, returns 0 for a non-partial checkout or when nothing folded.
+ """
+ try:
+ if _partial_clone_filter(repo_root, creationflags=windows_hide_flags()) is None:
+ return 0 # only a promisor remote's on-demand fetches write these packs
+ before = len(list(_pack_dir(repo_root).glob("pack-*.pack")))
+ subprocess.run(
+ ["git", "-c", "gc.autoDetach=false", "-c", "gc.writeCommitGraph=false", "gc", "--auto"],
+ cwd=str(repo_root), capture_output=True, timeout=300,
+ creationflags=windows_hide_flags(),
+ )
+ mark_unmarked_packs_promisor(repo_root)
+ folded = before - len(list(_pack_dir(repo_root).glob("pack-*.pack")))
+ if folded > 0:
+ logger.info("Folded %d lazy-fetch pack(s) in %s", folded, repo_root)
+ return max(folded, 0)
+ except Exception:
+ logger.debug("lazy-fetch pack consolidation failed for %s", repo_root, exc_info=True)
+ return 0
diff --git a/hermes_cli/update_cmd.py b/hermes_cli/update_cmd.py
index 41a05002b66..8cae4d42163 100644
--- a/hermes_cli/update_cmd.py
+++ b/hermes_cli/update_cmd.py
@@ -1541,6 +1541,12 @@ def _cmd_update_impl(args, gateway_mode: bool):
swept = clear_stale_tmp_packs(_m().PROJECT_ROOT)
if swept:
print(" (removed %d aborted-fetch pack temp file(s))" % len(swept))
+ # A partial clone's on-demand fetches strand one small packfile each and never
+ # consolidate on their own (#129712); fold them before this run's fetch adds more.
+ from hermes_cli.gitlock import consolidate_lazy_fetch_packs
+ folded = consolidate_lazy_fetch_packs(_m().PROJECT_ROOT)
+ if folded:
+ print(f" (folded {folded} lazy-fetch pack(s) into one)")
# Shallow installer checkouts collect one `.git/shallow` graft per past depth-1 fetch
# (#105951); stale grafts break merge-base and push this run into the divergence path.
from hermes_cli.gitlock import repair_broken_shallow_boundaries, prune_stale_shallow_grafts
diff --git a/hermes_cli/update_cmd_check.py b/hermes_cli/update_cmd_check.py
index 8ded5b4cd1d..f84c074dace 100644
--- a/hermes_cli/update_cmd_check.py
+++ b/hermes_cli/update_cmd_check.py
@@ -36,6 +36,8 @@ def clear_git_debris(root: Path) -> None:
A crashed fetch can leave ``.git/shallow.lock`` (or another lock) behind, and every later
fetch then fails with "File exists". Aborted fetches on flaky lines also strand
``tmp_pack_*`` debris: unchecked it reached 6 GB and corrupted the pack dir (#93732).
+ A partial clone's on-demand fetches also strand one small packfile each — fold those
+ back in (#129712).
"""
from hermes_cli.gitlock import clear_stale_git_locks, clear_stale_tmp_packs
@@ -44,6 +46,11 @@ def clear_git_debris(root: Path) -> None:
swept = clear_stale_tmp_packs(root)
if swept:
print(f" (removed {len(swept)} aborted-fetch pack temp file(s))")
+ from hermes_cli.gitlock import consolidate_lazy_fetch_packs
+
+ folded = consolidate_lazy_fetch_packs(root)
+ if folded:
+ print(f" (folded {folded} lazy-fetch pack(s) into one)")
def channel_compare_branch(selected_channel: str, git_cmd: list[str], root: Path) -> str | None:
diff --git a/tests/hermes_cli/test_gitlock.py b/tests/hermes_cli/test_gitlock.py
index 328f26fa6e2..69b473cfc60 100644
--- a/tests/hermes_cli/test_gitlock.py
+++ b/tests/hermes_cli/test_gitlock.py
@@ -193,3 +193,106 @@ def test_recovery_marks_unmarked_packs_and_retries_the_same_fetch(crash_stderr,
assert calls == [(["git"], ["fetch", "origin", "main"])] * 2
assert (pack_dir / "pack-local.promisor").exists()
assert result.returncode == 0
+
+
+# A partial clone's on-demand fetches strand one small packfile each and nothing consolidates
+# them (#129712). The fold rides `git gc --auto`: git's own small-pack threshold
+# (gc.autoPackLimit, default 50 in the wild) decides when repacking is worth it, so a healthy
+# checkout pays a no-op probe and a lazy-fetch-saturated one converges.
+
+from hermes_cli.gitlock import consolidate_lazy_fetch_packs # noqa: E402
+
+
+def partial_clone(tmp_path: Path) -> Path:
+ """A ``tree:0`` clone of a local upstream: every on-demand blob fetch writes a packfile.
+
+ ``core.commitGraph false`` keeps git ≤2.50's lazy fetches working: a clone-time (or
+ fetch-maintenance) commit-graph makes the third one abort with "attempting to fetch <sha>,
+ which is in the commit graph file but not in the object database"."""
+ seed, up, clone = tmp_path / "seed", tmp_path / "up.git", tmp_path / "clone"
+ subprocess.run(["git", "init", "-q", "-b", "main", str(seed)], check=True)
+ for name, text in (("f0.txt", "zero\n"), ("f1.txt", "one\n"), ("f2.txt", "two\n")):
+ (seed / name).write_text(text, encoding="utf-8")
+ subprocess.run(["git", "add", str(name)], cwd=seed, check=True)
+ subprocess.run(
+ ["git", "-c", "user.email=t@t", "-c", "user.name=t", "commit", "-qm", f"add {name}"],
+ cwd=seed, check=True)
+ subprocess.run(["git", "clone", "-q", "--bare", str(seed), str(up)], check=True)
+ subprocess.run(["git", "config", "uploadpack.allowFilter", "true"], cwd=up, check=True)
+ subprocess.run(["git", "config", "uploadpack.allowAnySHA1InWant", "true"], cwd=up, check=True)
+ subprocess.run(["git", "clone", "-q", "--filter=tree:0", "--no-checkout", up.as_uri(), str(clone)],
+ check=True)
+ subprocess.run(["git", "config", "core.commitGraph", "false"], cwd=clone, check=True)
+ return clone
+
+
+def _packs(repo: Path) -> list:
+ return list((repo / ".git" / "objects" / "pack").glob("pack-*.pack"))
+
+
+def _lazy_fetch_blobs(clone: Path, *names: str) -> None:
+ for name in names:
+ sha = subprocess.run(["git", "rev-parse", f"HEAD:{name}"], cwd=clone, check=True,
+ capture_output=True, text=True).stdout.strip()
+ subprocess.run(["git", "cat-file", "-p", sha], cwd=clone, check=True, capture_output=True)
+
+
+def test_consolidate_folds_lazy_fetch_packs(partial_clone: Path) -> None:
+ _lazy_fetch_blobs(partial_clone, "f0.txt", "f1.txt", "f2.txt")
+ before = _packs(partial_clone)
+ assert len(before) > 2, "each on-demand fetch should have stranded its own packfile"
+ # The wild default threshold (gc.autoPackLimit 50) cannot be crossed in a fixture; drop it
+ # to 1 so any second small pack is already worth folding — same decision, smaller scale.
+ subprocess.run(["git", "config", "gc.autoPackLimit", "1"], cwd=partial_clone, check=True)
+
+ folded = consolidate_lazy_fetch_packs(partial_clone)
+
+ remaining = _packs(partial_clone)
+ assert folded == len(before) - len(remaining) > 0
+ # The folded pack must still carry the .promisor marker, or git 2.53+ fetches crash (#124272).
+ assert all(pack.with_suffix(".promisor").exists() for pack in remaining)
+ sha = subprocess.run(["git", "rev-parse", "HEAD:f1.txt"], cwd=partial_clone, check=True,
+ capture_output=True, text=True).stdout.strip()
+ blob = subprocess.run(["git", "cat-file", "-p", sha], cwd=partial_clone, check=True,
+ capture_output=True, text=True)
+ assert blob.stdout == "one\n", "the folded repository must still read its objects"
+
+
+def test_consolidate_leaves_a_converged_checkout_alone(partial_clone: Path) -> None:
+ """Under git's small-pack threshold the fold is a no-op: one pack, nothing folded."""
+ assert len(_packs(partial_clone)) == 1
+
+ assert consolidate_lazy_fetch_packs(partial_clone) == 0
+ assert len(_packs(partial_clone)) == 1
+
+
+def test_consolidate_skips_non_partial_checkouts(repo: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ """Lazy-fetch packs only exist on a promisor remote — a plain checkout never spawns the gc."""
+ import hermes_cli.gitlock as gitlock
+
+ spawns = []
+ real_run = subprocess.run
+
+ def _spy(*args, **kwargs):
+ if "gc" in args[0]:
+ spawns.append(args[0])
+ return real_run(*args, **kwargs)
+
+ monkeypatch.setattr(gitlock.subprocess, "run", _spy)
+ assert consolidate_lazy_fetch_packs(repo) == 0
+ assert not spawns
+
+
+def test_update_check_debris_cleanup_folds_lazy_fetch_packs(
+ partial_clone: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ """``hermes update --check`` is the pass that runs on its own (CLI banner prefetch), so its
+ debris cleanup must be the folding point."""
+ import hermes_cli.gitlock as gitlock
+ import hermes_cli.update_cmd_check as check
+
+ seen = {}
+ monkeypatch.setattr(gitlock, "consolidate_lazy_fetch_packs",
+ lambda root: seen.setdefault("root", root) or 0)
+ check.clear_git_debris(partial_clone)
+ assert seen.get("root") == partial_clone