The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(update): stop folding lazy-fetch packs during hermes update
teknium11fd75357e92d
diff --git a/hermes_cli/gitlock.py b/hermes_cli/gitlock.pyindex e0b11e02549..4d4b28cf98b 100644--- a/hermes_cli/gitlock.py+++ b/hermes_cli/gitlock.py@@ -24,8 +24,6 @@ logger = logging.getLogger(__name__)# Folding ~100 small packs takes seconds, but the checkouts this exists for (thousands of packs,# tens of GiB) need a full repack. A killed fold restarts from scratch on every update and never# converges, so the bound is generous and a timeout is reported, not swallowed.-LAZY_FETCH_GC_TIMEOUT_SECONDS = 20 * 60-_GC_AUTO_PACK_LIMIT_DEFAULT = 50# Files younger than this are presumed live (a fetch may be in flight) and are never removed. Lock# files live for seconds and a healthy fetch completes in minutes; 10 minutes is abandoned.@@ -144,7 +142,7 @@ def mark_unmarked_packs_promisor(repo_root: Path) -> int:# 2.50.1, 2.53.0 and 2.55.0 alike). So a promisor checkout never writes the graph. Automatic# maintenance itself stays on: on git <= 2.53 its post-fetch ``gc --auto`` is what keeps the# lazy-fetch packs folded between updates. ``gc.auto`` stays at its default for the same reason-# (``gc.auto=0`` turns consolidate_lazy_fetch_packs into a no-op).+# (``gc.auto=0`` turns that fold into a no-op)._TREE0_MAINTENANCE_OFF = (("maintenance.commit-graph.enabled", "false"),("gc.writeCommitGraph", "false"),@@ -610,49 +608,13 @@ def fetch_with_partial_clone_recovery(runner: Callable[..., subprocess.Completedreturn runner(git_cmd, fetch_args)-def _gc_auto_pack_limit(repo_root: Path) -> int:- lines = _git_stdout_lines(repo_root, ["config", "--int", "--get", "gc.autoPackLimit"])- return int(lines[0]) if lines else _GC_AUTO_PACK_LIMIT_DEFAULT---def consolidate_lazy_fetch_packs(repo_root: Path, *,- on_fold_start: Optional[Callable[[int], None]] = None) -> Optional[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, keeping the ``.promisor`` marker. The gc must not- write a commit-graph (see ``_TREE0_MAINTENANCE_OFF``): over a Bloom-carrying graph that is a- lazy fetch per unseen commit, so the same call that folds 100 packs would leave 30 new ones.- Runs under ``bounded_probe_run`` because ``subprocess.run(timeout=)`` kills only ``git gc``- and leaves its ``pack-objects`` child running. ``on_fold_start(pack_count)`` fires just before- a fold gc will actually do (pack count past the limit), so the caller can say why the update- went quiet. Best-effort like every helper here: never raises, returns 0 for a non-partial- checkout or when nothing folded, and ``None`` when the fold hit its time limit.+def settle_partial_clone_maintenance(repo_root: Path) -> None:+ """Persist the commit-graph-off keys on a partial clone; a full clone keeps stock maintenance.++ Runs on every update so checkouts that predate the installer change converge. Never raises."""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- disable_tree0_auto_maintenance(repo_root)- before = len(list(_pack_dir(repo_root).glob("pack-*.pack")))- limit = _gc_auto_pack_limit(repo_root)- if on_fold_start is not None and 0 < limit < before:- on_fold_start(before)- if bounded_probe_run(- ["git", "-c", "gc.autoDetach=false", "-c", "gc.writeCommitGraph=false", "gc", "--auto"],- timeout=LAZY_FETCH_GC_TIMEOUT_SECONDS, cwd=str(repo_root),- env={**noninteractive_git_env(), **NO_LAZY_FETCH_ENV},- ) is None:- logger.warning("Folding %d lazy-fetch pack(s) in %s timed out after %ds",- before, repo_root, LAZY_FETCH_GC_TIMEOUT_SECONDS)- return None- 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)+ if _partial_clone_filter(repo_root, creationflags=windows_hide_flags()) is not None:+ disable_tree0_auto_maintenance(repo_root)except Exception:- logger.debug("lazy-fetch pack consolidation failed for %s", repo_root, exc_info=True)- return 0+ logger.debug("partial-clone maintenance settings failed for %s", repo_root, exc_info=True)diff --git a/hermes_cli/update_cmd.py b/hermes_cli/update_cmd.pyindex 031571ae629..5eaf0a2b7f7 100644--- a/hermes_cli/update_cmd.py+++ b/hermes_cli/update_cmd.py@@ -1541,9 +1541,9 @@ 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.- _check.fold_lazy_fetch_packs(_m().PROJECT_ROOT)+ # A partial clone must never write a commit-graph (#127711); keep its keys in place.+ from hermes_cli.gitlock import settle_partial_clone_maintenance+ settle_partial_clone_maintenance(_m().PROJECT_ROOT)# 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_graftsdiff --git a/hermes_cli/update_cmd_check.py b/hermes_cli/update_cmd_check.pyindex 6f6fd910002..10f96c4261c 100644--- a/hermes_cli/update_cmd_check.py+++ b/hermes_cli/update_cmd_check.py@@ -36,31 +36,16 @@ def clear_git_debris(root: Path) -> None:A crashed fetch can leave ``.git/shallow.lock`` (or another lock) behind, and every laterfetch 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).+ A partial clone also gets its commit-graph-off keys re-applied (#127711)."""- from hermes_cli.gitlock import clear_stale_git_locks, clear_stale_tmp_packs+ from hermes_cli.gitlock import clear_stale_git_locks, clear_stale_tmp_packs, settle_partial_clone_maintenancefor lock_path in clear_stale_git_locks(root):print(f" (removed stale git lock: {lock_path})")swept = clear_stale_tmp_packs(root)if swept:print(f" (removed {len(swept)} aborted-fetch pack temp file(s))")- fold_lazy_fetch_packs(root)---def fold_lazy_fetch_packs(root: Path) -> None:- """Fold a partial clone's lazy-fetch packs (#129712), announcing a slow fold and a timed-out one."""- from hermes_cli.gitlock import LAZY_FETCH_GC_TIMEOUT_SECONDS, consolidate_lazy_fetch_packs-- folded = consolidate_lazy_fetch_packs(root, on_fold_start=lambda count: print(- f" Folding {count} lazy-fetch packs into one (one-time; can take several minutes)...", flush=True))- if folded is None:- print(f" ⚠ Folding lazy-fetch packs did not finish within {LAZY_FETCH_GC_TIMEOUT_SECONDS // 60} min."- " With Hermes closed, run:")- print(f' git -C "{root}" -c gc.writeCommitGraph=false gc --auto')- elif folded:- print(f" (folded {folded} lazy-fetch pack(s) into one)")+ settle_partial_clone_maintenance(root)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.pyindex 871934e9e4e..265a286e09f 100644--- a/tests/hermes_cli/test_gitlock.py+++ b/tests/hermes_cli/test_gitlock.py@@ -203,7 +203,7 @@ def test_recovery_marks_unmarked_packs_and_retries_the_same_fetch(crash_stderr,# `git gc --auto` (git's own gc.autoPackLimit decides when it is worth it). Real git against a# local blobless clone: these pin how the pieces interact, not their command lines.-from hermes_cli.gitlock import consolidate_lazy_fetch_packs, disable_tree0_auto_maintenance # noqa: E402+from hermes_cli.gitlock import settle_partial_clone_maintenance, disable_tree0_auto_maintenance # noqa: E402_GIT_ENV = {**os.environ, "GIT_CONFIG_GLOBAL": os.devnull, "GIT_CONFIG_NOSYSTEM": "1"}@@ -245,24 +245,8 @@ def partial_clone(tmp_path: Path) -> Path:return clone-def test_consolidate_folds_lazy_fetch_packs_that_the_maintenance_keys_leave_foldable(partial_clone: Path) -> None:- before = _packs(partial_clone)- assert len(before) > 2, "each on-demand fetch should have stranded its own packfile"- # gc.auto=0 here (an earlier cut of the maintenance keys) would turn the fold into a no-op.- disable_tree0_auto_maintenance(partial_clone)-- folded = consolidate_lazy_fetch_packs(partial_clone)-- remaining = _packs(partial_clone)- assert folded == len(before) - len(remaining) > 0- assert all(pack.with_suffix(".promisor").exists() for pack in remaining)- blob = _run_git("cat-file", "-p", _run_git("rev-parse", "HEAD:d1/f.txt", cwd=partial_clone), cwd=partial_clone,- env={**_GIT_ENV, "GIT_NO_LAZY_FETCH": "1"})- assert blob == "v1", "the folded repository must still read its objects without the promisor"---def test_fold_does_not_lazy_fetch_the_trees_of_commits_a_bloom_graph_has_not_seen(tmp_path: Path) -> None:- """The same gc that folds the packs, left to write a commit-graph, adds one pack per unseen commit."""+def test_gits_own_gc_does_not_lazy_fetch_the_trees_of_commits_a_bloom_graph_has_not_seen(tmp_path: Path) -> None:+ """A gc that folds the packs, left to write a commit-graph, adds one pack per unseen commit."""seed, up, clone = _blobless_clone(tmp_path, 12)full = tmp_path / "full"_run_git("clone", "-q", up.as_uri(), str(full), cwd=tmp_path)@@ -280,7 +264,8 @@ def test_fold_does_not_lazy_fetch_the_trees_of_commits_a_bloom_graph_has_not_see_run_git("config", "gc.autoPackLimit", "3", cwd=clone)assert len(_packs(clone)) > 3- consolidate_lazy_fetch_packs(clone)+ settle_partial_clone_maintenance(clone)+ _run_git("-c", "gc.autoDetach=false", "gc", "--auto", cwd=clone)assert len(_packs(clone)) == 1@@ -318,14 +303,15 @@ def test_an_operators_own_maintenance_auto_false_is_never_erased(repo: Path) ->assert _run_git("config", "--local", "--get", "maintenance.auto", cwd=repo) == "false"-def test_a_checkout_the_first_cut_configured_folds_on_update(partial_clone: Path) -> None:+def test_a_checkout_the_first_cut_configured_folds_again(partial_clone: Path) -> None:"""73c17151f61 persisted ``gc.auto=0`` (beside ``maintenance.auto=false`` and``fetch.writeCommitGraph=false``); left in place, ``gc --auto`` is a no-op and no fold ever runs."""for key, value in (("gc.auto", "0"), ("fetch.writeCommitGraph", "false")):_run_git("config", key, value, cwd=partial_clone)assert len(_packs(partial_clone)) > 2- consolidate_lazy_fetch_packs(partial_clone)+ settle_partial_clone_maintenance(partial_clone)+ _run_git("-c", "gc.autoDetach=false", "gc", "--auto", cwd=partial_clone)assert len(_packs(partial_clone)) == 1left = subprocess.run(["git", "config", "--local", "--get-regexp", r"^(maintenance\.auto|gc\.auto)$"],@@ -334,24 +320,7 @@ def test_a_checkout_the_first_cut_configured_folds_on_update(partial_clone: Pathdef test_non_partial_checkout_is_left_alone(repo: Path) -> None:- assert consolidate_lazy_fetch_packs(repo) == 0+ settle_partial_clone_maintenance(repo)keys = subprocess.run(["git", "config", "--local", "--get-regexp", "maintenance|writecommitgraph"], cwd=repo,capture_output=True, text=True).stdoutassert keys == "", "a full clone keeps git's stock maintenance"---def test_update_debris_cleanup_folds_and_reports_a_fold_that_runs_out_of_time(- partial_clone: Path, monkeypatch: pytest.MonkeyPatch, capfd: pytest.CaptureFixture[str]) -> None:- """A killed fold restarts from scratch every update, so it must say so instead of returning 0."""- from hermes_cli import gitlock- from hermes_cli.update_cmd_check import clear_git_debris-- before = len(_packs(partial_clone))- with monkeypatch.context() as patched:- patched.setattr(gitlock, "LAZY_FETCH_GC_TIMEOUT_SECONDS", 0) # the real gc, killed by the real bound- clear_git_debris(partial_clone)- out = capfd.readouterr().out- assert f"Folding {before} lazy-fetch packs" in out and "gc.writeCommitGraph=false gc --auto" in out-- clear_git_debris(partial_clone)- assert len(_packs(partial_clone)) < beforediff --git a/website/docs/getting-started/updating.md b/website/docs/getting-started/updating.mdindex f5ffa0fc241..ad46ff5771d 100644--- a/website/docs/getting-started/updating.md+++ b/website/docs/getting-started/updating.md@@ -170,14 +170,12 @@ git -C $repo rev-list --objects --missing=error --all | Out-Null; $LASTEXITCODEThe installer's checkout is a partial clone: git downloads trees and blobs on demand, and eachon-demand download is written as its own small pack. `hermes update` and `hermes update --check`-fold them back together with `git gc --auto` (git's own `gc.autoPackLimit`, 50 by default), so a-healthy checkout pays a no-op. They also set `maintenance.commit-graph.enabled`,-`gc.writeCommitGraph` and `fetch.writeCommitGraph` to `false` in that checkout, because a-commit-graph write over commits the graph has not seen yet downloads every one of their trees. Leave those settings alone, and leave-`gc.auto` at its default: `gc.auto=0` stops the fold. The first fold on a checkout that has-piled up thousands of packs is a full repack and can take several minutes; the update says so-before it starts, and if the fold runs past 20 minutes it stops and prints the command below.-To fold by hand (with Hermes closed):+set `maintenance.commit-graph.enabled`, `gc.writeCommitGraph` and `fetch.writeCommitGraph` to+`false` in that checkout, because a commit-graph write over commits the graph has not seen yet+downloads every one of their trees. Leave those settings alone, and leave `gc.auto` at its+default so git's own automatic gc can still fold packs. The update does not fold them itself:+on a large checkout that fold is a full repack that can run for many minutes. To fold by hand+(with Hermes closed):```bashgit -C "$repo" -c gc.writeCommitGraph=false gc --auto