The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(update): pack tidy erases only provably redundant packs
Teknium2fa8090568cf
diff --git a/hermes_cli/git_pack_tidy.py b/hermes_cli/git_pack_tidy.pyindex b613ab1ffea..3e2996244d2 100644--- a/hermes_cli/git_pack_tidy.py+++ b/hermes_cli/git_pack_tidy.py@@ -1,32 +1,33 @@-"""Progressive, time-boxed cleanup of a partial clone's on-demand packfiles (#129712).+"""Progressive, time-boxed cleanup of a partial clone's promisor packfiles (#129712).-A partial clone (the installer's ``--filter=tree:0`` checkout) downloads trees and blobs when git-first needs them, and every such download lands as its own small packfile that nothing removes:-``.git`` reached 39 GiB on a ~1 GiB repository. A full ``git gc`` over that is all-or-nothing and-on a big checkout runs for tens of minutes, so ``hermes update`` instead spends at most-``TIDY_BUDGET_SECONDS`` per run and every unit of work it finishes is kept:+A partial clone downloads objects when git first needs them, and git asks for them without telling+the server what it already has, so the same trees (and, for history downloads, commits) land again+and again, each download as its own packfile that nothing removes: ``.git`` reached 39 GiB on a+~1 GiB repository. A full ``git gc`` over that is all-or-nothing and on a big checkout runs for tens+of minutes, so ``hermes update`` instead spends at most ``TIDY_BUDGET_SECONDS`` per run and every+unit of work it finishes is kept:-1. Erase on-demand packs that hold no commits. Their objects are copies of what the promisor- remote serves, so deleting them frees the disk and git fetches anything it needs again. A pack- holding commits is kept, because a ref may point into it.+1. Erase promisor packs whose every object is also in another promisor pack. Nothing is lost, and+ nothing depends on the remote still serving it: the rule is proven against the local packs alone.2. While more than ``PACK_COUNT_TARGET`` promisor packs remain, merge the smallest few into one- with ``git pack-objects --stdin-packs`` (cost proportional to those packs, no reachability walk).+ with ``git pack-objects --stdin-packs``; the merged pack holds each object once.-Each erased pack and each merge is atomic, so an update that runs out of budget leaves the rest for-the next one.+Each erase and each merge is atomic for git (a pack exists for git only while both its ``.idx`` and+``.pack`` do), so an update that runs out of budget, fails or is killed leaves the rest for the next."""from __future__ import annotationsimport jsonimport logging+import mmapimport osimport shutilimport structimport timefrom dataclasses import dataclassfrom pathlib import Path-from typing import Dict, List+from typing import Dict, List, Optionalfrom hermes_cli._subprocess_compat import (NO_LAZY_FETCH_ENV,@@ -39,16 +40,22 @@ logger = logging.getLogger(__name__)TIDY_BUDGET_SECONDS = 60PACK_COUNT_TARGET = 50-# A pack this young may still be in use by the git that just fetched it.+# A pack this young may still be in use by the git that just fetched it; index-pack also writes a+# new pack's .promisor/.keep before its .pack, so a young marker without a payload may be a live fetch._MIN_PACK_AGE_SECONDS = 60 * 60_MERGE_BATCH_BYTES = 256 * 1024 * 1024-# Kept in .git/: per-pack "holds commits" verdicts (pack names are content hashes, so a verdict never-# goes stale) and the merge batch size, halved after a merge that ran out of time. Remembering both-# is what guarantees progress: no update repeats work an earlier one could not finish.+# Kept in .git/: packs proven to hold an object no other pack has (valid until a new pack appears,+# since removing packs never adds copies) and the merge batch size, halved after a merge that ran out+# of time. Remembering both is what guarantees progress: no update repeats work an earlier one finished._STATE_FILE = "hermes-pack-tidy.json"+# Two tidies at once could each erase a pack because the other still has its copies.+_LOCK_FILE = "hermes-pack-tidy.lock"# Payload first: git loads a pack only when both .idx and .pack exist, so once .pack is gone the pack is# gone for git, and a failure on .pack itself (a reader still maps it on Windows) changes nothing._PACK_SUFFIXES = (".pack", ".idx", ".rev", ".bitmap", ".mtimes", ".promisor", ".keep")+_IDX_V2 = b"\xfftOc\x00\x00\x00\x02"+_FANOUT = 8+_NAMES = _FANOUT + 256 * 4@dataclass@@ -60,40 +67,66 @@ class TidyResult:out_of_time: bool = False+class _Index:+ """A version-2 SHA-1 pack index (what a GitHub clone writes), searched in place."""++ def __init__(self, idx: Path) -> None:+ with open(idx, "rb") as fh:+ self._map = mmap.mmap(fh.fileno(), 0, access=mmap.ACCESS_READ)+ if self._map[:8] != _IDX_V2:+ self.close()+ raise ValueError(f"{idx.name}: not a v2 SHA-1 pack index")+ self.count = struct.unpack_from(">I", self._map, _FANOUT + 255 * 4)[0]++ def oids(self) -> List[bytes]:+ return [self._map[_NAMES + i * 20: _NAMES + i * 20 + 20] for i in range(self.count)]++ def __contains__(self, oid: bytes) -> bool:+ lo = struct.unpack_from(">I", self._map, _FANOUT + (oid[0] - 1) * 4)[0] if oid[0] else 0+ hi = struct.unpack_from(">I", self._map, _FANOUT + oid[0] * 4)[0]+ while lo < hi:+ mid = (lo + hi) // 2+ name = self._map[_NAMES + mid * 20: _NAMES + mid * 20 + 20]+ if name == oid:+ return True+ if name < oid:+ lo = mid + 1+ else:+ hi = mid+ return False++ def close(self) -> None:+ self._map.close() # Windows refuses to unlink a mapped file++def _git_env() -> Dict[str, str]:return {**noninteractive_git_env(), **NO_LAZY_FETCH_ENV}-def _oids_in_pack_order(idx: Path) -> List[str]:- """Object ids of a version-2 SHA-1 pack index (every pack a clone of GitHub writes), in the order- they sit in the pack. git writes commits first, so a pack that holds any shows one up front."""- data = idx.read_bytes()- if data[:8] != b"\xfftOc\x00\x00\x00\x02":- raise ValueError(f"{idx.name}: not a v2 pack index")- count = struct.unpack(">I", data[8 + 255 * 4: 8 + 256 * 4])[0]- names = 8 + 256 * 4- offsets = struct.unpack(f">{count}I", data[names + count * 24: names + count * 28]) # after names + CRCs- order = sorted(range(count), key=lambda i: offsets[i]) # MSB-set (past 2 GiB) entries sort last- return [data[names + i * 20: names + (i + 1) * 20].hex() for i in order]---def _holds_commits(repo_root: Path, pack: Path, timeout: float) -> bool:- """Whether the pack holds a commit. A pack git cannot classify in time counts as holding one:- keeping a pack only costs disk, erasing one a ref points into costs history."""- oids = _oids_in_pack_order(pack.with_suffix(".idx"))- deadline = time.monotonic() + timeout- for chunk in (oids[:256], oids[256:]):- left = deadline - time.monotonic()- if not chunk:- continue- result = bounded_probe_run(- ["git", "cat-file", "--batch-check=%(objecttype)"], timeout=max(left, 0.1), cwd=str(repo_root),- env=_git_env(), input="\n".join(chunk) + "\n")- if left <= 0 or result is None or result.returncode != 0:- return True- if "commit" in result.stdout.split():- return True- return False+def _promisor_packs(pack_dir: Path) -> List[Path]:+ return [p for p in pack_dir.glob("pack-*.pack")+ if p.with_suffix(".promisor").exists() and p.with_suffix(".idx").exists()]+++def _pinned(pack: Path, cutoff: float) -> bool:+ """Whether a ``.keep`` pins the pack. fetch-pack and index-pack write ``<cmd> <pid> on <host>`` and+ delete it once the fetch has updated its refs, so an old one of theirs belongs to a fetch that was+ killed; it pins nothing, and git's own repack never touches the pack while it exists."""+ keep = pack.with_suffix(".keep")+ try:+ return not (keep.read_text(encoding="utf-8-sig", errors="replace").startswith(("fetch-pack ", "index-pack "))+ and keep.stat().st_mtime < cutoff)+ except FileNotFoundError:+ return False+ except OSError:+ return True+++def _drop_midx(pack_dir: Path) -> None:+ """A multi-pack-index names the packs it covers; dropping it before any pack goes means no crash+ can leave one naming a deleted pack. git rebuilds it on its own maintenance."""+ for midx in pack_dir.glob("multi-pack-index*"):+ midx.unlink(missing_ok=True)def _remove_pack(pack: Path) -> int:@@ -101,6 +134,7 @@ def _remove_pack(pack: Path) -> int:Raises on the first part that will not go. Leftovers after the payload are invisible to git and:func:`_sweep_remnants` retries them on a later run."""+ _drop_midx(pack.parent)freed = 0for suffix in _PACK_SUFFIXES:part = pack.with_suffix(suffix)@@ -117,7 +151,7 @@ def _remove_pack(pack: Path) -> int:def _sweep_remnants(pack_dir: Path) -> None:"""Finish deletions an earlier run could not complete: pack files whose payload is already gone."""- cutoff = time.time() - _MIN_PACK_AGE_SECONDS # index-pack writes .promisor/.keep before its .pack+ cutoff = time.time() - _MIN_PACK_AGE_SECONDSfor part in pack_dir.glob("pack-*.*"):try:if part.suffix in _PACK_SUFFIXES[1:] and not part.with_suffix(".pack").exists() \@@ -130,59 +164,92 @@ def _sweep_remnants(pack_dir: Path) -> None:def _load_state(pack_dir: Path) -> dict:try:state = json.loads((pack_dir.parent.parent / _STATE_FILE).read_text(encoding="utf-8-sig"))- return {"commits": dict(state.get("commits", {})),- "merge_bytes": int(state.get("merge_bytes", _MERGE_BATCH_BYTES))}+ kept, seen = set(state.get("kept", [])), set(state.get("seen", []))+ merge_bytes = int(state.get("merge_bytes", _MERGE_BATCH_BYTES))except (OSError, ValueError, TypeError, AttributeError):- return {"commits": {}, "merge_bytes": _MERGE_BATCH_BYTES}+ kept, seen, merge_bytes = set(), set(), _MERGE_BATCH_BYTES+ if {p.stem for p in pack_dir.glob("pack-*.pack")} - seen:+ kept = set() # a new pack may hold the other copy of what a kept pack holds+ return {"kept": kept, "merge_bytes": merge_bytes}def _save_state(pack_dir: Path, state: dict) -> None:- live = {p.stem for p in pack_dir.glob("pack-*.pack")}- state = {**state, "commits": {k: v for k, v in state["commits"].items() if k in live}}+ live = sorted(p.stem for p in pack_dir.glob("pack-*.pack"))+ data = {"kept": sorted(state["kept"] & set(live)), "seen": live, "merge_bytes": state["merge_bytes"]}try:- (pack_dir.parent.parent / _STATE_FILE).write_text(json.dumps(state), encoding="utf-8")+ (pack_dir.parent.parent / _STATE_FILE).write_text(json.dumps(data), encoding="utf-8")except OSError:logger.debug("could not record pack tidy state in %s", pack_dir, exc_info=True)-def _erase_on_demand_packs(repo_root: Path, pack_dir: Path, deadline: float, result: TidyResult,- verdicts: Dict[str, bool]) -> None:+def _is_redundant(oids: List[bytes], others: List[_Index], deadline: float) -> Optional[bool]:+ """Whether every oid is in one of ``others``; None when the deadline passed first."""+ hit = 0+ for n, oid in enumerate(oids):+ if n % 1024 == 0 and time.monotonic() > deadline:+ return None+ if oid in others[hit]:+ continue+ for j, other in enumerate(others): # objects cluster: try the pack that had the last one first+ if j != hit and oid in other:+ hit = j+ break+ else:+ return False+ return True+++def _erase_redundant_packs(pack_dir: Path, deadline: float, result: TidyResult, state: dict) -> None:cutoff = time.time() - _MIN_PACK_AGE_SECONDS- candidates = []- for marker in pack_dir.glob("pack-*.promisor"):- pack = marker.with_suffix(".pack")+ sizes: Dict[Path, int] = {}+ candidates: List[Path] = []+ for pack in _promisor_packs(pack_dir):try:- # An on-demand fetch writes an empty marker; a ref fetch lists the refs it fetched.- if marker.stat().st_size == 0 and pack.stat().st_mtime < cutoff and not pack.with_suffix(".keep").exists():- candidates.append((pack.stat().st_mtime, pack))+ st = pack.stat()except OSError:continue- for _mtime, pack in sorted(candidates):- left = deadline - time.monotonic()- if left <= 0:- result.out_of_time = True- return- if pack.stem not in verdicts:+ sizes[pack] = st.st_size+ if pack.stem not in state["kept"] and st.st_mtime < cutoff and not _pinned(pack, cutoff):+ candidates.append(pack)+ if not candidates:+ return+ indexes: Dict[str, _Index] = {}+ try:+ for pack in sizes:try:- verdicts[pack.stem] = _holds_commits(repo_root, pack, left)+ indexes[pack.stem] = _Index(pack.with_suffix(".idx"))except (OSError, ValueError):- verdicts[pack.stem] = True- if verdicts[pack.stem]:- continue- try:- result.freed_bytes += _remove_pack(pack)- result.erased += 1- except OSError as exc:- logger.warning("Could not erase on-demand pack %s (a later update retries): %s", pack.name, exc)+ state["kept"].add(pack.stem) # unreadable: never a candidate, never counted as a copy+ by_size = sorted(sizes, key=lambda p: sizes[p], reverse=True) # big packs hold most copies+ for pack in sorted(candidates, key=lambda p: sizes[p]): # small first: cheapest to prove, likeliest copies+ if pack.stem not in indexes:+ continue+ others = [indexes[p.stem] for p in by_size if p.stem != pack.stem and p.stem in indexes]+ verdict = _is_redundant(indexes[pack.stem].oids(), others, deadline) if others else False+ if verdict is None:+ result.out_of_time = True+ return+ if not verdict:+ state["kept"].add(pack.stem)+ continue+ indexes.pop(pack.stem).close()+ try:+ result.freed_bytes += _remove_pack(pack)+ result.erased += 1+ except OSError as exc:+ logger.warning("Could not erase redundant pack %s (a later update retries): %s", pack.name, exc)+ finally:+ for index in indexes.values():+ index.close()def _merge_smallest_packs(repo_root: Path, pack_dir: Path, deadline: float, result: TidyResult,state: dict) -> None:"""Merge the smallest promisor packs, a batch at a time, until the count is under target."""staging = pack_dir.parent.parent / "hermes-tidy-staging" # outside objects/: git counts strays there as garbage+ cutoff = time.time() - _MIN_PACK_AGE_SECONDSwhile True:- packs = sorted((p.stat().st_size, p) for p in pack_dir.glob("pack-*.pack")- if p.with_suffix(".promisor").exists() and not p.with_suffix(".keep").exists())+ packs = sorted((p.stat().st_size, p) for p in _promisor_packs(pack_dir) if not _pinned(p, cutoff))if len(packs) <= PACK_COUNT_TARGET:returnbatch, total = [], 0@@ -198,24 +265,29 @@ def _merge_smallest_packs(repo_root: Path, pack_dir: Path, deadline: float, resushutil.rmtree(staging, ignore_errors=True)staging.mkdir()try:+ # packSizeLimit=0 whatever the user's config says: inputs retire only after everything+ # they held is published, and that is one output pack.done = bounded_probe_run(- ["git", "pack-objects", "-q", "--stdin-packs", str(staging / "pack")],+ ["git", "-c", "pack.packSizeLimit=0", "pack-objects", "-q", "--stdin-packs", str(staging / "pack")],timeout=left, cwd=str(repo_root), env=_git_env(),input="".join(p.name + "\n" for p in batch))if done is None:result.out_of_time = Truestate["merge_bytes"] = max(state["merge_bytes"] // 2, 1) # next update tries a smaller batchreturn- if done.returncode != 0:- logger.warning("Merging %d packs failed: %s", len(batch), done.stderr.strip()[-300:])+ outputs = list(staging.glob("pack-*.idx"))+ if done.returncode != 0 or len(outputs) != 1:+ logger.warning("Merging %d packs failed (%d outputs): %s", len(batch), len(outputs),+ done.stderr.strip()[-300:])return- new = next(staging.glob("pack-*.idx")).with_suffix("")+ new = outputs[0].with_suffix("")# Marker first, index last: the merged pack is a promisor pack from the moment git sees it.(pack_dir / (new.name + ".promisor")).write_bytes(b"".join(p.with_suffix(".promisor").read_bytes() for p in batch))- for suffix in (".pack", ".rev", ".idx"):- if new.with_suffix(suffix).exists():- os.replace(new.with_suffix(suffix), pack_dir / (new.name + suffix))+ os.replace(new.with_suffix(".pack"), pack_dir / (new.name + ".pack"))+ if new.with_suffix(".rev").exists():+ os.replace(new.with_suffix(".rev"), pack_dir / (new.name + ".rev"))+ os.replace(new.with_suffix(".idx"), pack_dir / (new.name + ".idx"))for pack in batch:if pack.stem != new.name:try:@@ -227,8 +299,27 @@ def _merge_smallest_packs(repo_root: Path, pack_dir: Path, deadline: float, resushutil.rmtree(staging, ignore_errors=True)+def _take_lock(git_dir: Path) -> Optional[Path]:+ """The tidy lock, or None while another tidy holds it. A lock older than an hour is a killed run's+ (a run lasts about ``TIDY_BUDGET_SECONDS``); renaming it away first means one taker wins."""+ lock = git_dir / _LOCK_FILE+ for _attempt in range(2):+ try:+ os.close(os.open(lock, os.O_CREAT | os.O_EXCL | os.O_WRONLY))+ return lock+ except FileExistsError:+ try:+ if lock.stat().st_mtime > time.time() - _MIN_PACK_AGE_SECONDS:+ return None+ os.replace(lock, git_dir / f"{_LOCK_FILE}.stale-{os.getpid()}")+ (git_dir / f"{_LOCK_FILE}.stale-{os.getpid()}").unlink()+ except OSError:+ return None+ return None++def tidy_partial_clone_packs(repo_root: Path, *, budget_seconds: float = TIDY_BUDGET_SECONDS) -> TidyResult:- """Spend at most ``budget_seconds`` erasing and merging on-demand packs. Never raises."""+ """Spend at most ``budget_seconds`` erasing redundant and merging small promisor packs. Never raises."""from hermes_cli.gitlock import _partial_clone_filterresult = TidyResult()@@ -237,19 +328,20 @@ def tidy_partial_clone_packs(repo_root: Path, *, budget_seconds: float = TIDY_BUif not pack_dir.is_dir() or _partial_clone_filter(repo_root, creationflags=windows_hide_flags()) is None:return resultdeadline = time.monotonic() + budget_seconds- state = _load_state(pack_dir)- before = {p.name for p in pack_dir.glob("pack-*.pack")}+ lock = _take_lock(pack_dir.parent.parent)+ if lock is None:+ return resulttry:- _sweep_remnants(pack_dir)- _erase_on_demand_packs(repo_root, pack_dir, deadline, result, state["commits"])- if not result.out_of_time:- _merge_smallest_packs(repo_root, pack_dir, deadline, result, state)+ state = _load_state(pack_dir)+ try:+ _sweep_remnants(pack_dir)+ _erase_redundant_packs(pack_dir, deadline, result, state)+ if not result.out_of_time:+ _merge_smallest_packs(repo_root, pack_dir, deadline, result, state)+ finally:+ _save_state(pack_dir, state)finally:- _save_state(pack_dir, state)- if before - {p.name for p in pack_dir.glob("pack-*.pack")}:- # A multi-pack-index names the packs it covers; git rebuilds one on its own maintenance.- for midx in pack_dir.glob("multi-pack-index*"):- midx.unlink(missing_ok=True)+ lock.unlink(missing_ok=True)result.packs_left = len(list(pack_dir.glob("pack-*.pack")))except Exception:logger.warning("partial-clone pack tidy failed in %s", repo_root, exc_info=True)diff --git a/tests/hermes_cli/test_git_pack_tidy.py b/tests/hermes_cli/test_git_pack_tidy.pyindex 88ece4aff00..cb7a1e0ab87 100644--- a/tests/hermes_cli/test_git_pack_tidy.py+++ b/tests/hermes_cli/test_git_pack_tidy.py@@ -1,9 +1,10 @@-"""Progressive partial-clone pack cleanup (#129712), on real git: a blobless clone of a local upstream."""+"""Progressive partial-clone pack cleanup (#129712), on real git: partial clones of a local upstream."""from __future__ import annotationsimport osimport subprocess+import sysimport timefrom pathlib import Path@@ -24,93 +25,138 @@ def _packs(repo: Path) -> list[Path]:return sorted((repo / ".git" / "objects" / "pack").glob("pack-*.pack"))-def clone(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> tuple[Path, str]:- """A tree:0 clone with one on-demand pack per file it read, plus one holding a fetched-by-id commit."""- monkeypatch.setenv("GIT_CONFIG_GLOBAL", os.devnull)- monkeypatch.setenv("GIT_CONFIG_NOSYSTEM", "1")- seed, up, repo = tmp_path / "seed", tmp_path / "up.git", tmp_path / "clone"+def _objects(repo: Path) -> set[str]:+ """Every object the clone holds locally (what no cleanup may lose)."""+ return set(_git("cat-file", "--batch-all-objects", "--batch-check=%(objectname)", cwd=repo, env=_OFFLINE).split())+++def _age(repo: Path) -> None:+ old = time.time() - 2 * 3600+ for entry in (repo / ".git" / "objects" / "pack").iterdir():+ os.utime(entry, (old, old))+++def _upstream(tmp_path: Path, contents: list[bytes]) -> Path:+ seed, up = tmp_path / "seed", tmp_path / "up.git"_git("init", "-q", "-b", "main", str(seed), cwd=tmp_path)- for i in range(6):- (seed / f"f{i}.txt").write_text(f"v{i}\n", encoding="utf-8")+ for i, data in enumerate(contents):+ (seed / f"f{i}").write_bytes(data)_git("add", "-A", cwd=seed)_git("commit", "-qm", f"c{i}", cwd=seed)- _git("switch", "-q", "-c", "side", cwd=seed)- _git("commit", "-q", "--allow-empty", "-m", "side", cwd=seed)- side = _git("rev-parse", "side", cwd=seed)_git("clone", "-q", "--bare", str(seed), str(up), cwd=tmp_path)for key in ("uploadpack.allowFilter", "uploadpack.allowAnySHA1InWant"):_git("config", key, "true", cwd=up)- _git("clone", "-q", "--filter=tree:0", "--no-checkout", "--single-branch", "-b", "main", up.as_uri(), str(repo),- cwd=tmp_path)- _git("config", "maintenance.auto", "false", cwd=repo)- for i in range(6):- _git("cat-file", "-p", _git("rev-parse", f"HEAD:f{i}.txt", cwd=repo), cwd=repo)- _git("cat-file", "-t", side, cwd=repo) # an on-demand fetch that brings a commit- _git("update-ref", "refs/heads/keep-side", side, cwd=repo)- old = time.time() - 2 * 3600- for entry in (repo / ".git" / "objects" / "pack").iterdir():- os.utime(entry, (old, old))- return repo, side+ return up-def test_erases_commit_free_on_demand_packs_and_keeps_what_refs_need(clone: tuple[Path, str]) -> None:- repo, side = clone- before = _packs(repo)-- result = tidy.tidy_partial_clone_packs(repo)-- after = _packs(repo)- assert result.erased > 0 and len(after) == len(before) - result.erased and result.freed_bytes > 0- assert _git("cat-file", "-t", side, cwd=repo, env=_OFFLINE) == "commit", "a ref points into that pack"- assert _git("rev-list", "--count", "HEAD", cwd=repo, env=_OFFLINE) == "6"- # Erased objects are copies of what the promisor serves: git fetches them again on demand.- assert _git("cat-file", "-p", "HEAD:f3.txt", cwd=repo) == "v3"- assert tidy.tidy_partial_clone_packs(repo).erased == 0---def test_merges_down_to_the_target_without_losing_objects(clone: tuple[Path, str],- monkeypatch: pytest.MonkeyPatch) -> None:- repo, side = clone- monkeypatch.setattr(tidy, "_MIN_PACK_AGE_SECONDS", 10 ** 9) # nothing is old enough to erase+def clone(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:+ """A treeless install converted to blobless: its on-demand tree packs now duplicate the refetch+ pack, its on-demand blob packs hold the only copies, and a local branch needs both. The upstream+ is then rewritten and pruned, so nothing the clone lost could be fetched again."""+ monkeypatch.setenv("GIT_CONFIG_GLOBAL", os.devnull)+ monkeypatch.setenv("GIT_CONFIG_NOSYSTEM", "1")+ up = _upstream(tmp_path, [f"v{i}\n".encode() for i in range(6)])+ repo = tmp_path / "clone"+ _git("clone", "-q", "--filter=tree:0", "--no-checkout", "-b", "main", up.as_uri(), str(repo), cwd=tmp_path)+ _git("config", "maintenance.auto", "false", cwd=repo)+ _git("config", "gc.auto", "0", cwd=repo)+ for i in range(6):+ _git("cat-file", "-p", f"HEAD:f{i}", cwd=repo) # one tree pack, then one blob pack, per file+ _git("update-ref", "refs/heads/local",+ _git("commit-tree", "HEAD^{tree}", "-p", "HEAD", "-m", "local", cwd=repo), cwd=repo)+ _git("fetch", "-q", "--refetch", "--filter=blob:none", "origin", "main", cwd=repo)+ _git("update-ref", "refs/heads/main", _git("commit-tree", "4b825dc642cb6eb9a060e54bf8d69288fbee4904",+ "-m", "rewrite", cwd=up), cwd=up)+ _git("gc", "-q", "--prune=now", cwd=up)+ _age(repo)+ return repo+++def test_erases_only_packs_whose_every_object_has_another_copy(clone: Path) -> None:+ before = _packs(clone)+ for pack in before: # what killed fetches leave behind; git's own repack never frees these+ pack.with_suffix(".keep").write_text("fetch-pack 4242 on host\n", encoding="utf-8")+ head = _git("rev-parse", "HEAD", cwd=clone)+ listings = {p: _git("verify-pack", "-v", str(p.with_suffix(".idx")), cwd=clone, env=_OFFLINE) for p in before}+ clone_pack = min((p for p in before if head in listings[p]), key=lambda p: len(listings[p])) # commits only+ clone_pack.with_suffix(".keep").write_text("pinned by hand\n", encoding="utf-8")+ _age(clone)+ held = _objects(clone)++ result = tidy.tidy_partial_clone_packs(clone)++ assert result.erased > 0 and len(_packs(clone)) == len(before) - result.erased and result.freed_bytes > 0+ assert clone_pack.exists(), "a pack pinned by hand was erased"+ assert _objects(clone) == held, "an erased pack held the only copy of an object"+ assert _git("cat-file", "-p", "local:f3", cwd=clone, env=_OFFLINE) == "v3"+ assert tidy.tidy_partial_clone_packs(clone).erased == 0+++def test_merges_down_to_the_target_into_one_pack_whatever_the_size_limit(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setenv("GIT_CONFIG_GLOBAL", os.devnull)+ monkeypatch.setenv("GIT_CONFIG_NOSYSTEM", "1")+ up = _upstream(tmp_path, [os.urandom(400 * 1024) for _ in range(6)])+ repo = tmp_path / "clone"+ _git("clone", "-q", "--filter=blob:none", "--no-checkout", "-b", "main", up.as_uri(), str(repo), cwd=tmp_path)+ _git("config", "maintenance.auto", "false", cwd=repo)+ _git("config", "pack.packSizeLimit", "1m", cwd=repo) # would split the merge into several packs+ for i in range(6):+ _git("cat-file", "-s", f"HEAD:f{i}", cwd=repo) # one on-demand pack per blob+ _age(repo)+ held = _objects(repo)monkeypatch.setattr(tidy, "PACK_COUNT_TARGET", 1)- assert len(_packs(repo)) > 2result = tidy.tidy_partial_clone_packs(repo)- assert result.erased == 0 and result.packs_left == 1- assert _packs(repo)[0].with_suffix(".promisor").exists()- assert _git("cat-file", "-t", side, cwd=repo, env=_OFFLINE) == "commit"- assert _git("cat-file", "-p", "HEAD:f3.txt", cwd=repo, env=_OFFLINE) == "v3"+ assert result.packs_left == 1 and _packs(repo)[0].with_suffix(".promisor").exists()+ assert _objects(repo) == held-def test_a_pack_that_will_not_unlink_stays_whole_or_is_finished_later(clone: tuple[Path, str],- monkeypatch: pytest.MonkeyPatch) -> None:- repo, side = clone- pack_dir = repo / ".git" / "objects" / "pack"- _git("multi-pack-index", "write", cwd=repo)+_KILLED_MID_ERASE = """+import os, sys+from pathlib import Path+import hermes_cli.git_pack_tidy as tidy+real = Path.unlink+def unlink(self, missing_ok=False):+ real(self, missing_ok=missing_ok)+ if self.suffix == ".pack":+ os._exit(9) # die between a pack's payload and the rest of its files+Path.unlink = unlink+tidy.tidy_partial_clone_packs(Path(sys.argv[1]))+"""+++def test_a_refused_or_killed_erase_leaves_git_reading_and_is_finished_later(+ clone: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ pack_dir = clone / ".git" / "objects" / "pack"+ _git("multi-pack-index", "write", cwd=clone)+ held, before = _objects(clone), _packs(clone)real_unlink = Path.unlink- locked = {".pack"} # a reader holds the payload (Windows refuses to unlink a mapped file)- def unlink(self: Path, missing_ok: bool = False) -> None:- if self.parent == pack_dir and self.suffix in locked:- raise PermissionError(13, "in use", str(self))+ def refuse_payload(self: Path, missing_ok: bool = False) -> None:+ if self.parent == pack_dir and self.suffix == ".pack":+ raise PermissionError(13, "in use", str(self)) # a reader maps it (Windows)real_unlink(self, missing_ok=missing_ok)- monkeypatch.setattr(Path, "unlink", unlink)- before = _packs(repo)- assert tidy.tidy_partial_clone_packs(repo).erased == 0- assert _packs(repo) == before and all(p.with_suffix(".idx").exists() for p in before), "a failed unlink changed a pack"-- locked.clear()- locked.add(".promisor") # now the payload goes and a later part sticks- tidy.tidy_partial_clone_packs(repo)- assert not list(pack_dir.glob("multi-pack-index*")), "the multi-pack-index still names erased packs"- assert _git("cat-file", "-t", side, cwd=repo, env=_OFFLINE) == "commit"- assert _git("rev-list", "--count", "HEAD", cwd=repo, env=_OFFLINE) == "6"- assert any(not p.with_suffix(".pack").exists() for p in pack_dir.glob("pack-*.promisor"))-- locked.clear()- tidy.tidy_partial_clone_packs(repo)- assert all(p.with_suffix(".pack").exists() for p in pack_dir.glob("pack-*.*") if p.suffix != ".pack"), \- "leftovers of an interrupted erase survived the retry"+ with monkeypatch.context() as patched:+ patched.setattr(Path, "unlink", refuse_payload)+ assert tidy.tidy_partial_clone_packs(clone).erased == 0+ assert _packs(clone) == before and all(p.with_suffix(".idx").exists() for p in before)++ _git("multi-pack-index", "write", cwd=clone)+ child = subprocess.run([sys.executable, "-c", _KILLED_MID_ERASE, str(clone)], capture_output=True, text=True, encoding="utf-8",+ env={**_GIT_ENV, "PYTHONPATH": str(Path(tidy.__file__).resolve().parents[1])})+ assert child.returncode == 9, child.stderr+ assert not list(pack_dir.glob("multi-pack-index*")), "a killed erase left a multi-pack-index naming a lost pack"+ assert _objects(clone) == held+ assert _git("cat-file", "-p", "local:f3", cwd=clone, env=_OFFLINE) == "v3"++ lock = clone / ".git" / tidy._LOCK_FILE+ assert lock.exists(), "the killed run's lock"+ os.utime(lock, (time.time() - 2 * 3600,) * 2) # an hour on: the next update takes it over+ tidy.tidy_partial_clone_packs(clone)+ assert all(p.with_suffix(".pack").exists() for p in pack_dir.glob("pack-*.*")), \+ "leftovers of an interrupted erase survived the next run"+ assert _objects(clone) == helddiff --git a/website/docs/getting-started/updating.md b/website/docs/getting-started/updating.mdindex 3ae4ab33cbd..335fef704fa 100644--- a/website/docs/getting-started/updating.md+++ b/website/docs/getting-started/updating.md@@ -182,9 +182,10 @@ downloads every one of their trees. Leave those settings alone, and leave `gc.audefault so git's own automatic gc can still fold packs.Each `hermes update` also spends at most 60 seconds cleaning those packs up, picking up where the-previous update stopped. It first deletes on-demand packs that hold no commits (git downloads-anything it needs from them again), then merges the smallest remaining packs while there are more-than 50. A pack that holds commits is never deleted, because a branch may point into it. To fold+previous update stopped. It deletes packs whose every object is also stored in another pack, then+merges the smallest remaining packs while there are more than 50. Nothing stored locally is ever+lost, and nothing depends on GitHub still serving it. Packs that a killed `git fetch` left pinned+with a `.keep` file are included; git's own repack never touches those. To foldeverything at once by hand instead (with Hermes closed; on a large checkout this is a full repackthat can run for many minutes):